make_rst.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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 re
  6. import sys
  7. import xml.etree.ElementTree as ET
  8. from collections import OrderedDict
  9. # Import hardcoded version information from version.py
  10. root_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../")
  11. sys.path.append(root_directory) # Include the root directory
  12. import version
  13. # Uncomment to do type checks. I have it commented out so it works below Python 3.5
  14. # from typing import List, Dict, TextIO, Tuple, Iterable, Optional, DefaultDict, Any, Union
  15. # $DOCS_URL/path/to/page.html(#fragment-tag)
  16. GODOT_DOCS_PATTERN = re.compile(r"^\$DOCS_URL/(.*)\.html(#.*)?$")
  17. # Based on reStructedText inline markup recognition rules
  18. # https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
  19. MARKUP_ALLOWED_PRECEDENT = " -:/'\"<([{"
  20. MARKUP_ALLOWED_SUBSEQUENT = " -.,:;!?\\/'\")]}>"
  21. # Used to translate section headings and other hardcoded strings when required with
  22. # the --lang argument. The BASE_STRINGS list should be synced with what we actually
  23. # write in this script (check `translate()` uses), and also hardcoded in
  24. # `doc/translations/extract.py` to include them in the source POT file.
  25. BASE_STRINGS = [
  26. "Description",
  27. "Tutorials",
  28. "Properties",
  29. "Methods",
  30. "Theme Properties",
  31. "Signals",
  32. "Enumerations",
  33. "Constants",
  34. "Property Descriptions",
  35. "Method Descriptions",
  36. "Theme Property Descriptions",
  37. "Inherits:",
  38. "Inherited By:",
  39. "(overrides %s)",
  40. "Default",
  41. "Setter",
  42. "value",
  43. "Getter",
  44. "This method should typically be overridden by the user to have any effect.",
  45. "This method has no side effects. It doesn't modify any of the instance's member variables.",
  46. "This method accepts any number of arguments after the ones described here.",
  47. ]
  48. strings_l10n = {}
  49. def print_error(error, state): # type: (str, State) -> None
  50. print("ERROR: {}".format(error))
  51. state.errored = True
  52. class TypeName:
  53. def __init__(self, type_name, enum=None): # type: (str, Optional[str]) -> None
  54. self.type_name = type_name
  55. self.enum = enum
  56. def to_rst(self, state): # type: ("State") -> str
  57. if self.enum is not None:
  58. return make_enum(self.enum, state)
  59. elif self.type_name == "void":
  60. return "void"
  61. else:
  62. return make_type(self.type_name, state)
  63. @classmethod
  64. def from_element(cls, element): # type: (ET.Element) -> "TypeName"
  65. return cls(element.attrib["type"], element.get("enum"))
  66. class PropertyDef:
  67. def __init__(
  68. self, name, type_name, setter, getter, text, default_value, overrides
  69. ): # type: (str, TypeName, Optional[str], Optional[str], Optional[str], Optional[str], Optional[str]) -> None
  70. self.name = name
  71. self.type_name = type_name
  72. self.setter = setter
  73. self.getter = getter
  74. self.text = text
  75. self.default_value = default_value
  76. self.overrides = overrides
  77. class ParameterDef:
  78. def __init__(self, name, type_name, default_value): # type: (str, TypeName, Optional[str]) -> None
  79. self.name = name
  80. self.type_name = type_name
  81. self.default_value = default_value
  82. class SignalDef:
  83. def __init__(self, name, parameters, description): # type: (str, List[ParameterDef], Optional[str]) -> None
  84. self.name = name
  85. self.parameters = parameters
  86. self.description = description
  87. class MethodDef:
  88. def __init__(
  89. self, name, return_type, parameters, description, qualifiers
  90. ): # type: (str, TypeName, List[ParameterDef], Optional[str], Optional[str]) -> None
  91. self.name = name
  92. self.return_type = return_type
  93. self.parameters = parameters
  94. self.description = description
  95. self.qualifiers = qualifiers
  96. class ConstantDef:
  97. def __init__(self, name, value, text): # type: (str, str, Optional[str]) -> None
  98. self.name = name
  99. self.value = value
  100. self.text = text
  101. class EnumDef:
  102. def __init__(self, name): # type: (str) -> None
  103. self.name = name
  104. self.values = OrderedDict() # type: OrderedDict[str, ConstantDef]
  105. class ThemeItemDef:
  106. def __init__(
  107. self, name, type_name, data_name, text, default_value
  108. ): # type: (str, TypeName, str, Optional[str], Optional[str]) -> None
  109. self.name = name
  110. self.type_name = type_name
  111. self.data_name = data_name
  112. self.text = text
  113. self.default_value = default_value
  114. class ClassDef:
  115. def __init__(self, name): # type: (str) -> None
  116. self.name = name
  117. self.constants = OrderedDict() # type: OrderedDict[str, ConstantDef]
  118. self.enums = OrderedDict() # type: OrderedDict[str, EnumDef]
  119. self.properties = OrderedDict() # type: OrderedDict[str, PropertyDef]
  120. self.methods = OrderedDict() # type: OrderedDict[str, List[MethodDef]]
  121. self.signals = OrderedDict() # type: OrderedDict[str, SignalDef]
  122. self.theme_items = OrderedDict() # type: OrderedDict[str, ThemeItemDef]
  123. self.inherits = None # type: Optional[str]
  124. self.brief_description = None # type: Optional[str]
  125. self.description = None # type: Optional[str]
  126. self.tutorials = [] # type: List[Tuple[str, str]]
  127. # Used to match the class with XML source for output filtering purposes.
  128. self.filepath = "" # type: str
  129. class State:
  130. def __init__(self): # type: () -> None
  131. # Has any error been reported?
  132. self.errored = False
  133. self.classes = OrderedDict() # type: OrderedDict[str, ClassDef]
  134. self.current_class = "" # type: str
  135. def parse_class(self, class_root, filepath): # type: (ET.Element, str) -> None
  136. class_name = class_root.attrib["name"]
  137. class_def = ClassDef(class_name)
  138. self.classes[class_name] = class_def
  139. class_def.filepath = filepath
  140. inherits = class_root.get("inherits")
  141. if inherits is not None:
  142. class_def.inherits = inherits
  143. brief_desc = class_root.find("brief_description")
  144. if brief_desc is not None and brief_desc.text:
  145. class_def.brief_description = brief_desc.text
  146. desc = class_root.find("description")
  147. if desc is not None and desc.text:
  148. class_def.description = desc.text
  149. properties = class_root.find("members")
  150. if properties is not None:
  151. for property in properties:
  152. assert property.tag == "member"
  153. property_name = property.attrib["name"]
  154. if property_name in class_def.properties:
  155. print_error("Duplicate property '{}', file: {}".format(property_name, class_name), self)
  156. continue
  157. type_name = TypeName.from_element(property)
  158. setter = property.get("setter") or None # Use or None so '' gets turned into None.
  159. getter = property.get("getter") or None
  160. default_value = property.get("default") or None
  161. if default_value is not None:
  162. default_value = "``{}``".format(default_value)
  163. overrides = property.get("overrides") or None
  164. property_def = PropertyDef(
  165. property_name, type_name, setter, getter, property.text, default_value, overrides
  166. )
  167. class_def.properties[property_name] = property_def
  168. methods = class_root.find("methods")
  169. if methods is not None:
  170. for method in methods:
  171. assert method.tag == "method"
  172. method_name = method.attrib["name"]
  173. qualifiers = method.get("qualifiers")
  174. return_element = method.find("return")
  175. if return_element is not None:
  176. return_type = TypeName.from_element(return_element)
  177. else:
  178. return_type = TypeName("void")
  179. params = parse_arguments(method)
  180. desc_element = method.find("description")
  181. method_desc = None
  182. if desc_element is not None:
  183. method_desc = desc_element.text
  184. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  185. if method_name not in class_def.methods:
  186. class_def.methods[method_name] = []
  187. class_def.methods[method_name].append(method_def)
  188. constants = class_root.find("constants")
  189. if constants is not None:
  190. for constant in constants:
  191. assert constant.tag == "constant"
  192. constant_name = constant.attrib["name"]
  193. value = constant.attrib["value"]
  194. enum = constant.get("enum")
  195. constant_def = ConstantDef(constant_name, value, constant.text)
  196. if enum is None:
  197. if constant_name in class_def.constants:
  198. print_error("Duplicate constant '{}', file: {}".format(constant_name, class_name), self)
  199. continue
  200. class_def.constants[constant_name] = constant_def
  201. else:
  202. if enum in class_def.enums:
  203. enum_def = class_def.enums[enum]
  204. else:
  205. enum_def = EnumDef(enum)
  206. class_def.enums[enum] = enum_def
  207. enum_def.values[constant_name] = constant_def
  208. signals = class_root.find("signals")
  209. if signals is not None:
  210. for signal in signals:
  211. assert signal.tag == "signal"
  212. signal_name = signal.attrib["name"]
  213. if signal_name in class_def.signals:
  214. print_error("Duplicate signal '{}', file: {}".format(signal_name, class_name), self)
  215. continue
  216. params = parse_arguments(signal)
  217. desc_element = signal.find("description")
  218. signal_desc = None
  219. if desc_element is not None:
  220. signal_desc = desc_element.text
  221. signal_def = SignalDef(signal_name, params, signal_desc)
  222. class_def.signals[signal_name] = signal_def
  223. theme_items = class_root.find("theme_items")
  224. if theme_items is not None:
  225. for theme_item in theme_items:
  226. assert theme_item.tag == "theme_item"
  227. theme_item_name = theme_item.attrib["name"]
  228. theme_item_data_name = theme_item.attrib["data_type"]
  229. theme_item_id = "{}_{}".format(theme_item_data_name, theme_item_name)
  230. if theme_item_id in class_def.theme_items:
  231. print_error(
  232. "Duplicate theme property '{}' of type '{}', file: {}".format(
  233. theme_item_name, theme_item_data_name, class_name
  234. ),
  235. self,
  236. )
  237. continue
  238. default_value = theme_item.get("default") or None
  239. if default_value is not None:
  240. default_value = "``{}``".format(default_value)
  241. theme_item_def = ThemeItemDef(
  242. theme_item_name,
  243. TypeName.from_element(theme_item),
  244. theme_item_data_name,
  245. theme_item.text,
  246. default_value,
  247. )
  248. class_def.theme_items[theme_item_id] = theme_item_def
  249. tutorials = class_root.find("tutorials")
  250. if tutorials is not None:
  251. for link in tutorials:
  252. assert link.tag == "link"
  253. if link.text is not None:
  254. class_def.tutorials.append((link.text.strip(), link.get("title", "")))
  255. def sort_classes(self): # type: () -> None
  256. self.classes = OrderedDict(sorted(self.classes.items(), key=lambda t: t[0]))
  257. def parse_arguments(root): # type: (ET.Element) -> List[ParameterDef]
  258. param_elements = root.findall("argument")
  259. params = [None] * len(param_elements) # type: Any
  260. for param_element in param_elements:
  261. param_name = param_element.attrib["name"]
  262. index = int(param_element.attrib["index"])
  263. type_name = TypeName.from_element(param_element)
  264. default = param_element.get("default")
  265. params[index] = ParameterDef(param_name, type_name, default)
  266. cast = params # type: List[ParameterDef]
  267. return cast
  268. def main(): # type: () -> None
  269. parser = argparse.ArgumentParser()
  270. parser.add_argument("path", nargs="+", help="A path to an XML file or a directory containing XML files to parse.")
  271. parser.add_argument("--filter", default="", help="The filepath pattern for XML files to filter.")
  272. parser.add_argument("--lang", "-l", default="en", help="Language to use for section headings.")
  273. group = parser.add_mutually_exclusive_group()
  274. group.add_argument("--output", "-o", default=".", help="The directory to save output .rst files in.")
  275. group.add_argument(
  276. "--dry-run",
  277. action="store_true",
  278. help="If passed, no output will be generated and XML files are only checked for errors.",
  279. )
  280. args = parser.parse_args()
  281. # Retrieve heading translations for the given language.
  282. if not args.dry_run and args.lang != "en":
  283. lang_file = os.path.join(
  284. os.path.dirname(os.path.realpath(__file__)), "..", "translations", "{}.po".format(args.lang)
  285. )
  286. if os.path.exists(lang_file):
  287. try:
  288. import polib
  289. except ImportError:
  290. print("Base template strings localization requires `polib`.")
  291. exit(1)
  292. pofile = polib.pofile(lang_file)
  293. for entry in pofile.translated_entries():
  294. if entry.msgid in BASE_STRINGS:
  295. strings_l10n[entry.msgid] = entry.msgstr
  296. else:
  297. print("No PO file at '{}' for language '{}'.".format(lang_file, args.lang))
  298. print("Checking for errors in the XML class reference...")
  299. file_list = [] # type: List[str]
  300. for path in args.path:
  301. # Cut off trailing slashes so os.path.basename doesn't choke.
  302. if path.endswith("/") or path.endswith("\\"):
  303. path = path[:-1]
  304. if os.path.basename(path) == "modules":
  305. for subdir, dirs, _ in os.walk(path):
  306. if "doc_classes" in dirs:
  307. doc_dir = os.path.join(subdir, "doc_classes")
  308. class_file_names = (f for f in os.listdir(doc_dir) if f.endswith(".xml"))
  309. file_list += (os.path.join(doc_dir, f) for f in class_file_names)
  310. elif os.path.isdir(path):
  311. file_list += (os.path.join(path, f) for f in os.listdir(path) if f.endswith(".xml"))
  312. elif os.path.isfile(path):
  313. if not path.endswith(".xml"):
  314. print("Got non-.xml file '{}' in input, skipping.".format(path))
  315. continue
  316. file_list.append(path)
  317. classes = {} # type: Dict[str, ET.Element]
  318. state = State()
  319. for cur_file in file_list:
  320. try:
  321. tree = ET.parse(cur_file)
  322. except ET.ParseError as e:
  323. print_error("Parse error reading file '{}': {}".format(cur_file, e), state)
  324. continue
  325. doc = tree.getroot()
  326. if "version" not in doc.attrib:
  327. print_error("Version missing from 'doc', file: {}".format(cur_file), state)
  328. continue
  329. name = doc.attrib["name"]
  330. if name in classes:
  331. print_error("Duplicate class '{}'".format(name), state)
  332. continue
  333. classes[name] = (doc, cur_file)
  334. for name, data in classes.items():
  335. try:
  336. state.parse_class(data[0], data[1])
  337. except Exception as e:
  338. print_error("Exception while parsing class '{}': {}".format(name, e), state)
  339. state.sort_classes()
  340. pattern = re.compile(args.filter)
  341. # Create the output folder recursively if it doesn't already exist.
  342. os.makedirs(args.output, exist_ok=True)
  343. for class_name, class_def in state.classes.items():
  344. if args.filter and not pattern.search(class_def.filepath):
  345. continue
  346. state.current_class = class_name
  347. make_rst_class(class_def, state, args.dry_run, args.output)
  348. if not state.errored:
  349. print("No errors found.")
  350. if not args.dry_run:
  351. print("Wrote reStructuredText files for each class to: %s" % args.output)
  352. else:
  353. print("Errors were found in the class reference XML. Please check the messages above.")
  354. exit(1)
  355. def translate(string): # type: (str) -> str
  356. """Translate a string based on translations sourced from `doc/translations/*.po`
  357. for a language if defined via the --lang command line argument.
  358. Returns the original string if no translation exists.
  359. """
  360. return strings_l10n.get(string, string)
  361. def make_rst_class(class_def, state, dry_run, output_dir): # type: (ClassDef, State, bool, str) -> None
  362. class_name = class_def.name
  363. if dry_run:
  364. f = open(os.devnull, "w", encoding="utf-8")
  365. else:
  366. f = open(os.path.join(output_dir, "class_" + class_name.lower() + ".rst"), "w", encoding="utf-8")
  367. # Remove the "Edit on Github" button from the online docs page.
  368. f.write(":github_url: hide\n\n")
  369. # Warn contributors not to edit this file directly.
  370. # Also provide links to the source files for reference.
  371. git_branch = "master"
  372. if hasattr(version, "docs") and version.docs != "latest":
  373. git_branch = version.docs
  374. source_xml_path = os.path.relpath(class_def.filepath, root_directory).replace("\\", "/")
  375. source_github_url = "https://github.com/godotengine/godot/tree/{}/{}".format(git_branch, source_xml_path)
  376. generator_github_url = "https://github.com/godotengine/godot/tree/{}/doc/tools/make_rst.py".format(git_branch)
  377. f.write(".. DO NOT EDIT THIS FILE!!!\n")
  378. f.write(".. Generated automatically from Godot engine sources.\n")
  379. f.write(".. Generator: " + generator_github_url + ".\n")
  380. f.write(".. XML source: " + source_github_url + ".\n\n")
  381. # Document reference id and header.
  382. f.write(".. _class_" + class_name + ":\n\n")
  383. f.write(make_heading(class_name, "=", False))
  384. # Inheritance tree
  385. # Ascendants
  386. if class_def.inherits:
  387. inherits = class_def.inherits.strip()
  388. f.write("**" + translate("Inherits:") + "** ")
  389. first = True
  390. while inherits in state.classes:
  391. if not first:
  392. f.write(" **<** ")
  393. else:
  394. first = False
  395. f.write(make_type(inherits, state))
  396. inode = state.classes[inherits].inherits
  397. if inode:
  398. inherits = inode.strip()
  399. else:
  400. break
  401. f.write("\n\n")
  402. # Descendents
  403. inherited = []
  404. for c in state.classes.values():
  405. if c.inherits and c.inherits.strip() == class_name:
  406. inherited.append(c.name)
  407. if len(inherited):
  408. f.write("**" + translate("Inherited By:") + "** ")
  409. for i, child in enumerate(inherited):
  410. if i > 0:
  411. f.write(", ")
  412. f.write(make_type(child, state))
  413. f.write("\n\n")
  414. # Brief description
  415. if class_def.brief_description is not None:
  416. f.write(rstize_text(class_def.brief_description.strip(), state) + "\n\n")
  417. # Class description
  418. if class_def.description is not None and class_def.description.strip() != "":
  419. f.write(make_heading("Description", "-"))
  420. f.write(rstize_text(class_def.description.strip(), state) + "\n\n")
  421. # Online tutorials
  422. if len(class_def.tutorials) > 0:
  423. f.write(make_heading("Tutorials", "-"))
  424. for url, title in class_def.tutorials:
  425. f.write("- " + make_link(url, title) + "\n\n")
  426. # Properties overview
  427. if len(class_def.properties) > 0:
  428. f.write(make_heading("Properties", "-"))
  429. ml = [] # type: List[Tuple[str, str, str]]
  430. for property_def in class_def.properties.values():
  431. type_rst = property_def.type_name.to_rst(state)
  432. default = property_def.default_value
  433. if default is not None and property_def.overrides:
  434. ref = ":ref:`{1}<class_{1}_property_{0}>`".format(property_def.name, property_def.overrides)
  435. # Not using translate() for now as it breaks table formatting.
  436. ml.append((type_rst, property_def.name, default + " " + "(overrides %s)" % ref))
  437. else:
  438. ref = ":ref:`{0}<class_{1}_property_{0}>`".format(property_def.name, class_name)
  439. ml.append((type_rst, ref, default))
  440. format_table(f, ml, True)
  441. # Methods overview
  442. if len(class_def.methods) > 0:
  443. f.write(make_heading("Methods", "-"))
  444. ml = []
  445. for method_list in class_def.methods.values():
  446. for m in method_list:
  447. ml.append(make_method_signature(class_def, m, True, state))
  448. format_table(f, ml)
  449. # Theme properties
  450. if len(class_def.theme_items) > 0:
  451. f.write(make_heading("Theme Properties", "-"))
  452. pl = []
  453. for theme_item_def in class_def.theme_items.values():
  454. ref = ":ref:`{0}<class_{2}_theme_{1}_{0}>`".format(
  455. theme_item_def.name, theme_item_def.data_name, class_name
  456. )
  457. pl.append((theme_item_def.type_name.to_rst(state), ref, theme_item_def.default_value))
  458. format_table(f, pl, True)
  459. # Signals
  460. if len(class_def.signals) > 0:
  461. f.write(make_heading("Signals", "-"))
  462. index = 0
  463. for signal in class_def.signals.values():
  464. if index != 0:
  465. f.write("----\n\n")
  466. f.write(".. _class_{}_signal_{}:\n\n".format(class_name, signal.name))
  467. _, signature = make_method_signature(class_def, signal, False, state)
  468. f.write("- {}\n\n".format(signature))
  469. if signal.description is not None and signal.description.strip() != "":
  470. f.write(rstize_text(signal.description.strip(), state) + "\n\n")
  471. index += 1
  472. # Enums
  473. if len(class_def.enums) > 0:
  474. f.write(make_heading("Enumerations", "-"))
  475. index = 0
  476. for e in class_def.enums.values():
  477. if index != 0:
  478. f.write("----\n\n")
  479. f.write(".. _enum_{}_{}:\n\n".format(class_name, e.name))
  480. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  481. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  482. # As to why I'm not modifying the reference parser to directly link to the _enum label:
  483. # If somebody gets annoyed enough to fix it, all existing references will magically improve.
  484. for value in e.values.values():
  485. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, value.name))
  486. f.write("enum **{}**:\n\n".format(e.name))
  487. for value in e.values.values():
  488. f.write("- **{}** = **{}**".format(value.name, value.value))
  489. if value.text is not None and value.text.strip() != "":
  490. # If value.text contains a bullet point list, each entry needs additional indentation
  491. f.write(" --- " + indent_bullets(rstize_text(value.text.strip(), state)))
  492. f.write("\n\n")
  493. index += 1
  494. # Constants
  495. if len(class_def.constants) > 0:
  496. f.write(make_heading("Constants", "-"))
  497. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  498. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  499. for constant in class_def.constants.values():
  500. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, constant.name))
  501. for constant in class_def.constants.values():
  502. f.write("- **{}** = **{}**".format(constant.name, constant.value))
  503. if constant.text is not None and constant.text.strip() != "":
  504. f.write(" --- " + rstize_text(constant.text.strip(), state))
  505. f.write("\n\n")
  506. # Property descriptions
  507. if any(not p.overrides for p in class_def.properties.values()) > 0:
  508. f.write(make_heading("Property Descriptions", "-"))
  509. index = 0
  510. for property_def in class_def.properties.values():
  511. if property_def.overrides:
  512. continue
  513. if index != 0:
  514. f.write("----\n\n")
  515. f.write(".. _class_{}_property_{}:\n\n".format(class_name, property_def.name))
  516. f.write("- {} **{}**\n\n".format(property_def.type_name.to_rst(state), property_def.name))
  517. info = []
  518. # Not using translate() for now as it breaks table formatting.
  519. if property_def.default_value is not None:
  520. info.append(("*" + "Default" + "*", property_def.default_value))
  521. if property_def.setter is not None and not property_def.setter.startswith("_"):
  522. info.append(("*" + "Setter" + "*", property_def.setter + "(" + "value" + ")"))
  523. if property_def.getter is not None and not property_def.getter.startswith("_"):
  524. info.append(("*" + "Getter" + "*", property_def.getter + "()"))
  525. if len(info) > 0:
  526. format_table(f, info)
  527. if property_def.text is not None and property_def.text.strip() != "":
  528. f.write(rstize_text(property_def.text.strip(), state) + "\n\n")
  529. index += 1
  530. # Method descriptions
  531. if len(class_def.methods) > 0:
  532. f.write(make_heading("Method Descriptions", "-"))
  533. index = 0
  534. for method_list in class_def.methods.values():
  535. for i, m in enumerate(method_list):
  536. if index != 0:
  537. f.write("----\n\n")
  538. if i == 0:
  539. f.write(".. _class_{}_method_{}:\n\n".format(class_name, m.name))
  540. ret_type, signature = make_method_signature(class_def, m, False, state)
  541. f.write("- {} {}\n\n".format(ret_type, signature))
  542. if m.description is not None and m.description.strip() != "":
  543. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  544. index += 1
  545. # Theme property descriptions
  546. if len(class_def.theme_items) > 0:
  547. f.write(make_heading("Theme Property Descriptions", "-"))
  548. index = 0
  549. for theme_item_def in class_def.theme_items.values():
  550. if index != 0:
  551. f.write("----\n\n")
  552. f.write(".. _class_{}_theme_{}_{}:\n\n".format(class_name, theme_item_def.data_name, theme_item_def.name))
  553. f.write("- {} **{}**\n\n".format(theme_item_def.type_name.to_rst(state), theme_item_def.name))
  554. info = []
  555. if theme_item_def.default_value is not None:
  556. # Not using translate() for now as it breaks table formatting.
  557. info.append(("*" + "Default" + "*", theme_item_def.default_value))
  558. if len(info) > 0:
  559. format_table(f, info)
  560. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  561. f.write(rstize_text(theme_item_def.text.strip(), state) + "\n\n")
  562. index += 1
  563. f.write(make_footer())
  564. def escape_rst(text, until_pos=-1): # type: (str, int) -> str
  565. # Escape \ character, otherwise it ends up as an escape character in rst
  566. pos = 0
  567. while True:
  568. pos = text.find("\\", pos, until_pos)
  569. if pos == -1:
  570. break
  571. text = text[:pos] + "\\\\" + text[pos + 1 :]
  572. pos += 2
  573. # Escape * character to avoid interpreting it as emphasis
  574. pos = 0
  575. while True:
  576. pos = text.find("*", pos, until_pos)
  577. if pos == -1:
  578. break
  579. text = text[:pos] + "\*" + text[pos + 1 :]
  580. pos += 2
  581. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  582. pos = 0
  583. while True:
  584. pos = text.find("_", pos, until_pos)
  585. if pos == -1:
  586. break
  587. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  588. text = text[:pos] + "\_" + text[pos + 1 :]
  589. pos += 2
  590. else:
  591. pos += 1
  592. return text
  593. def rstize_text(text, state): # type: (str, State) -> str
  594. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  595. pos = 0
  596. while True:
  597. pos = text.find("\n", pos)
  598. if pos == -1:
  599. break
  600. pre_text = text[:pos]
  601. indent_level = 0
  602. while pos + 1 < len(text) and text[pos + 1] == "\t":
  603. pos += 1
  604. indent_level += 1
  605. post_text = text[pos + 1 :]
  606. # Handle codeblocks
  607. if post_text.startswith("[codeblock]"):
  608. end_pos = post_text.find("[/codeblock]")
  609. if end_pos == -1:
  610. print_error("[codeblock] without a closing tag, file: {}".format(state.current_class), state)
  611. return ""
  612. code_text = post_text[len("[codeblock]") : end_pos]
  613. post_text = post_text[end_pos:]
  614. # Remove extraneous tabs
  615. code_pos = 0
  616. while True:
  617. code_pos = code_text.find("\n", code_pos)
  618. if code_pos == -1:
  619. break
  620. to_skip = 0
  621. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  622. to_skip += 1
  623. if to_skip > indent_level:
  624. print_error(
  625. "Four spaces should be used for indentation within [codeblock], file: {}".format(
  626. state.current_class
  627. ),
  628. state,
  629. )
  630. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  631. code_text = code_text[:code_pos] + "\n"
  632. code_pos += 1
  633. else:
  634. code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1 :]
  635. code_pos += 5 - to_skip
  636. text = pre_text + "\n[codeblock]" + code_text + post_text
  637. pos += len("\n[codeblock]" + code_text) - indent_level
  638. # Handle normal text
  639. else:
  640. text = pre_text + "\n\n" + post_text
  641. pos += 2 - indent_level
  642. next_brac_pos = text.find("[")
  643. text = escape_rst(text, next_brac_pos)
  644. # Handle [tags]
  645. inside_code = False
  646. pos = 0
  647. tag_depth = 0
  648. previous_pos = 0
  649. while True:
  650. pos = text.find("[", pos)
  651. if pos == -1:
  652. break
  653. endq_pos = text.find("]", pos + 1)
  654. if endq_pos == -1:
  655. break
  656. pre_text = text[:pos]
  657. post_text = text[endq_pos + 1 :]
  658. tag_text = text[pos + 1 : endq_pos]
  659. escape_pre = False
  660. escape_post = False
  661. if tag_text in state.classes:
  662. if tag_text == state.current_class:
  663. # We don't want references to the same class
  664. tag_text = "``{}``".format(tag_text)
  665. else:
  666. tag_text = make_type(tag_text, state)
  667. escape_pre = True
  668. escape_post = True
  669. else: # command
  670. cmd = tag_text
  671. space_pos = tag_text.find(" ")
  672. if cmd == "/codeblock":
  673. tag_text = ""
  674. tag_depth -= 1
  675. inside_code = False
  676. # Strip newline if the tag was alone on one
  677. if pre_text[-1] == "\n":
  678. pre_text = pre_text[:-1]
  679. elif cmd == "/code":
  680. tag_text = "``"
  681. tag_depth -= 1
  682. inside_code = False
  683. escape_post = True
  684. elif inside_code:
  685. tag_text = "[" + tag_text + "]"
  686. elif cmd.find("html") == 0:
  687. param = tag_text[space_pos + 1 :]
  688. tag_text = param
  689. elif (
  690. cmd.startswith("method")
  691. or cmd.startswith("member")
  692. or cmd.startswith("signal")
  693. or cmd.startswith("constant")
  694. ):
  695. param = tag_text[space_pos + 1 :]
  696. if param.find(".") != -1:
  697. ss = param.split(".")
  698. if len(ss) > 2:
  699. print_error("Bad reference: '{}', file: {}".format(param, state.current_class), state)
  700. class_param, method_param = ss
  701. else:
  702. class_param = state.current_class
  703. method_param = param
  704. ref_type = ""
  705. if class_param in state.classes:
  706. class_def = state.classes[class_param]
  707. if cmd.startswith("method"):
  708. if method_param not in class_def.methods:
  709. print_error("Unresolved method '{}', file: {}".format(param, state.current_class), state)
  710. ref_type = "_method"
  711. elif cmd.startswith("member"):
  712. if method_param not in class_def.properties:
  713. print_error("Unresolved member '{}', file: {}".format(param, state.current_class), state)
  714. ref_type = "_property"
  715. elif cmd.startswith("signal"):
  716. if method_param not in class_def.signals:
  717. print_error("Unresolved signal '{}', file: {}".format(param, state.current_class), state)
  718. ref_type = "_signal"
  719. elif cmd.startswith("constant"):
  720. found = False
  721. # Search in the current class
  722. search_class_defs = [class_def]
  723. if param.find(".") == -1:
  724. # Also search in @GlobalScope as a last resort if no class was specified
  725. search_class_defs.append(state.classes["@GlobalScope"])
  726. for search_class_def in search_class_defs:
  727. if method_param in search_class_def.constants:
  728. class_param = search_class_def.name
  729. found = True
  730. else:
  731. for enum in search_class_def.enums.values():
  732. if method_param in enum.values:
  733. class_param = search_class_def.name
  734. found = True
  735. break
  736. if not found:
  737. print_error("Unresolved constant '{}', file: {}".format(param, state.current_class), state)
  738. ref_type = "_constant"
  739. else:
  740. print_error(
  741. "Unresolved type reference '{}' in method reference '{}', file: {}".format(
  742. class_param, param, state.current_class
  743. ),
  744. state,
  745. )
  746. repl_text = method_param
  747. if class_param != state.current_class:
  748. repl_text = "{}.{}".format(class_param, method_param)
  749. tag_text = ":ref:`{}<class_{}{}_{}>`".format(repl_text, class_param, ref_type, method_param)
  750. escape_pre = True
  751. escape_post = True
  752. elif cmd.find("image=") == 0:
  753. tag_text = "" # '![](' + cmd[6:] + ')'
  754. elif cmd.find("url=") == 0:
  755. # URLs are handled in full here as we need to extract the optional link
  756. # title to use `make_link`.
  757. link_url = cmd[4:]
  758. endurl_pos = text.find("[/url]", endq_pos + 1)
  759. if endurl_pos == -1:
  760. print_error(
  761. "Tag depth mismatch for [url]: no closing [/url], file: {}".format(state.current_class), state
  762. )
  763. break
  764. link_title = text[endq_pos + 1 : endurl_pos]
  765. tag_text = make_link(link_url, link_title)
  766. pre_text = text[:pos]
  767. post_text = text[endurl_pos + 6 :]
  768. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  769. pre_text += "\ "
  770. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  771. post_text = "\ " + post_text
  772. text = pre_text + tag_text + post_text
  773. pos = len(pre_text) + len(tag_text)
  774. previous_pos = pos
  775. continue
  776. elif cmd == "center":
  777. tag_depth += 1
  778. tag_text = ""
  779. elif cmd == "/center":
  780. tag_depth -= 1
  781. tag_text = ""
  782. elif cmd == "codeblock":
  783. tag_depth += 1
  784. tag_text = "\n::\n"
  785. inside_code = True
  786. elif cmd == "br":
  787. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  788. tag_text = "\n\n"
  789. # Strip potential leading spaces
  790. while post_text[0] == " ":
  791. post_text = post_text[1:]
  792. elif cmd == "i" or cmd == "/i":
  793. if cmd == "/i":
  794. tag_depth -= 1
  795. escape_post = True
  796. else:
  797. tag_depth += 1
  798. escape_pre = True
  799. tag_text = "*"
  800. elif cmd == "b" or cmd == "/b":
  801. if cmd == "/b":
  802. tag_depth -= 1
  803. escape_post = True
  804. else:
  805. tag_depth += 1
  806. escape_pre = True
  807. tag_text = "**"
  808. elif cmd == "u" or cmd == "/u":
  809. if cmd == "/u":
  810. tag_depth -= 1
  811. escape_post = True
  812. else:
  813. tag_depth += 1
  814. escape_pre = True
  815. tag_text = ""
  816. elif cmd == "code":
  817. tag_text = "``"
  818. tag_depth += 1
  819. inside_code = True
  820. escape_pre = True
  821. elif cmd == "kbd":
  822. tag_text = ":kbd:`"
  823. tag_depth += 1
  824. elif cmd == "/kbd":
  825. tag_text = "`"
  826. tag_depth -= 1
  827. elif cmd.startswith("enum "):
  828. tag_text = make_enum(cmd[5:], state)
  829. escape_pre = True
  830. escape_post = True
  831. else:
  832. tag_text = make_type(tag_text, state)
  833. escape_pre = True
  834. escape_post = True
  835. # Properly escape things like `[Node]s`
  836. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  837. pre_text += "\ "
  838. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  839. post_text = "\ " + post_text
  840. next_brac_pos = post_text.find("[", 0)
  841. iter_pos = 0
  842. while not inside_code:
  843. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  844. if iter_pos == -1:
  845. break
  846. post_text = post_text[:iter_pos] + "\*" + post_text[iter_pos + 1 :]
  847. iter_pos += 2
  848. iter_pos = 0
  849. while not inside_code:
  850. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  851. if iter_pos == -1:
  852. break
  853. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  854. post_text = post_text[:iter_pos] + "\_" + post_text[iter_pos + 1 :]
  855. iter_pos += 2
  856. else:
  857. iter_pos += 1
  858. text = pre_text + tag_text + post_text
  859. pos = len(pre_text) + len(tag_text)
  860. previous_pos = pos
  861. if tag_depth > 0:
  862. print_error("Tag depth mismatch: too many/little open/close tags, file: {}".format(state.current_class), state)
  863. return text
  864. def format_table(f, data, remove_empty_columns=False): # type: (TextIO, Iterable[Tuple[str, ...]], bool) -> None
  865. if len(data) == 0:
  866. return
  867. column_sizes = [0] * len(data[0])
  868. for row in data:
  869. for i, text in enumerate(row):
  870. text_length = len(text or "")
  871. if text_length > column_sizes[i]:
  872. column_sizes[i] = text_length
  873. sep = ""
  874. for size in column_sizes:
  875. if size == 0 and remove_empty_columns:
  876. continue
  877. sep += "+" + "-" * (size + 2)
  878. sep += "+\n"
  879. f.write(sep)
  880. for row in data:
  881. row_text = "|"
  882. for i, text in enumerate(row):
  883. if column_sizes[i] == 0 and remove_empty_columns:
  884. continue
  885. row_text += " " + (text or "").ljust(column_sizes[i]) + " |"
  886. row_text += "\n"
  887. f.write(row_text)
  888. f.write(sep)
  889. f.write("\n")
  890. def make_type(t, state): # type: (str, State) -> str
  891. if t in state.classes:
  892. return ":ref:`{0}<class_{0}>`".format(t)
  893. print_error("Unresolved type '{}', file: {}".format(t, state.current_class), state)
  894. return t
  895. def make_enum(t, state): # type: (str, State) -> str
  896. p = t.find(".")
  897. if p >= 0:
  898. c = t[0:p]
  899. e = t[p + 1 :]
  900. # Variant enums live in GlobalScope but still use periods.
  901. if c == "Variant":
  902. c = "@GlobalScope"
  903. e = "Variant." + e
  904. else:
  905. c = state.current_class
  906. e = t
  907. if c in state.classes and e not in state.classes[c].enums:
  908. c = "@GlobalScope"
  909. if not c in state.classes and c.startswith("_"):
  910. c = c[1:] # Remove the underscore prefix
  911. if c in state.classes and e in state.classes[c].enums:
  912. return ":ref:`{0}<enum_{1}_{0}>`".format(e, c)
  913. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  914. if "{}.{}".format(c, e) != "Vector3.Axis":
  915. print_error("Unresolved enum '{}', file: {}".format(t, state.current_class), state)
  916. return t
  917. def make_method_signature(
  918. class_def, method_def, make_ref, state
  919. ): # type: (ClassDef, Union[MethodDef, SignalDef], bool, State) -> Tuple[str, str]
  920. ret_type = " "
  921. ref_type = "signal"
  922. if isinstance(method_def, MethodDef):
  923. ret_type = method_def.return_type.to_rst(state)
  924. ref_type = "method"
  925. out = ""
  926. if make_ref:
  927. out += ":ref:`{0}<class_{1}_{2}_{0}>` ".format(method_def.name, class_def.name, ref_type)
  928. else:
  929. out += "**{}** ".format(method_def.name)
  930. out += "**(**"
  931. for i, arg in enumerate(method_def.parameters):
  932. if i > 0:
  933. out += ", "
  934. else:
  935. out += " "
  936. out += "{} {}".format(arg.type_name.to_rst(state), arg.name)
  937. if arg.default_value is not None:
  938. out += "=" + arg.default_value
  939. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None and "vararg" in method_def.qualifiers:
  940. if len(method_def.parameters) > 0:
  941. out += ", ..."
  942. else:
  943. out += " ..."
  944. out += " **)**"
  945. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None:
  946. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  947. # See `make_footer()` for descriptions.
  948. for qualifier in method_def.qualifiers.split():
  949. out += " |" + qualifier + "|"
  950. return ret_type, out
  951. def make_heading(title, underline, l10n=True): # type: (str, str, bool) -> str
  952. if l10n:
  953. new_title = translate(title)
  954. if new_title != title:
  955. title = new_title
  956. underline *= 2 # Double length to handle wide chars.
  957. return title + "\n" + (underline * len(title)) + "\n\n"
  958. def make_footer(): # type: () -> str
  959. # Generate reusable abbreviation substitutions.
  960. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  961. # fmt: off
  962. return (
  963. ".. |virtual| replace:: :abbr:`virtual (" + translate("This method should typically be overridden by the user to have any effect.") + ")`\n"
  964. ".. |const| replace:: :abbr:`const (" + translate("This method has no side effects. It doesn't modify any of the instance's member variables.") + ")`\n"
  965. ".. |vararg| replace:: :abbr:`vararg (" + translate("This method accepts any number of arguments after the ones described here.") + ")`\n"
  966. )
  967. # fmt: on
  968. def make_link(url, title): # type: (str, str) -> str
  969. match = GODOT_DOCS_PATTERN.search(url)
  970. if match:
  971. groups = match.groups()
  972. if match.lastindex == 2:
  973. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  974. # `#calling-javascript-from-script in Exporting For Web`
  975. # Or use the title if provided.
  976. if title != "":
  977. return "`" + title + " <../" + groups[0] + ".html" + groups[1] + ">`__"
  978. return "`" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`__ in :doc:`../" + groups[0] + "`"
  979. elif match.lastindex == 1:
  980. # Doc reference, for example:
  981. # `Math`
  982. if title != "":
  983. return ":doc:`" + title + " <../" + groups[0] + ">`"
  984. return ":doc:`../" + groups[0] + "`"
  985. else:
  986. # External link, for example:
  987. # `http://enet.bespin.org/usergroup0.html`
  988. if title != "":
  989. return "`" + title + " <" + url + ">`__"
  990. return "`" + url + " <" + url + ">`__"
  991. def indent_bullets(text): # type: (str) -> str
  992. # Take the text and check each line for a bullet point represented by "-".
  993. # Where found, indent the given line by a further "\t".
  994. # Used to properly indent bullet points contained in the description for enum values.
  995. # Ignore the first line - text will be prepended to it so bullet points wouldn't work anyway.
  996. bullet_points = "-"
  997. lines = text.splitlines(keepends=True)
  998. for line_index, line in enumerate(lines[1:], start=1):
  999. pos = 0
  1000. while pos < len(line) and line[pos] == "\t":
  1001. pos += 1
  1002. if pos < len(line) and line[pos] in bullet_points:
  1003. lines[line_index] = line[:pos] + "\t" + line[pos:]
  1004. return "".join(lines)
  1005. if __name__ == "__main__":
  1006. main()