makerst.py 38 KB

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