makerst.py 40 KB

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