make_rst.py 103 KB

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