make_rst.py 93 KB

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