make_rst.py 79 KB

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