docgen.nim 70 KB

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