make_rst.py 89 KB

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