make_rst.py 90 KB

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