make_rst.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. #!/usr/bin/env python3
  2. # This script makes RST files from the XML class reference for use with the online docs.
  3. import argparse
  4. import os
  5. import re
  6. import xml.etree.ElementTree as ET
  7. from collections import OrderedDict
  8. # Uncomment to do type checks. I have it commented out so it works below Python 3.5
  9. # from typing import List, Dict, TextIO, Tuple, Iterable, Optional, DefaultDict, Any, Union
  10. # $DOCS_URL/path/to/page.html(#fragment-tag)
  11. GODOT_DOCS_PATTERN = re.compile(r"^\$DOCS_URL/(.*)\.html(#.*)?$")
  12. # Based on reStructedText inline markup recognition rules
  13. # https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
  14. MARKUP_ALLOWED_PRECEDENT = " -:/'\"<([{"
  15. MARKUP_ALLOWED_SUBSEQUENT = " -.,:;!?\\/'\")]}>"
  16. # Used to translate section headings and other hardcoded strings when required with
  17. # the --lang argument. The BASE_STRINGS list should be synced with what we actually
  18. # write in this script (check `translate()` uses), and also hardcoded in
  19. # `doc/translations/extract.py` to include them in the source POT file.
  20. BASE_STRINGS = [
  21. "Description",
  22. "Tutorials",
  23. "Properties",
  24. "Constructors",
  25. "Methods",
  26. "Operators",
  27. "Theme Properties",
  28. "Signals",
  29. "Enumerations",
  30. "Constants",
  31. "Property Descriptions",
  32. "Constructor Descriptions",
  33. "Method Descriptions",
  34. "Operator Descriptions",
  35. "Theme Property Descriptions",
  36. "Inherits:",
  37. "Inherited By:",
  38. "(overrides %s)",
  39. "Default",
  40. "Setter",
  41. "value",
  42. "Getter",
  43. "This method should typically be overridden by the user to have any effect.",
  44. "This method has no side effects. It doesn't modify any of the instance's member variables.",
  45. "This method accepts any number of arguments after the ones described here.",
  46. "This method is used to construct a type.",
  47. "This method doesn't need an instance to be called, so it can be called directly using the class name.",
  48. "This method describes a valid operator to use with this type as left-hand operand.",
  49. ]
  50. strings_l10n = {}
  51. def print_error(error, state): # type: (str, State) -> None
  52. print("ERROR: {}".format(error))
  53. state.errored = True
  54. class TypeName:
  55. def __init__(self, type_name, enum=None): # type: (str, Optional[str]) -> None
  56. self.type_name = type_name
  57. self.enum = enum
  58. def to_rst(self, state): # type: ("State") -> str
  59. if self.enum is not None:
  60. return make_enum(self.enum, state)
  61. elif self.type_name == "void":
  62. return "void"
  63. else:
  64. return make_type(self.type_name, state)
  65. @classmethod
  66. def from_element(cls, element): # type: (ET.Element) -> "TypeName"
  67. return cls(element.attrib["type"], element.get("enum"))
  68. class PropertyDef:
  69. def __init__(
  70. self, name, type_name, setter, getter, text, default_value, overrides
  71. ): # type: (str, TypeName, Optional[str], Optional[str], Optional[str], Optional[str], Optional[str]) -> None
  72. self.name = name
  73. self.type_name = type_name
  74. self.setter = setter
  75. self.getter = getter
  76. self.text = text
  77. self.default_value = default_value
  78. self.overrides = overrides
  79. class ParameterDef:
  80. def __init__(self, name, type_name, default_value): # type: (str, TypeName, Optional[str]) -> None
  81. self.name = name
  82. self.type_name = type_name
  83. self.default_value = default_value
  84. class SignalDef:
  85. def __init__(self, name, parameters, description): # type: (str, List[ParameterDef], Optional[str]) -> None
  86. self.name = name
  87. self.parameters = parameters
  88. self.description = description
  89. class MethodDef:
  90. def __init__(
  91. self, name, return_type, parameters, description, qualifiers
  92. ): # type: (str, TypeName, List[ParameterDef], Optional[str], Optional[str]) -> None
  93. self.name = name
  94. self.return_type = return_type
  95. self.parameters = parameters
  96. self.description = description
  97. self.qualifiers = qualifiers
  98. class ConstantDef:
  99. def __init__(self, name, value, text): # type: (str, str, Optional[str]) -> None
  100. self.name = name
  101. self.value = value
  102. self.text = text
  103. class EnumDef:
  104. def __init__(self, name): # type: (str) -> None
  105. self.name = name
  106. self.values = OrderedDict() # type: OrderedDict[str, ConstantDef]
  107. class ThemeItemDef:
  108. def __init__(
  109. self, name, type_name, data_name, text, default_value
  110. ): # type: (str, TypeName, str, Optional[str], Optional[str]) -> None
  111. self.name = name
  112. self.type_name = type_name
  113. self.data_name = data_name
  114. self.text = text
  115. self.default_value = default_value
  116. class ClassDef:
  117. def __init__(self, name): # type: (str) -> None
  118. self.name = name
  119. self.constants = OrderedDict() # type: OrderedDict[str, ConstantDef]
  120. self.enums = OrderedDict() # type: OrderedDict[str, EnumDef]
  121. self.properties = OrderedDict() # type: OrderedDict[str, PropertyDef]
  122. self.constructors = OrderedDict() # type: OrderedDict[str, List[MethodDef]]
  123. self.methods = OrderedDict() # type: OrderedDict[str, List[MethodDef]]
  124. self.operators = OrderedDict() # type: OrderedDict[str, List[MethodDef]]
  125. self.signals = OrderedDict() # type: OrderedDict[str, SignalDef]
  126. self.theme_items = OrderedDict() # type: OrderedDict[str, ThemeItemDef]
  127. self.inherits = None # type: Optional[str]
  128. self.brief_description = None # type: Optional[str]
  129. self.description = None # type: Optional[str]
  130. self.tutorials = [] # type: List[Tuple[str, str]]
  131. # Used to match the class with XML source for output filtering purposes.
  132. self.filepath = "" # type: str
  133. class State:
  134. def __init__(self): # type: () -> None
  135. # Has any error been reported?
  136. self.errored = False
  137. self.classes = OrderedDict() # type: OrderedDict[str, ClassDef]
  138. self.current_class = "" # type: str
  139. def parse_class(self, class_root, filepath): # type: (ET.Element, str) -> None
  140. class_name = class_root.attrib["name"]
  141. class_def = ClassDef(class_name)
  142. self.classes[class_name] = class_def
  143. class_def.filepath = filepath
  144. inherits = class_root.get("inherits")
  145. if inherits is not None:
  146. class_def.inherits = inherits
  147. brief_desc = class_root.find("brief_description")
  148. if brief_desc is not None and brief_desc.text:
  149. class_def.brief_description = brief_desc.text
  150. desc = class_root.find("description")
  151. if desc is not None and desc.text:
  152. class_def.description = desc.text
  153. properties = class_root.find("members")
  154. if properties is not None:
  155. for property in properties:
  156. assert property.tag == "member"
  157. property_name = property.attrib["name"]
  158. if property_name in class_def.properties:
  159. print_error("Duplicate property '{}', file: {}".format(property_name, class_name), self)
  160. continue
  161. type_name = TypeName.from_element(property)
  162. setter = property.get("setter") or None # Use or None so '' gets turned into None.
  163. getter = property.get("getter") or None
  164. default_value = property.get("default") or None
  165. if default_value is not None:
  166. default_value = "``{}``".format(default_value)
  167. overrides = property.get("overrides") or None
  168. property_def = PropertyDef(
  169. property_name, type_name, setter, getter, property.text, default_value, overrides
  170. )
  171. class_def.properties[property_name] = property_def
  172. constructors = class_root.find("constructors")
  173. if constructors is not None:
  174. for constructor in constructors:
  175. assert constructor.tag == "constructor"
  176. method_name = constructor.attrib["name"]
  177. qualifiers = constructor.get("qualifiers")
  178. return_element = constructor.find("return")
  179. if return_element is not None:
  180. return_type = TypeName.from_element(return_element)
  181. else:
  182. return_type = TypeName("void")
  183. params = parse_arguments(constructor)
  184. desc_element = constructor.find("description")
  185. method_desc = None
  186. if desc_element is not None:
  187. method_desc = desc_element.text
  188. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  189. if method_name not in class_def.constructors:
  190. class_def.constructors[method_name] = []
  191. class_def.constructors[method_name].append(method_def)
  192. methods = class_root.find("methods")
  193. if methods is not None:
  194. for method in methods:
  195. assert method.tag == "method"
  196. method_name = method.attrib["name"]
  197. qualifiers = method.get("qualifiers")
  198. return_element = method.find("return")
  199. if return_element is not None:
  200. return_type = TypeName.from_element(return_element)
  201. else:
  202. return_type = TypeName("void")
  203. params = parse_arguments(method)
  204. desc_element = method.find("description")
  205. method_desc = None
  206. if desc_element is not None:
  207. method_desc = desc_element.text
  208. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  209. if method_name not in class_def.methods:
  210. class_def.methods[method_name] = []
  211. class_def.methods[method_name].append(method_def)
  212. operators = class_root.find("operators")
  213. if operators is not None:
  214. for operator in operators:
  215. assert operator.tag == "operator"
  216. method_name = operator.attrib["name"]
  217. qualifiers = operator.get("qualifiers")
  218. return_element = operator.find("return")
  219. if return_element is not None:
  220. return_type = TypeName.from_element(return_element)
  221. else:
  222. return_type = TypeName("void")
  223. params = parse_arguments(operator)
  224. desc_element = operator.find("description")
  225. method_desc = None
  226. if desc_element is not None:
  227. method_desc = desc_element.text
  228. method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
  229. if method_name not in class_def.operators:
  230. class_def.operators[method_name] = []
  231. class_def.operators[method_name].append(method_def)
  232. constants = class_root.find("constants")
  233. if constants is not None:
  234. for constant in constants:
  235. assert constant.tag == "constant"
  236. constant_name = constant.attrib["name"]
  237. value = constant.attrib["value"]
  238. enum = constant.get("enum")
  239. constant_def = ConstantDef(constant_name, value, constant.text)
  240. if enum is None:
  241. if constant_name in class_def.constants:
  242. print_error("Duplicate constant '{}', file: {}".format(constant_name, class_name), self)
  243. continue
  244. class_def.constants[constant_name] = constant_def
  245. else:
  246. if enum in class_def.enums:
  247. enum_def = class_def.enums[enum]
  248. else:
  249. enum_def = EnumDef(enum)
  250. class_def.enums[enum] = enum_def
  251. enum_def.values[constant_name] = constant_def
  252. signals = class_root.find("signals")
  253. if signals is not None:
  254. for signal in signals:
  255. assert signal.tag == "signal"
  256. signal_name = signal.attrib["name"]
  257. if signal_name in class_def.signals:
  258. print_error("Duplicate signal '{}', file: {}".format(signal_name, class_name), self)
  259. continue
  260. params = parse_arguments(signal)
  261. desc_element = signal.find("description")
  262. signal_desc = None
  263. if desc_element is not None:
  264. signal_desc = desc_element.text
  265. signal_def = SignalDef(signal_name, params, signal_desc)
  266. class_def.signals[signal_name] = signal_def
  267. theme_items = class_root.find("theme_items")
  268. if theme_items is not None:
  269. for theme_item in theme_items:
  270. assert theme_item.tag == "theme_item"
  271. theme_item_name = theme_item.attrib["name"]
  272. theme_item_data_name = theme_item.attrib["data_type"]
  273. theme_item_id = "{}_{}".format(theme_item_data_name, theme_item_name)
  274. if theme_item_id in class_def.theme_items:
  275. print_error(
  276. "Duplicate theme property '{}' of type '{}', file: {}".format(
  277. theme_item_name, theme_item_data_name, class_name
  278. ),
  279. self,
  280. )
  281. continue
  282. default_value = theme_item.get("default") or None
  283. if default_value is not None:
  284. default_value = "``{}``".format(default_value)
  285. theme_item_def = ThemeItemDef(
  286. theme_item_name,
  287. TypeName.from_element(theme_item),
  288. theme_item_data_name,
  289. theme_item.text,
  290. default_value,
  291. )
  292. class_def.theme_items[theme_item_name] = theme_item_def
  293. tutorials = class_root.find("tutorials")
  294. if tutorials is not None:
  295. for link in tutorials:
  296. assert link.tag == "link"
  297. if link.text is not None:
  298. class_def.tutorials.append((link.text.strip(), link.get("title", "")))
  299. def sort_classes(self): # type: () -> None
  300. self.classes = OrderedDict(sorted(self.classes.items(), key=lambda t: t[0]))
  301. def parse_arguments(root): # type: (ET.Element) -> List[ParameterDef]
  302. param_elements = root.findall("argument")
  303. params = [None] * len(param_elements) # type: Any
  304. for param_element in param_elements:
  305. param_name = param_element.attrib["name"]
  306. index = int(param_element.attrib["index"])
  307. type_name = TypeName.from_element(param_element)
  308. default = param_element.get("default")
  309. params[index] = ParameterDef(param_name, type_name, default)
  310. cast = params # type: List[ParameterDef]
  311. return cast
  312. def main(): # type: () -> None
  313. parser = argparse.ArgumentParser()
  314. parser.add_argument("path", nargs="+", help="A path to an XML file or a directory containing XML files to parse.")
  315. parser.add_argument("--filter", default="", help="The filepath pattern for XML files to filter.")
  316. parser.add_argument("--lang", "-l", default="en", help="Language to use for section headings.")
  317. group = parser.add_mutually_exclusive_group()
  318. group.add_argument("--output", "-o", default=".", help="The directory to save output .rst files in.")
  319. group.add_argument(
  320. "--dry-run",
  321. action="store_true",
  322. help="If passed, no output will be generated and XML files are only checked for errors.",
  323. )
  324. args = parser.parse_args()
  325. # Retrieve heading translations for the given language.
  326. if not args.dry_run and args.lang != "en":
  327. lang_file = os.path.join(
  328. os.path.dirname(os.path.realpath(__file__)), "..", "translations", "{}.po".format(args.lang)
  329. )
  330. if os.path.exists(lang_file):
  331. try:
  332. import polib
  333. except ImportError:
  334. print("Base template strings localization requires `polib`.")
  335. exit(1)
  336. pofile = polib.pofile(lang_file)
  337. for entry in pofile.translated_entries():
  338. if entry.msgid in BASE_STRINGS:
  339. strings_l10n[entry.msgid] = entry.msgstr
  340. else:
  341. print("No PO file at '{}' for language '{}'.".format(lang_file, args.lang))
  342. print("Checking for errors in the XML class reference...")
  343. file_list = [] # type: List[str]
  344. for path in args.path:
  345. # Cut off trailing slashes so os.path.basename doesn't choke.
  346. if path.endswith(os.sep):
  347. path = path[:-1]
  348. if os.path.basename(path) == "modules":
  349. for subdir, dirs, _ in os.walk(path):
  350. if "doc_classes" in dirs:
  351. doc_dir = os.path.join(subdir, "doc_classes")
  352. class_file_names = (f for f in os.listdir(doc_dir) if f.endswith(".xml"))
  353. file_list += (os.path.join(doc_dir, f) for f in class_file_names)
  354. elif os.path.isdir(path):
  355. file_list += (os.path.join(path, f) for f in os.listdir(path) if f.endswith(".xml"))
  356. elif os.path.isfile(path):
  357. if not path.endswith(".xml"):
  358. print("Got non-.xml file '{}' in input, skipping.".format(path))
  359. continue
  360. file_list.append(path)
  361. classes = {} # type: Dict[str, ET.Element]
  362. state = State()
  363. for cur_file in file_list:
  364. try:
  365. tree = ET.parse(cur_file)
  366. except ET.ParseError as e:
  367. print_error("Parse error reading file '{}': {}".format(cur_file, e), state)
  368. continue
  369. doc = tree.getroot()
  370. if "version" not in doc.attrib:
  371. print_error("Version missing from 'doc', file: {}".format(cur_file), state)
  372. continue
  373. name = doc.attrib["name"]
  374. if name in classes:
  375. print_error("Duplicate class '{}'".format(name), state)
  376. continue
  377. classes[name] = (doc, cur_file)
  378. for name, data in classes.items():
  379. try:
  380. state.parse_class(data[0], data[1])
  381. except Exception as e:
  382. print_error("Exception while parsing class '{}': {}".format(name, e), state)
  383. state.sort_classes()
  384. pattern = re.compile(args.filter)
  385. # Create the output folder recursively if it doesn't already exist.
  386. os.makedirs(args.output, exist_ok=True)
  387. for class_name, class_def in state.classes.items():
  388. if args.filter and not pattern.search(class_def.filepath):
  389. continue
  390. state.current_class = class_name
  391. make_rst_class(class_def, state, args.dry_run, args.output)
  392. if not state.errored:
  393. print("No errors found.")
  394. if not args.dry_run:
  395. print("Wrote reStructuredText files for each class to: %s" % args.output)
  396. else:
  397. print("Errors were found in the class reference XML. Please check the messages above.")
  398. exit(1)
  399. def translate(string): # type: (str) -> str
  400. """Translate a string based on translations sourced from `doc/translations/*.po`
  401. for a language if defined via the --lang command line argument.
  402. Returns the original string if no translation exists.
  403. """
  404. return strings_l10n.get(string, string)
  405. def make_rst_class(class_def, state, dry_run, output_dir): # type: (ClassDef, State, bool, str) -> None
  406. class_name = class_def.name
  407. if dry_run:
  408. f = open(os.devnull, "w", encoding="utf-8")
  409. else:
  410. f = open(os.path.join(output_dir, "class_" + class_name.lower() + ".rst"), "w", encoding="utf-8")
  411. # Warn contributors not to edit this file directly
  412. f.write(":github_url: hide\n\n")
  413. f.write(".. Generated automatically by doc/tools/make_rst.py in Godot's source tree.\n")
  414. f.write(".. DO NOT EDIT THIS FILE, but the " + class_name + ".xml source instead.\n")
  415. f.write(".. The source is found in doc/classes or modules/<name>/doc_classes.\n\n")
  416. f.write(".. _class_" + class_name + ":\n\n")
  417. f.write(make_heading(class_name, "=", False))
  418. # Inheritance tree
  419. # Ascendants
  420. if class_def.inherits:
  421. inh = class_def.inherits.strip()
  422. f.write("**" + translate("Inherits:") + "** ")
  423. first = True
  424. while inh in state.classes:
  425. if not first:
  426. f.write(" **<** ")
  427. else:
  428. first = False
  429. f.write(make_type(inh, state))
  430. inode = state.classes[inh].inherits
  431. if inode:
  432. inh = inode.strip()
  433. else:
  434. break
  435. f.write("\n\n")
  436. # Descendents
  437. inherited = []
  438. for c in state.classes.values():
  439. if c.inherits and c.inherits.strip() == class_name:
  440. inherited.append(c.name)
  441. if len(inherited):
  442. f.write("**" + translate("Inherited By:") + "** ")
  443. for i, child in enumerate(inherited):
  444. if i > 0:
  445. f.write(", ")
  446. f.write(make_type(child, state))
  447. f.write("\n\n")
  448. # Brief description
  449. if class_def.brief_description is not None:
  450. f.write(rstize_text(class_def.brief_description.strip(), state) + "\n\n")
  451. # Class description
  452. if class_def.description is not None and class_def.description.strip() != "":
  453. f.write(make_heading("Description", "-"))
  454. f.write(rstize_text(class_def.description.strip(), state) + "\n\n")
  455. # Online tutorials
  456. if len(class_def.tutorials) > 0:
  457. f.write(make_heading("Tutorials", "-"))
  458. for url, title in class_def.tutorials:
  459. f.write("- " + make_link(url, title) + "\n\n")
  460. # Properties overview
  461. if len(class_def.properties) > 0:
  462. f.write(make_heading("Properties", "-"))
  463. ml = [] # type: List[Tuple[str, str, str]]
  464. for property_def in class_def.properties.values():
  465. type_rst = property_def.type_name.to_rst(state)
  466. default = property_def.default_value
  467. if default is not None and property_def.overrides:
  468. ref = ":ref:`{1}<class_{1}_property_{0}>`".format(property_def.name, property_def.overrides)
  469. # Not using translate() for now as it breaks table formatting.
  470. ml.append((type_rst, property_def.name, default + " " + "(overrides %s)" % ref))
  471. else:
  472. ref = ":ref:`{0}<class_{1}_property_{0}>`".format(property_def.name, class_name)
  473. ml.append((type_rst, ref, default))
  474. format_table(f, ml, True)
  475. # Constructors, Methods, Operators overview
  476. if len(class_def.constructors) > 0:
  477. f.write(make_heading("Constructors", "-"))
  478. ml = []
  479. for method_list in class_def.constructors.values():
  480. for m in method_list:
  481. ml.append(make_method_signature(class_def, m, "constructor", state))
  482. format_table(f, ml)
  483. if len(class_def.methods) > 0:
  484. f.write(make_heading("Methods", "-"))
  485. ml = []
  486. for method_list in class_def.methods.values():
  487. for m in method_list:
  488. ml.append(make_method_signature(class_def, m, "method", state))
  489. format_table(f, ml)
  490. if len(class_def.operators) > 0:
  491. f.write(make_heading("Operators", "-"))
  492. ml = []
  493. for method_list in class_def.operators.values():
  494. for m in method_list:
  495. ml.append(make_method_signature(class_def, m, "operator", state))
  496. format_table(f, ml)
  497. # Theme properties
  498. if len(class_def.theme_items) > 0:
  499. f.write(make_heading("Theme Properties", "-"))
  500. pl = []
  501. for theme_item_def in class_def.theme_items.values():
  502. ref = ":ref:`{0}<class_{2}_theme_{1}_{0}>`".format(
  503. theme_item_def.name, theme_item_def.data_name, class_name
  504. )
  505. pl.append((theme_item_def.type_name.to_rst(state), ref, theme_item_def.default_value))
  506. format_table(f, pl, True)
  507. # Signals
  508. if len(class_def.signals) > 0:
  509. f.write(make_heading("Signals", "-"))
  510. index = 0
  511. for signal in class_def.signals.values():
  512. if index != 0:
  513. f.write("----\n\n")
  514. f.write(".. _class_{}_signal_{}:\n\n".format(class_name, signal.name))
  515. _, signature = make_method_signature(class_def, signal, "", state)
  516. f.write("- {}\n\n".format(signature))
  517. if signal.description is not None and signal.description.strip() != "":
  518. f.write(rstize_text(signal.description.strip(), state) + "\n\n")
  519. index += 1
  520. # Enums
  521. if len(class_def.enums) > 0:
  522. f.write(make_heading("Enumerations", "-"))
  523. index = 0
  524. for e in class_def.enums.values():
  525. if index != 0:
  526. f.write("----\n\n")
  527. f.write(".. _enum_{}_{}:\n\n".format(class_name, e.name))
  528. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  529. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  530. # As to why I'm not modifying the reference parser to directly link to the _enum label:
  531. # If somebody gets annoyed enough to fix it, all existing references will magically improve.
  532. for value in e.values.values():
  533. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, value.name))
  534. f.write("enum **{}**:\n\n".format(e.name))
  535. for value in e.values.values():
  536. f.write("- **{}** = **{}**".format(value.name, value.value))
  537. if value.text is not None and value.text.strip() != "":
  538. f.write(" --- " + rstize_text(value.text.strip(), state))
  539. f.write("\n\n")
  540. index += 1
  541. # Constants
  542. if len(class_def.constants) > 0:
  543. f.write(make_heading("Constants", "-"))
  544. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  545. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  546. for constant in class_def.constants.values():
  547. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, constant.name))
  548. for constant in class_def.constants.values():
  549. f.write("- **{}** = **{}**".format(constant.name, constant.value))
  550. if constant.text is not None and constant.text.strip() != "":
  551. f.write(" --- " + rstize_text(constant.text.strip(), state))
  552. f.write("\n\n")
  553. # Property descriptions
  554. if any(not p.overrides for p in class_def.properties.values()) > 0:
  555. f.write(make_heading("Property Descriptions", "-"))
  556. index = 0
  557. for property_def in class_def.properties.values():
  558. if property_def.overrides:
  559. continue
  560. if index != 0:
  561. f.write("----\n\n")
  562. f.write(".. _class_{}_property_{}:\n\n".format(class_name, property_def.name))
  563. f.write("- {} **{}**\n\n".format(property_def.type_name.to_rst(state), property_def.name))
  564. info = []
  565. # Not using translate() for now as it breaks table formatting.
  566. if property_def.default_value is not None:
  567. info.append(("*" + "Default" + "*", property_def.default_value))
  568. if property_def.setter is not None and not property_def.setter.startswith("_"):
  569. info.append(("*" + "Setter" + "*", property_def.setter + "(" + "value" + ")"))
  570. if property_def.getter is not None and not property_def.getter.startswith("_"):
  571. info.append(("*" + "Getter" + "*", property_def.getter + "()"))
  572. if len(info) > 0:
  573. format_table(f, info)
  574. if property_def.text is not None and property_def.text.strip() != "":
  575. f.write(rstize_text(property_def.text.strip(), state) + "\n\n")
  576. index += 1
  577. # Constructor, Method, Operator descriptions
  578. if len(class_def.constructors) > 0:
  579. f.write(make_heading("Constructor Descriptions", "-"))
  580. index = 0
  581. for method_list in class_def.constructors.values():
  582. for i, m in enumerate(method_list):
  583. if index != 0:
  584. f.write("----\n\n")
  585. if i == 0:
  586. f.write(".. _class_{}_constructor_{}:\n\n".format(class_name, m.name))
  587. ret_type, signature = make_method_signature(class_def, m, "", state)
  588. f.write("- {} {}\n\n".format(ret_type, signature))
  589. if m.description is not None and m.description.strip() != "":
  590. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  591. index += 1
  592. if len(class_def.methods) > 0:
  593. f.write(make_heading("Method Descriptions", "-"))
  594. index = 0
  595. for method_list in class_def.methods.values():
  596. for i, m in enumerate(method_list):
  597. if index != 0:
  598. f.write("----\n\n")
  599. if i == 0:
  600. f.write(".. _class_{}_method_{}:\n\n".format(class_name, m.name))
  601. ret_type, signature = make_method_signature(class_def, m, "", state)
  602. f.write("- {} {}\n\n".format(ret_type, signature))
  603. if m.description is not None and m.description.strip() != "":
  604. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  605. index += 1
  606. if len(class_def.operators) > 0:
  607. f.write(make_heading("Operator Descriptions", "-"))
  608. index = 0
  609. for method_list in class_def.operators.values():
  610. for i, m in enumerate(method_list):
  611. if index != 0:
  612. f.write("----\n\n")
  613. if i == 0:
  614. f.write(
  615. ".. _class_{}_operator_{}_{}:\n\n".format(
  616. class_name, sanitize_operator_name(m.name, state), m.return_type.type_name
  617. )
  618. )
  619. ret_type, signature = make_method_signature(class_def, m, "", state)
  620. f.write("- {} {}\n\n".format(ret_type, signature))
  621. if m.description is not None and m.description.strip() != "":
  622. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  623. index += 1
  624. # Theme property descriptions
  625. if len(class_def.theme_items) > 0:
  626. f.write(make_heading("Theme Property Descriptions", "-"))
  627. index = 0
  628. for theme_item_def in class_def.theme_items.values():
  629. if index != 0:
  630. f.write("----\n\n")
  631. f.write(".. _class_{}_theme_{}_{}:\n\n".format(class_name, theme_item_def.data_name, theme_item_def.name))
  632. f.write("- {} **{}**\n\n".format(theme_item_def.type_name.to_rst(state), theme_item_def.name))
  633. info = []
  634. if theme_item_def.default_value is not None:
  635. # Not using translate() for now as it breaks table formatting.
  636. info.append(("*" + "Default" + "*", theme_item_def.default_value))
  637. if len(info) > 0:
  638. format_table(f, info)
  639. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  640. f.write(rstize_text(theme_item_def.text.strip(), state) + "\n\n")
  641. index += 1
  642. f.write(make_footer())
  643. def escape_rst(text, until_pos=-1): # type: (str) -> str
  644. # Escape \ character, otherwise it ends up as an escape character in rst
  645. pos = 0
  646. while True:
  647. pos = text.find("\\", pos, until_pos)
  648. if pos == -1:
  649. break
  650. text = text[:pos] + "\\\\" + text[pos + 1 :]
  651. pos += 2
  652. # Escape * character to avoid interpreting it as emphasis
  653. pos = 0
  654. while True:
  655. pos = text.find("*", pos, until_pos)
  656. if pos == -1:
  657. break
  658. text = text[:pos] + "\*" + text[pos + 1 :]
  659. pos += 2
  660. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  661. pos = 0
  662. while True:
  663. pos = text.find("_", pos, until_pos)
  664. if pos == -1:
  665. break
  666. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  667. text = text[:pos] + "\_" + text[pos + 1 :]
  668. pos += 2
  669. else:
  670. pos += 1
  671. return text
  672. def format_codeblock(code_type, post_text, indent_level, state): # types: str, str, int, state
  673. end_pos = post_text.find("[/" + code_type + "]")
  674. if end_pos == -1:
  675. print_error("[" + code_type + "] without a closing tag, file: {}".format(state.current_class), state)
  676. return None
  677. code_text = post_text[len("[" + code_type + "]") : end_pos]
  678. post_text = post_text[end_pos:]
  679. # Remove extraneous tabs
  680. code_pos = 0
  681. while True:
  682. code_pos = code_text.find("\n", code_pos)
  683. if code_pos == -1:
  684. break
  685. to_skip = 0
  686. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  687. to_skip += 1
  688. if to_skip > indent_level:
  689. print_error(
  690. "Four spaces should be used for indentation within ["
  691. + code_type
  692. + "], file: {}".format(state.current_class),
  693. state,
  694. )
  695. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  696. code_text = code_text[:code_pos] + "\n"
  697. code_pos += 1
  698. else:
  699. code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1 :]
  700. code_pos += 5 - to_skip
  701. return ["\n[" + code_type + "]" + code_text + post_text, len("\n[" + code_type + "]" + code_text)]
  702. def rstize_text(text, state): # type: (str, State) -> str
  703. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  704. pos = 0
  705. while True:
  706. pos = text.find("\n", pos)
  707. if pos == -1:
  708. break
  709. pre_text = text[:pos]
  710. indent_level = 0
  711. while text[pos + 1] == "\t":
  712. pos += 1
  713. indent_level += 1
  714. post_text = text[pos + 1 :]
  715. # Handle codeblocks
  716. if (
  717. post_text.startswith("[codeblock]")
  718. or post_text.startswith("[gdscript]")
  719. or post_text.startswith("[csharp]")
  720. ):
  721. block_type = post_text[1:].split("]")[0]
  722. result = format_codeblock(block_type, post_text, indent_level, state)
  723. if result is None:
  724. return ""
  725. text = pre_text + result[0]
  726. pos += result[1] - indent_level
  727. # Handle normal text
  728. else:
  729. text = pre_text + "\n\n" + post_text
  730. pos += 2 - indent_level
  731. next_brac_pos = text.find("[")
  732. text = escape_rst(text, next_brac_pos)
  733. # Handle [tags]
  734. inside_code = False
  735. pos = 0
  736. tag_depth = 0
  737. previous_pos = 0
  738. while True:
  739. pos = text.find("[", pos)
  740. if pos == -1:
  741. break
  742. endq_pos = text.find("]", pos + 1)
  743. if endq_pos == -1:
  744. break
  745. pre_text = text[:pos]
  746. post_text = text[endq_pos + 1 :]
  747. tag_text = text[pos + 1 : endq_pos]
  748. escape_pre = False
  749. escape_post = False
  750. if tag_text in state.classes:
  751. if tag_text == state.current_class:
  752. # We don't want references to the same class
  753. tag_text = "``{}``".format(tag_text)
  754. else:
  755. tag_text = make_type(tag_text, state)
  756. escape_pre = True
  757. escape_post = True
  758. else: # command
  759. cmd = tag_text
  760. space_pos = tag_text.find(" ")
  761. if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp":
  762. tag_text = ""
  763. tag_depth -= 1
  764. inside_code = False
  765. # Strip newline if the tag was alone on one
  766. if pre_text[-1] == "\n":
  767. pre_text = pre_text[:-1]
  768. elif cmd == "/code":
  769. tag_text = "``"
  770. tag_depth -= 1
  771. inside_code = False
  772. escape_post = True
  773. elif inside_code:
  774. tag_text = "[" + tag_text + "]"
  775. elif cmd.find("html") == 0:
  776. param = tag_text[space_pos + 1 :]
  777. tag_text = param
  778. elif (
  779. cmd.startswith("method")
  780. or cmd.startswith("member")
  781. or cmd.startswith("signal")
  782. or cmd.startswith("constant")
  783. or cmd.startswith("theme_item")
  784. ):
  785. param = tag_text[space_pos + 1 :]
  786. if param.find(".") != -1:
  787. ss = param.split(".")
  788. if len(ss) > 2:
  789. print_error("Bad reference: '{}', file: {}".format(param, state.current_class), state)
  790. class_param, method_param = ss
  791. else:
  792. class_param = state.current_class
  793. method_param = param
  794. ref_type = ""
  795. if class_param in state.classes:
  796. class_def = state.classes[class_param]
  797. if cmd.startswith("constructor"):
  798. if method_param not in class_def.constructors:
  799. print_error(
  800. "Unresolved constructor '{}', file: {}".format(param, state.current_class), state
  801. )
  802. ref_type = "_constructor"
  803. if cmd.startswith("method"):
  804. if method_param not in class_def.methods:
  805. print_error("Unresolved method '{}', file: {}".format(param, state.current_class), state)
  806. ref_type = "_method"
  807. if cmd.startswith("operator"):
  808. if method_param not in class_def.operators:
  809. print_error("Unresolved operator '{}', file: {}".format(param, state.current_class), state)
  810. ref_type = "_operator"
  811. elif cmd.startswith("member"):
  812. if method_param not in class_def.properties:
  813. print_error("Unresolved member '{}', file: {}".format(param, state.current_class), state)
  814. ref_type = "_property"
  815. elif cmd.startswith("theme_item"):
  816. if method_param not in class_def.theme_items:
  817. print_error(
  818. "Unresolved theme item '{}', file: {}".format(param, state.current_class), state
  819. )
  820. ref_type = "_theme_{}".format(class_def.theme_items[method_param].data_name)
  821. elif cmd.startswith("signal"):
  822. if method_param not in class_def.signals:
  823. print_error("Unresolved signal '{}', file: {}".format(param, state.current_class), state)
  824. ref_type = "_signal"
  825. elif cmd.startswith("constant"):
  826. found = False
  827. # Search in the current class
  828. search_class_defs = [class_def]
  829. if param.find(".") == -1:
  830. # Also search in @GlobalScope as a last resort if no class was specified
  831. search_class_defs.append(state.classes["@GlobalScope"])
  832. for search_class_def in search_class_defs:
  833. if method_param in search_class_def.constants:
  834. class_param = search_class_def.name
  835. found = True
  836. else:
  837. for enum in search_class_def.enums.values():
  838. if method_param in enum.values:
  839. class_param = search_class_def.name
  840. found = True
  841. break
  842. if not found:
  843. print_error("Unresolved constant '{}', file: {}".format(param, state.current_class), state)
  844. ref_type = "_constant"
  845. else:
  846. print_error(
  847. "Unresolved type reference '{}' in method reference '{}', file: {}".format(
  848. class_param, param, state.current_class
  849. ),
  850. state,
  851. )
  852. repl_text = method_param
  853. if class_param != state.current_class:
  854. repl_text = "{}.{}".format(class_param, method_param)
  855. tag_text = ":ref:`{}<class_{}{}_{}>`".format(repl_text, class_param, ref_type, method_param)
  856. escape_post = True
  857. elif cmd.find("image=") == 0:
  858. tag_text = "" # '![](' + cmd[6:] + ')'
  859. elif cmd.find("url=") == 0:
  860. # URLs are handled in full here as we need to extract the optional link
  861. # title to use `make_link`.
  862. link_url = cmd[4:]
  863. endurl_pos = text.find("[/url]", endq_pos + 1)
  864. if endurl_pos == -1:
  865. print_error(
  866. "Tag depth mismatch for [url]: no closing [/url], file: {}".format(state.current_class), state
  867. )
  868. break
  869. link_title = text[endq_pos + 1 : endurl_pos]
  870. tag_text = make_link(link_url, link_title)
  871. pre_text = text[:pos]
  872. post_text = text[endurl_pos + 6 :]
  873. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  874. pre_text += "\ "
  875. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  876. post_text = "\ " + post_text
  877. text = pre_text + tag_text + post_text
  878. pos = len(pre_text) + len(tag_text)
  879. previous_pos = pos
  880. continue
  881. elif cmd == "center":
  882. tag_depth += 1
  883. tag_text = ""
  884. elif cmd == "/center":
  885. tag_depth -= 1
  886. tag_text = ""
  887. elif cmd == "codeblock":
  888. tag_depth += 1
  889. tag_text = "\n::\n"
  890. inside_code = True
  891. elif cmd == "gdscript":
  892. tag_depth += 1
  893. tag_text = "\n .. code-tab:: gdscript\n"
  894. inside_code = True
  895. elif cmd == "csharp":
  896. tag_depth += 1
  897. tag_text = "\n .. code-tab:: csharp\n"
  898. inside_code = True
  899. elif cmd == "codeblocks":
  900. tag_depth += 1
  901. tag_text = "\n.. tabs::"
  902. elif cmd == "/codeblocks":
  903. tag_depth -= 1
  904. tag_text = ""
  905. elif cmd == "br":
  906. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  907. tag_text = "\n\n"
  908. # Strip potential leading spaces
  909. while post_text[0] == " ":
  910. post_text = post_text[1:]
  911. elif cmd == "i" or cmd == "/i":
  912. if cmd == "/i":
  913. tag_depth -= 1
  914. escape_post = True
  915. else:
  916. tag_depth += 1
  917. escape_pre = True
  918. tag_text = "*"
  919. elif cmd == "b" or cmd == "/b":
  920. if cmd == "/b":
  921. tag_depth -= 1
  922. escape_post = True
  923. else:
  924. tag_depth += 1
  925. escape_pre = True
  926. tag_text = "**"
  927. elif cmd == "u" or cmd == "/u":
  928. if cmd == "/u":
  929. tag_depth -= 1
  930. escape_post = True
  931. else:
  932. tag_depth += 1
  933. escape_pre = True
  934. tag_text = ""
  935. elif cmd == "code":
  936. tag_text = "``"
  937. tag_depth += 1
  938. inside_code = True
  939. escape_pre = True
  940. elif cmd == "kbd":
  941. tag_text = ":kbd:`"
  942. tag_depth += 1
  943. escape_pre = True
  944. elif cmd == "/kbd":
  945. tag_text = "`"
  946. tag_depth -= 1
  947. escape_post = True
  948. elif cmd.startswith("enum "):
  949. tag_text = make_enum(cmd[5:], state)
  950. escape_pre = True
  951. escape_post = True
  952. else:
  953. tag_text = make_type(tag_text, state)
  954. escape_pre = True
  955. escape_post = True
  956. # Properly escape things like `[Node]s`
  957. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  958. pre_text += "\ "
  959. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  960. post_text = "\ " + post_text
  961. next_brac_pos = post_text.find("[", 0)
  962. iter_pos = 0
  963. while not inside_code:
  964. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  965. if iter_pos == -1:
  966. break
  967. post_text = post_text[:iter_pos] + "\*" + post_text[iter_pos + 1 :]
  968. iter_pos += 2
  969. iter_pos = 0
  970. while not inside_code:
  971. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  972. if iter_pos == -1:
  973. break
  974. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  975. post_text = post_text[:iter_pos] + "\_" + post_text[iter_pos + 1 :]
  976. iter_pos += 2
  977. else:
  978. iter_pos += 1
  979. text = pre_text + tag_text + post_text
  980. pos = len(pre_text) + len(tag_text)
  981. previous_pos = pos
  982. if tag_depth > 0:
  983. print_error("Tag depth mismatch: too many/little open/close tags, file: {}".format(state.current_class), state)
  984. return text
  985. def format_table(f, data, remove_empty_columns=False): # type: (TextIO, Iterable[Tuple[str, ...]]) -> None
  986. if len(data) == 0:
  987. return
  988. column_sizes = [0] * len(data[0])
  989. for row in data:
  990. for i, text in enumerate(row):
  991. text_length = len(text or "")
  992. if text_length > column_sizes[i]:
  993. column_sizes[i] = text_length
  994. sep = ""
  995. for size in column_sizes:
  996. if size == 0 and remove_empty_columns:
  997. continue
  998. sep += "+" + "-" * (size + 2)
  999. sep += "+\n"
  1000. f.write(sep)
  1001. for row in data:
  1002. row_text = "|"
  1003. for i, text in enumerate(row):
  1004. if column_sizes[i] == 0 and remove_empty_columns:
  1005. continue
  1006. row_text += " " + (text or "").ljust(column_sizes[i]) + " |"
  1007. row_text += "\n"
  1008. f.write(row_text)
  1009. f.write(sep)
  1010. f.write("\n")
  1011. def make_type(klass, state): # type: (str, State) -> str
  1012. if klass.find("*") != -1: # Pointer, ignore
  1013. return klass
  1014. link_type = klass
  1015. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  1016. link_type = link_type[:-2]
  1017. if link_type in state.classes:
  1018. return ":ref:`{}<class_{}>`".format(klass, link_type)
  1019. print_error("Unresolved type '{}', file: {}".format(klass, state.current_class), state)
  1020. return klass
  1021. def make_enum(t, state): # type: (str, State) -> str
  1022. p = t.find(".")
  1023. if p >= 0:
  1024. c = t[0:p]
  1025. e = t[p + 1 :]
  1026. # Variant enums live in GlobalScope but still use periods.
  1027. if c == "Variant":
  1028. c = "@GlobalScope"
  1029. e = "Variant." + e
  1030. else:
  1031. c = state.current_class
  1032. e = t
  1033. if c in state.classes and e not in state.classes[c].enums:
  1034. c = "@GlobalScope"
  1035. if c in state.classes and e in state.classes[c].enums:
  1036. return ":ref:`{0}<enum_{1}_{0}>`".format(e, c)
  1037. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  1038. if "{}.{}".format(c, e) != "Vector3.Axis":
  1039. print_error("Unresolved enum '{}', file: {}".format(t, state.current_class), state)
  1040. return t
  1041. def make_method_signature(
  1042. class_def, method_def, ref_type, state
  1043. ): # type: (ClassDef, Union[MethodDef, SignalDef], str, State) -> Tuple[str, str]
  1044. ret_type = " "
  1045. if isinstance(method_def, MethodDef):
  1046. ret_type = method_def.return_type.to_rst(state)
  1047. out = ""
  1048. if ref_type != "":
  1049. if ref_type == "operator":
  1050. out += ":ref:`{0}<class_{1}_{2}_{3}_{4}>` ".format(
  1051. method_def.name,
  1052. class_def.name,
  1053. ref_type,
  1054. sanitize_operator_name(method_def.name, state),
  1055. method_def.return_type.type_name,
  1056. )
  1057. else:
  1058. out += ":ref:`{0}<class_{1}_{2}_{0}>` ".format(method_def.name, class_def.name, ref_type)
  1059. else:
  1060. out += "**{}** ".format(method_def.name)
  1061. out += "**(**"
  1062. for i, arg in enumerate(method_def.parameters):
  1063. if i > 0:
  1064. out += ", "
  1065. else:
  1066. out += " "
  1067. out += "{} {}".format(arg.type_name.to_rst(state), arg.name)
  1068. if arg.default_value is not None:
  1069. out += "=" + arg.default_value
  1070. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None and "vararg" in method_def.qualifiers:
  1071. if len(method_def.parameters) > 0:
  1072. out += ", ..."
  1073. else:
  1074. out += " ..."
  1075. out += " **)**"
  1076. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None:
  1077. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  1078. # See `make_footer()` for descriptions.
  1079. for qualifier in method_def.qualifiers.split():
  1080. out += " |" + qualifier + "|"
  1081. return ret_type, out
  1082. def make_heading(title, underline, l10n=True): # type: (str, str, bool) -> str
  1083. if l10n:
  1084. new_title = translate(title)
  1085. if new_title != title:
  1086. title = new_title
  1087. underline *= 2 # Double length to handle wide chars.
  1088. return title + "\n" + (underline * len(title)) + "\n\n"
  1089. def make_footer(): # type: () -> str
  1090. # Generate reusable abbreviation substitutions.
  1091. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  1092. # fmt: off
  1093. return (
  1094. ".. |virtual| replace:: :abbr:`virtual (" + translate("This method should typically be overridden by the user to have any effect.") + ")`\n"
  1095. ".. |const| replace:: :abbr:`const (" + translate("This method has no side effects. It doesn't modify any of the instance's member variables.") + ")`\n"
  1096. ".. |vararg| replace:: :abbr:`vararg (" + translate("This method accepts any number of arguments after the ones described here.") + ")`\n"
  1097. ".. |constructor| replace:: :abbr:`constructor (" + translate("This method is used to construct a type.") + ")`\n"
  1098. ".. |static| replace:: :abbr:`static (" + translate("This method doesn't need an instance to be called, so it can be called directly using the class name.") + ")`\n"
  1099. ".. |operator| replace:: :abbr:`operator (" + translate("This method describes a valid operator to use with this type as left-hand operand.") + ")`\n"
  1100. )
  1101. # fmt: on
  1102. def make_link(url, title): # type: (str, str) -> str
  1103. match = GODOT_DOCS_PATTERN.search(url)
  1104. if match:
  1105. groups = match.groups()
  1106. if match.lastindex == 2:
  1107. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  1108. # `#calling-javascript-from-script in Exporting For Web`
  1109. # Or use the title if provided.
  1110. if title != "":
  1111. return "`" + title + " <../" + groups[0] + ".html" + groups[1] + ">`__"
  1112. return "`" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`__ in :doc:`../" + groups[0] + "`"
  1113. elif match.lastindex == 1:
  1114. # Doc reference, for example:
  1115. # `Math`
  1116. if title != "":
  1117. return ":doc:`" + title + " <../" + groups[0] + ">`"
  1118. return ":doc:`../" + groups[0] + "`"
  1119. else:
  1120. # External link, for example:
  1121. # `http://enet.bespin.org/usergroup0.html`
  1122. if title != "":
  1123. return "`" + title + " <" + url + ">`__"
  1124. return "`" + url + " <" + url + ">`__"
  1125. def sanitize_operator_name(dirty_name, state): # type: (str, State) -> str
  1126. clear_name = dirty_name.replace("operator ", "")
  1127. if clear_name == "!=":
  1128. clear_name = "neq"
  1129. elif clear_name == "==":
  1130. clear_name = "eq"
  1131. elif clear_name == "<":
  1132. clear_name = "lt"
  1133. elif clear_name == "<=":
  1134. clear_name = "lte"
  1135. elif clear_name == ">":
  1136. clear_name = "gt"
  1137. elif clear_name == ">=":
  1138. clear_name = "gte"
  1139. elif clear_name == "+":
  1140. clear_name = "sum"
  1141. elif clear_name == "-":
  1142. clear_name = "dif"
  1143. elif clear_name == "*":
  1144. clear_name = "mul"
  1145. elif clear_name == "/":
  1146. clear_name = "div"
  1147. elif clear_name == "%":
  1148. clear_name = "mod"
  1149. elif clear_name == "unary+":
  1150. clear_name = "unplus"
  1151. elif clear_name == "unary-":
  1152. clear_name = "unminus"
  1153. elif clear_name == "<<":
  1154. clear_name = "bwsl"
  1155. elif clear_name == ">>":
  1156. clear_name = "bwsr"
  1157. elif clear_name == "&":
  1158. clear_name = "bwand"
  1159. elif clear_name == "|":
  1160. clear_name = "bwor"
  1161. elif clear_name == "^":
  1162. clear_name = "bwxor"
  1163. elif clear_name == "~":
  1164. clear_name = "bwnot"
  1165. elif clear_name == "[]":
  1166. clear_name = "idx"
  1167. else:
  1168. clear_name = "xxx"
  1169. print_error("Unsupported operator type '{}', please add the missing rule.".format(dirty_name), state)
  1170. return clear_name
  1171. if __name__ == "__main__":
  1172. main()