make_rst.py 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  1. #!/usr/bin/env python3
  2. # This script makes RST files from the XML class reference for use with the online docs.
  3. import argparse
  4. import os
  5. import platform
  6. import re
  7. import sys
  8. import xml.etree.ElementTree as ET
  9. from collections import OrderedDict
  10. from typing import List, Dict, TextIO, Tuple, Optional, Any, Union
  11. # Import hardcoded version information from version.py
  12. root_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../")
  13. sys.path.append(root_directory) # Include the root directory
  14. import version
  15. # $DOCS_URL/path/to/page.html(#fragment-tag)
  16. GODOT_DOCS_PATTERN = re.compile(r"^\$DOCS_URL/(.*)\.html(#.*)?$")
  17. # Based on reStructuredText inline markup recognition rules
  18. # https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
  19. MARKUP_ALLOWED_PRECEDENT = " -:/'\"<([{"
  20. MARKUP_ALLOWED_SUBSEQUENT = " -.,:;!?\\/'\")]}>"
  21. # Used to translate section headings and other hardcoded strings when required with
  22. # the --lang argument. The BASE_STRINGS list should be synced with what we actually
  23. # write in this script (check `translate()` uses), and also hardcoded in
  24. # `scripts/extract_classes.py` (godotengine/godot-editor-l10n repo) to include them in the source POT file.
  25. BASE_STRINGS = [
  26. "All classes",
  27. "Globals",
  28. "Nodes",
  29. "Resources",
  30. "Editor-only",
  31. "Other objects",
  32. "Variant types",
  33. "Description",
  34. "Tutorials",
  35. "Properties",
  36. "Constructors",
  37. "Methods",
  38. "Operators",
  39. "Theme Properties",
  40. "Signals",
  41. "Enumerations",
  42. "Constants",
  43. "Annotations",
  44. "Property Descriptions",
  45. "Constructor Descriptions",
  46. "Method Descriptions",
  47. "Operator Descriptions",
  48. "Theme Property Descriptions",
  49. "Inherits:",
  50. "Inherited By:",
  51. "(overrides %s)",
  52. "Default",
  53. "Setter",
  54. "value",
  55. "Getter",
  56. "This method should typically be overridden by the user to have any effect.",
  57. "This method has no side effects. It doesn't modify any of the instance's member variables.",
  58. "This method accepts any number of arguments after the ones described here.",
  59. "This method is used to construct a type.",
  60. "This method doesn't need an instance to be called, so it can be called directly using the class name.",
  61. "This method describes a valid operator to use with this type as left-hand operand.",
  62. "This value is an integer composed as a bitmask of the following flags.",
  63. "There is currently no description for this class. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  64. "There is currently no description for this signal. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  65. "There is currently no description for this annotation. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  66. "There is currently no description for this property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  67. "There is currently no description for this constructor. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  68. "There is currently no description for this method. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  69. "There is currently no description for this operator. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  70. "There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
  71. "There are notable differences when using this API with C#. See :ref:`doc_c_sharp_differences` for more information.",
  72. ]
  73. strings_l10n: Dict[str, str] = {}
  74. STYLES: Dict[str, str] = {}
  75. CLASS_GROUPS: Dict[str, str] = {
  76. "global": "Globals",
  77. "node": "Nodes",
  78. "resource": "Resources",
  79. "object": "Other objects",
  80. "editor": "Editor-only",
  81. "variant": "Variant types",
  82. }
  83. CLASS_GROUPS_BASE: Dict[str, str] = {
  84. "node": "Node",
  85. "resource": "Resource",
  86. "object": "Object",
  87. "variant": "Variant",
  88. }
  89. # Sync with editor\register_editor_types.cpp
  90. EDITOR_CLASSES: List[str] = [
  91. "FileSystemDock",
  92. "ScriptCreateDialog",
  93. "ScriptEditor",
  94. "ScriptEditorBase",
  95. ]
  96. # Sync with the types mentioned in https://docs.godotengine.org/en/stable/tutorials/scripting/c_sharp/c_sharp_differences.html
  97. CLASSES_WITH_CSHARP_DIFFERENCES: List[str] = [
  98. "@GlobalScope",
  99. "String",
  100. "NodePath",
  101. "Signal",
  102. "Callable",
  103. "RID",
  104. "Basis",
  105. "Transform2D",
  106. "Transform3D",
  107. "Rect2",
  108. "Rect2i",
  109. "AABB",
  110. "Quaternion",
  111. "Projection",
  112. "Color",
  113. "Array",
  114. "Dictionary",
  115. "PackedByteArray",
  116. "PackedColorArray",
  117. "PackedFloat32Array",
  118. "PackedFloat64Array",
  119. "PackedInt32Array",
  120. "PackedInt64Array",
  121. "PackedStringArray",
  122. "PackedVector2Array",
  123. "PackedVector3Array",
  124. "Variant",
  125. ]
  126. class State:
  127. def __init__(self) -> None:
  128. self.num_errors = 0
  129. self.num_warnings = 0
  130. self.classes: OrderedDict[str, ClassDef] = OrderedDict()
  131. self.current_class: str = ""
  132. def parse_class(self, class_root: ET.Element, filepath: str) -> None:
  133. class_name = class_root.attrib["name"]
  134. self.current_class = class_name
  135. class_def = ClassDef(class_name)
  136. self.classes[class_name] = class_def
  137. class_def.filepath = filepath
  138. inherits = class_root.get("inherits")
  139. if inherits is not None:
  140. class_def.inherits = inherits
  141. brief_desc = class_root.find("brief_description")
  142. if brief_desc is not None and brief_desc.text:
  143. class_def.brief_description = brief_desc.text
  144. desc = class_root.find("description")
  145. if desc is not None and desc.text:
  146. class_def.description = desc.text
  147. properties = class_root.find("members")
  148. if properties is not None:
  149. for property in properties:
  150. assert property.tag == "member"
  151. property_name = property.attrib["name"]
  152. if property_name in class_def.properties:
  153. print_error(f'{class_name}.xml: Duplicate property "{property_name}".', self)
  154. continue
  155. type_name = TypeName.from_element(property)
  156. setter = property.get("setter") or None # Use or None so '' gets turned into None.
  157. getter = property.get("getter") or None
  158. default_value = property.get("default") or None
  159. if default_value is not None:
  160. default_value = f"``{default_value}``"
  161. overrides = property.get("overrides") or None
  162. property_def = PropertyDef(
  163. property_name, type_name, setter, getter, property.text, default_value, overrides
  164. )
  165. class_def.properties[property_name] = property_def
  166. constructors = class_root.find("constructors")
  167. if constructors is not None:
  168. for constructor in constructors:
  169. assert constructor.tag == "constructor"
  170. method_name = constructor.attrib["name"]
  171. qualifiers = constructor.get("qualifiers")
  172. return_element = constructor.find("return")
  173. if return_element is not None:
  174. return_type = TypeName.from_element(return_element)
  175. else:
  176. return_type = TypeName("void")
  177. params = self.parse_params(constructor, "constructor")
  178. desc_element = constructor.find("description")
  179. method_desc = None
  180. if desc_element is not None:
  181. method_desc = desc_element.text
  182. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  183. method_def.definition_name = "constructor"
  184. if method_name not in class_def.constructors:
  185. class_def.constructors[method_name] = []
  186. class_def.constructors[method_name].append(method_def)
  187. methods = class_root.find("methods")
  188. if methods is not None:
  189. for method in methods:
  190. assert method.tag == "method"
  191. method_name = method.attrib["name"]
  192. qualifiers = method.get("qualifiers")
  193. return_element = method.find("return")
  194. if return_element is not None:
  195. return_type = TypeName.from_element(return_element)
  196. else:
  197. return_type = TypeName("void")
  198. params = self.parse_params(method, "method")
  199. desc_element = method.find("description")
  200. method_desc = None
  201. if desc_element is not None:
  202. method_desc = desc_element.text
  203. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  204. if method_name not in class_def.methods:
  205. class_def.methods[method_name] = []
  206. class_def.methods[method_name].append(method_def)
  207. operators = class_root.find("operators")
  208. if operators is not None:
  209. for operator in operators:
  210. assert operator.tag == "operator"
  211. method_name = operator.attrib["name"]
  212. qualifiers = operator.get("qualifiers")
  213. return_element = operator.find("return")
  214. if return_element is not None:
  215. return_type = TypeName.from_element(return_element)
  216. else:
  217. return_type = TypeName("void")
  218. params = self.parse_params(operator, "operator")
  219. desc_element = operator.find("description")
  220. method_desc = None
  221. if desc_element is not None:
  222. method_desc = desc_element.text
  223. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  224. method_def.definition_name = "operator"
  225. if method_name not in class_def.operators:
  226. class_def.operators[method_name] = []
  227. class_def.operators[method_name].append(method_def)
  228. constants = class_root.find("constants")
  229. if constants is not None:
  230. for constant in constants:
  231. assert constant.tag == "constant"
  232. constant_name = constant.attrib["name"]
  233. value = constant.attrib["value"]
  234. enum = constant.get("enum")
  235. is_bitfield = constant.get("is_bitfield") == "true"
  236. constant_def = ConstantDef(constant_name, value, constant.text, is_bitfield)
  237. if enum is None:
  238. if constant_name in class_def.constants:
  239. print_error(f'{class_name}.xml: Duplicate constant "{constant_name}".', self)
  240. continue
  241. class_def.constants[constant_name] = constant_def
  242. else:
  243. if enum in class_def.enums:
  244. enum_def = class_def.enums[enum]
  245. else:
  246. enum_def = EnumDef(enum, TypeName("int", enum), is_bitfield)
  247. class_def.enums[enum] = enum_def
  248. enum_def.values[constant_name] = constant_def
  249. annotations = class_root.find("annotations")
  250. if annotations is not None:
  251. for annotation in annotations:
  252. assert annotation.tag == "annotation"
  253. annotation_name = annotation.attrib["name"]
  254. qualifiers = annotation.get("qualifiers")
  255. params = self.parse_params(annotation, "annotation")
  256. desc_element = annotation.find("description")
  257. annotation_desc = None
  258. if desc_element is not None:
  259. annotation_desc = desc_element.text
  260. annotation_def = AnnotationDef(annotation_name, params, annotation_desc, qualifiers)
  261. if annotation_name not in class_def.annotations:
  262. class_def.annotations[annotation_name] = []
  263. class_def.annotations[annotation_name].append(annotation_def)
  264. signals = class_root.find("signals")
  265. if signals is not None:
  266. for signal in signals:
  267. assert signal.tag == "signal"
  268. signal_name = signal.attrib["name"]
  269. if signal_name in class_def.signals:
  270. print_error(f'{class_name}.xml: Duplicate signal "{signal_name}".', self)
  271. continue
  272. params = self.parse_params(signal, "signal")
  273. desc_element = signal.find("description")
  274. signal_desc = None
  275. if desc_element is not None:
  276. signal_desc = desc_element.text
  277. signal_def = SignalDef(signal_name, params, signal_desc)
  278. class_def.signals[signal_name] = signal_def
  279. theme_items = class_root.find("theme_items")
  280. if theme_items is not None:
  281. for theme_item in theme_items:
  282. assert theme_item.tag == "theme_item"
  283. theme_item_name = theme_item.attrib["name"]
  284. theme_item_data_name = theme_item.attrib["data_type"]
  285. theme_item_id = "{}_{}".format(theme_item_data_name, theme_item_name)
  286. if theme_item_id in class_def.theme_items:
  287. print_error(
  288. f'{class_name}.xml: Duplicate theme item "{theme_item_name}" of type "{theme_item_data_name}".',
  289. self,
  290. )
  291. continue
  292. default_value = theme_item.get("default") or None
  293. if default_value is not None:
  294. default_value = f"``{default_value}``"
  295. theme_item_def = ThemeItemDef(
  296. theme_item_name,
  297. TypeName.from_element(theme_item),
  298. theme_item_data_name,
  299. theme_item.text,
  300. default_value,
  301. )
  302. class_def.theme_items[theme_item_name] = theme_item_def
  303. tutorials = class_root.find("tutorials")
  304. if tutorials is not None:
  305. for link in tutorials:
  306. assert link.tag == "link"
  307. if link.text is not None:
  308. class_def.tutorials.append((link.text.strip(), link.get("title", "")))
  309. self.current_class = ""
  310. def parse_params(self, root: ET.Element, context: str) -> List["ParameterDef"]:
  311. param_elements = root.findall("param")
  312. params: Any = [None] * len(param_elements)
  313. for param_index, param_element in enumerate(param_elements):
  314. param_name = param_element.attrib["name"]
  315. index = int(param_element.attrib["index"])
  316. type_name = TypeName.from_element(param_element)
  317. default = param_element.get("default")
  318. if param_name.strip() == "" or param_name.startswith("_unnamed_arg"):
  319. print_error(
  320. f'{self.current_class}.xml: Empty argument name in {context} "{root.attrib["name"]}" at position {param_index}.',
  321. self,
  322. )
  323. params[index] = ParameterDef(param_name, type_name, default)
  324. cast: List[ParameterDef] = params
  325. return cast
  326. def sort_classes(self) -> None:
  327. self.classes = OrderedDict(sorted(self.classes.items(), key=lambda t: t[0].lower()))
  328. class TypeName:
  329. def __init__(self, type_name: str, enum: Optional[str] = None, is_bitfield: bool = False) -> None:
  330. self.type_name = type_name
  331. self.enum = enum
  332. self.is_bitfield = is_bitfield
  333. def to_rst(self, state: State) -> str:
  334. if self.enum is not None:
  335. return make_enum(self.enum, self.is_bitfield, state)
  336. elif self.type_name == "void":
  337. return "void"
  338. else:
  339. return make_type(self.type_name, state)
  340. @classmethod
  341. def from_element(cls, element: ET.Element) -> "TypeName":
  342. return cls(element.attrib["type"], element.get("enum"), element.get("is_bitfield") == "true")
  343. class DefinitionBase:
  344. def __init__(
  345. self,
  346. definition_name: str,
  347. name: str,
  348. ) -> None:
  349. self.definition_name = definition_name
  350. self.name = name
  351. class PropertyDef(DefinitionBase):
  352. def __init__(
  353. self,
  354. name: str,
  355. type_name: TypeName,
  356. setter: Optional[str],
  357. getter: Optional[str],
  358. text: Optional[str],
  359. default_value: Optional[str],
  360. overrides: Optional[str],
  361. ) -> None:
  362. super().__init__("property", name)
  363. self.type_name = type_name
  364. self.setter = setter
  365. self.getter = getter
  366. self.text = text
  367. self.default_value = default_value
  368. self.overrides = overrides
  369. class ParameterDef(DefinitionBase):
  370. def __init__(self, name: str, type_name: TypeName, default_value: Optional[str]) -> None:
  371. super().__init__("parameter", name)
  372. self.type_name = type_name
  373. self.default_value = default_value
  374. class SignalDef(DefinitionBase):
  375. def __init__(self, name: str, parameters: List[ParameterDef], description: Optional[str]) -> None:
  376. super().__init__("signal", name)
  377. self.parameters = parameters
  378. self.description = description
  379. class AnnotationDef(DefinitionBase):
  380. def __init__(
  381. self,
  382. name: str,
  383. parameters: List[ParameterDef],
  384. description: Optional[str],
  385. qualifiers: Optional[str],
  386. ) -> None:
  387. super().__init__("annotation", name)
  388. self.parameters = parameters
  389. self.description = description
  390. self.qualifiers = qualifiers
  391. class MethodDef(DefinitionBase):
  392. def __init__(
  393. self,
  394. name: str,
  395. return_type: TypeName,
  396. parameters: List[ParameterDef],
  397. description: Optional[str],
  398. qualifiers: Optional[str],
  399. ) -> None:
  400. super().__init__("method", name)
  401. self.return_type = return_type
  402. self.parameters = parameters
  403. self.description = description
  404. self.qualifiers = qualifiers
  405. class ConstantDef(DefinitionBase):
  406. def __init__(self, name: str, value: str, text: Optional[str], bitfield: bool) -> None:
  407. super().__init__("constant", name)
  408. self.value = value
  409. self.text = text
  410. self.is_bitfield = bitfield
  411. class EnumDef(DefinitionBase):
  412. def __init__(self, name: str, type_name: TypeName, bitfield: bool) -> None:
  413. super().__init__("enum", name)
  414. self.type_name = type_name
  415. self.values: OrderedDict[str, ConstantDef] = OrderedDict()
  416. self.is_bitfield = bitfield
  417. class ThemeItemDef(DefinitionBase):
  418. def __init__(
  419. self, name: str, type_name: TypeName, data_name: str, text: Optional[str], default_value: Optional[str]
  420. ) -> None:
  421. super().__init__("theme item", name)
  422. self.type_name = type_name
  423. self.data_name = data_name
  424. self.text = text
  425. self.default_value = default_value
  426. class ClassDef(DefinitionBase):
  427. def __init__(self, name: str) -> None:
  428. super().__init__("class", name)
  429. self.constants: OrderedDict[str, ConstantDef] = OrderedDict()
  430. self.enums: OrderedDict[str, EnumDef] = OrderedDict()
  431. self.properties: OrderedDict[str, PropertyDef] = OrderedDict()
  432. self.constructors: OrderedDict[str, List[MethodDef]] = OrderedDict()
  433. self.methods: OrderedDict[str, List[MethodDef]] = OrderedDict()
  434. self.operators: OrderedDict[str, List[MethodDef]] = OrderedDict()
  435. self.signals: OrderedDict[str, SignalDef] = OrderedDict()
  436. self.annotations: OrderedDict[str, List[AnnotationDef]] = OrderedDict()
  437. self.theme_items: OrderedDict[str, ThemeItemDef] = OrderedDict()
  438. self.inherits: Optional[str] = None
  439. self.brief_description: Optional[str] = None
  440. self.description: Optional[str] = None
  441. self.tutorials: List[Tuple[str, str]] = []
  442. # Used to match the class with XML source for output filtering purposes.
  443. self.filepath: str = ""
  444. # Entry point for the RST generator.
  445. def main() -> None:
  446. # Enable ANSI escape code support on Windows 10 and later (for colored console output).
  447. # <https://bugs.python.org/issue29059>
  448. if platform.system().lower() == "windows":
  449. from ctypes import windll, c_int, byref # type: ignore
  450. stdout_handle = windll.kernel32.GetStdHandle(c_int(-11))
  451. mode = c_int(0)
  452. windll.kernel32.GetConsoleMode(c_int(stdout_handle), byref(mode))
  453. mode = c_int(mode.value | 4)
  454. windll.kernel32.SetConsoleMode(c_int(stdout_handle), mode)
  455. parser = argparse.ArgumentParser()
  456. parser.add_argument("path", nargs="+", help="A path to an XML file or a directory containing XML files to parse.")
  457. parser.add_argument("--filter", default="", help="The filepath pattern for XML files to filter.")
  458. parser.add_argument("--lang", "-l", default="en", help="Language to use for section headings.")
  459. parser.add_argument(
  460. "--color",
  461. action="store_true",
  462. help="If passed, force colored output even if stdout is not a TTY (useful for continuous integration).",
  463. )
  464. group = parser.add_mutually_exclusive_group()
  465. group.add_argument("--output", "-o", default=".", help="The directory to save output .rst files in.")
  466. group.add_argument(
  467. "--dry-run",
  468. action="store_true",
  469. help="If passed, no output will be generated and XML files are only checked for errors.",
  470. )
  471. args = parser.parse_args()
  472. should_color = args.color or (hasattr(sys.stdout, "isatty") and sys.stdout.isatty())
  473. STYLES["red"] = "\x1b[91m" if should_color else ""
  474. STYLES["green"] = "\x1b[92m" if should_color else ""
  475. STYLES["yellow"] = "\x1b[93m" if should_color else ""
  476. STYLES["bold"] = "\x1b[1m" if should_color else ""
  477. STYLES["regular"] = "\x1b[22m" if should_color else ""
  478. STYLES["reset"] = "\x1b[0m" if should_color else ""
  479. # Retrieve heading translations for the given language.
  480. if not args.dry_run and args.lang != "en":
  481. lang_file = os.path.join(
  482. os.path.dirname(os.path.realpath(__file__)), "..", "translations", "{}.po".format(args.lang)
  483. )
  484. if os.path.exists(lang_file):
  485. try:
  486. import polib # type: ignore
  487. except ImportError:
  488. print("Base template strings localization requires `polib`.")
  489. exit(1)
  490. pofile = polib.pofile(lang_file)
  491. for entry in pofile.translated_entries():
  492. if entry.msgid in BASE_STRINGS:
  493. strings_l10n[entry.msgid] = entry.msgstr
  494. else:
  495. print(f'No PO file at "{lang_file}" for language "{args.lang}".')
  496. print("Checking for errors in the XML class reference...")
  497. file_list: List[str] = []
  498. for path in args.path:
  499. # Cut off trailing slashes so os.path.basename doesn't choke.
  500. if path.endswith("/") or path.endswith("\\"):
  501. path = path[:-1]
  502. if os.path.basename(path) in ["modules", "platform"]:
  503. for subdir, dirs, _ in os.walk(path):
  504. if "doc_classes" in dirs:
  505. doc_dir = os.path.join(subdir, "doc_classes")
  506. class_file_names = (f for f in os.listdir(doc_dir) if f.endswith(".xml"))
  507. file_list += (os.path.join(doc_dir, f) for f in class_file_names)
  508. elif os.path.isdir(path):
  509. file_list += (os.path.join(path, f) for f in os.listdir(path) if f.endswith(".xml"))
  510. elif os.path.isfile(path):
  511. if not path.endswith(".xml"):
  512. print(f'Got non-.xml file "{path}" in input, skipping.')
  513. continue
  514. file_list.append(path)
  515. classes: Dict[str, Tuple[ET.Element, str]] = {}
  516. state = State()
  517. for cur_file in file_list:
  518. try:
  519. tree = ET.parse(cur_file)
  520. except ET.ParseError as e:
  521. print_error(f"{cur_file}: Parse error while reading the file: {e}", state)
  522. continue
  523. doc = tree.getroot()
  524. name = doc.attrib["name"]
  525. if name in classes:
  526. print_error(f'{cur_file}: Duplicate class "{name}".', state)
  527. continue
  528. classes[name] = (doc, cur_file)
  529. for name, data in classes.items():
  530. try:
  531. state.parse_class(data[0], data[1])
  532. except Exception as e:
  533. print_error(f"{name}.xml: Exception while parsing class: {e}", state)
  534. state.sort_classes()
  535. pattern = re.compile(args.filter)
  536. # Create the output folder recursively if it doesn't already exist.
  537. os.makedirs(args.output, exist_ok=True)
  538. print("Generating the RST class reference...")
  539. grouped_classes: Dict[str, List[str]] = {}
  540. for class_name, class_def in state.classes.items():
  541. if args.filter and not pattern.search(class_def.filepath):
  542. continue
  543. state.current_class = class_name
  544. make_rst_class(class_def, state, args.dry_run, args.output)
  545. group_name = get_class_group(class_def, state)
  546. if group_name not in grouped_classes:
  547. grouped_classes[group_name] = []
  548. grouped_classes[group_name].append(class_name)
  549. if is_editor_class(class_def):
  550. if "editor" not in grouped_classes:
  551. grouped_classes["editor"] = []
  552. grouped_classes["editor"].append(class_name)
  553. print("")
  554. print("Generating the index file...")
  555. make_rst_index(grouped_classes, args.dry_run, args.output)
  556. print("")
  557. if state.num_warnings >= 2:
  558. print(
  559. f'{STYLES["yellow"]}{state.num_warnings} warnings were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  560. )
  561. elif state.num_warnings == 1:
  562. print(
  563. f'{STYLES["yellow"]}1 warning was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  564. )
  565. if state.num_errors == 0:
  566. print(f'{STYLES["green"]}No errors found in the class reference XML.{STYLES["reset"]}')
  567. if not args.dry_run:
  568. print(f"Wrote reStructuredText files for each class to: {args.output}")
  569. else:
  570. if state.num_errors >= 2:
  571. print(
  572. f'{STYLES["red"]}{state.num_errors} errors were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  573. )
  574. else:
  575. print(
  576. f'{STYLES["red"]}1 error was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  577. )
  578. exit(1)
  579. # Common helpers.
  580. def print_error(error: str, state: State) -> None:
  581. print(f'{STYLES["red"]}{STYLES["bold"]}ERROR:{STYLES["regular"]} {error}{STYLES["reset"]}')
  582. state.num_errors += 1
  583. def print_warning(warning: str, state: State) -> None:
  584. print(f'{STYLES["yellow"]}{STYLES["bold"]}WARNING:{STYLES["regular"]} {warning}{STYLES["reset"]}')
  585. state.num_warnings += 1
  586. def translate(string: str) -> str:
  587. """Translate a string based on translations sourced from `doc/translations/*.po`
  588. for a language if defined via the --lang command line argument.
  589. Returns the original string if no translation exists.
  590. """
  591. return strings_l10n.get(string, string)
  592. def get_git_branch() -> str:
  593. if hasattr(version, "docs") and version.docs != "latest":
  594. return version.docs
  595. return "master"
  596. def get_class_group(class_def: ClassDef, state: State) -> str:
  597. group_name = "variant"
  598. class_name = class_def.name
  599. if class_name.startswith("@"):
  600. group_name = "global"
  601. elif class_def.inherits:
  602. inherits = class_def.inherits.strip()
  603. while inherits in state.classes:
  604. if inherits == "Node":
  605. group_name = "node"
  606. break
  607. if inherits == "Resource":
  608. group_name = "resource"
  609. break
  610. if inherits == "Object":
  611. group_name = "object"
  612. break
  613. inode = state.classes[inherits].inherits
  614. if inode:
  615. inherits = inode.strip()
  616. else:
  617. break
  618. return group_name
  619. def is_editor_class(class_def: ClassDef) -> bool:
  620. class_name = class_def.name
  621. if class_name.startswith("Editor"):
  622. return True
  623. if class_name in EDITOR_CLASSES:
  624. return True
  625. return False
  626. # Generator methods.
  627. def make_rst_class(class_def: ClassDef, state: State, dry_run: bool, output_dir: str) -> None:
  628. class_name = class_def.name
  629. if dry_run:
  630. f = open(os.devnull, "w", encoding="utf-8")
  631. else:
  632. f = open(os.path.join(output_dir, f"class_{class_name.lower()}.rst"), "w", encoding="utf-8")
  633. # Remove the "Edit on Github" button from the online docs page.
  634. f.write(":github_url: hide\n\n")
  635. # Warn contributors not to edit this file directly.
  636. # Also provide links to the source files for reference.
  637. git_branch = get_git_branch()
  638. source_xml_path = os.path.relpath(class_def.filepath, root_directory).replace("\\", "/")
  639. source_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/{source_xml_path}"
  640. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  641. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  642. f.write(".. Generated automatically from Godot engine sources.\n")
  643. f.write(f".. Generator: {generator_github_url}.\n")
  644. f.write(f".. XML source: {source_github_url}.\n\n")
  645. # Document reference id and header.
  646. f.write(f".. _class_{class_name}:\n\n")
  647. f.write(make_heading(class_name, "=", False))
  648. ### INHERITANCE TREE ###
  649. # Ascendants
  650. if class_def.inherits:
  651. inherits = class_def.inherits.strip()
  652. f.write(f'**{translate("Inherits:")}** ')
  653. first = True
  654. while inherits in state.classes:
  655. if not first:
  656. f.write(" **<** ")
  657. else:
  658. first = False
  659. f.write(make_type(inherits, state))
  660. inode = state.classes[inherits].inherits
  661. if inode:
  662. inherits = inode.strip()
  663. else:
  664. break
  665. f.write("\n\n")
  666. # Descendants
  667. inherited: List[str] = []
  668. for c in state.classes.values():
  669. if c.inherits and c.inherits.strip() == class_name:
  670. inherited.append(c.name)
  671. if len(inherited):
  672. f.write(f'**{translate("Inherited By:")}** ')
  673. for i, child in enumerate(inherited):
  674. if i > 0:
  675. f.write(", ")
  676. f.write(make_type(child, state))
  677. f.write("\n\n")
  678. ### INTRODUCTION ###
  679. has_description = False
  680. # Brief description
  681. if class_def.brief_description is not None and class_def.brief_description.strip() != "":
  682. has_description = True
  683. f.write(f"{format_text_block(class_def.brief_description.strip(), class_def, state)}\n\n")
  684. # Class description
  685. if class_def.description is not None and class_def.description.strip() != "":
  686. has_description = True
  687. f.write(".. rst-class:: classref-introduction-group\n\n")
  688. f.write(make_heading("Description", "-"))
  689. f.write(f"{format_text_block(class_def.description.strip(), class_def, state)}\n\n")
  690. if not has_description:
  691. f.write(".. container:: contribute\n\n\t")
  692. f.write(
  693. translate(
  694. "There is currently no description for this class. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  695. )
  696. + "\n\n"
  697. )
  698. if class_def.name in CLASSES_WITH_CSHARP_DIFFERENCES:
  699. f.write(".. note::\n\n\t")
  700. f.write(
  701. translate(
  702. "There are notable differences when using this API with C#. See :ref:`doc_c_sharp_differences` for more information."
  703. )
  704. + "\n\n"
  705. )
  706. # Online tutorials
  707. if len(class_def.tutorials) > 0:
  708. f.write(".. rst-class:: classref-introduction-group\n\n")
  709. f.write(make_heading("Tutorials", "-"))
  710. for url, title in class_def.tutorials:
  711. f.write(f"- {make_link(url, title)}\n\n")
  712. ### REFERENCE TABLES ###
  713. # Reused container for reference tables.
  714. ml: List[Tuple[Optional[str], ...]] = []
  715. # Properties reference table
  716. if len(class_def.properties) > 0:
  717. f.write(".. rst-class:: classref-reftable-group\n\n")
  718. f.write(make_heading("Properties", "-"))
  719. ml = []
  720. for property_def in class_def.properties.values():
  721. type_rst = property_def.type_name.to_rst(state)
  722. default = property_def.default_value
  723. if default is not None and property_def.overrides:
  724. ref = f":ref:`{property_def.overrides}<class_{property_def.overrides}_property_{property_def.name}>`"
  725. # Not using translate() for now as it breaks table formatting.
  726. ml.append((type_rst, property_def.name, f"{default} (overrides {ref})"))
  727. else:
  728. ref = f":ref:`{property_def.name}<class_{class_name}_property_{property_def.name}>`"
  729. ml.append((type_rst, ref, default))
  730. format_table(f, ml, True)
  731. # Constructors, Methods, Operators reference tables
  732. if len(class_def.constructors) > 0:
  733. f.write(".. rst-class:: classref-reftable-group\n\n")
  734. f.write(make_heading("Constructors", "-"))
  735. ml = []
  736. for method_list in class_def.constructors.values():
  737. for m in method_list:
  738. ml.append(make_method_signature(class_def, m, "constructor", state))
  739. format_table(f, ml)
  740. if len(class_def.methods) > 0:
  741. f.write(".. rst-class:: classref-reftable-group\n\n")
  742. f.write(make_heading("Methods", "-"))
  743. ml = []
  744. for method_list in class_def.methods.values():
  745. for m in method_list:
  746. ml.append(make_method_signature(class_def, m, "method", state))
  747. format_table(f, ml)
  748. if len(class_def.operators) > 0:
  749. f.write(".. rst-class:: classref-reftable-group\n\n")
  750. f.write(make_heading("Operators", "-"))
  751. ml = []
  752. for method_list in class_def.operators.values():
  753. for m in method_list:
  754. ml.append(make_method_signature(class_def, m, "operator", state))
  755. format_table(f, ml)
  756. # Theme properties reference table
  757. if len(class_def.theme_items) > 0:
  758. f.write(".. rst-class:: classref-reftable-group\n\n")
  759. f.write(make_heading("Theme Properties", "-"))
  760. ml = []
  761. for theme_item_def in class_def.theme_items.values():
  762. ref = f":ref:`{theme_item_def.name}<class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}>`"
  763. ml.append((theme_item_def.type_name.to_rst(state), ref, theme_item_def.default_value))
  764. format_table(f, ml, True)
  765. ### DETAILED DESCRIPTIONS ###
  766. # Signal descriptions
  767. if len(class_def.signals) > 0:
  768. f.write(make_separator(True))
  769. f.write(".. rst-class:: classref-descriptions-group\n\n")
  770. f.write(make_heading("Signals", "-"))
  771. index = 0
  772. for signal in class_def.signals.values():
  773. if index != 0:
  774. f.write(make_separator())
  775. # Create signal signature and anchor point.
  776. f.write(f".. _class_{class_name}_signal_{signal.name}:\n\n")
  777. f.write(".. rst-class:: classref-signal\n\n")
  778. _, signature = make_method_signature(class_def, signal, "", state)
  779. f.write(f"{signature}\n\n")
  780. # Add signal description, or a call to action if it's missing.
  781. if signal.description is not None and signal.description.strip() != "":
  782. f.write(f"{format_text_block(signal.description.strip(), signal, state)}\n\n")
  783. else:
  784. f.write(".. container:: contribute\n\n\t")
  785. f.write(
  786. translate(
  787. "There is currently no description for this signal. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  788. )
  789. + "\n\n"
  790. )
  791. index += 1
  792. # Enumeration descriptions
  793. if len(class_def.enums) > 0:
  794. f.write(make_separator(True))
  795. f.write(".. rst-class:: classref-descriptions-group\n\n")
  796. f.write(make_heading("Enumerations", "-"))
  797. index = 0
  798. for e in class_def.enums.values():
  799. if index != 0:
  800. f.write(make_separator())
  801. # Create enumeration signature and anchor point.
  802. f.write(f".. _enum_{class_name}_{e.name}:\n\n")
  803. f.write(".. rst-class:: classref-enumeration\n\n")
  804. if e.is_bitfield:
  805. f.write(f"flags **{e.name}**:\n\n")
  806. else:
  807. f.write(f"enum **{e.name}**:\n\n")
  808. for value in e.values.values():
  809. # Also create signature and anchor point for each enum constant.
  810. f.write(f".. _class_{class_name}_constant_{value.name}:\n\n")
  811. f.write(".. rst-class:: classref-enumeration-constant\n\n")
  812. f.write(f"{e.type_name.to_rst(state)} **{value.name}** = ``{value.value}``\n\n")
  813. # Add enum constant description.
  814. if value.text is not None and value.text.strip() != "":
  815. f.write(f"{format_text_block(value.text.strip(), value, state)}")
  816. f.write("\n\n")
  817. index += 1
  818. # Constant descriptions
  819. if len(class_def.constants) > 0:
  820. f.write(make_separator(True))
  821. f.write(".. rst-class:: classref-descriptions-group\n\n")
  822. f.write(make_heading("Constants", "-"))
  823. for constant in class_def.constants.values():
  824. # Create constant signature and anchor point.
  825. f.write(f".. _class_{class_name}_constant_{constant.name}:\n\n")
  826. f.write(".. rst-class:: classref-constant\n\n")
  827. f.write(f"**{constant.name}** = ``{constant.value}``\n\n")
  828. # Add enum constant description.
  829. if constant.text is not None and constant.text.strip() != "":
  830. f.write(f"{format_text_block(constant.text.strip(), constant, state)}")
  831. f.write("\n\n")
  832. # Annotation descriptions
  833. if len(class_def.annotations) > 0:
  834. f.write(make_separator(True))
  835. f.write(make_heading("Annotations", "-"))
  836. index = 0
  837. for method_list in class_def.annotations.values(): # type: ignore
  838. for i, m in enumerate(method_list):
  839. if index != 0:
  840. f.write(make_separator())
  841. # Create annotation signature and anchor point.
  842. if i == 0:
  843. f.write(f".. _class_{class_name}_annotation_{m.name}:\n\n")
  844. f.write(".. rst-class:: classref-annotation\n\n")
  845. _, signature = make_method_signature(class_def, m, "", state)
  846. f.write(f"{signature}\n\n")
  847. # Add annotation description, or a call to action if it's missing.
  848. if m.description is not None and m.description.strip() != "":
  849. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  850. else:
  851. f.write(".. container:: contribute\n\n\t")
  852. f.write(
  853. translate(
  854. "There is currently no description for this annotation. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  855. )
  856. + "\n\n"
  857. )
  858. index += 1
  859. # Property descriptions
  860. if any(not p.overrides for p in class_def.properties.values()) > 0:
  861. f.write(make_separator(True))
  862. f.write(".. rst-class:: classref-descriptions-group\n\n")
  863. f.write(make_heading("Property Descriptions", "-"))
  864. index = 0
  865. for property_def in class_def.properties.values():
  866. if property_def.overrides:
  867. continue
  868. if index != 0:
  869. f.write(make_separator())
  870. # Create property signature and anchor point.
  871. f.write(f".. _class_{class_name}_property_{property_def.name}:\n\n")
  872. f.write(".. rst-class:: classref-property\n\n")
  873. property_default = ""
  874. if property_def.default_value is not None:
  875. property_default = f" = {property_def.default_value}"
  876. f.write(f"{property_def.type_name.to_rst(state)} **{property_def.name}**{property_default}\n\n")
  877. # Create property setter and getter records.
  878. property_setget = ""
  879. if property_def.setter is not None and not property_def.setter.startswith("_"):
  880. property_setter = make_setter_signature(class_def, property_def, state)
  881. property_setget += f"- {property_setter}\n"
  882. if property_def.getter is not None and not property_def.getter.startswith("_"):
  883. property_getter = make_getter_signature(class_def, property_def, state)
  884. property_setget += f"- {property_getter}\n"
  885. if property_setget != "":
  886. f.write(".. rst-class:: classref-property-setget\n\n")
  887. f.write(property_setget)
  888. f.write("\n")
  889. # Add property description, or a call to action if it's missing.
  890. if property_def.text is not None and property_def.text.strip() != "":
  891. f.write(f"{format_text_block(property_def.text.strip(), property_def, state)}\n\n")
  892. else:
  893. f.write(".. container:: contribute\n\n\t")
  894. f.write(
  895. translate(
  896. "There is currently no description for this property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  897. )
  898. + "\n\n"
  899. )
  900. index += 1
  901. # Constructor, Method, Operator descriptions
  902. if len(class_def.constructors) > 0:
  903. f.write(make_separator(True))
  904. f.write(".. rst-class:: classref-descriptions-group\n\n")
  905. f.write(make_heading("Constructor Descriptions", "-"))
  906. index = 0
  907. for method_list in class_def.constructors.values():
  908. for i, m in enumerate(method_list):
  909. if index != 0:
  910. f.write(make_separator())
  911. # Create constructor signature and anchor point.
  912. if i == 0:
  913. f.write(f".. _class_{class_name}_constructor_{m.name}:\n\n")
  914. f.write(".. rst-class:: classref-constructor\n\n")
  915. ret_type, signature = make_method_signature(class_def, m, "", state)
  916. f.write(f"{ret_type} {signature}\n\n")
  917. # Add constructor description, or a call to action if it's missing.
  918. if m.description is not None and m.description.strip() != "":
  919. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  920. else:
  921. f.write(".. container:: contribute\n\n\t")
  922. f.write(
  923. translate(
  924. "There is currently no description for this constructor. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  925. )
  926. + "\n\n"
  927. )
  928. index += 1
  929. if len(class_def.methods) > 0:
  930. f.write(make_separator(True))
  931. f.write(".. rst-class:: classref-descriptions-group\n\n")
  932. f.write(make_heading("Method Descriptions", "-"))
  933. index = 0
  934. for method_list in class_def.methods.values():
  935. for i, m in enumerate(method_list):
  936. if index != 0:
  937. f.write(make_separator())
  938. # Create method signature and anchor point.
  939. if i == 0:
  940. f.write(f".. _class_{class_name}_method_{m.name}:\n\n")
  941. f.write(".. rst-class:: classref-method\n\n")
  942. ret_type, signature = make_method_signature(class_def, m, "", state)
  943. f.write(f"{ret_type} {signature}\n\n")
  944. # Add method description, or a call to action if it's missing.
  945. if m.description is not None and m.description.strip() != "":
  946. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  947. else:
  948. f.write(".. container:: contribute\n\n\t")
  949. f.write(
  950. translate(
  951. "There is currently no description for this method. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  952. )
  953. + "\n\n"
  954. )
  955. index += 1
  956. if len(class_def.operators) > 0:
  957. f.write(make_separator(True))
  958. f.write(".. rst-class:: classref-descriptions-group\n\n")
  959. f.write(make_heading("Operator Descriptions", "-"))
  960. index = 0
  961. for method_list in class_def.operators.values():
  962. for i, m in enumerate(method_list):
  963. if index != 0:
  964. f.write(make_separator())
  965. # Create operator signature and anchor point.
  966. operator_anchor = f".. _class_{class_name}_operator_{sanitize_operator_name(m.name, state)}"
  967. for parameter in m.parameters:
  968. operator_anchor += f"_{parameter.type_name.type_name}"
  969. operator_anchor += f":\n\n"
  970. f.write(operator_anchor)
  971. f.write(".. rst-class:: classref-operator\n\n")
  972. ret_type, signature = make_method_signature(class_def, m, "", state)
  973. f.write(f"{ret_type} {signature}\n\n")
  974. # Add operator description, or a call to action if it's missing.
  975. if m.description is not None and m.description.strip() != "":
  976. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  977. else:
  978. f.write(".. container:: contribute\n\n\t")
  979. f.write(
  980. translate(
  981. "There is currently no description for this operator. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  982. )
  983. + "\n\n"
  984. )
  985. index += 1
  986. # Theme property descriptions
  987. if len(class_def.theme_items) > 0:
  988. f.write(make_separator(True))
  989. f.write(".. rst-class:: classref-descriptions-group\n\n")
  990. f.write(make_heading("Theme Property Descriptions", "-"))
  991. index = 0
  992. for theme_item_def in class_def.theme_items.values():
  993. if index != 0:
  994. f.write(make_separator())
  995. # Create theme property signature and anchor point.
  996. f.write(f".. _class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}:\n\n")
  997. f.write(".. rst-class:: classref-themeproperty\n\n")
  998. theme_item_default = ""
  999. if theme_item_def.default_value is not None:
  1000. theme_item_default = f" = {theme_item_def.default_value}"
  1001. f.write(f"{theme_item_def.type_name.to_rst(state)} **{theme_item_def.name}**{theme_item_default}\n\n")
  1002. # Add theme property description, or a call to action if it's missing.
  1003. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  1004. f.write(f"{format_text_block(theme_item_def.text.strip(), theme_item_def, state)}\n\n")
  1005. else:
  1006. f.write(".. container:: contribute\n\n\t")
  1007. f.write(
  1008. translate(
  1009. "There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  1010. )
  1011. + "\n\n"
  1012. )
  1013. index += 1
  1014. f.write(make_footer())
  1015. def make_type(klass: str, state: State) -> str:
  1016. if klass.find("*") != -1: # Pointer, ignore
  1017. return klass
  1018. link_type = klass
  1019. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  1020. link_type = link_type[:-2]
  1021. if link_type in state.classes:
  1022. return f":ref:`{klass}<class_{link_type}>`"
  1023. print_error(f'{state.current_class}.xml: Unresolved type "{klass}".', state)
  1024. return klass
  1025. def make_enum(t: str, is_bitfield: bool, state: State) -> str:
  1026. p = t.find(".")
  1027. if p >= 0:
  1028. c = t[0:p]
  1029. e = t[p + 1 :]
  1030. # Variant enums live in GlobalScope but still use periods.
  1031. if c == "Variant":
  1032. c = "@GlobalScope"
  1033. e = "Variant." + e
  1034. else:
  1035. c = state.current_class
  1036. e = t
  1037. if c in state.classes and e not in state.classes[c].enums:
  1038. c = "@GlobalScope"
  1039. if c in state.classes and e in state.classes[c].enums:
  1040. if is_bitfield:
  1041. if not state.classes[c].enums[e].is_bitfield:
  1042. print_error(f'{state.current_class}.xml: Enum "{t}" is not bitfield.', state)
  1043. return f"|bitfield|\<:ref:`{e}<enum_{c}_{e}>`\>"
  1044. else:
  1045. return f":ref:`{e}<enum_{c}_{e}>`"
  1046. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  1047. if f"{c}.{e}" != "Vector3.Axis":
  1048. print_error(f'{state.current_class}.xml: Unresolved enum "{t}".', state)
  1049. return t
  1050. def make_method_signature(
  1051. class_def: ClassDef, definition: Union[AnnotationDef, MethodDef, SignalDef], ref_type: str, state: State
  1052. ) -> Tuple[str, str]:
  1053. ret_type = ""
  1054. if isinstance(definition, MethodDef):
  1055. ret_type = definition.return_type.to_rst(state)
  1056. qualifiers = None
  1057. if isinstance(definition, (MethodDef, AnnotationDef)):
  1058. qualifiers = definition.qualifiers
  1059. out = ""
  1060. if isinstance(definition, MethodDef) and ref_type != "":
  1061. if ref_type == "operator":
  1062. op_name = definition.name.replace("<", "\\<") # So operator "<" gets correctly displayed.
  1063. out += f":ref:`{op_name}<class_{class_def.name}_{ref_type}_{sanitize_operator_name(definition.name, state)}"
  1064. for parameter in definition.parameters:
  1065. out += f"_{parameter.type_name.type_name}"
  1066. out += f">` "
  1067. else:
  1068. out += f":ref:`{definition.name}<class_{class_def.name}_{ref_type}_{definition.name}>` "
  1069. else:
  1070. out += f"**{definition.name}** "
  1071. out += "**(**"
  1072. for i, arg in enumerate(definition.parameters):
  1073. if i > 0:
  1074. out += ", "
  1075. else:
  1076. out += " "
  1077. out += f"{arg.type_name.to_rst(state)} {arg.name}"
  1078. if arg.default_value is not None:
  1079. out += f"={arg.default_value}"
  1080. if qualifiers is not None and "vararg" in qualifiers:
  1081. if len(definition.parameters) > 0:
  1082. out += ", ..."
  1083. else:
  1084. out += " ..."
  1085. out += " **)**"
  1086. if qualifiers is not None:
  1087. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  1088. # See `make_footer()` for descriptions.
  1089. for qualifier in qualifiers.split():
  1090. out += f" |{qualifier}|"
  1091. return ret_type, out
  1092. def make_setter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  1093. if property_def.setter is None:
  1094. return ""
  1095. # If setter is a method available as a method definition, we use that.
  1096. if property_def.setter in class_def.methods:
  1097. setter = class_def.methods[property_def.setter][0]
  1098. # Otherwise we fake it with the information we have available.
  1099. else:
  1100. setter_params: List[ParameterDef] = []
  1101. setter_params.append(ParameterDef("value", property_def.type_name, None))
  1102. setter = MethodDef(property_def.setter, TypeName("void"), setter_params, None, None)
  1103. ret_type, signature = make_method_signature(class_def, setter, "", state)
  1104. return f"{ret_type} {signature}"
  1105. def make_getter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  1106. if property_def.getter is None:
  1107. return ""
  1108. # If getter is a method available as a method definition, we use that.
  1109. if property_def.getter in class_def.methods:
  1110. getter = class_def.methods[property_def.getter][0]
  1111. # Otherwise we fake it with the information we have available.
  1112. else:
  1113. getter_params: List[ParameterDef] = []
  1114. getter = MethodDef(property_def.getter, property_def.type_name, getter_params, None, None)
  1115. ret_type, signature = make_method_signature(class_def, getter, "", state)
  1116. return f"{ret_type} {signature}"
  1117. def make_heading(title: str, underline: str, l10n: bool = True) -> str:
  1118. if l10n:
  1119. new_title = translate(title)
  1120. if new_title != title:
  1121. title = new_title
  1122. underline *= 2 # Double length to handle wide chars.
  1123. return f"{title}\n{(underline * len(title))}\n\n"
  1124. def make_footer() -> str:
  1125. # Generate reusable abbreviation substitutions.
  1126. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  1127. virtual_msg = translate("This method should typically be overridden by the user to have any effect.")
  1128. const_msg = translate("This method has no side effects. It doesn't modify any of the instance's member variables.")
  1129. vararg_msg = translate("This method accepts any number of arguments after the ones described here.")
  1130. constructor_msg = translate("This method is used to construct a type.")
  1131. static_msg = translate(
  1132. "This method doesn't need an instance to be called, so it can be called directly using the class name."
  1133. )
  1134. operator_msg = translate("This method describes a valid operator to use with this type as left-hand operand.")
  1135. bitfield_msg = translate("This value is an integer composed as a bitmask of the following flags.")
  1136. return (
  1137. f".. |virtual| replace:: :abbr:`virtual ({virtual_msg})`\n"
  1138. f".. |const| replace:: :abbr:`const ({const_msg})`\n"
  1139. f".. |vararg| replace:: :abbr:`vararg ({vararg_msg})`\n"
  1140. f".. |constructor| replace:: :abbr:`constructor ({constructor_msg})`\n"
  1141. f".. |static| replace:: :abbr:`static ({static_msg})`\n"
  1142. f".. |operator| replace:: :abbr:`operator ({operator_msg})`\n"
  1143. f".. |bitfield| replace:: :abbr:`BitField ({bitfield_msg})`\n"
  1144. )
  1145. def make_separator(section_level: bool = False) -> str:
  1146. separator_class = "item"
  1147. if section_level:
  1148. separator_class = "section"
  1149. return f".. rst-class:: classref-{separator_class}-separator\n\n----\n\n"
  1150. def make_link(url: str, title: str) -> str:
  1151. match = GODOT_DOCS_PATTERN.search(url)
  1152. if match:
  1153. groups = match.groups()
  1154. if match.lastindex == 2:
  1155. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  1156. # `#calling-javascript-from-script in Exporting For Web`
  1157. # Or use the title if provided.
  1158. if title != "":
  1159. return f"`{title} <../{groups[0]}.html{groups[1]}>`__"
  1160. return f"`{groups[1]} <../{groups[0]}.html{groups[1]}>`__ in :doc:`../{groups[0]}`"
  1161. elif match.lastindex == 1:
  1162. # Doc reference, for example:
  1163. # `Math`
  1164. if title != "":
  1165. return f":doc:`{title} <../{groups[0]}>`"
  1166. return f":doc:`../{groups[0]}`"
  1167. # External link, for example:
  1168. # `http://enet.bespin.org/usergroup0.html`
  1169. if title != "":
  1170. return f"`{title} <{url}>`__"
  1171. return f"`{url} <{url}>`__"
  1172. def make_rst_index(grouped_classes: Dict[str, List[str]], dry_run: bool, output_dir: str) -> None:
  1173. if dry_run:
  1174. f = open(os.devnull, "w", encoding="utf-8")
  1175. else:
  1176. f = open(os.path.join(output_dir, "index.rst"), "w", encoding="utf-8")
  1177. # Remove the "Edit on Github" button from the online docs page.
  1178. f.write(":github_url: hide\n\n")
  1179. # Warn contributors not to edit this file directly.
  1180. # Also provide links to the source files for reference.
  1181. git_branch = get_git_branch()
  1182. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  1183. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  1184. f.write(".. Generated automatically from Godot engine sources.\n")
  1185. f.write(f".. Generator: {generator_github_url}.\n\n")
  1186. f.write(".. _doc_class_reference:\n\n")
  1187. main_title = translate("All classes")
  1188. f.write(f"{main_title}\n")
  1189. f.write(f"{'=' * len(main_title)}\n\n")
  1190. for group_name in CLASS_GROUPS:
  1191. if group_name in grouped_classes:
  1192. group_title = translate(CLASS_GROUPS[group_name])
  1193. f.write(f"{group_title}\n")
  1194. f.write(f"{'=' * len(group_title)}\n\n")
  1195. f.write(".. toctree::\n")
  1196. f.write(" :maxdepth: 1\n")
  1197. f.write(f" :name: toc-class-ref-{group_name}s\n")
  1198. f.write("\n")
  1199. if group_name in CLASS_GROUPS_BASE:
  1200. f.write(f" class_{CLASS_GROUPS_BASE[group_name].lower()}\n")
  1201. for class_name in grouped_classes[group_name]:
  1202. if group_name in CLASS_GROUPS_BASE and CLASS_GROUPS_BASE[group_name].lower() == class_name.lower():
  1203. continue
  1204. f.write(f" class_{class_name.lower()}\n")
  1205. f.write("\n")
  1206. # Formatting helpers.
  1207. RESERVED_FORMATTING_TAGS = ["i", "b", "u", "code", "kbd", "center", "url", "br"]
  1208. RESERVED_CODEBLOCK_TAGS = ["codeblocks", "codeblock", "gdscript", "csharp"]
  1209. RESERVED_CROSSLINK_TAGS = ["method", "member", "signal", "constant", "enum", "annotation", "theme_item", "param"]
  1210. def is_in_tagset(tag_text: str, tagset: List[str]) -> bool:
  1211. for tag in tagset:
  1212. # Complete match.
  1213. if tag_text == tag:
  1214. return True
  1215. # Tag with arguments.
  1216. if tag_text.startswith(tag + " "):
  1217. return True
  1218. # Tag with arguments, special case for [url].
  1219. if tag_text.startswith(tag + "="):
  1220. return True
  1221. return False
  1222. def format_text_block(
  1223. text: str,
  1224. context: Union[DefinitionBase, None],
  1225. state: State,
  1226. ) -> str:
  1227. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  1228. pos = 0
  1229. while True:
  1230. pos = text.find("\n", pos)
  1231. if pos == -1:
  1232. break
  1233. pre_text = text[:pos]
  1234. indent_level = 0
  1235. while pos + 1 < len(text) and text[pos + 1] == "\t":
  1236. pos += 1
  1237. indent_level += 1
  1238. post_text = text[pos + 1 :]
  1239. # Handle codeblocks
  1240. if (
  1241. post_text.startswith("[codeblock]")
  1242. or post_text.startswith("[gdscript]")
  1243. or post_text.startswith("[csharp]")
  1244. ):
  1245. block_type = post_text[1:].split("]")[0]
  1246. result = format_codeblock(block_type, post_text, indent_level, state)
  1247. if result is None:
  1248. return ""
  1249. text = f"{pre_text}{result[0]}"
  1250. pos += result[1] - indent_level
  1251. # Handle normal text
  1252. else:
  1253. text = f"{pre_text}\n\n{post_text}"
  1254. pos += 2 - indent_level
  1255. next_brac_pos = text.find("[")
  1256. text = escape_rst(text, next_brac_pos)
  1257. context_name = format_context_name(context)
  1258. # Handle [tags]
  1259. inside_code = False
  1260. inside_code_tag = ""
  1261. inside_code_tabs = False
  1262. pos = 0
  1263. tag_depth = 0
  1264. while True:
  1265. pos = text.find("[", pos)
  1266. if pos == -1:
  1267. break
  1268. endq_pos = text.find("]", pos + 1)
  1269. if endq_pos == -1:
  1270. break
  1271. pre_text = text[:pos]
  1272. post_text = text[endq_pos + 1 :]
  1273. tag_text = text[pos + 1 : endq_pos]
  1274. escape_pre = False
  1275. escape_post = False
  1276. # Tag is a reference to a class.
  1277. if tag_text in state.classes and not inside_code:
  1278. if tag_text == state.current_class:
  1279. # Don't create a link to the same class, format it as strong emphasis.
  1280. tag_text = f"**{tag_text}**"
  1281. else:
  1282. tag_text = make_type(tag_text, state)
  1283. escape_pre = True
  1284. escape_post = True
  1285. # Tag is a cross-reference or a formatting directive.
  1286. else:
  1287. cmd = tag_text
  1288. space_pos = tag_text.find(" ")
  1289. # Anything identified as a tag inside of a code block is valid,
  1290. # unless it's a matching closing tag.
  1291. if inside_code:
  1292. # Exiting codeblocks and inline code tags.
  1293. if inside_code_tag == cmd[1:]:
  1294. if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp":
  1295. tag_text = ""
  1296. tag_depth -= 1
  1297. inside_code = False
  1298. # Strip newline if the tag was alone on one
  1299. if pre_text[-1] == "\n":
  1300. pre_text = pre_text[:-1]
  1301. elif cmd == "/code":
  1302. tag_text = "``"
  1303. tag_depth -= 1
  1304. inside_code = False
  1305. escape_post = True
  1306. else:
  1307. if cmd.startswith("/"):
  1308. print_warning(
  1309. f'{state.current_class}.xml: Potential error inside of a code tag, found a string that looks like a closing tag "[{cmd}]" in {context_name}.',
  1310. state,
  1311. )
  1312. tag_text = f"[{tag_text}]"
  1313. # Entering codeblocks and inline code tags.
  1314. elif cmd == "codeblocks":
  1315. tag_depth += 1
  1316. tag_text = "\n.. tabs::"
  1317. inside_code_tabs = True
  1318. elif cmd == "/codeblocks":
  1319. tag_depth -= 1
  1320. tag_text = ""
  1321. inside_code_tabs = False
  1322. elif cmd == "codeblock" or cmd == "gdscript" or cmd == "csharp":
  1323. tag_depth += 1
  1324. if cmd == "gdscript":
  1325. if not inside_code_tabs:
  1326. print_error(
  1327. f"{state.current_class}.xml: GDScript code block is used outside of [codeblocks] in {context_name}.",
  1328. state,
  1329. )
  1330. tag_text = "\n .. code-tab:: gdscript\n"
  1331. elif cmd == "csharp":
  1332. if not inside_code_tabs:
  1333. print_error(
  1334. f"{state.current_class}.xml: C# code block is used outside of [codeblocks] in {context_name}.",
  1335. state,
  1336. )
  1337. tag_text = "\n .. code-tab:: csharp\n"
  1338. else:
  1339. tag_text = "\n::\n"
  1340. inside_code = True
  1341. inside_code_tag = cmd
  1342. elif cmd == "code":
  1343. tag_text = "``"
  1344. tag_depth += 1
  1345. inside_code = True
  1346. inside_code_tag = cmd
  1347. escape_pre = True
  1348. valid_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1349. if valid_context:
  1350. endcode_pos = text.find("[/code]", endq_pos + 1)
  1351. if endcode_pos == -1:
  1352. print_error(
  1353. f"{state.current_class}.xml: Tag depth mismatch for [code]: no closing [/code] in {context_name}.",
  1354. state,
  1355. )
  1356. break
  1357. inside_code_text = text[endq_pos + 1 : endcode_pos]
  1358. context_params: List[ParameterDef] = context.parameters # type: ignore
  1359. for param_def in context_params:
  1360. if param_def.name == inside_code_text:
  1361. print_warning(
  1362. f'{state.current_class}.xml: Potential error inside of a code tag, found a string "{inside_code_text}" that matches one of the parameters in {context_name}.',
  1363. state,
  1364. )
  1365. break
  1366. # Cross-references to items in this or other class documentation pages.
  1367. elif is_in_tagset(cmd, RESERVED_CROSSLINK_TAGS):
  1368. link_type: str = ""
  1369. link_target: str = ""
  1370. if space_pos >= 0:
  1371. link_type = tag_text[:space_pos]
  1372. link_target = tag_text[space_pos + 1 :].strip()
  1373. if link_target == "":
  1374. print_error(
  1375. f'{state.current_class}.xml: Empty cross-reference link "{cmd}" in {context_name}.',
  1376. state,
  1377. )
  1378. tag_text = ""
  1379. else:
  1380. if (
  1381. cmd.startswith("method")
  1382. or cmd.startswith("constructor")
  1383. or cmd.startswith("operator")
  1384. or cmd.startswith("member")
  1385. or cmd.startswith("signal")
  1386. or cmd.startswith("annotation")
  1387. or cmd.startswith("theme_item")
  1388. or cmd.startswith("constant")
  1389. ):
  1390. if link_target.find(".") != -1:
  1391. ss = link_target.split(".")
  1392. if len(ss) > 2:
  1393. print_error(
  1394. f'{state.current_class}.xml: Bad reference "{link_target}" in {context_name}.',
  1395. state,
  1396. )
  1397. class_param, method_param = ss
  1398. else:
  1399. class_param = state.current_class
  1400. method_param = link_target
  1401. # Default to the tag command name. This works by default for most tags,
  1402. # but member and theme_item have special cases.
  1403. ref_type = "_{}".format(link_type)
  1404. if link_type == "member":
  1405. ref_type = "_property"
  1406. if class_param in state.classes:
  1407. class_def = state.classes[class_param]
  1408. if cmd.startswith("method") and method_param not in class_def.methods:
  1409. print_error(
  1410. f'{state.current_class}.xml: Unresolved method reference "{link_target}" in {context_name}.',
  1411. state,
  1412. )
  1413. elif cmd.startswith("constructor") and method_param not in class_def.constructors:
  1414. print_error(
  1415. f'{state.current_class}.xml: Unresolved constructor reference "{link_target}" in {context_name}.',
  1416. state,
  1417. )
  1418. elif cmd.startswith("operator") and method_param not in class_def.operators:
  1419. print_error(
  1420. f'{state.current_class}.xml: Unresolved operator reference "{link_target}" in {context_name}.',
  1421. state,
  1422. )
  1423. elif cmd.startswith("member") and method_param not in class_def.properties:
  1424. print_error(
  1425. f'{state.current_class}.xml: Unresolved member reference "{link_target}" in {context_name}.',
  1426. state,
  1427. )
  1428. elif cmd.startswith("signal") and method_param not in class_def.signals:
  1429. print_error(
  1430. f'{state.current_class}.xml: Unresolved signal reference "{link_target}" in {context_name}.',
  1431. state,
  1432. )
  1433. elif cmd.startswith("annotation") and method_param not in class_def.annotations:
  1434. print_error(
  1435. f'{state.current_class}.xml: Unresolved annotation reference "{link_target}" in {context_name}.',
  1436. state,
  1437. )
  1438. elif cmd.startswith("theme_item"):
  1439. if method_param not in class_def.theme_items:
  1440. print_error(
  1441. f'{state.current_class}.xml: Unresolved theme item reference "{link_target}" in {context_name}.',
  1442. state,
  1443. )
  1444. else:
  1445. # Needs theme data type to be properly linked, which we cannot get without a class.
  1446. name = class_def.theme_items[method_param].data_name
  1447. ref_type = f"_theme_{name}"
  1448. elif cmd.startswith("constant"):
  1449. found = False
  1450. # Search in the current class
  1451. search_class_defs = [class_def]
  1452. if link_target.find(".") == -1:
  1453. # Also search in @GlobalScope as a last resort if no class was specified
  1454. search_class_defs.append(state.classes["@GlobalScope"])
  1455. for search_class_def in search_class_defs:
  1456. if method_param in search_class_def.constants:
  1457. class_param = search_class_def.name
  1458. found = True
  1459. else:
  1460. for enum in search_class_def.enums.values():
  1461. if method_param in enum.values:
  1462. class_param = search_class_def.name
  1463. found = True
  1464. break
  1465. if not found:
  1466. print_error(
  1467. f'{state.current_class}.xml: Unresolved constant reference "{link_target}" in {context_name}.',
  1468. state,
  1469. )
  1470. else:
  1471. print_error(
  1472. f'{state.current_class}.xml: Unresolved type reference "{class_param}" in method reference "{link_target}" in {context_name}.',
  1473. state,
  1474. )
  1475. repl_text = method_param
  1476. if class_param != state.current_class:
  1477. repl_text = f"{class_param}.{method_param}"
  1478. tag_text = f":ref:`{repl_text}<class_{class_param}{ref_type}_{method_param}>`"
  1479. escape_pre = True
  1480. escape_post = True
  1481. elif cmd.startswith("enum"):
  1482. tag_text = make_enum(link_target, False, state)
  1483. escape_pre = True
  1484. escape_post = True
  1485. elif cmd.startswith("param"):
  1486. valid_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1487. if not valid_context:
  1488. print_error(
  1489. f'{state.current_class}.xml: Argument reference "{link_target}" used outside of method, signal, or annotation context in {context_name}.',
  1490. state,
  1491. )
  1492. else:
  1493. context_params: List[ParameterDef] = context.parameters # type: ignore
  1494. found = False
  1495. for param_def in context_params:
  1496. if param_def.name == link_target:
  1497. found = True
  1498. break
  1499. if not found:
  1500. print_error(
  1501. f'{state.current_class}.xml: Unresolved argument reference "{link_target}" in {context_name}.',
  1502. state,
  1503. )
  1504. tag_text = f"``{link_target}``"
  1505. escape_pre = True
  1506. escape_post = True
  1507. # Formatting directives.
  1508. elif is_in_tagset(cmd, ["url"]):
  1509. if cmd.startswith("url="):
  1510. # URLs are handled in full here as we need to extract the optional link
  1511. # title to use `make_link`.
  1512. link_url = cmd[4:]
  1513. endurl_pos = text.find("[/url]", endq_pos + 1)
  1514. if endurl_pos == -1:
  1515. print_error(
  1516. f"{state.current_class}.xml: Tag depth mismatch for [url]: no closing [/url] in {context_name}.",
  1517. state,
  1518. )
  1519. break
  1520. link_title = text[endq_pos + 1 : endurl_pos]
  1521. tag_text = make_link(link_url, link_title)
  1522. pre_text = text[:pos]
  1523. post_text = text[endurl_pos + 6 :]
  1524. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1525. pre_text += "\ "
  1526. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1527. post_text = "\ " + post_text
  1528. text = pre_text + tag_text + post_text
  1529. pos = len(pre_text) + len(tag_text)
  1530. continue
  1531. else:
  1532. print_error(
  1533. f'{state.current_class}.xml: Misformatted [url] tag "{cmd}" in {context_name}.',
  1534. state,
  1535. )
  1536. elif cmd == "br":
  1537. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  1538. tag_text = "\n\n"
  1539. # Strip potential leading spaces
  1540. while post_text[0] == " ":
  1541. post_text = post_text[1:]
  1542. elif cmd == "center" or cmd == "/center":
  1543. if cmd == "/center":
  1544. tag_depth -= 1
  1545. else:
  1546. tag_depth += 1
  1547. tag_text = ""
  1548. elif cmd == "i" or cmd == "/i":
  1549. if cmd == "/i":
  1550. tag_depth -= 1
  1551. escape_post = True
  1552. else:
  1553. tag_depth += 1
  1554. escape_pre = True
  1555. tag_text = "*"
  1556. elif cmd == "b" or cmd == "/b":
  1557. if cmd == "/b":
  1558. tag_depth -= 1
  1559. escape_post = True
  1560. else:
  1561. tag_depth += 1
  1562. escape_pre = True
  1563. tag_text = "**"
  1564. elif cmd == "u" or cmd == "/u":
  1565. if cmd == "/u":
  1566. tag_depth -= 1
  1567. escape_post = True
  1568. else:
  1569. tag_depth += 1
  1570. escape_pre = True
  1571. tag_text = ""
  1572. elif cmd == "kbd" or cmd == "/kbd":
  1573. tag_text = "`"
  1574. if cmd == "/kbd":
  1575. tag_depth -= 1
  1576. escape_post = True
  1577. else:
  1578. tag_text = ":kbd:" + tag_text
  1579. tag_depth += 1
  1580. escape_pre = True
  1581. # Invalid syntax checks.
  1582. elif cmd.startswith("/"):
  1583. print_error(f'{state.current_class}.xml: Unrecognized closing tag "{cmd}" in {context_name}.', state)
  1584. tag_text = f"[{tag_text}]"
  1585. else:
  1586. print_error(f'{state.current_class}.xml: Unrecognized opening tag "{cmd}" in {context_name}.', state)
  1587. tag_text = f"``{tag_text}``"
  1588. escape_pre = True
  1589. escape_post = True
  1590. # Properly escape things like `[Node]s`
  1591. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1592. pre_text += "\ "
  1593. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1594. post_text = "\ " + post_text
  1595. next_brac_pos = post_text.find("[", 0)
  1596. iter_pos = 0
  1597. while not inside_code:
  1598. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  1599. if iter_pos == -1:
  1600. break
  1601. post_text = f"{post_text[:iter_pos]}\*{post_text[iter_pos + 1 :]}"
  1602. iter_pos += 2
  1603. iter_pos = 0
  1604. while not inside_code:
  1605. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  1606. if iter_pos == -1:
  1607. break
  1608. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  1609. post_text = f"{post_text[:iter_pos]}\_{post_text[iter_pos + 1 :]}"
  1610. iter_pos += 2
  1611. else:
  1612. iter_pos += 1
  1613. text = pre_text + tag_text + post_text
  1614. pos = len(pre_text) + len(tag_text)
  1615. if tag_depth > 0:
  1616. print_error(
  1617. f"{state.current_class}.xml: Tag depth mismatch: too many (or too few) open/close tags in {context_name}.",
  1618. state,
  1619. )
  1620. return text
  1621. def format_context_name(context: Union[DefinitionBase, None]) -> str:
  1622. context_name: str = "unknown context"
  1623. if context is not None:
  1624. context_name = f'{context.definition_name} "{context.name}" description'
  1625. return context_name
  1626. def escape_rst(text: str, until_pos: int = -1) -> str:
  1627. # Escape \ character, otherwise it ends up as an escape character in rst
  1628. pos = 0
  1629. while True:
  1630. pos = text.find("\\", pos, until_pos)
  1631. if pos == -1:
  1632. break
  1633. text = f"{text[:pos]}\\\\{text[pos + 1 :]}"
  1634. pos += 2
  1635. # Escape * character to avoid interpreting it as emphasis
  1636. pos = 0
  1637. while True:
  1638. pos = text.find("*", pos, until_pos)
  1639. if pos == -1:
  1640. break
  1641. text = f"{text[:pos]}\*{text[pos + 1 :]}"
  1642. pos += 2
  1643. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  1644. pos = 0
  1645. while True:
  1646. pos = text.find("_", pos, until_pos)
  1647. if pos == -1:
  1648. break
  1649. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  1650. text = f"{text[:pos]}\_{text[pos + 1 :]}"
  1651. pos += 2
  1652. else:
  1653. pos += 1
  1654. return text
  1655. def format_codeblock(code_type: str, post_text: str, indent_level: int, state: State) -> Union[Tuple[str, int], None]:
  1656. end_pos = post_text.find("[/" + code_type + "]")
  1657. if end_pos == -1:
  1658. print_error(f"{state.current_class}.xml: [{code_type}] without a closing tag.", state)
  1659. return None
  1660. code_text = post_text[len(f"[{code_type}]") : end_pos]
  1661. post_text = post_text[end_pos:]
  1662. # Remove extraneous tabs
  1663. code_pos = 0
  1664. while True:
  1665. code_pos = code_text.find("\n", code_pos)
  1666. if code_pos == -1:
  1667. break
  1668. to_skip = 0
  1669. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  1670. to_skip += 1
  1671. if to_skip > indent_level:
  1672. print_error(
  1673. f"{state.current_class}.xml: Four spaces should be used for indentation within [{code_type}].",
  1674. state,
  1675. )
  1676. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  1677. code_text = f"{code_text[:code_pos]}\n"
  1678. code_pos += 1
  1679. else:
  1680. code_text = f"{code_text[:code_pos]}\n {code_text[code_pos + to_skip + 1 :]}"
  1681. code_pos += 5 - to_skip
  1682. return (f"\n[{code_type}]{code_text}{post_text}", len(f"\n[{code_type}]{code_text}"))
  1683. def format_table(f: TextIO, data: List[Tuple[Optional[str], ...]], remove_empty_columns: bool = False) -> None:
  1684. if len(data) == 0:
  1685. return
  1686. f.write(".. table::\n")
  1687. f.write(" :widths: auto\n\n")
  1688. # Calculate the width of each column first, we will use this information
  1689. # to properly format RST-style tables.
  1690. column_sizes = [0] * len(data[0])
  1691. for row in data:
  1692. for i, text in enumerate(row):
  1693. text_length = len(text or "")
  1694. if text_length > column_sizes[i]:
  1695. column_sizes[i] = text_length
  1696. # Each table row is wrapped in two separators, consecutive rows share the same separator.
  1697. # All separators, or rather borders, have the same shape and content. We compose it once,
  1698. # then reuse it.
  1699. sep = ""
  1700. for size in column_sizes:
  1701. if size == 0 and remove_empty_columns:
  1702. continue
  1703. sep += "+" + "-" * (size + 2) # Content of each cell is padded by 1 on each side.
  1704. sep += "+\n"
  1705. # Draw the first separator.
  1706. f.write(f" {sep}")
  1707. # Draw each row and close it with a separator.
  1708. for row in data:
  1709. row_text = "|"
  1710. for i, text in enumerate(row):
  1711. if column_sizes[i] == 0 and remove_empty_columns:
  1712. continue
  1713. row_text += f' {(text or "").ljust(column_sizes[i])} |'
  1714. row_text += "\n"
  1715. f.write(f" {row_text}")
  1716. f.write(f" {sep}")
  1717. f.write("\n")
  1718. def sanitize_operator_name(dirty_name: str, state: State) -> str:
  1719. clear_name = dirty_name.replace("operator ", "")
  1720. if clear_name == "!=":
  1721. clear_name = "neq"
  1722. elif clear_name == "==":
  1723. clear_name = "eq"
  1724. elif clear_name == "<":
  1725. clear_name = "lt"
  1726. elif clear_name == "<=":
  1727. clear_name = "lte"
  1728. elif clear_name == ">":
  1729. clear_name = "gt"
  1730. elif clear_name == ">=":
  1731. clear_name = "gte"
  1732. elif clear_name == "+":
  1733. clear_name = "sum"
  1734. elif clear_name == "-":
  1735. clear_name = "dif"
  1736. elif clear_name == "*":
  1737. clear_name = "mul"
  1738. elif clear_name == "/":
  1739. clear_name = "div"
  1740. elif clear_name == "%":
  1741. clear_name = "mod"
  1742. elif clear_name == "**":
  1743. clear_name = "pow"
  1744. elif clear_name == "unary+":
  1745. clear_name = "unplus"
  1746. elif clear_name == "unary-":
  1747. clear_name = "unminus"
  1748. elif clear_name == "<<":
  1749. clear_name = "bwsl"
  1750. elif clear_name == ">>":
  1751. clear_name = "bwsr"
  1752. elif clear_name == "&":
  1753. clear_name = "bwand"
  1754. elif clear_name == "|":
  1755. clear_name = "bwor"
  1756. elif clear_name == "^":
  1757. clear_name = "bwxor"
  1758. elif clear_name == "~":
  1759. clear_name = "bwnot"
  1760. elif clear_name == "[]":
  1761. clear_name = "idx"
  1762. else:
  1763. clear_name = "xxx"
  1764. print_error(f'Unsupported operator type "{dirty_name}", please add the missing rule.', state)
  1765. return clear_name
  1766. if __name__ == "__main__":
  1767. main()