make_rst.py 42 KB

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