makerst.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 = '``{}``'.format(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. # Brief description
  303. if class_def.brief_description is not None:
  304. f.write(rstize_text(class_def.brief_description.strip(), state) + "\n\n")
  305. # Class description
  306. if class_def.description is not None and class_def.description.strip() != '':
  307. f.write(make_heading('Description', '-'))
  308. f.write(rstize_text(class_def.description.strip(), state) + "\n\n")
  309. # Online tutorials
  310. if len(class_def.tutorials) > 0:
  311. f.write(make_heading('Tutorials', '-'))
  312. for t in class_def.tutorials:
  313. link = t.strip()
  314. f.write("- " + make_url(link) + "\n\n")
  315. # Properties overview
  316. if len(class_def.properties) > 0:
  317. f.write(make_heading('Properties', '-'))
  318. ml = [] # type: List[Tuple[str, str, str]]
  319. for property_def in class_def.properties.values():
  320. type_rst = property_def.type_name.to_rst(state)
  321. default = property_def.default_value
  322. if property_def.overridden:
  323. ml.append((type_rst, property_def.name, "**O:** " + default))
  324. else:
  325. ref = ":ref:`{0}<class_{1}_property_{0}>`".format(property_def.name, class_name)
  326. ml.append((type_rst, ref, default))
  327. format_table(f, ml, True)
  328. # Methods overview
  329. if len(class_def.methods) > 0:
  330. f.write(make_heading('Methods', '-'))
  331. ml = []
  332. for method_list in class_def.methods.values():
  333. for m in method_list:
  334. ml.append(make_method_signature(class_def, m, True, state))
  335. format_table(f, ml)
  336. # Theme properties
  337. if class_def.theme_items is not None and len(class_def.theme_items) > 0:
  338. f.write(make_heading('Theme Properties', '-'))
  339. pl = []
  340. for theme_item_list in class_def.theme_items.values():
  341. for theme_item in theme_item_list:
  342. pl.append((theme_item.type_name.to_rst(state), theme_item.name, theme_item.default_value))
  343. format_table(f, pl, True)
  344. # Signals
  345. if len(class_def.signals) > 0:
  346. f.write(make_heading('Signals', '-'))
  347. index = 0
  348. for signal in class_def.signals.values():
  349. if index != 0:
  350. f.write('----\n\n')
  351. f.write(".. _class_{}_signal_{}:\n\n".format(class_name, signal.name))
  352. _, signature = make_method_signature(class_def, signal, False, state)
  353. f.write("- {}\n\n".format(signature))
  354. if signal.description is not None and signal.description.strip() != '':
  355. f.write(rstize_text(signal.description.strip(), state) + '\n\n')
  356. index += 1
  357. # Enums
  358. if len(class_def.enums) > 0:
  359. f.write(make_heading('Enumerations', '-'))
  360. index = 0
  361. for e in class_def.enums.values():
  362. if index != 0:
  363. f.write('----\n\n')
  364. f.write(".. _enum_{}_{}:\n\n".format(class_name, e.name))
  365. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  366. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  367. # As to why I'm not modifying the reference parser to directly link to the _enum label:
  368. # If somebody gets annoyed enough to fix it, all existing references will magically improve.
  369. for value in e.values.values():
  370. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, value.name))
  371. f.write("enum **{}**:\n\n".format(e.name))
  372. for value in e.values.values():
  373. f.write("- **{}** = **{}**".format(value.name, value.value))
  374. if value.text is not None and value.text.strip() != '':
  375. f.write(' --- ' + rstize_text(value.text.strip(), state))
  376. f.write('\n\n')
  377. index += 1
  378. # Constants
  379. if len(class_def.constants) > 0:
  380. f.write(make_heading('Constants', '-'))
  381. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  382. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  383. for constant in class_def.constants.values():
  384. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, constant.name))
  385. for constant in class_def.constants.values():
  386. f.write("- **{}** = **{}**".format(constant.name, constant.value))
  387. if constant.text is not None and constant.text.strip() != '':
  388. f.write(' --- ' + rstize_text(constant.text.strip(), state))
  389. f.write('\n\n')
  390. # Property descriptions
  391. if any(not p.overridden for p in class_def.properties.values()) > 0:
  392. f.write(make_heading('Property Descriptions', '-'))
  393. index = 0
  394. for property_def in class_def.properties.values():
  395. if property_def.overridden:
  396. continue
  397. if index != 0:
  398. f.write('----\n\n')
  399. f.write(".. _class_{}_property_{}:\n\n".format(class_name, property_def.name))
  400. f.write('- {} **{}**\n\n'.format(property_def.type_name.to_rst(state), property_def.name))
  401. info = []
  402. if property_def.default_value is not None:
  403. info.append(("*Default*", property_def.default_value))
  404. if property_def.setter is not None and not property_def.setter.startswith("_"):
  405. info.append(("*Setter*", property_def.setter + '(value)'))
  406. if property_def.getter is not None and not property_def.getter.startswith("_"):
  407. info.append(('*Getter*', property_def.getter + '()'))
  408. if len(info) > 0:
  409. format_table(f, info)
  410. if property_def.text is not None and property_def.text.strip() != '':
  411. f.write(rstize_text(property_def.text.strip(), state) + '\n\n')
  412. index += 1
  413. # Method descriptions
  414. if len(class_def.methods) > 0:
  415. f.write(make_heading('Method Descriptions', '-'))
  416. index = 0
  417. for method_list in class_def.methods.values():
  418. for i, m in enumerate(method_list):
  419. if index != 0:
  420. f.write('----\n\n')
  421. if i == 0:
  422. f.write(".. _class_{}_method_{}:\n\n".format(class_name, m.name))
  423. ret_type, signature = make_method_signature(class_def, m, False, state)
  424. f.write("- {} {}\n\n".format(ret_type, signature))
  425. if m.description is not None and m.description.strip() != '':
  426. f.write(rstize_text(m.description.strip(), state) + '\n\n')
  427. index += 1
  428. def make_class_list(class_list, columns): # type: (List[str], int) -> None
  429. # This function is no longer used.
  430. f = open('class_list.rst', 'w', encoding='utf-8')
  431. col_max = len(class_list) // columns + 1
  432. print(('col max is ', col_max))
  433. fit_columns = [] # type: List[List[str]]
  434. for _ in range(0, columns):
  435. fit_columns.append([])
  436. indexers = [] # type List[str]
  437. last_initial = ''
  438. for idx, name in enumerate(class_list):
  439. col = idx // col_max
  440. if col >= columns:
  441. col = columns - 1
  442. fit_columns[col].append(name)
  443. idx += 1
  444. if name[:1] != last_initial:
  445. indexers.append(name)
  446. last_initial = name[:1]
  447. row_max = 0
  448. f.write("\n")
  449. for n in range(0, columns):
  450. if len(fit_columns[n]) > row_max:
  451. row_max = len(fit_columns[n])
  452. f.write("| ")
  453. for n in range(0, columns):
  454. f.write(" | |")
  455. f.write("\n")
  456. f.write("+")
  457. for n in range(0, columns):
  458. f.write("--+-------+")
  459. f.write("\n")
  460. for r in range(0, row_max):
  461. s = '+ '
  462. for c in range(0, columns):
  463. if r >= len(fit_columns[c]):
  464. continue
  465. classname = fit_columns[c][r]
  466. initial = classname[0]
  467. if classname in indexers:
  468. s += '**' + initial + '** | '
  469. else:
  470. s += ' | '
  471. s += '[' + classname + '](class_' + classname.lower() + ') | '
  472. s += '\n'
  473. f.write(s)
  474. for n in range(0, columns):
  475. f.write("--+-------+")
  476. f.write("\n")
  477. f.close()
  478. def escape_rst(text, until_pos=-1): # type: (str) -> str
  479. # Escape \ character, otherwise it ends up as an escape character in rst
  480. pos = 0
  481. while True:
  482. pos = text.find('\\', pos, until_pos)
  483. if pos == -1:
  484. break
  485. text = text[:pos] + "\\\\" + text[pos + 1:]
  486. pos += 2
  487. # Escape * character to avoid interpreting it as emphasis
  488. pos = 0
  489. while True:
  490. pos = text.find('*', pos, until_pos)
  491. if pos == -1:
  492. break
  493. text = text[:pos] + "\*" + text[pos + 1:]
  494. pos += 2
  495. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  496. pos = 0
  497. while True:
  498. pos = text.find('_', pos, until_pos)
  499. if pos == -1:
  500. break
  501. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  502. text = text[:pos] + "\_" + text[pos + 1:]
  503. pos += 2
  504. else:
  505. pos += 1
  506. return text
  507. def rstize_text(text, state): # type: (str, State) -> str
  508. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  509. pos = 0
  510. while True:
  511. pos = text.find('\n', pos)
  512. if pos == -1:
  513. break
  514. pre_text = text[:pos]
  515. indent_level = 0
  516. while text[pos + 1] == '\t':
  517. pos += 1
  518. indent_level += 1
  519. post_text = text[pos + 1:]
  520. # Handle codeblocks
  521. if post_text.startswith("[codeblock]"):
  522. end_pos = post_text.find("[/codeblock]")
  523. if end_pos == -1:
  524. print_error("[codeblock] without a closing tag, file: {}".format(state.current_class), state)
  525. return ""
  526. code_text = post_text[len("[codeblock]"):end_pos]
  527. post_text = post_text[end_pos:]
  528. # Remove extraneous tabs
  529. code_pos = 0
  530. while True:
  531. code_pos = code_text.find('\n', code_pos)
  532. if code_pos == -1:
  533. break
  534. to_skip = 0
  535. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == '\t':
  536. to_skip += 1
  537. if to_skip > indent_level:
  538. print_error("Four spaces should be used for indentation within [codeblock], file: {}".format(state.current_class), state)
  539. if len(code_text[code_pos + to_skip + 1:]) == 0:
  540. code_text = code_text[:code_pos] + "\n"
  541. code_pos += 1
  542. else:
  543. code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1:]
  544. code_pos += 5 - to_skip
  545. text = pre_text + "\n[codeblock]" + code_text + post_text
  546. pos += len("\n[codeblock]" + code_text)
  547. # Handle normal text
  548. else:
  549. text = pre_text + "\n\n" + post_text
  550. pos += 2
  551. next_brac_pos = text.find('[')
  552. text = escape_rst(text, next_brac_pos)
  553. # Handle [tags]
  554. inside_code = False
  555. inside_url = False
  556. url_has_name = False
  557. url_link = ""
  558. pos = 0
  559. tag_depth = 0
  560. previous_pos = 0
  561. while True:
  562. pos = text.find('[', pos)
  563. if inside_url and (pos > previous_pos):
  564. url_has_name = True
  565. if pos == -1:
  566. break
  567. endq_pos = text.find(']', pos + 1)
  568. if endq_pos == -1:
  569. break
  570. pre_text = text[:pos]
  571. post_text = text[endq_pos + 1:]
  572. tag_text = text[pos + 1:endq_pos]
  573. escape_post = False
  574. if tag_text in state.classes:
  575. if tag_text == state.current_class:
  576. # We don't want references to the same class
  577. tag_text = '``{}``'.format(tag_text)
  578. else:
  579. tag_text = make_type(tag_text, state)
  580. escape_post = True
  581. else: # command
  582. cmd = tag_text
  583. space_pos = tag_text.find(' ')
  584. if cmd == '/codeblock':
  585. tag_text = ''
  586. tag_depth -= 1
  587. inside_code = False
  588. # Strip newline if the tag was alone on one
  589. if pre_text[-1] == '\n':
  590. pre_text = pre_text[:-1]
  591. elif cmd == '/code':
  592. tag_text = '``'
  593. tag_depth -= 1
  594. inside_code = False
  595. escape_post = True
  596. elif inside_code:
  597. tag_text = '[' + tag_text + ']'
  598. elif cmd.find('html') == 0:
  599. param = tag_text[space_pos + 1:]
  600. tag_text = param
  601. elif cmd.startswith('method') or cmd.startswith('member') or cmd.startswith('signal') or cmd.startswith('constant'):
  602. param = tag_text[space_pos + 1:]
  603. if param.find('.') != -1:
  604. ss = param.split('.')
  605. if len(ss) > 2:
  606. print_error("Bad reference: '{}', file: {}".format(param, state.current_class), state)
  607. class_param, method_param = ss
  608. else:
  609. class_param = state.current_class
  610. method_param = param
  611. ref_type = ""
  612. if class_param in state.classes:
  613. class_def = state.classes[class_param]
  614. if cmd.startswith("method"):
  615. if method_param not in class_def.methods:
  616. print_error("Unresolved method '{}', file: {}".format(param, state.current_class), state)
  617. ref_type = "_method"
  618. elif cmd.startswith("member"):
  619. if method_param not in class_def.properties:
  620. print_error("Unresolved member '{}', file: {}".format(param, state.current_class), state)
  621. ref_type = "_property"
  622. elif cmd.startswith("signal"):
  623. if method_param not in class_def.signals:
  624. print_error("Unresolved signal '{}', file: {}".format(param, state.current_class), state)
  625. ref_type = "_signal"
  626. elif cmd.startswith("constant"):
  627. found = False
  628. # Search in the current class
  629. search_class_defs = [class_def]
  630. if param.find('.') == -1:
  631. # Also search in @GlobalScope as a last resort if no class was specified
  632. search_class_defs.append(state.classes["@GlobalScope"])
  633. for search_class_def in search_class_defs:
  634. if method_param in search_class_def.constants:
  635. class_param = search_class_def.name
  636. found = True
  637. else:
  638. for enum in search_class_def.enums.values():
  639. if method_param in enum.values:
  640. class_param = search_class_def.name
  641. found = True
  642. break
  643. if not found:
  644. print_error("Unresolved constant '{}', file: {}".format(param, state.current_class), state)
  645. ref_type = "_constant"
  646. else:
  647. print_error("Unresolved type reference '{}' in method reference '{}', file: {}".format(class_param, param, state.current_class), state)
  648. repl_text = method_param
  649. if class_param != state.current_class:
  650. repl_text = "{}.{}".format(class_param, method_param)
  651. tag_text = ':ref:`{}<class_{}{}_{}>`'.format(repl_text, class_param, ref_type, method_param)
  652. escape_post = True
  653. elif cmd.find('image=') == 0:
  654. tag_text = "" # '![](' + cmd[6:] + ')'
  655. elif cmd.find('url=') == 0:
  656. url_link = cmd[4:]
  657. tag_text = '`'
  658. tag_depth += 1
  659. inside_url = True
  660. url_has_name = False
  661. elif cmd == '/url':
  662. tag_text = ('' if url_has_name else url_link) + " <" + url_link + ">`_"
  663. tag_depth -= 1
  664. escape_post = True
  665. inside_url = False
  666. url_has_name = False
  667. elif cmd == 'center':
  668. tag_depth += 1
  669. tag_text = ''
  670. elif cmd == '/center':
  671. tag_depth -= 1
  672. tag_text = ''
  673. elif cmd == 'codeblock':
  674. tag_depth += 1
  675. tag_text = '\n::\n'
  676. inside_code = True
  677. elif cmd == 'br':
  678. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  679. tag_text = '\n\n'
  680. # Strip potential leading spaces
  681. while post_text[0] == ' ':
  682. post_text = post_text[1:]
  683. elif cmd == 'i' or cmd == '/i':
  684. if cmd == "/i":
  685. tag_depth -= 1
  686. else:
  687. tag_depth += 1
  688. tag_text = '*'
  689. elif cmd == 'b' or cmd == '/b':
  690. if cmd == "/b":
  691. tag_depth -= 1
  692. else:
  693. tag_depth += 1
  694. tag_text = '**'
  695. elif cmd == 'u' or cmd == '/u':
  696. if cmd == "/u":
  697. tag_depth -= 1
  698. else:
  699. tag_depth += 1
  700. tag_text = ''
  701. elif cmd == 'code':
  702. tag_text = '``'
  703. tag_depth += 1
  704. inside_code = True
  705. elif cmd.startswith('enum '):
  706. tag_text = make_enum(cmd[5:], state)
  707. escape_post = True
  708. else:
  709. tag_text = make_type(tag_text, state)
  710. escape_post = True
  711. # Properly escape things like `[Node]s`
  712. if escape_post and post_text and (post_text[0].isalnum() or post_text[0] == "("): # not punctuation, escape
  713. post_text = '\ ' + post_text
  714. next_brac_pos = post_text.find('[', 0)
  715. iter_pos = 0
  716. while not inside_code:
  717. iter_pos = post_text.find('*', iter_pos, next_brac_pos)
  718. if iter_pos == -1:
  719. break
  720. post_text = post_text[:iter_pos] + "\*" + post_text[iter_pos + 1:]
  721. iter_pos += 2
  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. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  728. post_text = post_text[:iter_pos] + "\_" + post_text[iter_pos + 1:]
  729. iter_pos += 2
  730. else:
  731. iter_pos += 1
  732. text = pre_text + tag_text + post_text
  733. pos = len(pre_text) + len(tag_text)
  734. previous_pos = pos
  735. if tag_depth > 0:
  736. print_error("Tag depth mismatch: too many/little open/close tags, file: {}".format(state.current_class), state)
  737. return text
  738. def format_table(f, data, remove_empty_columns=False): # type: (TextIO, Iterable[Tuple[str, ...]]) -> None
  739. if len(data) == 0:
  740. return
  741. column_sizes = [0] * len(data[0])
  742. for row in data:
  743. for i, text in enumerate(row):
  744. text_length = len(text or '')
  745. if text_length > column_sizes[i]:
  746. column_sizes[i] = text_length
  747. sep = ""
  748. for size in column_sizes:
  749. if size == 0 and remove_empty_columns:
  750. continue
  751. sep += "+" + "-" * (size + 2)
  752. sep += "+\n"
  753. f.write(sep)
  754. for row in data:
  755. row_text = "|"
  756. for i, text in enumerate(row):
  757. if column_sizes[i] == 0 and remove_empty_columns:
  758. continue
  759. row_text += " " + (text or '').ljust(column_sizes[i]) + " |"
  760. row_text += "\n"
  761. f.write(row_text)
  762. f.write(sep)
  763. f.write('\n')
  764. def make_type(t, state): # type: (str, State) -> str
  765. if t in state.classes:
  766. return ':ref:`{0}<class_{0}>`'.format(t)
  767. print_error("Unresolved type '{}', file: {}".format(t, state.current_class), state)
  768. return t
  769. def make_enum(t, state): # type: (str, State) -> str
  770. p = t.find(".")
  771. if p >= 0:
  772. c = t[0:p]
  773. e = t[p + 1:]
  774. # Variant enums live in GlobalScope but still use periods.
  775. if c == "Variant":
  776. c = "@GlobalScope"
  777. e = "Variant." + e
  778. else:
  779. c = state.current_class
  780. e = t
  781. if c in state.classes and e not in state.classes[c].enums:
  782. c = "@GlobalScope"
  783. if not c in state.classes and c.startswith("_"):
  784. c = c[1:] # Remove the underscore prefix
  785. if c in state.classes and e in state.classes[c].enums:
  786. return ":ref:`{0}<enum_{1}_{0}>`".format(e, c)
  787. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  788. if "{}.{}".format(c, e) != "Vector3.Axis":
  789. print_error("Unresolved enum '{}', file: {}".format(t, state.current_class), state)
  790. return t
  791. def make_method_signature(class_def, method_def, make_ref, state): # type: (ClassDef, Union[MethodDef, SignalDef], bool, State) -> Tuple[str, str]
  792. ret_type = " "
  793. ref_type = "signal"
  794. if isinstance(method_def, MethodDef):
  795. ret_type = method_def.return_type.to_rst(state)
  796. ref_type = "method"
  797. out = ""
  798. if make_ref:
  799. out += ":ref:`{0}<class_{1}_{2}_{0}>` ".format(method_def.name, class_def.name, ref_type)
  800. else:
  801. out += "**{}** ".format(method_def.name)
  802. out += '**(**'
  803. for i, arg in enumerate(method_def.parameters):
  804. if i > 0:
  805. out += ', '
  806. else:
  807. out += ' '
  808. out += "{} {}".format(arg.type_name.to_rst(state), arg.name)
  809. if arg.default_value is not None:
  810. out += '=' + arg.default_value
  811. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None and 'vararg' in method_def.qualifiers:
  812. if len(method_def.parameters) > 0:
  813. out += ', ...'
  814. else:
  815. out += ' ...'
  816. out += ' **)**'
  817. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None:
  818. out += ' ' + method_def.qualifiers
  819. return ret_type, out
  820. def make_heading(title, underline): # type: (str, str) -> str
  821. return title + '\n' + (underline * len(title)) + "\n\n"
  822. def make_url(link): # type: (str) -> str
  823. match = GODOT_DOCS_PATTERN.search(link)
  824. if match:
  825. groups = match.groups()
  826. if match.lastindex == 2:
  827. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  828. # `#calling-javascript-from-script in Exporting For Web`
  829. return "`" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`_ in :doc:`../" + groups[0] + "`"
  830. # Commented out alternative: Instead just emit:
  831. # `Subsection in Exporting For Web`
  832. # return "`Subsection <../" + groups[0] + ".html" + groups[1] + ">`__ in :doc:`../" + groups[0] + "`"
  833. elif match.lastindex == 1:
  834. # Doc reference, for example:
  835. # `Math`
  836. return ":doc:`../" + groups[0] + "`"
  837. else:
  838. # External link, for example:
  839. # `http://enet.bespin.org/usergroup0.html`
  840. return "`" + link + " <" + link + ">`_"
  841. if __name__ == '__main__':
  842. main()