makerst.py 40 KB

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