makerst.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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 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. inside_url = False
  572. url_has_name = False
  573. url_link = ""
  574. pos = 0
  575. tag_depth = 0
  576. previous_pos = 0
  577. while True:
  578. pos = text.find("[", pos)
  579. if inside_url and (pos > previous_pos):
  580. url_has_name = True
  581. if pos == -1:
  582. break
  583. endq_pos = text.find("]", pos + 1)
  584. if endq_pos == -1:
  585. break
  586. pre_text = text[:pos]
  587. post_text = text[endq_pos + 1 :]
  588. tag_text = text[pos + 1 : endq_pos]
  589. escape_post = False
  590. if tag_text in state.classes:
  591. if tag_text == state.current_class:
  592. # We don't want references to the same class
  593. tag_text = "``{}``".format(tag_text)
  594. else:
  595. tag_text = make_type(tag_text, state)
  596. escape_post = True
  597. else: # command
  598. cmd = tag_text
  599. space_pos = tag_text.find(" ")
  600. if cmd == "/codeblock":
  601. tag_text = ""
  602. tag_depth -= 1
  603. inside_code = False
  604. # Strip newline if the tag was alone on one
  605. if pre_text[-1] == "\n":
  606. pre_text = pre_text[:-1]
  607. elif cmd == "/code":
  608. tag_text = "``"
  609. tag_depth -= 1
  610. inside_code = False
  611. escape_post = True
  612. elif inside_code:
  613. tag_text = "[" + tag_text + "]"
  614. elif cmd.find("html") == 0:
  615. param = tag_text[space_pos + 1 :]
  616. tag_text = param
  617. elif (
  618. cmd.startswith("method")
  619. or cmd.startswith("member")
  620. or cmd.startswith("signal")
  621. or cmd.startswith("constant")
  622. ):
  623. param = tag_text[space_pos + 1 :]
  624. if param.find(".") != -1:
  625. ss = param.split(".")
  626. if len(ss) > 2:
  627. print_error("Bad reference: '{}', file: {}".format(param, state.current_class), state)
  628. class_param, method_param = ss
  629. else:
  630. class_param = state.current_class
  631. method_param = param
  632. ref_type = ""
  633. if class_param in state.classes:
  634. class_def = state.classes[class_param]
  635. if cmd.startswith("method"):
  636. if method_param not in class_def.methods:
  637. print_error("Unresolved method '{}', file: {}".format(param, state.current_class), state)
  638. ref_type = "_method"
  639. elif cmd.startswith("member"):
  640. if method_param not in class_def.properties:
  641. print_error("Unresolved member '{}', file: {}".format(param, state.current_class), state)
  642. ref_type = "_property"
  643. elif cmd.startswith("signal"):
  644. if method_param not in class_def.signals:
  645. print_error("Unresolved signal '{}', file: {}".format(param, state.current_class), state)
  646. ref_type = "_signal"
  647. elif cmd.startswith("constant"):
  648. found = False
  649. # Search in the current class
  650. search_class_defs = [class_def]
  651. if param.find(".") == -1:
  652. # Also search in @GlobalScope as a last resort if no class was specified
  653. search_class_defs.append(state.classes["@GlobalScope"])
  654. for search_class_def in search_class_defs:
  655. if method_param in search_class_def.constants:
  656. class_param = search_class_def.name
  657. found = True
  658. else:
  659. for enum in search_class_def.enums.values():
  660. if method_param in enum.values:
  661. class_param = search_class_def.name
  662. found = True
  663. break
  664. if not found:
  665. print_error("Unresolved constant '{}', file: {}".format(param, state.current_class), state)
  666. ref_type = "_constant"
  667. else:
  668. print_error(
  669. "Unresolved type reference '{}' in method reference '{}', file: {}".format(
  670. class_param, param, state.current_class
  671. ),
  672. state,
  673. )
  674. repl_text = method_param
  675. if class_param != state.current_class:
  676. repl_text = "{}.{}".format(class_param, method_param)
  677. tag_text = ":ref:`{}<class_{}{}_{}>`".format(repl_text, class_param, ref_type, method_param)
  678. escape_post = True
  679. elif cmd.find("image=") == 0:
  680. tag_text = "" # '![](' + cmd[6:] + ')'
  681. elif cmd.find("url=") == 0:
  682. url_link = cmd[4:]
  683. tag_text = "`"
  684. tag_depth += 1
  685. inside_url = True
  686. url_has_name = False
  687. elif cmd == "/url":
  688. tag_text = ("" if url_has_name else url_link) + " <" + url_link + ">`_"
  689. tag_depth -= 1
  690. escape_post = True
  691. inside_url = False
  692. url_has_name = False
  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. return "`" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`_ in :doc:`../" + groups[0] + "`"
  871. # Commented out alternative: Instead just emit:
  872. # `Subsection in Exporting For Web`
  873. # return "`Subsection <../" + groups[0] + ".html" + groups[1] + ">`__ in :doc:`../" + groups[0] + "`"
  874. elif match.lastindex == 1:
  875. # Doc reference, for example:
  876. # `Math`
  877. return ":doc:`../" + groups[0] + "`"
  878. else:
  879. # External link, for example:
  880. # `http://enet.bespin.org/usergroup0.html`
  881. if title != "":
  882. return "`" + title + " <" + url + ">`_"
  883. else:
  884. return "`" + url + " <" + url + ">`_"
  885. if __name__ == "__main__":
  886. main()