docgen.nim 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This is the Nim documentation generator. Cross-references are generated
  10. ## by knowing how the anchors are going to be named.
  11. ##
  12. ## .. importdoc:: ../docgen.md
  13. ##
  14. ## For corresponding users' documentation see [Nim DocGen Tools Guide].
  15. import
  16. ast, strutils, strtabs, algorithm, sequtils, options, msgs, os, idents,
  17. wordrecg, syntaxes, renderer, lexer,
  18. packages/docutils/[rst, rstidx, rstgen, dochelpers],
  19. json, xmltree, trees, types,
  20. typesrenderer, astalgo, lineinfos, intsets,
  21. pathutils, tables, nimpaths, renderverbatim, osproc, packages
  22. import packages/docutils/rstast except FileIndex, TLineInfo
  23. from uri import encodeUrl
  24. from nodejs import findNodeJs
  25. when defined(nimPreviewSlimSystem):
  26. import std/[assertions, syncio]
  27. const
  28. exportSection = skField
  29. docCmdSkip = "skip"
  30. DocColOffset = "## ".len # assuming that a space was added after ##
  31. type
  32. ItemFragment = object ## A fragment from each item will be eventually
  33. ## constructed by converting `rst` fields to strings.
  34. case isRst: bool
  35. of true:
  36. rst: PRstNode
  37. of false: ## contains ready markup e.g. from runnableExamples
  38. str: string
  39. ItemPre = seq[ItemFragment] ## A pre-processed item.
  40. Item = object ## Any item in documentation, e.g. symbol
  41. ## entry. Configuration variable ``doc.item``
  42. ## is used for its HTML rendering.
  43. descRst: ItemPre ## Description of the item (may contain
  44. ## runnableExamples).
  45. substitutions: seq[string] ## Variable names in `doc.item`...
  46. sortName: string ## The string used for sorting in output
  47. info: rstast.TLineInfo ## place where symbol was defined (for messages)
  48. anchor: string ## e.g. HTML anchor
  49. name: string ## short name of the symbol, not unique
  50. ## (includes backticks ` if present)
  51. detailedName: string ## longer name like `proc search(x: int): int`
  52. ModSection = object ## Section like Procs, Types, etc.
  53. secItems: Table[string, seq[Item]]
  54. ## Map basic name -> pre-processed items.
  55. finalMarkup: string ## The items, after RST pass 2 and rendering.
  56. ModSections = array[TSymKind, ModSection]
  57. TocItem = object ## HTML TOC item
  58. content: string
  59. sortName: string
  60. TocSectionsFinal = array[TSymKind, string]
  61. ExampleGroup = ref object
  62. ## a group of runnableExamples with same rdoccmd
  63. rdoccmd: string ## from 1st arg in `runnableExamples(rdoccmd): body`
  64. docCmd: string ## from user config, e.g. --doccmd:-d:foo
  65. code: string ## contains imports; each import contains `body`
  66. index: int ## group index
  67. JsonItem = object # pre-processed item: `rst` should be finalized
  68. json: JsonNode
  69. rst: PRstNode
  70. rstField: string
  71. TDocumentor = object of rstgen.RstGenerator
  72. modDescPre: ItemPre # module description, not finalized
  73. modDescFinal: string # module description, after RST pass 2 and rendering
  74. module: PSym
  75. modDeprecationMsg: string
  76. section: ModSections # entries of ``.nim`` file (for `proc`s, etc)
  77. tocSimple: array[TSymKind, seq[TocItem]]
  78. # TOC entries for non-overloadable symbols (e.g. types, constants)...
  79. tocTable: array[TSymKind, Table[string, seq[TocItem]]]
  80. # ...otherwise (e.g. procs)
  81. toc2: TocSectionsFinal # TOC `content`, which is probably wrapped
  82. # in `doc.section.toc2`
  83. toc: TocSectionsFinal # final TOC (wrapped in `doc.section.toc`)
  84. indexValFilename: string
  85. analytics: string # Google Analytics javascript, "" if doesn't exist
  86. seenSymbols: StringTableRef # avoids duplicate symbol generation for HTML.
  87. jEntriesPre: seq[JsonItem] # pre-processed RST + JSON content
  88. jEntriesFinal: JsonNode # final JSON after RST pass 2 and rendering
  89. types: TStrTable
  90. sharedState: PRstSharedState
  91. standaloneDoc: bool # is markup (.rst/.md) document?
  92. conf*: ConfigRef
  93. cache*: IdentCache
  94. exampleCounter: int
  95. emitted: IntSet # we need to track which symbols have been emitted
  96. # already. See bug #3655
  97. thisDir*: AbsoluteDir
  98. exampleGroups: OrderedTable[string, ExampleGroup]
  99. wroteSupportFiles*: bool
  100. nimToRstFid: Table[lineinfos.FileIndex, rstast.FileIndex]
  101. ## map Nim FileIndex -> RST one, it's needed because we keep them separate
  102. PDoc* = ref TDocumentor ## Alias to type less.
  103. proc add(dest: var ItemPre, rst: PRstNode) = dest.add ItemFragment(isRst: true, rst: rst)
  104. proc add(dest: var ItemPre, str: string) = dest.add ItemFragment(isRst: false, str: str)
  105. proc addRstFileIndex(d: PDoc, fileIndex: lineinfos.FileIndex): rstast.FileIndex =
  106. let invalid = rstast.FileIndex(-1)
  107. result = d.nimToRstFid.getOrDefault(fileIndex, default = invalid)
  108. if result == invalid:
  109. let fname = toFullPath(d.conf, fileIndex)
  110. result = addFilename(d.sharedState, fname)
  111. d.nimToRstFid[fileIndex] = result
  112. proc addRstFileIndex(d: PDoc, info: lineinfos.TLineInfo): rstast.FileIndex =
  113. addRstFileIndex(d, info.fileIndex)
  114. proc cmpDecimalsIgnoreCase(a, b: string): int =
  115. ## For sorting with correct handling of cases like 'uint8' and 'uint16'.
  116. ## Also handles leading zeros well (however note that leading zeros are
  117. ## significant when lengths of numbers mismatch, e.g. 'bar08' > 'bar8' !).
  118. runnableExamples:
  119. doAssert cmpDecimalsIgnoreCase("uint8", "uint16") < 0
  120. doAssert cmpDecimalsIgnoreCase("val00032", "val16suffix") > 0
  121. doAssert cmpDecimalsIgnoreCase("val16suffix", "val16") > 0
  122. doAssert cmpDecimalsIgnoreCase("val_08_32", "val_08_8") > 0
  123. doAssert cmpDecimalsIgnoreCase("val_07_32", "val_08_8") < 0
  124. doAssert cmpDecimalsIgnoreCase("ab8", "ab08") < 0
  125. doAssert cmpDecimalsIgnoreCase("ab8de", "ab08c") < 0 # sanity check
  126. let aLen = a.len
  127. let bLen = b.len
  128. var
  129. iA = 0
  130. iB = 0
  131. while iA < aLen and iB < bLen:
  132. if isDigit(a[iA]) and isDigit(b[iB]):
  133. var
  134. limitA = iA # index after the last (least significant) digit
  135. limitB = iB
  136. while limitA < aLen and isDigit(a[limitA]): inc limitA
  137. while limitB < bLen and isDigit(b[limitB]): inc limitB
  138. var pos = max(limitA-iA, limitB-iA)
  139. while pos > 0:
  140. if limitA-pos < iA: # digit in `a` is 0 effectively
  141. result = ord('0') - ord(b[limitB-pos])
  142. elif limitB-pos < iB: # digit in `b` is 0 effectively
  143. result = ord(a[limitA-pos]) - ord('0')
  144. else:
  145. result = ord(a[limitA-pos]) - ord(b[limitB-pos])
  146. if result != 0: return
  147. dec pos
  148. result = (limitA - iA) - (limitB - iB) # consider 'bar08' > 'bar8'
  149. if result != 0: return
  150. iA = limitA
  151. iB = limitB
  152. else:
  153. result = ord(toLowerAscii(a[iA])) - ord(toLowerAscii(b[iB]))
  154. if result != 0: return
  155. inc iA
  156. inc iB
  157. result = (aLen - iA) - (bLen - iB)
  158. proc prettyString(a: object): string =
  159. # xxx pending std/prettyprint refs https://github.com/nim-lang/RFCs/issues/203#issuecomment-602534906
  160. for k, v in fieldPairs(a):
  161. result.add k & ": " & $v & "\n"
  162. proc presentationPath*(conf: ConfigRef, file: AbsoluteFile): RelativeFile =
  163. ## returns a relative file that will be appended to outDir
  164. let file2 = $file
  165. template bail() =
  166. result = relativeTo(file, conf.projectPath)
  167. proc nimbleDir(): AbsoluteDir =
  168. getNimbleFile(conf, file2).parentDir.AbsoluteDir
  169. case conf.docRoot:
  170. of docRootDefault:
  171. result = getRelativePathFromConfigPath(conf, file)
  172. let dir = nimbleDir()
  173. if not dir.isEmpty:
  174. let result2 = relativeTo(file, dir)
  175. if not result2.isEmpty and (result.isEmpty or result2.string.len < result.string.len):
  176. result = result2
  177. if result.isEmpty: bail()
  178. of "@pkg":
  179. let dir = nimbleDir()
  180. if dir.isEmpty: bail()
  181. else: result = relativeTo(file, dir)
  182. of "@path":
  183. result = getRelativePathFromConfigPath(conf, file)
  184. if result.isEmpty: bail()
  185. elif conf.docRoot.len > 0:
  186. # we're (currently) requiring `isAbsolute` to avoid confusion when passing
  187. # a relative path (would it be relative with regard to $PWD or to projectfile)
  188. conf.globalAssert conf.docRoot.isAbsolute, arg=conf.docRoot
  189. conf.globalAssert conf.docRoot.dirExists, arg=conf.docRoot
  190. # needed because `canonicalizePath` called on `file`
  191. result = file.relativeTo conf.docRoot.expandFilename.AbsoluteDir
  192. else:
  193. bail()
  194. if isAbsolute(result.string):
  195. result = file.string.splitPath()[1].RelativeFile
  196. result = result.string.replace("..", dotdotMangle).RelativeFile
  197. doAssert not result.isEmpty
  198. doAssert not isAbsolute(result.string)
  199. proc whichType(d: PDoc; n: PNode): PSym =
  200. if n.kind == nkSym:
  201. if d.types.strTableContains(n.sym):
  202. result = n.sym
  203. else:
  204. for i in 0..<n.safeLen:
  205. let x = whichType(d, n[i])
  206. if x != nil: return x
  207. proc attachToType(d: PDoc; p: PSym): PSym =
  208. let params = p.ast[paramsPos]
  209. template check(i) =
  210. result = whichType(d, params[i])
  211. if result != nil: return result
  212. # first check the first parameter, then the return type,
  213. # then the other parameter:
  214. if params.len > 1: check(1)
  215. if params.len > 0: check(0)
  216. for i in 2..<params.len: check(i)
  217. template declareClosures(currentFilename: AbsoluteFile, destFile: string) =
  218. proc compilerMsgHandler(filename: string, line, col: int,
  219. msgKind: rst.MsgKind, arg: string) {.gcsafe.} =
  220. # translate msg kind:
  221. var k: TMsgKind
  222. case msgKind
  223. of meCannotOpenFile: k = errCannotOpenFile
  224. of meExpected: k = errXExpected
  225. of meMissingClosing: k = errRstMissingClosing
  226. of meGridTableNotImplemented: k = errRstGridTableNotImplemented
  227. of meMarkdownIllformedTable: k = errRstMarkdownIllformedTable
  228. of meIllformedTable: k = errRstIllformedTable
  229. of meNewSectionExpected: k = errRstNewSectionExpected
  230. of meGeneralParseError: k = errRstGeneralParseError
  231. of meInvalidDirective: k = errRstInvalidDirectiveX
  232. of meInvalidField: k = errRstInvalidField
  233. of meFootnoteMismatch: k = errRstFootnoteMismatch
  234. of meSandboxedDirective: k = errRstSandboxedDirective
  235. of mwRedefinitionOfLabel: k = warnRstRedefinitionOfLabel
  236. of mwUnknownSubstitution: k = warnRstUnknownSubstitutionX
  237. of mwAmbiguousLink: k = warnRstAmbiguousLink
  238. of mwBrokenLink: k = warnRstBrokenLink
  239. of mwUnsupportedLanguage: k = warnRstLanguageXNotSupported
  240. of mwUnsupportedField: k = warnRstFieldXNotSupported
  241. of mwUnusedImportdoc: k = warnRstUnusedImportdoc
  242. of mwRstStyle: k = warnRstStyle
  243. {.gcsafe.}:
  244. globalError(conf, newLineInfo(conf, AbsoluteFile filename, line, col), k, arg)
  245. proc docgenFindFile(s: string): string {.gcsafe.} =
  246. result = options.findFile(conf, s).string
  247. if result.len == 0:
  248. result = getCurrentDir() / s
  249. if not fileExists(result): result = ""
  250. proc docgenFindRefFile(targetRelPath: string):
  251. tuple[targetPath: string, linkRelPath: string] {.gcsafe.} =
  252. let fromDir = splitFile(destFile).dir # dir where we reference from
  253. let basedir = os.splitFile(currentFilename.string).dir
  254. let outDirPath: RelativeFile =
  255. presentationPath(conf, AbsoluteFile(basedir / targetRelPath))
  256. # use presentationPath because `..` path can be be mangled to `_._`
  257. result.targetPath = string(conf.outDir / outDirPath)
  258. if not fileExists(result.targetPath):
  259. # this can happen if targetRelPath goes to parent directory `OUTDIR/..`.
  260. # Trying it, this may cause ambiguities, but allows us to insert
  261. # "packages" into each other, which is actually used in Nim repo itself.
  262. let destPath = fromDir / targetRelPath
  263. if destPath != result.targetPath and fileExists(destPath):
  264. result.targetPath = destPath
  265. result.linkRelPath = relativePath(result.targetPath.splitFile.dir,
  266. fromDir).replace('\\', '/')
  267. proc parseRst(text: string,
  268. line, column: int,
  269. conf: ConfigRef, sharedState: PRstSharedState): PRstNode =
  270. result = rstParsePass1(text, line, column, sharedState)
  271. proc getOutFile2(conf: ConfigRef; filename: RelativeFile,
  272. ext: string, guessTarget: bool): AbsoluteFile =
  273. if optWholeProject in conf.globalOptions or guessTarget:
  274. let d = conf.outDir
  275. createDir(d)
  276. result = d / changeFileExt(filename, ext)
  277. elif not conf.outFile.isEmpty:
  278. result = absOutFile(conf)
  279. else:
  280. result = getOutFile(conf, filename, ext)
  281. proc isLatexCmd(conf: ConfigRef): bool =
  282. conf.cmd in {cmdRst2tex, cmdMd2tex, cmdDoc2tex}
  283. proc newDocumentor*(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef,
  284. outExt: string = HtmlExt, module: PSym = nil,
  285. standaloneDoc = false, preferMarkdown = true,
  286. hasToc = true): PDoc =
  287. let destFile = getOutFile2(conf, presentationPath(conf, filename), outExt, false).string
  288. declareClosures(currentFilename = filename, destFile = destFile)
  289. new(result)
  290. result.module = module
  291. result.conf = conf
  292. result.cache = cache
  293. result.outDir = conf.outDir.string
  294. result.standaloneDoc = standaloneDoc
  295. var options= {roSupportRawDirective, roSupportMarkdown, roSandboxDisabled}
  296. if preferMarkdown:
  297. options.incl roPreferMarkdown
  298. if not standaloneDoc: options.incl roNimFile
  299. # (options can be changed dynamically in `setDoctype` by `{.doctype.}`)
  300. result.hasToc = hasToc
  301. result.sharedState = newRstSharedState(
  302. options, filename.string,
  303. docgenFindFile, docgenFindRefFile, compilerMsgHandler, hasToc)
  304. initRstGenerator(result[], (if conf.isLatexCmd: outLatex else: outHtml),
  305. conf.configVars, filename.string,
  306. docgenFindFile, compilerMsgHandler)
  307. if conf.configVars.hasKey("doc.googleAnalytics") and
  308. conf.configVars.hasKey("doc.plausibleAnalytics"):
  309. doAssert false, "Either use googleAnalytics or plausibleAnalytics"
  310. if conf.configVars.hasKey("doc.googleAnalytics"):
  311. result.analytics = """
  312. <script>
  313. (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  314. (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  315. m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  316. })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  317. ga('create', '$1', 'auto');
  318. ga('send', 'pageview');
  319. </script>
  320. """ % [conf.configVars.getOrDefault"doc.googleAnalytics"]
  321. elif conf.configVars.hasKey("doc.plausibleAnalytics"):
  322. result.analytics = """
  323. <script defer data-domain="$1" src="https://plausible.io/js/plausible.js"></script>
  324. """ % [conf.configVars.getOrDefault"doc.plausibleAnalytics"]
  325. else:
  326. result.analytics = ""
  327. result.seenSymbols = newStringTable(modeCaseInsensitive)
  328. result.id = 100
  329. result.jEntriesFinal = newJArray()
  330. initStrTable result.types
  331. result.onTestSnippet =
  332. proc (gen: var RstGenerator; filename, cmd: string; status: int; content: string) {.gcsafe.} =
  333. if conf.docCmd == docCmdSkip: return
  334. inc(gen.id)
  335. var d = (ptr TDocumentor)(addr gen)
  336. var outp: AbsoluteFile
  337. if filename.len == 0:
  338. let nameOnly = splitFile(d.filename).name
  339. # "snippets" needed, refs bug #17183
  340. outp = getNimcacheDir(conf) / "snippets".RelativeDir / RelativeDir(nameOnly) /
  341. RelativeFile(nameOnly & "_snippet_" & $d.id & ".nim")
  342. elif isAbsolute(filename):
  343. outp = AbsoluteFile(filename)
  344. else:
  345. # Nim's convention: every path is relative to the file it was written in:
  346. let nameOnly = splitFile(d.filename).name
  347. outp = AbsoluteDir(nameOnly) / RelativeFile(filename)
  348. # Make sure the destination directory exists
  349. createDir(outp.splitFile.dir)
  350. # Include the current file if we're parsing a nim file
  351. let importStmt = if d.standaloneDoc: "" else: "import \"$1\"\n" % [d.filename.replace("\\", "/")]
  352. writeFile(outp, importStmt & content)
  353. proc interpSnippetCmd(cmd: string): string =
  354. # backward compatibility hacks; interpolation commands should explicitly use `$`
  355. if cmd.startsWith "nim ": result = "$nim " & cmd[4..^1]
  356. else: result = cmd
  357. # factor with D20210224T221756
  358. result = result.replace("$1", "$options") % [
  359. "nim", os.getAppFilename().quoteShell,
  360. "libpath", quoteShell(d.conf.libpath),
  361. "docCmd", d.conf.docCmd,
  362. "backend", $d.conf.backend,
  363. "options", outp.quoteShell,
  364. # xxx `quoteShell` seems buggy if user passes options = "-d:foo somefile.nim"
  365. ]
  366. let cmd = cmd.interpSnippetCmd
  367. rawMessage(conf, hintExecuting, cmd)
  368. let (output, gotten) = execCmdEx(cmd)
  369. if gotten != status:
  370. rawMessage(conf, errGenerated, "snippet failed: cmd: '$1' status: $2 expected: $3 output: $4" % [cmd, $gotten, $status, output])
  371. result.emitted = initIntSet()
  372. result.destFile = destFile
  373. result.thisDir = result.destFile.AbsoluteFile.splitFile.dir
  374. template dispA(conf: ConfigRef; dest: var string, xml, tex: string,
  375. args: openArray[string]) =
  376. if not conf.isLatexCmd: dest.addf(xml, args)
  377. else: dest.addf(tex, args)
  378. proc getVarIdx(varnames: openArray[string], id: string): int =
  379. for i in 0..high(varnames):
  380. if cmpIgnoreStyle(varnames[i], id) == 0:
  381. return i
  382. result = -1
  383. proc genComment(d: PDoc, n: PNode): PRstNode =
  384. if n.comment.len > 0:
  385. d.sharedState.currFileIdx = addRstFileIndex(d, n.info)
  386. result = parseRst(n.comment,
  387. toLinenumber(n.info),
  388. toColumn(n.info) + DocColOffset,
  389. d.conf, d.sharedState)
  390. proc genRecCommentAux(d: PDoc, n: PNode): PRstNode =
  391. if n == nil: return nil
  392. result = genComment(d, n)
  393. if result == nil:
  394. if n.kind in {nkStmtList, nkStmtListExpr, nkTypeDef, nkConstDef,
  395. nkObjectTy, nkRefTy, nkPtrTy, nkAsgn, nkFastAsgn, nkSinkAsgn, nkHiddenStdConv}:
  396. # notin {nkEmpty..nkNilLit, nkEnumTy, nkTupleTy}:
  397. for i in 0..<n.len:
  398. result = genRecCommentAux(d, n[i])
  399. if result != nil: return
  400. else:
  401. n.comment = ""
  402. proc genRecComment(d: PDoc, n: PNode): PRstNode =
  403. if n == nil: return nil
  404. result = genComment(d, n)
  405. if result == nil:
  406. if n.kind in {nkProcDef, nkFuncDef, nkMethodDef, nkIteratorDef,
  407. nkMacroDef, nkTemplateDef, nkConverterDef}:
  408. result = genRecCommentAux(d, n[bodyPos])
  409. else:
  410. result = genRecCommentAux(d, n)
  411. proc getPlainDocstring(n: PNode): string =
  412. ## Gets the plain text docstring of a node non destructively.
  413. ##
  414. ## You need to call this before genRecComment, whose side effects are removal
  415. ## of comments from the tree. The proc will recursively scan and return all
  416. ## the concatenated ``##`` comments of the node.
  417. if n == nil: result = ""
  418. elif startsWith(n.comment, "##"):
  419. result = n.comment
  420. else:
  421. for i in 0..<n.safeLen:
  422. result = getPlainDocstring(n[i])
  423. if result.len > 0: return
  424. proc externalDep(d: PDoc; module: PSym): string =
  425. if optWholeProject in d.conf.globalOptions or d.conf.docRoot.len > 0:
  426. let full = AbsoluteFile toFullPath(d.conf, FileIndex module.position)
  427. let tmp = getOutFile2(d.conf, presentationPath(d.conf, full), HtmlExt, sfMainModule notin module.flags)
  428. result = relativeTo(tmp, d.thisDir, '/').string
  429. else:
  430. result = extractFilename toFullPath(d.conf, FileIndex module.position)
  431. proc nodeToHighlightedHtml(d: PDoc; n: PNode; result: var string;
  432. renderFlags: TRenderFlags = {};
  433. procLink: string) =
  434. var r: TSrcGen
  435. var literal = ""
  436. initTokRender(r, n, renderFlags)
  437. var kind = tkEof
  438. var tokenPos = 0
  439. var procTokenPos = 0
  440. template escLit(): untyped = esc(d.target, literal)
  441. while true:
  442. getNextTok(r, kind, literal)
  443. inc tokenPos
  444. case kind
  445. of tkEof:
  446. break
  447. of tkComment:
  448. dispA(d.conf, result, "<span class=\"Comment\">$1</span>", "\\spanComment{$1}",
  449. [escLit])
  450. of tokKeywordLow..tokKeywordHigh:
  451. if kind in {tkProc, tkMethod, tkIterator, tkMacro, tkTemplate, tkFunc, tkConverter}:
  452. procTokenPos = tokenPos
  453. dispA(d.conf, result, "<span class=\"Keyword\">$1</span>", "\\spanKeyword{$1}",
  454. [literal])
  455. of tkOpr:
  456. dispA(d.conf, result, "<span class=\"Operator\">$1</span>", "\\spanOperator{$1}",
  457. [escLit])
  458. of tkStrLit..tkTripleStrLit, tkCustomLit:
  459. dispA(d.conf, result, "<span class=\"StringLit\">$1</span>",
  460. "\\spanStringLit{$1}", [escLit])
  461. of tkCharLit:
  462. dispA(d.conf, result, "<span class=\"CharLit\">$1</span>", "\\spanCharLit{$1}",
  463. [escLit])
  464. of tkIntLit..tkUInt64Lit:
  465. dispA(d.conf, result, "<span class=\"DecNumber\">$1</span>",
  466. "\\spanDecNumber{$1}", [escLit])
  467. of tkFloatLit..tkFloat128Lit:
  468. dispA(d.conf, result, "<span class=\"FloatNumber\">$1</span>",
  469. "\\spanFloatNumber{$1}", [escLit])
  470. of tkSymbol:
  471. let s = getTokSym(r)
  472. # -2 because of the whitespace in between:
  473. if procTokenPos == tokenPos-2 and procLink != "":
  474. dispA(d.conf, result, "<a href=\"#$2\"><span class=\"Identifier\">$1</span></a>",
  475. "\\spanIdentifier{$1}", [escLit, procLink])
  476. elif s != nil and s.kind in {skType, skVar, skLet, skConst} and
  477. sfExported in s.flags and s.owner != nil and
  478. belongsToProjectPackage(d.conf, s.owner) and d.target == outHtml:
  479. let external = externalDep(d, s.owner)
  480. result.addf "<a href=\"$1#$2\"><span class=\"Identifier\">$3</span></a>",
  481. [changeFileExt(external, "html"), literal,
  482. escLit]
  483. else:
  484. dispA(d.conf, result, "<span class=\"Identifier\">$1</span>",
  485. "\\spanIdentifier{$1}", [escLit])
  486. of tkSpaces, tkInvalid:
  487. result.add(literal)
  488. of tkHideableStart:
  489. template fun(s) = dispA(d.conf, result, s, "\\spanOther{$1}", [escLit])
  490. if renderRunnableExamples in renderFlags: fun "$1"
  491. else:
  492. # 1st span is required for the JS to work properly
  493. fun """
  494. <span>
  495. <span class="Other pragmadots">...</span>
  496. </span>
  497. <span class="pragmawrap">""".replace("\n", "") # Must remove newlines because wrapped in a <pre>
  498. of tkHideableEnd:
  499. template fun(s) = dispA(d.conf, result, s, "\\spanOther{$1}", [escLit])
  500. if renderRunnableExamples in renderFlags: fun "$1"
  501. else: fun "</span>"
  502. of tkCurlyDotLe: dispA(d.conf, result, "$1", "\\spanOther{$1}", [escLit])
  503. of tkCurlyDotRi: dispA(d.conf, result, "$1", "\\spanOther{$1}", [escLit])
  504. of tkParLe, tkParRi, tkBracketLe, tkBracketRi, tkCurlyLe, tkCurlyRi,
  505. tkBracketDotLe, tkBracketDotRi, tkParDotLe,
  506. tkParDotRi, tkComma, tkSemiColon, tkColon, tkEquals, tkDot, tkDotDot,
  507. tkAccent, tkColonColon,
  508. tkGStrLit, tkGTripleStrLit, tkInfixOpr, tkPrefixOpr, tkPostfixOpr,
  509. tkBracketLeColon:
  510. dispA(d.conf, result, "<span class=\"Other\">$1</span>", "\\spanOther{$1}",
  511. [escLit])
  512. proc exampleOutputDir(d: PDoc): AbsoluteDir = d.conf.getNimcacheDir / RelativeDir"runnableExamples"
  513. proc runAllExamples(d: PDoc) =
  514. # This used to be: `let backend = if isDefined(d.conf, "js"): "js"` (etc), however
  515. # using `-d:js` (etc) cannot work properly, e.g. would fail with `importjs`
  516. # since semantics are affected by `config.backend`, not by isDefined(d.conf, "js")
  517. let outputDir = d.exampleOutputDir
  518. for _, group in d.exampleGroups:
  519. if group.docCmd == docCmdSkip: continue
  520. let outp = outputDir / RelativeFile("$1_group$2_examples.nim" % [d.filename.splitFile.name, $group.index])
  521. group.code = "# autogenerated by docgen\n# source: $1\n# rdoccmd: $2\n$3" % [d.filename, group.rdoccmd, group.code]
  522. writeFile(outp, group.code)
  523. # most useful semantics is that `docCmd` comes after `rdoccmd`, so that we can (temporarily) override
  524. # via command line
  525. # D20210224T221756:here
  526. let cmd = "$nim $backend -r --lib:$libpath --warning:UnusedImport:off --path:$path --nimcache:$nimcache $rdoccmd $docCmd $file" % [
  527. "nim", quoteShell(os.getAppFilename()),
  528. "backend", $d.conf.backend,
  529. "path", quoteShell(d.conf.projectPath),
  530. "libpath", quoteShell(d.conf.libpath),
  531. "nimcache", quoteShell(outputDir),
  532. "file", quoteShell(outp),
  533. "rdoccmd", group.rdoccmd,
  534. "docCmd", group.docCmd,
  535. ]
  536. if d.conf.backend == backendJs and findNodeJs() == "":
  537. discard "ignore JS runnableExample"
  538. elif os.execShellCmd(cmd) != 0:
  539. d.conf.quitOrRaise "[runnableExamples] failed: generated file: '$1' group: '$2' cmd: $3" % [outp.string, group[].prettyString, cmd]
  540. else:
  541. # keep generated source file `outp` to allow inspection.
  542. rawMessage(d.conf, hintSuccess, ["runnableExamples: " & outp.string])
  543. # removeFile(outp.changeFileExt(ExeExt)) # it's in nimcache, no need to remove
  544. proc quoted(a: string): string = result.addQuoted(a)
  545. proc toInstantiationInfo(conf: ConfigRef, info: TLineInfo): (string, int, int) =
  546. # xxx expose in compiler/lineinfos.nim
  547. (conf.toMsgFilename(info), info.line.int, info.col.int + ColOffset)
  548. proc prepareExample(d: PDoc; n: PNode, topLevel: bool): tuple[rdoccmd: string, code: string] =
  549. ## returns `rdoccmd` and source code for this runnableExamples
  550. var rdoccmd = ""
  551. if n.len < 2 or n.len > 3: globalError(d.conf, n.info, "runnableExamples invalid")
  552. if n.len == 3:
  553. let n1 = n[1]
  554. # xxx this should be evaluated during sempass
  555. if n1.kind notin nkStrKinds: globalError(d.conf, n1.info, "string litteral expected")
  556. rdoccmd = n1.strVal
  557. let useRenderModule = false
  558. let loc = d.conf.toFileLineCol(n.info)
  559. let code = extractRunnableExamplesSource(d.conf, n)
  560. let codeIndent = extractRunnableExamplesSource(d.conf, n, indent = 2)
  561. if d.conf.errorCounter > 0:
  562. return (rdoccmd, code)
  563. let comment = "autogenerated by docgen\nloc: $1\nrdoccmd: $2" % [loc, rdoccmd]
  564. let outputDir = d.exampleOutputDir
  565. createDir(outputDir)
  566. inc d.exampleCounter
  567. let outp = outputDir / RelativeFile("$#_examples_$#.nim" % [d.filename.extractFilename.changeFileExt"", $d.exampleCounter])
  568. if useRenderModule:
  569. var docComment = newTree(nkCommentStmt)
  570. docComment.comment = comment
  571. var runnableExamples = newTree(nkStmtList,
  572. docComment,
  573. newTree(nkImportStmt, newStrNode(nkStrLit, d.filename)))
  574. runnableExamples.info = n.info
  575. for a in n.lastSon: runnableExamples.add a
  576. # buggy, refs bug #17292
  577. # still worth fixing as it can affect other code relying on `renderModule`,
  578. # so we keep this code path here for now, which could still be useful in some
  579. # other situations.
  580. renderModule(runnableExamples, outp.string, conf = d.conf)
  581. else:
  582. var code2 = code
  583. if code.len > 0 and "codeReordering" notin code:
  584. # hacky but simplest solution, until we devise a way to make `{.line.}`
  585. # work without introducing a scope
  586. code2 = """
  587. {.line: $#.}:
  588. $#
  589. """ % [$toInstantiationInfo(d.conf, n.info), codeIndent]
  590. code2 = """
  591. #[
  592. $#
  593. ]#
  594. import $#
  595. $#
  596. """ % [comment, d.filename.quoted, code2]
  597. writeFile(outp.string, code2)
  598. if rdoccmd notin d.exampleGroups:
  599. d.exampleGroups[rdoccmd] = ExampleGroup(rdoccmd: rdoccmd, docCmd: d.conf.docCmd, index: d.exampleGroups.len)
  600. d.exampleGroups[rdoccmd].code.add "import $1\n" % outp.string.quoted
  601. var codeShown: string
  602. if topLevel: # refs https://github.com/nim-lang/RFCs/issues/352
  603. let title = canonicalImport(d.conf, AbsoluteFile d.filename)
  604. codeShown = "import $#\n$#" % [title, code]
  605. else:
  606. codeShown = code
  607. result = (rdoccmd, codeShown)
  608. when false:
  609. proc extractImports(n: PNode; result: PNode) =
  610. if n.kind in {nkImportStmt, nkImportExceptStmt, nkFromStmt}:
  611. result.add copyTree(n)
  612. n.kind = nkEmpty
  613. return
  614. for i in 0..<n.safeLen: extractImports(n[i], result)
  615. let imports = newTree(nkStmtList)
  616. var savedLastSon = copyTree n.lastSon
  617. extractImports(savedLastSon, imports)
  618. for imp in imports: runnableExamples.add imp
  619. runnableExamples.add newTree(nkBlockStmt, newNode(nkEmpty), copyTree savedLastSon)
  620. type RunnableState = enum
  621. rsStart
  622. rsComment
  623. rsRunnable
  624. rsDone
  625. proc getAllRunnableExamplesImpl(d: PDoc; n: PNode, dest: var ItemPre,
  626. state: RunnableState, topLevel: bool):
  627. RunnableState =
  628. ##[
  629. Simple state machine to tell whether we render runnableExamples and doc comments.
  630. This is to ensure that we can interleave runnableExamples and doc comments freely;
  631. the logic is easy to change but currently a doc comment following another doc comment
  632. will not render, to avoid rendering in following case:
  633. proc fn* =
  634. runnableExamples: discard
  635. ## d1
  636. runnableExamples: discard
  637. ## d2
  638. ## internal explanation # <- this one should be out; it's part of rest of function body and would likey not make sense in doc comment
  639. discard # some code
  640. ]##
  641. case n.kind
  642. of nkCommentStmt:
  643. if state in {rsStart, rsRunnable}:
  644. dest.add genRecComment(d, n)
  645. return rsComment
  646. of nkCallKinds:
  647. if isRunnableExamples(n[0]) and
  648. n.len >= 2 and n.lastSon.kind == nkStmtList:
  649. if state in {rsStart, rsComment, rsRunnable}:
  650. let (rdoccmd, code) = prepareExample(d, n, topLevel)
  651. var msg = "Example:"
  652. if rdoccmd.len > 0: msg.add " cmd: " & rdoccmd
  653. var s: string
  654. dispA(d.conf, s, "\n<p><strong class=\"examples_text\">$1</strong></p>\n",
  655. "\n\n\\textbf{$1}\n", [msg])
  656. dest.add s
  657. inc d.listingCounter
  658. let id = $d.listingCounter
  659. dest.add(d.config.getOrDefault"doc.listing_start" % [id, "langNim", ""])
  660. var dest2 = ""
  661. renderNimCode(dest2, code, d.target)
  662. dest.add dest2
  663. dest.add(d.config.getOrDefault"doc.listing_end" % id)
  664. return rsRunnable
  665. else:
  666. localError(d.conf, n.info, errUser, "runnableExamples must appear before the first non-comment statement")
  667. else: discard
  668. return rsDone
  669. # change this to `rsStart` if you want to keep generating doc comments
  670. # and runnableExamples that occur after some code in routine
  671. proc getRoutineBody(n: PNode): PNode =
  672. ##[
  673. nim transforms these quite differently:
  674. proc someType*(): int =
  675. ## foo
  676. result = 3
  677. =>
  678. result =
  679. ## foo
  680. 3;
  681. proc someType*(): int =
  682. ## foo
  683. 3
  684. =>
  685. ## foo
  686. result = 3;
  687. so we normalize the results to get to the statement list containing the
  688. (0 or more) doc comments and runnableExamples.
  689. ]##
  690. result = n[bodyPos]
  691. # This won't be transformed: result.id = 10. Namely result[0].kind != nkSym.
  692. if result.kind == nkAsgn and result[0].kind == nkSym and
  693. n.len > bodyPos+1 and n[bodyPos+1].kind == nkSym:
  694. doAssert result.len == 2
  695. result = result[1]
  696. proc getAllRunnableExamples(d: PDoc, n: PNode, dest: var ItemPre) =
  697. var n = n
  698. var state = rsStart
  699. template fn(n2, topLevel) =
  700. state = getAllRunnableExamplesImpl(d, n2, dest, state, topLevel)
  701. dest.add genComment(d, n)
  702. case n.kind
  703. of routineDefs:
  704. n = n.getRoutineBody
  705. case n.kind
  706. of nkCommentStmt, nkCallKinds: fn(n, topLevel = false)
  707. else:
  708. for i in 0..<n.safeLen:
  709. fn(n[i], topLevel = false)
  710. if state == rsDone: discard # check all sons
  711. else: fn(n, topLevel = true)
  712. proc isVisible(d: PDoc; n: PNode): bool =
  713. result = false
  714. if n.kind == nkPostfix:
  715. if n.len == 2 and n[0].kind == nkIdent:
  716. var v = n[0].ident
  717. result = v.id == ord(wStar) or v.id == ord(wMinus)
  718. elif n.kind == nkSym:
  719. # we cannot generate code for forwarded symbols here as we have no
  720. # exception tracking information here. Instead we copy over the comment
  721. # from the proc header.
  722. if optDocInternal in d.conf.globalOptions:
  723. result = {sfFromGeneric, sfForward}*n.sym.flags == {}
  724. else:
  725. result = {sfExported, sfFromGeneric, sfForward}*n.sym.flags == {sfExported}
  726. if result and containsOrIncl(d.emitted, n.sym.id):
  727. result = false
  728. elif n.kind == nkPragmaExpr:
  729. result = isVisible(d, n[0])
  730. proc getName(n: PNode): string =
  731. case n.kind
  732. of nkPostfix: result = getName(n[1])
  733. of nkPragmaExpr: result = getName(n[0])
  734. of nkSym: result = n.sym.renderDefinitionName
  735. of nkIdent: result = n.ident.s
  736. of nkAccQuoted:
  737. result = "`"
  738. for i in 0..<n.len: result.add(getName(n[i]))
  739. result = "`"
  740. of nkOpenSymChoice, nkClosedSymChoice:
  741. result = getName(n[0])
  742. else:
  743. result = ""
  744. proc getNameEsc(d: PDoc, n: PNode): string =
  745. esc(d.target, getName(n))
  746. proc getNameIdent(cache: IdentCache; n: PNode): PIdent =
  747. case n.kind
  748. of nkPostfix: result = getNameIdent(cache, n[1])
  749. of nkPragmaExpr: result = getNameIdent(cache, n[0])
  750. of nkSym: result = n.sym.name
  751. of nkIdent: result = n.ident
  752. of nkAccQuoted:
  753. var r = ""
  754. for i in 0..<n.len: r.add(getNameIdent(cache, n[i]).s)
  755. result = getIdent(cache, r)
  756. of nkOpenSymChoice, nkClosedSymChoice:
  757. result = getNameIdent(cache, n[0])
  758. else:
  759. result = nil
  760. proc getRstName(n: PNode): PRstNode =
  761. case n.kind
  762. of nkPostfix: result = getRstName(n[1])
  763. of nkPragmaExpr: result = getRstName(n[0])
  764. of nkSym: result = newRstLeaf(n.sym.renderDefinitionName)
  765. of nkIdent: result = newRstLeaf(n.ident.s)
  766. of nkAccQuoted:
  767. result = getRstName(n[0])
  768. for i in 1..<n.len: result.text.add(getRstName(n[i]).text)
  769. of nkOpenSymChoice, nkClosedSymChoice:
  770. result = getRstName(n[0])
  771. else:
  772. result = nil
  773. proc newUniquePlainSymbol(d: PDoc, original: string): string =
  774. ## Returns a new unique plain symbol made up from the original.
  775. ##
  776. ## When a collision is found in the seenSymbols table, new numerical variants
  777. ## with underscore + number will be generated.
  778. if not d.seenSymbols.hasKey(original):
  779. result = original
  780. d.seenSymbols[original] = ""
  781. return
  782. # Iterate over possible numeric variants of the original name.
  783. var count = 2
  784. while true:
  785. result = original & "_" & $count
  786. if not d.seenSymbols.hasKey(result):
  787. d.seenSymbols[result] = ""
  788. break
  789. count += 1
  790. proc complexName(k: TSymKind, n: PNode, baseName: string): string =
  791. ## Builds a complex unique href name for the node.
  792. ##
  793. ## Pass as ``baseName`` the plain symbol obtained from the nodeName. The
  794. ## format of the returned symbol will be ``baseName(.callable type)?,(param
  795. ## type)?(,param type)*``. The callable type part will be added only if the
  796. ## node is not a proc, as those are the common ones. The suffix will be a dot
  797. ## and a single letter representing the type of the callable. The parameter
  798. ## types will be added with a preceding dash. Return types won't be added.
  799. ##
  800. ## If you modify the output of this proc, please update the anchor generation
  801. ## section of ``doc/docgen.rst``.
  802. result = baseName
  803. case k
  804. of skProc, skFunc: discard
  805. of skMacro: result.add(".m")
  806. of skMethod: result.add(".e")
  807. of skIterator: result.add(".i")
  808. of skTemplate: result.add(".t")
  809. of skConverter: result.add(".c")
  810. else: discard
  811. if n.safeLen > paramsPos and n[paramsPos].kind == nkFormalParams:
  812. let params = renderParamTypes(n[paramsPos])
  813. if params.len > 0:
  814. result.add(defaultParamSeparator)
  815. result.add(params)
  816. proc docstringSummary(rstText: string): string =
  817. ## Returns just the first line or a brief chunk of text from a rst string.
  818. ##
  819. ## Most docstrings will contain a one liner summary, so stripping at the
  820. ## first newline is usually fine. If after that the content is still too big,
  821. ## it is stripped at the first comma, colon or dot, usual English sentence
  822. ## separators.
  823. ##
  824. ## No guarantees are made on the size of the output, but it should be small.
  825. ## Also, we hope to not break the rst, but maybe we do. If there is any
  826. ## trimming done, an ellipsis unicode char is added.
  827. const maxDocstringChars = 100
  828. assert(rstText.len < 2 or (rstText[0] == '#' and rstText[1] == '#'))
  829. result = rstText.substr(2).strip
  830. var pos = result.find('\L')
  831. if pos > 0:
  832. result.setLen(pos - 1)
  833. result.add("…")
  834. if pos < maxDocstringChars:
  835. return
  836. # Try to keep trimming at other natural boundaries.
  837. pos = result.find({'.', ',', ':'})
  838. let last = result.len - 1
  839. if pos > 0 and pos < last:
  840. result.setLen(pos - 1)
  841. result.add("…")
  842. proc genDeprecationMsg(d: PDoc, n: PNode): string =
  843. ## Given a nkPragma wDeprecated node output a well-formatted section
  844. if n == nil: return
  845. case n.safeLen:
  846. of 0: # Deprecated w/o any message
  847. result = getConfigVar(d.conf, "doc.deprecationmsg") % [
  848. "label" , "Deprecated", "message", ""]
  849. of 2: # Deprecated w/ a message
  850. if n[1].kind in {nkStrLit..nkTripleStrLit}:
  851. result = getConfigVar(d.conf, "doc.deprecationmsg") % [
  852. "label", "Deprecated:", "message", xmltree.escape(n[1].strVal)]
  853. else:
  854. doAssert false
  855. type DocFlags = enum
  856. kDefault
  857. kForceExport
  858. proc genSeeSrc(d: PDoc, path: string, line: int): string =
  859. let docItemSeeSrc = getConfigVar(d.conf, "doc.item.seesrc")
  860. if docItemSeeSrc.len > 0:
  861. let path = relativeTo(AbsoluteFile path, AbsoluteDir getCurrentDir(), '/')
  862. when false:
  863. let cwd = canonicalizePath(d.conf, getCurrentDir())
  864. var path = path
  865. if path.startsWith(cwd):
  866. path = path[cwd.len+1..^1].replace('\\', '/')
  867. let gitUrl = getConfigVar(d.conf, "git.url")
  868. if gitUrl.len > 0:
  869. let defaultBranch =
  870. if NimPatch mod 2 == 1: "devel"
  871. else: "version-$1-$2" % [$NimMajor, $NimMinor]
  872. let commit = getConfigVar(d.conf, "git.commit", defaultBranch)
  873. let develBranch = getConfigVar(d.conf, "git.devel", "devel")
  874. dispA(d.conf, result, "$1", "", [docItemSeeSrc % [
  875. "path", path.string, "line", $line, "url", gitUrl,
  876. "commit", commit, "devel", develBranch]])
  877. proc symbolPriority(k: TSymKind): int =
  878. result = case k
  879. of skMacro: -3
  880. of skTemplate: -2
  881. of skIterator: -1
  882. else: 0 # including skProc which have higher priority
  883. # documentation itself has even higher priority 1
  884. proc getTypeKind(n: PNode): string =
  885. case n[2].kind
  886. of nkEnumTy: "enum"
  887. of nkObjectTy: "object"
  888. of nkTupleTy: "tuple"
  889. else: ""
  890. proc toLangSymbol(k: TSymKind, n: PNode, baseName: string): LangSymbol =
  891. ## Converts symbol info (names/types/parameters) in `n` into format
  892. ## `LangSymbol` convenient for ``rst.nim``/``dochelpers.nim``.
  893. result.name = baseName.nimIdentNormalize
  894. result.symKind = k.toHumanStr
  895. if k in routineKinds:
  896. var
  897. paramTypes: seq[string]
  898. renderParamTypes(paramTypes, n[paramsPos], toNormalize=true)
  899. let paramNames = renderParamNames(n[paramsPos], toNormalize=true)
  900. # In some rare cases (system.typeof) parameter type is not set for default:
  901. doAssert paramTypes.len <= paramNames.len
  902. for i in 0 ..< paramNames.len:
  903. if i < paramTypes.len:
  904. result.parameters.add (paramNames[i], paramTypes[i])
  905. else:
  906. result.parameters.add (paramNames[i], "")
  907. result.parametersProvided = true
  908. result.outType = renderOutType(n[paramsPos], toNormalize=true)
  909. if k in {skProc, skFunc, skType, skIterator}:
  910. # Obtain `result.generics`
  911. # Use `n[miscPos]` since n[genericParamsPos] does not contain constraints
  912. var genNode: PNode = nil
  913. if k == skType:
  914. genNode = n[1] # FIXME: what is index 1?
  915. else:
  916. if n[miscPos].kind != nkEmpty:
  917. genNode = n[miscPos][1] # FIXME: what is index 1?
  918. if genNode != nil:
  919. var literal = ""
  920. var r: TSrcGen
  921. initTokRender(r, genNode, {renderNoBody, renderNoComments,
  922. renderNoPragmas, renderNoProcDefs, renderExpandUsing})
  923. var kind = tkEof
  924. while true:
  925. getNextTok(r, kind, literal)
  926. if kind == tkEof:
  927. break
  928. if kind != tkSpaces:
  929. result.generics.add(literal.nimIdentNormalize)
  930. if k == skType: result.symTypeKind = getTypeKind(n)
  931. proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags, nonExports: bool = false) =
  932. if (docFlags != kForceExport) and not isVisible(d, nameNode): return
  933. let
  934. name = getName(nameNode)
  935. nameEsc = esc(d.target, name)
  936. var plainDocstring = getPlainDocstring(n) # call here before genRecComment!
  937. var result = ""
  938. var literal, plainName = ""
  939. var kind = tkEof
  940. var comm: ItemPre
  941. if n.kind in routineDefs:
  942. getAllRunnableExamples(d, n, comm)
  943. else:
  944. comm.add genRecComment(d, n)
  945. var r: TSrcGen
  946. # Obtain the plain rendered string for hyperlink titles.
  947. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments,
  948. renderNoPragmas, renderNoProcDefs, renderExpandUsing})
  949. while true:
  950. getNextTok(r, kind, literal)
  951. if kind == tkEof:
  952. break
  953. plainName.add(literal)
  954. var pragmaNode = getDeclPragma(n)
  955. if pragmaNode != nil: pragmaNode = findPragma(pragmaNode, wDeprecated)
  956. inc(d.id)
  957. let
  958. plainNameEsc = esc(d.target, plainName.strip)
  959. typeDescr =
  960. if k == skType and getTypeKind(n) != "": getTypeKind(n)
  961. else: k.toHumanStr
  962. detailedName = typeDescr & " " & (
  963. if k in routineKinds: plainName else: name)
  964. uniqueName = if k in routineKinds: plainNameEsc else: nameEsc
  965. sortName = if k in routineKinds: plainName.strip else: name
  966. cleanPlainSymbol = renderPlainSymbolName(nameNode)
  967. complexSymbol = complexName(k, n, cleanPlainSymbol)
  968. plainSymbolEnc = encodeUrl(cleanPlainSymbol, usePlus = false)
  969. symbolOrId = d.newUniquePlainSymbol(complexSymbol)
  970. symbolOrIdEnc = encodeUrl(symbolOrId, usePlus = false)
  971. deprecationMsg = genDeprecationMsg(d, pragmaNode)
  972. rstLangSymbol = toLangSymbol(k, n, cleanPlainSymbol)
  973. # we generate anchors automatically for subsequent use in doc comments
  974. let lineinfo = rstast.TLineInfo(
  975. line: nameNode.info.line, col: nameNode.info.col,
  976. fileIndex: addRstFileIndex(d, nameNode.info))
  977. addAnchorNim(d.sharedState, external = false, refn = symbolOrId,
  978. tooltip = detailedName, langSym = rstLangSymbol,
  979. priority = symbolPriority(k), info = lineinfo,
  980. module = addRstFileIndex(d, FileIndex d.module.position))
  981. let renderFlags =
  982. if nonExports: {renderNoBody, renderNoComments, renderDocComments, renderSyms,
  983. renderExpandUsing, renderNonExportedFields}
  984. else: {renderNoBody, renderNoComments, renderDocComments, renderSyms, renderExpandUsing}
  985. nodeToHighlightedHtml(d, n, result, renderFlags, symbolOrIdEnc)
  986. let seeSrc = genSeeSrc(d, toFullPath(d.conf, n.info), n.info.line.int)
  987. d.section[k].secItems.mgetOrPut(cleanPlainSymbol, newSeq[Item]()).add Item(
  988. descRst: comm,
  989. sortName: sortName,
  990. info: lineinfo,
  991. anchor: symbolOrId,
  992. detailedName: detailedName,
  993. name: name,
  994. substitutions: @[
  995. "uniqueName", uniqueName,
  996. "header", result, "itemID", $d.id,
  997. "header_plain", plainNameEsc, "itemSym", cleanPlainSymbol,
  998. "itemSymEnc", plainSymbolEnc,
  999. "itemSymOrIDEnc", symbolOrIdEnc, "seeSrc", seeSrc,
  1000. "deprecationMsg", deprecationMsg])
  1001. let external = d.destFile.AbsoluteFile.relativeTo(d.conf.outDir, '/').changeFileExt(HtmlExt).string
  1002. var attype = ""
  1003. if k in routineKinds and nameNode.kind == nkSym:
  1004. let att = attachToType(d, nameNode.sym)
  1005. if att != nil:
  1006. attype = esc(d.target, att.name.s)
  1007. elif k == skType and nameNode.kind == nkSym and nameNode.sym.typ.kind in {tyEnum, tyBool}:
  1008. let etyp = nameNode.sym.typ
  1009. for e in etyp.n:
  1010. if e.sym.kind != skEnumField: continue
  1011. let plain = renderPlainSymbolName(e)
  1012. let symbolOrId = d.newUniquePlainSymbol(plain)
  1013. setIndexTerm(d[], ieNim, htmlFile = external, id = symbolOrId,
  1014. term = plain, linkTitle = nameNode.sym.name.s & '.' & plain,
  1015. linkDesc = xmltree.escape(getPlainDocstring(e).docstringSummary),
  1016. line = n.info.line.int)
  1017. d.tocSimple[k].add TocItem(
  1018. sortName: sortName,
  1019. content: getConfigVar(d.conf, "doc.item.toc") % [
  1020. "name", name, "header_plain", plainNameEsc,
  1021. "itemSymOrIDEnc", symbolOrIdEnc])
  1022. d.tocTable[k].mgetOrPut(cleanPlainSymbol, newSeq[TocItem]()).add TocItem(
  1023. sortName: sortName,
  1024. content: getConfigVar(d.conf, "doc.item.tocTable") % [
  1025. "name", name, "header_plain", plainNameEsc,
  1026. "itemSymOrID", symbolOrId.replace(",", ",<wbr>"),
  1027. "itemSymOrIDEnc", symbolOrIdEnc])
  1028. setIndexTerm(d[], ieNim, htmlFile = external, id = symbolOrId, term = name,
  1029. linkTitle = detailedName,
  1030. linkDesc = xmltree.escape(plainDocstring.docstringSummary),
  1031. line = n.info.line.int)
  1032. if k == skType and nameNode.kind == nkSym:
  1033. d.types.strTableAdd nameNode.sym
  1034. proc genJsonItem(d: PDoc, n, nameNode: PNode, k: TSymKind): JsonItem =
  1035. if not isVisible(d, nameNode): return
  1036. var
  1037. name = getNameEsc(d, nameNode)
  1038. comm = genRecComment(d, n)
  1039. r: TSrcGen
  1040. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments, renderExpandUsing})
  1041. result.json = %{ "name": %name, "type": %($k), "line": %n.info.line.int,
  1042. "col": %n.info.col}
  1043. if comm != nil:
  1044. result.rst = comm
  1045. result.rstField = "description"
  1046. if r.buf.len > 0:
  1047. result.json["code"] = %r.buf
  1048. if k in routineKinds:
  1049. result.json["signature"] = newJObject()
  1050. if n[paramsPos][0].kind != nkEmpty:
  1051. result.json["signature"]["return"] = %($n[paramsPos][0])
  1052. if n[paramsPos].len > 1:
  1053. result.json["signature"]["arguments"] = newJArray()
  1054. for paramIdx in 1 ..< n[paramsPos].len:
  1055. for identIdx in 0 ..< n[paramsPos][paramIdx].len - 2:
  1056. let
  1057. paramName = $n[paramsPos][paramIdx][identIdx]
  1058. paramType = $n[paramsPos][paramIdx][^2]
  1059. if n[paramsPos][paramIdx][^1].kind != nkEmpty:
  1060. let paramDefault = $n[paramsPos][paramIdx][^1]
  1061. result.json["signature"]["arguments"].add %{"name": %paramName, "type": %paramType, "default": %paramDefault}
  1062. else:
  1063. result.json["signature"]["arguments"].add %{"name": %paramName, "type": %paramType}
  1064. if n[pragmasPos].kind != nkEmpty:
  1065. result.json["signature"]["pragmas"] = newJArray()
  1066. for pragma in n[pragmasPos]:
  1067. result.json["signature"]["pragmas"].add %($pragma)
  1068. if n[genericParamsPos].kind != nkEmpty:
  1069. result.json["signature"]["genericParams"] = newJArray()
  1070. for genericParam in n[genericParamsPos]:
  1071. var param = %{"name": %($genericParam)}
  1072. if genericParam.sym.typ.sons.len > 0:
  1073. param["types"] = newJArray()
  1074. for kind in genericParam.sym.typ.sons:
  1075. param["types"].add %($kind)
  1076. result.json["signature"]["genericParams"].add param
  1077. if optGenIndex in d.conf.globalOptions:
  1078. genItem(d, n, nameNode, k, kForceExport)
  1079. proc setDoctype(d: PDoc, n: PNode) =
  1080. ## Processes `{.doctype.}` pragma changing Markdown/RST parsing options.
  1081. if n == nil:
  1082. return
  1083. if n.len != 2:
  1084. localError(d.conf, n.info, errUser,
  1085. "doctype pragma takes exactly 1 argument"
  1086. )
  1087. return
  1088. var dt = ""
  1089. case n[1].kind
  1090. of nkStrLit:
  1091. dt = toLowerAscii(n[1].strVal)
  1092. of nkIdent:
  1093. dt = toLowerAscii(n[1].ident.s)
  1094. else:
  1095. localError(d.conf, n.info, errUser,
  1096. "unknown argument type $1 provided to doctype" % [$n[1].kind]
  1097. )
  1098. return
  1099. case dt
  1100. of "markdown":
  1101. d.sharedState.options.incl roSupportMarkdown
  1102. d.sharedState.options.incl roPreferMarkdown
  1103. of "rstmarkdown":
  1104. d.sharedState.options.incl roSupportMarkdown
  1105. d.sharedState.options.excl roPreferMarkdown
  1106. of "rst":
  1107. d.sharedState.options.excl roSupportMarkdown
  1108. d.sharedState.options.excl roPreferMarkdown
  1109. else:
  1110. localError(d.conf, n.info, errUser,
  1111. (
  1112. "unknown doctype value \"$1\", should be from " &
  1113. "\"RST\", \"Markdown\", \"RstMarkdown\""
  1114. ) % [dt]
  1115. )
  1116. proc checkForFalse(n: PNode): bool =
  1117. result = n.kind == nkIdent and cmpIgnoreStyle(n.ident.s, "false") == 0
  1118. proc traceDeps(d: PDoc, it: PNode) =
  1119. const k = skModule
  1120. if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
  1121. let sep = it[0]
  1122. let dir = it[1]
  1123. let a = newNodeI(nkInfix, it.info)
  1124. a.add sep
  1125. a.add dir
  1126. a.add sep # dummy entry, replaced in the loop
  1127. for x in it[2]:
  1128. a[2] = x
  1129. traceDeps(d, a)
  1130. elif it.kind == nkSym and belongsToProjectPackage(d.conf, it.sym):
  1131. let external = externalDep(d, it.sym)
  1132. if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
  1133. dispA(d.conf, d.section[k].finalMarkup,
  1134. "<a class=\"reference external\" href=\"$2\">$1</a>",
  1135. "$1", [esc(d.target, external.prettyLink),
  1136. changeFileExt(external, "html")])
  1137. proc exportSym(d: PDoc; s: PSym) =
  1138. const k = exportSection
  1139. if s.kind == skModule and belongsToProjectPackage(d.conf, s):
  1140. let external = externalDep(d, s)
  1141. if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
  1142. dispA(d.conf, d.section[k].finalMarkup,
  1143. "<a class=\"reference external\" href=\"$2\">$1</a>",
  1144. "$1", [esc(d.target, external.prettyLink),
  1145. changeFileExt(external, "html")])
  1146. elif s.kind != skModule and s.owner != nil:
  1147. let module = originatingModule(s)
  1148. if belongsToProjectPackage(d.conf, module):
  1149. let
  1150. complexSymbol = complexName(s.kind, s.ast, s.name.s)
  1151. symbolOrId = d.newUniquePlainSymbol(complexSymbol)
  1152. external = externalDep(d, module)
  1153. if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
  1154. # XXX proper anchor generation here
  1155. dispA(d.conf, d.section[k].finalMarkup,
  1156. "<a href=\"$2#$3\"><span class=\"Identifier\">$1</span></a>",
  1157. "$1", [esc(d.target, s.name.s),
  1158. changeFileExt(external, "html"),
  1159. symbolOrId])
  1160. proc documentNewEffect(cache: IdentCache; n: PNode): PNode =
  1161. let s = n[namePos].sym
  1162. if tfReturnsNew in s.typ.flags:
  1163. result = newIdentNode(getIdent(cache, "new"), n.info)
  1164. proc documentEffect(cache: IdentCache; n, x: PNode, effectType: TSpecialWord, idx: int): PNode =
  1165. let spec = effectSpec(x, effectType)
  1166. if isNil(spec):
  1167. let s = n[namePos].sym
  1168. let actual = s.typ.n[0]
  1169. if actual.len != effectListLen: return
  1170. let real = actual[idx]
  1171. if real == nil: return
  1172. let realLen = real.len
  1173. # warning: hack ahead:
  1174. var effects = newNodeI(nkBracket, n.info, realLen)
  1175. for i in 0..<realLen:
  1176. var t = typeToString(real[i].typ)
  1177. if t.startsWith("ref "): t = substr(t, 4)
  1178. effects[i] = newIdentNode(getIdent(cache, t), n.info)
  1179. # set the type so that the following analysis doesn't screw up:
  1180. effects[i].typ = real[i].typ
  1181. result = newTreeI(nkExprColonExpr, n.info,
  1182. newIdentNode(getIdent(cache, $effectType), n.info), effects)
  1183. proc documentWriteEffect(cache: IdentCache; n: PNode; flag: TSymFlag; pragmaName: string): PNode =
  1184. let s = n[namePos].sym
  1185. let params = s.typ.n
  1186. var effects = newNodeI(nkBracket, n.info)
  1187. for i in 1..<params.len:
  1188. if params[i].kind == nkSym and flag in params[i].sym.flags:
  1189. effects.add params[i]
  1190. if effects.len > 0:
  1191. result = newTreeI(nkExprColonExpr, n.info,
  1192. newIdentNode(getIdent(cache, pragmaName), n.info), effects)
  1193. proc documentRaises*(cache: IdentCache; n: PNode) =
  1194. if n[namePos].kind != nkSym: return
  1195. let pragmas = n[pragmasPos]
  1196. let p1 = documentEffect(cache, n, pragmas, wRaises, exceptionEffects)
  1197. let p2 = documentEffect(cache, n, pragmas, wTags, tagEffects)
  1198. let p3 = documentWriteEffect(cache, n, sfWrittenTo, "writes")
  1199. let p4 = documentNewEffect(cache, n)
  1200. let p5 = documentWriteEffect(cache, n, sfEscapes, "escapes")
  1201. let p6 = documentEffect(cache, n, pragmas, wForbids, forbiddenEffects)
  1202. if p1 != nil or p2 != nil or p3 != nil or p4 != nil or p5 != nil or p6 != nil:
  1203. if pragmas.kind == nkEmpty:
  1204. n[pragmasPos] = newNodeI(nkPragma, n.info)
  1205. if p1 != nil: n[pragmasPos].add p1
  1206. if p2 != nil: n[pragmasPos].add p2
  1207. if p3 != nil: n[pragmasPos].add p3
  1208. if p4 != nil: n[pragmasPos].add p4
  1209. if p5 != nil: n[pragmasPos].add p5
  1210. if p6 != nil: n[pragmasPos].add p6
  1211. proc generateDoc*(d: PDoc, n, orig: PNode, config: ConfigRef, docFlags: DocFlags = kDefault) =
  1212. ## Goes through nim nodes recursively and collects doc comments.
  1213. ## Main function for `doc`:option: command,
  1214. ## which is implemented in ``docgen2.nim``.
  1215. template genItemAux(skind) =
  1216. genItem(d, n, n[namePos], skind, docFlags)
  1217. let showNonExports = optShowNonExportedFields in config.globalOptions
  1218. case n.kind
  1219. of nkPragma:
  1220. let pragmaNode = findPragma(n, wDeprecated)
  1221. d.modDeprecationMsg.add(genDeprecationMsg(d, pragmaNode))
  1222. let doctypeNode = findPragma(n, wDoctype)
  1223. setDoctype(d, doctypeNode)
  1224. of nkCommentStmt: d.modDescPre.add(genComment(d, n))
  1225. of nkProcDef, nkFuncDef:
  1226. when useEffectSystem: documentRaises(d.cache, n)
  1227. genItemAux(skProc)
  1228. of nkMethodDef:
  1229. when useEffectSystem: documentRaises(d.cache, n)
  1230. genItemAux(skMethod)
  1231. of nkIteratorDef:
  1232. when useEffectSystem: documentRaises(d.cache, n)
  1233. genItemAux(skIterator)
  1234. of nkMacroDef: genItemAux(skMacro)
  1235. of nkTemplateDef: genItemAux(skTemplate)
  1236. of nkConverterDef:
  1237. when useEffectSystem: documentRaises(d.cache, n)
  1238. genItemAux(skConverter)
  1239. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  1240. for i in 0..<n.len:
  1241. if n[i].kind != nkCommentStmt:
  1242. # order is always 'type var let const':
  1243. genItem(d, n[i], n[i][0],
  1244. succ(skType, ord(n.kind)-ord(nkTypeSection)), docFlags, showNonExports)
  1245. of nkStmtList:
  1246. for i in 0..<n.len: generateDoc(d, n[i], orig, config)
  1247. of nkWhenStmt:
  1248. # generate documentation for the first branch only:
  1249. if not checkForFalse(n[0][0]):
  1250. generateDoc(d, lastSon(n[0]), orig, config)
  1251. of nkImportStmt:
  1252. for it in n: traceDeps(d, it)
  1253. of nkExportStmt:
  1254. for it in n:
  1255. if it.kind == nkSym:
  1256. if d.module != nil and d.module == it.sym.owner:
  1257. generateDoc(d, it.sym.ast, orig, config, kForceExport)
  1258. elif it.sym.ast != nil:
  1259. exportSym(d, it.sym)
  1260. of nkExportExceptStmt: discard "transformed into nkExportStmt by semExportExcept"
  1261. of nkFromStmt, nkImportExceptStmt: traceDeps(d, n[0])
  1262. of nkCallKinds:
  1263. var comm: ItemPre
  1264. getAllRunnableExamples(d, n, comm)
  1265. if comm.len != 0: d.modDescPre.add(comm)
  1266. else: discard
  1267. proc overloadGroupName(s: string, k: TSymKind): string =
  1268. ## Turns a name like `f` into anchor `f-procs-all`
  1269. s & "-" & k.toHumanStr & "s-all"
  1270. proc setIndexTitle(d: PDoc, useMetaTitle: bool) =
  1271. let titleKind = if d.standaloneDoc: ieMarkupTitle else: ieNimTitle
  1272. let external = AbsoluteFile(d.destFile)
  1273. .relativeTo(d.conf.outDir, '/')
  1274. .changeFileExt(HtmlExt)
  1275. .string
  1276. var term, linkTitle: string
  1277. if useMetaTitle and d.meta[metaTitle].len != 0:
  1278. term = d.meta[metaTitleRaw]
  1279. linkTitle = d.meta[metaTitleRaw]
  1280. else:
  1281. let filename = extractFilename(d.filename)
  1282. term =
  1283. if d.standaloneDoc: filename # keep .rst/.md extension
  1284. else: changeFileExt(filename, "") # rm .nim extension
  1285. linkTitle =
  1286. if d.standaloneDoc: term # keep .rst/.md extension
  1287. else: canonicalImport(d.conf, AbsoluteFile d.filename)
  1288. if not d.standaloneDoc:
  1289. linkTitle = "module " & linkTitle
  1290. setIndexTerm(d[], titleKind, htmlFile = external, id = "",
  1291. term = term, linkTitle = linkTitle)
  1292. proc finishGenerateDoc*(d: var PDoc) =
  1293. ## Perform 2nd RST pass for resolution of links/footnotes/headings...
  1294. # copy file map `filenames` to ``rstgen.nim`` for its warnings
  1295. d.filenames = d.sharedState.filenames
  1296. # Main title/subtitle are allowed only in the first RST fragment of document
  1297. var firstRst = PRstNode(nil)
  1298. for fragment in d.modDescPre:
  1299. if fragment.isRst:
  1300. firstRst = fragment.rst
  1301. break
  1302. d.hasToc = d.hasToc or d.sharedState.hasToc
  1303. # in --index:only mode we do NOT want to load other .idx, only write ours:
  1304. let importdoc = optGenIndexOnly notin d.conf.globalOptions and
  1305. optNoImportdoc notin d.conf.globalOptions
  1306. preparePass2(d.sharedState, firstRst, importdoc)
  1307. if optGenIndexOnly in d.conf.globalOptions:
  1308. # Top-level doc.comments may contain titles and :idx: statements:
  1309. for fragment in d.modDescPre:
  1310. if fragment.isRst:
  1311. traverseForIndex(d[], fragment.rst)
  1312. setIndexTitle(d, useMetaTitle = d.standaloneDoc)
  1313. # Symbol-associated doc.comments may contain :idx: statements:
  1314. for k in TSymKind:
  1315. for _, overloadChoices in d.section[k].secItems:
  1316. for item in overloadChoices:
  1317. for fragment in item.descRst:
  1318. if fragment.isRst:
  1319. traverseForIndex(d[], fragment.rst)
  1320. # add anchors to overload groups before RST resolution
  1321. for k in TSymKind:
  1322. if k in routineKinds:
  1323. for plainName, overloadChoices in d.section[k].secItems:
  1324. if overloadChoices.len > 1:
  1325. let refn = overloadGroupName(plainName, k)
  1326. let tooltip = "$1 ($2 overloads)" % [
  1327. k.toHumanStr & " " & plainName, $overloadChoices.len]
  1328. let name = nimIdentBackticksNormalize(plainName)
  1329. # save overload group to ``.idx``
  1330. let external = d.destFile.AbsoluteFile.relativeTo(d.conf.outDir, '/').
  1331. changeFileExt(HtmlExt).string
  1332. setIndexTerm(d[], ieNimGroup, htmlFile = external, id = refn,
  1333. term = name, linkTitle = k.toHumanStr,
  1334. linkDesc = "", line = overloadChoices[0].info.line.int)
  1335. if optGenIndexOnly in d.conf.globalOptions: continue
  1336. addAnchorNim(d.sharedState, external=false, refn, tooltip,
  1337. LangSymbol(symKind: k.toHumanStr,
  1338. name: name,
  1339. isGroup: true),
  1340. priority = symbolPriority(k),
  1341. # select index `0` just to have any meaningful warning:
  1342. info = overloadChoices[0].info,
  1343. module = addRstFileIndex(d, FileIndex d.module.position))
  1344. if optGenIndexOnly in d.conf.globalOptions:
  1345. return
  1346. # Finalize fragments of ``.nim`` or ``.rst`` file
  1347. proc renderItemPre(d: PDoc, fragments: ItemPre, result: var string) =
  1348. for f in fragments:
  1349. case f.isRst:
  1350. of true:
  1351. var resolved = resolveSubs(d.sharedState, f.rst)
  1352. renderRstToOut(d[], resolved, result)
  1353. of false: result &= f.str
  1354. proc cmp(x, y: Item): int = cmpDecimalsIgnoreCase(x.sortName, y.sortName)
  1355. for k in TSymKind:
  1356. # add symbols to section for each `k`, while optionally wrapping
  1357. # overloadable items with the same basic name by ``doc.item2``
  1358. let overloadableNames = toSeq(keys(d.section[k].secItems))
  1359. for plainName in overloadableNames.sorted(cmpDecimalsIgnoreCase):
  1360. var overloadChoices = d.section[k].secItems[plainName]
  1361. overloadChoices.sort(cmp)
  1362. var nameContent = ""
  1363. for item in overloadChoices:
  1364. var itemDesc: string
  1365. renderItemPre(d, item.descRst, itemDesc)
  1366. nameContent.add(
  1367. getConfigVar(d.conf, "doc.item") % (
  1368. item.substitutions & @[
  1369. "desc", itemDesc,
  1370. "name", item.name,
  1371. "itemSymOrID", item.anchor]))
  1372. if k in routineKinds:
  1373. let plainNameEsc1 = esc(d.target, plainName.strip)
  1374. let plainNameEsc2 = esc(d.target, plainName.strip, escMode=emUrl)
  1375. d.section[k].finalMarkup.add(
  1376. getConfigVar(d.conf, "doc.item2") % (
  1377. @["header_plain", plainNameEsc1,
  1378. "overloadGroupName", overloadGroupName(plainNameEsc2, k),
  1379. "content", nameContent]))
  1380. else:
  1381. d.section[k].finalMarkup.add(nameContent)
  1382. d.section[k].secItems.clear
  1383. renderItemPre(d, d.modDescPre, d.modDescFinal)
  1384. d.modDescPre.setLen 0
  1385. # Finalize fragments of ``.json`` file
  1386. for i, entry in d.jEntriesPre:
  1387. if entry.rst != nil:
  1388. let resolved = resolveSubs(d.sharedState, entry.rst)
  1389. var str: string
  1390. renderRstToOut(d[], resolved, str)
  1391. entry.json[entry.rstField] = %str
  1392. d.jEntriesPre[i].rst = nil
  1393. d.jEntriesFinal.add entry.json # generates docs
  1394. setIndexTitle(d, useMetaTitle = d.standaloneDoc)
  1395. completePass2(d.sharedState)
  1396. proc add(d: PDoc; j: JsonItem) =
  1397. if j.json != nil or j.rst != nil: d.jEntriesPre.add j
  1398. proc generateJson*(d: PDoc, n: PNode, includeComments: bool = true) =
  1399. case n.kind
  1400. of nkPragma:
  1401. let doctypeNode = findPragma(n, wDoctype)
  1402. setDoctype(d, doctypeNode)
  1403. of nkCommentStmt:
  1404. if includeComments:
  1405. d.add JsonItem(rst: genComment(d, n), rstField: "comment",
  1406. json: %Table[string, string]())
  1407. else:
  1408. d.modDescPre.add(genComment(d, n))
  1409. of nkProcDef, nkFuncDef:
  1410. when useEffectSystem: documentRaises(d.cache, n)
  1411. d.add genJsonItem(d, n, n[namePos], skProc)
  1412. of nkMethodDef:
  1413. when useEffectSystem: documentRaises(d.cache, n)
  1414. d.add genJsonItem(d, n, n[namePos], skMethod)
  1415. of nkIteratorDef:
  1416. when useEffectSystem: documentRaises(d.cache, n)
  1417. d.add genJsonItem(d, n, n[namePos], skIterator)
  1418. of nkMacroDef:
  1419. d.add genJsonItem(d, n, n[namePos], skMacro)
  1420. of nkTemplateDef:
  1421. d.add genJsonItem(d, n, n[namePos], skTemplate)
  1422. of nkConverterDef:
  1423. when useEffectSystem: documentRaises(d.cache, n)
  1424. d.add genJsonItem(d, n, n[namePos], skConverter)
  1425. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  1426. for i in 0..<n.len:
  1427. if n[i].kind != nkCommentStmt:
  1428. # order is always 'type var let const':
  1429. d.add genJsonItem(d, n[i], n[i][0],
  1430. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  1431. of nkStmtList:
  1432. for i in 0..<n.len:
  1433. generateJson(d, n[i], includeComments)
  1434. of nkWhenStmt:
  1435. # generate documentation for the first branch only:
  1436. if not checkForFalse(n[0][0]):
  1437. generateJson(d, lastSon(n[0]), includeComments)
  1438. else: discard
  1439. proc genTagsItem(d: PDoc, n, nameNode: PNode, k: TSymKind): string =
  1440. result = getNameEsc(d, nameNode) & "\n"
  1441. proc generateTags*(d: PDoc, n: PNode, r: var string) =
  1442. case n.kind
  1443. of nkCommentStmt:
  1444. if startsWith(n.comment, "##"):
  1445. let stripped = n.comment.substr(2).strip
  1446. r.add stripped
  1447. of nkProcDef:
  1448. when useEffectSystem: documentRaises(d.cache, n)
  1449. r.add genTagsItem(d, n, n[namePos], skProc)
  1450. of nkFuncDef:
  1451. when useEffectSystem: documentRaises(d.cache, n)
  1452. r.add genTagsItem(d, n, n[namePos], skFunc)
  1453. of nkMethodDef:
  1454. when useEffectSystem: documentRaises(d.cache, n)
  1455. r.add genTagsItem(d, n, n[namePos], skMethod)
  1456. of nkIteratorDef:
  1457. when useEffectSystem: documentRaises(d.cache, n)
  1458. r.add genTagsItem(d, n, n[namePos], skIterator)
  1459. of nkMacroDef:
  1460. r.add genTagsItem(d, n, n[namePos], skMacro)
  1461. of nkTemplateDef:
  1462. r.add genTagsItem(d, n, n[namePos], skTemplate)
  1463. of nkConverterDef:
  1464. when useEffectSystem: documentRaises(d.cache, n)
  1465. r.add genTagsItem(d, n, n[namePos], skConverter)
  1466. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  1467. for i in 0..<n.len:
  1468. if n[i].kind != nkCommentStmt:
  1469. # order is always 'type var let const':
  1470. r.add genTagsItem(d, n[i], n[i][0],
  1471. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  1472. of nkStmtList:
  1473. for i in 0..<n.len:
  1474. generateTags(d, n[i], r)
  1475. of nkWhenStmt:
  1476. # generate documentation for the first branch only:
  1477. if not checkForFalse(n[0][0]):
  1478. generateTags(d, lastSon(n[0]), r)
  1479. else: discard
  1480. proc genSection(d: PDoc, kind: TSymKind, groupedToc = false) =
  1481. const sectionNames: array[skModule..skField, string] = [
  1482. "Imports", "Types", "Vars", "Lets", "Consts", "Vars", "Procs", "Funcs",
  1483. "Methods", "Iterators", "Converters", "Macros", "Templates", "Exports"
  1484. ]
  1485. if d.section[kind].finalMarkup == "": return
  1486. var title = sectionNames[kind]
  1487. d.section[kind].finalMarkup = getConfigVar(d.conf, "doc.section") % [
  1488. "sectionid", $ord(kind), "sectionTitle", title,
  1489. "sectionTitleID", $(ord(kind) + 50), "content", d.section[kind].finalMarkup]
  1490. proc cmp(x, y: TocItem): int = cmpDecimalsIgnoreCase(x.sortName, y.sortName)
  1491. if groupedToc:
  1492. let overloadableNames = toSeq(keys(d.tocTable[kind]))
  1493. for plainName in overloadableNames.sorted(cmpDecimalsIgnoreCase):
  1494. var overloadChoices = d.tocTable[kind][plainName]
  1495. overloadChoices.sort(cmp)
  1496. var content: string
  1497. for item in overloadChoices:
  1498. content.add item.content
  1499. d.toc2[kind].add getConfigVar(d.conf, "doc.section.toc2") % [
  1500. "sectionid", $ord(kind), "sectionTitle", title,
  1501. "sectionTitleID", $(ord(kind) + 50),
  1502. "content", content, "plainName", plainName]
  1503. else:
  1504. for item in d.tocSimple[kind].sorted(cmp):
  1505. d.toc2[kind].add item.content
  1506. let sectionValues = @[
  1507. "sectionID", $ord(kind), "sectionTitleID", $(ord(kind) + 50),
  1508. "sectionTitle", title
  1509. ]
  1510. # Check if the toc has any children
  1511. if d.toc2[kind] != "":
  1512. # Use the dropdown version instead and store the children in the dropdown
  1513. d.toc[kind] = getConfigVar(d.conf, "doc.section.toc") % (sectionValues & @[
  1514. "content", d.toc2[kind]
  1515. ])
  1516. else:
  1517. # Just have the link
  1518. d.toc[kind] = getConfigVar(d.conf, "doc.section.toc_item") % sectionValues
  1519. proc relLink(outDir: AbsoluteDir, destFile: AbsoluteFile, linkto: RelativeFile): string =
  1520. $relativeTo(outDir / linkto, destFile.splitFile().dir, '/')
  1521. proc genOutFile(d: PDoc, groupedToc = false): string =
  1522. var
  1523. code, content: string
  1524. title = ""
  1525. var j = 0
  1526. var toc = ""
  1527. renderTocEntries(d[], j, 1, toc)
  1528. for i in TSymKind:
  1529. var shouldSort = i in routineKinds and groupedToc
  1530. genSection(d, i, shouldSort)
  1531. toc.add(d.toc[i])
  1532. if toc != "" or d.target == outLatex:
  1533. # for Latex $doc.toc will automatically generate TOC if `d.hasToc` is set
  1534. toc = getConfigVar(d.conf, "doc.toc") % ["content", toc]
  1535. for i in TSymKind: code.add(d.section[i].finalMarkup)
  1536. # Extract the title. Non API modules generate an entry in the index table.
  1537. if d.meta[metaTitle].len != 0:
  1538. title = d.meta[metaTitle]
  1539. else:
  1540. title = canonicalImport(d.conf, AbsoluteFile d.filename)
  1541. title = esc(d.target, title)
  1542. var subtitle = ""
  1543. if d.meta[metaSubtitle] != "":
  1544. dispA(d.conf, subtitle, "<h2 class=\"subtitle\">$1</h2>",
  1545. "\\\\\\vspace{0.5em}\\large $1", [esc(d.target, d.meta[metaSubtitle])])
  1546. var groupsection = getConfigVar(d.conf, "doc.body_toc_groupsection")
  1547. let bodyname = if d.hasToc and not d.standaloneDoc and not d.conf.isLatexCmd:
  1548. groupsection.setLen 0
  1549. "doc.body_toc_group"
  1550. elif d.hasToc: "doc.body_toc"
  1551. else: "doc.body_no_toc"
  1552. let seeSrc = genSeeSrc(d, d.filename, 1)
  1553. content = getConfigVar(d.conf, bodyname) % [
  1554. "title", title, "subtitle", subtitle,
  1555. "tableofcontents", toc, "moduledesc", d.modDescFinal, "date", getDateStr(),
  1556. "time", getClockStr(), "content", code,
  1557. "deprecationMsg", d.modDeprecationMsg,
  1558. "theindexhref", relLink(d.conf.outDir, d.destFile.AbsoluteFile,
  1559. theindexFname.RelativeFile),
  1560. "body_toc_groupsection", groupsection, "seeSrc", seeSrc]
  1561. if optCompileOnly notin d.conf.globalOptions:
  1562. # XXX what is this hack doing here? 'optCompileOnly' means raw output!?
  1563. code = getConfigVar(d.conf, "doc.file") % [
  1564. "nimdoccss", relLink(d.conf.outDir, d.destFile.AbsoluteFile,
  1565. nimdocOutCss.RelativeFile),
  1566. "dochackjs", relLink(d.conf.outDir, d.destFile.AbsoluteFile,
  1567. docHackJsFname.RelativeFile),
  1568. "title", title, "subtitle", subtitle, "tableofcontents", toc,
  1569. "moduledesc", d.modDescFinal, "date", getDateStr(), "time", getClockStr(),
  1570. "content", content, "author", d.meta[metaAuthor],
  1571. "version", esc(d.target, d.meta[metaVersion]), "analytics", d.analytics,
  1572. "deprecationMsg", d.modDeprecationMsg]
  1573. else:
  1574. code = content
  1575. result = code
  1576. proc indexFile(d: PDoc): AbsoluteFile =
  1577. let dir = d.conf.outDir
  1578. result = dir / changeFileExt(presentationPath(d.conf,
  1579. AbsoluteFile d.filename),
  1580. IndexExt)
  1581. let (finalDir, _, _) = result.string.splitFile
  1582. createDir(finalDir)
  1583. proc generateIndex*(d: PDoc) =
  1584. if optGenIndex in d.conf.globalOptions:
  1585. let dest = indexFile(d)
  1586. writeIndexFile(d[], dest.string)
  1587. proc updateOutfile(d: PDoc, outfile: AbsoluteFile) =
  1588. if d.module == nil or sfMainModule in d.module.flags: # nil for e.g. for commandRst2Html
  1589. if d.conf.outFile.isEmpty:
  1590. d.conf.outFile = outfile.relativeTo(d.conf.outDir)
  1591. if isAbsolute(d.conf.outFile.string):
  1592. d.conf.outFile = splitPath(d.conf.outFile.string)[1].RelativeFile
  1593. proc writeOutput*(d: PDoc, useWarning = false, groupedToc = false) =
  1594. if optGenIndexOnly in d.conf.globalOptions:
  1595. d.conf.outFile = indexFile(d).relativeTo(d.conf.outDir) # just for display
  1596. return
  1597. runAllExamples(d)
  1598. var content = genOutFile(d, groupedToc)
  1599. if optStdout in d.conf.globalOptions:
  1600. write(stdout, content)
  1601. else:
  1602. template outfile: untyped = d.destFile.AbsoluteFile
  1603. #let outfile = getOutFile2(d.conf, shortenDir(d.conf, filename), outExt)
  1604. let dir = outfile.splitFile.dir
  1605. createDir(dir)
  1606. updateOutfile(d, outfile)
  1607. try:
  1608. writeFile(outfile, content)
  1609. except IOError:
  1610. rawMessage(d.conf, if useWarning: warnCannotOpenFile else: errCannotOpenFile,
  1611. outfile.string)
  1612. if not d.wroteSupportFiles: # nimdoc.css + dochack.js
  1613. let nimr = $d.conf.getPrefixDir()
  1614. case d.target
  1615. of outHtml:
  1616. copyFile(docCss.interp(nimr = nimr), $d.conf.outDir / nimdocOutCss)
  1617. of outLatex:
  1618. copyFile(docCls.interp(nimr = nimr), $d.conf.outDir / nimdocOutCls)
  1619. if optGenIndex in d.conf.globalOptions:
  1620. let docHackJs2 = getDocHacksJs(nimr, nim = getAppFilename())
  1621. copyFile(docHackJs2, $d.conf.outDir / docHackJs2.lastPathPart)
  1622. d.wroteSupportFiles = true
  1623. proc writeOutputJson*(d: PDoc, useWarning = false) =
  1624. runAllExamples(d)
  1625. var modDesc: string
  1626. for desc in d.modDescFinal:
  1627. modDesc &= desc
  1628. let content = %*{"orig": d.filename,
  1629. "nimble": getPackageName(d.conf, d.filename),
  1630. "moduleDescription": modDesc,
  1631. "entries": d.jEntriesFinal}
  1632. if optStdout in d.conf.globalOptions:
  1633. write(stdout, $content)
  1634. else:
  1635. let dir = d.destFile.splitFile.dir
  1636. createDir(dir)
  1637. var f: File
  1638. if open(f, d.destFile, fmWrite):
  1639. write(f, $content)
  1640. close(f)
  1641. updateOutfile(d, d.destFile.AbsoluteFile)
  1642. else:
  1643. localError(d.conf, newLineInfo(d.conf, AbsoluteFile d.filename, -1, -1),
  1644. warnUser, "unable to open file \"" & d.destFile &
  1645. "\" for writing")
  1646. proc handleDocOutputOptions*(conf: ConfigRef) =
  1647. if optWholeProject in conf.globalOptions:
  1648. # Backward compatibility with previous versions
  1649. # xxx this is buggy when user provides `nim doc --project -o:sub/bar.html main`,
  1650. # it'd write to `sub/bar.html/main.html`
  1651. conf.outDir = AbsoluteDir(conf.outDir / conf.outFile)
  1652. proc commandDoc*(cache: IdentCache, conf: ConfigRef) =
  1653. ## implementation of deprecated ``doc0`` command (without semantic checking)
  1654. handleDocOutputOptions conf
  1655. var ast = parseFile(conf.projectMainIdx, cache, conf)
  1656. if ast == nil: return
  1657. var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
  1658. generateDoc(d, ast, ast, conf)
  1659. finishGenerateDoc(d)
  1660. writeOutput(d)
  1661. generateIndex(d)
  1662. proc commandRstAux(cache: IdentCache, conf: ConfigRef;
  1663. filename: AbsoluteFile, outExt: string,
  1664. preferMarkdown: bool) =
  1665. var filen = addFileExt(filename, "txt")
  1666. var d = newDocumentor(filen, cache, conf, outExt, standaloneDoc = true,
  1667. preferMarkdown = preferMarkdown, hasToc = false)
  1668. let rst = parseRst(readFile(filen.string),
  1669. line=LineRstInit, column=ColRstInit,
  1670. conf, d.sharedState)
  1671. d.modDescPre = @[ItemFragment(isRst: true, rst: rst)]
  1672. finishGenerateDoc(d)
  1673. writeOutput(d)
  1674. generateIndex(d)
  1675. proc commandRst2Html*(cache: IdentCache, conf: ConfigRef,
  1676. preferMarkdown=false) =
  1677. commandRstAux(cache, conf, conf.projectFull, HtmlExt, preferMarkdown)
  1678. proc commandRst2TeX*(cache: IdentCache, conf: ConfigRef,
  1679. preferMarkdown=false) =
  1680. commandRstAux(cache, conf, conf.projectFull, TexExt, preferMarkdown)
  1681. proc commandJson*(cache: IdentCache, conf: ConfigRef) =
  1682. ## implementation of a deprecated jsondoc0 command
  1683. var ast = parseFile(conf.projectMainIdx, cache, conf)
  1684. if ast == nil: return
  1685. var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
  1686. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  1687. status: int; content: string) {.gcsafe.} =
  1688. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  1689. warnUser, "the ':test:' attribute is not supported by this backend")
  1690. generateJson(d, ast)
  1691. finishGenerateDoc(d)
  1692. let json = d.jEntriesFinal
  1693. let content = pretty(json)
  1694. if optStdout in d.conf.globalOptions:
  1695. write(stdout, content)
  1696. else:
  1697. #echo getOutFile(gProjectFull, JsonExt)
  1698. let filename = getOutFile(conf, RelativeFile conf.projectName, JsonExt)
  1699. try:
  1700. writeFile(filename, content)
  1701. except IOError:
  1702. rawMessage(conf, errCannotOpenFile, filename.string)
  1703. proc commandTags*(cache: IdentCache, conf: ConfigRef) =
  1704. var ast = parseFile(conf.projectMainIdx, cache, conf)
  1705. if ast == nil: return
  1706. var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
  1707. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  1708. status: int; content: string) {.gcsafe.} =
  1709. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  1710. warnUser, "the ':test:' attribute is not supported by this backend")
  1711. var
  1712. content = ""
  1713. generateTags(d, ast, content)
  1714. if optStdout in d.conf.globalOptions:
  1715. write(stdout, content)
  1716. else:
  1717. #echo getOutFile(gProjectFull, TagsExt)
  1718. let filename = getOutFile(conf, RelativeFile conf.projectName, TagsExt)
  1719. try:
  1720. writeFile(filename, content)
  1721. except IOError:
  1722. rawMessage(conf, errCannotOpenFile, filename.string)
  1723. proc commandBuildIndex*(conf: ConfigRef, dir: string, outFile = RelativeFile"") =
  1724. if optGenIndexOnly in conf.globalOptions:
  1725. return
  1726. var content = mergeIndexes(dir)
  1727. var outFile = outFile
  1728. if outFile.isEmpty: outFile = theindexFname.RelativeFile.changeFileExt("")
  1729. let filename = getOutFile(conf, outFile, HtmlExt)
  1730. let code = getConfigVar(conf, "doc.file") % [
  1731. "nimdoccss", relLink(conf.outDir, filename, nimdocOutCss.RelativeFile),
  1732. "dochackjs", relLink(conf.outDir, filename, docHackJsFname.RelativeFile),
  1733. "title", "Index",
  1734. "subtitle", "", "tableofcontents", "", "moduledesc", "",
  1735. "date", getDateStr(), "time", getClockStr(),
  1736. "content", content, "author", "", "version", "", "analytics", ""]
  1737. # no analytics because context is not available
  1738. try:
  1739. writeFile(filename, code)
  1740. except IOError:
  1741. rawMessage(conf, errCannotOpenFile, filename.string)
  1742. proc commandBuildIndexJson*(conf: ConfigRef, dir: string, outFile = RelativeFile"") =
  1743. var (modules, symbols, docs) = readIndexDir(dir)
  1744. let documents = toSeq(keys(Table[IndexEntry, seq[IndexEntry]](docs)))
  1745. let body = %*({"documents": documents, "modules": modules, "symbols": symbols})
  1746. var outFile = outFile
  1747. if outFile.isEmpty: outFile = theindexFname.RelativeFile.changeFileExt("")
  1748. let filename = getOutFile(conf, outFile, JsonExt)
  1749. try:
  1750. writeFile(filename, $body)
  1751. except IOError:
  1752. rawMessage(conf, errCannotOpenFile, filename.string)