make_rst.py 56 KB

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