make_rst.py 104 KB

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