makerst.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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 format_codeblock(code_type, post_text, indent_level, state): # types: str, str, int, state
  481. end_pos = post_text.find("[/" + code_type + "]")
  482. if end_pos == -1:
  483. print_error("[" + code_type + "] without a closing tag, file: {}".format(state.current_class), state)
  484. return None
  485. code_text = post_text[len("[" + code_type + "]") : end_pos]
  486. post_text = post_text[end_pos:]
  487. # Remove extraneous tabs
  488. code_pos = 0
  489. while True:
  490. code_pos = code_text.find("\n", code_pos)
  491. if code_pos == -1:
  492. break
  493. to_skip = 0
  494. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  495. to_skip += 1
  496. if to_skip > indent_level:
  497. print_error(
  498. "Four spaces should be used for indentation within ["
  499. + code_type
  500. + "], file: {}".format(state.current_class),
  501. state,
  502. )
  503. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  504. code_text = code_text[:code_pos] + "\n"
  505. code_pos += 1
  506. else:
  507. code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1 :]
  508. code_pos += 5 - to_skip
  509. return ["\n[" + code_type + "]" + code_text + post_text, len("\n[" + code_type + "]" + code_text)]
  510. def rstize_text(text, state): # type: (str, State) -> str
  511. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  512. pos = 0
  513. while True:
  514. pos = text.find("\n", pos)
  515. if pos == -1:
  516. break
  517. pre_text = text[:pos]
  518. indent_level = 0
  519. while text[pos + 1] == "\t":
  520. pos += 1
  521. indent_level += 1
  522. post_text = text[pos + 1 :]
  523. # Handle codeblocks
  524. if (
  525. post_text.startswith("[codeblock]")
  526. or post_text.startswith("[gdscript]")
  527. or post_text.startswith("[csharp]")
  528. ):
  529. block_type = post_text[1:].split("]")[0]
  530. result = format_codeblock(block_type, post_text, indent_level, state)
  531. if result is None:
  532. return ""
  533. text = pre_text + result[0]
  534. pos += result[1]
  535. # Handle normal text
  536. else:
  537. text = pre_text + "\n\n" + post_text
  538. pos += 2
  539. next_brac_pos = text.find("[")
  540. text = escape_rst(text, next_brac_pos)
  541. # Handle [tags]
  542. inside_code = False
  543. inside_url = False
  544. url_has_name = False
  545. url_link = ""
  546. pos = 0
  547. tag_depth = 0
  548. previous_pos = 0
  549. while True:
  550. pos = text.find("[", pos)
  551. if inside_url and (pos > previous_pos):
  552. url_has_name = True
  553. if pos == -1:
  554. break
  555. endq_pos = text.find("]", pos + 1)
  556. if endq_pos == -1:
  557. break
  558. pre_text = text[:pos]
  559. post_text = text[endq_pos + 1 :]
  560. tag_text = text[pos + 1 : endq_pos]
  561. escape_post = False
  562. if tag_text in state.classes:
  563. if tag_text == state.current_class:
  564. # We don't want references to the same class
  565. tag_text = "``{}``".format(tag_text)
  566. else:
  567. tag_text = make_type(tag_text, state)
  568. escape_post = True
  569. else: # command
  570. cmd = tag_text
  571. space_pos = tag_text.find(" ")
  572. if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp":
  573. tag_text = ""
  574. tag_depth -= 1
  575. inside_code = False
  576. # Strip newline if the tag was alone on one
  577. if pre_text[-1] == "\n":
  578. pre_text = pre_text[:-1]
  579. elif cmd == "/code":
  580. tag_text = "``"
  581. tag_depth -= 1
  582. inside_code = False
  583. escape_post = True
  584. elif inside_code:
  585. tag_text = "[" + tag_text + "]"
  586. elif cmd.find("html") == 0:
  587. param = tag_text[space_pos + 1 :]
  588. tag_text = param
  589. elif (
  590. cmd.startswith("method")
  591. or cmd.startswith("member")
  592. or cmd.startswith("signal")
  593. or cmd.startswith("constant")
  594. ):
  595. param = tag_text[space_pos + 1 :]
  596. if param.find(".") != -1:
  597. ss = param.split(".")
  598. if len(ss) > 2:
  599. print_error("Bad reference: '{}', file: {}".format(param, state.current_class), state)
  600. class_param, method_param = ss
  601. else:
  602. class_param = state.current_class
  603. method_param = param
  604. ref_type = ""
  605. if class_param in state.classes:
  606. class_def = state.classes[class_param]
  607. if cmd.startswith("method"):
  608. if method_param not in class_def.methods:
  609. print_error("Unresolved method '{}', file: {}".format(param, state.current_class), state)
  610. ref_type = "_method"
  611. elif cmd.startswith("member"):
  612. if method_param not in class_def.properties:
  613. print_error("Unresolved member '{}', file: {}".format(param, state.current_class), state)
  614. ref_type = "_property"
  615. elif cmd.startswith("signal"):
  616. if method_param not in class_def.signals:
  617. print_error("Unresolved signal '{}', file: {}".format(param, state.current_class), state)
  618. ref_type = "_signal"
  619. elif cmd.startswith("constant"):
  620. found = False
  621. # Search in the current class
  622. search_class_defs = [class_def]
  623. if param.find(".") == -1:
  624. # Also search in @GlobalScope as a last resort if no class was specified
  625. search_class_defs.append(state.classes["@GlobalScope"])
  626. for search_class_def in search_class_defs:
  627. if method_param in search_class_def.constants:
  628. class_param = search_class_def.name
  629. found = True
  630. else:
  631. for enum in search_class_def.enums.values():
  632. if method_param in enum.values:
  633. class_param = search_class_def.name
  634. found = True
  635. break
  636. if not found:
  637. print_error("Unresolved constant '{}', file: {}".format(param, state.current_class), state)
  638. ref_type = "_constant"
  639. else:
  640. print_error(
  641. "Unresolved type reference '{}' in method reference '{}', file: {}".format(
  642. class_param, param, state.current_class
  643. ),
  644. state,
  645. )
  646. repl_text = method_param
  647. if class_param != state.current_class:
  648. repl_text = "{}.{}".format(class_param, method_param)
  649. tag_text = ":ref:`{}<class_{}{}_{}>`".format(repl_text, class_param, ref_type, method_param)
  650. escape_post = True
  651. elif cmd.find("image=") == 0:
  652. tag_text = "" # '![](' + cmd[6:] + ')'
  653. elif cmd.find("url=") == 0:
  654. url_link = cmd[4:]
  655. tag_text = "`"
  656. tag_depth += 1
  657. inside_url = True
  658. url_has_name = False
  659. elif cmd == "/url":
  660. tag_text = ("" if url_has_name else url_link) + " <" + url_link + ">`_"
  661. tag_depth -= 1
  662. escape_post = True
  663. inside_url = False
  664. url_has_name = False
  665. elif cmd == "center":
  666. tag_depth += 1
  667. tag_text = ""
  668. elif cmd == "/center":
  669. tag_depth -= 1
  670. tag_text = ""
  671. elif cmd == "codeblock":
  672. tag_depth += 1
  673. tag_text = "\n::\n"
  674. inside_code = True
  675. elif cmd == "gdscript":
  676. tag_depth += 1
  677. tag_text = "\n .. code-tab:: gdscript\n"
  678. inside_code = True
  679. elif cmd == "csharp":
  680. tag_depth += 1
  681. tag_text = "\n .. code-tab:: csharp\n"
  682. inside_code = True
  683. elif cmd == "codeblocks":
  684. tag_depth += 1
  685. tag_text = "\n.. tabs::"
  686. elif cmd == "/codeblocks":
  687. tag_depth -= 1
  688. tag_text = ""
  689. elif cmd == "br":
  690. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  691. tag_text = "\n\n"
  692. # Strip potential leading spaces
  693. while post_text[0] == " ":
  694. post_text = post_text[1:]
  695. elif cmd == "i" or cmd == "/i":
  696. if cmd == "/i":
  697. tag_depth -= 1
  698. else:
  699. tag_depth += 1
  700. tag_text = "*"
  701. elif cmd == "b" or cmd == "/b":
  702. if cmd == "/b":
  703. tag_depth -= 1
  704. else:
  705. tag_depth += 1
  706. tag_text = "**"
  707. elif cmd == "u" or cmd == "/u":
  708. if cmd == "/u":
  709. tag_depth -= 1
  710. else:
  711. tag_depth += 1
  712. tag_text = ""
  713. elif cmd == "code":
  714. tag_text = "``"
  715. tag_depth += 1
  716. inside_code = True
  717. elif cmd == "kbd":
  718. tag_text = ":kbd:`"
  719. tag_depth += 1
  720. elif cmd == "/kbd":
  721. tag_text = "`"
  722. tag_depth -= 1
  723. elif cmd.startswith("enum "):
  724. tag_text = make_enum(cmd[5:], state)
  725. escape_post = True
  726. else:
  727. tag_text = make_type(tag_text, state)
  728. escape_post = True
  729. # Properly escape things like `[Node]s`
  730. if escape_post and post_text and (post_text[0].isalnum() or post_text[0] == "("): # not punctuation, escape
  731. post_text = "\ " + post_text
  732. next_brac_pos = post_text.find("[", 0)
  733. iter_pos = 0
  734. while not inside_code:
  735. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  736. if iter_pos == -1:
  737. break
  738. post_text = post_text[:iter_pos] + "\*" + post_text[iter_pos + 1 :]
  739. iter_pos += 2
  740. iter_pos = 0
  741. while not inside_code:
  742. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  743. if iter_pos == -1:
  744. break
  745. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  746. post_text = post_text[:iter_pos] + "\_" + post_text[iter_pos + 1 :]
  747. iter_pos += 2
  748. else:
  749. iter_pos += 1
  750. text = pre_text + tag_text + post_text
  751. pos = len(pre_text) + len(tag_text)
  752. previous_pos = pos
  753. if tag_depth > 0:
  754. print_error("Tag depth mismatch: too many/little open/close tags, file: {}".format(state.current_class), state)
  755. return text
  756. def format_table(f, data, remove_empty_columns=False): # type: (TextIO, Iterable[Tuple[str, ...]]) -> None
  757. if len(data) == 0:
  758. return
  759. column_sizes = [0] * len(data[0])
  760. for row in data:
  761. for i, text in enumerate(row):
  762. text_length = len(text or "")
  763. if text_length > column_sizes[i]:
  764. column_sizes[i] = text_length
  765. sep = ""
  766. for size in column_sizes:
  767. if size == 0 and remove_empty_columns:
  768. continue
  769. sep += "+" + "-" * (size + 2)
  770. sep += "+\n"
  771. f.write(sep)
  772. for row in data:
  773. row_text = "|"
  774. for i, text in enumerate(row):
  775. if column_sizes[i] == 0 and remove_empty_columns:
  776. continue
  777. row_text += " " + (text or "").ljust(column_sizes[i]) + " |"
  778. row_text += "\n"
  779. f.write(row_text)
  780. f.write(sep)
  781. f.write("\n")
  782. def make_type(klass, state): # type: (str, State) -> str
  783. link_type = klass
  784. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  785. link_type = link_type[:-2]
  786. if link_type in state.classes:
  787. return ":ref:`{}<class_{}>`".format(klass, link_type)
  788. print_error("Unresolved type '{}', file: {}".format(klass, state.current_class), state)
  789. return klass
  790. def make_enum(t, state): # type: (str, State) -> str
  791. p = t.find(".")
  792. if p >= 0:
  793. c = t[0:p]
  794. e = t[p + 1 :]
  795. # Variant enums live in GlobalScope but still use periods.
  796. if c == "Variant":
  797. c = "@GlobalScope"
  798. e = "Variant." + e
  799. else:
  800. c = state.current_class
  801. e = t
  802. if c in state.classes and e not in state.classes[c].enums:
  803. c = "@GlobalScope"
  804. if not c in state.classes and c.startswith("_"):
  805. c = c[1:] # Remove the underscore prefix
  806. if c in state.classes and e in state.classes[c].enums:
  807. return ":ref:`{0}<enum_{1}_{0}>`".format(e, c)
  808. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  809. if "{}.{}".format(c, e) != "Vector3.Axis":
  810. print_error("Unresolved enum '{}', file: {}".format(t, state.current_class), state)
  811. return t
  812. def make_method_signature(
  813. class_def, method_def, make_ref, state
  814. ): # type: (ClassDef, Union[MethodDef, SignalDef], bool, State) -> Tuple[str, str]
  815. ret_type = " "
  816. ref_type = "signal"
  817. if isinstance(method_def, MethodDef):
  818. ret_type = method_def.return_type.to_rst(state)
  819. ref_type = "method"
  820. out = ""
  821. if make_ref:
  822. out += ":ref:`{0}<class_{1}_{2}_{0}>` ".format(method_def.name, class_def.name, ref_type)
  823. else:
  824. out += "**{}** ".format(method_def.name)
  825. out += "**(**"
  826. for i, arg in enumerate(method_def.parameters):
  827. if i > 0:
  828. out += ", "
  829. else:
  830. out += " "
  831. out += "{} {}".format(arg.type_name.to_rst(state), arg.name)
  832. if arg.default_value is not None:
  833. out += "=" + arg.default_value
  834. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None and "vararg" in method_def.qualifiers:
  835. if len(method_def.parameters) > 0:
  836. out += ", ..."
  837. else:
  838. out += " ..."
  839. out += " **)**"
  840. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None:
  841. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  842. # See `make_footer()` for descriptions.
  843. for qualifier in method_def.qualifiers.split():
  844. out += " |" + qualifier + "|"
  845. return ret_type, out
  846. def make_heading(title, underline): # type: (str, str) -> str
  847. return title + "\n" + (underline * len(title)) + "\n\n"
  848. def make_footer(): # type: () -> str
  849. # Generate reusable abbreviation substitutions.
  850. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  851. # fmt: off
  852. return (
  853. ".. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)`\n"
  854. ".. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)`\n"
  855. ".. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`\n"
  856. ".. |constructor| replace:: :abbr:`constructor (This method is used to construct a type.)`\n"
  857. ".. |operator| replace:: :abbr:`operator (This method describes a valid operator to use with this type as left-hand operand.)`\n"
  858. )
  859. # fmt: on
  860. def make_link(url, title): # type: (str, str) -> str
  861. match = GODOT_DOCS_PATTERN.search(url)
  862. if match:
  863. groups = match.groups()
  864. if match.lastindex == 2:
  865. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  866. # `#calling-javascript-from-script in Exporting For Web`
  867. return "`" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`_ in :doc:`../" + groups[0] + "`"
  868. # Commented out alternative: Instead just emit:
  869. # `Subsection in Exporting For Web`
  870. # return "`Subsection <../" + groups[0] + ".html" + groups[1] + ">`__ in :doc:`../" + groups[0] + "`"
  871. elif match.lastindex == 1:
  872. # Doc reference, for example:
  873. # `Math`
  874. return ":doc:`../" + groups[0] + "`"
  875. else:
  876. # External link, for example:
  877. # `http://enet.bespin.org/usergroup0.html`
  878. if title != "":
  879. return "`" + title + " <" + url + ">`_"
  880. else:
  881. return "`" + url + " <" + url + ">`_"
  882. if __name__ == "__main__":
  883. main()