make_rst.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391
  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. method_qualifier = ""
  948. if m.name.startswith("_"):
  949. method_qualifier = "private_"
  950. f.write(f".. _class_{class_name}_{method_qualifier}method_{m.name}:\n\n")
  951. f.write(".. rst-class:: classref-method\n\n")
  952. ret_type, signature = make_method_signature(class_def, m, "", state)
  953. f.write(f"{ret_type} {signature}\n\n")
  954. # Add method description, or a call to action if it's missing.
  955. if m.description is not None and m.description.strip() != "":
  956. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  957. else:
  958. f.write(".. container:: contribute\n\n\t")
  959. f.write(
  960. translate(
  961. "There is currently no description for this method. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  962. )
  963. + "\n\n"
  964. )
  965. index += 1
  966. if len(class_def.operators) > 0:
  967. f.write(make_separator(True))
  968. f.write(".. rst-class:: classref-descriptions-group\n\n")
  969. f.write(make_heading("Operator Descriptions", "-"))
  970. index = 0
  971. for method_list in class_def.operators.values():
  972. for i, m in enumerate(method_list):
  973. if index != 0:
  974. f.write(make_separator())
  975. # Create operator signature and anchor point.
  976. operator_anchor = f".. _class_{class_name}_operator_{sanitize_operator_name(m.name, state)}"
  977. for parameter in m.parameters:
  978. operator_anchor += f"_{parameter.type_name.type_name}"
  979. operator_anchor += f":\n\n"
  980. f.write(operator_anchor)
  981. f.write(".. rst-class:: classref-operator\n\n")
  982. ret_type, signature = make_method_signature(class_def, m, "", state)
  983. f.write(f"{ret_type} {signature}\n\n")
  984. # Add operator description, or a call to action if it's missing.
  985. if m.description is not None and m.description.strip() != "":
  986. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  987. else:
  988. f.write(".. container:: contribute\n\n\t")
  989. f.write(
  990. translate(
  991. "There is currently no description for this operator. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  992. )
  993. + "\n\n"
  994. )
  995. index += 1
  996. # Theme property descriptions
  997. if len(class_def.theme_items) > 0:
  998. f.write(make_separator(True))
  999. f.write(".. rst-class:: classref-descriptions-group\n\n")
  1000. f.write(make_heading("Theme Property Descriptions", "-"))
  1001. index = 0
  1002. for theme_item_def in class_def.theme_items.values():
  1003. if index != 0:
  1004. f.write(make_separator())
  1005. # Create theme property signature and anchor point.
  1006. f.write(f".. _class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}:\n\n")
  1007. f.write(".. rst-class:: classref-themeproperty\n\n")
  1008. theme_item_default = ""
  1009. if theme_item_def.default_value is not None:
  1010. theme_item_default = f" = {theme_item_def.default_value}"
  1011. f.write(f"{theme_item_def.type_name.to_rst(state)} **{theme_item_def.name}**{theme_item_default}\n\n")
  1012. # Add theme property description, or a call to action if it's missing.
  1013. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  1014. f.write(f"{format_text_block(theme_item_def.text.strip(), theme_item_def, state)}\n\n")
  1015. else:
  1016. f.write(".. container:: contribute\n\n\t")
  1017. f.write(
  1018. translate(
  1019. "There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  1020. )
  1021. + "\n\n"
  1022. )
  1023. index += 1
  1024. f.write(make_footer())
  1025. def make_type(klass: str, state: State) -> str:
  1026. if klass.find("*") != -1: # Pointer, ignore
  1027. return klass
  1028. link_type = klass
  1029. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  1030. link_type = link_type[:-2]
  1031. if link_type in state.classes:
  1032. return f":ref:`{klass}<class_{link_type}>`"
  1033. print_error(f'{state.current_class}.xml: Unresolved type "{klass}".', state)
  1034. return klass
  1035. def make_enum(t: str, is_bitfield: bool, state: State) -> str:
  1036. p = t.find(".")
  1037. if p >= 0:
  1038. c = t[0:p]
  1039. e = t[p + 1 :]
  1040. # Variant enums live in GlobalScope but still use periods.
  1041. if c == "Variant":
  1042. c = "@GlobalScope"
  1043. e = "Variant." + e
  1044. else:
  1045. c = state.current_class
  1046. e = t
  1047. if c in state.classes and e not in state.classes[c].enums:
  1048. c = "@GlobalScope"
  1049. if c in state.classes and e in state.classes[c].enums:
  1050. if is_bitfield:
  1051. if not state.classes[c].enums[e].is_bitfield:
  1052. print_error(f'{state.current_class}.xml: Enum "{t}" is not bitfield.', state)
  1053. return f"|bitfield|\\<:ref:`{e}<enum_{c}_{e}>`\\>"
  1054. else:
  1055. return f":ref:`{e}<enum_{c}_{e}>`"
  1056. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  1057. if f"{c}.{e}" != "Vector3.Axis":
  1058. print_error(f'{state.current_class}.xml: Unresolved enum "{t}".', state)
  1059. return t
  1060. def make_method_signature(
  1061. class_def: ClassDef, definition: Union[AnnotationDef, MethodDef, SignalDef], ref_type: str, state: State
  1062. ) -> Tuple[str, str]:
  1063. ret_type = ""
  1064. if isinstance(definition, MethodDef):
  1065. ret_type = definition.return_type.to_rst(state)
  1066. qualifiers = None
  1067. if isinstance(definition, (MethodDef, AnnotationDef)):
  1068. qualifiers = definition.qualifiers
  1069. out = ""
  1070. if isinstance(definition, MethodDef) and ref_type != "":
  1071. if ref_type == "operator":
  1072. op_name = definition.name.replace("<", "\\<") # So operator "<" gets correctly displayed.
  1073. out += f":ref:`{op_name}<class_{class_def.name}_{ref_type}_{sanitize_operator_name(definition.name, state)}"
  1074. for parameter in definition.parameters:
  1075. out += f"_{parameter.type_name.type_name}"
  1076. out += f">` "
  1077. elif ref_type == "method":
  1078. ref_type_qualifier = ""
  1079. if definition.name.startswith("_"):
  1080. ref_type_qualifier = "private_"
  1081. out += f":ref:`{definition.name}<class_{class_def.name}_{ref_type_qualifier}{ref_type}_{definition.name}>` "
  1082. else:
  1083. out += f":ref:`{definition.name}<class_{class_def.name}_{ref_type}_{definition.name}>` "
  1084. else:
  1085. out += f"**{definition.name}** "
  1086. out += "**(**"
  1087. for i, arg in enumerate(definition.parameters):
  1088. if i > 0:
  1089. out += ", "
  1090. else:
  1091. out += " "
  1092. out += f"{arg.type_name.to_rst(state)} {arg.name}"
  1093. if arg.default_value is not None:
  1094. out += f"={arg.default_value}"
  1095. if qualifiers is not None and "vararg" in qualifiers:
  1096. if len(definition.parameters) > 0:
  1097. out += ", ..."
  1098. else:
  1099. out += " ..."
  1100. out += " **)**"
  1101. if qualifiers is not None:
  1102. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  1103. # See `make_footer()` for descriptions.
  1104. for qualifier in qualifiers.split():
  1105. out += f" |{qualifier}|"
  1106. return ret_type, out
  1107. def make_setter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  1108. if property_def.setter is None:
  1109. return ""
  1110. # If setter is a method available as a method definition, we use that.
  1111. if property_def.setter in class_def.methods:
  1112. setter = class_def.methods[property_def.setter][0]
  1113. # Otherwise we fake it with the information we have available.
  1114. else:
  1115. setter_params: List[ParameterDef] = []
  1116. setter_params.append(ParameterDef("value", property_def.type_name, None))
  1117. setter = MethodDef(property_def.setter, TypeName("void"), setter_params, None, None)
  1118. ret_type, signature = make_method_signature(class_def, setter, "", state)
  1119. return f"{ret_type} {signature}"
  1120. def make_getter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  1121. if property_def.getter is None:
  1122. return ""
  1123. # If getter is a method available as a method definition, we use that.
  1124. if property_def.getter in class_def.methods:
  1125. getter = class_def.methods[property_def.getter][0]
  1126. # Otherwise we fake it with the information we have available.
  1127. else:
  1128. getter_params: List[ParameterDef] = []
  1129. getter = MethodDef(property_def.getter, property_def.type_name, getter_params, None, None)
  1130. ret_type, signature = make_method_signature(class_def, getter, "", state)
  1131. return f"{ret_type} {signature}"
  1132. def make_heading(title: str, underline: str, l10n: bool = True) -> str:
  1133. if l10n:
  1134. new_title = translate(title)
  1135. if new_title != title:
  1136. title = new_title
  1137. underline *= 2 # Double length to handle wide chars.
  1138. return f"{title}\n{(underline * len(title))}\n\n"
  1139. def make_footer() -> str:
  1140. # Generate reusable abbreviation substitutions.
  1141. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  1142. virtual_msg = translate("This method should typically be overridden by the user to have any effect.")
  1143. const_msg = translate("This method has no side effects. It doesn't modify any of the instance's member variables.")
  1144. vararg_msg = translate("This method accepts any number of arguments after the ones described here.")
  1145. constructor_msg = translate("This method is used to construct a type.")
  1146. static_msg = translate(
  1147. "This method doesn't need an instance to be called, so it can be called directly using the class name."
  1148. )
  1149. operator_msg = translate("This method describes a valid operator to use with this type as left-hand operand.")
  1150. bitfield_msg = translate("This value is an integer composed as a bitmask of the following flags.")
  1151. return (
  1152. f".. |virtual| replace:: :abbr:`virtual ({virtual_msg})`\n"
  1153. f".. |const| replace:: :abbr:`const ({const_msg})`\n"
  1154. f".. |vararg| replace:: :abbr:`vararg ({vararg_msg})`\n"
  1155. f".. |constructor| replace:: :abbr:`constructor ({constructor_msg})`\n"
  1156. f".. |static| replace:: :abbr:`static ({static_msg})`\n"
  1157. f".. |operator| replace:: :abbr:`operator ({operator_msg})`\n"
  1158. f".. |bitfield| replace:: :abbr:`BitField ({bitfield_msg})`\n"
  1159. )
  1160. def make_separator(section_level: bool = False) -> str:
  1161. separator_class = "item"
  1162. if section_level:
  1163. separator_class = "section"
  1164. return f".. rst-class:: classref-{separator_class}-separator\n\n----\n\n"
  1165. def make_link(url: str, title: str) -> str:
  1166. match = GODOT_DOCS_PATTERN.search(url)
  1167. if match:
  1168. groups = match.groups()
  1169. if match.lastindex == 2:
  1170. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  1171. # `#calling-javascript-from-script in Exporting For Web`
  1172. # Or use the title if provided.
  1173. if title != "":
  1174. return f"`{title} <../{groups[0]}.html{groups[1]}>`__"
  1175. return f"`{groups[1]} <../{groups[0]}.html{groups[1]}>`__ in :doc:`../{groups[0]}`"
  1176. elif match.lastindex == 1:
  1177. # Doc reference, for example:
  1178. # `Math`
  1179. if title != "":
  1180. return f":doc:`{title} <../{groups[0]}>`"
  1181. return f":doc:`../{groups[0]}`"
  1182. # External link, for example:
  1183. # `http://enet.bespin.org/usergroup0.html`
  1184. if title != "":
  1185. return f"`{title} <{url}>`__"
  1186. return f"`{url} <{url}>`__"
  1187. def make_rst_index(grouped_classes: Dict[str, List[str]], dry_run: bool, output_dir: str) -> None:
  1188. if dry_run:
  1189. f = open(os.devnull, "w", encoding="utf-8")
  1190. else:
  1191. f = open(os.path.join(output_dir, "index.rst"), "w", encoding="utf-8")
  1192. # Remove the "Edit on Github" button from the online docs page, and disallow user-contributed notes
  1193. # on the index page. User-contributed notes are allowed on individual class pages.
  1194. f.write(":github_url: hide\n:allow_comments: False\n\n")
  1195. # Warn contributors not to edit this file directly.
  1196. # Also provide links to the source files for reference.
  1197. git_branch = get_git_branch()
  1198. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  1199. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  1200. f.write(".. Generated automatically from Godot engine sources.\n")
  1201. f.write(f".. Generator: {generator_github_url}.\n\n")
  1202. f.write(".. _doc_class_reference:\n\n")
  1203. main_title = translate("All classes")
  1204. f.write(f"{main_title}\n")
  1205. f.write(f"{'=' * len(main_title)}\n\n")
  1206. for group_name in CLASS_GROUPS:
  1207. if group_name in grouped_classes:
  1208. group_title = translate(CLASS_GROUPS[group_name])
  1209. f.write(f"{group_title}\n")
  1210. f.write(f"{'=' * len(group_title)}\n\n")
  1211. f.write(".. toctree::\n")
  1212. f.write(" :maxdepth: 1\n")
  1213. f.write(f" :name: toc-class-ref-{group_name}s\n")
  1214. f.write("\n")
  1215. if group_name in CLASS_GROUPS_BASE:
  1216. f.write(f" class_{CLASS_GROUPS_BASE[group_name].lower()}\n")
  1217. for class_name in grouped_classes[group_name]:
  1218. if group_name in CLASS_GROUPS_BASE and CLASS_GROUPS_BASE[group_name].lower() == class_name.lower():
  1219. continue
  1220. f.write(f" class_{class_name.lower()}\n")
  1221. f.write("\n")
  1222. # Formatting helpers.
  1223. RESERVED_FORMATTING_TAGS = ["i", "b", "u", "code", "kbd", "center", "url", "br"]
  1224. RESERVED_LAYOUT_TAGS = ["codeblocks"]
  1225. RESERVED_CODEBLOCK_TAGS = ["codeblock", "gdscript", "csharp"]
  1226. RESERVED_CROSSLINK_TAGS = [
  1227. "method",
  1228. "constructor",
  1229. "operator",
  1230. "member",
  1231. "signal",
  1232. "constant",
  1233. "enum",
  1234. "annotation",
  1235. "theme_item",
  1236. "param",
  1237. ]
  1238. def is_in_tagset(tag_text: str, tagset: List[str]) -> bool:
  1239. for tag in tagset:
  1240. # Complete match.
  1241. if tag_text == tag:
  1242. return True
  1243. # Tag with arguments.
  1244. if tag_text.startswith(tag + " "):
  1245. return True
  1246. # Tag with arguments, special case for [url].
  1247. if tag_text.startswith(tag + "="):
  1248. return True
  1249. return False
  1250. def get_tag_and_args(tag_text: str) -> TagState:
  1251. tag_name = tag_text
  1252. arguments: List[str] = []
  1253. assign_pos = tag_text.find("=")
  1254. if assign_pos >= 0:
  1255. tag_name = tag_text[:assign_pos]
  1256. arguments = [tag_text[assign_pos + 1 :].strip()]
  1257. else:
  1258. space_pos = tag_text.find(" ")
  1259. if space_pos >= 0:
  1260. tag_name = tag_text[:space_pos]
  1261. arguments = [tag_text[space_pos + 1 :].strip()]
  1262. closing = False
  1263. if tag_name.startswith("/"):
  1264. tag_name = tag_name[1:]
  1265. closing = True
  1266. return TagState(tag_text, tag_name, arguments, closing)
  1267. def parse_link_target(link_target: str, state: State, context_name: str) -> List[str]:
  1268. if link_target.find(".") != -1:
  1269. return link_target.split(".")
  1270. else:
  1271. return [state.current_class, link_target]
  1272. def format_text_block(
  1273. text: str,
  1274. context: Union[DefinitionBase, None],
  1275. state: State,
  1276. ) -> str:
  1277. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  1278. pos = 0
  1279. while True:
  1280. pos = text.find("\n", pos)
  1281. if pos == -1:
  1282. break
  1283. pre_text = text[:pos]
  1284. indent_level = 0
  1285. while pos + 1 < len(text) and text[pos + 1] == "\t":
  1286. pos += 1
  1287. indent_level += 1
  1288. post_text = text[pos + 1 :]
  1289. # Handle codeblocks
  1290. if (
  1291. post_text.startswith("[codeblock]")
  1292. or post_text.startswith("[codeblock ")
  1293. or post_text.startswith("[gdscript]")
  1294. or post_text.startswith("[gdscript ")
  1295. or post_text.startswith("[csharp]")
  1296. or post_text.startswith("[csharp ")
  1297. ):
  1298. tag_text = post_text[1:].split("]", 1)[0]
  1299. tag_state = get_tag_and_args(tag_text)
  1300. result = format_codeblock(tag_state, post_text, indent_level, state)
  1301. if result is None:
  1302. return ""
  1303. text = f"{pre_text}{result[0]}"
  1304. pos += result[1] - indent_level
  1305. # Handle normal text
  1306. else:
  1307. text = f"{pre_text}\n\n{post_text}"
  1308. pos += 2 - indent_level
  1309. next_brac_pos = text.find("[")
  1310. text = escape_rst(text, next_brac_pos)
  1311. context_name = format_context_name(context)
  1312. # Handle [tags]
  1313. inside_code = False
  1314. inside_code_tag = ""
  1315. inside_code_tabs = False
  1316. ignore_code_warnings = False
  1317. pos = 0
  1318. tag_depth = 0
  1319. while True:
  1320. pos = text.find("[", pos)
  1321. if pos == -1:
  1322. break
  1323. endq_pos = text.find("]", pos + 1)
  1324. if endq_pos == -1:
  1325. break
  1326. pre_text = text[:pos]
  1327. post_text = text[endq_pos + 1 :]
  1328. tag_text = text[pos + 1 : endq_pos]
  1329. escape_pre = False
  1330. escape_post = False
  1331. # Tag is a reference to a class.
  1332. if tag_text in state.classes and not inside_code:
  1333. if tag_text == state.current_class:
  1334. # Don't create a link to the same class, format it as strong emphasis.
  1335. tag_text = f"**{tag_text}**"
  1336. else:
  1337. tag_text = make_type(tag_text, state)
  1338. escape_pre = True
  1339. escape_post = True
  1340. # Tag is a cross-reference or a formatting directive.
  1341. else:
  1342. tag_state = get_tag_and_args(tag_text)
  1343. # Anything identified as a tag inside of a code block is valid,
  1344. # unless it's a matching closing tag.
  1345. if inside_code:
  1346. # Exiting codeblocks and inline code tags.
  1347. if tag_state.closing and tag_state.name == inside_code_tag:
  1348. if is_in_tagset(tag_state.name, RESERVED_CODEBLOCK_TAGS):
  1349. tag_text = ""
  1350. tag_depth -= 1
  1351. inside_code = False
  1352. ignore_code_warnings = False
  1353. # Strip newline if the tag was alone on one
  1354. if pre_text[-1] == "\n":
  1355. pre_text = pre_text[:-1]
  1356. elif is_in_tagset(tag_state.name, ["code"]):
  1357. tag_text = "``"
  1358. tag_depth -= 1
  1359. inside_code = False
  1360. ignore_code_warnings = False
  1361. escape_post = True
  1362. else:
  1363. if not ignore_code_warnings and tag_state.closing:
  1364. print_warning(
  1365. f'{state.current_class}.xml: Found a code string that looks like a closing tag "[{tag_state.raw}]" in {context_name}.',
  1366. state,
  1367. )
  1368. tag_text = f"[{tag_text}]"
  1369. # Entering codeblocks and inline code tags.
  1370. elif tag_state.name == "codeblocks":
  1371. if tag_state.closing:
  1372. tag_depth -= 1
  1373. tag_text = ""
  1374. inside_code_tabs = False
  1375. else:
  1376. tag_depth += 1
  1377. tag_text = "\n.. tabs::"
  1378. inside_code_tabs = True
  1379. elif is_in_tagset(tag_state.name, RESERVED_CODEBLOCK_TAGS):
  1380. tag_depth += 1
  1381. if tag_state.name == "gdscript":
  1382. if not inside_code_tabs:
  1383. print_error(
  1384. f"{state.current_class}.xml: GDScript code block is used outside of [codeblocks] in {context_name}.",
  1385. state,
  1386. )
  1387. tag_text = "\n .. code-tab:: gdscript\n"
  1388. elif tag_state.name == "csharp":
  1389. if not inside_code_tabs:
  1390. print_error(
  1391. f"{state.current_class}.xml: C# code block is used outside of [codeblocks] in {context_name}.",
  1392. state,
  1393. )
  1394. tag_text = "\n .. code-tab:: csharp\n"
  1395. else:
  1396. tag_text = "\n::\n"
  1397. inside_code = True
  1398. inside_code_tag = tag_state.name
  1399. ignore_code_warnings = "skip-lint" in tag_state.arguments
  1400. elif is_in_tagset(tag_state.name, ["code"]):
  1401. tag_text = "``"
  1402. tag_depth += 1
  1403. inside_code = True
  1404. inside_code_tag = "code"
  1405. ignore_code_warnings = "skip-lint" in tag_state.arguments
  1406. escape_pre = True
  1407. if not ignore_code_warnings:
  1408. endcode_pos = text.find("[/code]", endq_pos + 1)
  1409. if endcode_pos == -1:
  1410. print_error(
  1411. f"{state.current_class}.xml: Tag depth mismatch for [code]: no closing [/code] in {context_name}.",
  1412. state,
  1413. )
  1414. break
  1415. inside_code_text = text[endq_pos + 1 : endcode_pos]
  1416. if inside_code_text.endswith("()"):
  1417. # It's formatted like a call for some reason, may still be a mistake.
  1418. inside_code_text = inside_code_text[:-2]
  1419. if inside_code_text in state.classes:
  1420. print_warning(
  1421. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches one of the known classes in {context_name}.',
  1422. state,
  1423. )
  1424. target_class_name, target_name, *rest = parse_link_target(inside_code_text, state, context_name)
  1425. if len(rest) == 0 and target_class_name in state.classes:
  1426. class_def = state.classes[target_class_name]
  1427. if target_name in class_def.methods:
  1428. print_warning(
  1429. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches the {target_class_name}.{target_name} method in {context_name}.',
  1430. state,
  1431. )
  1432. elif target_name in class_def.constructors:
  1433. print_warning(
  1434. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches the {target_class_name}.{target_name} constructor in {context_name}.',
  1435. state,
  1436. )
  1437. elif target_name in class_def.operators:
  1438. print_warning(
  1439. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches the {target_class_name}.{target_name} operator in {context_name}.',
  1440. state,
  1441. )
  1442. elif target_name in class_def.properties:
  1443. print_warning(
  1444. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches the {target_class_name}.{target_name} member in {context_name}.',
  1445. state,
  1446. )
  1447. elif target_name in class_def.signals:
  1448. print_warning(
  1449. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches the {target_class_name}.{target_name} signal in {context_name}.',
  1450. state,
  1451. )
  1452. elif target_name in class_def.annotations:
  1453. print_warning(
  1454. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches the {target_class_name}.{target_name} annotation in {context_name}.',
  1455. state,
  1456. )
  1457. elif target_name in class_def.theme_items:
  1458. print_warning(
  1459. 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}.',
  1460. state,
  1461. )
  1462. elif target_name in class_def.constants:
  1463. print_warning(
  1464. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches the {target_class_name}.{target_name} constant in {context_name}.',
  1465. state,
  1466. )
  1467. else:
  1468. for enum in class_def.enums.values():
  1469. if target_name in enum.values:
  1470. print_warning(
  1471. 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}.',
  1472. state,
  1473. )
  1474. break
  1475. valid_param_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1476. if valid_param_context:
  1477. context_params: List[ParameterDef] = context.parameters # type: ignore
  1478. for param_def in context_params:
  1479. if param_def.name == inside_code_text:
  1480. print_warning(
  1481. f'{state.current_class}.xml: Found a code string "{inside_code_text}" that matches one of the parameters in {context_name}.',
  1482. state,
  1483. )
  1484. break
  1485. # Cross-references to items in this or other class documentation pages.
  1486. elif is_in_tagset(tag_state.name, RESERVED_CROSSLINK_TAGS):
  1487. link_target: str = tag_state.arguments[0] if len(tag_state.arguments) > 0 else ""
  1488. if link_target == "":
  1489. print_error(
  1490. f'{state.current_class}.xml: Empty cross-reference link "[{tag_state.raw}]" in {context_name}.',
  1491. state,
  1492. )
  1493. tag_text = ""
  1494. else:
  1495. if (
  1496. tag_state.name == "method"
  1497. or tag_state.name == "constructor"
  1498. or tag_state.name == "operator"
  1499. or tag_state.name == "member"
  1500. or tag_state.name == "signal"
  1501. or tag_state.name == "annotation"
  1502. or tag_state.name == "theme_item"
  1503. or tag_state.name == "constant"
  1504. ):
  1505. target_class_name, target_name, *rest = parse_link_target(link_target, state, context_name)
  1506. if len(rest) > 0:
  1507. print_error(
  1508. f'{state.current_class}.xml: Bad reference "{link_target}" in {context_name}.',
  1509. state,
  1510. )
  1511. # Default to the tag command name. This works by default for most tags,
  1512. # but method, member, and theme_item have special cases.
  1513. ref_type = "_{}".format(tag_state.name)
  1514. if target_class_name in state.classes:
  1515. class_def = state.classes[target_class_name]
  1516. if tag_state.name == "method":
  1517. if target_name.startswith("_"):
  1518. ref_type = "_private_method"
  1519. if target_name not in class_def.methods:
  1520. print_error(
  1521. f'{state.current_class}.xml: Unresolved method reference "{link_target}" in {context_name}.',
  1522. state,
  1523. )
  1524. elif tag_state.name == "constructor" and target_name not in class_def.constructors:
  1525. print_error(
  1526. f'{state.current_class}.xml: Unresolved constructor reference "{link_target}" in {context_name}.',
  1527. state,
  1528. )
  1529. elif tag_state.name == "operator" and target_name not in class_def.operators:
  1530. print_error(
  1531. f'{state.current_class}.xml: Unresolved operator reference "{link_target}" in {context_name}.',
  1532. state,
  1533. )
  1534. elif tag_state.name == "member":
  1535. ref_type = "_property"
  1536. if target_name not in class_def.properties:
  1537. print_error(
  1538. f'{state.current_class}.xml: Unresolved member reference "{link_target}" in {context_name}.',
  1539. state,
  1540. )
  1541. elif tag_state.name == "signal" and target_name not in class_def.signals:
  1542. print_error(
  1543. f'{state.current_class}.xml: Unresolved signal reference "{link_target}" in {context_name}.',
  1544. state,
  1545. )
  1546. elif tag_state.name == "annotation" and target_name not in class_def.annotations:
  1547. print_error(
  1548. f'{state.current_class}.xml: Unresolved annotation reference "{link_target}" in {context_name}.',
  1549. state,
  1550. )
  1551. elif tag_state.name == "theme_item":
  1552. if target_name not in class_def.theme_items:
  1553. print_error(
  1554. f'{state.current_class}.xml: Unresolved theme item reference "{link_target}" in {context_name}.',
  1555. state,
  1556. )
  1557. else:
  1558. # Needs theme data type to be properly linked, which we cannot get without a class.
  1559. name = class_def.theme_items[target_name].data_name
  1560. ref_type = f"_theme_{name}"
  1561. elif tag_state.name == "constant":
  1562. found = False
  1563. # Search in the current class
  1564. search_class_defs = [class_def]
  1565. if link_target.find(".") == -1:
  1566. # Also search in @GlobalScope as a last resort if no class was specified
  1567. search_class_defs.append(state.classes["@GlobalScope"])
  1568. for search_class_def in search_class_defs:
  1569. if target_name in search_class_def.constants:
  1570. target_class_name = search_class_def.name
  1571. found = True
  1572. else:
  1573. for enum in search_class_def.enums.values():
  1574. if target_name in enum.values:
  1575. target_class_name = search_class_def.name
  1576. found = True
  1577. break
  1578. if not found:
  1579. print_error(
  1580. f'{state.current_class}.xml: Unresolved constant reference "{link_target}" in {context_name}.',
  1581. state,
  1582. )
  1583. else:
  1584. print_error(
  1585. f'{state.current_class}.xml: Unresolved type reference "{target_class_name}" in method reference "{link_target}" in {context_name}.',
  1586. state,
  1587. )
  1588. repl_text = target_name
  1589. if target_class_name != state.current_class:
  1590. repl_text = f"{target_class_name}.{target_name}"
  1591. tag_text = f":ref:`{repl_text}<class_{target_class_name}{ref_type}_{target_name}>`"
  1592. escape_pre = True
  1593. escape_post = True
  1594. elif tag_state.name == "enum":
  1595. tag_text = make_enum(link_target, False, state)
  1596. escape_pre = True
  1597. escape_post = True
  1598. elif tag_state.name == "param":
  1599. valid_param_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1600. if not valid_param_context:
  1601. print_error(
  1602. f'{state.current_class}.xml: Argument reference "{link_target}" used outside of method, signal, or annotation context in {context_name}.',
  1603. state,
  1604. )
  1605. else:
  1606. context_params: List[ParameterDef] = context.parameters # type: ignore
  1607. found = False
  1608. for param_def in context_params:
  1609. if param_def.name == link_target:
  1610. found = True
  1611. break
  1612. if not found:
  1613. print_error(
  1614. f'{state.current_class}.xml: Unresolved argument reference "{link_target}" in {context_name}.',
  1615. state,
  1616. )
  1617. tag_text = f"``{link_target}``"
  1618. escape_pre = True
  1619. escape_post = True
  1620. # Formatting directives.
  1621. elif is_in_tagset(tag_state.name, ["url"]):
  1622. url_target = tag_state.arguments[0] if len(tag_state.arguments) > 0 else ""
  1623. if url_target == "":
  1624. print_error(
  1625. f'{state.current_class}.xml: Misformatted [url] tag "[{tag_state.raw}]" in {context_name}.',
  1626. state,
  1627. )
  1628. else:
  1629. # Unlike other tags, URLs are handled in full here, as we need to extract
  1630. # the optional link title to use `make_link`.
  1631. endurl_pos = text.find("[/url]", endq_pos + 1)
  1632. if endurl_pos == -1:
  1633. print_error(
  1634. f"{state.current_class}.xml: Tag depth mismatch for [url]: no closing [/url] in {context_name}.",
  1635. state,
  1636. )
  1637. break
  1638. link_title = text[endq_pos + 1 : endurl_pos]
  1639. tag_text = make_link(url_target, link_title)
  1640. pre_text = text[:pos]
  1641. post_text = text[endurl_pos + 6 :]
  1642. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1643. pre_text += "\\ "
  1644. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1645. post_text = "\\ " + post_text
  1646. text = pre_text + tag_text + post_text
  1647. pos = len(pre_text) + len(tag_text)
  1648. continue
  1649. elif tag_state.name == "br":
  1650. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  1651. tag_text = "\n\n"
  1652. # Strip potential leading spaces
  1653. while post_text[0] == " ":
  1654. post_text = post_text[1:]
  1655. elif tag_state.name == "center":
  1656. if tag_state.closing:
  1657. tag_depth -= 1
  1658. else:
  1659. tag_depth += 1
  1660. tag_text = ""
  1661. elif tag_state.name == "i":
  1662. if tag_state.closing:
  1663. tag_depth -= 1
  1664. escape_post = True
  1665. else:
  1666. tag_depth += 1
  1667. escape_pre = True
  1668. tag_text = "*"
  1669. elif tag_state.name == "b":
  1670. if tag_state.closing:
  1671. tag_depth -= 1
  1672. escape_post = True
  1673. else:
  1674. tag_depth += 1
  1675. escape_pre = True
  1676. tag_text = "**"
  1677. elif tag_state.name == "u":
  1678. if tag_state.closing:
  1679. tag_depth -= 1
  1680. escape_post = True
  1681. else:
  1682. tag_depth += 1
  1683. escape_pre = True
  1684. tag_text = ""
  1685. elif tag_state.name == "kbd":
  1686. tag_text = "`"
  1687. if tag_state.closing:
  1688. tag_depth -= 1
  1689. escape_post = True
  1690. else:
  1691. tag_text = ":kbd:" + tag_text
  1692. tag_depth += 1
  1693. escape_pre = True
  1694. # Invalid syntax.
  1695. else:
  1696. if tag_state.closing:
  1697. print_error(
  1698. f'{state.current_class}.xml: Unrecognized closing tag "[{tag_state.raw}]" in {context_name}.',
  1699. state,
  1700. )
  1701. tag_text = f"[{tag_text}]"
  1702. else:
  1703. print_error(
  1704. f'{state.current_class}.xml: Unrecognized opening tag "[{tag_state.raw}]" in {context_name}.',
  1705. state,
  1706. )
  1707. tag_text = f"``{tag_text}``"
  1708. escape_pre = True
  1709. escape_post = True
  1710. # Properly escape things like `[Node]s`
  1711. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1712. pre_text += "\\ "
  1713. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1714. post_text = "\\ " + post_text
  1715. next_brac_pos = post_text.find("[", 0)
  1716. iter_pos = 0
  1717. while not inside_code:
  1718. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  1719. if iter_pos == -1:
  1720. break
  1721. post_text = f"{post_text[:iter_pos]}\\*{post_text[iter_pos + 1 :]}"
  1722. iter_pos += 2
  1723. iter_pos = 0
  1724. while not inside_code:
  1725. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  1726. if iter_pos == -1:
  1727. break
  1728. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  1729. post_text = f"{post_text[:iter_pos]}\\_{post_text[iter_pos + 1 :]}"
  1730. iter_pos += 2
  1731. else:
  1732. iter_pos += 1
  1733. text = pre_text + tag_text + post_text
  1734. pos = len(pre_text) + len(tag_text)
  1735. if tag_depth > 0:
  1736. print_error(
  1737. f"{state.current_class}.xml: Tag depth mismatch: too many (or too few) open/close tags in {context_name}.",
  1738. state,
  1739. )
  1740. return text
  1741. def format_context_name(context: Union[DefinitionBase, None]) -> str:
  1742. context_name: str = "unknown context"
  1743. if context is not None:
  1744. context_name = f'{context.definition_name} "{context.name}" description'
  1745. return context_name
  1746. def escape_rst(text: str, until_pos: int = -1) -> str:
  1747. # Escape \ character, otherwise it ends up as an escape character in rst
  1748. pos = 0
  1749. while True:
  1750. pos = text.find("\\", pos, until_pos)
  1751. if pos == -1:
  1752. break
  1753. text = f"{text[:pos]}\\\\{text[pos + 1 :]}"
  1754. pos += 2
  1755. # Escape * character to avoid interpreting it as emphasis
  1756. pos = 0
  1757. while True:
  1758. pos = text.find("*", pos, until_pos)
  1759. if pos == -1:
  1760. break
  1761. text = f"{text[:pos]}\\*{text[pos + 1 :]}"
  1762. pos += 2
  1763. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  1764. pos = 0
  1765. while True:
  1766. pos = text.find("_", pos, until_pos)
  1767. if pos == -1:
  1768. break
  1769. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  1770. text = f"{text[:pos]}\\_{text[pos + 1 :]}"
  1771. pos += 2
  1772. else:
  1773. pos += 1
  1774. return text
  1775. def format_codeblock(
  1776. tag_state: TagState, post_text: str, indent_level: int, state: State
  1777. ) -> Union[Tuple[str, int], None]:
  1778. end_pos = post_text.find("[/" + tag_state.name + "]")
  1779. if end_pos == -1:
  1780. print_error(
  1781. f"{state.current_class}.xml: Tag depth mismatch for [{tag_state.name}]: no closing [/{tag_state.name}].",
  1782. state,
  1783. )
  1784. return None
  1785. opening_formatted = tag_state.name
  1786. if len(tag_state.arguments) > 0:
  1787. opening_formatted += " " + " ".join(tag_state.arguments)
  1788. code_text = post_text[len(f"[{opening_formatted}]") : end_pos]
  1789. post_text = post_text[end_pos:]
  1790. # Remove extraneous tabs
  1791. code_pos = 0
  1792. while True:
  1793. code_pos = code_text.find("\n", code_pos)
  1794. if code_pos == -1:
  1795. break
  1796. to_skip = 0
  1797. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  1798. to_skip += 1
  1799. if to_skip > indent_level:
  1800. print_error(
  1801. f"{state.current_class}.xml: Four spaces should be used for indentation within [{tag_state.name}].",
  1802. state,
  1803. )
  1804. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  1805. code_text = f"{code_text[:code_pos]}\n"
  1806. code_pos += 1
  1807. else:
  1808. code_text = f"{code_text[:code_pos]}\n {code_text[code_pos + to_skip + 1 :]}"
  1809. code_pos += 5 - to_skip
  1810. return (f"\n[{opening_formatted}]{code_text}{post_text}", len(f"\n[{opening_formatted}]{code_text}"))
  1811. def format_table(f: TextIO, data: List[Tuple[Optional[str], ...]], remove_empty_columns: bool = False) -> None:
  1812. if len(data) == 0:
  1813. return
  1814. f.write(".. table::\n")
  1815. f.write(" :widths: auto\n\n")
  1816. # Calculate the width of each column first, we will use this information
  1817. # to properly format RST-style tables.
  1818. column_sizes = [0] * len(data[0])
  1819. for row in data:
  1820. for i, text in enumerate(row):
  1821. text_length = len(text or "")
  1822. if text_length > column_sizes[i]:
  1823. column_sizes[i] = text_length
  1824. # Each table row is wrapped in two separators, consecutive rows share the same separator.
  1825. # All separators, or rather borders, have the same shape and content. We compose it once,
  1826. # then reuse it.
  1827. sep = ""
  1828. for size in column_sizes:
  1829. if size == 0 and remove_empty_columns:
  1830. continue
  1831. sep += "+" + "-" * (size + 2) # Content of each cell is padded by 1 on each side.
  1832. sep += "+\n"
  1833. # Draw the first separator.
  1834. f.write(f" {sep}")
  1835. # Draw each row and close it with a separator.
  1836. for row in data:
  1837. row_text = "|"
  1838. for i, text in enumerate(row):
  1839. if column_sizes[i] == 0 and remove_empty_columns:
  1840. continue
  1841. row_text += f' {(text or "").ljust(column_sizes[i])} |'
  1842. row_text += "\n"
  1843. f.write(f" {row_text}")
  1844. f.write(f" {sep}")
  1845. f.write("\n")
  1846. def sanitize_operator_name(dirty_name: str, state: State) -> str:
  1847. clear_name = dirty_name.replace("operator ", "")
  1848. if clear_name == "!=":
  1849. clear_name = "neq"
  1850. elif clear_name == "==":
  1851. clear_name = "eq"
  1852. elif clear_name == "<":
  1853. clear_name = "lt"
  1854. elif clear_name == "<=":
  1855. clear_name = "lte"
  1856. elif clear_name == ">":
  1857. clear_name = "gt"
  1858. elif clear_name == ">=":
  1859. clear_name = "gte"
  1860. elif clear_name == "+":
  1861. clear_name = "sum"
  1862. elif clear_name == "-":
  1863. clear_name = "dif"
  1864. elif clear_name == "*":
  1865. clear_name = "mul"
  1866. elif clear_name == "/":
  1867. clear_name = "div"
  1868. elif clear_name == "%":
  1869. clear_name = "mod"
  1870. elif clear_name == "**":
  1871. clear_name = "pow"
  1872. elif clear_name == "unary+":
  1873. clear_name = "unplus"
  1874. elif clear_name == "unary-":
  1875. clear_name = "unminus"
  1876. elif clear_name == "<<":
  1877. clear_name = "bwsl"
  1878. elif clear_name == ">>":
  1879. clear_name = "bwsr"
  1880. elif clear_name == "&":
  1881. clear_name = "bwand"
  1882. elif clear_name == "|":
  1883. clear_name = "bwor"
  1884. elif clear_name == "^":
  1885. clear_name = "bwxor"
  1886. elif clear_name == "~":
  1887. clear_name = "bwnot"
  1888. elif clear_name == "[]":
  1889. clear_name = "idx"
  1890. else:
  1891. clear_name = "xxx"
  1892. print_error(f'Unsupported operator type "{dirty_name}", please add the missing rule.', state)
  1893. return clear_name
  1894. if __name__ == "__main__":
  1895. main()