make_rst.py 52 KB

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