make_rst.py 103 KB

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