make_rst.py 67 KB

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