make_rst.py 40 KB

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