make_rst.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  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. # If value.text contains a bullet point list, each entry needs additional indentation
  543. f.write(" --- " + indent_bullets(rstize_text(value.text.strip(), state)))
  544. f.write("\n\n")
  545. index += 1
  546. # Constants
  547. if len(class_def.constants) > 0:
  548. f.write(make_heading("Constants", "-"))
  549. # Sphinx seems to divide the bullet list into individual <ul> tags if we weave the labels into it.
  550. # As such I'll put them all above the list. Won't be perfect but better than making the list visually broken.
  551. for constant in class_def.constants.values():
  552. f.write(".. _class_{}_constant_{}:\n\n".format(class_name, constant.name))
  553. for constant in class_def.constants.values():
  554. f.write("- **{}** = **{}**".format(constant.name, constant.value))
  555. if constant.text is not None and constant.text.strip() != "":
  556. f.write(" --- " + rstize_text(constant.text.strip(), state))
  557. f.write("\n\n")
  558. # Property descriptions
  559. if any(not p.overrides for p in class_def.properties.values()) > 0:
  560. f.write(make_heading("Property Descriptions", "-"))
  561. index = 0
  562. for property_def in class_def.properties.values():
  563. if property_def.overrides:
  564. continue
  565. if index != 0:
  566. f.write("----\n\n")
  567. f.write(".. _class_{}_property_{}:\n\n".format(class_name, property_def.name))
  568. f.write("- {} **{}**\n\n".format(property_def.type_name.to_rst(state), property_def.name))
  569. info = []
  570. # Not using translate() for now as it breaks table formatting.
  571. if property_def.default_value is not None:
  572. info.append(("*" + "Default" + "*", property_def.default_value))
  573. if property_def.setter is not None and not property_def.setter.startswith("_"):
  574. info.append(("*" + "Setter" + "*", property_def.setter + "(" + "value" + ")"))
  575. if property_def.getter is not None and not property_def.getter.startswith("_"):
  576. info.append(("*" + "Getter" + "*", property_def.getter + "()"))
  577. if len(info) > 0:
  578. format_table(f, info)
  579. if property_def.text is not None and property_def.text.strip() != "":
  580. f.write(rstize_text(property_def.text.strip(), state) + "\n\n")
  581. index += 1
  582. # Constructor, Method, Operator descriptions
  583. if len(class_def.constructors) > 0:
  584. f.write(make_heading("Constructor Descriptions", "-"))
  585. index = 0
  586. for method_list in class_def.constructors.values():
  587. for i, m in enumerate(method_list):
  588. if index != 0:
  589. f.write("----\n\n")
  590. if i == 0:
  591. f.write(".. _class_{}_constructor_{}:\n\n".format(class_name, m.name))
  592. ret_type, signature = make_method_signature(class_def, m, "", state)
  593. f.write("- {} {}\n\n".format(ret_type, signature))
  594. if m.description is not None and m.description.strip() != "":
  595. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  596. index += 1
  597. if len(class_def.methods) > 0:
  598. f.write(make_heading("Method Descriptions", "-"))
  599. index = 0
  600. for method_list in class_def.methods.values():
  601. for i, m in enumerate(method_list):
  602. if index != 0:
  603. f.write("----\n\n")
  604. if i == 0:
  605. f.write(".. _class_{}_method_{}:\n\n".format(class_name, m.name))
  606. ret_type, signature = make_method_signature(class_def, m, "", state)
  607. f.write("- {} {}\n\n".format(ret_type, signature))
  608. if m.description is not None and m.description.strip() != "":
  609. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  610. index += 1
  611. if len(class_def.operators) > 0:
  612. f.write(make_heading("Operator Descriptions", "-"))
  613. index = 0
  614. for method_list in class_def.operators.values():
  615. for i, m in enumerate(method_list):
  616. if index != 0:
  617. f.write("----\n\n")
  618. if i == 0:
  619. f.write(
  620. ".. _class_{}_operator_{}_{}:\n\n".format(
  621. class_name, sanitize_operator_name(m.name, state), m.return_type.type_name
  622. )
  623. )
  624. ret_type, signature = make_method_signature(class_def, m, "", state)
  625. f.write("- {} {}\n\n".format(ret_type, signature))
  626. if m.description is not None and m.description.strip() != "":
  627. f.write(rstize_text(m.description.strip(), state) + "\n\n")
  628. index += 1
  629. # Theme property descriptions
  630. if len(class_def.theme_items) > 0:
  631. f.write(make_heading("Theme Property Descriptions", "-"))
  632. index = 0
  633. for theme_item_def in class_def.theme_items.values():
  634. if index != 0:
  635. f.write("----\n\n")
  636. f.write(".. _class_{}_theme_{}_{}:\n\n".format(class_name, theme_item_def.data_name, theme_item_def.name))
  637. f.write("- {} **{}**\n\n".format(theme_item_def.type_name.to_rst(state), theme_item_def.name))
  638. info = []
  639. if theme_item_def.default_value is not None:
  640. # Not using translate() for now as it breaks table formatting.
  641. info.append(("*" + "Default" + "*", theme_item_def.default_value))
  642. if len(info) > 0:
  643. format_table(f, info)
  644. if theme_item_def.text is not None and theme_item_def.text.strip() != "":
  645. f.write(rstize_text(theme_item_def.text.strip(), state) + "\n\n")
  646. index += 1
  647. f.write(make_footer())
  648. def escape_rst(text, until_pos=-1): # type: (str) -> str
  649. # Escape \ character, otherwise it ends up as an escape character in rst
  650. pos = 0
  651. while True:
  652. pos = text.find("\\", pos, until_pos)
  653. if pos == -1:
  654. break
  655. text = text[:pos] + "\\\\" + text[pos + 1 :]
  656. pos += 2
  657. # Escape * character to avoid interpreting it as emphasis
  658. pos = 0
  659. while True:
  660. pos = text.find("*", pos, until_pos)
  661. if pos == -1:
  662. break
  663. text = text[:pos] + "\*" + text[pos + 1 :]
  664. pos += 2
  665. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  666. pos = 0
  667. while True:
  668. pos = text.find("_", pos, until_pos)
  669. if pos == -1:
  670. break
  671. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  672. text = text[:pos] + "\_" + text[pos + 1 :]
  673. pos += 2
  674. else:
  675. pos += 1
  676. return text
  677. def format_codeblock(code_type, post_text, indent_level, state): # types: str, str, int, state
  678. end_pos = post_text.find("[/" + code_type + "]")
  679. if end_pos == -1:
  680. print_error("{}.xml: [" + code_type + "] without a closing tag.".format(state.current_class), state)
  681. return None
  682. code_text = post_text[len("[" + code_type + "]") : end_pos]
  683. post_text = post_text[end_pos:]
  684. # Remove extraneous tabs
  685. code_pos = 0
  686. while True:
  687. code_pos = code_text.find("\n", code_pos)
  688. if code_pos == -1:
  689. break
  690. to_skip = 0
  691. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t":
  692. to_skip += 1
  693. if to_skip > indent_level:
  694. print_error(
  695. "{}.xml: Four spaces should be used for indentation within ["
  696. + code_type
  697. + "].".format(state.current_class),
  698. state,
  699. )
  700. if len(code_text[code_pos + to_skip + 1 :]) == 0:
  701. code_text = code_text[:code_pos] + "\n"
  702. code_pos += 1
  703. else:
  704. code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1 :]
  705. code_pos += 5 - to_skip
  706. return ["\n[" + code_type + "]" + code_text + post_text, len("\n[" + code_type + "]" + code_text)]
  707. def rstize_text(text, state): # type: (str, State) -> str
  708. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  709. pos = 0
  710. while True:
  711. pos = text.find("\n", pos)
  712. if pos == -1:
  713. break
  714. pre_text = text[:pos]
  715. indent_level = 0
  716. while pos + 1 < len(text) and text[pos + 1] == "\t":
  717. pos += 1
  718. indent_level += 1
  719. post_text = text[pos + 1 :]
  720. # Handle codeblocks
  721. if (
  722. post_text.startswith("[codeblock]")
  723. or post_text.startswith("[gdscript]")
  724. or post_text.startswith("[csharp]")
  725. ):
  726. block_type = post_text[1:].split("]")[0]
  727. result = format_codeblock(block_type, post_text, indent_level, state)
  728. if result is None:
  729. return ""
  730. text = pre_text + result[0]
  731. pos += result[1] - indent_level
  732. # Handle normal text
  733. else:
  734. text = pre_text + "\n\n" + post_text
  735. pos += 2 - indent_level
  736. next_brac_pos = text.find("[")
  737. text = escape_rst(text, next_brac_pos)
  738. # Handle [tags]
  739. inside_code = False
  740. pos = 0
  741. tag_depth = 0
  742. previous_pos = 0
  743. while True:
  744. pos = text.find("[", pos)
  745. if pos == -1:
  746. break
  747. endq_pos = text.find("]", pos + 1)
  748. if endq_pos == -1:
  749. break
  750. pre_text = text[:pos]
  751. post_text = text[endq_pos + 1 :]
  752. tag_text = text[pos + 1 : endq_pos]
  753. escape_pre = False
  754. escape_post = False
  755. if tag_text in state.classes:
  756. if tag_text == state.current_class:
  757. # We don't want references to the same class
  758. tag_text = "``{}``".format(tag_text)
  759. else:
  760. tag_text = make_type(tag_text, state)
  761. escape_pre = True
  762. escape_post = True
  763. else: # command
  764. cmd = tag_text
  765. space_pos = tag_text.find(" ")
  766. if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp":
  767. tag_text = ""
  768. tag_depth -= 1
  769. inside_code = False
  770. # Strip newline if the tag was alone on one
  771. if pre_text[-1] == "\n":
  772. pre_text = pre_text[:-1]
  773. elif cmd == "/code":
  774. tag_text = "``"
  775. tag_depth -= 1
  776. inside_code = False
  777. escape_post = True
  778. elif inside_code:
  779. tag_text = "[" + tag_text + "]"
  780. elif cmd.find("html") == 0:
  781. param = tag_text[space_pos + 1 :]
  782. tag_text = param
  783. elif (
  784. cmd.startswith("method")
  785. or cmd.startswith("member")
  786. or cmd.startswith("signal")
  787. or cmd.startswith("constant")
  788. or cmd.startswith("theme_item")
  789. ):
  790. param = tag_text[space_pos + 1 :]
  791. if param.find(".") != -1:
  792. ss = param.split(".")
  793. if len(ss) > 2:
  794. print_error('{}.xml: Bad reference: "{}".'.format(state.current_class, param), state)
  795. class_param, method_param = ss
  796. else:
  797. class_param = state.current_class
  798. method_param = param
  799. ref_type = ""
  800. if class_param in state.classes:
  801. class_def = state.classes[class_param]
  802. if cmd.startswith("constructor"):
  803. if method_param not in class_def.constructors:
  804. print_error(
  805. '{}.xml: Unresolved constructor "{}".'.format(state.current_class, param), state
  806. )
  807. ref_type = "_constructor"
  808. if cmd.startswith("method"):
  809. if method_param not in class_def.methods:
  810. print_error('{}.xml: Unresolved method "{}".'.format(state.current_class, param), state)
  811. ref_type = "_method"
  812. if cmd.startswith("operator"):
  813. if method_param not in class_def.operators:
  814. print_error('{}.xml: Unresolved operator "{}".'.format(state.current_class, param), state)
  815. ref_type = "_operator"
  816. elif cmd.startswith("member"):
  817. if method_param not in class_def.properties:
  818. print_error('{}.xml: Unresolved member "{}".'.format(state.current_class, param), state)
  819. ref_type = "_property"
  820. elif cmd.startswith("theme_item"):
  821. if method_param not in class_def.theme_items:
  822. print_error('{}.xml: Unresolved theme item "{}".'.format(state.current_class, param), state)
  823. ref_type = "_theme_{}".format(class_def.theme_items[method_param].data_name)
  824. elif cmd.startswith("signal"):
  825. if method_param not in class_def.signals:
  826. print_error('{}.xml: Unresolved signal "{}".'.format(state.current_class, param), state)
  827. ref_type = "_signal"
  828. elif cmd.startswith("constant"):
  829. found = False
  830. # Search in the current class
  831. search_class_defs = [class_def]
  832. if param.find(".") == -1:
  833. # Also search in @GlobalScope as a last resort if no class was specified
  834. search_class_defs.append(state.classes["@GlobalScope"])
  835. for search_class_def in search_class_defs:
  836. if method_param in search_class_def.constants:
  837. class_param = search_class_def.name
  838. found = True
  839. else:
  840. for enum in search_class_def.enums.values():
  841. if method_param in enum.values:
  842. class_param = search_class_def.name
  843. found = True
  844. break
  845. if not found:
  846. print_error('{}.xml: Unresolved constant "{}".'.format(state.current_class, param), state)
  847. ref_type = "_constant"
  848. else:
  849. print_error(
  850. '{}.xml: Unresolved type reference "{}" in method reference "{}".'.format(
  851. state.current_class, class_param, param
  852. ),
  853. state,
  854. )
  855. repl_text = method_param
  856. if class_param != state.current_class:
  857. repl_text = "{}.{}".format(class_param, method_param)
  858. tag_text = ":ref:`{}<class_{}{}_{}>`".format(repl_text, class_param, ref_type, method_param)
  859. escape_pre = True
  860. escape_post = True
  861. elif cmd.find("image=") == 0:
  862. tag_text = "" # '![](' + cmd[6:] + ')'
  863. elif cmd.find("url=") == 0:
  864. # URLs are handled in full here as we need to extract the optional link
  865. # title to use `make_link`.
  866. link_url = cmd[4:]
  867. endurl_pos = text.find("[/url]", endq_pos + 1)
  868. if endurl_pos == -1:
  869. print_error(
  870. "{}.xml: Tag depth mismatch for [url]: no closing [/url]".format(state.current_class), state
  871. )
  872. break
  873. link_title = text[endq_pos + 1 : endurl_pos]
  874. tag_text = make_link(link_url, link_title)
  875. pre_text = text[:pos]
  876. post_text = text[endurl_pos + 6 :]
  877. if pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  878. pre_text += "\ "
  879. if post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  880. post_text = "\ " + post_text
  881. text = pre_text + tag_text + post_text
  882. pos = len(pre_text) + len(tag_text)
  883. previous_pos = pos
  884. continue
  885. elif cmd == "center":
  886. tag_depth += 1
  887. tag_text = ""
  888. elif cmd == "/center":
  889. tag_depth -= 1
  890. tag_text = ""
  891. elif cmd == "codeblock":
  892. tag_depth += 1
  893. tag_text = "\n::\n"
  894. inside_code = True
  895. elif cmd == "gdscript":
  896. tag_depth += 1
  897. tag_text = "\n .. code-tab:: gdscript\n"
  898. inside_code = True
  899. elif cmd == "csharp":
  900. tag_depth += 1
  901. tag_text = "\n .. code-tab:: csharp\n"
  902. inside_code = True
  903. elif cmd == "codeblocks":
  904. tag_depth += 1
  905. tag_text = "\n.. tabs::"
  906. elif cmd == "/codeblocks":
  907. tag_depth -= 1
  908. tag_text = ""
  909. elif cmd == "br":
  910. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  911. tag_text = "\n\n"
  912. # Strip potential leading spaces
  913. while post_text[0] == " ":
  914. post_text = post_text[1:]
  915. elif cmd == "i" or cmd == "/i":
  916. if cmd == "/i":
  917. tag_depth -= 1
  918. escape_post = True
  919. else:
  920. tag_depth += 1
  921. escape_pre = True
  922. tag_text = "*"
  923. elif cmd == "b" or cmd == "/b":
  924. if cmd == "/b":
  925. tag_depth -= 1
  926. escape_post = True
  927. else:
  928. tag_depth += 1
  929. escape_pre = True
  930. tag_text = "**"
  931. elif cmd == "u" or cmd == "/u":
  932. if cmd == "/u":
  933. tag_depth -= 1
  934. escape_post = True
  935. else:
  936. tag_depth += 1
  937. escape_pre = True
  938. tag_text = ""
  939. elif cmd == "code":
  940. tag_text = "``"
  941. tag_depth += 1
  942. inside_code = True
  943. escape_pre = True
  944. elif cmd == "kbd":
  945. tag_text = ":kbd:`"
  946. tag_depth += 1
  947. escape_pre = True
  948. elif cmd == "/kbd":
  949. tag_text = "`"
  950. tag_depth -= 1
  951. escape_post = True
  952. elif cmd.startswith("enum "):
  953. tag_text = make_enum(cmd[5:], state)
  954. escape_pre = True
  955. escape_post = True
  956. else:
  957. tag_text = make_type(tag_text, state)
  958. escape_pre = True
  959. escape_post = True
  960. # Properly escape things like `[Node]s`
  961. if escape_pre and pre_text and pre_text[-1] not in MARKUP_ALLOWED_PRECEDENT:
  962. pre_text += "\ "
  963. if escape_post and post_text and post_text[0] not in MARKUP_ALLOWED_SUBSEQUENT:
  964. post_text = "\ " + post_text
  965. next_brac_pos = post_text.find("[", 0)
  966. iter_pos = 0
  967. while not inside_code:
  968. iter_pos = post_text.find("*", iter_pos, next_brac_pos)
  969. if iter_pos == -1:
  970. break
  971. post_text = post_text[:iter_pos] + "\*" + post_text[iter_pos + 1 :]
  972. iter_pos += 2
  973. iter_pos = 0
  974. while not inside_code:
  975. iter_pos = post_text.find("_", iter_pos, next_brac_pos)
  976. if iter_pos == -1:
  977. break
  978. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  979. post_text = post_text[:iter_pos] + "\_" + post_text[iter_pos + 1 :]
  980. iter_pos += 2
  981. else:
  982. iter_pos += 1
  983. text = pre_text + tag_text + post_text
  984. pos = len(pre_text) + len(tag_text)
  985. previous_pos = pos
  986. if tag_depth > 0:
  987. print_error(
  988. "{}.xml: Tag depth mismatch: too many (or too little) open/close tags.".format(state.current_class), state
  989. )
  990. return text
  991. def format_table(f, data, remove_empty_columns=False): # type: (TextIO, Iterable[Tuple[str, ...]]) -> None
  992. if len(data) == 0:
  993. return
  994. column_sizes = [0] * len(data[0])
  995. for row in data:
  996. for i, text in enumerate(row):
  997. text_length = len(text or "")
  998. if text_length > column_sizes[i]:
  999. column_sizes[i] = text_length
  1000. sep = ""
  1001. for size in column_sizes:
  1002. if size == 0 and remove_empty_columns:
  1003. continue
  1004. sep += "+" + "-" * (size + 2)
  1005. sep += "+\n"
  1006. f.write(sep)
  1007. for row in data:
  1008. row_text = "|"
  1009. for i, text in enumerate(row):
  1010. if column_sizes[i] == 0 and remove_empty_columns:
  1011. continue
  1012. row_text += " " + (text or "").ljust(column_sizes[i]) + " |"
  1013. row_text += "\n"
  1014. f.write(row_text)
  1015. f.write(sep)
  1016. f.write("\n")
  1017. def make_type(klass, state): # type: (str, State) -> str
  1018. if klass.find("*") != -1: # Pointer, ignore
  1019. return klass
  1020. link_type = klass
  1021. if link_type.endswith("[]"): # Typed array, strip [] to link to contained type.
  1022. link_type = link_type[:-2]
  1023. if link_type in state.classes:
  1024. return ":ref:`{}<class_{}>`".format(klass, link_type)
  1025. print_error('{}.xml: Unresolved type "{}".'.format(state.current_class, klass), state)
  1026. return klass
  1027. def make_enum(t, state): # type: (str, State) -> str
  1028. p = t.find(".")
  1029. if p >= 0:
  1030. c = t[0:p]
  1031. e = t[p + 1 :]
  1032. # Variant enums live in GlobalScope but still use periods.
  1033. if c == "Variant":
  1034. c = "@GlobalScope"
  1035. e = "Variant." + e
  1036. else:
  1037. c = state.current_class
  1038. e = t
  1039. if c in state.classes and e not in state.classes[c].enums:
  1040. c = "@GlobalScope"
  1041. if c in state.classes and e in state.classes[c].enums:
  1042. return ":ref:`{0}<enum_{1}_{0}>`".format(e, c)
  1043. # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved.
  1044. if "{}.{}".format(c, e) != "Vector3.Axis":
  1045. print_error('{}.xml: Unresolved enum "{}".'.format(state.current_class, t), state)
  1046. return t
  1047. def make_method_signature(
  1048. class_def, method_def, ref_type, state
  1049. ): # type: (ClassDef, Union[MethodDef, SignalDef], str, State) -> Tuple[str, str]
  1050. ret_type = " "
  1051. if isinstance(method_def, MethodDef):
  1052. ret_type = method_def.return_type.to_rst(state)
  1053. out = ""
  1054. if ref_type != "":
  1055. if ref_type == "operator":
  1056. out += ":ref:`{0}<class_{1}_{2}_{3}_{4}>` ".format(
  1057. method_def.name,
  1058. class_def.name,
  1059. ref_type,
  1060. sanitize_operator_name(method_def.name, state),
  1061. method_def.return_type.type_name,
  1062. )
  1063. else:
  1064. out += ":ref:`{0}<class_{1}_{2}_{0}>` ".format(method_def.name, class_def.name, ref_type)
  1065. else:
  1066. out += "**{}** ".format(method_def.name)
  1067. out += "**(**"
  1068. for i, arg in enumerate(method_def.parameters):
  1069. if i > 0:
  1070. out += ", "
  1071. else:
  1072. out += " "
  1073. out += "{} {}".format(arg.type_name.to_rst(state), arg.name)
  1074. if arg.default_value is not None:
  1075. out += "=" + arg.default_value
  1076. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None and "vararg" in method_def.qualifiers:
  1077. if len(method_def.parameters) > 0:
  1078. out += ", ..."
  1079. else:
  1080. out += " ..."
  1081. out += " **)**"
  1082. if isinstance(method_def, MethodDef) and method_def.qualifiers is not None:
  1083. # Use substitutions for abbreviations. This is used to display tooltips on hover.
  1084. # See `make_footer()` for descriptions.
  1085. for qualifier in method_def.qualifiers.split():
  1086. out += " |" + qualifier + "|"
  1087. return ret_type, out
  1088. def make_heading(title, underline, l10n=True): # type: (str, str, bool) -> str
  1089. if l10n:
  1090. new_title = translate(title)
  1091. if new_title != title:
  1092. title = new_title
  1093. underline *= 2 # Double length to handle wide chars.
  1094. return title + "\n" + (underline * len(title)) + "\n\n"
  1095. def make_footer(): # type: () -> str
  1096. # Generate reusable abbreviation substitutions.
  1097. # This way, we avoid bloating the generated rST with duplicate abbreviations.
  1098. # fmt: off
  1099. return (
  1100. ".. |virtual| replace:: :abbr:`virtual (" + translate("This method should typically be overridden by the user to have any effect.") + ")`\n"
  1101. ".. |const| replace:: :abbr:`const (" + translate("This method has no side effects. It doesn't modify any of the instance's member variables.") + ")`\n"
  1102. ".. |vararg| replace:: :abbr:`vararg (" + translate("This method accepts any number of arguments after the ones described here.") + ")`\n"
  1103. ".. |constructor| replace:: :abbr:`constructor (" + translate("This method is used to construct a type.") + ")`\n"
  1104. ".. |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"
  1105. ".. |operator| replace:: :abbr:`operator (" + translate("This method describes a valid operator to use with this type as left-hand operand.") + ")`\n"
  1106. )
  1107. # fmt: on
  1108. def make_link(url, title): # type: (str, str) -> str
  1109. match = GODOT_DOCS_PATTERN.search(url)
  1110. if match:
  1111. groups = match.groups()
  1112. if match.lastindex == 2:
  1113. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  1114. # `#calling-javascript-from-script in Exporting For Web`
  1115. # Or use the title if provided.
  1116. if title != "":
  1117. return "`" + title + " <../" + groups[0] + ".html" + groups[1] + ">`__"
  1118. return "`" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`__ in :doc:`../" + groups[0] + "`"
  1119. elif match.lastindex == 1:
  1120. # Doc reference, for example:
  1121. # `Math`
  1122. if title != "":
  1123. return ":doc:`" + title + " <../" + groups[0] + ">`"
  1124. return ":doc:`../" + groups[0] + "`"
  1125. else:
  1126. # External link, for example:
  1127. # `http://enet.bespin.org/usergroup0.html`
  1128. if title != "":
  1129. return "`" + title + " <" + url + ">`__"
  1130. return "`" + url + " <" + url + ">`__"
  1131. def sanitize_operator_name(dirty_name, state): # type: (str, State) -> str
  1132. clear_name = dirty_name.replace("operator ", "")
  1133. if clear_name == "!=":
  1134. clear_name = "neq"
  1135. elif clear_name == "==":
  1136. clear_name = "eq"
  1137. elif clear_name == "<":
  1138. clear_name = "lt"
  1139. elif clear_name == "<=":
  1140. clear_name = "lte"
  1141. elif clear_name == ">":
  1142. clear_name = "gt"
  1143. elif clear_name == ">=":
  1144. clear_name = "gte"
  1145. elif clear_name == "+":
  1146. clear_name = "sum"
  1147. elif clear_name == "-":
  1148. clear_name = "dif"
  1149. elif clear_name == "*":
  1150. clear_name = "mul"
  1151. elif clear_name == "/":
  1152. clear_name = "div"
  1153. elif clear_name == "%":
  1154. clear_name = "mod"
  1155. elif clear_name == "unary+":
  1156. clear_name = "unplus"
  1157. elif clear_name == "unary-":
  1158. clear_name = "unminus"
  1159. elif clear_name == "<<":
  1160. clear_name = "bwsl"
  1161. elif clear_name == ">>":
  1162. clear_name = "bwsr"
  1163. elif clear_name == "&":
  1164. clear_name = "bwand"
  1165. elif clear_name == "|":
  1166. clear_name = "bwor"
  1167. elif clear_name == "^":
  1168. clear_name = "bwxor"
  1169. elif clear_name == "~":
  1170. clear_name = "bwnot"
  1171. elif clear_name == "[]":
  1172. clear_name = "idx"
  1173. else:
  1174. clear_name = "xxx"
  1175. print_error('Unsupported operator type "{}", please add the missing rule.'.format(dirty_name), state)
  1176. return clear_name
  1177. def indent_bullets(text): # type: (str) -> str
  1178. # Take the text and check each line for a bullet point represented by "-".
  1179. # Where found, indent the given line by a further "\t".
  1180. # Used to properly indent bullet points contained in the description for enum values.
  1181. # Ignore the first line - text will be prepended to it so bullet points wouldn't work anyway.
  1182. bullet_points = "-"
  1183. lines = text.splitlines(keepends=True)
  1184. for line_index, line in enumerate(lines[1:], start=1):
  1185. pos = 0
  1186. while pos < len(line) and line[pos] == "\t":
  1187. pos += 1
  1188. if pos < len(line) and line[pos] in bullet_points:
  1189. lines[line_index] = line[:pos] + "\t" + line[pos:]
  1190. return "".join(lines)
  1191. if __name__ == "__main__":
  1192. main()