docgen.nim 61 KB

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