make_rst.py 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624
  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, force_stderr_color, force_stdout_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. force_stdout_color(True)
  569. force_stderr_color(True)
  570. # Retrieve heading translations for the given language.
  571. if not args.dry_run and args.lang != "en":
  572. lang_file = os.path.join(
  573. os.path.dirname(os.path.realpath(__file__)), "..", "translations", "{}.po".format(args.lang)
  574. )
  575. if os.path.exists(lang_file):
  576. try:
  577. import polib # type: ignore
  578. except ImportError:
  579. print("Base template strings localization requires `polib`.")
  580. exit(1)
  581. pofile = polib.pofile(lang_file)
  582. for entry in pofile.translated_entries():
  583. if entry.msgid in BASE_STRINGS:
  584. strings_l10n[entry.msgid] = entry.msgstr
  585. else:
  586. print(f'No PO file at "{lang_file}" for language "{args.lang}".')
  587. print("Checking for errors in the XML class reference...")
  588. file_list: List[str] = []
  589. for path in args.path:
  590. # Cut off trailing slashes so os.path.basename doesn't choke.
  591. if path.endswith("/") or path.endswith("\\"):
  592. path = path[:-1]
  593. if os.path.basename(path) in ["modules", "platform"]:
  594. for subdir, dirs, _ in os.walk(path):
  595. if "doc_classes" in dirs:
  596. doc_dir = os.path.join(subdir, "doc_classes")
  597. class_file_names = (f for f in os.listdir(doc_dir) if f.endswith(".xml"))
  598. file_list += (os.path.join(doc_dir, f) for f in class_file_names)
  599. elif os.path.isdir(path):
  600. file_list += (os.path.join(path, f) for f in os.listdir(path) if f.endswith(".xml"))
  601. elif os.path.isfile(path):
  602. if not path.endswith(".xml"):
  603. print(f'Got non-.xml file "{path}" in input, skipping.')
  604. continue
  605. file_list.append(path)
  606. classes: Dict[str, Tuple[ET.Element, str]] = {}
  607. state = State()
  608. for cur_file in file_list:
  609. try:
  610. tree = ET.parse(cur_file)
  611. except ET.ParseError as e:
  612. print_error(f"{cur_file}: Parse error while reading the file: {e}", state)
  613. continue
  614. doc = tree.getroot()
  615. name = doc.attrib["name"]
  616. if name in classes:
  617. print_error(f'{cur_file}: Duplicate class "{name}".', state)
  618. continue
  619. classes[name] = (doc, cur_file)
  620. for name, data in classes.items():
  621. try:
  622. state.parse_class(data[0], data[1])
  623. except Exception as e:
  624. print_error(f"{name}.xml: Exception while parsing class: {e}", state)
  625. state.sort_classes()
  626. pattern = re.compile(args.filter)
  627. # Create the output folder recursively if it doesn't already exist.
  628. os.makedirs(args.output, exist_ok=True)
  629. print("Generating the RST class reference...")
  630. grouped_classes: Dict[str, List[str]] = {}
  631. for class_name, class_def in state.classes.items():
  632. if args.filter and not pattern.search(class_def.filepath):
  633. continue
  634. state.current_class = class_name
  635. class_def.update_class_group(state)
  636. make_rst_class(class_def, state, args.dry_run, args.output)
  637. if class_def.class_group not in grouped_classes:
  638. grouped_classes[class_def.class_group] = []
  639. grouped_classes[class_def.class_group].append(class_name)
  640. if class_def.editor_class:
  641. if "editor" not in grouped_classes:
  642. grouped_classes["editor"] = []
  643. grouped_classes["editor"].append(class_name)
  644. print("")
  645. print("Generating the index file...")
  646. make_rst_index(grouped_classes, args.dry_run, args.output)
  647. print("")
  648. # Print out checks.
  649. if state.script_language_parity_check.hit_count > 0:
  650. if not args.verbose:
  651. print(
  652. f"{Ansi.YELLOW}{state.script_language_parity_check.hit_count} code samples failed parity check. Use --verbose to get more information.{Ansi.RESET}"
  653. )
  654. else:
  655. print(
  656. f"{Ansi.YELLOW}{state.script_language_parity_check.hit_count} code samples failed parity check:{Ansi.RESET}"
  657. )
  658. for class_name in state.script_language_parity_check.hit_map.keys():
  659. class_hits = state.script_language_parity_check.hit_map[class_name]
  660. print(f'{Ansi.YELLOW}- {len(class_hits)} hits in class "{class_name}"{Ansi.RESET}')
  661. for context, error in class_hits:
  662. print(f" - {error} in {format_context_name(context)}")
  663. print("")
  664. # Print out warnings and errors, or lack thereof, and exit with an appropriate code.
  665. if state.num_warnings >= 2:
  666. print(
  667. f"{Ansi.YELLOW}{state.num_warnings} warnings were found in the class reference XML. Please check the messages above.{Ansi.RESET}"
  668. )
  669. elif state.num_warnings == 1:
  670. print(
  671. f"{Ansi.YELLOW}1 warning was found in the class reference XML. Please check the messages above.{Ansi.RESET}"
  672. )
  673. if state.num_errors >= 2:
  674. print(
  675. f"{Ansi.RED}{state.num_errors} errors were found in the class reference XML. Please check the messages above.{Ansi.RESET}"
  676. )
  677. elif state.num_errors == 1:
  678. print(f"{Ansi.RED}1 error was found in the class reference XML. Please check the messages above.{Ansi.RESET}")
  679. if state.num_warnings == 0 and state.num_errors == 0:
  680. print(f"{Ansi.GREEN}No warnings or errors found in the class reference XML.{Ansi.RESET}")
  681. if not args.dry_run:
  682. print(f"Wrote reStructuredText files for each class to: {args.output}")
  683. else:
  684. exit(1)
  685. # Common helpers.
  686. def print_error(error: str, state: State) -> None:
  687. print(f"{Ansi.RED}{Ansi.BOLD}ERROR:{Ansi.REGULAR} {error}{Ansi.RESET}")
  688. state.num_errors += 1
  689. def print_warning(warning: str, state: State) -> None:
  690. print(f"{Ansi.YELLOW}{Ansi.BOLD}WARNING:{Ansi.REGULAR} {warning}{Ansi.RESET}")
  691. state.num_warnings += 1
  692. def translate(string: str) -> str:
  693. """Translate a string based on translations sourced from `doc/translations/*.po`
  694. for a language if defined via the --lang command line argument.
  695. Returns the original string if no translation exists.
  696. """
  697. return strings_l10n.get(string, string)
  698. def get_git_branch() -> str:
  699. if hasattr(version, "docs") and version.docs != "latest":
  700. return version.docs
  701. return "master"
  702. # Generator methods.
  703. def make_rst_class(class_def: ClassDef, state: State, dry_run: bool, output_dir: str) -> None:
  704. class_name = class_def.name
  705. with open(
  706. os.devnull if dry_run else os.path.join(output_dir, f"class_{sanitize_class_name(class_name, True)}.rst"),
  707. "w",
  708. encoding="utf-8",
  709. newline="\n",
  710. ) as f:
  711. # Remove the "Edit on Github" button from the online docs page.
  712. f.write(":github_url: hide\n\n")
  713. # Add keywords metadata.
  714. if class_def.keywords is not None and class_def.keywords != "":
  715. f.write(f".. meta::\n\t:keywords: {class_def.keywords}\n\n")
  716. # Warn contributors not to edit this file directly.
  717. # Also provide links to the source files for reference.
  718. git_branch = get_git_branch()
  719. source_xml_path = os.path.relpath(class_def.filepath, root_directory).replace("\\", "/")
  720. source_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/{source_xml_path}"
  721. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  722. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  723. f.write(".. Generated automatically from Godot engine sources.\n")
  724. f.write(f".. Generator: {generator_github_url}.\n")
  725. f.write(f".. XML source: {source_github_url}.\n\n")
  726. # Document reference id and header.
  727. f.write(f".. _class_{sanitize_class_name(class_name)}:\n\n")
  728. f.write(make_heading(class_name, "=", False))
  729. f.write(make_deprecated_experimental(class_def, state))
  730. ### INHERITANCE TREE ###
  731. # Ascendants
  732. if class_def.inherits:
  733. inherits = class_def.inherits.strip()
  734. f.write(f"**{translate('Inherits:')}** ")
  735. first = True
  736. while inherits is not None:
  737. if not first:
  738. f.write(" **<** ")
  739. else:
  740. first = False
  741. f.write(make_type(inherits, state))
  742. if inherits not in state.classes:
  743. break # Parent unknown.
  744. inode = state.classes[inherits].inherits
  745. if inode:
  746. inherits = inode.strip()
  747. else:
  748. break
  749. f.write("\n\n")
  750. # Descendants
  751. inherited: List[str] = []
  752. for c in state.classes.values():
  753. if c.inherits and c.inherits.strip() == class_name:
  754. inherited.append(c.name)
  755. if len(inherited):
  756. f.write(f"**{translate('Inherited By:')}** ")
  757. for i, child in enumerate(inherited):
  758. if i > 0:
  759. f.write(", ")
  760. f.write(make_type(child, state))
  761. f.write("\n\n")
  762. ### INTRODUCTION ###
  763. has_description = False
  764. # Brief description
  765. if class_def.brief_description is not None and class_def.brief_description.strip() != "":
  766. has_description = True
  767. f.write(f"{format_text_block(class_def.brief_description.strip(), class_def, state)}\n\n")
  768. # Class description
  769. if class_def.description is not None and class_def.description.strip() != "":
  770. has_description = True
  771. f.write(".. rst-class:: classref-introduction-group\n\n")
  772. f.write(make_heading("Description", "-"))
  773. f.write(f"{format_text_block(class_def.description.strip(), class_def, state)}\n\n")
  774. if not has_description:
  775. f.write(".. container:: contribute\n\n\t")
  776. f.write(
  777. translate(
  778. "There is currently no description for this class. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  779. )
  780. + "\n\n"
  781. )
  782. if class_def.name in CLASSES_WITH_CSHARP_DIFFERENCES:
  783. f.write(".. note::\n\n\t")
  784. f.write(
  785. translate(
  786. "There are notable differences when using this API with C#. See :ref:`doc_c_sharp_differences` for more information."
  787. )
  788. + "\n\n"
  789. )
  790. # Online tutorials
  791. if len(class_def.tutorials) > 0:
  792. f.write(".. rst-class:: classref-introduction-group\n\n")
  793. f.write(make_heading("Tutorials", "-"))
  794. for url, title in class_def.tutorials:
  795. f.write(f"- {make_link(url, title)}\n\n")
  796. ### REFERENCE TABLES ###
  797. # Reused container for reference tables.
  798. ml: List[Tuple[Optional[str], ...]] = []
  799. # Properties reference table
  800. if len(class_def.properties) > 0:
  801. f.write(".. rst-class:: classref-reftable-group\n\n")
  802. f.write(make_heading("Properties", "-"))
  803. ml = []
  804. for property_def in class_def.properties.values():
  805. type_rst = property_def.type_name.to_rst(state)
  806. default = property_def.default_value
  807. if default is not None and property_def.overrides:
  808. ref = f":ref:`{property_def.overrides}<class_{sanitize_class_name(property_def.overrides)}_property_{property_def.name}>`"
  809. # Not using translate() for now as it breaks table formatting.
  810. ml.append((type_rst, property_def.name, f"{default} (overrides {ref})"))
  811. else:
  812. ref = f":ref:`{property_def.name}<class_{sanitize_class_name(class_name)}_property_{property_def.name}>`"
  813. ml.append((type_rst, ref, default))
  814. format_table(f, ml, True)
  815. # Constructors, Methods, Operators reference tables
  816. if len(class_def.constructors) > 0:
  817. f.write(".. rst-class:: classref-reftable-group\n\n")
  818. f.write(make_heading("Constructors", "-"))
  819. ml = []
  820. for method_list in class_def.constructors.values():
  821. for m in method_list:
  822. ml.append(make_method_signature(class_def, m, "constructor", state))
  823. format_table(f, ml)
  824. if len(class_def.methods) > 0:
  825. f.write(".. rst-class:: classref-reftable-group\n\n")
  826. f.write(make_heading("Methods", "-"))
  827. ml = []
  828. for method_list in class_def.methods.values():
  829. for m in method_list:
  830. ml.append(make_method_signature(class_def, m, "method", state))
  831. format_table(f, ml)
  832. if len(class_def.operators) > 0:
  833. f.write(".. rst-class:: classref-reftable-group\n\n")
  834. f.write(make_heading("Operators", "-"))
  835. ml = []
  836. for method_list in class_def.operators.values():
  837. for m in method_list:
  838. ml.append(make_method_signature(class_def, m, "operator", state))
  839. format_table(f, ml)
  840. # Theme properties reference table
  841. if len(class_def.theme_items) > 0:
  842. f.write(".. rst-class:: classref-reftable-group\n\n")
  843. f.write(make_heading("Theme Properties", "-"))
  844. ml = []
  845. for theme_item_def in class_def.theme_items.values():
  846. ref = f":ref:`{theme_item_def.name}<class_{sanitize_class_name(class_name)}_theme_{theme_item_def.data_name}_{theme_item_def.name}>`"
  847. ml.append((theme_item_def.type_name.to_rst(state), ref, theme_item_def.default_value))
  848. format_table(f, ml, True)
  849. ### DETAILED DESCRIPTIONS ###
  850. # Signal descriptions
  851. if len(class_def.signals) > 0:
  852. f.write(make_separator(True))
  853. f.write(".. rst-class:: classref-descriptions-group\n\n")
  854. f.write(make_heading("Signals", "-"))
  855. index = 0
  856. for signal in class_def.signals.values():
  857. if index != 0:
  858. f.write(make_separator())
  859. # Create signal signature and anchor point.
  860. signal_anchor = f"class_{sanitize_class_name(class_name)}_signal_{signal.name}"
  861. f.write(f".. _{signal_anchor}:\n\n")
  862. self_link = f":ref:`🔗<{signal_anchor}>`"
  863. f.write(".. rst-class:: classref-signal\n\n")
  864. _, signature = make_method_signature(class_def, signal, "", state)
  865. f.write(f"{signature} {self_link}\n\n")
  866. # Add signal description, or a call to action if it's missing.
  867. f.write(make_deprecated_experimental(signal, state))
  868. if signal.description is not None and signal.description.strip() != "":
  869. f.write(f"{format_text_block(signal.description.strip(), signal, state)}\n\n")
  870. elif signal.deprecated is None and signal.experimental is None:
  871. f.write(".. container:: contribute\n\n\t")
  872. f.write(
  873. translate(
  874. "There is currently no description for this signal. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  875. )
  876. + "\n\n"
  877. )
  878. index += 1
  879. # Enumeration descriptions
  880. if len(class_def.enums) > 0:
  881. f.write(make_separator(True))
  882. f.write(".. rst-class:: classref-descriptions-group\n\n")
  883. f.write(make_heading("Enumerations", "-"))
  884. index = 0
  885. for e in class_def.enums.values():
  886. if index != 0:
  887. f.write(make_separator())
  888. # Create enumeration signature and anchor point.
  889. enum_anchor = f"enum_{sanitize_class_name(class_name)}_{e.name}"
  890. f.write(f".. _{enum_anchor}:\n\n")
  891. self_link = f":ref:`🔗<{enum_anchor}>`"
  892. f.write(".. rst-class:: classref-enumeration\n\n")
  893. if e.is_bitfield:
  894. f.write(f"flags **{e.name}**: {self_link}\n\n")
  895. else:
  896. f.write(f"enum **{e.name}**: {self_link}\n\n")
  897. for value in e.values.values():
  898. # Also create signature and anchor point for each enum constant.
  899. f.write(f".. _class_{sanitize_class_name(class_name)}_constant_{value.name}:\n\n")
  900. f.write(".. rst-class:: classref-enumeration-constant\n\n")
  901. f.write(f"{e.type_name.to_rst(state)} **{value.name}** = ``{value.value}``\n\n")
  902. # Add enum constant description.
  903. f.write(make_deprecated_experimental(value, state))
  904. if value.text is not None and value.text.strip() != "":
  905. f.write(f"{format_text_block(value.text.strip(), value, state)}")
  906. elif value.deprecated is None and value.experimental is None:
  907. f.write(".. container:: contribute\n\n\t")
  908. f.write(
  909. translate(
  910. "There is currently no description for this enum. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  911. )
  912. + "\n\n"
  913. )
  914. f.write("\n\n")
  915. index += 1
  916. # Constant descriptions
  917. if len(class_def.constants) > 0:
  918. f.write(make_separator(True))
  919. f.write(".. rst-class:: classref-descriptions-group\n\n")
  920. f.write(make_heading("Constants", "-"))
  921. for constant in class_def.constants.values():
  922. # Create constant signature and anchor point.
  923. constant_anchor = f"class_{sanitize_class_name(class_name)}_constant_{constant.name}"
  924. f.write(f".. _{constant_anchor}:\n\n")
  925. self_link = f":ref:`🔗<{constant_anchor}>`"
  926. f.write(".. rst-class:: classref-constant\n\n")
  927. f.write(f"**{constant.name}** = ``{constant.value}`` {self_link}\n\n")
  928. # Add constant description.
  929. f.write(make_deprecated_experimental(constant, state))
  930. if constant.text is not None and constant.text.strip() != "":
  931. f.write(f"{format_text_block(constant.text.strip(), constant, state)}")
  932. elif constant.deprecated is None and constant.experimental is None:
  933. f.write(".. container:: contribute\n\n\t")
  934. f.write(
  935. translate(
  936. "There is currently no description for this constant. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  937. )
  938. + "\n\n"
  939. )
  940. f.write("\n\n")
  941. # Annotation descriptions
  942. if len(class_def.annotations) > 0:
  943. f.write(make_separator(True))
  944. f.write(make_heading("Annotations", "-"))
  945. index = 0
  946. for method_list in class_def.annotations.values(): # type: ignore
  947. for i, m in enumerate(method_list):
  948. if index != 0:
  949. f.write(make_separator())
  950. # Create annotation signature and anchor point.
  951. self_link = ""
  952. if i == 0:
  953. annotation_anchor = f"class_{sanitize_class_name(class_name)}_annotation_{m.name}"
  954. f.write(f".. _{annotation_anchor}:\n\n")
  955. self_link = f" :ref:`🔗<{annotation_anchor}>`"
  956. f.write(".. rst-class:: classref-annotation\n\n")
  957. _, signature = make_method_signature(class_def, m, "", state)
  958. f.write(f"{signature}{self_link}\n\n")
  959. # Add annotation description, or a call to action if it's missing.
  960. if m.description is not None and m.description.strip() != "":
  961. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  962. else:
  963. f.write(".. container:: contribute\n\n\t")
  964. f.write(
  965. translate(
  966. "There is currently no description for this annotation. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  967. )
  968. + "\n\n"
  969. )
  970. index += 1
  971. # Property descriptions
  972. if any(not p.overrides for p in class_def.properties.values()) > 0:
  973. f.write(make_separator(True))
  974. f.write(".. rst-class:: classref-descriptions-group\n\n")
  975. f.write(make_heading("Property Descriptions", "-"))
  976. index = 0
  977. for property_def in class_def.properties.values():
  978. if property_def.overrides:
  979. continue
  980. if index != 0:
  981. f.write(make_separator())
  982. # Create property signature and anchor point.
  983. property_anchor = f"class_{sanitize_class_name(class_name)}_property_{property_def.name}"
  984. f.write(f".. _{property_anchor}:\n\n")
  985. self_link = f":ref:`🔗<{property_anchor}>`"
  986. f.write(".. rst-class:: classref-property\n\n")
  987. property_default = ""
  988. if property_def.default_value is not None:
  989. property_default = f" = {property_def.default_value}"
  990. f.write(
  991. f"{property_def.type_name.to_rst(state)} **{property_def.name}**{property_default} {self_link}\n\n"
  992. )
  993. # Create property setter and getter records.
  994. property_setget = ""
  995. if property_def.setter is not None and not property_def.setter.startswith("_"):
  996. property_setter = make_setter_signature(class_def, property_def, state)
  997. property_setget += f"- {property_setter}\n"
  998. if property_def.getter is not None and not property_def.getter.startswith("_"):
  999. property_getter = make_getter_signature(class_def, property_def, state)
  1000. property_setget += f"- {property_getter}\n"
  1001. if property_setget != "":
  1002. f.write(".. rst-class:: classref-property-setget\n\n")
  1003. f.write(property_setget)
  1004. f.write("\n")
  1005. # Add property description, or a call to action if it's missing.
  1006. f.write(make_deprecated_experimental(property_def, state))
  1007. if property_def.text is not None and property_def.text.strip() != "":
  1008. f.write(f"{format_text_block(property_def.text.strip(), property_def, state)}\n\n")
  1009. elif property_def.deprecated is None and property_def.experimental is None:
  1010. f.write(".. container:: contribute\n\n\t")
  1011. f.write(
  1012. translate(
  1013. "There is currently no description for this property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  1014. )
  1015. + "\n\n"
  1016. )
  1017. # Add copy note to built-in properties returning `Packed*Array`.
  1018. if property_def.type_name.type_name in PACKED_ARRAY_TYPES:
  1019. 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."
  1020. f.write(f"{format_text_block(copy_note, property_def, state)}\n\n")
  1021. index += 1
  1022. # Constructor, Method, Operator descriptions
  1023. if len(class_def.constructors) > 0:
  1024. f.write(make_separator(True))
  1025. f.write(".. rst-class:: classref-descriptions-group\n\n")
  1026. f.write(make_heading("Constructor Descriptions", "-"))
  1027. index = 0
  1028. for method_list in class_def.constructors.values():
  1029. for i, m in enumerate(method_list):
  1030. if index != 0:
  1031. f.write(make_separator())
  1032. # Create constructor signature and anchor point.
  1033. self_link = ""
  1034. if i == 0:
  1035. constructor_anchor = f"class_{sanitize_class_name(class_name)}_constructor_{m.name}"
  1036. f.write(f".. _{constructor_anchor}:\n\n")
  1037. self_link = f" :ref:`🔗<{constructor_anchor}>`"
  1038. f.write(".. rst-class:: classref-constructor\n\n")
  1039. ret_type, signature = make_method_signature(class_def, m, "", state)
  1040. f.write(f"{ret_type} {signature}{self_link}\n\n")
  1041. # Add constructor description, or a call to action if it's missing.
  1042. f.write(make_deprecated_experimental(m, state))
  1043. if m.description is not None and m.description.strip() != "":
  1044. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  1045. elif m.deprecated is None and m.experimental is None:
  1046. f.write(".. container:: contribute\n\n\t")
  1047. f.write(
  1048. translate(
  1049. "There is currently no description for this constructor. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  1050. )
  1051. + "\n\n"
  1052. )
  1053. index += 1
  1054. if len(class_def.methods) > 0:
  1055. f.write(make_separator(True))
  1056. f.write(".. rst-class:: classref-descriptions-group\n\n")
  1057. f.write(make_heading("Method Descriptions", "-"))
  1058. index = 0
  1059. for method_list in class_def.methods.values():
  1060. for i, m in enumerate(method_list):
  1061. if index != 0:
  1062. f.write(make_separator())
  1063. # Create method signature and anchor point.
  1064. self_link = ""
  1065. if i == 0:
  1066. method_qualifier = ""
  1067. if m.name.startswith("_"):
  1068. method_qualifier = "private_"
  1069. method_anchor = f"class_{sanitize_class_name(class_name)}_{method_qualifier}method_{m.name}"
  1070. f.write(f".. _{method_anchor}:\n\n")
  1071. self_link = f" :ref:`🔗<{method_anchor}>`"
  1072. f.write(".. rst-class:: classref-method\n\n")
  1073. ret_type, signature = make_method_signature(class_def, m, "", state)
  1074. f.write(f"{ret_type} {signature}{self_link}\n\n")
  1075. # Add method description, or a call to action if it's missing.
  1076. f.write(make_deprecated_experimental(m, state))
  1077. if m.description is not None and m.description.strip() != "":
  1078. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  1079. elif m.deprecated is None and m.experimental is None:
  1080. f.write(".. container:: contribute\n\n\t")
  1081. f.write(
  1082. translate(
  1083. "There is currently no description for this method. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  1084. )
  1085. + "\n\n"
  1086. )
  1087. index += 1
  1088. if len(class_def.operators) > 0:
  1089. f.write(make_separator(True))
  1090. f.write(".. rst-class:: classref-descriptions-group\n\n")
  1091. f.write(make_heading("Operator Descriptions", "-"))
  1092. index = 0
  1093. for method_list in class_def.operators.values():
  1094. for i, m in enumerate(method_list):
  1095. if index != 0:
  1096. f.write(make_separator())
  1097. # Create operator signature and anchor point.
  1098. operator_anchor = (
  1099. f"class_{sanitize_class_name(class_name)}_operator_{sanitize_operator_name(m.name, state)}"
  1100. )
  1101. for parameter in m.parameters:
  1102. operator_anchor += f"_{parameter.type_name.type_name}"
  1103. f.write(f".. _{operator_anchor}:\n\n")
  1104. self_link = f":ref:`🔗<{operator_anchor}>`"
  1105. f.write(".. rst-class:: classref-operator\n\n")
  1106. ret_type, signature = make_method_signature(class_def, m, "", state)
  1107. f.write(f"{ret_type} {signature} {self_link}\n\n")
  1108. # Add operator description, or a call to action if it's missing.
  1109. f.write(make_deprecated_experimental(m, state))
  1110. if m.description is not None and m.description.strip() != "":
  1111. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  1112. elif m.deprecated is None and m.experimental is None:
  1113. f.write(".. container:: contribute\n\n\t")
  1114. f.write(
  1115. translate(
  1116. "There is currently no description for this operator. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  1117. )
  1118. + "\n\n"
  1119. )
  1120. index += 1
  1121. # Theme property descriptions
  1122. if len(class_def.theme_items) > 0:
  1123. f.write(make_separator(True))
  1124. f.write(".. rst-class:: classref-descriptions-group\n\n")
  1125. f.write(make_heading("Theme Property Descriptions", "-"))
  1126. index = 0
  1127. for theme_item_def in class_def.theme_items.values():
  1128. if index != 0:
  1129. f.write(make_separator())
  1130. # Create theme property signature and anchor point.
  1131. theme_item_anchor = (
  1132. f"class_{sanitize_class_name(class_name)}_theme_{theme_item_def.data_name}_{theme_item_def.name}"
  1133. )
  1134. f.write(f".. _{theme_item_anchor}:\n\n")
  1135. self_link = f":ref:`🔗<{theme_item_anchor}>`"
  1136. f.write(".. rst-class:: classref-themeproperty\n\n")
  1137. theme_item_default = ""
  1138. if theme_item_def.default_value is not None:
  1139. theme_item_default = f" = {theme_item_def.default_value}"
  1140. f.write(
  1141. f"{theme_item_def.type_name.to_rst(state)} **{theme_item_def.name}**{theme_item_default} {self_link}\n\n"
  1142. )
  1143. # Add theme property description, or a call to action if it's missing.
  1144. f.write(make_deprecated_experimental(theme_item_def, state))
  1145. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  1146. f.write(f"{format_text_block(theme_item_def.text.strip(), theme_item_def, state)}\n\n")
  1147. elif theme_item_def.deprecated is None and theme_item_def.experimental is None:
  1148. f.write(".. container:: contribute\n\n\t")
  1149. f.write(
  1150. translate(
  1151. "There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  1152. )
  1153. + "\n\n"
  1154. )
  1155. index += 1
  1156. f.write(make_footer())
  1157. def make_type(klass: str, state: State) -> str:
  1158. if klass.find("*") != -1: # Pointer, ignore
  1159. return f"``{klass}``"
  1160. def resolve_type(link_type: str) -> str:
  1161. if link_type in state.classes:
  1162. return f":ref:`{link_type}<class_{sanitize_class_name(link_type)}>`"
  1163. else:
  1164. print_error(f'{state.current_class}.xml: Unresolved type "{link_type}".', state)
  1165. return f"``{link_type}``"
  1166. if klass.endswith("[]"): # Typed array, strip [] to link to contained type.
  1167. return f":ref:`Array<class_Array>`\\[{resolve_type(klass[: -len('[]')])}\\]"
  1168. if klass.startswith("Dictionary["): # Typed dictionary, split elements to link contained types.
  1169. parts = klass[len("Dictionary[") : -len("]")].partition(", ")
  1170. key = parts[0]
  1171. value = parts[2]
  1172. return f":ref:`Dictionary<class_Dictionary>`\\[{resolve_type(key)}, {resolve_type(value)}\\]"
  1173. return resolve_type(klass)
  1174. def make_enum(t: str, is_bitfield: bool, state: State) -> str:
  1175. p = t.rfind(".")
  1176. if p >= 0:
  1177. c = t[0:p]
  1178. e = t[p + 1 :]
  1179. # Variant enums live in GlobalScope but still use periods.
  1180. if c == "Variant":
  1181. c = "@GlobalScope"
  1182. e = "Variant." + e
  1183. else:
  1184. c = state.current_class
  1185. e = t
  1186. if c in state.classes and e not in state.classes[c].enums:
  1187. c = "@GlobalScope"
  1188. if c in state.classes and e in state.classes[c].enums:
  1189. if is_bitfield:
  1190. if not state.classes[c].enums[e].is_bitfield:
  1191. print_error(f'{state.current_class}.xml: Enum "{t}" is not bitfield.', state)
  1192. return f"|bitfield|\\[:ref:`{e}<enum_{sanitize_class_name(c)}_{e}>`\\]"
  1193. else:
  1194. return f":ref:`{e}<enum_{sanitize_class_name(c)}_{e}>`"
  1195. print_error(f'{state.current_class}.xml: Unresolved enum "{t}".', state)
  1196. return t
  1197. def make_method_signature(
  1198. class_def: ClassDef, definition: Union[AnnotationDef, MethodDef, SignalDef], ref_type: str, state: State
  1199. ) -> Tuple[str, str]:
  1200. ret_type = ""
  1201. if isinstance(definition, MethodDef):
  1202. ret_type = definition.return_type.to_rst(state)
  1203. qualifiers = None
  1204. if isinstance(definition, (MethodDef, AnnotationDef)):
  1205. qualifiers = definition.qualifiers
  1206. out = ""
  1207. if isinstance(definition, MethodDef) and ref_type != "":
  1208. if ref_type == "operator":
  1209. op_name = definition.name.replace("<", "\\<") # So operator "<" gets correctly displayed.
  1210. out += f":ref:`{op_name}<class_{sanitize_class_name(class_def.name)}_{ref_type}_{sanitize_operator_name(definition.name, state)}"
  1211. for parameter in definition.parameters:
  1212. out += f"_{parameter.type_name.type_name}"
  1213. out += ">`"
  1214. elif ref_type == "method":
  1215. ref_type_qualifier = ""
  1216. if definition.name.startswith("_"):
  1217. ref_type_qualifier = "private_"
  1218. out += f":ref:`{definition.name}<class_{sanitize_class_name(class_def.name)}_{ref_type_qualifier}{ref_type}_{definition.name}>`"
  1219. else:
  1220. out += f":ref:`{definition.name}<class_{sanitize_class_name(class_def.name)}_{ref_type}_{definition.name}>`"
  1221. else:
  1222. out += f"**{definition.name}**"
  1223. out += "\\ ("
  1224. for i, arg in enumerate(definition.parameters):
  1225. if i > 0:
  1226. out += ", "
  1227. else:
  1228. out += "\\ "
  1229. out += f"{arg.name}\\: {arg.type_name.to_rst(state)}"
  1230. if arg.default_value is not None:
  1231. out += f" = {arg.default_value}"
  1232. if qualifiers is not None and "vararg" in qualifiers:
  1233. if len(definition.parameters) > 0:
  1234. out += ", ..."
  1235. else:
  1236. out += "\\ ..."
  1237. out += "\\ )"
  1238. if qualifiers is not None:
  1239. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  1240. # See `make_footer()` for descriptions.
  1241. for qualifier in qualifiers.split():
  1242. out += f" |{qualifier}|"
  1243. return ret_type, out
  1244. def make_setter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  1245. if property_def.setter is None:
  1246. return ""
  1247. # If setter is a method available as a method definition, we use that.
  1248. if property_def.setter in class_def.methods:
  1249. setter = class_def.methods[property_def.setter][0]
  1250. # Otherwise we fake it with the information we have available.
  1251. else:
  1252. setter_params: List[ParameterDef] = []
  1253. setter_params.append(ParameterDef("value", property_def.type_name, None))
  1254. setter = MethodDef(property_def.setter, TypeName("void"), setter_params, None, None)
  1255. ret_type, signature = make_method_signature(class_def, setter, "", state)
  1256. return f"{ret_type} {signature}"
  1257. def make_getter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  1258. if property_def.getter is None:
  1259. return ""
  1260. # If getter is a method available as a method definition, we use that.
  1261. if property_def.getter in class_def.methods:
  1262. getter = class_def.methods[property_def.getter][0]
  1263. # Otherwise we fake it with the information we have available.
  1264. else:
  1265. getter_params: List[ParameterDef] = []
  1266. getter = MethodDef(property_def.getter, property_def.type_name, getter_params, None, None)
  1267. ret_type, signature = make_method_signature(class_def, getter, "", state)
  1268. return f"{ret_type} {signature}"
  1269. def make_deprecated_experimental(item: DefinitionBase, state: State) -> str:
  1270. result = ""
  1271. if item.deprecated is not None:
  1272. deprecated_prefix = translate("Deprecated:")
  1273. if item.deprecated.strip() == "":
  1274. default_message = translate(f"This {item.definition_name} may be changed or removed in future versions.")
  1275. result += f"**{deprecated_prefix}** {default_message}\n\n"
  1276. else:
  1277. result += f"**{deprecated_prefix}** {format_text_block(item.deprecated.strip(), item, state)}\n\n"
  1278. if item.experimental is not None:
  1279. experimental_prefix = translate("Experimental:")
  1280. if item.experimental.strip() == "":
  1281. default_message = translate(f"This {item.definition_name} may be changed or removed in future versions.")
  1282. result += f"**{experimental_prefix}** {default_message}\n\n"
  1283. else:
  1284. result += f"**{experimental_prefix}** {format_text_block(item.experimental.strip(), item, state)}\n\n"
  1285. return result
  1286. def make_heading(title: str, underline: str, l10n: bool = True) -> str:
  1287. if l10n:
  1288. new_title = translate(title)
  1289. if new_title != title:
  1290. title = new_title
  1291. underline *= 2 # Double length to handle wide chars.
  1292. return f"{title}\n{(underline * len(title))}\n\n"
  1293. def make_footer() -> str:
  1294. # Generate reusable abbreviation substitutions.
  1295. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  1296. virtual_msg = translate("This method should typically be overridden by the user to have any effect.")
  1297. const_msg = translate("This method has no side effects. It doesn't modify any of the instance's member variables.")
  1298. vararg_msg = translate("This method accepts any number of arguments after the ones described here.")
  1299. constructor_msg = translate("This method is used to construct a type.")
  1300. static_msg = translate(
  1301. "This method doesn't need an instance to be called, so it can be called directly using the class name."
  1302. )
  1303. operator_msg = translate("This method describes a valid operator to use with this type as left-hand operand.")
  1304. bitfield_msg = translate("This value is an integer composed as a bitmask of the following flags.")
  1305. void_msg = translate("No return value.")
  1306. return (
  1307. f".. |virtual| replace:: :abbr:`virtual ({virtual_msg})`\n"
  1308. f".. |const| replace:: :abbr:`const ({const_msg})`\n"
  1309. f".. |vararg| replace:: :abbr:`vararg ({vararg_msg})`\n"
  1310. f".. |constructor| replace:: :abbr:`constructor ({constructor_msg})`\n"
  1311. f".. |static| replace:: :abbr:`static ({static_msg})`\n"
  1312. f".. |operator| replace:: :abbr:`operator ({operator_msg})`\n"
  1313. f".. |bitfield| replace:: :abbr:`BitField ({bitfield_msg})`\n"
  1314. f".. |void| replace:: :abbr:`void ({void_msg})`\n"
  1315. )
  1316. def make_separator(section_level: bool = False) -> str:
  1317. separator_class = "item"
  1318. if section_level:
  1319. separator_class = "section"
  1320. return f".. rst-class:: classref-{separator_class}-separator\n\n----\n\n"
  1321. def make_link(url: str, title: str) -> str:
  1322. match = GODOT_DOCS_PATTERN.search(url)
  1323. if match:
  1324. groups = match.groups()
  1325. if match.lastindex == 2:
  1326. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  1327. # `#calling-javascript-from-script in Exporting For Web`
  1328. # Or use the title if provided.
  1329. if title != "":
  1330. return f"`{title} <../{groups[0]}.html{groups[1]}>`__"
  1331. return f"`{groups[1]} <../{groups[0]}.html{groups[1]}>`__ in :doc:`../{groups[0]}`"
  1332. elif match.lastindex == 1:
  1333. # Doc reference, for example:
  1334. # `Math`
  1335. if title != "":
  1336. return f":doc:`{title} <../{groups[0]}>`"
  1337. return f":doc:`../{groups[0]}`"
  1338. # External link, for example:
  1339. # `http://enet.bespin.org/usergroup0.html`
  1340. if title != "":
  1341. return f"`{title} <{url}>`__"
  1342. return f"`{url} <{url}>`__"
  1343. def make_rst_index(grouped_classes: Dict[str, List[str]], dry_run: bool, output_dir: str) -> None:
  1344. with open(
  1345. os.devnull if dry_run else os.path.join(output_dir, "index.rst"), "w", encoding="utf-8", newline="\n"
  1346. ) as f:
  1347. # Remove the "Edit on Github" button from the online docs page, and disallow user-contributed notes
  1348. # on the index page. User-contributed notes are allowed on individual class pages.
  1349. f.write(":github_url: hide\n:allow_comments: False\n\n")
  1350. # Warn contributors not to edit this file directly.
  1351. # Also provide links to the source files for reference.
  1352. git_branch = get_git_branch()
  1353. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  1354. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  1355. f.write(".. Generated automatically from Godot engine sources.\n")
  1356. f.write(f".. Generator: {generator_github_url}.\n\n")
  1357. f.write(".. _doc_class_reference:\n\n")
  1358. f.write(make_heading("All classes", "="))
  1359. for group_name in CLASS_GROUPS:
  1360. if group_name in grouped_classes:
  1361. f.write(make_heading(CLASS_GROUPS[group_name], "="))
  1362. f.write(".. toctree::\n")
  1363. f.write(" :maxdepth: 1\n")
  1364. f.write(f" :name: toc-class-ref-{group_name}s\n")
  1365. f.write("\n")
  1366. if group_name in CLASS_GROUPS_BASE:
  1367. f.write(f" class_{sanitize_class_name(CLASS_GROUPS_BASE[group_name], True)}\n")
  1368. for class_name in grouped_classes[group_name]:
  1369. if group_name in CLASS_GROUPS_BASE and sanitize_class_name(
  1370. CLASS_GROUPS_BASE[group_name], True
  1371. ) == sanitize_class_name(class_name, True):
  1372. continue
  1373. f.write(f" class_{sanitize_class_name(class_name, True)}\n")
  1374. f.write("\n")
  1375. # Formatting helpers.
  1376. RESERVED_FORMATTING_TAGS = ["i", "b", "u", "lb", "rb", "code", "kbd", "center", "url", "br"]
  1377. RESERVED_LAYOUT_TAGS = ["codeblocks"]
  1378. RESERVED_CODEBLOCK_TAGS = ["codeblock", "gdscript", "csharp"]
  1379. RESERVED_CROSSLINK_TAGS = [
  1380. "method",
  1381. "constructor",
  1382. "operator",
  1383. "member",
  1384. "signal",
  1385. "constant",
  1386. "enum",
  1387. "annotation",
  1388. "theme_item",
  1389. "param",
  1390. ]
  1391. def is_in_tagset(tag_text: str, tagset: List[str]) -> bool:
  1392. for tag in tagset:
  1393. # Complete match.
  1394. if tag_text == tag:
  1395. return True
  1396. # Tag with arguments.
  1397. if tag_text.startswith(tag + " "):
  1398. return True
  1399. # Tag with arguments, special case for [url], [color], and [font].
  1400. if tag_text.startswith(tag + "="):
  1401. return True
  1402. return False
  1403. def get_tag_and_args(tag_text: str) -> TagState:
  1404. tag_name = tag_text
  1405. arguments: str = ""
  1406. delim_pos = -1
  1407. space_pos = tag_text.find(" ")
  1408. if space_pos >= 0:
  1409. delim_pos = space_pos
  1410. # Special case for [url], [color], and [font].
  1411. assign_pos = tag_text.find("=")
  1412. if assign_pos >= 0 and (delim_pos < 0 or assign_pos < delim_pos):
  1413. delim_pos = assign_pos
  1414. if delim_pos >= 0:
  1415. tag_name = tag_text[:delim_pos]
  1416. arguments = tag_text[delim_pos + 1 :].strip()
  1417. closing = False
  1418. if tag_name.startswith("/"):
  1419. tag_name = tag_name[1:]
  1420. closing = True
  1421. return TagState(tag_text, tag_name, arguments, closing)
  1422. def parse_link_target(link_target: str, state: State, context_name: str) -> List[str]:
  1423. if link_target.find(".") != -1:
  1424. return link_target.split(".")
  1425. else:
  1426. return [state.current_class, link_target]
  1427. def format_text_block(
  1428. text: str,
  1429. context: DefinitionBase,
  1430. state: State,
  1431. ) -> str:
  1432. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  1433. pos = 0
  1434. while True:
  1435. pos = text.find("\n", pos)
  1436. if pos == -1:
  1437. break
  1438. pre_text = text[:pos]
  1439. indent_level = 0
  1440. while pos + 1 < len(text) and text[pos + 1] == "\t":
  1441. pos += 1
  1442. indent_level += 1
  1443. post_text = text[pos + 1 :]
  1444. # Handle codeblocks
  1445. if (
  1446. post_text.startswith("[codeblock]")
  1447. or post_text.startswith("[codeblock ")
  1448. or post_text.startswith("[gdscript]")
  1449. or post_text.startswith("[gdscript ")
  1450. or post_text.startswith("[csharp]")
  1451. or post_text.startswith("[csharp ")
  1452. ):
  1453. tag_text = post_text[1:].split("]", 1)[0]
  1454. tag_state = get_tag_and_args(tag_text)
  1455. result = format_codeblock(tag_state, post_text, indent_level, state)
  1456. if result is None:
  1457. return ""
  1458. text = f"{pre_text}{result[0]}"
  1459. pos += result[1] - indent_level
  1460. # Handle normal text
  1461. else:
  1462. text = f"{pre_text}\n\n{post_text}"
  1463. pos += 2 - indent_level
  1464. next_brac_pos = text.find("[")
  1465. text = escape_rst(text, next_brac_pos)
  1466. context_name = format_context_name(context)
  1467. # Handle [tags]
  1468. inside_code = False
  1469. inside_code_tag = ""
  1470. inside_code_tabs = False
  1471. ignore_code_warnings = False
  1472. code_warning_if_intended_string = "If this is intended, use [code skip-lint]...[/code]."
  1473. has_codeblocks_gdscript = False
  1474. has_codeblocks_csharp = False
  1475. pos = 0
  1476. tag_depth = 0
  1477. while True:
  1478. pos = text.find("[", pos)
  1479. if pos == -1:
  1480. break
  1481. endq_pos = text.find("]", pos + 1)
  1482. if endq_pos == -1:
  1483. break
  1484. pre_text = text[:pos]
  1485. post_text = text[endq_pos + 1 :]
  1486. tag_text = text[pos + 1 : endq_pos]
  1487. escape_pre = False
  1488. escape_post = False
  1489. # Tag is a reference to a class.
  1490. if tag_text in state.classes and not inside_code:
  1491. if tag_text == state.current_class:
  1492. # Don't create a link to the same class, format it as strong emphasis.
  1493. tag_text = f"**{tag_text}**"
  1494. else:
  1495. tag_text = make_type(tag_text, state)
  1496. escape_pre = True
  1497. escape_post = True
  1498. # Tag is a cross-reference or a formatting directive.
  1499. else:
  1500. tag_state = get_tag_and_args(tag_text)
  1501. # Anything identified as a tag inside of a code block is valid,
  1502. # unless it's a matching closing tag.
  1503. if inside_code:
  1504. # Exiting codeblocks and inline code tags.
  1505. if tag_state.closing and tag_state.name == inside_code_tag:
  1506. if is_in_tagset(tag_state.name, RESERVED_CODEBLOCK_TAGS):
  1507. tag_text = ""
  1508. tag_depth -= 1
  1509. inside_code = False
  1510. ignore_code_warnings = False
  1511. # Strip newline if the tag was alone on one
  1512. if pre_text[-1] == "\n":
  1513. pre_text = pre_text[:-1]
  1514. elif is_in_tagset(tag_state.name, ["code"]):
  1515. tag_text = "``"
  1516. tag_depth -= 1
  1517. inside_code = False
  1518. ignore_code_warnings = False
  1519. escape_post = True
  1520. else:
  1521. if not ignore_code_warnings and tag_state.closing:
  1522. print_warning(
  1523. 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}',
  1524. state,
  1525. )
  1526. tag_text = f"[{tag_text}]"
  1527. # Entering codeblocks and inline code tags.
  1528. elif tag_state.name == "codeblocks":
  1529. if tag_state.closing:
  1530. if not has_codeblocks_gdscript or not has_codeblocks_csharp:
  1531. state.script_language_parity_check.add_hit(
  1532. state.current_class,
  1533. context,
  1534. "Only one script language sample found in [codeblocks]",
  1535. state,
  1536. )
  1537. has_codeblocks_gdscript = False
  1538. has_codeblocks_csharp = False
  1539. tag_depth -= 1
  1540. tag_text = ""
  1541. inside_code_tabs = False
  1542. else:
  1543. tag_depth += 1
  1544. tag_text = "\n.. tabs::"
  1545. inside_code_tabs = True
  1546. elif is_in_tagset(tag_state.name, RESERVED_CODEBLOCK_TAGS):
  1547. tag_depth += 1
  1548. if tag_state.name == "gdscript":
  1549. if not inside_code_tabs:
  1550. print_error(
  1551. f"{state.current_class}.xml: GDScript code block is used outside of [codeblocks] in {context_name}.",
  1552. state,
  1553. )
  1554. else:
  1555. has_codeblocks_gdscript = True
  1556. tag_text = "\n .. code-tab:: gdscript\n"
  1557. elif tag_state.name == "csharp":
  1558. if not inside_code_tabs:
  1559. print_error(
  1560. f"{state.current_class}.xml: C# code block is used outside of [codeblocks] in {context_name}.",
  1561. state,
  1562. )
  1563. else:
  1564. has_codeblocks_csharp = True
  1565. tag_text = "\n .. code-tab:: csharp\n"
  1566. else:
  1567. state.script_language_parity_check.add_hit(
  1568. state.current_class,
  1569. context,
  1570. "Code sample is formatted with [codeblock] where [codeblocks] should be used",
  1571. state,
  1572. )
  1573. if "lang=text" in tag_state.arguments.split(" "):
  1574. tag_text = "\n.. code:: text\n"
  1575. else:
  1576. tag_text = "\n::\n"
  1577. inside_code = True
  1578. inside_code_tag = tag_state.name
  1579. ignore_code_warnings = "skip-lint" in tag_state.arguments.split(" ")
  1580. elif is_in_tagset(tag_state.name, ["code"]):
  1581. tag_text = "``"
  1582. tag_depth += 1
  1583. inside_code = True
  1584. inside_code_tag = "code"
  1585. ignore_code_warnings = "skip-lint" in tag_state.arguments.split(" ")
  1586. escape_pre = True
  1587. if not ignore_code_warnings:
  1588. endcode_pos = text.find("[/code]", endq_pos + 1)
  1589. if endcode_pos == -1:
  1590. print_error(
  1591. f"{state.current_class}.xml: Tag depth mismatch for [code]: no closing [/code] in {context_name}.",
  1592. state,
  1593. )
  1594. break
  1595. inside_code_text = text[endq_pos + 1 : endcode_pos]
  1596. if inside_code_text.endswith("()"):
  1597. # It's formatted like a call for some reason, may still be a mistake.
  1598. inside_code_text = inside_code_text[:-2]
  1599. if inside_code_text in state.classes:
  1600. print_warning(
  1601. 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}',
  1602. state,
  1603. )
  1604. target_class_name, target_name, *rest = parse_link_target(inside_code_text, state, context_name)
  1605. if len(rest) == 0 and target_class_name in state.classes:
  1606. class_def = state.classes[target_class_name]
  1607. if target_name in class_def.methods:
  1608. print_warning(
  1609. 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}',
  1610. state,
  1611. )
  1612. elif target_name in class_def.constructors:
  1613. print_warning(
  1614. 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}',
  1615. state,
  1616. )
  1617. elif target_name in class_def.operators:
  1618. print_warning(
  1619. 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}',
  1620. state,
  1621. )
  1622. elif target_name in class_def.properties:
  1623. print_warning(
  1624. 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}',
  1625. state,
  1626. )
  1627. elif target_name in class_def.signals:
  1628. print_warning(
  1629. 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}',
  1630. state,
  1631. )
  1632. elif target_name in class_def.annotations:
  1633. print_warning(
  1634. 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}',
  1635. state,
  1636. )
  1637. elif target_name in class_def.theme_items:
  1638. print_warning(
  1639. 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}',
  1640. state,
  1641. )
  1642. elif target_name in class_def.constants:
  1643. print_warning(
  1644. 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}',
  1645. state,
  1646. )
  1647. else:
  1648. for enum in class_def.enums.values():
  1649. if target_name in enum.values:
  1650. print_warning(
  1651. 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}',
  1652. state,
  1653. )
  1654. break
  1655. valid_param_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1656. if valid_param_context:
  1657. context_params: List[ParameterDef] = context.parameters # type: ignore
  1658. for param_def in context_params:
  1659. if param_def.name == inside_code_text:
  1660. print_warning(
  1661. 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}',
  1662. state,
  1663. )
  1664. break
  1665. # Cross-references to items in this or other class documentation pages.
  1666. elif is_in_tagset(tag_state.name, RESERVED_CROSSLINK_TAGS):
  1667. link_target: str = tag_state.arguments
  1668. if link_target == "":
  1669. print_error(
  1670. f'{state.current_class}.xml: Empty cross-reference link "[{tag_state.raw}]" in {context_name}.',
  1671. state,
  1672. )
  1673. tag_text = ""
  1674. else:
  1675. if (
  1676. tag_state.name == "method"
  1677. or tag_state.name == "constructor"
  1678. or tag_state.name == "operator"
  1679. or tag_state.name == "member"
  1680. or tag_state.name == "signal"
  1681. or tag_state.name == "annotation"
  1682. or tag_state.name == "theme_item"
  1683. or tag_state.name == "constant"
  1684. ):
  1685. target_class_name, target_name, *rest = parse_link_target(link_target, state, context_name)
  1686. if len(rest) > 0:
  1687. print_error(
  1688. f'{state.current_class}.xml: Bad reference "{link_target}" in {context_name}.',
  1689. state,
  1690. )
  1691. # Default to the tag command name. This works by default for most tags,
  1692. # but method, member, and theme_item have special cases.
  1693. ref_type = "_{}".format(tag_state.name)
  1694. if target_class_name in state.classes:
  1695. class_def = state.classes[target_class_name]
  1696. if tag_state.name == "method":
  1697. if target_name.startswith("_"):
  1698. ref_type = "_private_method"
  1699. if target_name not in class_def.methods:
  1700. print_error(
  1701. f'{state.current_class}.xml: Unresolved method reference "{link_target}" in {context_name}.',
  1702. state,
  1703. )
  1704. elif tag_state.name == "constructor" and target_name not in class_def.constructors:
  1705. print_error(
  1706. f'{state.current_class}.xml: Unresolved constructor reference "{link_target}" in {context_name}.',
  1707. state,
  1708. )
  1709. elif tag_state.name == "operator" and target_name not in class_def.operators:
  1710. print_error(
  1711. f'{state.current_class}.xml: Unresolved operator reference "{link_target}" in {context_name}.',
  1712. state,
  1713. )
  1714. elif tag_state.name == "member":
  1715. ref_type = "_property"
  1716. if target_name not in class_def.properties:
  1717. print_error(
  1718. f'{state.current_class}.xml: Unresolved member reference "{link_target}" in {context_name}.',
  1719. state,
  1720. )
  1721. elif tag_state.name == "signal" and target_name not in class_def.signals:
  1722. print_error(
  1723. f'{state.current_class}.xml: Unresolved signal reference "{link_target}" in {context_name}.',
  1724. state,
  1725. )
  1726. elif tag_state.name == "annotation" and target_name not in class_def.annotations:
  1727. print_error(
  1728. f'{state.current_class}.xml: Unresolved annotation reference "{link_target}" in {context_name}.',
  1729. state,
  1730. )
  1731. elif tag_state.name == "theme_item":
  1732. if target_name not in class_def.theme_items:
  1733. print_error(
  1734. f'{state.current_class}.xml: Unresolved theme property reference "{link_target}" in {context_name}.',
  1735. state,
  1736. )
  1737. else:
  1738. # Needs theme data type to be properly linked, which we cannot get without a class.
  1739. name = class_def.theme_items[target_name].data_name
  1740. ref_type = f"_theme_{name}"
  1741. elif tag_state.name == "constant":
  1742. found = False
  1743. # Search in the current class
  1744. search_class_defs = [class_def]
  1745. if link_target.find(".") == -1:
  1746. # Also search in @GlobalScope as a last resort if no class was specified
  1747. search_class_defs.append(state.classes["@GlobalScope"])
  1748. for search_class_def in search_class_defs:
  1749. if target_name in search_class_def.constants:
  1750. target_class_name = search_class_def.name
  1751. found = True
  1752. else:
  1753. for enum in search_class_def.enums.values():
  1754. if target_name in enum.values:
  1755. target_class_name = search_class_def.name
  1756. found = True
  1757. break
  1758. if not found:
  1759. print_error(
  1760. f'{state.current_class}.xml: Unresolved constant reference "{link_target}" in {context_name}.',
  1761. state,
  1762. )
  1763. else:
  1764. print_error(
  1765. f'{state.current_class}.xml: Unresolved type reference "{target_class_name}" in method reference "{link_target}" in {context_name}.',
  1766. state,
  1767. )
  1768. repl_text = target_name
  1769. if target_class_name != state.current_class:
  1770. repl_text = f"{target_class_name}.{target_name}"
  1771. if tag_state.name == "method":
  1772. repl_text = f"{repl_text}()"
  1773. tag_text = f":ref:`{repl_text}<class_{sanitize_class_name(target_class_name)}{ref_type}_{target_name}>`"
  1774. escape_pre = True
  1775. escape_post = True
  1776. elif tag_state.name == "enum":
  1777. tag_text = make_enum(link_target, False, state)
  1778. escape_pre = True
  1779. escape_post = True
  1780. elif tag_state.name == "param":
  1781. valid_param_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1782. if not valid_param_context:
  1783. print_error(
  1784. f'{state.current_class}.xml: Argument reference "{link_target}" used outside of method, signal, or annotation context in {context_name}.',
  1785. state,
  1786. )
  1787. else:
  1788. context_params: List[ParameterDef] = context.parameters # type: ignore
  1789. found = False
  1790. for param_def in context_params:
  1791. if param_def.name == link_target:
  1792. found = True
  1793. break
  1794. if not found:
  1795. print_error(
  1796. f'{state.current_class}.xml: Unresolved argument reference "{link_target}" in {context_name}.',
  1797. state,
  1798. )
  1799. tag_text = f"``{link_target}``"
  1800. escape_pre = True
  1801. escape_post = True
  1802. # Formatting directives.
  1803. elif is_in_tagset(tag_state.name, ["url"]):
  1804. url_target = tag_state.arguments
  1805. if url_target == "":
  1806. print_error(
  1807. f'{state.current_class}.xml: Misformatted [url] tag "[{tag_state.raw}]" in {context_name}.',
  1808. state,
  1809. )
  1810. else:
  1811. # Unlike other tags, URLs are handled in full here, as we need to extract
  1812. # the optional link title to use `make_link`.
  1813. endurl_pos = text.find("[/url]", endq_pos + 1)
  1814. if endurl_pos == -1:
  1815. print_error(
  1816. f"{state.current_class}.xml: Tag depth mismatch for [url]: no closing [/url] in {context_name}.",
  1817. state,
  1818. )
  1819. break
  1820. link_title = text[endq_pos + 1 : endurl_pos]
  1821. tag_text = make_link(url_target, link_title)
  1822. pre_text = text[:pos]
  1823. post_text = text[endurl_pos + 6 :]
  1824. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1825. pre_text += "\\ "
  1826. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1827. post_text = "\\ " + post_text
  1828. text = pre_text + tag_text + post_text
  1829. pos = len(pre_text) + len(tag_text)
  1830. continue
  1831. elif tag_state.name == "br":
  1832. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  1833. tag_text = "\n\n"
  1834. # Strip potential leading spaces
  1835. while post_text[0] == " ":
  1836. post_text = post_text[1:]
  1837. elif tag_state.name == "center":
  1838. if tag_state.closing:
  1839. tag_depth -= 1
  1840. else:
  1841. tag_depth += 1
  1842. tag_text = ""
  1843. elif tag_state.name == "i":
  1844. if tag_state.closing:
  1845. tag_depth -= 1
  1846. escape_post = True
  1847. else:
  1848. tag_depth += 1
  1849. escape_pre = True
  1850. tag_text = "*"
  1851. elif tag_state.name == "b":
  1852. if tag_state.closing:
  1853. tag_depth -= 1
  1854. escape_post = True
  1855. else:
  1856. tag_depth += 1
  1857. escape_pre = True
  1858. tag_text = "**"
  1859. elif tag_state.name == "u":
  1860. if tag_state.closing:
  1861. tag_depth -= 1
  1862. escape_post = True
  1863. else:
  1864. tag_depth += 1
  1865. escape_pre = True
  1866. tag_text = ""
  1867. elif tag_state.name == "lb":
  1868. tag_text = "\\["
  1869. elif tag_state.name == "rb":
  1870. tag_text = "\\]"
  1871. elif tag_state.name == "kbd":
  1872. tag_text = "`"
  1873. if tag_state.closing:
  1874. tag_depth -= 1
  1875. escape_post = True
  1876. else:
  1877. tag_text = ":kbd:" + tag_text
  1878. tag_depth += 1
  1879. escape_pre = True
  1880. # Invalid syntax.
  1881. else:
  1882. if tag_state.closing:
  1883. print_error(
  1884. f'{state.current_class}.xml: Unrecognized closing tag "[{tag_state.raw}]" in {context_name}.',
  1885. state,
  1886. )
  1887. tag_text = f"[{tag_text}]"
  1888. else:
  1889. print_error(
  1890. f'{state.current_class}.xml: Unrecognized opening tag "[{tag_state.raw}]" in {context_name}.',
  1891. state,
  1892. )
  1893. tag_text = f"``{tag_text}``"
  1894. escape_pre = True
  1895. escape_post = True
  1896. # Properly escape things like `[Node]s`
  1897. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1898. pre_text += "\\ "
  1899. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1900. post_text = "\\ " + post_text
  1901. next_brac_pos = post_text.find("[", 0)
  1902. iter_pos = 0
  1903. while not inside_code:
  1904. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  1905. if iter_pos == -1:
  1906. break
  1907. post_text = f"{post_text[:iter_pos]}\\*{post_text[iter_pos + 1 :]}"
  1908. iter_pos += 2
  1909. iter_pos = 0
  1910. while not inside_code:
  1911. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  1912. if iter_pos == -1:
  1913. break
  1914. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  1915. post_text = f"{post_text[:iter_pos]}\\_{post_text[iter_pos + 1 :]}"
  1916. iter_pos += 2
  1917. else:
  1918. iter_pos += 1
  1919. text = pre_text + tag_text + post_text
  1920. pos = len(pre_text) + len(tag_text)
  1921. if tag_depth > 0:
  1922. print_error(
  1923. f"{state.current_class}.xml: Tag depth mismatch: too many (or too few) open/close tags in {context_name}.",
  1924. state,
  1925. )
  1926. return text
  1927. def format_context_name(context: Union[DefinitionBase, None]) -> str:
  1928. context_name: str = "unknown context"
  1929. if context is not None:
  1930. context_name = f'{context.definition_name} "{context.name}" description'
  1931. return context_name
  1932. def escape_rst(text: str, until_pos: int = -1) -> str:
  1933. # Escape \ character, otherwise it ends up as an escape character in rst
  1934. pos = 0
  1935. while True:
  1936. pos = text.find("\\", pos, until_pos)
  1937. if pos == -1:
  1938. break
  1939. text = f"{text[:pos]}\\\\{text[pos + 1 :]}"
  1940. pos += 2
  1941. # Escape * character to avoid interpreting it as emphasis
  1942. pos = 0
  1943. while True:
  1944. pos = text.find("*", pos, until_pos)
  1945. if pos == -1:
  1946. break
  1947. text = f"{text[:pos]}\\*{text[pos + 1 :]}"
  1948. pos += 2
  1949. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  1950. pos = 0
  1951. while True:
  1952. pos = text.find("_", pos, until_pos)
  1953. if pos == -1:
  1954. break
  1955. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  1956. text = f"{text[:pos]}\\_{text[pos + 1 :]}"
  1957. pos += 2
  1958. else:
  1959. pos += 1
  1960. return text
  1961. def format_codeblock(
  1962. tag_state: TagState, post_text: str, indent_level: int, state: State
  1963. ) -> Union[Tuple[str, int], None]:
  1964. end_pos = post_text.find("[/" + tag_state.name + "]")
  1965. if end_pos == -1:
  1966. print_error(
  1967. f"{state.current_class}.xml: Tag depth mismatch for [{tag_state.name}]: no closing [/{tag_state.name}].",
  1968. state,
  1969. )
  1970. return None
  1971. opening_formatted = tag_state.name
  1972. if len(tag_state.arguments) > 0:
  1973. opening_formatted += " " + tag_state.arguments
  1974. code_text = post_text[len(f"[{opening_formatted}]") : end_pos]
  1975. post_text = post_text[end_pos:]
  1976. # Remove extraneous tabs
  1977. code_pos = 0
  1978. while True:
  1979. code_pos = code_text.find("\n", code_pos)
  1980. if code_pos == -1:
  1981. break
  1982. to_skip = 0
  1983. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  1984. to_skip += 1
  1985. if to_skip > indent_level:
  1986. print_error(
  1987. f"{state.current_class}.xml: Four spaces should be used for indentation within [{tag_state.name}].",
  1988. state,
  1989. )
  1990. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  1991. code_text = f"{code_text[:code_pos]}\n"
  1992. code_pos += 1
  1993. else:
  1994. code_text = f"{code_text[:code_pos]}\n {code_text[code_pos + to_skip + 1 :]}"
  1995. code_pos += 5 - to_skip
  1996. return (f"\n[{opening_formatted}]{code_text}{post_text}", len(f"\n[{opening_formatted}]{code_text}"))
  1997. def format_table(f: TextIO, data: List[Tuple[Optional[str], ...]], remove_empty_columns: bool = False) -> None:
  1998. if len(data) == 0:
  1999. return
  2000. f.write(".. table::\n")
  2001. f.write(" :widths: auto\n\n")
  2002. # Calculate the width of each column first, we will use this information
  2003. # to properly format RST-style tables.
  2004. column_sizes = [0] * len(data[0])
  2005. for row in data:
  2006. for i, text in enumerate(row):
  2007. text_length = len(text or "")
  2008. if text_length > column_sizes[i]:
  2009. column_sizes[i] = text_length
  2010. # Each table row is wrapped in two separators, consecutive rows share the same separator.
  2011. # All separators, or rather borders, have the same shape and content. We compose it once,
  2012. # then reuse it.
  2013. sep = ""
  2014. for size in column_sizes:
  2015. if size == 0 and remove_empty_columns:
  2016. continue
  2017. sep += "+" + "-" * (size + 2) # Content of each cell is padded by 1 on each side.
  2018. sep += "+\n"
  2019. # Draw the first separator.
  2020. f.write(f" {sep}")
  2021. # Draw each row and close it with a separator.
  2022. for row in data:
  2023. row_text = "|"
  2024. for i, text in enumerate(row):
  2025. if column_sizes[i] == 0 and remove_empty_columns:
  2026. continue
  2027. row_text += f" {(text or '').ljust(column_sizes[i])} |"
  2028. row_text += "\n"
  2029. f.write(f" {row_text}")
  2030. f.write(f" {sep}")
  2031. f.write("\n")
  2032. def sanitize_class_name(dirty_name: str, is_file_name=False) -> str:
  2033. if is_file_name:
  2034. return dirty_name.lower().replace('"', "").replace("/", "--")
  2035. else:
  2036. return dirty_name.replace('"', "").replace("/", "_").replace(".", "_")
  2037. def sanitize_operator_name(dirty_name: str, state: State) -> str:
  2038. clear_name = dirty_name.replace("operator ", "")
  2039. if clear_name == "!=":
  2040. clear_name = "neq"
  2041. elif clear_name == "==":
  2042. clear_name = "eq"
  2043. elif clear_name == "<":
  2044. clear_name = "lt"
  2045. elif clear_name == "<=":
  2046. clear_name = "lte"
  2047. elif clear_name == ">":
  2048. clear_name = "gt"
  2049. elif clear_name == ">=":
  2050. clear_name = "gte"
  2051. elif clear_name == "+":
  2052. clear_name = "sum"
  2053. elif clear_name == "-":
  2054. clear_name = "dif"
  2055. elif clear_name == "*":
  2056. clear_name = "mul"
  2057. elif clear_name == "/":
  2058. clear_name = "div"
  2059. elif clear_name == "%":
  2060. clear_name = "mod"
  2061. elif clear_name == "**":
  2062. clear_name = "pow"
  2063. elif clear_name == "unary+":
  2064. clear_name = "unplus"
  2065. elif clear_name == "unary-":
  2066. clear_name = "unminus"
  2067. elif clear_name == "<<":
  2068. clear_name = "bwsl"
  2069. elif clear_name == ">>":
  2070. clear_name = "bwsr"
  2071. elif clear_name == "&":
  2072. clear_name = "bwand"
  2073. elif clear_name == "|":
  2074. clear_name = "bwor"
  2075. elif clear_name == "^":
  2076. clear_name = "bwxor"
  2077. elif clear_name == "~":
  2078. clear_name = "bwnot"
  2079. elif clear_name == "[]":
  2080. clear_name = "idx"
  2081. else:
  2082. clear_name = "xxx"
  2083. print_error(f'Unsupported operator type "{dirty_name}", please add the missing rule.', state)
  2084. return clear_name
  2085. if __name__ == "__main__":
  2086. main()