2
0

make_rst.py 56 KB

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