makerst.py 37 KB

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