make_rst.py 65 KB

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