makerst.py 38 KB

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