make_rst.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980
  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. out = f".. _class_{class_name}_operator_{sanitize_operator_name(m.name, state)}"
  845. for parameter in m.parameters:
  846. out += f"_{parameter.type_name.type_name}"
  847. out += f":\n\n"
  848. f.write(out)
  849. ret_type, signature = make_method_signature(class_def, m, "", state)
  850. f.write(f"- {ret_type} {signature}\n\n")
  851. if m.description is not None and m.description.strip() != "":
  852. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  853. else:
  854. f.write(".. container:: contribute\n\n\t")
  855. f.write(
  856. translate(
  857. "There is currently no description for this operator. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  858. )
  859. + "\n\n"
  860. )
  861. index += 1
  862. # Theme property descriptions
  863. if len(class_def.theme_items) > 0:
  864. f.write(make_heading("Theme Property Descriptions", "-"))
  865. index = 0
  866. for theme_item_def in class_def.theme_items.values():
  867. if index != 0:
  868. f.write("----\n\n")
  869. f.write(f".. _class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}:\n\n")
  870. f.write(f"- {theme_item_def.type_name.to_rst(state)} **{theme_item_def.name}**\n\n")
  871. info = []
  872. if theme_item_def.default_value is not None:
  873. # Not using translate() for now as it breaks table formatting.
  874. info.append(("*Default*", theme_item_def.default_value))
  875. if len(info) > 0:
  876. format_table(f, info)
  877. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  878. f.write(f"{format_text_block(theme_item_def.text.strip(), theme_item_def, state)}\n\n")
  879. else:
  880. f.write(".. container:: contribute\n\n\t")
  881. f.write(
  882. translate(
  883. "There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  884. )
  885. + "\n\n"
  886. )
  887. index += 1
  888. f.write(make_footer())
  889. def make_type(klass: str, state: State) -> str:
  890. if klass.find("*") != -1: # Pointer, ignore
  891. return klass
  892. link_type = klass
  893. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  894. link_type = link_type[:-2]
  895. if link_type in state.classes:
  896. return f":ref:`{klass}<class_{link_type}>`"
  897. print_error(f'{state.current_class}.xml: Unresolved type "{klass}".', state)
  898. return klass
  899. def make_enum(t: str, state: State) -> str:
  900. p = t.find(".")
  901. if p >= 0:
  902. c = t[0:p]
  903. e = t[p + 1 :]
  904. # Variant enums live in GlobalScope but still use periods.
  905. if c == "Variant":
  906. c = "@GlobalScope"
  907. e = "Variant." + e
  908. else:
  909. c = state.current_class
  910. e = t
  911. if c in state.classes and e not in state.classes[c].enums:
  912. c = "@GlobalScope"
  913. if c in state.classes and e in state.classes[c].enums:
  914. return f":ref:`{e}<enum_{c}_{e}>`"
  915. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  916. if f"{c}.{e}" != "Vector3.Axis":
  917. print_error(f'{state.current_class}.xml: Unresolved enum "{t}".', state)
  918. return t
  919. def make_method_signature(
  920. class_def: ClassDef, definition: Union[AnnotationDef, MethodDef, SignalDef], ref_type: str, state: State
  921. ) -> Tuple[str, str]:
  922. ret_type = ""
  923. if isinstance(definition, MethodDef):
  924. ret_type = definition.return_type.to_rst(state)
  925. qualifiers = None
  926. if isinstance(definition, (MethodDef, AnnotationDef)):
  927. qualifiers = definition.qualifiers
  928. out = ""
  929. if isinstance(definition, MethodDef) and ref_type != "":
  930. if ref_type == "operator":
  931. op_name = definition.name.replace("<", "\\<") # So operator "<" gets correctly displayed.
  932. out += f":ref:`{op_name}<class_{class_def.name}_{ref_type}_{sanitize_operator_name(definition.name, state)}"
  933. for parameter in definition.parameters:
  934. out += f"_{parameter.type_name.type_name}"
  935. out += f">` "
  936. else:
  937. out += f":ref:`{definition.name}<class_{class_def.name}_{ref_type}_{definition.name}>` "
  938. else:
  939. out += f"**{definition.name}** "
  940. out += "**(**"
  941. for i, arg in enumerate(definition.parameters):
  942. if i > 0:
  943. out += ", "
  944. else:
  945. out += " "
  946. out += f"{arg.type_name.to_rst(state)} {arg.name}"
  947. if arg.default_value is not None:
  948. out += f"={arg.default_value}"
  949. if qualifiers is not None and "vararg" in qualifiers:
  950. if len(definition.parameters) > 0:
  951. out += ", ..."
  952. else:
  953. out += " ..."
  954. out += " **)**"
  955. if qualifiers is not None:
  956. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  957. # See `make_footer()` for descriptions.
  958. for qualifier in qualifiers.split():
  959. out += f" |{qualifier}|"
  960. return ret_type, out
  961. def make_heading(title: str, underline: str, l10n: bool = True) -> str:
  962. if l10n:
  963. new_title = translate(title)
  964. if new_title != title:
  965. title = new_title
  966. underline *= 2 # Double length to handle wide chars.
  967. return f"{title}\n{(underline * len(title))}\n\n"
  968. def make_footer() -> str:
  969. # Generate reusable abbreviation substitutions.
  970. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  971. virtual_msg = translate("This method should typically be overridden by the user to have any effect.")
  972. const_msg = translate("This method has no side effects. It doesn't modify any of the instance's member variables.")
  973. vararg_msg = translate("This method accepts any number of arguments after the ones described here.")
  974. constructor_msg = translate("This method is used to construct a type.")
  975. static_msg = translate(
  976. "This method doesn't need an instance to be called, so it can be called directly using the class name."
  977. )
  978. operator_msg = translate("This method describes a valid operator to use with this type as left-hand operand.")
  979. return (
  980. f".. |virtual| replace:: :abbr:`virtual ({virtual_msg})`\n"
  981. f".. |const| replace:: :abbr:`const ({const_msg})`\n"
  982. f".. |vararg| replace:: :abbr:`vararg ({vararg_msg})`\n"
  983. f".. |constructor| replace:: :abbr:`constructor ({constructor_msg})`\n"
  984. f".. |static| replace:: :abbr:`static ({static_msg})`\n"
  985. f".. |operator| replace:: :abbr:`operator ({operator_msg})`\n"
  986. )
  987. def make_link(url: str, title: str) -> str:
  988. match = GODOT_DOCS_PATTERN.search(url)
  989. if match:
  990. groups = match.groups()
  991. if match.lastindex == 2:
  992. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  993. # `#calling-javascript-from-script in Exporting For Web`
  994. # Or use the title if provided.
  995. if title != "":
  996. return f"`{title} <../{groups[0]}.html{groups[1]}>`__"
  997. return f"`{groups[1]} <../{groups[0]}.html{groups[1]}>`__ in :doc:`../{groups[0]}`"
  998. elif match.lastindex == 1:
  999. # Doc reference, for example:
  1000. # `Math`
  1001. if title != "":
  1002. return f":doc:`{title} <../{groups[0]}>`"
  1003. return f":doc:`../{groups[0]}`"
  1004. # External link, for example:
  1005. # `http://enet.bespin.org/usergroup0.html`
  1006. if title != "":
  1007. return f"`{title} <{url}>`__"
  1008. return f"`{url} <{url}>`__"
  1009. def make_rst_index(grouped_classes: Dict[str, List[str]], dry_run: bool, output_dir: str) -> None:
  1010. if dry_run:
  1011. f = open(os.devnull, "w", encoding="utf-8")
  1012. else:
  1013. f = open(os.path.join(output_dir, "index.rst"), "w", encoding="utf-8")
  1014. # Remove the "Edit on Github" button from the online docs page.
  1015. f.write(":github_url: hide\n\n")
  1016. # Warn contributors not to edit this file directly.
  1017. # Also provide links to the source files for reference.
  1018. git_branch = get_git_branch()
  1019. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  1020. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  1021. f.write(".. Generated automatically from Godot engine sources.\n")
  1022. f.write(f".. Generator: {generator_github_url}.\n\n")
  1023. f.write(".. _doc_class_reference:\n\n")
  1024. main_title = translate("All classes")
  1025. f.write(f"{main_title}\n")
  1026. f.write(f"{'=' * len(main_title)}\n\n")
  1027. for group_name in CLASS_GROUPS:
  1028. if group_name in grouped_classes:
  1029. group_title = translate(CLASS_GROUPS[group_name])
  1030. f.write(f"{group_title}\n")
  1031. f.write(f"{'=' * len(group_title)}\n\n")
  1032. f.write(".. toctree::\n")
  1033. f.write(" :maxdepth: 1\n")
  1034. f.write(f" :name: toc-class-ref-{group_name}s\n")
  1035. f.write("\n")
  1036. if group_name in CLASS_GROUPS_BASE:
  1037. f.write(f" class_{CLASS_GROUPS_BASE[group_name].lower()}\n")
  1038. for class_name in grouped_classes[group_name]:
  1039. f.write(f" class_{class_name.lower()}\n")
  1040. f.write("\n")
  1041. # Formatting helpers.
  1042. RESERVED_FORMATTING_TAGS = ["i", "b", "u", "code", "kbd", "center", "url", "br"]
  1043. RESERVED_CODEBLOCK_TAGS = ["codeblocks", "codeblock", "gdscript", "csharp"]
  1044. RESERVED_CROSSLINK_TAGS = ["method", "member", "signal", "constant", "enum", "annotation", "theme_item", "param"]
  1045. def is_in_tagset(tag_text: str, tagset: List[str]) -> bool:
  1046. for tag in tagset:
  1047. # Complete match.
  1048. if tag_text == tag:
  1049. return True
  1050. # Tag with arguments.
  1051. if tag_text.startswith(tag + " "):
  1052. return True
  1053. # Tag with arguments, special case for [url].
  1054. if tag_text.startswith(tag + "="):
  1055. return True
  1056. return False
  1057. def format_text_block(
  1058. text: str,
  1059. context: Union[DefinitionBase, None],
  1060. state: State,
  1061. ) -> str:
  1062. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  1063. pos = 0
  1064. while True:
  1065. pos = text.find("\n", pos)
  1066. if pos == -1:
  1067. break
  1068. pre_text = text[:pos]
  1069. indent_level = 0
  1070. while pos + 1 < len(text) and text[pos + 1] == "\t":
  1071. pos += 1
  1072. indent_level += 1
  1073. post_text = text[pos + 1 :]
  1074. # Handle codeblocks
  1075. if (
  1076. post_text.startswith("[codeblock]")
  1077. or post_text.startswith("[gdscript]")
  1078. or post_text.startswith("[csharp]")
  1079. ):
  1080. block_type = post_text[1:].split("]")[0]
  1081. result = format_codeblock(block_type, post_text, indent_level, state)
  1082. if result is None:
  1083. return ""
  1084. text = f"{pre_text}{result[0]}"
  1085. pos += result[1] - indent_level
  1086. # Handle normal text
  1087. else:
  1088. text = f"{pre_text}\n\n{post_text}"
  1089. pos += 2 - indent_level
  1090. next_brac_pos = text.find("[")
  1091. text = escape_rst(text, next_brac_pos)
  1092. context_name = format_context_name(context)
  1093. # Handle [tags]
  1094. inside_code = False
  1095. inside_code_tag = ""
  1096. inside_code_tabs = False
  1097. pos = 0
  1098. tag_depth = 0
  1099. while True:
  1100. pos = text.find("[", pos)
  1101. if pos == -1:
  1102. break
  1103. endq_pos = text.find("]", pos + 1)
  1104. if endq_pos == -1:
  1105. break
  1106. pre_text = text[:pos]
  1107. post_text = text[endq_pos + 1 :]
  1108. tag_text = text[pos + 1 : endq_pos]
  1109. escape_pre = False
  1110. escape_post = False
  1111. # Tag is a reference to a class.
  1112. if tag_text in state.classes:
  1113. if tag_text == state.current_class:
  1114. # Don't create a link to the same class, format it as inline code.
  1115. tag_text = f"``{tag_text}``"
  1116. else:
  1117. tag_text = make_type(tag_text, state)
  1118. escape_pre = True
  1119. escape_post = True
  1120. # Tag is a cross-reference or a formatting directive.
  1121. else:
  1122. cmd = tag_text
  1123. space_pos = tag_text.find(" ")
  1124. # Anything identified as a tag inside of a code block is valid,
  1125. # unless it's a matching closing tag.
  1126. if inside_code:
  1127. # Exiting codeblocks and inline code tags.
  1128. if inside_code_tag == cmd[1:]:
  1129. if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp":
  1130. tag_text = ""
  1131. tag_depth -= 1
  1132. inside_code = False
  1133. # Strip newline if the tag was alone on one
  1134. if pre_text[-1] == "\n":
  1135. pre_text = pre_text[:-1]
  1136. elif cmd == "/code":
  1137. tag_text = "``"
  1138. tag_depth -= 1
  1139. inside_code = False
  1140. escape_post = True
  1141. else:
  1142. if cmd.startswith("/"):
  1143. print_warning(
  1144. 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}.',
  1145. state,
  1146. )
  1147. tag_text = f"[{tag_text}]"
  1148. # Entering codeblocks and inline code tags.
  1149. elif cmd == "codeblocks":
  1150. tag_depth += 1
  1151. tag_text = "\n.. tabs::"
  1152. inside_code_tabs = True
  1153. elif cmd == "/codeblocks":
  1154. tag_depth -= 1
  1155. tag_text = ""
  1156. inside_code_tabs = False
  1157. elif cmd == "codeblock" or cmd == "gdscript" or cmd == "csharp":
  1158. tag_depth += 1
  1159. if cmd == "gdscript":
  1160. if not inside_code_tabs:
  1161. print_error(
  1162. f"{state.current_class}.xml: GDScript code block is used outside of [codeblocks] in {context_name}.",
  1163. state,
  1164. )
  1165. tag_text = "\n .. code-tab:: gdscript\n"
  1166. elif cmd == "csharp":
  1167. if not inside_code_tabs:
  1168. print_error(
  1169. f"{state.current_class}.xml: C# code block is used outside of [codeblocks] in {context_name}.",
  1170. state,
  1171. )
  1172. tag_text = "\n .. code-tab:: csharp\n"
  1173. else:
  1174. tag_text = "\n::\n"
  1175. inside_code = True
  1176. inside_code_tag = cmd
  1177. elif cmd == "code":
  1178. tag_text = "``"
  1179. tag_depth += 1
  1180. inside_code = True
  1181. inside_code_tag = cmd
  1182. escape_pre = True
  1183. # Cross-references to items in this or other class documentation pages.
  1184. elif is_in_tagset(cmd, RESERVED_CROSSLINK_TAGS):
  1185. link_type: str = ""
  1186. link_target: str = ""
  1187. if space_pos >= 0:
  1188. link_type = tag_text[:space_pos]
  1189. link_target = tag_text[space_pos + 1 :].strip()
  1190. if link_target == "":
  1191. print_error(
  1192. f'{state.current_class}.xml: Empty cross-reference link "{cmd}" in {context_name}.',
  1193. state,
  1194. )
  1195. tag_text = ""
  1196. else:
  1197. if (
  1198. cmd.startswith("method")
  1199. or cmd.startswith("constructor")
  1200. or cmd.startswith("operator")
  1201. or cmd.startswith("member")
  1202. or cmd.startswith("signal")
  1203. or cmd.startswith("annotation")
  1204. or cmd.startswith("theme_item")
  1205. or cmd.startswith("constant")
  1206. ):
  1207. if link_target.find(".") != -1:
  1208. ss = link_target.split(".")
  1209. if len(ss) > 2:
  1210. print_error(
  1211. f'{state.current_class}.xml: Bad reference "{link_target}" in {context_name}.',
  1212. state,
  1213. )
  1214. class_param, method_param = ss
  1215. else:
  1216. class_param = state.current_class
  1217. method_param = link_target
  1218. # Default to the tag command name. This works by default for most tags,
  1219. # but member and theme_item have special cases.
  1220. ref_type = "_{}".format(link_type)
  1221. if link_type == "member":
  1222. ref_type = "_property"
  1223. if class_param in state.classes:
  1224. class_def = state.classes[class_param]
  1225. if cmd.startswith("method") and method_param not in class_def.methods:
  1226. print_error(
  1227. f'{state.current_class}.xml: Unresolved method reference "{link_target}" in {context_name}.',
  1228. state,
  1229. )
  1230. elif cmd.startswith("constructor") and method_param not in class_def.constructors:
  1231. print_error(
  1232. f'{state.current_class}.xml: Unresolved constructor reference "{link_target}" in {context_name}.',
  1233. state,
  1234. )
  1235. elif cmd.startswith("operator") and method_param not in class_def.operators:
  1236. print_error(
  1237. f'{state.current_class}.xml: Unresolved operator reference "{link_target}" in {context_name}.',
  1238. state,
  1239. )
  1240. elif cmd.startswith("member") and method_param not in class_def.properties:
  1241. print_error(
  1242. f'{state.current_class}.xml: Unresolved member reference "{link_target}" in {context_name}.',
  1243. state,
  1244. )
  1245. elif cmd.startswith("signal") and method_param not in class_def.signals:
  1246. print_error(
  1247. f'{state.current_class}.xml: Unresolved signal reference "{link_target}" in {context_name}.',
  1248. state,
  1249. )
  1250. elif cmd.startswith("annotation") and method_param not in class_def.annotations:
  1251. print_error(
  1252. f'{state.current_class}.xml: Unresolved annotation reference "{link_target}" in {context_name}.',
  1253. state,
  1254. )
  1255. elif cmd.startswith("theme_item"):
  1256. if method_param not in class_def.theme_items:
  1257. print_error(
  1258. f'{state.current_class}.xml: Unresolved theme item reference "{link_target}" in {context_name}.',
  1259. state,
  1260. )
  1261. else:
  1262. # Needs theme data type to be properly linked, which we cannot get without a class.
  1263. name = class_def.theme_items[method_param].data_name
  1264. ref_type = f"_theme_{name}"
  1265. elif cmd.startswith("constant"):
  1266. found = False
  1267. # Search in the current class
  1268. search_class_defs = [class_def]
  1269. if link_target.find(".") == -1:
  1270. # Also search in @GlobalScope as a last resort if no class was specified
  1271. search_class_defs.append(state.classes["@GlobalScope"])
  1272. for search_class_def in search_class_defs:
  1273. if method_param in search_class_def.constants:
  1274. class_param = search_class_def.name
  1275. found = True
  1276. else:
  1277. for enum in search_class_def.enums.values():
  1278. if method_param in enum.values:
  1279. class_param = search_class_def.name
  1280. found = True
  1281. break
  1282. if not found:
  1283. print_error(
  1284. f'{state.current_class}.xml: Unresolved constant reference "{link_target}" in {context_name}.',
  1285. state,
  1286. )
  1287. else:
  1288. print_error(
  1289. f'{state.current_class}.xml: Unresolved type reference "{class_param}" in method reference "{link_target}" in {context_name}.',
  1290. state,
  1291. )
  1292. repl_text = method_param
  1293. if class_param != state.current_class:
  1294. repl_text = f"{class_param}.{method_param}"
  1295. tag_text = f":ref:`{repl_text}<class_{class_param}{ref_type}_{method_param}>`"
  1296. escape_pre = True
  1297. escape_post = True
  1298. elif cmd.startswith("enum"):
  1299. tag_text = make_enum(link_target, state)
  1300. escape_pre = True
  1301. escape_post = True
  1302. elif cmd.startswith("param"):
  1303. valid_context = isinstance(context, (MethodDef, SignalDef, AnnotationDef))
  1304. if not valid_context:
  1305. print_error(
  1306. f'{state.current_class}.xml: Argument reference "{link_target}" used outside of method, signal, or annotation context in {context_name}.',
  1307. state,
  1308. )
  1309. else:
  1310. context_params: List[ParameterDef] = context.parameters # type: ignore
  1311. found = False
  1312. for param_def in context_params:
  1313. if param_def.name == link_target:
  1314. found = True
  1315. break
  1316. if not found:
  1317. print_error(
  1318. f'{state.current_class}.xml: Unresolved argument reference "{link_target}" in {context_name}.',
  1319. state,
  1320. )
  1321. tag_text = f"``{link_target}``"
  1322. escape_pre = True
  1323. escape_post = True
  1324. # Formatting directives.
  1325. elif is_in_tagset(cmd, ["url"]):
  1326. if cmd.startswith("url="):
  1327. # URLs are handled in full here as we need to extract the optional link
  1328. # title to use `make_link`.
  1329. link_url = cmd[4:]
  1330. endurl_pos = text.find("[/url]", endq_pos + 1)
  1331. if endurl_pos == -1:
  1332. print_error(
  1333. f"{state.current_class}.xml: Tag depth mismatch for [url]: no closing [/url] in {context_name}.",
  1334. state,
  1335. )
  1336. break
  1337. link_title = text[endq_pos + 1 : endurl_pos]
  1338. tag_text = make_link(link_url, link_title)
  1339. pre_text = text[:pos]
  1340. post_text = text[endurl_pos + 6 :]
  1341. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1342. pre_text += "\ "
  1343. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1344. post_text = "\ " + post_text
  1345. text = pre_text + tag_text + post_text
  1346. pos = len(pre_text) + len(tag_text)
  1347. continue
  1348. else:
  1349. print_error(
  1350. f'{state.current_class}.xml: Misformatted [url] tag "{cmd}" in {context_name}.',
  1351. state,
  1352. )
  1353. elif cmd == "br":
  1354. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  1355. tag_text = "\n\n"
  1356. # Strip potential leading spaces
  1357. while post_text[0] == " ":
  1358. post_text = post_text[1:]
  1359. elif cmd == "center" or cmd == "/center":
  1360. if cmd == "/center":
  1361. tag_depth -= 1
  1362. else:
  1363. tag_depth += 1
  1364. tag_text = ""
  1365. elif cmd == "i" or cmd == "/i":
  1366. if cmd == "/i":
  1367. tag_depth -= 1
  1368. escape_post = True
  1369. else:
  1370. tag_depth += 1
  1371. escape_pre = True
  1372. tag_text = "*"
  1373. elif cmd == "b" or cmd == "/b":
  1374. if cmd == "/b":
  1375. tag_depth -= 1
  1376. escape_post = True
  1377. else:
  1378. tag_depth += 1
  1379. escape_pre = True
  1380. tag_text = "**"
  1381. elif cmd == "u" or cmd == "/u":
  1382. if cmd == "/u":
  1383. tag_depth -= 1
  1384. escape_post = True
  1385. else:
  1386. tag_depth += 1
  1387. escape_pre = True
  1388. tag_text = ""
  1389. elif cmd == "kbd" or cmd == "/kbd":
  1390. tag_text = "`"
  1391. if cmd == "/kbd":
  1392. tag_depth -= 1
  1393. escape_post = True
  1394. else:
  1395. tag_text = ":kbd:" + tag_text
  1396. tag_depth += 1
  1397. escape_pre = True
  1398. # Invalid syntax checks.
  1399. elif cmd.startswith("/"):
  1400. print_error(f'{state.current_class}.xml: Unrecognized closing tag "{cmd}" in {context_name}.', state)
  1401. tag_text = f"[{tag_text}]"
  1402. else:
  1403. print_error(f'{state.current_class}.xml: Unrecognized opening tag "{cmd}" in {context_name}.', state)
  1404. tag_text = f"``{tag_text}``"
  1405. escape_pre = True
  1406. escape_post = True
  1407. # Properly escape things like `[Node]s`
  1408. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1409. pre_text += "\ "
  1410. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1411. post_text = "\ " + post_text
  1412. next_brac_pos = post_text.find("[", 0)
  1413. iter_pos = 0
  1414. while not inside_code:
  1415. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  1416. if iter_pos == -1:
  1417. break
  1418. post_text = f"{post_text[:iter_pos]}\*{post_text[iter_pos + 1 :]}"
  1419. iter_pos += 2
  1420. iter_pos = 0
  1421. while not inside_code:
  1422. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  1423. if iter_pos == -1:
  1424. break
  1425. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  1426. post_text = f"{post_text[:iter_pos]}\_{post_text[iter_pos + 1 :]}"
  1427. iter_pos += 2
  1428. else:
  1429. iter_pos += 1
  1430. text = pre_text + tag_text + post_text
  1431. pos = len(pre_text) + len(tag_text)
  1432. if tag_depth > 0:
  1433. print_error(
  1434. f"{state.current_class}.xml: Tag depth mismatch: too many (or too few) open/close tags in {context_name}.",
  1435. state,
  1436. )
  1437. return text
  1438. def format_context_name(context: Union[DefinitionBase, None]) -> str:
  1439. context_name: str = "unknown context"
  1440. if context is not None:
  1441. context_name = f'{context.definition_name} "{context.name}" description'
  1442. return context_name
  1443. def escape_rst(text: str, until_pos: int = -1) -> str:
  1444. # Escape \ character, otherwise it ends up as an escape character in rst
  1445. pos = 0
  1446. while True:
  1447. pos = text.find("\\", pos, until_pos)
  1448. if pos == -1:
  1449. break
  1450. text = f"{text[:pos]}\\\\{text[pos + 1 :]}"
  1451. pos += 2
  1452. # Escape * character to avoid interpreting it as emphasis
  1453. pos = 0
  1454. while True:
  1455. pos = text.find("*", pos, until_pos)
  1456. if pos == -1:
  1457. break
  1458. text = f"{text[:pos]}\*{text[pos + 1 :]}"
  1459. pos += 2
  1460. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  1461. pos = 0
  1462. while True:
  1463. pos = text.find("_", pos, until_pos)
  1464. if pos == -1:
  1465. break
  1466. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  1467. text = f"{text[:pos]}\_{text[pos + 1 :]}"
  1468. pos += 2
  1469. else:
  1470. pos += 1
  1471. return text
  1472. def format_codeblock(code_type: str, post_text: str, indent_level: int, state: State) -> Union[Tuple[str, int], None]:
  1473. end_pos = post_text.find("[/" + code_type + "]")
  1474. if end_pos == -1:
  1475. print_error(f"{state.current_class}.xml: [{code_type}] without a closing tag.", state)
  1476. return None
  1477. code_text = post_text[len(f"[{code_type}]") : end_pos]
  1478. post_text = post_text[end_pos:]
  1479. # Remove extraneous tabs
  1480. code_pos = 0
  1481. while True:
  1482. code_pos = code_text.find("\n", code_pos)
  1483. if code_pos == -1:
  1484. break
  1485. to_skip = 0
  1486. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  1487. to_skip += 1
  1488. if to_skip > indent_level:
  1489. print_error(
  1490. f"{state.current_class}.xml: Four spaces should be used for indentation within [{code_type}].",
  1491. state,
  1492. )
  1493. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  1494. code_text = f"{code_text[:code_pos]}\n"
  1495. code_pos += 1
  1496. else:
  1497. code_text = f"{code_text[:code_pos]}\n {code_text[code_pos + to_skip + 1 :]}"
  1498. code_pos += 5 - to_skip
  1499. return (f"\n[{code_type}]{code_text}{post_text}", len(f"\n[{code_type}]{code_text}"))
  1500. def format_table(f: TextIO, data: List[Tuple[Optional[str], ...]], remove_empty_columns: bool = False) -> None:
  1501. if len(data) == 0:
  1502. return
  1503. column_sizes = [0] * len(data[0])
  1504. for row in data:
  1505. for i, text in enumerate(row):
  1506. text_length = len(text or "")
  1507. if text_length > column_sizes[i]:
  1508. column_sizes[i] = text_length
  1509. sep = ""
  1510. for size in column_sizes:
  1511. if size == 0 and remove_empty_columns:
  1512. continue
  1513. sep += "+" + "-" * (size + 2)
  1514. sep += "+\n"
  1515. f.write(sep)
  1516. for row in data:
  1517. row_text = "|"
  1518. for i, text in enumerate(row):
  1519. if column_sizes[i] == 0 and remove_empty_columns:
  1520. continue
  1521. row_text += f' {(text or "").ljust(column_sizes[i])} |'
  1522. row_text += "\n"
  1523. f.write(row_text)
  1524. f.write(sep)
  1525. f.write("\n")
  1526. def sanitize_operator_name(dirty_name: str, state: State) -> str:
  1527. clear_name = dirty_name.replace("operator ", "")
  1528. if clear_name == "!=":
  1529. clear_name = "neq"
  1530. elif clear_name == "==":
  1531. clear_name = "eq"
  1532. elif clear_name == "<":
  1533. clear_name = "lt"
  1534. elif clear_name == "<=":
  1535. clear_name = "lte"
  1536. elif clear_name == ">":
  1537. clear_name = "gt"
  1538. elif clear_name == ">=":
  1539. clear_name = "gte"
  1540. elif clear_name == "+":
  1541. clear_name = "sum"
  1542. elif clear_name == "-":
  1543. clear_name = "dif"
  1544. elif clear_name == "*":
  1545. clear_name = "mul"
  1546. elif clear_name == "/":
  1547. clear_name = "div"
  1548. elif clear_name == "%":
  1549. clear_name = "mod"
  1550. elif clear_name == "**":
  1551. clear_name = "pow"
  1552. elif clear_name == "unary+":
  1553. clear_name = "unplus"
  1554. elif clear_name == "unary-":
  1555. clear_name = "unminus"
  1556. elif clear_name == "<<":
  1557. clear_name = "bwsl"
  1558. elif clear_name == ">>":
  1559. clear_name = "bwsr"
  1560. elif clear_name == "&":
  1561. clear_name = "bwand"
  1562. elif clear_name == "|":
  1563. clear_name = "bwor"
  1564. elif clear_name == "^":
  1565. clear_name = "bwxor"
  1566. elif clear_name == "~":
  1567. clear_name = "bwnot"
  1568. elif clear_name == "[]":
  1569. clear_name = "idx"
  1570. else:
  1571. clear_name = "xxx"
  1572. print_error(f'Unsupported operator type "{dirty_name}", please add the missing rule.', state)
  1573. return clear_name
  1574. def indent_bullets(text: str) -> str:
  1575. # Take the text and check each line for a bullet point represented by "-".
  1576. # Where found, indent the given line by a further "\t".
  1577. # Used to properly indent bullet points contained in the description for enum values.
  1578. # Ignore the first line - text will be prepended to it so bullet points wouldn't work anyway.
  1579. bullet_points = "-"
  1580. lines = text.splitlines(keepends=True)
  1581. for line_index, line in enumerate(lines[1:], start=1):
  1582. pos = 0
  1583. while pos < len(line) and line[pos] == "\t":
  1584. pos += 1
  1585. if pos < len(line) and line[pos] in bullet_points:
  1586. lines[line_index] = f"{line[:pos]}\t{line[pos:]}"
  1587. return "".join(lines)
  1588. if __name__ == "__main__":
  1589. main()