make_rst.py 80 KB

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