makerst.py 42 KB

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