docgen.nim 54 KB

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