2
0

makerst.py 38 KB

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