make_rst.py 54 KB

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