makerst.py 38 KB

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