make_rst.py 103 KB

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