make_rst.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  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. name = doc.attrib["name"]
  392. if name in classes:
  393. print_error(f'{cur_file}: Duplicate class "{name}".', state)
  394. continue
  395. classes[name] = (doc, cur_file)
  396. for name, data in classes.items():
  397. try:
  398. state.parse_class(data[0], data[1])
  399. except Exception as e:
  400. print_error(f"{name}.xml: Exception while parsing class: {e}", state)
  401. state.sort_classes()
  402. pattern = re.compile(args.filter)
  403. # Create the output folder recursively if it doesn't already exist.
  404. os.makedirs(args.output, exist_ok=True)
  405. print("Generating the RST class reference...")
  406. grouped_classes: Dict[str, List[str]] = {}
  407. for class_name, class_def in state.classes.items():
  408. if args.filter and not pattern.search(class_def.filepath):
  409. continue
  410. state.current_class = class_name
  411. make_rst_class(class_def, state, args.dry_run, args.output)
  412. group_name = get_class_group(class_def, state)
  413. if group_name not in grouped_classes:
  414. grouped_classes[group_name] = []
  415. grouped_classes[group_name].append(class_name)
  416. print("")
  417. print("Generating the index file...")
  418. make_rst_index(grouped_classes, args.dry_run, args.output)
  419. print("")
  420. if state.num_warnings >= 2:
  421. print(
  422. f'{STYLES["yellow"]}{state.num_warnings} warnings were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  423. )
  424. elif state.num_warnings == 1:
  425. print(
  426. f'{STYLES["yellow"]}1 warning was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  427. )
  428. if state.num_errors == 0:
  429. print(f'{STYLES["green"]}No errors found in the class reference XML.{STYLES["reset"]}')
  430. if not args.dry_run:
  431. print(f"Wrote reStructuredText files for each class to: {args.output}")
  432. else:
  433. if state.num_errors >= 2:
  434. print(
  435. f'{STYLES["red"]}{state.num_errors} errors were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  436. )
  437. else:
  438. print(
  439. f'{STYLES["red"]}1 error was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
  440. )
  441. exit(1)
  442. # Common helpers.
  443. def print_error(error: str, state: State) -> None:
  444. print(f'{STYLES["red"]}{STYLES["bold"]}ERROR:{STYLES["regular"]} {error}{STYLES["reset"]}')
  445. state.num_errors += 1
  446. def print_warning(warning: str, state: State) -> None:
  447. print(f'{STYLES["yellow"]}{STYLES["bold"]}WARNING:{STYLES["regular"]} {warning}{STYLES["reset"]}')
  448. state.num_warnings += 1
  449. def translate(string: str) -> str:
  450. """Translate a string based on translations sourced from `doc/translations/*.po`
  451. for a language if defined via the --lang command line argument.
  452. Returns the original string if no translation exists.
  453. """
  454. return strings_l10n.get(string, string)
  455. def get_git_branch() -> str:
  456. if hasattr(version, "docs") and version.docs != "latest":
  457. return version.docs
  458. return "master"
  459. def get_class_group(class_def: ClassDef, state: State) -> str:
  460. group_name = "variant"
  461. class_name = class_def.name
  462. if class_name.startswith("@"):
  463. group_name = "global"
  464. elif class_def.inherits:
  465. inherits = class_def.inherits.strip()
  466. while inherits in state.classes:
  467. if inherits == "Node":
  468. group_name = "node"
  469. break
  470. if inherits == "Resource":
  471. group_name = "resource"
  472. break
  473. if inherits == "Object":
  474. group_name = "object"
  475. break
  476. inode = state.classes[inherits].inherits
  477. if inode:
  478. inherits = inode.strip()
  479. else:
  480. break
  481. return group_name
  482. # Generator methods.
  483. def make_rst_class(class_def: ClassDef, state: State, dry_run: bool, output_dir: str) -> None:
  484. class_name = class_def.name
  485. if dry_run:
  486. f = open(os.devnull, "w", encoding="utf-8")
  487. else:
  488. f = open(os.path.join(output_dir, f"class_{class_name.lower()}.rst"), "w", encoding="utf-8")
  489. # Remove the "Edit on Github" button from the online docs page.
  490. f.write(":github_url: hide\n\n")
  491. # Warn contributors not to edit this file directly.
  492. # Also provide links to the source files for reference.
  493. git_branch = get_git_branch()
  494. source_xml_path = os.path.relpath(class_def.filepath, root_directory).replace("\\", "/")
  495. source_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/{source_xml_path}"
  496. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  497. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  498. f.write(".. Generated automatically from Godot engine sources.\n")
  499. f.write(f".. Generator: {generator_github_url}.\n")
  500. f.write(f".. XML source: {source_github_url}.\n\n")
  501. # Document reference id and header.
  502. f.write(f".. _class_{class_name}:\n\n")
  503. f.write(make_heading(class_name, "=", False))
  504. ### INHERITANCE TREE ###
  505. # Ascendants
  506. if class_def.inherits:
  507. inherits = class_def.inherits.strip()
  508. f.write(f'**{translate("Inherits:")}** ')
  509. first = True
  510. while inherits in state.classes:
  511. if not first:
  512. f.write(" **<** ")
  513. else:
  514. first = False
  515. f.write(make_type(inherits, state))
  516. inode = state.classes[inherits].inherits
  517. if inode:
  518. inherits = inode.strip()
  519. else:
  520. break
  521. f.write("\n\n")
  522. # Descendants
  523. inherited: List[str] = []
  524. for c in state.classes.values():
  525. if c.inherits and c.inherits.strip() == class_name:
  526. inherited.append(c.name)
  527. if len(inherited):
  528. f.write(f'**{translate("Inherited By:")}** ')
  529. for i, child in enumerate(inherited):
  530. if i > 0:
  531. f.write(", ")
  532. f.write(make_type(child, state))
  533. f.write("\n\n")
  534. ### INTRODUCTION ###
  535. has_description = False
  536. # Brief description
  537. if class_def.brief_description is not None and class_def.brief_description.strip() != "":
  538. has_description = True
  539. f.write(f"{format_text_block(class_def.brief_description.strip(), class_def, state)}\n\n")
  540. # Class description
  541. if class_def.description is not None and class_def.description.strip() != "":
  542. has_description = True
  543. f.write(".. rst-class:: classref-introduction-group\n\n")
  544. f.write(make_heading("Description", "-"))
  545. f.write(f"{format_text_block(class_def.description.strip(), class_def, state)}\n\n")
  546. if not has_description:
  547. f.write(".. container:: contribute\n\n\t")
  548. f.write(
  549. translate(
  550. "There is currently no description for this class. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  551. )
  552. + "\n\n"
  553. )
  554. # Online tutorials
  555. if len(class_def.tutorials) > 0:
  556. f.write(".. rst-class:: classref-introduction-group\n\n")
  557. f.write(make_heading("Tutorials", "-"))
  558. for url, title in class_def.tutorials:
  559. f.write(f"- {make_link(url, title)}\n\n")
  560. ### REFERENCE TABLES ###
  561. # Reused container for reference tables.
  562. ml: List[Tuple[Optional[str], ...]] = []
  563. # Properties reference table
  564. if len(class_def.properties) > 0:
  565. f.write(".. rst-class:: classref-reftable-group\n\n")
  566. f.write(make_heading("Properties", "-"))
  567. ml = []
  568. for property_def in class_def.properties.values():
  569. type_rst = property_def.type_name.to_rst(state)
  570. default = property_def.default_value
  571. if default is not None and property_def.overrides:
  572. ref = f":ref:`{property_def.overrides}<class_{property_def.overrides}_property_{property_def.name}>`"
  573. # Not using translate() for now as it breaks table formatting.
  574. ml.append((type_rst, property_def.name, f"{default} (overrides {ref})"))
  575. else:
  576. ref = f":ref:`{property_def.name}<class_{class_name}_property_{property_def.name}>`"
  577. ml.append((type_rst, ref, default))
  578. format_table(f, ml, True)
  579. # Methods reference tables
  580. if len(class_def.methods) > 0:
  581. f.write(".. rst-class:: classref-reftable-group\n\n")
  582. f.write(make_heading("Methods", "-"))
  583. ml = []
  584. for method_list in class_def.methods.values():
  585. for m in method_list:
  586. ml.append(make_method_signature(class_def, m, "method", state))
  587. format_table(f, ml)
  588. # Theme properties reference table
  589. if len(class_def.theme_items) > 0:
  590. f.write(".. rst-class:: classref-reftable-group\n\n")
  591. f.write(make_heading("Theme Properties", "-"))
  592. ml = []
  593. for theme_item_def in class_def.theme_items.values():
  594. ref = f":ref:`{theme_item_def.name}<class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}>`"
  595. ml.append((theme_item_def.type_name.to_rst(state), ref, theme_item_def.default_value))
  596. format_table(f, ml, True)
  597. ### DETAILED DESCRIPTIONS ###
  598. # Signal descriptions
  599. if len(class_def.signals) > 0:
  600. f.write(make_separator(True))
  601. f.write(".. rst-class:: classref-descriptions-group\n\n")
  602. f.write(make_heading("Signals", "-"))
  603. index = 0
  604. for signal in class_def.signals.values():
  605. if index != 0:
  606. f.write(make_separator())
  607. # Create signal signature and anchor point.
  608. f.write(f".. _class_{class_name}_signal_{signal.name}:\n\n")
  609. f.write(".. rst-class:: classref-signal\n\n")
  610. _, signature = make_method_signature(class_def, signal, "", state)
  611. f.write(f"{signature}\n\n")
  612. # Add signal description, or a call to action if it's missing.
  613. if signal.description is not None and signal.description.strip() != "":
  614. f.write(f"{format_text_block(signal.description.strip(), signal, state)}\n\n")
  615. else:
  616. f.write(".. container:: contribute\n\n\t")
  617. f.write(
  618. translate(
  619. "There is currently no description for this signal. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  620. )
  621. + "\n\n"
  622. )
  623. index += 1
  624. # Enumeration descriptions
  625. if len(class_def.enums) > 0:
  626. f.write(make_separator(True))
  627. f.write(".. rst-class:: classref-descriptions-group\n\n")
  628. f.write(make_heading("Enumerations", "-"))
  629. index = 0
  630. for e in class_def.enums.values():
  631. if index != 0:
  632. f.write(make_separator())
  633. # Create enumeration signature and anchor point.
  634. f.write(f".. _enum_{class_name}_{e.name}:\n\n")
  635. f.write(".. rst-class:: classref-enumeration\n\n")
  636. f.write(f"enum **{e.name}**:\n\n")
  637. for value in e.values.values():
  638. # Also create signature and anchor point for each enum constant.
  639. f.write(f".. _class_{class_name}_constant_{value.name}:\n\n")
  640. f.write(".. rst-class:: classref-enumeration-constant\n\n")
  641. f.write(f"{e.type_name.to_rst(state)} **{value.name}** = ``{value.value}``\n\n")
  642. # Add enum constant description.
  643. if value.text is not None and value.text.strip() != "":
  644. f.write(f"{format_text_block(value.text.strip(), value, state)}")
  645. f.write("\n\n")
  646. index += 1
  647. # Constant descriptions
  648. if len(class_def.constants) > 0:
  649. f.write(make_separator(True))
  650. f.write(".. rst-class:: classref-descriptions-group\n\n")
  651. f.write(make_heading("Constants", "-"))
  652. for constant in class_def.constants.values():
  653. # Create constant signature and anchor point.
  654. f.write(f".. _class_{class_name}_constant_{constant.name}:\n\n")
  655. f.write(".. rst-class:: classref-constant\n\n")
  656. f.write(f"**{constant.name}** = ``{constant.value}``\n\n")
  657. # Add enum constant description.
  658. if constant.text is not None and constant.text.strip() != "":
  659. f.write(f"{format_text_block(constant.text.strip(), constant, state)}")
  660. f.write("\n\n")
  661. # Property descriptions
  662. if any(not p.overrides for p in class_def.properties.values()) > 0:
  663. f.write(make_separator(True))
  664. f.write(".. rst-class:: classref-descriptions-group\n\n")
  665. f.write(make_heading("Property Descriptions", "-"))
  666. index = 0
  667. for property_def in class_def.properties.values():
  668. if property_def.overrides:
  669. continue
  670. if index != 0:
  671. f.write(make_separator())
  672. # Create property signature and anchor point.
  673. f.write(f".. _class_{class_name}_property_{property_def.name}:\n\n")
  674. f.write(".. rst-class:: classref-property\n\n")
  675. property_default = ""
  676. if property_def.default_value is not None:
  677. property_default = f" = {property_def.default_value}"
  678. f.write(f"{property_def.type_name.to_rst(state)} **{property_def.name}**{property_default}\n\n")
  679. # Create property setter and getter records.
  680. property_setget = ""
  681. if property_def.setter is not None and not property_def.setter.startswith("_"):
  682. property_setter = make_setter_signature(class_def, property_def, state)
  683. property_setget += f"- {property_setter}\n"
  684. if property_def.getter is not None and not property_def.getter.startswith("_"):
  685. property_getter = make_getter_signature(class_def, property_def, state)
  686. property_setget += f"- {property_getter}\n"
  687. if property_setget != "":
  688. f.write(".. rst-class:: classref-property-setget\n\n")
  689. f.write(property_setget)
  690. f.write("\n")
  691. # Add property description, or a call to action if it's missing.
  692. if property_def.text is not None and property_def.text.strip() != "":
  693. f.write(f"{format_text_block(property_def.text.strip(), property_def, state)}\n\n")
  694. else:
  695. f.write(".. container:: contribute\n\n\t")
  696. f.write(
  697. translate(
  698. "There is currently no description for this property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  699. )
  700. + "\n\n"
  701. )
  702. index += 1
  703. # Method descriptions
  704. if len(class_def.methods) > 0:
  705. f.write(make_separator(True))
  706. f.write(".. rst-class:: classref-descriptions-group\n\n")
  707. f.write(make_heading("Method Descriptions", "-"))
  708. index = 0
  709. for method_list in class_def.methods.values():
  710. for i, m in enumerate(method_list):
  711. if index != 0:
  712. f.write(make_separator())
  713. # Create method signature and anchor point.
  714. if i == 0:
  715. f.write(f".. _class_{class_name}_method_{m.name}:\n\n")
  716. f.write(".. rst-class:: classref-method\n\n")
  717. ret_type, signature = make_method_signature(class_def, m, "", state)
  718. f.write(f"{ret_type} {signature}\n\n")
  719. # Add method description, or a call to action if it's missing.
  720. if m.description is not None and m.description.strip() != "":
  721. f.write(f"{format_text_block(m.description.strip(), m, state)}\n\n")
  722. else:
  723. f.write(".. container:: contribute\n\n\t")
  724. f.write(
  725. translate(
  726. "There is currently no description for this method. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  727. )
  728. + "\n\n"
  729. )
  730. index += 1
  731. # Theme property descriptions
  732. if len(class_def.theme_items) > 0:
  733. f.write(make_separator(True))
  734. f.write(".. rst-class:: classref-descriptions-group\n\n")
  735. f.write(make_heading("Theme Property Descriptions", "-"))
  736. index = 0
  737. for theme_item_def in class_def.theme_items.values():
  738. if index != 0:
  739. f.write(make_separator())
  740. # Create theme property signature and anchor point.
  741. f.write(f".. _class_{class_name}_theme_{theme_item_def.data_name}_{theme_item_def.name}:\n\n")
  742. f.write(".. rst-class:: classref-themeproperty\n\n")
  743. theme_item_default = ""
  744. if theme_item_def.default_value is not None:
  745. theme_item_default = f" = {theme_item_def.default_value}"
  746. f.write(f"{theme_item_def.type_name.to_rst(state)} **{theme_item_def.name}**{theme_item_default}\n\n")
  747. # Add theme property description, or a call to action if it's missing.
  748. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  749. f.write(f"{format_text_block(theme_item_def.text.strip(), theme_item_def, state)}\n\n")
  750. else:
  751. f.write(".. container:: contribute\n\n\t")
  752. f.write(
  753. translate(
  754. "There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!"
  755. )
  756. + "\n\n"
  757. )
  758. index += 1
  759. f.write(make_footer())
  760. def make_type(klass: str, state: State) -> str:
  761. if klass.find("*") != -1: # Pointer, ignore
  762. return klass
  763. link_type = klass
  764. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  765. link_type = link_type[:-2]
  766. if link_type in state.classes:
  767. return f":ref:`{klass}<class_{link_type}>`"
  768. print_error(f'{state.current_class}.xml: Unresolved type "{klass}".', state)
  769. return klass
  770. def make_enum(t: str, state: State) -> str:
  771. p = t.find(".")
  772. if p >= 0:
  773. c = t[0:p]
  774. e = t[p + 1 :]
  775. # Variant enums live in GlobalScope but still use periods.
  776. if c == "Variant":
  777. c = "@GlobalScope"
  778. e = "Variant." + e
  779. else:
  780. c = state.current_class
  781. e = t
  782. if c in state.classes and e not in state.classes[c].enums:
  783. c = "@GlobalScope"
  784. if c in state.classes and e in state.classes[c].enums:
  785. return f":ref:`{e}<enum_{c}_{e}>`"
  786. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  787. if f"{c}.{e}" != "Vector3.Axis":
  788. print_error(f'{state.current_class}.xml: Unresolved enum "{t}".', state)
  789. return t
  790. def make_method_signature(
  791. class_def: ClassDef, definition: Union[MethodDef, SignalDef], ref_type: str, state: State
  792. ) -> Tuple[str, str]:
  793. ret_type = ""
  794. if isinstance(definition, MethodDef):
  795. ret_type = definition.return_type.to_rst(state)
  796. qualifiers = None
  797. if isinstance(definition, MethodDef):
  798. qualifiers = definition.qualifiers
  799. out = ""
  800. if isinstance(definition, MethodDef) and ref_type != "":
  801. out += f":ref:`{definition.name}<class_{class_def.name}_{ref_type}_{definition.name}>` "
  802. else:
  803. out += f"**{definition.name}** "
  804. out += "**(**"
  805. for i, arg in enumerate(definition.parameters):
  806. if i > 0:
  807. out += ", "
  808. else:
  809. out += " "
  810. out += f"{arg.type_name.to_rst(state)} {arg.name}"
  811. if arg.default_value is not None:
  812. out += f"={arg.default_value}"
  813. if qualifiers is not None and "vararg" in qualifiers:
  814. if len(definition.parameters) > 0:
  815. out += ", ..."
  816. else:
  817. out += " ..."
  818. out += " **)**"
  819. if qualifiers is not None:
  820. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  821. # See `make_footer()` for descriptions.
  822. for qualifier in qualifiers.split():
  823. out += f" |{qualifier}|"
  824. return ret_type, out
  825. def make_setter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  826. if property_def.setter is None:
  827. return ""
  828. # If setter is a method available as a method definition, we use that.
  829. if property_def.setter in class_def.methods:
  830. setter = class_def.methods[property_def.setter][0]
  831. # Otherwise we fake it with the information we have available.
  832. else:
  833. setter_params: List[ParameterDef] = []
  834. setter_params.append(ParameterDef("value", property_def.type_name, None))
  835. setter = MethodDef(property_def.setter, TypeName("void"), setter_params, None, None)
  836. ret_type, signature = make_method_signature(class_def, setter, "", state)
  837. return f"{ret_type} {signature}"
  838. def make_getter_signature(class_def: ClassDef, property_def: PropertyDef, state: State) -> str:
  839. if property_def.getter is None:
  840. return ""
  841. # If getter is a method available as a method definition, we use that.
  842. if property_def.getter in class_def.methods:
  843. getter = class_def.methods[property_def.getter][0]
  844. # Otherwise we fake it with the information we have available.
  845. else:
  846. getter_params: List[ParameterDef] = []
  847. getter = MethodDef(property_def.getter, property_def.type_name, getter_params, None, None)
  848. ret_type, signature = make_method_signature(class_def, getter, "", state)
  849. return f"{ret_type} {signature}"
  850. def make_heading(title: str, underline: str, l10n: bool = True) -> str:
  851. if l10n:
  852. new_title = translate(title)
  853. if new_title != title:
  854. title = new_title
  855. underline *= 2 # Double length to handle wide chars.
  856. return f"{title}\n{(underline * len(title))}\n\n"
  857. def make_footer() -> str:
  858. # Generate reusable abbreviation substitutions.
  859. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  860. virtual_msg = translate("This method should typically be overridden by the user to have any effect.")
  861. const_msg = translate("This method has no side effects. It doesn't modify any of the instance's member variables.")
  862. vararg_msg = translate("This method accepts any number of arguments after the ones described here.")
  863. static_msg = translate(
  864. "This method doesn't need an instance to be called, so it can be called directly using the class name."
  865. )
  866. return (
  867. f".. |virtual| replace:: :abbr:`virtual ({virtual_msg})`\n"
  868. f".. |const| replace:: :abbr:`const ({const_msg})`\n"
  869. f".. |vararg| replace:: :abbr:`vararg ({vararg_msg})`\n"
  870. f".. |static| replace:: :abbr:`static ({static_msg})`\n"
  871. )
  872. def make_separator(section_level: bool = False) -> str:
  873. separator_class = "item"
  874. if section_level:
  875. separator_class = "section"
  876. return f".. rst-class:: classref-{separator_class}-separator\n\n----\n\n"
  877. def make_link(url: str, title: str) -> str:
  878. match = GODOT_DOCS_PATTERN.search(url)
  879. if match:
  880. groups = match.groups()
  881. if match.lastindex == 2:
  882. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  883. # `#calling-javascript-from-script in Exporting For Web`
  884. # Or use the title if provided.
  885. if title != "":
  886. return f"`{title} <../{groups[0]}.html{groups[1]}>`__"
  887. return f"`{groups[1]} <../{groups[0]}.html{groups[1]}>`__ in :doc:`../{groups[0]}`"
  888. elif match.lastindex == 1:
  889. # Doc reference, for example:
  890. # `Math`
  891. if title != "":
  892. return f":doc:`{title} <../{groups[0]}>`"
  893. return f":doc:`../{groups[0]}`"
  894. # External link, for example:
  895. # `http://enet.bespin.org/usergroup0.html`
  896. if title != "":
  897. return f"`{title} <{url}>`__"
  898. return f"`{url} <{url}>`__"
  899. def make_rst_index(grouped_classes: Dict[str, List[str]], dry_run: bool, output_dir: str) -> None:
  900. if dry_run:
  901. f = open(os.devnull, "w", encoding="utf-8")
  902. else:
  903. f = open(os.path.join(output_dir, "index.rst"), "w", encoding="utf-8")
  904. # Remove the "Edit on Github" button from the online docs page.
  905. f.write(":github_url: hide\n\n")
  906. # Warn contributors not to edit this file directly.
  907. # Also provide links to the source files for reference.
  908. git_branch = get_git_branch()
  909. generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
  910. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  911. f.write(".. Generated automatically from Godot engine sources.\n")
  912. f.write(f".. Generator: {generator_github_url}.\n\n")
  913. f.write(".. _doc_class_reference:\n\n")
  914. main_title = translate("All classes")
  915. f.write(f"{main_title}\n")
  916. f.write(f"{'=' * len(main_title)}\n\n")
  917. for group_name in CLASS_GROUPS:
  918. if group_name in grouped_classes:
  919. group_title = translate(CLASS_GROUPS[group_name])
  920. f.write(f"{group_title}\n")
  921. f.write(f"{'=' * len(group_title)}\n\n")
  922. f.write(".. toctree::\n")
  923. f.write(" :maxdepth: 1\n")
  924. f.write(f" :name: toc-class-ref-{group_name}s\n")
  925. f.write("\n")
  926. if group_name in CLASS_GROUPS_BASE:
  927. f.write(f" class_{CLASS_GROUPS_BASE[group_name].lower()}\n")
  928. for class_name in grouped_classes[group_name]:
  929. f.write(f" class_{class_name.lower()}\n")
  930. f.write("\n")
  931. # Formatting helpers.
  932. RESERVED_FORMATTING_TAGS = ["i", "b", "u", "code", "kbd", "center", "url", "br"]
  933. RESERVED_CODEBLOCK_TAGS = ["codeblocks", "codeblock", "gdscript", "csharp"]
  934. RESERVED_CROSSLINK_TAGS = ["method", "member", "signal", "constant", "enum", "theme_item", "param"]
  935. def is_in_tagset(tag_text: str, tagset: List[str]) -> bool:
  936. for tag in tagset:
  937. # Complete match.
  938. if tag_text == tag:
  939. return True
  940. # Tag with arguments.
  941. if tag_text.startswith(tag + " "):
  942. return True
  943. # Tag with arguments, special case for [url].
  944. if tag_text.startswith(tag + "="):
  945. return True
  946. return False
  947. def format_text_block(
  948. text: str,
  949. context: Union[DefinitionBase, None],
  950. state: State,
  951. ) -> str:
  952. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  953. pos = 0
  954. while True:
  955. pos = text.find("\n", pos)
  956. if pos == -1:
  957. break
  958. pre_text = text[:pos]
  959. indent_level = 0
  960. while pos + 1 < len(text) and text[pos + 1] == "\t":
  961. pos += 1
  962. indent_level += 1
  963. post_text = text[pos + 1 :]
  964. # Handle codeblocks
  965. if (
  966. post_text.startswith("[codeblock]")
  967. or post_text.startswith("[gdscript]")
  968. or post_text.startswith("[csharp]")
  969. ):
  970. block_type = post_text[1:].split("]")[0]
  971. result = format_codeblock(block_type, post_text, indent_level, state)
  972. if result is None:
  973. return ""
  974. text = f"{pre_text}{result[0]}"
  975. pos += result[1] - indent_level
  976. # Handle normal text
  977. else:
  978. text = f"{pre_text}\n\n{post_text}"
  979. pos += 2 - indent_level
  980. next_brac_pos = text.find("[")
  981. text = escape_rst(text, next_brac_pos)
  982. context_name = format_context_name(context)
  983. # Handle [tags]
  984. inside_code = False
  985. inside_code_tag = ""
  986. inside_code_tabs = False
  987. pos = 0
  988. tag_depth = 0
  989. while True:
  990. pos = text.find("[", pos)
  991. if pos == -1:
  992. break
  993. endq_pos = text.find("]", pos + 1)
  994. if endq_pos == -1:
  995. break
  996. pre_text = text[:pos]
  997. post_text = text[endq_pos + 1 :]
  998. tag_text = text[pos + 1 : endq_pos]
  999. escape_pre = False
  1000. escape_post = False
  1001. # Tag is a reference to a class.
  1002. if tag_text in state.classes and not inside_code:
  1003. if tag_text == state.current_class:
  1004. # Don't create a link to the same class, format it as strong emphasis.
  1005. tag_text = f"**{tag_text}**"
  1006. else:
  1007. tag_text = make_type(tag_text, state)
  1008. escape_pre = True
  1009. escape_post = True
  1010. # Tag is a cross-reference or a formatting directive.
  1011. else:
  1012. cmd = tag_text
  1013. space_pos = tag_text.find(" ")
  1014. # Anything identified as a tag inside of a code block is valid,
  1015. # unless it's a matching closing tag.
  1016. if inside_code:
  1017. # Exiting codeblocks and inline code tags.
  1018. if inside_code_tag == cmd[1:]:
  1019. if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp":
  1020. tag_text = ""
  1021. tag_depth -= 1
  1022. inside_code = False
  1023. # Strip newline if the tag was alone on one
  1024. if pre_text[-1] == "\n":
  1025. pre_text = pre_text[:-1]
  1026. elif cmd == "/code":
  1027. tag_text = "``"
  1028. tag_depth -= 1
  1029. inside_code = False
  1030. escape_post = True
  1031. else:
  1032. if cmd.startswith("/"):
  1033. print_warning(
  1034. 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}.',
  1035. state,
  1036. )
  1037. tag_text = f"[{tag_text}]"
  1038. # Entering codeblocks and inline code tags.
  1039. elif cmd == "codeblocks":
  1040. tag_depth += 1
  1041. tag_text = "\n.. tabs::"
  1042. inside_code_tabs = True
  1043. elif cmd == "/codeblocks":
  1044. tag_depth -= 1
  1045. tag_text = ""
  1046. inside_code_tabs = False
  1047. elif cmd == "codeblock" or cmd == "gdscript" or cmd == "csharp":
  1048. tag_depth += 1
  1049. if cmd == "gdscript":
  1050. if not inside_code_tabs:
  1051. print_error(
  1052. f"{state.current_class}.xml: GDScript code block is used outside of [codeblocks] in {context_name}.",
  1053. state,
  1054. )
  1055. tag_text = "\n .. code-tab:: gdscript\n"
  1056. elif cmd == "csharp":
  1057. if not inside_code_tabs:
  1058. print_error(
  1059. f"{state.current_class}.xml: C# code block is used outside of [codeblocks] in {context_name}.",
  1060. state,
  1061. )
  1062. tag_text = "\n .. code-tab:: csharp\n"
  1063. else:
  1064. tag_text = "\n::\n"
  1065. inside_code = True
  1066. inside_code_tag = cmd
  1067. elif cmd == "code":
  1068. tag_text = "``"
  1069. tag_depth += 1
  1070. inside_code = True
  1071. inside_code_tag = cmd
  1072. escape_pre = True
  1073. # Cross-references to items in this or other class documentation pages.
  1074. elif is_in_tagset(cmd, RESERVED_CROSSLINK_TAGS):
  1075. link_type: str = ""
  1076. link_target: str = ""
  1077. if space_pos >= 0:
  1078. link_type = tag_text[:space_pos]
  1079. link_target = tag_text[space_pos + 1 :].strip()
  1080. if link_target == "":
  1081. print_error(
  1082. f'{state.current_class}.xml: Empty cross-reference link "{cmd}" in {context_name}.',
  1083. state,
  1084. )
  1085. tag_text = ""
  1086. else:
  1087. if (
  1088. cmd.startswith("method")
  1089. or cmd.startswith("member")
  1090. or cmd.startswith("signal")
  1091. or cmd.startswith("theme_item")
  1092. or cmd.startswith("constant")
  1093. ):
  1094. if link_target.find(".") != -1:
  1095. ss = link_target.split(".")
  1096. if len(ss) > 2:
  1097. print_error(
  1098. f'{state.current_class}.xml: Bad reference "{link_target}" in {context_name}.',
  1099. state,
  1100. )
  1101. class_param, method_param = ss
  1102. else:
  1103. class_param = state.current_class
  1104. method_param = link_target
  1105. # Default to the tag command name. This works by default for most tags,
  1106. # but member and theme_item have special cases.
  1107. ref_type = "_{}".format(link_type)
  1108. if link_type == "member":
  1109. ref_type = "_property"
  1110. if class_param in state.classes:
  1111. class_def = state.classes[class_param]
  1112. if cmd.startswith("method") and method_param not in class_def.methods:
  1113. print_error(
  1114. f'{state.current_class}.xml: Unresolved method reference "{link_target}" in {context_name}.',
  1115. state,
  1116. )
  1117. elif cmd.startswith("member") and method_param not in class_def.properties:
  1118. print_error(
  1119. f'{state.current_class}.xml: Unresolved member reference "{link_target}" in {context_name}.',
  1120. state,
  1121. )
  1122. elif cmd.startswith("signal") and method_param not in class_def.signals:
  1123. print_error(
  1124. f'{state.current_class}.xml: Unresolved signal reference "{link_target}" in {context_name}.',
  1125. state,
  1126. )
  1127. elif cmd.startswith("theme_item"):
  1128. if method_param not in class_def.theme_items:
  1129. print_error(
  1130. f'{state.current_class}.xml: Unresolved theme item reference "{link_target}" in {context_name}.',
  1131. state,
  1132. )
  1133. else:
  1134. # Needs theme data type to be properly linked, which we cannot get without a class.
  1135. name = class_def.theme_items[method_param].data_name
  1136. ref_type = f"_theme_{name}"
  1137. elif cmd.startswith("constant"):
  1138. found = False
  1139. # Search in the current class
  1140. search_class_defs = [class_def]
  1141. if link_target.find(".") == -1:
  1142. # Also search in @GlobalScope as a last resort if no class was specified
  1143. search_class_defs.append(state.classes["@GlobalScope"])
  1144. for search_class_def in search_class_defs:
  1145. if method_param in search_class_def.constants:
  1146. class_param = search_class_def.name
  1147. found = True
  1148. else:
  1149. for enum in search_class_def.enums.values():
  1150. if method_param in enum.values:
  1151. class_param = search_class_def.name
  1152. found = True
  1153. break
  1154. if not found:
  1155. print_error(
  1156. f'{state.current_class}.xml: Unresolved constant reference "{link_target}" in {context_name}.',
  1157. state,
  1158. )
  1159. else:
  1160. print_error(
  1161. f'{state.current_class}.xml: Unresolved type reference "{class_param}" in method reference "{link_target}" in {context_name}.',
  1162. state,
  1163. )
  1164. repl_text = method_param
  1165. if class_param != state.current_class:
  1166. repl_text = f"{class_param}.{method_param}"
  1167. tag_text = f":ref:`{repl_text}<class_{class_param}{ref_type}_{method_param}>`"
  1168. escape_pre = True
  1169. escape_post = True
  1170. elif cmd.startswith("enum"):
  1171. tag_text = make_enum(link_target, state)
  1172. escape_pre = True
  1173. escape_post = True
  1174. elif cmd.startswith("param"):
  1175. valid_context = isinstance(context, (MethodDef, SignalDef))
  1176. if not valid_context:
  1177. print_error(
  1178. f'{state.current_class}.xml: Argument reference "{link_target}" used outside of method, or signal context in {context_name}.',
  1179. state,
  1180. )
  1181. else:
  1182. context_params: List[ParameterDef] = context.parameters # type: ignore
  1183. found = False
  1184. for param_def in context_params:
  1185. if param_def.name == link_target:
  1186. found = True
  1187. break
  1188. if not found:
  1189. print_error(
  1190. f'{state.current_class}.xml: Unresolved argument reference "{link_target}" in {context_name}.',
  1191. state,
  1192. )
  1193. tag_text = f"``{link_target}``"
  1194. escape_pre = True
  1195. escape_post = True
  1196. # Formatting directives.
  1197. elif is_in_tagset(cmd, ["url"]):
  1198. if cmd.startswith("url="):
  1199. # URLs are handled in full here as we need to extract the optional link
  1200. # title to use `make_link`.
  1201. link_url = cmd[4:]
  1202. endurl_pos = text.find("[/url]", endq_pos + 1)
  1203. if endurl_pos == -1:
  1204. print_error(
  1205. f"{state.current_class}.xml: Tag depth mismatch for [url]: no closing [/url] in {context_name}.",
  1206. state,
  1207. )
  1208. break
  1209. link_title = text[endq_pos + 1 : endurl_pos]
  1210. tag_text = make_link(link_url, link_title)
  1211. pre_text = text[:pos]
  1212. post_text = text[endurl_pos + 6 :]
  1213. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1214. pre_text += "\\ "
  1215. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1216. post_text = "\\ " + post_text
  1217. text = pre_text + tag_text + post_text
  1218. pos = len(pre_text) + len(tag_text)
  1219. continue
  1220. else:
  1221. print_error(
  1222. f'{state.current_class}.xml: Misformatted [url] tag "{cmd}" in {context_name}.',
  1223. state,
  1224. )
  1225. elif cmd == "br":
  1226. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  1227. tag_text = "\n\n"
  1228. # Strip potential leading spaces
  1229. while post_text[0] == " ":
  1230. post_text = post_text[1:]
  1231. elif cmd == "center" or cmd == "/center":
  1232. if cmd == "/center":
  1233. tag_depth -= 1
  1234. else:
  1235. tag_depth += 1
  1236. tag_text = ""
  1237. elif cmd == "i" or cmd == "/i":
  1238. if cmd == "/i":
  1239. tag_depth -= 1
  1240. escape_post = True
  1241. else:
  1242. tag_depth += 1
  1243. escape_pre = True
  1244. tag_text = "*"
  1245. elif cmd == "b" or cmd == "/b":
  1246. if cmd == "/b":
  1247. tag_depth -= 1
  1248. escape_post = True
  1249. else:
  1250. tag_depth += 1
  1251. escape_pre = True
  1252. tag_text = "**"
  1253. elif cmd == "u" or cmd == "/u":
  1254. if cmd == "/u":
  1255. tag_depth -= 1
  1256. escape_post = True
  1257. else:
  1258. tag_depth += 1
  1259. escape_pre = True
  1260. tag_text = ""
  1261. elif cmd == "kbd" or cmd == "/kbd":
  1262. tag_text = "`"
  1263. if cmd == "/kbd":
  1264. tag_depth -= 1
  1265. escape_post = True
  1266. else:
  1267. tag_text = ":kbd:" + tag_text
  1268. tag_depth += 1
  1269. escape_pre = True
  1270. # Invalid syntax checks.
  1271. elif cmd.startswith("/"):
  1272. print_error(f'{state.current_class}.xml: Unrecognized closing tag "{cmd}" in {context_name}.', state)
  1273. tag_text = f"[{tag_text}]"
  1274. else:
  1275. print_error(f'{state.current_class}.xml: Unrecognized opening tag "{cmd}" in {context_name}.', state)
  1276. tag_text = f"``{tag_text}``"
  1277. escape_pre = True
  1278. escape_post = True
  1279. # Properly escape things like `[Node]s`
  1280. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  1281. pre_text += "\\ "
  1282. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  1283. post_text = "\\ " + post_text
  1284. next_brac_pos = post_text.find("[", 0)
  1285. iter_pos = 0
  1286. while not inside_code:
  1287. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  1288. if iter_pos == -1:
  1289. break
  1290. post_text = f"{post_text[:iter_pos]}\\*{post_text[iter_pos + 1 :]}"
  1291. iter_pos += 2
  1292. iter_pos = 0
  1293. while not inside_code:
  1294. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  1295. if iter_pos == -1:
  1296. break
  1297. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  1298. post_text = f"{post_text[:iter_pos]}\\_{post_text[iter_pos + 1 :]}"
  1299. iter_pos += 2
  1300. else:
  1301. iter_pos += 1
  1302. text = pre_text + tag_text + post_text
  1303. pos = len(pre_text) + len(tag_text)
  1304. if tag_depth > 0:
  1305. print_error(
  1306. f"{state.current_class}.xml: Tag depth mismatch: too many (or too few) open/close tags in {context_name}.",
  1307. state,
  1308. )
  1309. return text
  1310. def format_context_name(context: Union[DefinitionBase, None]) -> str:
  1311. context_name: str = "unknown context"
  1312. if context is not None:
  1313. context_name = f'{context.definition_name} "{context.name}" description'
  1314. return context_name
  1315. def escape_rst(text: str, until_pos: int = -1) -> str:
  1316. # Escape \ character, otherwise it ends up as an escape character in rst
  1317. pos = 0
  1318. while True:
  1319. pos = text.find("\\", pos, until_pos)
  1320. if pos == -1:
  1321. break
  1322. text = f"{text[:pos]}\\\\{text[pos + 1 :]}"
  1323. pos += 2
  1324. # Escape * character to avoid interpreting it as emphasis
  1325. pos = 0
  1326. while True:
  1327. pos = text.find("*", pos, until_pos)
  1328. if pos == -1:
  1329. break
  1330. text = f"{text[:pos]}\\*{text[pos + 1 :]}"
  1331. pos += 2
  1332. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  1333. pos = 0
  1334. while True:
  1335. pos = text.find("_", pos, until_pos)
  1336. if pos == -1:
  1337. break
  1338. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  1339. text = f"{text[:pos]}\\_{text[pos + 1 :]}"
  1340. pos += 2
  1341. else:
  1342. pos += 1
  1343. return text
  1344. def format_codeblock(code_type: str, post_text: str, indent_level: int, state: State) -> Union[Tuple[str, int], None]:
  1345. end_pos = post_text.find("[/" + code_type + "]")
  1346. if end_pos == -1:
  1347. print_error(f"{state.current_class}.xml: [{code_type}] without a closing tag.", state)
  1348. return None
  1349. code_text = post_text[len(f"[{code_type}]") : end_pos]
  1350. post_text = post_text[end_pos:]
  1351. # Remove extraneous tabs
  1352. code_pos = 0
  1353. while True:
  1354. code_pos = code_text.find("\n", code_pos)
  1355. if code_pos == -1:
  1356. break
  1357. to_skip = 0
  1358. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  1359. to_skip += 1
  1360. if to_skip > indent_level:
  1361. print_error(
  1362. f"{state.current_class}.xml: Four spaces should be used for indentation within [{code_type}].",
  1363. state,
  1364. )
  1365. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  1366. code_text = f"{code_text[:code_pos]}\n"
  1367. code_pos += 1
  1368. else:
  1369. code_text = f"{code_text[:code_pos]}\n {code_text[code_pos + to_skip + 1 :]}"
  1370. code_pos += 5 - to_skip
  1371. return (f"\n[{code_type}]{code_text}{post_text}", len(f"\n[{code_type}]{code_text}"))
  1372. def format_table(f: TextIO, data: List[Tuple[Optional[str], ...]], remove_empty_columns: bool = False) -> None:
  1373. if len(data) == 0:
  1374. return
  1375. f.write(".. table::\n")
  1376. f.write(" :widths: auto\n\n")
  1377. # Calculate the width of each column first, we will use this information
  1378. # to properly format RST-style tables.
  1379. column_sizes = [0] * len(data[0])
  1380. for row in data:
  1381. for i, text in enumerate(row):
  1382. text_length = len(text or "")
  1383. if text_length > column_sizes[i]:
  1384. column_sizes[i] = text_length
  1385. # Each table row is wrapped in two separators, consecutive rows share the same separator.
  1386. # All separators, or rather borders, have the same shape and content. We compose it once,
  1387. # then reuse it.
  1388. sep = ""
  1389. for size in column_sizes:
  1390. if size == 0 and remove_empty_columns:
  1391. continue
  1392. sep += "+" + "-" * (size + 2) # Content of each cell is padded by 1 on each side.
  1393. sep += "+\n"
  1394. # Draw the first separator.
  1395. f.write(f" {sep}")
  1396. # Draw each row and close it with a separator.
  1397. for row in data:
  1398. row_text = "|"
  1399. for i, text in enumerate(row):
  1400. if column_sizes[i] == 0 and remove_empty_columns:
  1401. continue
  1402. row_text += f' {(text or "").ljust(column_sizes[i])} |'
  1403. row_text += "\n"
  1404. f.write(f" {row_text}")
  1405. f.write(f" {sep}")
  1406. f.write("\n")
  1407. if __name__ == "__main__":
  1408. main()