make_rst.py 98 KB

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