2
0

make_rst.py 102 KB

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