make_rst.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978
  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 platform
  6. import re
  7. import sys
  8. import xml.etree.ElementTree as ET
  9. from collections import OrderedDict
  10. from typing import List, Dict, TextIO, Tuple, Optional, Any, Union
  11. # Import hardcoded version information from version.py
  12. root_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../")
  13. sys.path.append(root_directory) # Include the root directory
  14. import version
  15. # $DOCS_URL/path/to/page.html(#fragment-tag)
  16. GODOT_DOCS_PATTERN = re.compile(r"^\$DOCS_URL/(.*)\.html(#.*)?$")
  17. # Based on reStructuredText inline markup recognition rules
  18. # https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
  19. MARKUP_ALLOWED_PRECEDENT = " -:/'\"<([{"
  20. MARKUP_ALLOWED_SUBSEQUENT = " -.,:;!?\\/'\")]}>"
  21. # Used to translate section headings and other hardcoded strings when required with
  22. # the --lang argument. The BASE_STRINGS list should be synced with what we actually
  23. # write in this script (check `translate()` uses), and also hardcoded in
  24. # `doc/translations/extract.py` to include them in the source POT file.
  25. BASE_STRINGS = [
  26. "All classes",
  27. "Globals",
  28. "Nodes",
  29. "Resources",
  30. "Other objects",
  31. "Variant types",
  32. "Description",
  33. "Tutorials",
  34. "Properties",
  35. "Constructors",
  36. "Methods",
  37. "Operators",
  38. "Theme Properties",
  39. "Signals",
  40. "Enumerations",
  41. "Constants",
  42. "Annotations",
  43. "Property Descriptions",
  44. "Constructor Descriptions",
  45. "Method Descriptions",
  46. "Operator Descriptions",
  47. "Theme Property Descriptions",
  48. "Inherits:",
  49. "Inherited By:",
  50. "(overrides %s)",
  51. "Default",
  52. "Setter",
  53. "value",
  54. "Getter",
  55. "This method should typically be overridden by the user to have any effect.",
  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. ]
  62. strings_l10n: Dict[str, str] = {}
  63. STYLES: Dict[str, str] = {}
  64. CLASS_GROUPS: Dict[str, str] = {
  65. "global": "Globals",
  66. "node": "Nodes",
  67. "resource": "Resources",
  68. "object": "Other objects",
  69. "variant": "Variant types",
  70. }
  71. CLASS_GROUPS_BASE: Dict[str, str] = {
  72. "node": "Node",
  73. "resource": "Resource",
  74. "object": "Object",
  75. }
  76. class State:
  77. def __init__(self) -> None:
  78. self.num_errors = 0
  79. self.num_warnings = 0
  80. self.classes: OrderedDict[str, ClassDef] = OrderedDict()
  81. self.current_class: str = ""
  82. def parse_class(self, class_root: ET.Element, filepath: str) -> None:
  83. class_name = class_root.attrib["name"]
  84. self.current_class = class_name
  85. class_def = ClassDef(class_name)
  86. self.classes[class_name] = class_def
  87. class_def.filepath = filepath
  88. inherits = class_root.get("inherits")
  89. if inherits is not None:
  90. class_def.inherits = inherits
  91. brief_desc = class_root.find("brief_description")
  92. if brief_desc is not None and brief_desc.text:
  93. class_def.brief_description = brief_desc.text
  94. desc = class_root.find("description")
  95. if desc is not None and desc.text:
  96. class_def.description = desc.text
  97. properties = class_root.find("members")
  98. if properties is not None:
  99. for property in properties:
  100. assert property.tag == "member"
  101. property_name = property.attrib["name"]
  102. if property_name in class_def.properties:
  103. print_error(f'{class_name}.xml: Duplicate property "{property_name}".', self)
  104. continue
  105. type_name = TypeName.from_element(property)
  106. setter = property.get("setter") or None # Use or None so '' gets turned into None.
  107. getter = property.get("getter") or None
  108. default_value = property.get("default") or None
  109. if default_value is not None:
  110. default_value = f"``{default_value}``"
  111. overrides = property.get("overrides") or None
  112. property_def = PropertyDef(
  113. property_name, type_name, setter, getter, property.text, default_value, overrides
  114. )
  115. class_def.properties[property_name] = property_def
  116. constructors = class_root.find("constructors")
  117. if constructors is not None:
  118. for constructor in constructors:
  119. assert constructor.tag == "constructor"
  120. method_name = constructor.attrib["name"]
  121. qualifiers = constructor.get("qualifiers")
  122. return_element = constructor.find("return")
  123. if return_element is not None:
  124. return_type = TypeName.from_element(return_element)
  125. else:
  126. return_type = TypeName("void")
  127. params = self.parse_params(constructor, "constructor")
  128. desc_element = constructor.find("description")
  129. method_desc = None
  130. if desc_element is not None:
  131. method_desc = desc_element.text
  132. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  133. method_def.definition_name = "constructor"
  134. if method_name not in class_def.constructors:
  135. class_def.constructors[method_name] = []
  136. class_def.constructors[method_name].append(method_def)
  137. methods = class_root.find("methods")
  138. if methods is not None:
  139. for method in methods:
  140. assert method.tag == "method"
  141. method_name = method.attrib["name"]
  142. qualifiers = method.get("qualifiers")
  143. return_element = method.find("return")
  144. if return_element is not None:
  145. return_type = TypeName.from_element(return_element)
  146. else:
  147. return_type = TypeName("void")
  148. params = self.parse_params(method, "method")
  149. desc_element = method.find("description")
  150. method_desc = None
  151. if desc_element is not None:
  152. method_desc = desc_element.text
  153. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  154. if method_name not in class_def.methods:
  155. class_def.methods[method_name] = []
  156. class_def.methods[method_name].append(method_def)
  157. operators = class_root.find("operators")
  158. if operators is not None:
  159. for operator in operators:
  160. assert operator.tag == "operator"
  161. method_name = operator.attrib["name"]
  162. qualifiers = operator.get("qualifiers")
  163. return_element = operator.find("return")
  164. if return_element is not None:
  165. return_type = TypeName.from_element(return_element)
  166. else:
  167. return_type = TypeName("void")
  168. params = self.parse_params(operator, "operator")
  169. desc_element = operator.find("description")
  170. method_desc = None
  171. if desc_element is not None:
  172. method_desc = desc_element.text
  173. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  174. method_def.definition_name = "operator"
  175. if method_name not in class_def.operators:
  176. class_def.operators[method_name] = []
  177. class_def.operators[method_name].append(method_def)
  178. constants = class_root.find("constants")
  179. if constants is not None:
  180. for constant in constants:
  181. assert constant.tag == "constant"
  182. constant_name = constant.attrib["name"]
  183. value = constant.attrib["value"]
  184. enum = constant.get("enum")
  185. is_bitfield = constant.get("is_bitfield") == "true"
  186. constant_def = ConstantDef(constant_name, value, constant.text, is_bitfield)
  187. if enum is None:
  188. if constant_name in class_def.constants:
  189. print_error(f'{class_name}.xml: Duplicate constant "{constant_name}".', self)
  190. continue
  191. class_def.constants[constant_name] = constant_def
  192. else:
  193. if enum in class_def.enums:
  194. enum_def = class_def.enums[enum]
  195. else:
  196. enum_def = EnumDef(enum, is_bitfield)
  197. class_def.enums[enum] = enum_def
  198. enum_def.values[constant_name] = constant_def
  199. annotations = class_root.find("annotations")
  200. if annotations is not None:
  201. for annotation in annotations:
  202. assert annotation.tag == "annotation"
  203. annotation_name = annotation.attrib["name"]
  204. qualifiers = annotation.get("qualifiers")
  205. params = self.parse_params(annotation, "annotation")
  206. desc_element = annotation.find("description")
  207. annotation_desc = None
  208. if desc_element is not None:
  209. annotation_desc = desc_element.text
  210. annotation_def = AnnotationDef(annotation_name, params, annotation_desc, qualifiers)
  211. if annotation_name not in class_def.annotations:
  212. class_def.annotations[annotation_name] = []
  213. class_def.annotations[annotation_name].append(annotation_def)
  214. signals = class_root.find("signals")
  215. if signals is not None:
  216. for signal in signals:
  217. assert signal.tag == "signal"
  218. signal_name = signal.attrib["name"]
  219. if signal_name in class_def.signals:
  220. print_error(f'{class_name}.xml: Duplicate signal "{signal_name}".', self)
  221. continue
  222. params = self.parse_params(signal, "signal")
  223. desc_element = signal.find("description")
  224. signal_desc = None
  225. if desc_element is not None:
  226. signal_desc = desc_element.text
  227. signal_def = SignalDef(signal_name, params, signal_desc)
  228. class_def.signals[signal_name] = signal_def
  229. theme_items = class_root.find("theme_items")
  230. if theme_items is not None:
  231. for theme_item in theme_items:
  232. assert theme_item.tag == "theme_item"
  233. theme_item_name = theme_item.attrib["name"]
  234. theme_item_data_name = theme_item.attrib["data_type"]
  235. theme_item_id = "{}_{}".format(theme_item_data_name, theme_item_name)
  236. if theme_item_id in class_def.theme_items:
  237. print_error(
  238. f'{class_name}.xml: Duplicate theme item "{theme_item_name}" of type "{theme_item_data_name}".',
  239. self,
  240. )
  241. continue
  242. default_value = theme_item.get("default") or None
  243. if default_value is not None:
  244. default_value = f"``{default_value}``"
  245. theme_item_def = ThemeItemDef(
  246. theme_item_name,
  247. TypeName.from_element(theme_item),
  248. theme_item_data_name,
  249. theme_item.text,
  250. default_value,
  251. )
  252. class_def.theme_items[theme_item_name] = theme_item_def
  253. tutorials = class_root.find("tutorials")
  254. if tutorials is not None:
  255. for link in tutorials:
  256. assert link.tag == "link"
  257. if link.text is not None:
  258. class_def.tutorials.append((link.text.strip(), link.get("title", "")))
  259. self.current_class = ""
  260. def parse_params(self, root: ET.Element, context: str) -> List["ParameterDef"]:
  261. param_elements = root.findall("param")
  262. params: Any = [None] * len(param_elements)
  263. for param_index, param_element in enumerate(param_elements):
  264. param_name = param_element.attrib["name"]
  265. index = int(param_element.attrib["index"])
  266. type_name = TypeName.from_element(param_element)
  267. default = param_element.get("default")
  268. if param_name.strip() == "" or param_name.startswith("_unnamed_arg"):
  269. print_error(
  270. f'{self.current_class}.xml: Empty argument name in {context} "{root.attrib["name"]}" at position {param_index}.',
  271. self,
  272. )
  273. params[index] = ParameterDef(param_name, type_name, default)
  274. cast: List[ParameterDef] = params
  275. return cast
  276. def sort_classes(self) -> None:
  277. self.classes = OrderedDict(sorted(self.classes.items(), key=lambda t: t[0].lower()))
  278. class TypeName:
  279. def __init__(self, type_name: str, enum: Optional[str] = None) -> None:
  280. self.type_name = type_name
  281. self.enum = enum
  282. def to_rst(self, state: State) -> str:
  283. if self.enum is not None:
  284. return make_enum(self.enum, state)
  285. elif self.type_name == "void":
  286. return "void"
  287. else:
  288. return make_type(self.type_name, state)
  289. @classmethod
  290. def from_element(cls, element: ET.Element) -> "TypeName":
  291. return cls(element.attrib["type"], element.get("enum"))
  292. class DefinitionBase:
  293. def __init__(
  294. self,
  295. definition_name: str,
  296. name: str,
  297. ) -> None:
  298. self.definition_name = definition_name
  299. self.name = name
  300. class PropertyDef(DefinitionBase):
  301. def __init__(
  302. self,
  303. name: str,
  304. type_name: TypeName,
  305. setter: Optional[str],
  306. getter: Optional[str],
  307. text: Optional[str],
  308. default_value: Optional[str],
  309. overrides: Optional[str],
  310. ) -> None:
  311. super().__init__("property", name)
  312. self.type_name = type_name
  313. self.setter = setter
  314. self.getter = getter
  315. self.text = text
  316. self.default_value = default_value
  317. self.overrides = overrides
  318. class ParameterDef(DefinitionBase):
  319. def __init__(self, name: str, type_name: TypeName, default_value: Optional[str]) -> None:
  320. super().__init__("parameter", name)
  321. self.type_name = type_name
  322. self.default_value = default_value
  323. class SignalDef(DefinitionBase):
  324. def __init__(self, name: str, parameters: List[ParameterDef], description: Optional[str]) -> None:
  325. super().__init__("signal", name)
  326. self.parameters = parameters
  327. self.description = description
  328. class AnnotationDef(DefinitionBase):
  329. def __init__(
  330. self,
  331. name: str,
  332. parameters: List[ParameterDef],
  333. description: Optional[str],
  334. qualifiers: Optional[str],
  335. ) -> None:
  336. super().__init__("annotation", name)
  337. self.parameters = parameters
  338. self.description = description
  339. self.qualifiers = qualifiers
  340. class MethodDef(DefinitionBase):
  341. def __init__(
  342. self,
  343. name: str,
  344. return_type: TypeName,
  345. parameters: List[ParameterDef],
  346. description: Optional[str],
  347. qualifiers: Optional[str],
  348. ) -> None:
  349. super().__init__("method", name)
  350. self.return_type = return_type
  351. self.parameters = parameters
  352. self.description = description
  353. self.qualifiers = qualifiers
  354. class ConstantDef(DefinitionBase):
  355. def __init__(self, name: str, value: str, text: Optional[str], bitfield: bool) -> None:
  356. super().__init__("constant", name)
  357. self.value = value
  358. self.text = text
  359. self.is_bitfield = bitfield
  360. class EnumDef(DefinitionBase):
  361. def __init__(self, name: str, bitfield: bool) -> None:
  362. super().__init__("enum", name)
  363. self.values: OrderedDict[str, ConstantDef] = OrderedDict()
  364. self.is_bitfield = bitfield
  365. class ThemeItemDef(DefinitionBase):
  366. def __init__(
  367. self, name: str, type_name: TypeName, data_name: str, text: Optional[str], default_value: Optional[str]
  368. ) -> None:
  369. super().__init__("theme item", name)
  370. self.type_name = type_name
  371. self.data_name = data_name
  372. self.text = text
  373. self.default_value = default_value
  374. class ClassDef(DefinitionBase):
  375. def __init__(self, name: str) -> None:
  376. super().__init__("class", name)
  377. self.constants: OrderedDict[str, ConstantDef] = OrderedDict()
  378. self.enums: OrderedDict[str, EnumDef] = OrderedDict()
  379. self.properties: OrderedDict[str, PropertyDef] = OrderedDict()
  380. self.constructors: OrderedDict[str, List[MethodDef]] = OrderedDict()
  381. self.methods: OrderedDict[str, List[MethodDef]] = OrderedDict()
  382. self.operators: OrderedDict[str, List[MethodDef]] = OrderedDict()
  383. self.signals: OrderedDict[str, SignalDef] = OrderedDict()
  384. self.annotations: OrderedDict[str, List[AnnotationDef]] = OrderedDict()
  385. self.theme_items: OrderedDict[str, ThemeItemDef] = OrderedDict()
  386. self.inherits: Optional[str] = None
  387. self.brief_description: Optional[str] = None
  388. self.description: Optional[str] = None
  389. self.tutorials: List[Tuple[str, str]] = []
  390. # Used to match the class with XML source for output filtering purposes.
  391. self.filepath: str = ""
  392. # Entry point for the RST generator.
  393. def main() -> None:
  394. # Enable ANSI escape code support on Windows 10 and later (for colored console output).
  395. # <https://bugs.python.org/issue29059>
  396. if platform.system().lower() == "windows":
  397. from ctypes import windll, c_int, byref # type: ignore
  398. stdout_handle = windll.kernel32.GetStdHandle(c_int(-11))
  399. mode = c_int(0)
  400. windll.kernel32.GetConsoleMode(c_int(stdout_handle), byref(mode))
  401. mode = c_int(mode.value | 4)
  402. windll.kernel32.SetConsoleMode(c_int(stdout_handle), mode)
  403. parser = argparse.ArgumentParser()
  404. parser.add_argument("path", nargs="+", help="A path to an XML file or a directory containing XML files to parse.")
  405. parser.add_argument("--filter", default="", help="The filepath pattern for XML files to filter.")
  406. parser.add_argument("--lang", "-l", default="en", help="Language to use for section headings.")
  407. parser.add_argument(
  408. "--color",
  409. action="store_true",
  410. help="If passed, force colored output even if stdout is not a TTY (useful for continuous integration).",
  411. )
  412. group = parser.add_mutually_exclusive_group()
  413. group.add_argument("--output", "-o", default=".", help="The directory to save output .rst files in.")
  414. group.add_argument(
  415. "--dry-run",
  416. action="store_true",
  417. help="If passed, no output will be generated and XML files are only checked for errors.",
  418. )
  419. args = parser.parse_args()
  420. should_color = args.color or (hasattr(sys.stdout, "isatty") and sys.stdout.isatty())
  421. STYLES["red"] = "\x1b[91m" if should_color else ""
  422. STYLES["green"] = "\x1b[92m" if should_color else ""
  423. STYLES["yellow"] = "\x1b[93m" if should_color else ""
  424. STYLES["bold"] = "\x1b[1m" if should_color else ""
  425. STYLES["regular"] = "\x1b[22m" if should_color else ""
  426. STYLES["reset"] = "\x1b[0m" if should_color else ""
  427. # Retrieve heading translations for the given language.
  428. if not args.dry_run and args.lang != "en":
  429. lang_file = os.path.join(
  430. os.path.dirname(os.path.realpath(__file__)), "..", "translations", "{}.po".format(args.lang)
  431. )
  432. if os.path.exists(lang_file):
  433. try:
  434. import polib # type: ignore
  435. except ImportError:
  436. print("Base template strings localization requires `polib`.")
  437. exit(1)
  438. pofile = polib.pofile(lang_file)
  439. for entry in pofile.translated_entries():
  440. if entry.msgid in BASE_STRINGS:
  441. strings_l10n[entry.msgid] = entry.msgstr
  442. else:
  443. print(f'No PO file at "{lang_file}" for language "{args.lang}".')
  444. print("Checking for errors in the XML class reference...")
  445. file_list: List[str] = []
  446. for path in args.path:
  447. # Cut off trailing slashes so os.path.basename doesn't choke.
  448. if path.endswith("/") or path.endswith("\\"):
  449. path = path[:-1]
  450. if os.path.basename(path) == "modules":
  451. for subdir, dirs, _ in os.walk(path):
  452. if "doc_classes" in dirs:
  453. doc_dir = os.path.join(subdir, "doc_classes")
  454. class_file_names = (f for f in os.listdir(doc_dir) if f.endswith(".xml"))
  455. file_list += (os.path.join(doc_dir, f) for f in class_file_names)
  456. elif os.path.isdir(path):
  457. file_list += (os.path.join(path, f) for f in os.listdir(path) if f.endswith(".xml"))
  458. elif os.path.isfile(path):
  459. if not path.endswith(".xml"):
  460. print(f'Got non-.xml file "{path}" in input, skipping.')
  461. continue
  462. file_list.append(path)
  463. classes: Dict[str, Tuple[ET.Element, str]] = {}
  464. state = State()
  465. for cur_file in file_list:
  466. try:
  467. tree = ET.parse(cur_file)
  468. except ET.ParseError as e:
  469. print_error(f"{cur_file}: Parse error while reading the file: {e}", state)
  470. continue
  471. doc = tree.getroot()
  472. if "version" not in doc.attrib:
  473. print_error(f'{cur_file}: "version" attribute missing from "doc".', state)
  474. continue
  475. name = doc.attrib["name"]
  476. if name in classes:
  477. print_error(f'{cur_file}: Duplicate class "{name}".', state)
  478. continue
  479. classes[name] = (doc, cur_file)
  480. for name, data in classes.items():
  481. try:
  482. state.parse_class(data[0], data[1])
  483. except Exception as e:
  484. print_error(f"{name}.xml: Exception while parsing class: {e}", state)
  485. state.sort_classes()
  486. pattern = re.compile(args.filter)
  487. # Create the output folder recursively if it doesn't already exist.
  488. os.makedirs(args.output, exist_ok=True)
  489. print("Generating the RST class reference...")
  490. grouped_classes: Dict[str, List[str]] = {}
  491. for class_name, class_def in state.classes.items():
  492. if args.filter and not pattern.search(class_def.filepath):
  493. continue
  494. state.current_class = class_name
  495. make_rst_class(class_def, state, args.dry_run, args.output)
  496. group_name = get_class_group(class_def, state)
  497. if group_name not in grouped_classes:
  498. grouped_classes[group_name] = []
  499. grouped_classes[group_name].append(class_name)
  500. print("")
  501. print("Generating the index file...")
  502. make_rst_index(grouped_classes, args.dry_run, args.output)
  503. print("")
  504. if state.num_warnings >= 2:
  505. print(
  506. f'{STYLES["yellow"]}{state.num_warnings} warnings were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  507. )
  508. elif state.num_warnings == 1:
  509. print(
  510. f'{STYLES["yellow"]}1 warning was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  511. )
  512. if state.num_errors == 0:
  513. print(f'{STYLES["green"]}No errors found in the class reference XML.{STYLES["reset"]}')
  514. if not args.dry_run:
  515. print(f"Wrote reStructuredText files for each class to: {args.output}")
  516. else:
  517. if state.num_errors >= 2:
  518. print(
  519. f'{STYLES["red"]}{state.num_errors} errors were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  520. )
  521. else:
  522. print(
  523. f'{STYLES["red"]}1 error was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  524. )
  525. exit(1)
  526. # Common helpers.
  527. def print_error(error: str, state: State) -> None:
  528. print(f'{STYLES["red"]}{STYLES["bold"]}ERROR:{STYLES["regular"]} {error}{STYLES["reset"]}')
  529. state.num_errors += 1
  530. def print_warning(warning: str, state: State) -> None:
  531. print(f'{STYLES["yellow"]}{STYLES["bold"]}WARNING:{STYLES["regular"]} {warning}{STYLES["reset"]}')
  532. state.num_warnings += 1
  533. def translate(string: str) -> str:
  534. """Translate a string based on translations sourced from `doc/translations/*.po`
  535. for a language if defined via the --lang command line argument.
  536. Returns the original string if no translation exists.
  537. """
  538. return strings_l10n.get(string, string)
  539. def get_git_branch() -> str:
  540. if hasattr(version, "docs") and version.docs != "latest":
  541. return version.docs
  542. return "master"
  543. def get_class_group(class_def: ClassDef, state: State) -> str:
  544. group_name = "variant"
  545. class_name = class_def.name
  546. if class_name.startswith("@"):
  547. group_name = "global"
  548. elif class_def.inherits:
  549. inherits = class_def.inherits.strip()
  550. while inherits in state.classes:
  551. if inherits == "Node":
  552. group_name = "node"
  553. break
  554. if inherits == "Resource":
  555. group_name = "resource"
  556. break
  557. if inherits == "Object":
  558. group_name = "object"
  559. break
  560. inode = state.classes[inherits].inherits
  561. if inode:
  562. inherits = inode.strip()
  563. else:
  564. break
  565. return group_name
  566. # Generator methods.
  567. def make_rst_class(class_def: ClassDef, state: State, dry_run: bool, output_dir: str) -> None:
  568. class_name = class_def.name
  569. if dry_run:
  570. f = open(os.devnull, "w", encoding="utf-8")
  571. else:
  572. f = open(os.path.join(output_dir, f"class_{class_name.lower()}.rst"), "w", encoding="utf-8")
  573. # Remove the "Edit on Github" button from the online docs page.
  574. f.write(":github_url: hide\n\n")
  575. # Warn contributors not to edit this file directly.
  576. # Also provide links to the source files for reference.
  577. git_branch = get_git_branch()
  578. source_xml_path = os.path.relpath(class_def.filepath, root_directory).replace("\\", "/")
  579. source_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/{source_xml_path}"
  580. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  581. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  582. f.write(".. Generated automatically from Godot engine sources.\n")
  583. f.write(f".. Generator: {generator_github_url}.\n")
  584. f.write(f".. XML source: {source_github_url}.\n\n")
  585. # Document reference id and header.
  586. f.write(f".. _class_{class_name}:\n\n")
  587. f.write(make_heading(class_name, "=", False))
  588. # Inheritance tree
  589. # Ascendants
  590. if class_def.inherits:
  591. inherits = class_def.inherits.strip()
  592. f.write(f'**{translate("Inherits:")}** ')
  593. first = True
  594. while inherits in state.classes:
  595. if not first:
  596. f.write(" **<** ")
  597. else:
  598. first = False
  599. f.write(make_type(inherits, state))
  600. inode = state.classes[inherits].inherits
  601. if inode:
  602. inherits = inode.strip()
  603. else:
  604. break
  605. f.write("\n\n")
  606. # Descendants
  607. inherited: List[str] = []
  608. for c in state.classes.values():
  609. if c.inherits and c.inherits.strip() == class_name:
  610. inherited.append(c.name)
  611. if len(inherited):
  612. f.write(f'**{translate("Inherited By:")}** ')
  613. for i, child in enumerate(inherited):
  614. if i > 0:
  615. f.write(", ")
  616. f.write(make_type(child, state))
  617. f.write("\n\n")
  618. has_description = False
  619. # Brief description
  620. if class_def.brief_description is not None and class_def.brief_description.strip() != "":
  621. has_description = True
  622. f.write(f"{format_text_block(class_def.brief_description.strip(), class_def, state)}\n\n")
  623. # Class description
  624. if class_def.description is not None and class_def.description.strip() != "":
  625. has_description = True
  626. f.write(make_heading("Description", "-"))
  627. f.write(f"{format_text_block(class_def.description.strip(), class_def, state)}\n\n")
  628. if not has_description:
  629. f.write(".. container:: contribute\n\n\t")
  630. f.write(
  631. translate(
  632. "There is currently no description for this class. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  633. )
  634. + "\n\n"
  635. )
  636. # Online tutorials
  637. if len(class_def.tutorials) > 0:
  638. f.write(make_heading("Tutorials", "-"))
  639. for url, title in class_def.tutorials:
  640. f.write(f"- {make_link(url, title)}\n\n")
  641. # Properties overview
  642. ml: List[Tuple[Optional[str], ...]] = []
  643. if len(class_def.properties) > 0:
  644. f.write(make_heading("Properties", "-"))
  645. ml = []
  646. for property_def in class_def.properties.values():
  647. type_rst = property_def.type_name.to_rst(state)
  648. default = property_def.default_value
  649. if default is not None and property_def.overrides:
  650. ref = f":ref:`{property_def.overrides}<class_{property_def.overrides}_property_{property_def.name}>`"
  651. # Not using translate() for now as it breaks table formatting.
  652. ml.append((type_rst, property_def.name, f"{default} (overrides {ref})"))
  653. else:
  654. ref = f":ref:`{property_def.name}<class_{class_name}_property_{property_def.name}>`"
  655. ml.append((type_rst, ref, default))
  656. format_table(f, ml, True)
  657. # Constructors, Methods, Operators overview
  658. if len(class_def.constructors) > 0:
  659. f.write(make_heading("Constructors", "-"))
  660. ml = []
  661. for method_list in class_def.constructors.values():
  662. for m in method_list:
  663. ml.append(make_method_signature(class_def, m, "constructor", state))
  664. format_table(f, ml)
  665. if len(class_def.methods) > 0:
  666. f.write(make_heading("Methods", "-"))
  667. ml = []
  668. for method_list in class_def.methods.values():
  669. for m in method_list:
  670. ml.append(make_method_signature(class_def, m, "method", state))
  671. format_table(f, ml)
  672. if len(class_def.operators) > 0:
  673. f.write(make_heading("Operators", "-"))
  674. ml = []
  675. for method_list in class_def.operators.values():
  676. for m in method_list:
  677. ml.append(make_method_signature(class_def, m, "operator", state))
  678. format_table(f, ml)
  679. # Theme properties
  680. if len(class_def.theme_items) > 0:
  681. f.write(make_heading("Theme Properties", "-"))
  682. pl: List[Tuple[Optional[str], ...]] = []
  683. for theme_item_def in class_def.theme_items.values():
  684. ref = f":ref:`{theme_item_def.name}<class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}>`"
  685. pl.append((theme_item_def.type_name.to_rst(state), ref, theme_item_def.default_value))
  686. format_table(f, pl, True)
  687. # Signals
  688. if len(class_def.signals) > 0:
  689. f.write(make_heading("Signals", "-"))
  690. index = 0
  691. for signal in class_def.signals.values():
  692. if index != 0:
  693. f.write("----\n\n")
  694. f.write(f".. _class_{class_name}_signal_{signal.name}:\n\n")
  695. _, signature = make_method_signature(class_def, signal, "", state)
  696. f.write(f"- {signature}\n\n")
  697. if signal.description is not None and signal.description.strip() != "":
  698. f.write(f"{format_text_block(signal.description.strip(), signal, state)}\n\n")
  699. index += 1
  700. # Enums
  701. if len(class_def.enums) > 0:
  702. f.write(make_heading("Enumerations", "-"))
  703. index = 0
  704. for e in class_def.enums.values():
  705. if index != 0:
  706. f.write("----\n\n")
  707. f.write(f".. _enum_{class_name}_{e.name}:\n\n")
  708. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  709. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  710. # As to why I'm not modifying the reference parser to directly link to the _enum label:
  711. # If somebody gets annoyed enough to fix it, all existing references will magically improve.
  712. for value in e.values.values():
  713. f.write(f".. _class_{class_name}_constant_{value.name}:\n\n")
  714. if e.is_bitfield:
  715. f.write(f"flags **{e.name}**:\n\n")
  716. else:
  717. f.write(f"enum **{e.name}**:\n\n")
  718. for value in e.values.values():
  719. f.write(f"- **{value.name}** = **{value.value}**")
  720. if value.text is not None and value.text.strip() != "":
  721. # If value.text contains a bullet point list, each entry needs additional indentation
  722. f.write(f" --- {indent_bullets(format_text_block(value.text.strip(), value, state))}")
  723. f.write("\n\n")
  724. index += 1
  725. # Constants
  726. if len(class_def.constants) > 0:
  727. f.write(make_heading("Constants", "-"))
  728. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  729. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  730. for constant in class_def.constants.values():
  731. f.write(f".. _class_{class_name}_constant_{constant.name}:\n\n")
  732. for constant in class_def.constants.values():
  733. f.write(f"- **{constant.name}** = **{constant.value}**")
  734. if constant.text is not None and constant.text.strip() != "":
  735. f.write(f" --- {format_text_block(constant.text.strip(), constant, state)}")
  736. f.write("\n\n")
  737. # Annotations
  738. if len(class_def.annotations) > 0:
  739. f.write(make_heading("Annotations", "-"))
  740. index = 0
  741. for method_list in class_def.annotations.values(): # type: ignore
  742. for i, m in enumerate(method_list):
  743. if index != 0:
  744. f.write("----\n\n")
  745. if i == 0:
  746. f.write(f".. _class_{class_name}_annotation_{m.name}:\n\n")
  747. _, signature = make_method_signature(class_def, m, "", state)
  748. f.write(f"- {signature}\n\n")
  749. if m.description is not None and m.description.strip() != "":
  750. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  751. else:
  752. f.write(".. container:: contribute\n\n\t")
  753. f.write(
  754. translate(
  755. "There is currently no description for this annotation. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  756. )
  757. + "\n\n"
  758. )
  759. index += 1
  760. # Property descriptions
  761. if any(not p.overrides for p in class_def.properties.values()) > 0:
  762. f.write(make_heading("Property Descriptions", "-"))
  763. index = 0
  764. for property_def in class_def.properties.values():
  765. if property_def.overrides:
  766. continue
  767. if index != 0:
  768. f.write("----\n\n")
  769. f.write(f".. _class_{class_name}_property_{property_def.name}:\n\n")
  770. f.write(f"- {property_def.type_name.to_rst(state)} **{property_def.name}**\n\n")
  771. info: List[Tuple[Optional[str], ...]] = []
  772. # Not using translate() for now as it breaks table formatting.
  773. if property_def.default_value is not None:
  774. info.append(("*Default*", property_def.default_value))
  775. if property_def.setter is not None and not property_def.setter.startswith("_"):
  776. info.append(("*Setter*", f"{property_def.setter}(value)"))
  777. if property_def.getter is not None and not property_def.getter.startswith("_"):
  778. info.append(("*Getter*", f"{property_def.getter}()"))
  779. if len(info) > 0:
  780. format_table(f, info)
  781. if property_def.text is not None and property_def.text.strip() != "":
  782. f.write(f"{format_text_block(property_def.text.strip(), property_def, state)}\n\n")
  783. else:
  784. f.write(".. container:: contribute\n\n\t")
  785. f.write(
  786. translate(
  787. "There is currently no description for this property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  788. )
  789. + "\n\n"
  790. )
  791. index += 1
  792. # Constructor, Method, Operator descriptions
  793. if len(class_def.constructors) > 0:
  794. f.write(make_heading("Constructor Descriptions", "-"))
  795. index = 0
  796. for method_list in class_def.constructors.values():
  797. for i, m in enumerate(method_list):
  798. if index != 0:
  799. f.write("----\n\n")
  800. if i == 0:
  801. f.write(f".. _class_{class_name}_constructor_{m.name}:\n\n")
  802. ret_type, signature = make_method_signature(class_def, m, "", state)
  803. f.write(f"- {ret_type} {signature}\n\n")
  804. if m.description is not None and m.description.strip() != "":
  805. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  806. else:
  807. f.write(".. container:: contribute\n\n\t")
  808. f.write(
  809. translate(
  810. "There is currently no description for this constructor. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  811. )
  812. + "\n\n"
  813. )
  814. index += 1
  815. if len(class_def.methods) > 0:
  816. f.write(make_heading("Method Descriptions", "-"))
  817. index = 0
  818. for method_list in class_def.methods.values():
  819. for i, m in enumerate(method_list):
  820. if index != 0:
  821. f.write("----\n\n")
  822. if i == 0:
  823. f.write(f".. _class_{class_name}_method_{m.name}:\n\n")
  824. ret_type, signature = make_method_signature(class_def, m, "", state)
  825. f.write(f"- {ret_type} {signature}\n\n")
  826. if m.description is not None and m.description.strip() != "":
  827. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  828. else:
  829. f.write(".. container:: contribute\n\n\t")
  830. f.write(
  831. translate(
  832. "There is currently no description for this method. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  833. )
  834. + "\n\n"
  835. )
  836. index += 1
  837. if len(class_def.operators) > 0:
  838. f.write(make_heading("Operator Descriptions", "-"))
  839. index = 0
  840. for method_list in class_def.operators.values():
  841. for i, m in enumerate(method_list):
  842. if index != 0:
  843. f.write("----\n\n")
  844. if i == 0:
  845. f.write(
  846. f".. _class_{class_name}_operator_{sanitize_operator_name(m.name, state)}_{m.return_type.type_name}:\n\n"
  847. )
  848. ret_type, signature = make_method_signature(class_def, m, "", state)
  849. f.write(f"- {ret_type} {signature}\n\n")
  850. if m.description is not None and m.description.strip() != "":
  851. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  852. else:
  853. f.write(".. container:: contribute\n\n\t")
  854. f.write(
  855. translate(
  856. "There is currently no description for this operator. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  857. )
  858. + "\n\n"
  859. )
  860. index += 1
  861. # Theme property descriptions
  862. if len(class_def.theme_items) > 0:
  863. f.write(make_heading("Theme Property Descriptions", "-"))
  864. index = 0
  865. for theme_item_def in class_def.theme_items.values():
  866. if index != 0:
  867. f.write("----\n\n")
  868. f.write(f".. _class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}:\n\n")
  869. f.write(f"- {theme_item_def.type_name.to_rst(state)} **{theme_item_def.name}**\n\n")
  870. info = []
  871. if theme_item_def.default_value is not None:
  872. # Not using translate() for now as it breaks table formatting.
  873. info.append(("*Default*", theme_item_def.default_value))
  874. if len(info) > 0:
  875. format_table(f, info)
  876. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  877. f.write(f"{format_text_block(theme_item_def.text.strip(), theme_item_def, state)}\n\n")
  878. else:
  879. f.write(".. container:: contribute\n\n\t")
  880. f.write(
  881. translate(
  882. "There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  883. )
  884. + "\n\n"
  885. )
  886. index += 1
  887. f.write(make_footer())
  888. def make_type(klass: str, state: State) -> str:
  889. if klass.find("*") != -1: # Pointer, ignore
  890. return klass
  891. link_type = klass
  892. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  893. link_type = link_type[:-2]
  894. if link_type in state.classes:
  895. return f":ref:`{klass}<class_{link_type}>`"
  896. print_error(f'{state.current_class}.xml: Unresolved type "{klass}".', state)
  897. return klass
  898. def make_enum(t: str, state: State) -> str:
  899. p = t.find(".")
  900. if p >= 0:
  901. c = t[0:p]
  902. e = t[p + 1 :]
  903. # Variant enums live in GlobalScope but still use periods.
  904. if c == "Variant":
  905. c = "@GlobalScope"
  906. e = "Variant." + e
  907. else:
  908. c = state.current_class
  909. e = t
  910. if c in state.classes and e not in state.classes[c].enums:
  911. c = "@GlobalScope"
  912. if c in state.classes and e in state.classes[c].enums:
  913. return f":ref:`{e}<enum_{c}_{e}>`"
  914. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  915. if f"{c}.{e}" != "Vector3.Axis":
  916. print_error(f'{state.current_class}.xml: Unresolved enum "{t}".', state)
  917. return t
  918. def make_method_signature(
  919. class_def: ClassDef, definition: Union[AnnotationDef, MethodDef, SignalDef], ref_type: str, state: State
  920. ) -> Tuple[str, str]:
  921. ret_type = ""
  922. if isinstance(definition, MethodDef):
  923. ret_type = definition.return_type.to_rst(state)
  924. qualifiers = None
  925. if isinstance(definition, (MethodDef, AnnotationDef)):
  926. qualifiers = definition.qualifiers
  927. out = ""
  928. if isinstance(definition, MethodDef) and ref_type != "":
  929. if ref_type == "operator":
  930. op_name = definition.name.replace("<", "\\<") # So operator "<" gets correctly displayed.
  931. out += f":ref:`{op_name}<class_{class_def.name}_{ref_type}_{sanitize_operator_name(definition.name, state)}_{definition.return_type.type_name}>` "
  932. else:
  933. out += f":ref:`{definition.name}<class_{class_def.name}_{ref_type}_{definition.name}>` "
  934. else:
  935. out += f"**{definition.name}** "
  936. out += "**(**"
  937. for i, arg in enumerate(definition.parameters):
  938. if i > 0:
  939. out += ", "
  940. else:
  941. out += " "
  942. out += f"{arg.type_name.to_rst(state)} {arg.name}"
  943. if arg.default_value is not None:
  944. out += f"={arg.default_value}"
  945. if qualifiers is not None and "vararg" in qualifiers:
  946. if len(definition.parameters) > 0:
  947. out += ", ..."
  948. else:
  949. out += " ..."
  950. out += " **)**"
  951. if qualifiers is not None:
  952. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  953. # See `make_footer()` for descriptions.
  954. for qualifier in qualifiers.split():
  955. out += f" |{qualifier}|"
  956. return ret_type, out
  957. def make_heading(title: str, underline: str, l10n: bool = True) -> str:
  958. if l10n:
  959. new_title = translate(title)
  960. if new_title != title:
  961. title = new_title
  962. underline *= 2 # Double length to handle wide chars.
  963. return f"{title}\n{(underline * len(title))}\n\n"
  964. def make_footer() -> str:
  965. # Generate reusable abbreviation substitutions.
  966. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  967. virtual_msg = translate("This method should typically be overridden by the user to have any effect.")
  968. const_msg = translate("This method has no side effects. It doesn't modify any of the instance's member variables.")
  969. vararg_msg = translate("This method accepts any number of arguments after the ones described here.")
  970. constructor_msg = translate("This method is used to construct a type.")
  971. static_msg = translate(
  972. "This method doesn't need an instance to be called, so it can be called directly using the class name."
  973. )
  974. operator_msg = translate("This method describes a valid operator to use with this type as left-hand operand.")
  975. return (
  976. f".. |virtual| replace:: :abbr:`virtual ({virtual_msg})`\n"
  977. f".. |const| replace:: :abbr:`const ({const_msg})`\n"
  978. f".. |vararg| replace:: :abbr:`vararg ({vararg_msg})`\n"
  979. f".. |constructor| replace:: :abbr:`constructor ({constructor_msg})`\n"
  980. f".. |static| replace:: :abbr:`static ({static_msg})`\n"
  981. f".. |operator| replace:: :abbr:`operator ({operator_msg})`\n"
  982. )
  983. def make_link(url: str, title: str) -> str:
  984. match = GODOT_DOCS_PATTERN.search(url)
  985. if match:
  986. groups = match.groups()
  987. if match.lastindex == 2:
  988. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  989. # `#calling-javascript-from-script in Exporting For Web`
  990. # Or use the title if provided.
  991. if title != "":
  992. return f"`{title} <../{groups[0]}.html{groups[1]}>`__"
  993. return f"`{groups[1]} <../{groups[0]}.html{groups[1]}>`__ in :doc:`../{groups[0]}`"
  994. elif match.lastindex == 1:
  995. # Doc reference, for example:
  996. # `Math`
  997. if title != "":
  998. return f":doc:`{title} <../{groups[0]}>`"
  999. return f":doc:`../{groups[0]}`"
  1000. # External link, for example:
  1001. # `http://enet.bespin.org/usergroup0.html`
  1002. if title != "":
  1003. return f"`{title} <{url}>`__"
  1004. return f"`{url} <{url}>`__"
  1005. def make_rst_index(grouped_classes: Dict[str, List[str]], dry_run: bool, output_dir: str) -> None:
  1006. if dry_run:
  1007. f = open(os.devnull, "w", encoding="utf-8")
  1008. else:
  1009. f = open(os.path.join(output_dir, "index.rst"), "w", encoding="utf-8")
  1010. # Remove the "Edit on Github" button from the online docs page.
  1011. f.write(":github_url: hide\n\n")
  1012. # Warn contributors not to edit this file directly.
  1013. # Also provide links to the source files for reference.
  1014. git_branch = get_git_branch()
  1015. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  1016. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  1017. f.write(".. Generated automatically from Godot engine sources.\n")
  1018. f.write(f".. Generator: {generator_github_url}.\n\n")
  1019. f.write(".. _doc_class_reference:\n\n")
  1020. main_title = translate("All classes")
  1021. f.write(f"{main_title}\n")
  1022. f.write(f"{'=' * len(main_title)}\n\n")
  1023. for group_name in CLASS_GROUPS:
  1024. if group_name in grouped_classes:
  1025. group_title = translate(CLASS_GROUPS[group_name])
  1026. f.write(f"{group_title}\n")
  1027. f.write(f"{'=' * len(group_title)}\n\n")
  1028. f.write(".. toctree::\n")
  1029. f.write(" :maxdepth: 1\n")
  1030. f.write(f" :name: toc-class-ref-{group_name}s\n")
  1031. f.write("\n")
  1032. if group_name in CLASS_GROUPS_BASE:
  1033. f.write(f" class_{CLASS_GROUPS_BASE[group_name].lower()}\n")
  1034. for class_name in grouped_classes[group_name]:
  1035. f.write(f" class_{class_name.lower()}\n")
  1036. f.write("\n")
  1037. # Formatting helpers.
  1038. RESERVED_FORMATTING_TAGS = ["i", "b", "u", "code", "kbd", "center", "url", "br"]
  1039. RESERVED_CODEBLOCK_TAGS = ["codeblocks", "codeblock", "gdscript", "csharp"]
  1040. RESERVED_CROSSLINK_TAGS = ["method", "member", "signal", "constant", "enum", "annotation", "theme_item", "param"]
  1041. def is_in_tagset(tag_text: str, tagset: List[str]) -> bool:
  1042. for tag in tagset:
  1043. # Complete match.
  1044. if tag_text == tag:
  1045. return True
  1046. # Tag with arguments.
  1047. if tag_text.startswith(tag + " "):
  1048. return True
  1049. # Tag with arguments, special case for [url].
  1050. if tag_text.startswith(tag + "="):
  1051. return True
  1052. return False
  1053. def format_text_block(
  1054. text: str,
  1055. context: Union[DefinitionBase, None],
  1056. state: State,
  1057. ) -> str:
  1058. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  1059. pos = 0
  1060. while True:
  1061. pos = text.find("\n", pos)
  1062. if pos == -1:
  1063. break
  1064. pre_text = text[:pos]
  1065. indent_level = 0
  1066. while pos + 1 < len(text) and text[pos + 1] == "\t":
  1067. pos += 1
  1068. indent_level += 1
  1069. post_text = text[pos + 1 :]
  1070. # Handle codeblocks
  1071. if (
  1072. post_text.startswith("[codeblock]")
  1073. or post_text.startswith("[gdscript]")
  1074. or post_text.startswith("[csharp]")
  1075. ):
  1076. block_type = post_text[1:].split("]")[0]
  1077. result = format_codeblock(block_type, post_text, indent_level, state)
  1078. if result is None:
  1079. return ""
  1080. text = f"{pre_text}{result[0]}"
  1081. pos += result[1] - indent_level
  1082. # Handle normal text
  1083. else:
  1084. text = f"{pre_text}\n\n{post_text}"
  1085. pos += 2 - indent_level
  1086. next_brac_pos = text.find("[")
  1087. text = escape_rst(text, next_brac_pos)
  1088. context_name = format_context_name(context)
  1089. # Handle [tags]
  1090. inside_code = False
  1091. inside_code_tag = ""
  1092. inside_code_tabs = False
  1093. pos = 0
  1094. tag_depth = 0
  1095. while True:
  1096. pos = text.find("[", pos)
  1097. if pos == -1:
  1098. break
  1099. endq_pos = text.find("]", pos + 1)
  1100. if endq_pos == -1:
  1101. break
  1102. pre_text = text[:pos]
  1103. post_text = text[endq_pos + 1 :]
  1104. tag_text = text[pos + 1 : endq_pos]
  1105. escape_pre = False
  1106. escape_post = False
  1107. # Tag is a reference to a class.
  1108. if tag_text in state.classes:
  1109. if tag_text == state.current_class:
  1110. # Don't create a link to the same class, format it as inline code.
  1111. tag_text = f"``{tag_text}``"
  1112. else:
  1113. tag_text = make_type(tag_text, state)
  1114. escape_pre = True
  1115. escape_post = True
  1116. # Tag is a cross-reference or a formatting directive.
  1117. else:
  1118. cmd = tag_text
  1119. space_pos = tag_text.find(" ")
  1120. # Anything identified as a tag inside of a code block is valid,
  1121. # unless it's a matching closing tag.
  1122. if inside_code:
  1123. # Exiting codeblocks and inline code tags.
  1124. if inside_code_tag == cmd[1:]:
  1125. if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp":
  1126. tag_text = ""
  1127. tag_depth -= 1
  1128. inside_code = False
  1129. # Strip newline if the tag was alone on one
  1130. if pre_text[-1] == "\n":
  1131. pre_text = pre_text[:-1]
  1132. elif cmd == "/code":
  1133. tag_text = "``"
  1134. tag_depth -= 1
  1135. inside_code = False
  1136. escape_post = True
  1137. else:
  1138. if cmd.startswith("/"):
  1139. print_warning(
  1140. f'{state.current_class}.xml: Potential error inside of a code tag, found a string that looks like a closing tag "[{cmd}]" in {context_name}.',
  1141. state,
  1142. )
  1143. tag_text = f"[{tag_text}]"
  1144. # Entering codeblocks and inline code tags.
  1145. elif cmd == "codeblocks":
  1146. tag_depth += 1
  1147. tag_text = "\n.. tabs::"
  1148. inside_code_tabs = True
  1149. elif cmd == "/codeblocks":
  1150. tag_depth -= 1
  1151. tag_text = ""
  1152. inside_code_tabs = False
  1153. elif cmd == "codeblock" or cmd == "gdscript" or cmd == "csharp":
  1154. tag_depth += 1
  1155. if cmd == "gdscript":
  1156. if not inside_code_tabs:
  1157. print_error(
  1158. f"{state.current_class}.xml: GDScript code block is used outside of [codeblocks] in {context_name}.",
  1159. state,
  1160. )
  1161. tag_text = "\n .. code-tab:: gdscript\n"
  1162. elif cmd == "csharp":
  1163. if not inside_code_tabs:
  1164. print_error(
  1165. f"{state.current_class}.xml: C# code block is used outside of [codeblocks] in {context_name}.",
  1166. state,
  1167. )
  1168. tag_text = "\n .. code-tab:: csharp\n"
  1169. else:
  1170. tag_text = "\n::\n"
  1171. inside_code = True
  1172. inside_code_tag = cmd
  1173. elif cmd == "code":
  1174. tag_text = "``"
  1175. tag_depth += 1
  1176. inside_code = True
  1177. inside_code_tag = cmd
  1178. escape_pre = True
  1179. # Cross-references to items in this or other class documentation pages.
  1180. elif is_in_tagset(cmd, RESERVED_CROSSLINK_TAGS):
  1181. link_type: str = ""
  1182. link_target: str = ""
  1183. if space_pos >= 0:
  1184. link_type = tag_text[:space_pos]
  1185. link_target = tag_text[space_pos + 1 :].strip()
  1186. if link_target == "":
  1187. print_error(
  1188. f'{state.current_class}.xml: Empty cross-reference link "{cmd}" in {context_name}.',
  1189. state,
  1190. )
  1191. tag_text = ""
  1192. else:
  1193. if (
  1194. cmd.startswith("method")
  1195. or cmd.startswith("constructor")
  1196. or cmd.startswith("operator")
  1197. or cmd.startswith("member")
  1198. or cmd.startswith("signal")
  1199. or cmd.startswith("annotation")
  1200. or cmd.startswith("theme_item")
  1201. or cmd.startswith("constant")
  1202. ):
  1203. if link_target.find(".") != -1:
  1204. ss = link_target.split(".")
  1205. if len(ss) > 2:
  1206. print_error(
  1207. f'{state.current_class}.xml: Bad reference "{link_target}" in {context_name}.',
  1208. state,
  1209. )
  1210. class_param, method_param = ss
  1211. else:
  1212. class_param = state.current_class
  1213. method_param = link_target
  1214. # Default to the tag command name. This works by default for most tags,
  1215. # but member and theme_item have special cases.
  1216. ref_type = "_{}".format(link_type)
  1217. if link_type == "member":
  1218. ref_type = "_property"
  1219. if class_param in state.classes:
  1220. class_def = state.classes[class_param]
  1221. if cmd.startswith("method") and method_param not in class_def.methods:
  1222. print_error(
  1223. f'{state.current_class}.xml: Unresolved method reference "{link_target}" in {context_name}.',
  1224. state,
  1225. )
  1226. elif cmd.startswith("constructor") and method_param not in class_def.constructors:
  1227. print_error(
  1228. f'{state.current_class}.xml: Unresolved constructor reference "{link_target}" in {context_name}.',
  1229. state,
  1230. )
  1231. elif cmd.startswith("operator") and method_param not in class_def.operators:
  1232. print_error(
  1233. f'{state.current_class}.xml: Unresolved operator reference "{link_target}" in {context_name}.',
  1234. state,
  1235. )
  1236. elif cmd.startswith("member") and method_param not in class_def.properties:
  1237. print_error(
  1238. f'{state.current_class}.xml: Unresolved member reference "{link_target}" in {context_name}.',
  1239. state,
  1240. )
  1241. elif cmd.startswith("signal") and method_param not in class_def.signals:
  1242. print_error(
  1243. f'{state.current_class}.xml: Unresolved signal reference "{link_target}" in {context_name}.',
  1244. state,
  1245. )
  1246. elif cmd.startswith("annotation") and method_param not in class_def.annotations:
  1247. print_error(
  1248. f'{state.current_class}.xml: Unresolved annotation reference "{link_target}" in {context_name}.',
  1249. state,
  1250. )
  1251. elif cmd.startswith("theme_item"):
  1252. if method_param not in class_def.theme_items:
  1253. print_error(
  1254. f'{state.current_class}.xml: Unresolved theme item reference "{link_target}" in {context_name}.',
  1255. state,
  1256. )
  1257. else:
  1258. # Needs theme data type to be properly linked, which we cannot get without a class.
  1259. name = class_def.theme_items[method_param].data_name
  1260. ref_type = f"_theme_{name}"
  1261. elif cmd.startswith("constant"):
  1262. found = False
  1263. # Search in the current class
  1264. search_class_defs = [class_def]
  1265. if link_target.find(".") == -1:
  1266. # Also search in @GlobalScope as a last resort if no class was specified
  1267. search_class_defs.append(state.classes["@GlobalScope"])
  1268. for search_class_def in search_class_defs:
  1269. if method_param in search_class_def.constants:
  1270. class_param = search_class_def.name
  1271. found = True
  1272. else:
  1273. for enum in search_class_def.enums.values():
  1274. if method_param in enum.values:
  1275. class_param = search_class_def.name
  1276. found = True
  1277. break
  1278. if not found:
  1279. print_error(
  1280. f'{state.current_class}.xml: Unresolved constant reference "{link_target}" in {context_name}.',
  1281. state,
  1282. )
  1283. else:
  1284. print_error(
  1285. f'{state.current_class}.xml: Unresolved type reference "{class_param}" in method reference "{link_target}" in {context_name}.',
  1286. state,
  1287. )
  1288. repl_text = method_param
  1289. if class_param != state.current_class:
  1290. repl_text = f"{class_param}.{method_param}"
  1291. tag_text = f":ref:`{repl_text}<class_{class_param}{ref_type}_{method_param}>`"
  1292. escape_pre = True
  1293. escape_post = True
  1294. elif cmd.startswith("enum"):
  1295. tag_text = make_enum(link_target, state)
  1296. escape_pre = True
  1297. escape_post = True
  1298. elif cmd.startswith("param"):
  1299. valid_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1300. if not valid_context:
  1301. print_error(
  1302. f'{state.current_class}.xml: Argument reference "{link_target}" used outside of method, signal, or annotation context in {context_name}.',
  1303. state,
  1304. )
  1305. else:
  1306. context_params: List[ParameterDef] = context.parameters # type: ignore
  1307. found = False
  1308. for param_def in context_params:
  1309. if param_def.name == link_target:
  1310. found = True
  1311. break
  1312. if not found:
  1313. print_error(
  1314. f'{state.current_class}.xml: Unresolved argument reference "{link_target}" in {context_name}.',
  1315. state,
  1316. )
  1317. tag_text = f"``{link_target}``"
  1318. escape_pre = True
  1319. escape_post = True
  1320. # Formatting directives.
  1321. elif is_in_tagset(cmd, ["url"]):
  1322. if cmd.startswith("url="):
  1323. # URLs are handled in full here as we need to extract the optional link
  1324. # title to use `make_link`.
  1325. link_url = cmd[4:]
  1326. endurl_pos = text.find("[/url]", endq_pos + 1)
  1327. if endurl_pos == -1:
  1328. print_error(
  1329. f"{state.current_class}.xml: Tag depth mismatch for [url]: no closing [/url] in {context_name}.",
  1330. state,
  1331. )
  1332. break
  1333. link_title = text[endq_pos + 1 : endurl_pos]
  1334. tag_text = make_link(link_url, link_title)
  1335. pre_text = text[:pos]
  1336. post_text = text[endurl_pos + 6 :]
  1337. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1338. pre_text += "\ "
  1339. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1340. post_text = "\ " + post_text
  1341. text = pre_text + tag_text + post_text
  1342. pos = len(pre_text) + len(tag_text)
  1343. continue
  1344. else:
  1345. print_error(
  1346. f'{state.current_class}.xml: Misformatted [url] tag "{cmd}" in {context_name}.',
  1347. state,
  1348. )
  1349. elif cmd == "br":
  1350. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  1351. tag_text = "\n\n"
  1352. # Strip potential leading spaces
  1353. while post_text[0] == " ":
  1354. post_text = post_text[1:]
  1355. elif cmd == "center" or cmd == "/center":
  1356. if cmd == "/center":
  1357. tag_depth -= 1
  1358. else:
  1359. tag_depth += 1
  1360. tag_text = ""
  1361. elif cmd == "i" or cmd == "/i":
  1362. if cmd == "/i":
  1363. tag_depth -= 1
  1364. escape_post = True
  1365. else:
  1366. tag_depth += 1
  1367. escape_pre = True
  1368. tag_text = "*"
  1369. elif cmd == "b" or cmd == "/b":
  1370. if cmd == "/b":
  1371. tag_depth -= 1
  1372. escape_post = True
  1373. else:
  1374. tag_depth += 1
  1375. escape_pre = True
  1376. tag_text = "**"
  1377. elif cmd == "u" or cmd == "/u":
  1378. if cmd == "/u":
  1379. tag_depth -= 1
  1380. escape_post = True
  1381. else:
  1382. tag_depth += 1
  1383. escape_pre = True
  1384. tag_text = ""
  1385. elif cmd == "kbd" or cmd == "/kbd":
  1386. tag_text = "`"
  1387. if cmd == "/kbd":
  1388. tag_depth -= 1
  1389. escape_post = True
  1390. else:
  1391. tag_text = ":kbd:" + tag_text
  1392. tag_depth += 1
  1393. escape_pre = True
  1394. # Invalid syntax checks.
  1395. elif cmd.startswith("/"):
  1396. print_error(f'{state.current_class}.xml: Unrecognized closing tag "{cmd}" in {context_name}.', state)
  1397. tag_text = f"[{tag_text}]"
  1398. else:
  1399. print_error(f'{state.current_class}.xml: Unrecognized opening tag "{cmd}" in {context_name}.', state)
  1400. tag_text = f"``{tag_text}``"
  1401. escape_pre = True
  1402. escape_post = True
  1403. # Properly escape things like `[Node]s`
  1404. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1405. pre_text += "\ "
  1406. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1407. post_text = "\ " + post_text
  1408. next_brac_pos = post_text.find("[", 0)
  1409. iter_pos = 0
  1410. while not inside_code:
  1411. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  1412. if iter_pos == -1:
  1413. break
  1414. post_text = f"{post_text[:iter_pos]}\*{post_text[iter_pos + 1 :]}"
  1415. iter_pos += 2
  1416. iter_pos = 0
  1417. while not inside_code:
  1418. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  1419. if iter_pos == -1:
  1420. break
  1421. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  1422. post_text = f"{post_text[:iter_pos]}\_{post_text[iter_pos + 1 :]}"
  1423. iter_pos += 2
  1424. else:
  1425. iter_pos += 1
  1426. text = pre_text + tag_text + post_text
  1427. pos = len(pre_text) + len(tag_text)
  1428. if tag_depth > 0:
  1429. print_error(
  1430. f"{state.current_class}.xml: Tag depth mismatch: too many (or too few) open/close tags in {context_name}.",
  1431. state,
  1432. )
  1433. return text
  1434. def format_context_name(context: Union[DefinitionBase, None]) -> str:
  1435. context_name: str = "unknown context"
  1436. if context is not None:
  1437. context_name = f'{context.definition_name} "{context.name}" description'
  1438. return context_name
  1439. def escape_rst(text: str, until_pos: int = -1) -> str:
  1440. # Escape \ character, otherwise it ends up as an escape character in rst
  1441. pos = 0
  1442. while True:
  1443. pos = text.find("\\", pos, until_pos)
  1444. if pos == -1:
  1445. break
  1446. text = f"{text[:pos]}\\\\{text[pos + 1 :]}"
  1447. pos += 2
  1448. # Escape * character to avoid interpreting it as emphasis
  1449. pos = 0
  1450. while True:
  1451. pos = text.find("*", pos, until_pos)
  1452. if pos == -1:
  1453. break
  1454. text = f"{text[:pos]}\*{text[pos + 1 :]}"
  1455. pos += 2
  1456. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  1457. pos = 0
  1458. while True:
  1459. pos = text.find("_", pos, until_pos)
  1460. if pos == -1:
  1461. break
  1462. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  1463. text = f"{text[:pos]}\_{text[pos + 1 :]}"
  1464. pos += 2
  1465. else:
  1466. pos += 1
  1467. return text
  1468. def format_codeblock(code_type: str, post_text: str, indent_level: int, state: State) -> Union[Tuple[str, int], None]:
  1469. end_pos = post_text.find("[/" + code_type + "]")
  1470. if end_pos == -1:
  1471. print_error(f"{state.current_class}.xml: [{code_type}] without a closing tag.", state)
  1472. return None
  1473. code_text = post_text[len(f"[{code_type}]") : end_pos]
  1474. post_text = post_text[end_pos:]
  1475. # Remove extraneous tabs
  1476. code_pos = 0
  1477. while True:
  1478. code_pos = code_text.find("\n", code_pos)
  1479. if code_pos == -1:
  1480. break
  1481. to_skip = 0
  1482. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  1483. to_skip += 1
  1484. if to_skip > indent_level:
  1485. print_error(
  1486. f"{state.current_class}.xml: Four spaces should be used for indentation within [{code_type}].",
  1487. state,
  1488. )
  1489. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  1490. code_text = f"{code_text[:code_pos]}\n"
  1491. code_pos += 1
  1492. else:
  1493. code_text = f"{code_text[:code_pos]}\n {code_text[code_pos + to_skip + 1 :]}"
  1494. code_pos += 5 - to_skip
  1495. return (f"\n[{code_type}]{code_text}{post_text}", len(f"\n[{code_type}]{code_text}"))
  1496. def format_table(f: TextIO, data: List[Tuple[Optional[str], ...]], remove_empty_columns: bool = False) -> None:
  1497. if len(data) == 0:
  1498. return
  1499. column_sizes = [0] * len(data[0])
  1500. for row in data:
  1501. for i, text in enumerate(row):
  1502. text_length = len(text or "")
  1503. if text_length > column_sizes[i]:
  1504. column_sizes[i] = text_length
  1505. sep = ""
  1506. for size in column_sizes:
  1507. if size == 0 and remove_empty_columns:
  1508. continue
  1509. sep += "+" + "-" * (size + 2)
  1510. sep += "+\n"
  1511. f.write(sep)
  1512. for row in data:
  1513. row_text = "|"
  1514. for i, text in enumerate(row):
  1515. if column_sizes[i] == 0 and remove_empty_columns:
  1516. continue
  1517. row_text += f' {(text or "").ljust(column_sizes[i])} |'
  1518. row_text += "\n"
  1519. f.write(row_text)
  1520. f.write(sep)
  1521. f.write("\n")
  1522. def sanitize_operator_name(dirty_name: str, state: State) -> str:
  1523. clear_name = dirty_name.replace("operator ", "")
  1524. if clear_name == "!=":
  1525. clear_name = "neq"
  1526. elif clear_name == "==":
  1527. clear_name = "eq"
  1528. elif clear_name == "<":
  1529. clear_name = "lt"
  1530. elif clear_name == "<=":
  1531. clear_name = "lte"
  1532. elif clear_name == ">":
  1533. clear_name = "gt"
  1534. elif clear_name == ">=":
  1535. clear_name = "gte"
  1536. elif clear_name == "+":
  1537. clear_name = "sum"
  1538. elif clear_name == "-":
  1539. clear_name = "dif"
  1540. elif clear_name == "*":
  1541. clear_name = "mul"
  1542. elif clear_name == "/":
  1543. clear_name = "div"
  1544. elif clear_name == "%":
  1545. clear_name = "mod"
  1546. elif clear_name == "**":
  1547. clear_name = "pow"
  1548. elif clear_name == "unary+":
  1549. clear_name = "unplus"
  1550. elif clear_name == "unary-":
  1551. clear_name = "unminus"
  1552. elif clear_name == "<<":
  1553. clear_name = "bwsl"
  1554. elif clear_name == ">>":
  1555. clear_name = "bwsr"
  1556. elif clear_name == "&":
  1557. clear_name = "bwand"
  1558. elif clear_name == "|":
  1559. clear_name = "bwor"
  1560. elif clear_name == "^":
  1561. clear_name = "bwxor"
  1562. elif clear_name == "~":
  1563. clear_name = "bwnot"
  1564. elif clear_name == "[]":
  1565. clear_name = "idx"
  1566. else:
  1567. clear_name = "xxx"
  1568. print_error(f'Unsupported operator type "{dirty_name}", please add the missing rule.', state)
  1569. return clear_name
  1570. def indent_bullets(text: str) -> str:
  1571. # Take the text and check each line for a bullet point represented by "-".
  1572. # Where found, indent the given line by a further "\t".
  1573. # Used to properly indent bullet points contained in the description for enum values.
  1574. # Ignore the first line - text will be prepended to it so bullet points wouldn't work anyway.
  1575. bullet_points = "-"
  1576. lines = text.splitlines(keepends=True)
  1577. for line_index, line in enumerate(lines[1:], start=1):
  1578. pos = 0
  1579. while pos < len(line) and line[pos] == "\t":
  1580. pos += 1
  1581. if pos < len(line) and line[pos] in bullet_points:
  1582. lines[line_index] = f"{line[:pos]}\t{line[pos:]}"
  1583. return "".join(lines)
  1584. if __name__ == "__main__":
  1585. main()