makerst.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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[Tuple[str, 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.strip(), link.get("title", "")))
  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 url, title in class_def.tutorials:
  336. f.write("- " + make_link(url, title) + "\n\n")
  337. # Properties overview
  338. if len(class_def.properties) > 0:
  339. f.write(make_heading("Properties", "-"))
  340. ml = [] # type: List[Tuple[str, str, str]]
  341. for property_def in class_def.properties.values():
  342. type_rst = property_def.type_name.to_rst(state)
  343. default = property_def.default_value
  344. if default is not None and property_def.overridden:
  345. ml.append((type_rst, property_def.name, default + " *(parent override)*"))
  346. else:
  347. ref = ":ref:`{0}<class_{1}_property_{0}>`".format(property_def.name, class_name)
  348. ml.append((type_rst, ref, default))
  349. format_table(f, ml, True)
  350. # Methods overview
  351. if len(class_def.methods) > 0:
  352. f.write(make_heading("Methods", "-"))
  353. ml = []
  354. for method_list in class_def.methods.values():
  355. for m in method_list:
  356. ml.append(make_method_signature(class_def, m, True, state))
  357. format_table(f, ml)
  358. # Theme properties
  359. if class_def.theme_items is not None and len(class_def.theme_items) > 0:
  360. f.write(make_heading("Theme Properties", "-"))
  361. pl = []
  362. for theme_item_list in class_def.theme_items.values():
  363. for theme_item in theme_item_list:
  364. pl.append((theme_item.type_name.to_rst(state), theme_item.name, theme_item.default_value))
  365. format_table(f, pl, True)
  366. # Signals
  367. if len(class_def.signals) > 0:
  368. f.write(make_heading("Signals", "-"))
  369. index = 0
  370. for signal in class_def.signals.values():
  371. if index != 0:
  372. f.write("----\n\n")
  373. f.write(".. _class_{}_signal_{}:\n\n".format(class_name, signal.name))
  374. _, signature = make_method_signature(class_def, signal, False, state)
  375. f.write("- {}\n\n".format(signature))
  376. if signal.description is not None and signal.description.strip() != "":
  377. f.write(rstize_text(signal.description.strip(), state) + "\n\n")
  378. index += 1
  379. # Enums
  380. if len(class_def.enums) > 0:
  381. f.write(make_heading("Enumerations", "-"))
  382. index = 0
  383. for e in class_def.enums.values():
  384. if index != 0:
  385. f.write("----\n\n")
  386. f.write(".. _enum_{}_{}:\n\n".format(class_name, e.name))
  387. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  388. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  389. # As to why I'm not modifying the reference parser to directly link to the _enum label:
  390. # If somebody gets annoyed enough to fix it, all existing references will magically improve.
  391. for value in e.values.values():
  392. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, value.name))
  393. f.write("enum **{}**:\n\n".format(e.name))
  394. for value in e.values.values():
  395. f.write("- **{}** = **{}**".format(value.name, value.value))
  396. if value.text is not None and value.text.strip() != "":
  397. f.write(" --- " + rstize_text(value.text.strip(), state))
  398. f.write("\n\n")
  399. index += 1
  400. # Constants
  401. if len(class_def.constants) > 0:
  402. f.write(make_heading("Constants", "-"))
  403. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  404. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  405. for constant in class_def.constants.values():
  406. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, constant.name))
  407. for constant in class_def.constants.values():
  408. f.write("- **{}** = **{}**".format(constant.name, constant.value))
  409. if constant.text is not None and constant.text.strip() != "":
  410. f.write(" --- " + rstize_text(constant.text.strip(), state))
  411. f.write("\n\n")
  412. # Property descriptions
  413. if any(not p.overridden for p in class_def.properties.values()) > 0:
  414. f.write(make_heading("Property Descriptions", "-"))
  415. index = 0
  416. for property_def in class_def.properties.values():
  417. if property_def.overridden:
  418. continue
  419. if index != 0:
  420. f.write("----\n\n")
  421. f.write(".. _class_{}_property_{}:\n\n".format(class_name, property_def.name))
  422. f.write("- {} **{}**\n\n".format(property_def.type_name.to_rst(state), property_def.name))
  423. info = []
  424. if property_def.default_value is not None:
  425. info.append(("*Default*", property_def.default_value))
  426. if property_def.setter is not None and not property_def.setter.startswith("_"):
  427. info.append(("*Setter*", property_def.setter + "(value)"))
  428. if property_def.getter is not None and not property_def.getter.startswith("_"):
  429. info.append(("*Getter*", property_def.getter + "()"))
  430. if len(info) > 0:
  431. format_table(f, info)
  432. if property_def.text is not None and property_def.text.strip() != "":
  433. f.write(rstize_text(property_def.text.strip(), state) + "\n\n")
  434. index += 1
  435. # Method descriptions
  436. if len(class_def.methods) > 0:
  437. f.write(make_heading("Method Descriptions", "-"))
  438. index = 0
  439. for method_list in class_def.methods.values():
  440. for i, m in enumerate(method_list):
  441. if index != 0:
  442. f.write("----\n\n")
  443. if i == 0:
  444. f.write(".. _class_{}_method_{}:\n\n".format(class_name, m.name))
  445. ret_type, signature = make_method_signature(class_def, m, False, state)
  446. f.write("- {} {}\n\n".format(ret_type, signature))
  447. if m.description is not None and m.description.strip() != "":
  448. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  449. index += 1
  450. f.write(make_footer())
  451. def escape_rst(text, until_pos=-1): # type: (str) -> str
  452. # Escape \ character, otherwise it ends up as an escape character in rst
  453. pos = 0
  454. while True:
  455. pos = text.find("\\", pos, until_pos)
  456. if pos == -1:
  457. break
  458. text = text[:pos] + "\\\\" + text[pos + 1 :]
  459. pos += 2
  460. # Escape * character to avoid interpreting it as emphasis
  461. pos = 0
  462. while True:
  463. pos = text.find("*", pos, until_pos)
  464. if pos == -1:
  465. break
  466. text = text[:pos] + "\*" + text[pos + 1 :]
  467. pos += 2
  468. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  469. pos = 0
  470. while True:
  471. pos = text.find("_", pos, until_pos)
  472. if pos == -1:
  473. break
  474. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  475. text = text[:pos] + "\_" + text[pos + 1 :]
  476. pos += 2
  477. else:
  478. pos += 1
  479. return text
  480. def rstize_text(text, state): # type: (str, State) -> str
  481. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  482. pos = 0
  483. while True:
  484. pos = text.find("\n", pos)
  485. if pos == -1:
  486. break
  487. pre_text = text[:pos]
  488. indent_level = 0
  489. while text[pos + 1] == "\t":
  490. pos += 1
  491. indent_level += 1
  492. post_text = text[pos + 1 :]
  493. # Handle codeblocks
  494. if post_text.startswith("[codeblock]"):
  495. end_pos = post_text.find("[/codeblock]")
  496. if end_pos == -1:
  497. print_error("[codeblock] without a closing tag, file: {}".format(state.current_class), state)
  498. return ""
  499. code_text = post_text[len("[codeblock]") : end_pos]
  500. post_text = post_text[end_pos:]
  501. # Remove extraneous tabs
  502. code_pos = 0
  503. while True:
  504. code_pos = code_text.find("\n", code_pos)
  505. if code_pos == -1:
  506. break
  507. to_skip = 0
  508. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  509. to_skip += 1
  510. if to_skip > indent_level:
  511. print_error(
  512. "Four spaces should be used for indentation within [codeblock], file: {}".format(
  513. state.current_class
  514. ),
  515. state,
  516. )
  517. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  518. code_text = code_text[:code_pos] + "\n"
  519. code_pos += 1
  520. else:
  521. code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1 :]
  522. code_pos += 5 - to_skip
  523. text = pre_text + "\n[codeblock]" + code_text + post_text
  524. pos += len("\n[codeblock]" + code_text)
  525. # Handle normal text
  526. else:
  527. text = pre_text + "\n\n" + post_text
  528. pos += 2
  529. next_brac_pos = text.find("[")
  530. text = escape_rst(text, next_brac_pos)
  531. # Handle [tags]
  532. inside_code = False
  533. inside_url = False
  534. url_has_name = False
  535. url_link = ""
  536. pos = 0
  537. tag_depth = 0
  538. previous_pos = 0
  539. while True:
  540. pos = text.find("[", pos)
  541. if inside_url and (pos > previous_pos):
  542. url_has_name = True
  543. if pos == -1:
  544. break
  545. endq_pos = text.find("]", pos + 1)
  546. if endq_pos == -1:
  547. break
  548. pre_text = text[:pos]
  549. post_text = text[endq_pos + 1 :]
  550. tag_text = text[pos + 1 : endq_pos]
  551. escape_post = False
  552. if tag_text in state.classes:
  553. if tag_text == state.current_class:
  554. # We don't want references to the same class
  555. tag_text = "``{}``".format(tag_text)
  556. else:
  557. tag_text = make_type(tag_text, state)
  558. escape_post = True
  559. else: # command
  560. cmd = tag_text
  561. space_pos = tag_text.find(" ")
  562. if cmd == "/codeblock":
  563. tag_text = ""
  564. tag_depth -= 1
  565. inside_code = False
  566. # Strip newline if the tag was alone on one
  567. if pre_text[-1] == "\n":
  568. pre_text = pre_text[:-1]
  569. elif cmd == "/code":
  570. tag_text = "``"
  571. tag_depth -= 1
  572. inside_code = False
  573. escape_post = True
  574. elif inside_code:
  575. tag_text = "[" + tag_text + "]"
  576. elif cmd.find("html") == 0:
  577. param = tag_text[space_pos + 1 :]
  578. tag_text = param
  579. elif (
  580. cmd.startswith("method")
  581. or cmd.startswith("member")
  582. or cmd.startswith("signal")
  583. or cmd.startswith("constant")
  584. ):
  585. param = tag_text[space_pos + 1 :]
  586. if param.find(".") != -1:
  587. ss = param.split(".")
  588. if len(ss) > 2:
  589. print_error("Bad reference: '{}', file: {}".format(param, state.current_class), state)
  590. class_param, method_param = ss
  591. else:
  592. class_param = state.current_class
  593. method_param = param
  594. ref_type = ""
  595. if class_param in state.classes:
  596. class_def = state.classes[class_param]
  597. if cmd.startswith("method"):
  598. if method_param not in class_def.methods:
  599. print_error("Unresolved method '{}', file: {}".format(param, state.current_class), state)
  600. ref_type = "_method"
  601. elif cmd.startswith("member"):
  602. if method_param not in class_def.properties:
  603. print_error("Unresolved member '{}', file: {}".format(param, state.current_class), state)
  604. ref_type = "_property"
  605. elif cmd.startswith("signal"):
  606. if method_param not in class_def.signals:
  607. print_error("Unresolved signal '{}', file: {}".format(param, state.current_class), state)
  608. ref_type = "_signal"
  609. elif cmd.startswith("constant"):
  610. found = False
  611. # Search in the current class
  612. search_class_defs = [class_def]
  613. if param.find(".") == -1:
  614. # Also search in @GlobalScope as a last resort if no class was specified
  615. search_class_defs.append(state.classes["@GlobalScope"])
  616. for search_class_def in search_class_defs:
  617. if method_param in search_class_def.constants:
  618. class_param = search_class_def.name
  619. found = True
  620. else:
  621. for enum in search_class_def.enums.values():
  622. if method_param in enum.values:
  623. class_param = search_class_def.name
  624. found = True
  625. break
  626. if not found:
  627. print_error("Unresolved constant '{}', file: {}".format(param, state.current_class), state)
  628. ref_type = "_constant"
  629. else:
  630. print_error(
  631. "Unresolved type reference '{}' in method reference '{}', file: {}".format(
  632. class_param, param, state.current_class
  633. ),
  634. state,
  635. )
  636. repl_text = method_param
  637. if class_param != state.current_class:
  638. repl_text = "{}.{}".format(class_param, method_param)
  639. tag_text = ":ref:`{}<class_{}{}_{}>`".format(repl_text, class_param, ref_type, method_param)
  640. escape_post = True
  641. elif cmd.find("image=") == 0:
  642. tag_text = "" # '![](' + cmd[6:] + ')'
  643. elif cmd.find("url=") == 0:
  644. url_link = cmd[4:]
  645. tag_text = "`"
  646. tag_depth += 1
  647. inside_url = True
  648. url_has_name = False
  649. elif cmd == "/url":
  650. tag_text = ("" if url_has_name else url_link) + " <" + url_link + ">`_"
  651. tag_depth -= 1
  652. escape_post = True
  653. inside_url = False
  654. url_has_name = False
  655. elif cmd == "center":
  656. tag_depth += 1
  657. tag_text = ""
  658. elif cmd == "/center":
  659. tag_depth -= 1
  660. tag_text = ""
  661. elif cmd == "codeblock":
  662. tag_depth += 1
  663. tag_text = "\n::\n"
  664. inside_code = True
  665. elif cmd == "br":
  666. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  667. tag_text = "\n\n"
  668. # Strip potential leading spaces
  669. while post_text[0] == " ":
  670. post_text = post_text[1:]
  671. elif cmd == "i" or cmd == "/i":
  672. if cmd == "/i":
  673. tag_depth -= 1
  674. else:
  675. tag_depth += 1
  676. tag_text = "*"
  677. elif cmd == "b" or cmd == "/b":
  678. if cmd == "/b":
  679. tag_depth -= 1
  680. else:
  681. tag_depth += 1
  682. tag_text = "**"
  683. elif cmd == "u" or cmd == "/u":
  684. if cmd == "/u":
  685. tag_depth -= 1
  686. else:
  687. tag_depth += 1
  688. tag_text = ""
  689. elif cmd == "code":
  690. tag_text = "``"
  691. tag_depth += 1
  692. inside_code = True
  693. elif cmd.startswith("enum "):
  694. tag_text = make_enum(cmd[5:], state)
  695. escape_post = True
  696. else:
  697. tag_text = make_type(tag_text, state)
  698. escape_post = True
  699. # Properly escape things like `[Node]s`
  700. if escape_post and post_text and (post_text[0].isalnum() or post_text[0] == "("): # not punctuation, escape
  701. post_text = "\ " + post_text
  702. next_brac_pos = post_text.find("[", 0)
  703. iter_pos = 0
  704. while not inside_code:
  705. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  706. if iter_pos == -1:
  707. break
  708. post_text = post_text[:iter_pos] + "\*" + post_text[iter_pos + 1 :]
  709. iter_pos += 2
  710. iter_pos = 0
  711. while not inside_code:
  712. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  713. if iter_pos == -1:
  714. break
  715. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  716. post_text = post_text[:iter_pos] + "\_" + post_text[iter_pos + 1 :]
  717. iter_pos += 2
  718. else:
  719. iter_pos += 1
  720. text = pre_text + tag_text + post_text
  721. pos = len(pre_text) + len(tag_text)
  722. previous_pos = pos
  723. if tag_depth > 0:
  724. print_error("Tag depth mismatch: too many/little open/close tags, file: {}".format(state.current_class), state)
  725. return text
  726. def format_table(f, data, remove_empty_columns=False): # type: (TextIO, Iterable[Tuple[str, ...]]) -> None
  727. if len(data) == 0:
  728. return
  729. column_sizes = [0] * len(data[0])
  730. for row in data:
  731. for i, text in enumerate(row):
  732. text_length = len(text or "")
  733. if text_length > column_sizes[i]:
  734. column_sizes[i] = text_length
  735. sep = ""
  736. for size in column_sizes:
  737. if size == 0 and remove_empty_columns:
  738. continue
  739. sep += "+" + "-" * (size + 2)
  740. sep += "+\n"
  741. f.write(sep)
  742. for row in data:
  743. row_text = "|"
  744. for i, text in enumerate(row):
  745. if column_sizes[i] == 0 and remove_empty_columns:
  746. continue
  747. row_text += " " + (text or "").ljust(column_sizes[i]) + " |"
  748. row_text += "\n"
  749. f.write(row_text)
  750. f.write(sep)
  751. f.write("\n")
  752. def make_type(t, state): # type: (str, State) -> str
  753. if t in state.classes:
  754. return ":ref:`{0}<class_{0}>`".format(t)
  755. print_error("Unresolved type '{}', file: {}".format(t, state.current_class), state)
  756. return t
  757. def make_enum(t, state): # type: (str, State) -> str
  758. p = t.find(".")
  759. if p >= 0:
  760. c = t[0:p]
  761. e = t[p + 1 :]
  762. # Variant enums live in GlobalScope but still use periods.
  763. if c == "Variant":
  764. c = "@GlobalScope"
  765. e = "Variant." + e
  766. else:
  767. c = state.current_class
  768. e = t
  769. if c in state.classes and e not in state.classes[c].enums:
  770. c = "@GlobalScope"
  771. if not c in state.classes and c.startswith("_"):
  772. c = c[1:] # Remove the underscore prefix
  773. if c in state.classes and e in state.classes[c].enums:
  774. return ":ref:`{0}<enum_{1}_{0}>`".format(e, c)
  775. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  776. if "{}.{}".format(c, e) != "Vector3.Axis":
  777. print_error("Unresolved enum '{}', file: {}".format(t, state.current_class), state)
  778. return t
  779. def make_method_signature(
  780. class_def, method_def, make_ref, state
  781. ): # type: (ClassDef, Union[MethodDef, SignalDef], bool, State) -> Tuple[str, str]
  782. ret_type = " "
  783. ref_type = "signal"
  784. if isinstance(method_def, MethodDef):
  785. ret_type = method_def.return_type.to_rst(state)
  786. ref_type = "method"
  787. out = ""
  788. if make_ref:
  789. out += ":ref:`{0}<class_{1}_{2}_{0}>` ".format(method_def.name, class_def.name, ref_type)
  790. else:
  791. out += "**{}** ".format(method_def.name)
  792. out += "**(**"
  793. for i, arg in enumerate(method_def.parameters):
  794. if i > 0:
  795. out += ", "
  796. else:
  797. out += " "
  798. out += "{} {}".format(arg.type_name.to_rst(state), arg.name)
  799. if arg.default_value is not None:
  800. out += "=" + arg.default_value
  801. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None and "vararg" in method_def.qualifiers:
  802. if len(method_def.parameters) > 0:
  803. out += ", ..."
  804. else:
  805. out += " ..."
  806. out += " **)**"
  807. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None:
  808. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  809. # See `make_footer()` for descriptions.
  810. for qualifier in method_def.qualifiers.split():
  811. out += " |" + qualifier + "|"
  812. return ret_type, out
  813. def make_heading(title, underline): # type: (str, str) -> str
  814. return title + "\n" + (underline * len(title)) + "\n\n"
  815. def make_footer(): # type: () -> str
  816. # Generate reusable abbreviation substitutions.
  817. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  818. # fmt: off
  819. return (
  820. ".. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)`\n"
  821. ".. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)`\n"
  822. ".. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`\n"
  823. )
  824. # fmt: on
  825. def make_link(url, title): # type: (str, str) -> str
  826. match = GODOT_DOCS_PATTERN.search(url)
  827. if match:
  828. groups = match.groups()
  829. if match.lastindex == 2:
  830. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  831. # `#calling-javascript-from-script in Exporting For Web`
  832. return "`" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`_ in :doc:`../" + groups[0] + "`"
  833. # Commented out alternative: Instead just emit:
  834. # `Subsection in Exporting For Web`
  835. # return "`Subsection <../" + groups[0] + ".html" + groups[1] + ">`__ in :doc:`../" + groups[0] + "`"
  836. elif match.lastindex == 1:
  837. # Doc reference, for example:
  838. # `Math`
  839. return ":doc:`../" + groups[0] + "`"
  840. else:
  841. # External link, for example:
  842. # `http://enet.bespin.org/usergroup0.html`
  843. if title != "":
  844. return "`" + title + " <" + url + ">`_"
  845. else:
  846. return "`" + url + " <" + url + ">`_"
  847. if __name__ == "__main__":
  848. main()