make_rst.py 70 KB

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