make_rst.py 78 KB

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