make_rst.py 40 KB

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