make_rst.py 99 KB

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