docgen.nim 76 KB

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