make_rst.py 79 KB

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