makerst.py 38 KB

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