docgen.nim 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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. var pathArgs = "--path:$path" % [ "path", quoteShell(d.conf.projectPath) ]
  527. for p in d.conf.searchPaths:
  528. pathArgs = "$args --path:$path" % [ "args", pathArgs, "path", quoteShell(p) ]
  529. let cmd = "$nim $backend -r --lib:$libpath --warning:UnusedImport:off $pathArgs --nimcache:$nimcache $rdoccmd $docCmd $file" % [
  530. "nim", quoteShell(os.getAppFilename()),
  531. "backend", $d.conf.backend,
  532. "pathArgs", pathArgs,
  533. "libpath", quoteShell(d.conf.libpath),
  534. "nimcache", quoteShell(outputDir),
  535. "file", quoteShell(outp),
  536. "rdoccmd", group.rdoccmd,
  537. "docCmd", group.docCmd,
  538. ]
  539. if d.conf.backend == backendJs and findNodeJs() == "":
  540. discard "ignore JS runnableExample"
  541. elif os.execShellCmd(cmd) != 0:
  542. d.conf.quitOrRaise "[runnableExamples] failed: generated file: '$1' group: '$2' cmd: $3" % [outp.string, group[].prettyString, cmd]
  543. else:
  544. # keep generated source file `outp` to allow inspection.
  545. rawMessage(d.conf, hintSuccess, ["runnableExamples: " & outp.string])
  546. # removeFile(outp.changeFileExt(ExeExt)) # it's in nimcache, no need to remove
  547. proc quoted(a: string): string = result.addQuoted(a)
  548. proc toInstantiationInfo(conf: ConfigRef, info: TLineInfo): (string, int, int) =
  549. # xxx expose in compiler/lineinfos.nim
  550. (conf.toMsgFilename(info), info.line.int, info.col.int + ColOffset)
  551. proc prepareExample(d: PDoc; n: PNode, topLevel: bool): tuple[rdoccmd: string, code: string] =
  552. ## returns `rdoccmd` and source code for this runnableExamples
  553. var rdoccmd = ""
  554. if n.len < 2 or n.len > 3: globalError(d.conf, n.info, "runnableExamples invalid")
  555. if n.len == 3:
  556. let n1 = n[1]
  557. # xxx this should be evaluated during sempass
  558. if n1.kind notin nkStrKinds: globalError(d.conf, n1.info, "string litteral expected")
  559. rdoccmd = n1.strVal
  560. let useRenderModule = false
  561. let loc = d.conf.toFileLineCol(n.info)
  562. let code = extractRunnableExamplesSource(d.conf, n)
  563. if d.conf.errorCounter > 0:
  564. return (rdoccmd, code)
  565. let comment = "autogenerated by docgen\nloc: $1\nrdoccmd: $2" % [loc, rdoccmd]
  566. let outputDir = d.exampleOutputDir
  567. createDir(outputDir)
  568. inc d.exampleCounter
  569. let outp = outputDir / RelativeFile("$#_examples_$#.nim" % [d.filename.extractFilename.changeFileExt"", $d.exampleCounter])
  570. if useRenderModule:
  571. var docComment = newTree(nkCommentStmt)
  572. docComment.comment = comment
  573. var runnableExamples = newTree(nkStmtList,
  574. docComment,
  575. newTree(nkImportStmt, newStrNode(nkStrLit, "std/assertions")),
  576. newTree(nkImportStmt, newStrNode(nkStrLit, d.filename)))
  577. runnableExamples.info = n.info
  578. for a in n.lastSon: runnableExamples.add a
  579. # buggy, refs bug #17292
  580. # still worth fixing as it can affect other code relying on `renderModule`,
  581. # so we keep this code path here for now, which could still be useful in some
  582. # other situations.
  583. renderModule(runnableExamples, outp.string, conf = d.conf)
  584. else:
  585. var code2 = code
  586. if code.len > 0 and "codeReordering" notin code:
  587. let codeIndent = extractRunnableExamplesSource(d.conf, n, indent = 2)
  588. # hacky but simplest solution, until we devise a way to make `{.line.}`
  589. # work without introducing a scope
  590. code2 = """
  591. {.line: $#.}:
  592. $#
  593. """ % [$toInstantiationInfo(d.conf, n.info), codeIndent]
  594. code2 = """
  595. #[
  596. $#
  597. ]#
  598. import std/assertions
  599. import $#
  600. $#
  601. """ % [comment, d.filename.quoted, code2]
  602. writeFile(outp.string, code2)
  603. if rdoccmd notin d.exampleGroups:
  604. d.exampleGroups[rdoccmd] = ExampleGroup(rdoccmd: rdoccmd, docCmd: d.conf.docCmd, index: d.exampleGroups.len)
  605. d.exampleGroups[rdoccmd].code.add "import $1\n" % outp.string.quoted
  606. var codeShown: string
  607. if topLevel: # refs https://github.com/nim-lang/RFCs/issues/352
  608. let title = canonicalImport(d.conf, AbsoluteFile d.filename)
  609. codeShown = "import $#\n$#" % [title, code]
  610. else:
  611. codeShown = code
  612. result = (rdoccmd, codeShown)
  613. when false:
  614. proc extractImports(n: PNode; result: PNode) =
  615. if n.kind in {nkImportStmt, nkImportExceptStmt, nkFromStmt}:
  616. result.add copyTree(n)
  617. n.kind = nkEmpty
  618. return
  619. for i in 0..<n.safeLen: extractImports(n[i], result)
  620. let imports = newTree(nkStmtList)
  621. var savedLastSon = copyTree n.lastSon
  622. extractImports(savedLastSon, imports)
  623. for imp in imports: runnableExamples.add imp
  624. runnableExamples.add newTree(nkBlockStmt, newNode(nkEmpty), copyTree savedLastSon)
  625. type RunnableState = enum
  626. rsStart
  627. rsComment
  628. rsRunnable
  629. rsDone
  630. proc getAllRunnableExamplesImpl(d: PDoc; n: PNode, dest: var ItemPre,
  631. state: RunnableState, topLevel: bool):
  632. RunnableState =
  633. ##[
  634. Simple state machine to tell whether we render runnableExamples and doc comments.
  635. This is to ensure that we can interleave runnableExamples and doc comments freely;
  636. the logic is easy to change but currently a doc comment following another doc comment
  637. will not render, to avoid rendering in following case:
  638. proc fn* =
  639. runnableExamples: discard
  640. ## d1
  641. runnableExamples: discard
  642. ## d2
  643. ## internal explanation # <- this one should be out; it's part of rest of function body and would likey not make sense in doc comment
  644. discard # some code
  645. ]##
  646. case n.kind
  647. of nkCommentStmt:
  648. if state in {rsStart, rsRunnable}:
  649. dest.add genRecComment(d, n)
  650. return rsComment
  651. of nkCallKinds:
  652. if isRunnableExamples(n[0]) and
  653. n.len >= 2 and n.lastSon.kind == nkStmtList:
  654. if state in {rsStart, rsComment, rsRunnable}:
  655. let (rdoccmd, code) = prepareExample(d, n, topLevel)
  656. var msg = "Example:"
  657. if rdoccmd.len > 0: msg.add " cmd: " & rdoccmd
  658. var s: string
  659. dispA(d.conf, s, "\n<p><strong class=\"examples_text\">$1</strong></p>\n",
  660. "\n\n\\textbf{$1}\n", [msg])
  661. dest.add s
  662. inc d.listingCounter
  663. let id = $d.listingCounter
  664. dest.add(d.config.getOrDefault"doc.listing_start" % [id, "langNim", ""])
  665. var dest2 = ""
  666. renderNimCode(dest2, code, d.target)
  667. dest.add dest2
  668. dest.add(d.config.getOrDefault"doc.listing_end" % id)
  669. return rsRunnable
  670. else:
  671. localError(d.conf, n.info, errUser, "runnableExamples must appear before the first non-comment statement")
  672. else: discard
  673. return rsDone
  674. # change this to `rsStart` if you want to keep generating doc comments
  675. # and runnableExamples that occur after some code in routine
  676. proc getRoutineBody(n: PNode): PNode =
  677. ##[
  678. nim transforms these quite differently:
  679. proc someType*(): int =
  680. ## foo
  681. result = 3
  682. =>
  683. result =
  684. ## foo
  685. 3;
  686. proc someType*(): int =
  687. ## foo
  688. 3
  689. =>
  690. ## foo
  691. result = 3;
  692. so we normalize the results to get to the statement list containing the
  693. (0 or more) doc comments and runnableExamples.
  694. ]##
  695. result = n[bodyPos]
  696. # This won't be transformed: result.id = 10. Namely result[0].kind != nkSym.
  697. if result.kind == nkAsgn and result[0].kind == nkSym and
  698. n.len > bodyPos+1 and n[bodyPos+1].kind == nkSym:
  699. doAssert result.len == 2
  700. result = result[1]
  701. proc getAllRunnableExamples(d: PDoc, n: PNode, dest: var ItemPre) =
  702. var n = n
  703. var state = rsStart
  704. template fn(n2, topLevel) =
  705. state = getAllRunnableExamplesImpl(d, n2, dest, state, topLevel)
  706. dest.add genComment(d, n)
  707. case n.kind
  708. of routineDefs:
  709. n = n.getRoutineBody
  710. case n.kind
  711. of nkCommentStmt, nkCallKinds: fn(n, topLevel = false)
  712. else:
  713. for i in 0..<n.safeLen:
  714. fn(n[i], topLevel = false)
  715. if state == rsDone: discard # check all sons
  716. else: fn(n, topLevel = true)
  717. proc isVisible(d: PDoc; n: PNode): bool =
  718. result = false
  719. if n.kind == nkPostfix:
  720. if n.len == 2 and n[0].kind == nkIdent:
  721. var v = n[0].ident
  722. result = v.id == ord(wStar) or v.id == ord(wMinus)
  723. elif n.kind == nkSym:
  724. # we cannot generate code for forwarded symbols here as we have no
  725. # exception tracking information here. Instead we copy over the comment
  726. # from the proc header.
  727. if optDocInternal in d.conf.globalOptions:
  728. result = {sfFromGeneric, sfForward}*n.sym.flags == {}
  729. else:
  730. result = {sfExported, sfFromGeneric, sfForward}*n.sym.flags == {sfExported}
  731. if result and containsOrIncl(d.emitted, n.sym.id):
  732. result = false
  733. elif n.kind == nkPragmaExpr:
  734. result = isVisible(d, n[0])
  735. proc getName(n: PNode): string =
  736. case n.kind
  737. of nkPostfix: result = getName(n[1])
  738. of nkPragmaExpr: result = getName(n[0])
  739. of nkSym: result = n.sym.renderDefinitionName
  740. of nkIdent: result = n.ident.s
  741. of nkAccQuoted:
  742. result = "`"
  743. for i in 0..<n.len: result.add(getName(n[i]))
  744. result = "`"
  745. of nkOpenSymChoice, nkClosedSymChoice:
  746. result = getName(n[0])
  747. else:
  748. result = ""
  749. proc getNameEsc(d: PDoc, n: PNode): string =
  750. esc(d.target, getName(n))
  751. proc getNameIdent(cache: IdentCache; n: PNode): PIdent =
  752. case n.kind
  753. of nkPostfix: result = getNameIdent(cache, n[1])
  754. of nkPragmaExpr: result = getNameIdent(cache, n[0])
  755. of nkSym: result = n.sym.name
  756. of nkIdent: result = n.ident
  757. of nkAccQuoted:
  758. var r = ""
  759. for i in 0..<n.len: r.add(getNameIdent(cache, n[i]).s)
  760. result = getIdent(cache, r)
  761. of nkOpenSymChoice, nkClosedSymChoice:
  762. result = getNameIdent(cache, n[0])
  763. else:
  764. result = nil
  765. proc getRstName(n: PNode): PRstNode =
  766. case n.kind
  767. of nkPostfix: result = getRstName(n[1])
  768. of nkPragmaExpr: result = getRstName(n[0])
  769. of nkSym: result = newRstLeaf(n.sym.renderDefinitionName)
  770. of nkIdent: result = newRstLeaf(n.ident.s)
  771. of nkAccQuoted:
  772. result = getRstName(n[0])
  773. for i in 1..<n.len: result.text.add(getRstName(n[i]).text)
  774. of nkOpenSymChoice, nkClosedSymChoice:
  775. result = getRstName(n[0])
  776. else:
  777. result = nil
  778. proc newUniquePlainSymbol(d: PDoc, original: string): string =
  779. ## Returns a new unique plain symbol made up from the original.
  780. ##
  781. ## When a collision is found in the seenSymbols table, new numerical variants
  782. ## with underscore + number will be generated.
  783. if not d.seenSymbols.hasKey(original):
  784. result = original
  785. d.seenSymbols[original] = ""
  786. return
  787. # Iterate over possible numeric variants of the original name.
  788. var count = 2
  789. while true:
  790. result = original & "_" & $count
  791. if not d.seenSymbols.hasKey(result):
  792. d.seenSymbols[result] = ""
  793. break
  794. count += 1
  795. proc complexName(k: TSymKind, n: PNode, baseName: string): string =
  796. ## Builds a complex unique href name for the node.
  797. ##
  798. ## Pass as ``baseName`` the plain symbol obtained from the nodeName. The
  799. ## format of the returned symbol will be ``baseName(.callable type)?,(param
  800. ## type)?(,param type)*``. The callable type part will be added only if the
  801. ## node is not a proc, as those are the common ones. The suffix will be a dot
  802. ## and a single letter representing the type of the callable. The parameter
  803. ## types will be added with a preceding dash. Return types won't be added.
  804. ##
  805. ## If you modify the output of this proc, please update the anchor generation
  806. ## section of ``doc/docgen.rst``.
  807. result = baseName
  808. case k
  809. of skProc, skFunc: discard
  810. of skMacro: result.add(".m")
  811. of skMethod: result.add(".e")
  812. of skIterator: result.add(".i")
  813. of skTemplate: result.add(".t")
  814. of skConverter: result.add(".c")
  815. else: discard
  816. if n.safeLen > paramsPos and n[paramsPos].kind == nkFormalParams:
  817. let params = renderParamTypes(n[paramsPos])
  818. if params.len > 0:
  819. result.add(defaultParamSeparator)
  820. result.add(params)
  821. proc docstringSummary(rstText: string): string =
  822. ## Returns just the first line or a brief chunk of text from a rst string.
  823. ##
  824. ## Most docstrings will contain a one liner summary, so stripping at the
  825. ## first newline is usually fine. If after that the content is still too big,
  826. ## it is stripped at the first comma, colon or dot, usual English sentence
  827. ## separators.
  828. ##
  829. ## No guarantees are made on the size of the output, but it should be small.
  830. ## Also, we hope to not break the rst, but maybe we do. If there is any
  831. ## trimming done, an ellipsis unicode char is added.
  832. const maxDocstringChars = 100
  833. assert(rstText.len < 2 or (rstText[0] == '#' and rstText[1] == '#'))
  834. result = rstText.substr(2).strip
  835. var pos = result.find('\L')
  836. if pos > 0:
  837. result.setLen(pos - 1)
  838. result.add("…")
  839. if pos < maxDocstringChars:
  840. return
  841. # Try to keep trimming at other natural boundaries.
  842. pos = result.find({'.', ',', ':'})
  843. let last = result.len - 1
  844. if pos > 0 and pos < last:
  845. result.setLen(pos - 1)
  846. result.add("…")
  847. proc genDeprecationMsg(d: PDoc, n: PNode): string =
  848. ## Given a nkPragma wDeprecated node output a well-formatted section
  849. if n == nil: return
  850. case n.safeLen:
  851. of 0: # Deprecated w/o any message
  852. result = getConfigVar(d.conf, "doc.deprecationmsg") % [
  853. "label" , "Deprecated", "message", ""]
  854. of 2: # Deprecated w/ a message
  855. if n[1].kind in {nkStrLit..nkTripleStrLit}:
  856. result = getConfigVar(d.conf, "doc.deprecationmsg") % [
  857. "label", "Deprecated:", "message", xmltree.escape(n[1].strVal)]
  858. else:
  859. doAssert false
  860. type DocFlags = enum
  861. kDefault
  862. kForceExport
  863. proc genSeeSrc(d: PDoc, path: string, line: int): string =
  864. let docItemSeeSrc = getConfigVar(d.conf, "doc.item.seesrc")
  865. if docItemSeeSrc.len > 0:
  866. let path = relativeTo(AbsoluteFile path, AbsoluteDir getCurrentDir(), '/')
  867. when false:
  868. let cwd = canonicalizePath(d.conf, getCurrentDir())
  869. var path = path
  870. if path.startsWith(cwd):
  871. path = path[cwd.len+1..^1].replace('\\', '/')
  872. let gitUrl = getConfigVar(d.conf, "git.url")
  873. if gitUrl.len > 0:
  874. let defaultBranch =
  875. if NimPatch mod 2 == 1: "devel"
  876. else: "version-$1-$2" % [$NimMajor, $NimMinor]
  877. let commit = getConfigVar(d.conf, "git.commit", defaultBranch)
  878. let develBranch = getConfigVar(d.conf, "git.devel", "devel")
  879. dispA(d.conf, result, "$1", "", [docItemSeeSrc % [
  880. "path", path.string, "line", $line, "url", gitUrl,
  881. "commit", commit, "devel", develBranch]])
  882. proc symbolPriority(k: TSymKind): int =
  883. result = case k
  884. of skMacro: -3
  885. of skTemplate: -2
  886. of skIterator: -1
  887. else: 0 # including skProc which have higher priority
  888. # documentation itself has even higher priority 1
  889. proc getTypeKind(n: PNode): string =
  890. case n[2].kind
  891. of nkEnumTy: "enum"
  892. of nkObjectTy: "object"
  893. of nkTupleTy: "tuple"
  894. else: ""
  895. proc toLangSymbol(k: TSymKind, n: PNode, baseName: string): LangSymbol =
  896. ## Converts symbol info (names/types/parameters) in `n` into format
  897. ## `LangSymbol` convenient for ``rst.nim``/``dochelpers.nim``.
  898. result.name = baseName.nimIdentNormalize
  899. result.symKind = k.toHumanStr
  900. if k in routineKinds:
  901. var
  902. paramTypes: seq[string]
  903. renderParamTypes(paramTypes, n[paramsPos], toNormalize=true)
  904. let paramNames = renderParamNames(n[paramsPos], toNormalize=true)
  905. # In some rare cases (system.typeof) parameter type is not set for default:
  906. doAssert paramTypes.len <= paramNames.len
  907. for i in 0 ..< paramNames.len:
  908. if i < paramTypes.len:
  909. result.parameters.add (paramNames[i], paramTypes[i])
  910. else:
  911. result.parameters.add (paramNames[i], "")
  912. result.parametersProvided = true
  913. result.outType = renderOutType(n[paramsPos], toNormalize=true)
  914. if k in {skProc, skFunc, skType, skIterator}:
  915. # Obtain `result.generics`
  916. # Use `n[miscPos]` since n[genericParamsPos] does not contain constraints
  917. var genNode: PNode = nil
  918. if k == skType:
  919. genNode = n[1] # FIXME: what is index 1?
  920. else:
  921. if n[miscPos].kind != nkEmpty:
  922. genNode = n[miscPos][1] # FIXME: what is index 1?
  923. if genNode != nil:
  924. var literal = ""
  925. var r: TSrcGen
  926. initTokRender(r, genNode, {renderNoBody, renderNoComments,
  927. renderNoPragmas, renderNoProcDefs, renderExpandUsing})
  928. var kind = tkEof
  929. while true:
  930. getNextTok(r, kind, literal)
  931. if kind == tkEof:
  932. break
  933. if kind != tkSpaces:
  934. result.generics.add(literal.nimIdentNormalize)
  935. if k == skType: result.symTypeKind = getTypeKind(n)
  936. proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags, nonExports: bool = false) =
  937. if (docFlags != kForceExport) and not isVisible(d, nameNode): return
  938. let
  939. name = getName(nameNode)
  940. nameEsc = esc(d.target, name)
  941. var plainDocstring = getPlainDocstring(n) # call here before genRecComment!
  942. var result = ""
  943. var literal, plainName = ""
  944. var kind = tkEof
  945. var comm: ItemPre
  946. if n.kind in routineDefs:
  947. getAllRunnableExamples(d, n, comm)
  948. else:
  949. comm.add genRecComment(d, n)
  950. var r: TSrcGen
  951. # Obtain the plain rendered string for hyperlink titles.
  952. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments,
  953. renderNoPragmas, renderNoProcDefs, renderExpandUsing})
  954. while true:
  955. getNextTok(r, kind, literal)
  956. if kind == tkEof:
  957. break
  958. plainName.add(literal)
  959. var pragmaNode = getDeclPragma(n)
  960. if pragmaNode != nil: pragmaNode = findPragma(pragmaNode, wDeprecated)
  961. inc(d.id)
  962. let
  963. plainNameEsc = esc(d.target, plainName.strip)
  964. typeDescr =
  965. if k == skType and getTypeKind(n) != "": getTypeKind(n)
  966. else: k.toHumanStr
  967. detailedName = typeDescr & " " & (
  968. if k in routineKinds: plainName else: name)
  969. uniqueName = if k in routineKinds: plainNameEsc else: nameEsc
  970. sortName = if k in routineKinds: plainName.strip else: name
  971. cleanPlainSymbol = renderPlainSymbolName(nameNode)
  972. complexSymbol = complexName(k, n, cleanPlainSymbol)
  973. plainSymbolEnc = encodeUrl(cleanPlainSymbol, usePlus = false)
  974. symbolOrId = d.newUniquePlainSymbol(complexSymbol)
  975. symbolOrIdEnc = encodeUrl(symbolOrId, usePlus = false)
  976. deprecationMsg = genDeprecationMsg(d, pragmaNode)
  977. rstLangSymbol = toLangSymbol(k, n, cleanPlainSymbol)
  978. # we generate anchors automatically for subsequent use in doc comments
  979. let lineinfo = rstast.TLineInfo(
  980. line: nameNode.info.line, col: nameNode.info.col,
  981. fileIndex: addRstFileIndex(d, nameNode.info))
  982. addAnchorNim(d.sharedState, external = false, refn = symbolOrId,
  983. tooltip = detailedName, langSym = rstLangSymbol,
  984. priority = symbolPriority(k), info = lineinfo,
  985. module = addRstFileIndex(d, FileIndex d.module.position))
  986. let renderFlags =
  987. if nonExports: {renderNoBody, renderNoComments, renderDocComments, renderSyms,
  988. renderExpandUsing, renderNonExportedFields}
  989. else: {renderNoBody, renderNoComments, renderDocComments, renderSyms, renderExpandUsing}
  990. nodeToHighlightedHtml(d, n, result, renderFlags, symbolOrIdEnc)
  991. let seeSrc = genSeeSrc(d, toFullPath(d.conf, n.info), n.info.line.int)
  992. d.section[k].secItems.mgetOrPut(cleanPlainSymbol, newSeq[Item]()).add Item(
  993. descRst: comm,
  994. sortName: sortName,
  995. info: lineinfo,
  996. anchor: symbolOrId,
  997. detailedName: detailedName,
  998. name: name,
  999. substitutions: @[
  1000. "uniqueName", uniqueName,
  1001. "header", result, "itemID", $d.id,
  1002. "header_plain", plainNameEsc, "itemSym", cleanPlainSymbol,
  1003. "itemSymEnc", plainSymbolEnc,
  1004. "itemSymOrIDEnc", symbolOrIdEnc, "seeSrc", seeSrc,
  1005. "deprecationMsg", deprecationMsg])
  1006. let external = d.destFile.AbsoluteFile.relativeTo(d.conf.outDir, '/').changeFileExt(HtmlExt).string
  1007. var attype = ""
  1008. if k in routineKinds and nameNode.kind == nkSym:
  1009. let att = attachToType(d, nameNode.sym)
  1010. if att != nil:
  1011. attype = esc(d.target, att.name.s)
  1012. elif k == skType and nameNode.kind == nkSym and nameNode.sym.typ.kind in {tyEnum, tyBool}:
  1013. let etyp = nameNode.sym.typ
  1014. for e in etyp.n:
  1015. if e.sym.kind != skEnumField: continue
  1016. let plain = renderPlainSymbolName(e)
  1017. let symbolOrId = d.newUniquePlainSymbol(plain)
  1018. setIndexTerm(d[], ieNim, htmlFile = external, id = symbolOrId,
  1019. term = plain, linkTitle = nameNode.sym.name.s & '.' & plain,
  1020. linkDesc = xmltree.escape(getPlainDocstring(e).docstringSummary),
  1021. line = n.info.line.int)
  1022. d.tocSimple[k].add TocItem(
  1023. sortName: sortName,
  1024. content: getConfigVar(d.conf, "doc.item.toc") % [
  1025. "name", name, "header_plain", plainNameEsc,
  1026. "itemSymOrIDEnc", symbolOrIdEnc])
  1027. d.tocTable[k].mgetOrPut(cleanPlainSymbol, newSeq[TocItem]()).add TocItem(
  1028. sortName: sortName,
  1029. content: getConfigVar(d.conf, "doc.item.tocTable") % [
  1030. "name", name, "header_plain", plainNameEsc,
  1031. "itemSymOrID", symbolOrId.replace(",", ",<wbr>"),
  1032. "itemSymOrIDEnc", symbolOrIdEnc])
  1033. setIndexTerm(d[], ieNim, htmlFile = external, id = symbolOrId, term = name,
  1034. linkTitle = detailedName,
  1035. linkDesc = xmltree.escape(plainDocstring.docstringSummary),
  1036. line = n.info.line.int)
  1037. if k == skType and nameNode.kind == nkSym:
  1038. d.types.strTableAdd nameNode.sym
  1039. proc genJsonItem(d: PDoc, n, nameNode: PNode, k: TSymKind): JsonItem =
  1040. if not isVisible(d, nameNode): return
  1041. var
  1042. name = getNameEsc(d, nameNode)
  1043. comm = genRecComment(d, n)
  1044. r: TSrcGen
  1045. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments, renderExpandUsing})
  1046. result.json = %{ "name": %name, "type": %($k), "line": %n.info.line.int,
  1047. "col": %n.info.col}
  1048. if comm != nil:
  1049. result.rst = comm
  1050. result.rstField = "description"
  1051. if r.buf.len > 0:
  1052. result.json["code"] = %r.buf
  1053. if k in routineKinds:
  1054. result.json["signature"] = newJObject()
  1055. if n[paramsPos][0].kind != nkEmpty:
  1056. result.json["signature"]["return"] = %($n[paramsPos][0])
  1057. if n[paramsPos].len > 1:
  1058. result.json["signature"]["arguments"] = newJArray()
  1059. for paramIdx in 1 ..< n[paramsPos].len:
  1060. for identIdx in 0 ..< n[paramsPos][paramIdx].len - 2:
  1061. let
  1062. paramName = $n[paramsPos][paramIdx][identIdx]
  1063. paramType = $n[paramsPos][paramIdx][^2]
  1064. if n[paramsPos][paramIdx][^1].kind != nkEmpty:
  1065. let paramDefault = $n[paramsPos][paramIdx][^1]
  1066. result.json["signature"]["arguments"].add %{"name": %paramName, "type": %paramType, "default": %paramDefault}
  1067. else:
  1068. result.json["signature"]["arguments"].add %{"name": %paramName, "type": %paramType}
  1069. if n[pragmasPos].kind != nkEmpty:
  1070. result.json["signature"]["pragmas"] = newJArray()
  1071. for pragma in n[pragmasPos]:
  1072. result.json["signature"]["pragmas"].add %($pragma)
  1073. if n[genericParamsPos].kind != nkEmpty:
  1074. result.json["signature"]["genericParams"] = newJArray()
  1075. for genericParam in n[genericParamsPos]:
  1076. var param = %{"name": %($genericParam)}
  1077. if genericParam.sym.typ.sons.len > 0:
  1078. param["types"] = newJArray()
  1079. for kind in genericParam.sym.typ.sons:
  1080. param["types"].add %($kind)
  1081. result.json["signature"]["genericParams"].add param
  1082. if optGenIndex in d.conf.globalOptions:
  1083. genItem(d, n, nameNode, k, kForceExport)
  1084. proc setDoctype(d: PDoc, n: PNode) =
  1085. ## Processes `{.doctype.}` pragma changing Markdown/RST parsing options.
  1086. if n == nil:
  1087. return
  1088. if n.len != 2:
  1089. localError(d.conf, n.info, errUser,
  1090. "doctype pragma takes exactly 1 argument"
  1091. )
  1092. return
  1093. var dt = ""
  1094. case n[1].kind
  1095. of nkStrLit:
  1096. dt = toLowerAscii(n[1].strVal)
  1097. of nkIdent:
  1098. dt = toLowerAscii(n[1].ident.s)
  1099. else:
  1100. localError(d.conf, n.info, errUser,
  1101. "unknown argument type $1 provided to doctype" % [$n[1].kind]
  1102. )
  1103. return
  1104. case dt
  1105. of "markdown":
  1106. d.sharedState.options.incl roSupportMarkdown
  1107. d.sharedState.options.incl roPreferMarkdown
  1108. of "rstmarkdown":
  1109. d.sharedState.options.incl roSupportMarkdown
  1110. d.sharedState.options.excl roPreferMarkdown
  1111. of "rst":
  1112. d.sharedState.options.excl roSupportMarkdown
  1113. d.sharedState.options.excl roPreferMarkdown
  1114. else:
  1115. localError(d.conf, n.info, errUser,
  1116. (
  1117. "unknown doctype value \"$1\", should be from " &
  1118. "\"RST\", \"Markdown\", \"RstMarkdown\""
  1119. ) % [dt]
  1120. )
  1121. proc checkForFalse(n: PNode): bool =
  1122. result = n.kind == nkIdent and cmpIgnoreStyle(n.ident.s, "false") == 0
  1123. proc traceDeps(d: PDoc, it: PNode) =
  1124. const k = skModule
  1125. if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
  1126. let sep = it[0]
  1127. let dir = it[1]
  1128. let a = newNodeI(nkInfix, it.info)
  1129. a.add sep
  1130. a.add dir
  1131. a.add sep # dummy entry, replaced in the loop
  1132. for x in it[2]:
  1133. a[2] = x
  1134. traceDeps(d, a)
  1135. elif it.kind == nkSym and belongsToProjectPackage(d.conf, it.sym):
  1136. let external = externalDep(d, it.sym)
  1137. if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
  1138. dispA(d.conf, d.section[k].finalMarkup,
  1139. "<a class=\"reference external\" href=\"$2\">$1</a>",
  1140. "$1", [esc(d.target, external.prettyLink),
  1141. changeFileExt(external, "html")])
  1142. proc exportSym(d: PDoc; s: PSym) =
  1143. const k = exportSection
  1144. if s.kind == skModule and belongsToProjectPackage(d.conf, s):
  1145. let external = externalDep(d, s)
  1146. if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
  1147. dispA(d.conf, d.section[k].finalMarkup,
  1148. "<a class=\"reference external\" href=\"$2\">$1</a>",
  1149. "$1", [esc(d.target, external.prettyLink),
  1150. changeFileExt(external, "html")])
  1151. elif s.kind != skModule and s.owner != nil:
  1152. let module = originatingModule(s)
  1153. if belongsToProjectPackage(d.conf, module):
  1154. let
  1155. complexSymbol = complexName(s.kind, s.ast, s.name.s)
  1156. symbolOrId = d.newUniquePlainSymbol(complexSymbol)
  1157. external = externalDep(d, module)
  1158. if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
  1159. # XXX proper anchor generation here
  1160. dispA(d.conf, d.section[k].finalMarkup,
  1161. "<a href=\"$2#$3\"><span class=\"Identifier\">$1</span></a>",
  1162. "$1", [esc(d.target, s.name.s),
  1163. changeFileExt(external, "html"),
  1164. symbolOrId])
  1165. proc documentNewEffect(cache: IdentCache; n: PNode): PNode =
  1166. let s = n[namePos].sym
  1167. if tfReturnsNew in s.typ.flags:
  1168. result = newIdentNode(getIdent(cache, "new"), n.info)
  1169. proc documentEffect(cache: IdentCache; n, x: PNode, effectType: TSpecialWord, idx: int): PNode =
  1170. let spec = effectSpec(x, effectType)
  1171. if isNil(spec):
  1172. let s = n[namePos].sym
  1173. let actual = s.typ.n[0]
  1174. if actual.len != effectListLen: return
  1175. let real = actual[idx]
  1176. if real == nil: return
  1177. let realLen = real.len
  1178. # warning: hack ahead:
  1179. var effects = newNodeI(nkBracket, n.info, realLen)
  1180. for i in 0..<realLen:
  1181. var t = typeToString(real[i].typ)
  1182. if t.startsWith("ref "): t = substr(t, 4)
  1183. effects[i] = newIdentNode(getIdent(cache, t), n.info)
  1184. # set the type so that the following analysis doesn't screw up:
  1185. effects[i].typ = real[i].typ
  1186. result = newTreeI(nkExprColonExpr, n.info,
  1187. newIdentNode(getIdent(cache, $effectType), n.info), effects)
  1188. proc documentWriteEffect(cache: IdentCache; n: PNode; flag: TSymFlag; pragmaName: string): PNode =
  1189. let s = n[namePos].sym
  1190. let params = s.typ.n
  1191. var effects = newNodeI(nkBracket, n.info)
  1192. for i in 1..<params.len:
  1193. if params[i].kind == nkSym and flag in params[i].sym.flags:
  1194. effects.add params[i]
  1195. if effects.len > 0:
  1196. result = newTreeI(nkExprColonExpr, n.info,
  1197. newIdentNode(getIdent(cache, pragmaName), n.info), effects)
  1198. proc documentRaises*(cache: IdentCache; n: PNode) =
  1199. if n[namePos].kind != nkSym: return
  1200. let pragmas = n[pragmasPos]
  1201. let p1 = documentEffect(cache, n, pragmas, wRaises, exceptionEffects)
  1202. let p2 = documentEffect(cache, n, pragmas, wTags, tagEffects)
  1203. let p3 = documentWriteEffect(cache, n, sfWrittenTo, "writes")
  1204. let p4 = documentNewEffect(cache, n)
  1205. let p5 = documentWriteEffect(cache, n, sfEscapes, "escapes")
  1206. let p6 = documentEffect(cache, n, pragmas, wForbids, forbiddenEffects)
  1207. if p1 != nil or p2 != nil or p3 != nil or p4 != nil or p5 != nil or p6 != nil:
  1208. if pragmas.kind == nkEmpty:
  1209. n[pragmasPos] = newNodeI(nkPragma, n.info)
  1210. if p1 != nil: n[pragmasPos].add p1
  1211. if p2 != nil: n[pragmasPos].add p2
  1212. if p3 != nil: n[pragmasPos].add p3
  1213. if p4 != nil: n[pragmasPos].add p4
  1214. if p5 != nil: n[pragmasPos].add p5
  1215. if p6 != nil: n[pragmasPos].add p6
  1216. proc generateDoc*(d: PDoc, n, orig: PNode, config: ConfigRef, docFlags: DocFlags = kDefault) =
  1217. ## Goes through nim nodes recursively and collects doc comments.
  1218. ## Main function for `doc`:option: command,
  1219. ## which is implemented in ``docgen2.nim``.
  1220. template genItemAux(skind) =
  1221. genItem(d, n, n[namePos], skind, docFlags)
  1222. let showNonExports = optShowNonExportedFields in config.globalOptions
  1223. case n.kind
  1224. of nkPragma:
  1225. let pragmaNode = findPragma(n, wDeprecated)
  1226. d.modDeprecationMsg.add(genDeprecationMsg(d, pragmaNode))
  1227. let doctypeNode = findPragma(n, wDoctype)
  1228. setDoctype(d, doctypeNode)
  1229. of nkCommentStmt: d.modDescPre.add(genComment(d, n))
  1230. of nkProcDef, nkFuncDef:
  1231. when useEffectSystem: documentRaises(d.cache, n)
  1232. genItemAux(skProc)
  1233. of nkMethodDef:
  1234. when useEffectSystem: documentRaises(d.cache, n)
  1235. genItemAux(skMethod)
  1236. of nkIteratorDef:
  1237. when useEffectSystem: documentRaises(d.cache, n)
  1238. genItemAux(skIterator)
  1239. of nkMacroDef: genItemAux(skMacro)
  1240. of nkTemplateDef: genItemAux(skTemplate)
  1241. of nkConverterDef:
  1242. when useEffectSystem: documentRaises(d.cache, n)
  1243. genItemAux(skConverter)
  1244. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  1245. for i in 0..<n.len:
  1246. if n[i].kind != nkCommentStmt:
  1247. # order is always 'type var let const':
  1248. genItem(d, n[i], n[i][0],
  1249. succ(skType, ord(n.kind)-ord(nkTypeSection)), docFlags, showNonExports)
  1250. of nkStmtList:
  1251. for i in 0..<n.len: generateDoc(d, n[i], orig, config)
  1252. of nkWhenStmt:
  1253. # generate documentation for the first branch only:
  1254. if not checkForFalse(n[0][0]):
  1255. generateDoc(d, lastSon(n[0]), orig, config)
  1256. of nkImportStmt:
  1257. for it in n: traceDeps(d, it)
  1258. of nkExportStmt:
  1259. for it in n:
  1260. if it.kind == nkSym:
  1261. if d.module != nil and d.module == it.sym.owner:
  1262. generateDoc(d, it.sym.ast, orig, config, kForceExport)
  1263. elif it.sym.ast != nil:
  1264. exportSym(d, it.sym)
  1265. of nkExportExceptStmt: discard "transformed into nkExportStmt by semExportExcept"
  1266. of nkFromStmt, nkImportExceptStmt: traceDeps(d, n[0])
  1267. of nkCallKinds:
  1268. var comm: ItemPre
  1269. getAllRunnableExamples(d, n, comm)
  1270. if comm.len != 0: d.modDescPre.add(comm)
  1271. else: discard
  1272. proc overloadGroupName(s: string, k: TSymKind): string =
  1273. ## Turns a name like `f` into anchor `f-procs-all`
  1274. s & "-" & k.toHumanStr & "s-all"
  1275. proc setIndexTitle(d: PDoc, useMetaTitle: bool) =
  1276. let titleKind = if d.standaloneDoc: ieMarkupTitle else: ieNimTitle
  1277. let external = AbsoluteFile(d.destFile)
  1278. .relativeTo(d.conf.outDir, '/')
  1279. .changeFileExt(HtmlExt)
  1280. .string
  1281. var term, linkTitle: string
  1282. if useMetaTitle and d.meta[metaTitle].len != 0:
  1283. term = d.meta[metaTitleRaw]
  1284. linkTitle = d.meta[metaTitleRaw]
  1285. else:
  1286. let filename = extractFilename(d.filename)
  1287. term =
  1288. if d.standaloneDoc: filename # keep .rst/.md extension
  1289. else: changeFileExt(filename, "") # rm .nim extension
  1290. linkTitle =
  1291. if d.standaloneDoc: term # keep .rst/.md extension
  1292. else: canonicalImport(d.conf, AbsoluteFile d.filename)
  1293. if not d.standaloneDoc:
  1294. linkTitle = "module " & linkTitle
  1295. setIndexTerm(d[], titleKind, htmlFile = external, id = "",
  1296. term = term, linkTitle = linkTitle)
  1297. proc finishGenerateDoc*(d: var PDoc) =
  1298. ## Perform 2nd RST pass for resolution of links/footnotes/headings...
  1299. # copy file map `filenames` to ``rstgen.nim`` for its warnings
  1300. d.filenames = d.sharedState.filenames
  1301. # Main title/subtitle are allowed only in the first RST fragment of document
  1302. var firstRst = PRstNode(nil)
  1303. for fragment in d.modDescPre:
  1304. if fragment.isRst:
  1305. firstRst = fragment.rst
  1306. break
  1307. d.hasToc = d.hasToc or d.sharedState.hasToc
  1308. # in --index:only mode we do NOT want to load other .idx, only write ours:
  1309. let importdoc = optGenIndexOnly notin d.conf.globalOptions and
  1310. optNoImportdoc notin d.conf.globalOptions
  1311. preparePass2(d.sharedState, firstRst, importdoc)
  1312. if optGenIndexOnly in d.conf.globalOptions:
  1313. # Top-level doc.comments may contain titles and :idx: statements:
  1314. for fragment in d.modDescPre:
  1315. if fragment.isRst:
  1316. traverseForIndex(d[], fragment.rst)
  1317. setIndexTitle(d, useMetaTitle = d.standaloneDoc)
  1318. # Symbol-associated doc.comments may contain :idx: statements:
  1319. for k in TSymKind:
  1320. for _, overloadChoices in d.section[k].secItems:
  1321. for item in overloadChoices:
  1322. for fragment in item.descRst:
  1323. if fragment.isRst:
  1324. traverseForIndex(d[], fragment.rst)
  1325. # add anchors to overload groups before RST resolution
  1326. for k in TSymKind:
  1327. if k in routineKinds:
  1328. for plainName, overloadChoices in d.section[k].secItems:
  1329. if overloadChoices.len > 1:
  1330. let refn = overloadGroupName(plainName, k)
  1331. let tooltip = "$1 ($2 overloads)" % [
  1332. k.toHumanStr & " " & plainName, $overloadChoices.len]
  1333. let name = nimIdentBackticksNormalize(plainName)
  1334. # save overload group to ``.idx``
  1335. let external = d.destFile.AbsoluteFile.relativeTo(d.conf.outDir, '/').
  1336. changeFileExt(HtmlExt).string
  1337. setIndexTerm(d[], ieNimGroup, htmlFile = external, id = refn,
  1338. term = name, linkTitle = k.toHumanStr,
  1339. linkDesc = "", line = overloadChoices[0].info.line.int)
  1340. if optGenIndexOnly in d.conf.globalOptions: continue
  1341. addAnchorNim(d.sharedState, external=false, refn, tooltip,
  1342. LangSymbol(symKind: k.toHumanStr,
  1343. name: name,
  1344. isGroup: true),
  1345. priority = symbolPriority(k),
  1346. # select index `0` just to have any meaningful warning:
  1347. info = overloadChoices[0].info,
  1348. module = addRstFileIndex(d, FileIndex d.module.position))
  1349. if optGenIndexOnly in d.conf.globalOptions:
  1350. return
  1351. # Finalize fragments of ``.nim`` or ``.rst`` file
  1352. proc renderItemPre(d: PDoc, fragments: ItemPre, result: var string) =
  1353. for f in fragments:
  1354. case f.isRst:
  1355. of true:
  1356. var resolved = resolveSubs(d.sharedState, f.rst)
  1357. renderRstToOut(d[], resolved, result)
  1358. of false: result &= f.str
  1359. proc cmp(x, y: Item): int = cmpDecimalsIgnoreCase(x.sortName, y.sortName)
  1360. for k in TSymKind:
  1361. # add symbols to section for each `k`, while optionally wrapping
  1362. # overloadable items with the same basic name by ``doc.item2``
  1363. let overloadableNames = toSeq(keys(d.section[k].secItems))
  1364. for plainName in overloadableNames.sorted(cmpDecimalsIgnoreCase):
  1365. var overloadChoices = d.section[k].secItems[plainName]
  1366. overloadChoices.sort(cmp)
  1367. var nameContent = ""
  1368. for item in overloadChoices:
  1369. var itemDesc: string
  1370. renderItemPre(d, item.descRst, itemDesc)
  1371. nameContent.add(
  1372. getConfigVar(d.conf, "doc.item") % (
  1373. item.substitutions & @[
  1374. "desc", itemDesc,
  1375. "name", item.name,
  1376. "itemSymOrID", item.anchor]))
  1377. if k in routineKinds:
  1378. let plainNameEsc1 = esc(d.target, plainName.strip)
  1379. let plainNameEsc2 = esc(d.target, plainName.strip, escMode=emUrl)
  1380. d.section[k].finalMarkup.add(
  1381. getConfigVar(d.conf, "doc.item2") % (
  1382. @["header_plain", plainNameEsc1,
  1383. "overloadGroupName", overloadGroupName(plainNameEsc2, k),
  1384. "content", nameContent]))
  1385. else:
  1386. d.section[k].finalMarkup.add(nameContent)
  1387. d.section[k].secItems.clear
  1388. renderItemPre(d, d.modDescPre, d.modDescFinal)
  1389. d.modDescPre.setLen 0
  1390. # Finalize fragments of ``.json`` file
  1391. for i, entry in d.jEntriesPre:
  1392. if entry.rst != nil:
  1393. let resolved = resolveSubs(d.sharedState, entry.rst)
  1394. var str: string
  1395. renderRstToOut(d[], resolved, str)
  1396. entry.json[entry.rstField] = %str
  1397. d.jEntriesPre[i].rst = nil
  1398. d.jEntriesFinal.add entry.json # generates docs
  1399. setIndexTitle(d, useMetaTitle = d.standaloneDoc)
  1400. completePass2(d.sharedState)
  1401. proc add(d: PDoc; j: JsonItem) =
  1402. if j.json != nil or j.rst != nil: d.jEntriesPre.add j
  1403. proc generateJson*(d: PDoc, n: PNode, includeComments: bool = true) =
  1404. case n.kind
  1405. of nkPragma:
  1406. let doctypeNode = findPragma(n, wDoctype)
  1407. setDoctype(d, doctypeNode)
  1408. of nkCommentStmt:
  1409. if includeComments:
  1410. d.add JsonItem(rst: genComment(d, n), rstField: "comment",
  1411. json: %Table[string, string]())
  1412. else:
  1413. d.modDescPre.add(genComment(d, n))
  1414. of nkProcDef, nkFuncDef:
  1415. when useEffectSystem: documentRaises(d.cache, n)
  1416. d.add genJsonItem(d, n, n[namePos], skProc)
  1417. of nkMethodDef:
  1418. when useEffectSystem: documentRaises(d.cache, n)
  1419. d.add genJsonItem(d, n, n[namePos], skMethod)
  1420. of nkIteratorDef:
  1421. when useEffectSystem: documentRaises(d.cache, n)
  1422. d.add genJsonItem(d, n, n[namePos], skIterator)
  1423. of nkMacroDef:
  1424. d.add genJsonItem(d, n, n[namePos], skMacro)
  1425. of nkTemplateDef:
  1426. d.add genJsonItem(d, n, n[namePos], skTemplate)
  1427. of nkConverterDef:
  1428. when useEffectSystem: documentRaises(d.cache, n)
  1429. d.add genJsonItem(d, n, n[namePos], skConverter)
  1430. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  1431. for i in 0..<n.len:
  1432. if n[i].kind != nkCommentStmt:
  1433. # order is always 'type var let const':
  1434. d.add genJsonItem(d, n[i], n[i][0],
  1435. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  1436. of nkStmtList:
  1437. for i in 0..<n.len:
  1438. generateJson(d, n[i], includeComments)
  1439. of nkWhenStmt:
  1440. # generate documentation for the first branch only:
  1441. if not checkForFalse(n[0][0]):
  1442. generateJson(d, lastSon(n[0]), includeComments)
  1443. else: discard
  1444. proc genTagsItem(d: PDoc, n, nameNode: PNode, k: TSymKind): string =
  1445. result = getNameEsc(d, nameNode) & "\n"
  1446. proc generateTags*(d: PDoc, n: PNode, r: var string) =
  1447. case n.kind
  1448. of nkCommentStmt:
  1449. if startsWith(n.comment, "##"):
  1450. let stripped = n.comment.substr(2).strip
  1451. r.add stripped
  1452. of nkProcDef:
  1453. when useEffectSystem: documentRaises(d.cache, n)
  1454. r.add genTagsItem(d, n, n[namePos], skProc)
  1455. of nkFuncDef:
  1456. when useEffectSystem: documentRaises(d.cache, n)
  1457. r.add genTagsItem(d, n, n[namePos], skFunc)
  1458. of nkMethodDef:
  1459. when useEffectSystem: documentRaises(d.cache, n)
  1460. r.add genTagsItem(d, n, n[namePos], skMethod)
  1461. of nkIteratorDef:
  1462. when useEffectSystem: documentRaises(d.cache, n)
  1463. r.add genTagsItem(d, n, n[namePos], skIterator)
  1464. of nkMacroDef:
  1465. r.add genTagsItem(d, n, n[namePos], skMacro)
  1466. of nkTemplateDef:
  1467. r.add genTagsItem(d, n, n[namePos], skTemplate)
  1468. of nkConverterDef:
  1469. when useEffectSystem: documentRaises(d.cache, n)
  1470. r.add genTagsItem(d, n, n[namePos], skConverter)
  1471. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  1472. for i in 0..<n.len:
  1473. if n[i].kind != nkCommentStmt:
  1474. # order is always 'type var let const':
  1475. r.add genTagsItem(d, n[i], n[i][0],
  1476. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  1477. of nkStmtList:
  1478. for i in 0..<n.len:
  1479. generateTags(d, n[i], r)
  1480. of nkWhenStmt:
  1481. # generate documentation for the first branch only:
  1482. if not checkForFalse(n[0][0]):
  1483. generateTags(d, lastSon(n[0]), r)
  1484. else: discard
  1485. proc genSection(d: PDoc, kind: TSymKind, groupedToc = false) =
  1486. const sectionNames: array[skModule..skField, string] = [
  1487. "Imports", "Types", "Vars", "Lets", "Consts", "Vars", "Procs", "Funcs",
  1488. "Methods", "Iterators", "Converters", "Macros", "Templates", "Exports"
  1489. ]
  1490. if d.section[kind].finalMarkup == "": return
  1491. var title = sectionNames[kind]
  1492. d.section[kind].finalMarkup = getConfigVar(d.conf, "doc.section") % [
  1493. "sectionid", $ord(kind), "sectionTitle", title,
  1494. "sectionTitleID", $(ord(kind) + 50), "content", d.section[kind].finalMarkup]
  1495. proc cmp(x, y: TocItem): int = cmpDecimalsIgnoreCase(x.sortName, y.sortName)
  1496. if groupedToc:
  1497. let overloadableNames = toSeq(keys(d.tocTable[kind]))
  1498. for plainName in overloadableNames.sorted(cmpDecimalsIgnoreCase):
  1499. var overloadChoices = d.tocTable[kind][plainName]
  1500. overloadChoices.sort(cmp)
  1501. var content: string
  1502. for item in overloadChoices:
  1503. content.add item.content
  1504. d.toc2[kind].add getConfigVar(d.conf, "doc.section.toc2") % [
  1505. "sectionid", $ord(kind), "sectionTitle", title,
  1506. "sectionTitleID", $(ord(kind) + 50),
  1507. "content", content, "plainName", plainName]
  1508. else:
  1509. for item in d.tocSimple[kind].sorted(cmp):
  1510. d.toc2[kind].add item.content
  1511. let sectionValues = @[
  1512. "sectionID", $ord(kind), "sectionTitleID", $(ord(kind) + 50),
  1513. "sectionTitle", title
  1514. ]
  1515. # Check if the toc has any children
  1516. if d.toc2[kind] != "":
  1517. # Use the dropdown version instead and store the children in the dropdown
  1518. d.toc[kind] = getConfigVar(d.conf, "doc.section.toc") % (sectionValues & @[
  1519. "content", d.toc2[kind]
  1520. ])
  1521. else:
  1522. # Just have the link
  1523. d.toc[kind] = getConfigVar(d.conf, "doc.section.toc_item") % sectionValues
  1524. proc relLink(outDir: AbsoluteDir, destFile: AbsoluteFile, linkto: RelativeFile): string =
  1525. $relativeTo(outDir / linkto, destFile.splitFile().dir, '/')
  1526. proc genOutFile(d: PDoc, groupedToc = false): string =
  1527. var
  1528. code, content: string
  1529. title = ""
  1530. var j = 0
  1531. var toc = ""
  1532. renderTocEntries(d[], j, 1, toc)
  1533. for i in TSymKind:
  1534. var shouldSort = i in routineKinds and groupedToc
  1535. genSection(d, i, shouldSort)
  1536. toc.add(d.toc[i])
  1537. if toc != "" or d.target == outLatex:
  1538. # for Latex $doc.toc will automatically generate TOC if `d.hasToc` is set
  1539. toc = getConfigVar(d.conf, "doc.toc") % ["content", toc]
  1540. for i in TSymKind: code.add(d.section[i].finalMarkup)
  1541. # Extract the title. Non API modules generate an entry in the index table.
  1542. if d.meta[metaTitle].len != 0:
  1543. title = d.meta[metaTitle]
  1544. else:
  1545. title = canonicalImport(d.conf, AbsoluteFile d.filename)
  1546. title = esc(d.target, title)
  1547. var subtitle = ""
  1548. if d.meta[metaSubtitle] != "":
  1549. dispA(d.conf, subtitle, "<h2 class=\"subtitle\">$1</h2>",
  1550. "\\\\\\vspace{0.5em}\\large $1", [esc(d.target, d.meta[metaSubtitle])])
  1551. var groupsection = getConfigVar(d.conf, "doc.body_toc_groupsection")
  1552. let bodyname = if d.hasToc and not d.standaloneDoc and not d.conf.isLatexCmd:
  1553. groupsection.setLen 0
  1554. "doc.body_toc_group"
  1555. elif d.hasToc: "doc.body_toc"
  1556. else: "doc.body_no_toc"
  1557. let seeSrc = genSeeSrc(d, d.filename, 1)
  1558. content = getConfigVar(d.conf, bodyname) % [
  1559. "title", title, "subtitle", subtitle,
  1560. "tableofcontents", toc, "moduledesc", d.modDescFinal, "date", getDateStr(),
  1561. "time", getClockStr(), "content", code,
  1562. "deprecationMsg", d.modDeprecationMsg,
  1563. "theindexhref", relLink(d.conf.outDir, d.destFile.AbsoluteFile,
  1564. theindexFname.RelativeFile),
  1565. "body_toc_groupsection", groupsection, "seeSrc", seeSrc]
  1566. if optCompileOnly notin d.conf.globalOptions:
  1567. # XXX what is this hack doing here? 'optCompileOnly' means raw output!?
  1568. code = getConfigVar(d.conf, "doc.file") % [
  1569. "nimdoccss", relLink(d.conf.outDir, d.destFile.AbsoluteFile,
  1570. nimdocOutCss.RelativeFile),
  1571. "dochackjs", relLink(d.conf.outDir, d.destFile.AbsoluteFile,
  1572. docHackJsFname.RelativeFile),
  1573. "title", title, "subtitle", subtitle, "tableofcontents", toc,
  1574. "moduledesc", d.modDescFinal, "date", getDateStr(), "time", getClockStr(),
  1575. "content", content, "author", d.meta[metaAuthor],
  1576. "version", esc(d.target, d.meta[metaVersion]), "analytics", d.analytics,
  1577. "deprecationMsg", d.modDeprecationMsg]
  1578. else:
  1579. code = content
  1580. result = code
  1581. proc indexFile(d: PDoc): AbsoluteFile =
  1582. let dir = d.conf.outDir
  1583. result = dir / changeFileExt(presentationPath(d.conf,
  1584. AbsoluteFile d.filename),
  1585. IndexExt)
  1586. let (finalDir, _, _) = result.string.splitFile
  1587. createDir(finalDir)
  1588. proc generateIndex*(d: PDoc) =
  1589. if optGenIndex in d.conf.globalOptions:
  1590. let dest = indexFile(d)
  1591. writeIndexFile(d[], dest.string)
  1592. proc updateOutfile(d: PDoc, outfile: AbsoluteFile) =
  1593. if d.module == nil or sfMainModule in d.module.flags: # nil for e.g. for commandRst2Html
  1594. if d.conf.outFile.isEmpty:
  1595. d.conf.outFile = outfile.relativeTo(d.conf.outDir)
  1596. if isAbsolute(d.conf.outFile.string):
  1597. d.conf.outFile = splitPath(d.conf.outFile.string)[1].RelativeFile
  1598. proc writeOutput*(d: PDoc, useWarning = false, groupedToc = false) =
  1599. if optGenIndexOnly in d.conf.globalOptions:
  1600. d.conf.outFile = indexFile(d).relativeTo(d.conf.outDir) # just for display
  1601. return
  1602. runAllExamples(d)
  1603. var content = genOutFile(d, groupedToc)
  1604. if optStdout in d.conf.globalOptions:
  1605. write(stdout, content)
  1606. else:
  1607. template outfile: untyped = d.destFile.AbsoluteFile
  1608. #let outfile = getOutFile2(d.conf, shortenDir(d.conf, filename), outExt)
  1609. let dir = outfile.splitFile.dir
  1610. createDir(dir)
  1611. updateOutfile(d, outfile)
  1612. try:
  1613. writeFile(outfile, content)
  1614. except IOError:
  1615. rawMessage(d.conf, if useWarning: warnCannotOpenFile else: errCannotOpenFile,
  1616. outfile.string)
  1617. if not d.wroteSupportFiles: # nimdoc.css + dochack.js
  1618. let nimr = $d.conf.getPrefixDir()
  1619. case d.target
  1620. of outHtml:
  1621. copyFile(docCss.interp(nimr = nimr), $d.conf.outDir / nimdocOutCss)
  1622. of outLatex:
  1623. copyFile(docCls.interp(nimr = nimr), $d.conf.outDir / nimdocOutCls)
  1624. if optGenIndex in d.conf.globalOptions:
  1625. let docHackJs2 = getDocHacksJs(nimr, nim = getAppFilename())
  1626. copyFile(docHackJs2, $d.conf.outDir / docHackJs2.lastPathPart)
  1627. d.wroteSupportFiles = true
  1628. proc writeOutputJson*(d: PDoc, useWarning = false) =
  1629. runAllExamples(d)
  1630. var modDesc: string
  1631. for desc in d.modDescFinal:
  1632. modDesc &= desc
  1633. let content = %*{"orig": d.filename,
  1634. "nimble": getPackageName(d.conf, d.filename),
  1635. "moduleDescription": modDesc,
  1636. "entries": d.jEntriesFinal}
  1637. if optStdout in d.conf.globalOptions:
  1638. write(stdout, $content)
  1639. else:
  1640. let dir = d.destFile.splitFile.dir
  1641. createDir(dir)
  1642. var f: File
  1643. if open(f, d.destFile, fmWrite):
  1644. write(f, $content)
  1645. close(f)
  1646. updateOutfile(d, d.destFile.AbsoluteFile)
  1647. else:
  1648. localError(d.conf, newLineInfo(d.conf, AbsoluteFile d.filename, -1, -1),
  1649. warnUser, "unable to open file \"" & d.destFile &
  1650. "\" for writing")
  1651. proc handleDocOutputOptions*(conf: ConfigRef) =
  1652. if optWholeProject in conf.globalOptions:
  1653. # Backward compatibility with previous versions
  1654. # xxx this is buggy when user provides `nim doc --project -o:sub/bar.html main`,
  1655. # it'd write to `sub/bar.html/main.html`
  1656. conf.outDir = AbsoluteDir(conf.outDir / conf.outFile)
  1657. proc commandDoc*(cache: IdentCache, conf: ConfigRef) =
  1658. ## implementation of deprecated ``doc0`` command (without semantic checking)
  1659. handleDocOutputOptions conf
  1660. var ast = parseFile(conf.projectMainIdx, cache, conf)
  1661. if ast == nil: return
  1662. var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
  1663. generateDoc(d, ast, ast, conf)
  1664. finishGenerateDoc(d)
  1665. writeOutput(d)
  1666. generateIndex(d)
  1667. proc commandRstAux(cache: IdentCache, conf: ConfigRef;
  1668. filename: AbsoluteFile, outExt: string,
  1669. preferMarkdown: bool) =
  1670. var filen = addFileExt(filename, "txt")
  1671. var d = newDocumentor(filen, cache, conf, outExt, standaloneDoc = true,
  1672. preferMarkdown = preferMarkdown, hasToc = false)
  1673. let rst = parseRst(readFile(filen.string),
  1674. line=LineRstInit, column=ColRstInit,
  1675. conf, d.sharedState)
  1676. d.modDescPre = @[ItemFragment(isRst: true, rst: rst)]
  1677. finishGenerateDoc(d)
  1678. writeOutput(d)
  1679. generateIndex(d)
  1680. proc commandRst2Html*(cache: IdentCache, conf: ConfigRef,
  1681. preferMarkdown=false) =
  1682. commandRstAux(cache, conf, conf.projectFull, HtmlExt, preferMarkdown)
  1683. proc commandRst2TeX*(cache: IdentCache, conf: ConfigRef,
  1684. preferMarkdown=false) =
  1685. commandRstAux(cache, conf, conf.projectFull, TexExt, preferMarkdown)
  1686. proc commandJson*(cache: IdentCache, conf: ConfigRef) =
  1687. ## implementation of a deprecated jsondoc0 command
  1688. var ast = parseFile(conf.projectMainIdx, cache, conf)
  1689. if ast == nil: return
  1690. var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
  1691. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  1692. status: int; content: string) {.gcsafe.} =
  1693. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  1694. warnUser, "the ':test:' attribute is not supported by this backend")
  1695. generateJson(d, ast)
  1696. finishGenerateDoc(d)
  1697. let json = d.jEntriesFinal
  1698. let content = pretty(json)
  1699. if optStdout in d.conf.globalOptions:
  1700. write(stdout, content)
  1701. else:
  1702. #echo getOutFile(gProjectFull, JsonExt)
  1703. let filename = getOutFile(conf, RelativeFile conf.projectName, JsonExt)
  1704. try:
  1705. writeFile(filename, content)
  1706. except IOError:
  1707. rawMessage(conf, errCannotOpenFile, filename.string)
  1708. proc commandTags*(cache: IdentCache, conf: ConfigRef) =
  1709. var ast = parseFile(conf.projectMainIdx, cache, conf)
  1710. if ast == nil: return
  1711. var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
  1712. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  1713. status: int; content: string) {.gcsafe.} =
  1714. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  1715. warnUser, "the ':test:' attribute is not supported by this backend")
  1716. var
  1717. content = ""
  1718. generateTags(d, ast, content)
  1719. if optStdout in d.conf.globalOptions:
  1720. write(stdout, content)
  1721. else:
  1722. #echo getOutFile(gProjectFull, TagsExt)
  1723. let filename = getOutFile(conf, RelativeFile conf.projectName, TagsExt)
  1724. try:
  1725. writeFile(filename, content)
  1726. except IOError:
  1727. rawMessage(conf, errCannotOpenFile, filename.string)
  1728. proc commandBuildIndex*(conf: ConfigRef, dir: string, outFile = RelativeFile"") =
  1729. if optGenIndexOnly in conf.globalOptions:
  1730. return
  1731. var content = mergeIndexes(dir)
  1732. var outFile = outFile
  1733. if outFile.isEmpty: outFile = theindexFname.RelativeFile.changeFileExt("")
  1734. let filename = getOutFile(conf, outFile, HtmlExt)
  1735. let code = getConfigVar(conf, "doc.file") % [
  1736. "nimdoccss", relLink(conf.outDir, filename, nimdocOutCss.RelativeFile),
  1737. "dochackjs", relLink(conf.outDir, filename, docHackJsFname.RelativeFile),
  1738. "title", "Index",
  1739. "subtitle", "", "tableofcontents", "", "moduledesc", "",
  1740. "date", getDateStr(), "time", getClockStr(),
  1741. "content", content, "author", "", "version", "", "analytics", ""]
  1742. # no analytics because context is not available
  1743. try:
  1744. writeFile(filename, code)
  1745. except IOError:
  1746. rawMessage(conf, errCannotOpenFile, filename.string)
  1747. proc commandBuildIndexJson*(conf: ConfigRef, dir: string, outFile = RelativeFile"") =
  1748. var (modules, symbols, docs) = readIndexDir(dir)
  1749. let documents = toSeq(keys(Table[IndexEntry, seq[IndexEntry]](docs)))
  1750. let body = %*({"documents": documents, "modules": modules, "symbols": symbols})
  1751. var outFile = outFile
  1752. if outFile.isEmpty: outFile = theindexFname.RelativeFile.changeFileExt("")
  1753. let filename = getOutFile(conf, outFile, JsonExt)
  1754. try:
  1755. writeFile(filename, $body)
  1756. except IOError:
  1757. rawMessage(conf, errCannotOpenFile, filename.string)