makerst.py 36 KB

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