docgen.nim 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. packages/docutils/highlite, sempass2, json, xmltree, cgi,
  17. typesrenderer, astalgo, modulepaths, lineinfos, sequtils, intsets,
  18. pathutils
  19. const
  20. exportSection = skTemp
  21. type
  22. TSections = array[TSymKind, Rope]
  23. TDocumentor = object of rstgen.RstGenerator
  24. modDesc: Rope # module description
  25. toc, section: TSections
  26. indexValFilename: string
  27. analytics: string # Google Analytics javascript, "" if doesn't exist
  28. seenSymbols: StringTableRef # avoids duplicate symbol generation for HTML.
  29. jArray: JsonNode
  30. types: TStrTable
  31. isPureRst: bool
  32. conf*: ConfigRef
  33. cache*: IdentCache
  34. exampleCounter: int
  35. emitted: IntSet # we need to track which symbols have been emitted
  36. # already. See bug #3655
  37. destFile*: AbsoluteFile
  38. thisDir*: AbsoluteDir
  39. PDoc* = ref TDocumentor ## Alias to type less.
  40. proc whichType(d: PDoc; n: PNode): PSym =
  41. if n.kind == nkSym:
  42. if d.types.strTableContains(n.sym):
  43. result = n.sym
  44. else:
  45. for i in 0..<safeLen(n):
  46. let x = whichType(d, n[i])
  47. if x != nil: return x
  48. proc attachToType(d: PDoc; p: PSym): PSym =
  49. let params = p.ast.sons[paramsPos]
  50. template check(i) =
  51. result = whichType(d, params[i])
  52. if result != nil: return result
  53. # first check the first parameter, then the return type,
  54. # then the other parameter:
  55. if params.len > 1: check(1)
  56. if params.len > 0: check(0)
  57. for i in 2..<params.len: check(i)
  58. template declareClosures =
  59. proc compilerMsgHandler(filename: string, line, col: int,
  60. msgKind: rst.MsgKind, arg: string) {.procvar.} =
  61. # translate msg kind:
  62. var k: TMsgKind
  63. case msgKind
  64. of meCannotOpenFile: k = errCannotOpenFile
  65. of meExpected: k = errXExpected
  66. of meGridTableNotImplemented: k = errGridTableNotImplemented
  67. of meNewSectionExpected: k = errNewSectionExpected
  68. of meGeneralParseError: k = errGeneralParseError
  69. of meInvalidDirective: k = errInvalidDirectiveX
  70. of mwRedefinitionOfLabel: k = warnRedefinitionOfLabel
  71. of mwUnknownSubstitution: k = warnUnknownSubstitutionX
  72. of mwUnsupportedLanguage: k = warnLanguageXNotSupported
  73. of mwUnsupportedField: k = warnFieldXNotSupported
  74. globalError(conf, newLineInfo(conf, AbsoluteFile filename, line, col), k, arg)
  75. proc docgenFindFile(s: string): string {.procvar.} =
  76. result = options.findFile(conf, s).string
  77. if result.len == 0:
  78. result = getCurrentDir() / s
  79. if not existsFile(result): result = ""
  80. proc parseRst(text, filename: string,
  81. line, column: int, hasToc: var bool,
  82. rstOptions: RstParseOptions;
  83. conf: ConfigRef): PRstNode =
  84. declareClosures()
  85. result = rstParse(text, filename, line, column, hasToc, rstOptions,
  86. docgenFindFile, compilerMsgHandler)
  87. proc getOutFile2(conf: ConfigRef; filename: RelativeFile,
  88. ext: string, dir: RelativeDir; guessTarget: bool): AbsoluteFile =
  89. if optWholeProject in conf.globalOptions:
  90. # This is correct, for 'nim doc --project' we interpret the '--out' option as an
  91. # absolute directory, not as a filename!
  92. let d = if conf.outFile.isEmpty: conf.projectPath / dir else: AbsoluteDir(conf.outFile)
  93. createDir(d)
  94. result = d / changeFileExt(filename, ext)
  95. elif guessTarget:
  96. let d = if not conf.outFile.isEmpty: splitFile(conf.outFile).dir
  97. else: conf.projectPath
  98. createDir(d)
  99. result = d / changeFileExt(filename, ext)
  100. else:
  101. result = getOutFile(conf, filename, ext)
  102. proc newDocumentor*(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef, outExt: string = HtmlExt): PDoc =
  103. declareClosures()
  104. new(result)
  105. result.conf = conf
  106. result.cache = cache
  107. initRstGenerator(result[], (if conf.cmd != cmdRst2tex: outHtml else: outLatex),
  108. conf.configVars, filename.string, {roSupportRawDirective},
  109. docgenFindFile, compilerMsgHandler)
  110. if conf.configVars.hasKey("doc.googleAnalytics"):
  111. result.analytics = """
  112. <script>
  113. (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  114. (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  115. m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  116. })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  117. ga('create', '$1', 'auto');
  118. ga('send', 'pageview');
  119. </script>
  120. """ % [conf.configVars.getOrDefault"doc.googleAnalytics"]
  121. else:
  122. result.analytics = ""
  123. result.seenSymbols = newStringTable(modeCaseInsensitive)
  124. result.id = 100
  125. result.jArray = newJArray()
  126. initStrTable result.types
  127. result.onTestSnippet =
  128. proc (gen: var RstGenerator; filename, cmd: string; status: int; content: string) =
  129. var d = TDocumentor(gen)
  130. var outp: AbsoluteFile
  131. if filename.len == 0:
  132. inc(d.id)
  133. let nameOnly = splitFile(d.filename).name
  134. let subdir = getNimcacheDir(conf) / RelativeDir(nameOnly)
  135. createDir(subdir)
  136. outp = subdir / RelativeFile(nameOnly & "_snippet_" & $d.id & ".nim")
  137. elif isAbsolute(filename):
  138. outp = AbsoluteFile filename
  139. else:
  140. # Nim's convention: every path is relative to the file it was written in:
  141. outp = splitFile(d.filename).dir.AbsoluteDir / RelativeFile(filename)
  142. # Include the current file if we're parsing a nim file
  143. let importStmt = if d.isPureRst: "" else: "import \"$1\"\n" % [d.filename]
  144. writeFile(outp, importStmt & content)
  145. let c = if cmd.startsWith("nim "): os.getAppFilename() & cmd.substr(3)
  146. else: cmd
  147. let c2 = c % quoteShell(outp)
  148. rawMessage(conf, hintExecuting, c2)
  149. if execShellCmd(c2) != status:
  150. rawMessage(conf, errGenerated, "executing of external program failed: " & c2)
  151. result.emitted = initIntSet()
  152. result.destFile = getOutFile2(conf, relativeTo(filename, conf.projectPath),
  153. outExt, RelativeDir"htmldocs", false)
  154. result.thisDir = result.destFile.splitFile.dir
  155. proc dispA(conf: ConfigRef; dest: var Rope, xml, tex: string, args: openArray[Rope]) =
  156. if conf.cmd != cmdRst2tex: addf(dest, xml, args)
  157. else: addf(dest, tex, args)
  158. proc getVarIdx(varnames: openArray[string], id: string): int =
  159. for i in countup(0, high(varnames)):
  160. if cmpIgnoreStyle(varnames[i], id) == 0:
  161. return i
  162. result = -1
  163. proc ropeFormatNamedVars(conf: ConfigRef; frmt: FormatStr,
  164. varnames: openArray[string],
  165. varvalues: openArray[Rope]): Rope =
  166. var i = 0
  167. var L = len(frmt)
  168. result = nil
  169. var num = 0
  170. while i < L:
  171. if frmt[i] == '$':
  172. inc(i) # skip '$'
  173. case frmt[i]
  174. of '#':
  175. add(result, varvalues[num])
  176. inc(num)
  177. inc(i)
  178. of '$':
  179. add(result, "$")
  180. inc(i)
  181. of '0'..'9':
  182. var j = 0
  183. while true:
  184. j = (j * 10) + ord(frmt[i]) - ord('0')
  185. inc(i)
  186. if (i > L + 0 - 1) or not (frmt[i] in {'0'..'9'}): break
  187. if j > high(varvalues) + 1:
  188. rawMessage(conf, errGenerated, "Invalid format string; too many $s: " & frmt)
  189. num = j
  190. add(result, varvalues[j - 1])
  191. of 'A'..'Z', 'a'..'z', '\x80'..'\xFF':
  192. var id = ""
  193. while true:
  194. add(id, frmt[i])
  195. inc(i)
  196. if not (frmt[i] in {'A'..'Z', '_', 'a'..'z', '\x80'..'\xFF'}): break
  197. var idx = getVarIdx(varnames, id)
  198. if idx >= 0: add(result, varvalues[idx])
  199. else: rawMessage(conf, errGenerated, "unknown substition variable: " & id)
  200. of '{':
  201. var id = ""
  202. inc(i)
  203. while i < frmt.len and frmt[i] != '}':
  204. add(id, frmt[i])
  205. inc(i)
  206. if i >= frmt.len:
  207. rawMessage(conf, errGenerated, "expected closing '}'")
  208. else:
  209. inc(i) # skip }
  210. # search for the variable:
  211. let idx = getVarIdx(varnames, id)
  212. if idx >= 0: add(result, varvalues[idx])
  213. else: rawMessage(conf, errGenerated, "unknown substition variable: " & id)
  214. else:
  215. add(result, "$")
  216. var start = i
  217. while i < L:
  218. if frmt[i] != '$': inc(i)
  219. else: break
  220. if i - 1 >= start: add(result, substr(frmt, start, i - 1))
  221. proc genComment(d: PDoc, n: PNode): string =
  222. result = ""
  223. var dummyHasToc: bool
  224. if n.comment.len > 0:
  225. renderRstToOut(d[], parseRst(n.comment, toFilename(d.conf, n.info),
  226. toLinenumber(n.info), toColumn(n.info),
  227. dummyHasToc, d.options, d.conf), result)
  228. proc genRecCommentAux(d: PDoc, n: PNode): Rope =
  229. if n == nil: return nil
  230. result = genComment(d, n).rope
  231. if result == nil:
  232. if n.kind in {nkStmtList, nkStmtListExpr, nkTypeDef, nkConstDef,
  233. nkObjectTy, nkRefTy, nkPtrTy, nkAsgn, nkFastAsgn}:
  234. # notin {nkEmpty..nkNilLit, nkEnumTy, nkTupleTy}:
  235. for i in countup(0, len(n)-1):
  236. result = genRecCommentAux(d, n.sons[i])
  237. if result != nil: return
  238. else:
  239. when defined(nimNoNilSeqs): n.comment = ""
  240. else: n.comment = nil
  241. proc genRecComment(d: PDoc, n: PNode): Rope =
  242. if n == nil: return nil
  243. result = genComment(d, n).rope
  244. if result == nil:
  245. if n.kind in {nkProcDef, nkFuncDef, nkMethodDef, nkIteratorDef,
  246. nkMacroDef, nkTemplateDef, nkConverterDef}:
  247. result = genRecCommentAux(d, n[bodyPos])
  248. else:
  249. result = genRecCommentAux(d, n)
  250. proc getPlainDocstring(n: PNode): string =
  251. ## Gets the plain text docstring of a node non destructively.
  252. ##
  253. ## You need to call this before genRecComment, whose side effects are removal
  254. ## of comments from the tree. The proc will recursively scan and return all
  255. ## the concatenated ``##`` comments of the node.
  256. result = ""
  257. if n == nil: return
  258. if startsWith(n.comment, "##"):
  259. result = n.comment
  260. if result.len < 1:
  261. for i in countup(0, safeLen(n)-1):
  262. result = getPlainDocstring(n.sons[i])
  263. if result.len > 0: return
  264. proc belongsToPackage(conf: ConfigRef; module: PSym): bool =
  265. result = module.kind == skModule and module.owner != nil and
  266. module.owner.id == conf.mainPackageId
  267. proc externalDep(d: PDoc; module: PSym): string =
  268. if optWholeProject in d.conf.globalOptions:
  269. let full = AbsoluteFile toFullPath(d.conf, FileIndex module.position)
  270. let tmp = getOutFile2(d.conf, full.relativeTo(d.conf.projectPath), HtmlExt,
  271. RelativeDir"htmldocs", sfMainModule notin module.flags)
  272. result = relativeTo(tmp, d.thisDir, '/').string
  273. else:
  274. result = extractFilename toFullPath(d.conf, FileIndex module.position)
  275. proc nodeToHighlightedHtml(d: PDoc; n: PNode; result: var Rope; renderFlags: TRenderFlags = {}) =
  276. var r: TSrcGen
  277. var literal = ""
  278. initTokRender(r, n, renderFlags)
  279. var kind = tkEof
  280. while true:
  281. getNextTok(r, kind, literal)
  282. case kind
  283. of tkEof:
  284. break
  285. of tkComment:
  286. dispA(d.conf, result, "<span class=\"Comment\">$1</span>", "\\spanComment{$1}",
  287. [rope(esc(d.target, literal))])
  288. of tokKeywordLow..tokKeywordHigh:
  289. dispA(d.conf, result, "<span class=\"Keyword\">$1</span>", "\\spanKeyword{$1}",
  290. [rope(literal)])
  291. of tkOpr:
  292. dispA(d.conf, result, "<span class=\"Operator\">$1</span>", "\\spanOperator{$1}",
  293. [rope(esc(d.target, literal))])
  294. of tkStrLit..tkTripleStrLit:
  295. dispA(d.conf, result, "<span class=\"StringLit\">$1</span>",
  296. "\\spanStringLit{$1}", [rope(esc(d.target, literal))])
  297. of tkCharLit:
  298. dispA(d.conf, result, "<span class=\"CharLit\">$1</span>", "\\spanCharLit{$1}",
  299. [rope(esc(d.target, literal))])
  300. of tkIntLit..tkUInt64Lit:
  301. dispA(d.conf, result, "<span class=\"DecNumber\">$1</span>",
  302. "\\spanDecNumber{$1}", [rope(esc(d.target, literal))])
  303. of tkFloatLit..tkFloat128Lit:
  304. dispA(d.conf, result, "<span class=\"FloatNumber\">$1</span>",
  305. "\\spanFloatNumber{$1}", [rope(esc(d.target, literal))])
  306. of tkSymbol:
  307. let s = getTokSym(r)
  308. if s != nil and s.kind == skType and sfExported in s.flags and
  309. s.owner != nil and belongsToPackage(d.conf, s.owner) and
  310. d.target == outHtml:
  311. let external = externalDep(d, s.owner)
  312. result.addf "<a href=\"$1#$2\"><span class=\"Identifier\">$3</span></a>",
  313. [rope changeFileExt(external, "html"), rope literal,
  314. rope(esc(d.target, literal))]
  315. else:
  316. dispA(d.conf, result, "<span class=\"Identifier\">$1</span>",
  317. "\\spanIdentifier{$1}", [rope(esc(d.target, literal))])
  318. of tkSpaces, tkInvalid:
  319. add(result, literal)
  320. of tkCurlyDotLe:
  321. dispA(d.conf, result, "<span>" & # This span is required for the JS to work properly
  322. """<span class="Other">{</span><span class="Other pragmadots">...</span><span class="Other">}</span>
  323. </span>
  324. <span class="pragmawrap">
  325. <span class="Other">$1</span>
  326. <span class="pragma">""".replace("\n", ""), # Must remove newlines because wrapped in a <pre>
  327. "\\spanOther{$1}",
  328. [rope(esc(d.target, literal))])
  329. of tkCurlyDotRi:
  330. dispA(d.conf, result, """
  331. </span>
  332. <span class="Other">$1</span>
  333. </span>""".replace("\n", ""),
  334. "\\spanOther{$1}",
  335. [rope(esc(d.target, literal))])
  336. of tkParLe, tkParRi, tkBracketLe, tkBracketRi, tkCurlyLe, tkCurlyRi,
  337. tkBracketDotLe, tkBracketDotRi, tkParDotLe,
  338. tkParDotRi, tkComma, tkSemiColon, tkColon, tkEquals, tkDot, tkDotDot,
  339. tkAccent, tkColonColon,
  340. tkGStrLit, tkGTripleStrLit, tkInfixOpr, tkPrefixOpr, tkPostfixOpr,
  341. tkBracketLeColon:
  342. dispA(d.conf, result, "<span class=\"Other\">$1</span>", "\\spanOther{$1}",
  343. [rope(esc(d.target, literal))])
  344. proc testExample(d: PDoc; ex: PNode) =
  345. if d.conf.errorCounter > 0: return
  346. let outputDir = d.conf.getNimcacheDir / RelativeDir"runnableExamples"
  347. createDir(outputDir)
  348. inc d.exampleCounter
  349. let outp = outputDir / RelativeFile(extractFilename(d.filename.changeFileExt"" &
  350. "_examples" & $d.exampleCounter & ".nim"))
  351. #let nimcache = outp.changeFileExt"" & "_nimcache"
  352. renderModule(ex, d.filename, outp.string, conf = d.conf)
  353. let backend = if isDefined(d.conf, "js"): "js"
  354. elif isDefined(d.conf, "cpp"): "cpp"
  355. elif isDefined(d.conf, "objc"): "objc"
  356. else: "c"
  357. if os.execShellCmd(os.getAppFilename() & " " & backend &
  358. " --path:" & quoteShell(d.conf.projectPath) &
  359. " --nimcache:" & quoteShell(outputDir) &
  360. " -r " & quoteShell(outp)) != 0:
  361. quit "[Examples] failed: see " & outp.string
  362. else:
  363. # keep generated source file `outp` to allow inspection.
  364. rawMessage(d.conf, hintSuccess, ["runnableExamples: " & outp.string])
  365. removeFile(outp.changeFileExt(ExeExt))
  366. proc extractImports(n: PNode; result: PNode) =
  367. if n.kind in {nkImportStmt, nkImportExceptStmt, nkFromStmt}:
  368. result.add copyTree(n)
  369. n.kind = nkEmpty
  370. return
  371. for i in 0..<n.safeLen: extractImports(n[i], result)
  372. proc prepareExamples(d: PDoc; n: PNode) =
  373. var runnableExamples = newTree(nkStmtList,
  374. newTree(nkImportStmt, newStrNode(nkStrLit, d.filename)))
  375. runnableExamples.info = n.info
  376. let imports = newTree(nkStmtList)
  377. var savedLastSon = copyTree n.lastSon
  378. extractImports(savedLastSon, imports)
  379. for imp in imports: runnableExamples.add imp
  380. runnableExamples.add newTree(nkBlockStmt, newNode(nkEmpty), copyTree savedLastSon)
  381. testExample(d, runnableExamples)
  382. proc getAllRunnableExamplesRec(d: PDoc; n, orig: PNode; dest: var Rope) =
  383. if n.info.fileIndex != orig.info.fileIndex: return
  384. case n.kind
  385. of nkCallKinds:
  386. if isRunnableExamples(n[0]) and
  387. n.len >= 2 and n.lastSon.kind == nkStmtList:
  388. prepareExamples(d, n)
  389. dispA(d.conf, dest, "\n<p><strong class=\"examples_text\">$1</strong></p>\n",
  390. "\n\\textbf{$1}\n", [rope"Examples:"])
  391. inc d.listingCounter
  392. let id = $d.listingCounter
  393. dest.add(d.config.getOrDefault"doc.listing_start" % [id, "langNim"])
  394. # this is a rather hacky way to get rid of the initial indentation
  395. # that the renderer currently produces:
  396. var i = 0
  397. var body = n.lastSon
  398. if body.len == 1 and body.kind == nkStmtList and
  399. body.lastSon.kind == nkStmtList:
  400. body = body.lastSon
  401. for b in body:
  402. if i > 0: dest.add "\n"
  403. inc i
  404. nodeToHighlightedHtml(d, b, dest, {})
  405. dest.add(d.config.getOrDefault"doc.listing_end" % id)
  406. else: discard
  407. for i in 0 ..< n.safeLen:
  408. getAllRunnableExamplesRec(d, n[i], orig, dest)
  409. proc getAllRunnableExamples(d: PDoc; n: PNode; dest: var Rope) =
  410. getAllRunnableExamplesRec(d, n, n, dest)
  411. proc isVisible(d: PDoc; n: PNode): bool =
  412. result = false
  413. if n.kind == nkPostfix:
  414. if n.len == 2 and n.sons[0].kind == nkIdent:
  415. var v = n.sons[0].ident
  416. result = v.id == ord(wStar) or v.id == ord(wMinus)
  417. elif n.kind == nkSym:
  418. # we cannot generate code for forwarded symbols here as we have no
  419. # exception tracking information here. Instead we copy over the comment
  420. # from the proc header.
  421. result = {sfExported, sfFromGeneric, sfForward}*n.sym.flags == {sfExported}
  422. if result and containsOrIncl(d.emitted, n.sym.id):
  423. result = false
  424. elif n.kind == nkPragmaExpr:
  425. result = isVisible(d, n.sons[0])
  426. proc getName(d: PDoc, n: PNode, splitAfter = -1): string =
  427. case n.kind
  428. of nkPostfix: result = getName(d, n.sons[1], splitAfter)
  429. of nkPragmaExpr: result = getName(d, n.sons[0], splitAfter)
  430. of nkSym: result = esc(d.target, n.sym.renderDefinitionName, splitAfter)
  431. of nkIdent: result = esc(d.target, n.ident.s, splitAfter)
  432. of nkAccQuoted:
  433. result = esc(d.target, "`")
  434. for i in 0..<n.len: result.add(getName(d, n[i], splitAfter))
  435. result.add esc(d.target, "`")
  436. of nkOpenSymChoice, nkClosedSymChoice:
  437. result = getName(d, n[0], splitAfter)
  438. else:
  439. result = ""
  440. proc getNameIdent(cache: IdentCache; n: PNode): PIdent =
  441. case n.kind
  442. of nkPostfix: result = getNameIdent(cache, n.sons[1])
  443. of nkPragmaExpr: result = getNameIdent(cache, n.sons[0])
  444. of nkSym: result = n.sym.name
  445. of nkIdent: result = n.ident
  446. of nkAccQuoted:
  447. var r = ""
  448. for i in 0..<n.len: r.add(getNameIdent(cache, n[i]).s)
  449. result = getIdent(cache, r)
  450. of nkOpenSymChoice, nkClosedSymChoice:
  451. result = getNameIdent(cache, n[0])
  452. else:
  453. result = nil
  454. proc getRstName(n: PNode): PRstNode =
  455. case n.kind
  456. of nkPostfix: result = getRstName(n.sons[1])
  457. of nkPragmaExpr: result = getRstName(n.sons[0])
  458. of nkSym: result = newRstNode(rnLeaf, n.sym.renderDefinitionName)
  459. of nkIdent: result = newRstNode(rnLeaf, n.ident.s)
  460. of nkAccQuoted:
  461. result = getRstName(n.sons[0])
  462. for i in 1 ..< n.len: result.text.add(getRstName(n[i]).text)
  463. of nkOpenSymChoice, nkClosedSymChoice:
  464. result = getRstName(n[0])
  465. else:
  466. result = nil
  467. proc newUniquePlainSymbol(d: PDoc, original: string): string =
  468. ## Returns a new unique plain symbol made up from the original.
  469. ##
  470. ## When a collision is found in the seenSymbols table, new numerical variants
  471. ## with underscore + number will be generated.
  472. if not d.seenSymbols.hasKey(original):
  473. result = original
  474. d.seenSymbols[original] = ""
  475. return
  476. # Iterate over possible numeric variants of the original name.
  477. var count = 2
  478. while true:
  479. result = original & "_" & $count
  480. if not d.seenSymbols.hasKey(result):
  481. d.seenSymbols[result] = ""
  482. break
  483. count += 1
  484. proc complexName(k: TSymKind, n: PNode, baseName: string): string =
  485. ## Builds a complex unique href name for the node.
  486. ##
  487. ## Pass as ``baseName`` the plain symbol obtained from the nodeName. The
  488. ## format of the returned symbol will be ``baseName(.callable type)?,(param
  489. ## type)?(,param type)*``. The callable type part will be added only if the
  490. ## node is not a proc, as those are the common ones. The suffix will be a dot
  491. ## and a single letter representing the type of the callable. The parameter
  492. ## types will be added with a preceding dash. Return types won't be added.
  493. ##
  494. ## If you modify the output of this proc, please update the anchor generation
  495. ## section of ``doc/docgen.txt``.
  496. result = baseName
  497. case k:
  498. of skProc, skFunc: result.add(defaultParamSeparator)
  499. of skMacro: result.add(".m" & defaultParamSeparator)
  500. of skMethod: result.add(".e" & defaultParamSeparator)
  501. of skIterator: result.add(".i" & defaultParamSeparator)
  502. of skTemplate: result.add(".t" & defaultParamSeparator)
  503. of skConverter: result.add(".c" & defaultParamSeparator)
  504. else: discard
  505. if len(n) > paramsPos and n[paramsPos].kind == nkFormalParams:
  506. result.add(renderParamTypes(n[paramsPos]))
  507. proc isCallable(n: PNode): bool =
  508. ## Returns true if `n` contains a callable node.
  509. case n.kind
  510. of nkProcDef, nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef,
  511. nkConverterDef, nkFuncDef: result = true
  512. else:
  513. result = false
  514. proc docstringSummary(rstText: string): string =
  515. ## Returns just the first line or a brief chunk of text from a rst string.
  516. ##
  517. ## Most docstrings will contain a one liner summary, so stripping at the
  518. ## first newline is usually fine. If after that the content is still too big,
  519. ## it is stripped at the first comma, colon or dot, usual english sentence
  520. ## separators.
  521. ##
  522. ## No guarantees are made on the size of the output, but it should be small.
  523. ## Also, we hope to not break the rst, but maybe we do. If there is any
  524. ## trimming done, an ellipsis unicode char is added.
  525. const maxDocstringChars = 100
  526. assert(rstText.len < 2 or (rstText[0] == '#' and rstText[1] == '#'))
  527. result = rstText.substr(2).strip
  528. var pos = result.find('\L')
  529. if pos > 0:
  530. result.delete(pos, result.len - 1)
  531. result.add("…")
  532. if pos < maxDocstringChars:
  533. return
  534. # Try to keep trimming at other natural boundaries.
  535. pos = result.find({'.', ',', ':'})
  536. let last = result.len - 1
  537. if pos > 0 and pos < last:
  538. result.delete(pos, last)
  539. result.add("…")
  540. proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind) =
  541. if not isVisible(d, nameNode): return
  542. let
  543. name = getName(d, nameNode)
  544. nameRope = name.rope
  545. var plainDocstring = getPlainDocstring(n) # call here before genRecComment!
  546. var result: Rope = nil
  547. var literal, plainName = ""
  548. var kind = tkEof
  549. var comm = genRecComment(d, n) # call this here for the side-effect!
  550. getAllRunnableExamples(d, n, comm)
  551. var r: TSrcGen
  552. # Obtain the plain rendered string for hyperlink titles.
  553. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments,
  554. renderNoPragmas, renderNoProcDefs})
  555. while true:
  556. getNextTok(r, kind, literal)
  557. if kind == tkEof:
  558. break
  559. plainName.add(literal)
  560. nodeToHighlightedHtml(d, n, result, {renderNoBody, renderNoComments,
  561. renderDocComments, renderSyms})
  562. inc(d.id)
  563. let
  564. plainNameRope = rope(xmltree.escape(plainName.strip))
  565. cleanPlainSymbol = renderPlainSymbolName(nameNode)
  566. complexSymbol = complexName(k, n, cleanPlainSymbol)
  567. plainSymbolRope = rope(cleanPlainSymbol)
  568. plainSymbolEncRope = rope(encodeUrl(cleanPlainSymbol))
  569. itemIDRope = rope(d.id)
  570. symbolOrId = d.newUniquePlainSymbol(complexSymbol)
  571. symbolOrIdRope = symbolOrId.rope
  572. symbolOrIdEncRope = encodeUrl(symbolOrId).rope
  573. var seeSrcRope: Rope = nil
  574. let docItemSeeSrc = getConfigVar(d.conf, "doc.item.seesrc")
  575. if docItemSeeSrc.len > 0:
  576. let path = relativeTo(AbsoluteFile toFullPath(d.conf, n.info), AbsoluteDir getCurrentDir(), '/')
  577. when false:
  578. let cwd = canonicalizePath(d.conf, getCurrentDir())
  579. var path = toFullPath(d.conf, n.info)
  580. if path.startsWith(cwd):
  581. path = path[cwd.len+1 .. ^1].replace('\\', '/')
  582. let gitUrl = getConfigVar(d.conf, "git.url")
  583. if gitUrl.len > 0:
  584. let commit = getConfigVar(d.conf, "git.commit", "master")
  585. let develBranch = getConfigVar(d.conf, "git.devel", "devel")
  586. dispA(d.conf, seeSrcRope, "$1", "", [ropeFormatNamedVars(d.conf, docItemSeeSrc,
  587. ["path", "line", "url", "commit", "devel"], [rope path.string,
  588. rope($n.info.line), rope gitUrl, rope commit, rope develBranch])])
  589. add(d.section[k], ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.item"),
  590. ["name", "header", "desc", "itemID", "header_plain", "itemSym",
  591. "itemSymOrID", "itemSymEnc", "itemSymOrIDEnc", "seeSrc"],
  592. [nameRope, result, comm, itemIDRope, plainNameRope, plainSymbolRope,
  593. symbolOrIdRope, plainSymbolEncRope, symbolOrIdEncRope, seeSrcRope]))
  594. let external = AbsoluteFile(d.filename).relativeTo(d.conf.projectPath, '/').changeFileExt(HtmlExt).string
  595. var attype: Rope
  596. if k in routineKinds and nameNode.kind == nkSym:
  597. let att = attachToType(d, nameNode.sym)
  598. if att != nil:
  599. attype = rope esc(d.target, att.name.s)
  600. elif k == skType and nameNode.kind == nkSym and nameNode.sym.typ.kind in {tyEnum, tyBool}:
  601. let etyp = nameNode.sym.typ
  602. for e in etyp.n:
  603. if e.sym.kind != skEnumField: continue
  604. let plain = renderPlainSymbolName(e)
  605. let symbolOrId = d.newUniquePlainSymbol(plain)
  606. setIndexTerm(d[], external, symbolOrId, plain, nameNode.sym.name.s & '.' & plain,
  607. xmltree.escape(getPlainDocstring(e).docstringSummary))
  608. add(d.toc[k], ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.item.toc"),
  609. ["name", "header", "desc", "itemID", "header_plain", "itemSym",
  610. "itemSymOrID", "itemSymEnc", "itemSymOrIDEnc", "attype"],
  611. [rope(getName(d, nameNode, d.splitAfter)), result, comm,
  612. itemIDRope, plainNameRope, plainSymbolRope, symbolOrIdRope,
  613. plainSymbolEncRope, symbolOrIdEncRope, attype]))
  614. # Ironically for types the complexSymbol is *cleaner* than the plainName
  615. # because it doesn't include object fields or documentation comments. So we
  616. # use the plain one for callable elements, and the complex for the rest.
  617. var linkTitle = changeFileExt(extractFilename(d.filename), "") & ": "
  618. if n.isCallable: linkTitle.add(xmltree.escape(plainName.strip))
  619. else: linkTitle.add(xmltree.escape(complexSymbol.strip))
  620. setIndexTerm(d[], external, symbolOrId, name, linkTitle,
  621. xmltree.escape(plainDocstring.docstringSummary))
  622. if k == skType and nameNode.kind == nkSym:
  623. d.types.strTableAdd nameNode.sym
  624. proc genJsonItem(d: PDoc, n, nameNode: PNode, k: TSymKind): JsonNode =
  625. if not isVisible(d, nameNode): return
  626. var
  627. name = getName(d, nameNode)
  628. comm = $genRecComment(d, n)
  629. r: TSrcGen
  630. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments})
  631. result = %{ "name": %name, "type": %($k), "line": %n.info.line.int,
  632. "col": %n.info.col}
  633. if comm.len > 0:
  634. result["description"] = %comm
  635. if r.buf.len > 0:
  636. result["code"] = %r.buf
  637. proc checkForFalse(n: PNode): bool =
  638. result = n.kind == nkIdent and cmpIgnoreStyle(n.ident.s, "false") == 0
  639. proc traceDeps(d: PDoc, it: PNode) =
  640. const k = skModule
  641. if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
  642. let sep = it[0]
  643. let dir = it[1]
  644. let a = newNodeI(nkInfix, it.info)
  645. a.add sep
  646. a.add dir
  647. a.add sep # dummy entry, replaced in the loop
  648. for x in it[2]:
  649. a.sons[2] = x
  650. traceDeps(d, a)
  651. elif it.kind == nkSym and belongsToPackage(d.conf, it.sym):
  652. let external = externalDep(d, it.sym)
  653. if d.section[k] != nil: add(d.section[k], ", ")
  654. dispA(d.conf, d.section[k],
  655. "<a class=\"reference external\" href=\"$2\">$1</a>",
  656. "$1", [rope esc(d.target, changeFileExt(external, "")),
  657. rope changeFileExt(external, "html")])
  658. proc exportSym(d: PDoc; s: PSym) =
  659. const k = exportSection
  660. if s.kind == skModule and belongsToPackage(d.conf, s):
  661. let external = externalDep(d, s)
  662. if d.section[k] != nil: add(d.section[k], ", ")
  663. dispA(d.conf, d.section[k],
  664. "<a class=\"reference external\" href=\"$2\">$1</a>",
  665. "$1", [rope esc(d.target, changeFileExt(external, "")),
  666. rope changeFileExt(external, "html")])
  667. elif s.kind != skModule and s.owner != nil:
  668. let module = originatingModule(s)
  669. if belongsToPackage(d.conf, module):
  670. let external = externalDep(d, module)
  671. if d.section[k] != nil: add(d.section[k], ", ")
  672. # XXX proper anchor generation here
  673. dispA(d.conf, d.section[k],
  674. "<a href=\"$2#$1\"><span class=\"Identifier\">$1</span></a>",
  675. "$1", [rope esc(d.target, s.name.s),
  676. rope changeFileExt(external, "html")])
  677. proc generateDoc*(d: PDoc, n, orig: PNode) =
  678. case n.kind
  679. of nkCommentStmt: add(d.modDesc, genComment(d, n))
  680. of nkProcDef:
  681. when useEffectSystem: documentRaises(d.cache, n)
  682. genItem(d, n, n.sons[namePos], skProc)
  683. of nkFuncDef:
  684. when useEffectSystem: documentRaises(d.cache, n)
  685. genItem(d, n, n.sons[namePos], skFunc)
  686. of nkMethodDef:
  687. when useEffectSystem: documentRaises(d.cache, n)
  688. genItem(d, n, n.sons[namePos], skMethod)
  689. of nkIteratorDef:
  690. when useEffectSystem: documentRaises(d.cache, n)
  691. genItem(d, n, n.sons[namePos], skIterator)
  692. of nkMacroDef: genItem(d, n, n.sons[namePos], skMacro)
  693. of nkTemplateDef: genItem(d, n, n.sons[namePos], skTemplate)
  694. of nkConverterDef:
  695. when useEffectSystem: documentRaises(d.cache, n)
  696. genItem(d, n, n.sons[namePos], skConverter)
  697. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  698. for i in countup(0, sonsLen(n) - 1):
  699. if n.sons[i].kind != nkCommentStmt:
  700. # order is always 'type var let const':
  701. genItem(d, n.sons[i], n.sons[i].sons[0],
  702. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  703. of nkStmtList:
  704. for i in countup(0, sonsLen(n) - 1): generateDoc(d, n.sons[i], orig)
  705. of nkWhenStmt:
  706. # generate documentation for the first branch only:
  707. if not checkForFalse(n.sons[0].sons[0]):
  708. generateDoc(d, lastSon(n.sons[0]), orig)
  709. of nkImportStmt:
  710. for it in n: traceDeps(d, it)
  711. of nkExportStmt:
  712. for it in n:
  713. if it.kind == nkSym: exportSym(d, it.sym)
  714. of nkExportExceptStmt: discard "transformed into nkExportStmt by semExportExcept"
  715. of nkFromStmt, nkImportExceptStmt: traceDeps(d, n.sons[0])
  716. of nkCallKinds:
  717. var comm: Rope = nil
  718. getAllRunnableExamples(d, n, comm)
  719. if comm != nil: add(d.modDesc, comm)
  720. else: discard
  721. proc add(d: PDoc; j: JsonNode) =
  722. if j != nil: d.jArray.add j
  723. proc generateJson*(d: PDoc, n: PNode, includeComments: bool = true) =
  724. case n.kind
  725. of nkCommentStmt:
  726. if includeComments:
  727. d.add %*{"comment": genComment(d, n)}
  728. else:
  729. add(d.modDesc, genComment(d, n))
  730. of nkProcDef:
  731. when useEffectSystem: documentRaises(d.cache, n)
  732. d.add genJsonItem(d, n, n.sons[namePos], skProc)
  733. of nkFuncDef:
  734. when useEffectSystem: documentRaises(d.cache, n)
  735. d.add genJsonItem(d, n, n.sons[namePos], skFunc)
  736. of nkMethodDef:
  737. when useEffectSystem: documentRaises(d.cache, n)
  738. d.add genJsonItem(d, n, n.sons[namePos], skMethod)
  739. of nkIteratorDef:
  740. when useEffectSystem: documentRaises(d.cache, n)
  741. d.add genJsonItem(d, n, n.sons[namePos], skIterator)
  742. of nkMacroDef:
  743. d.add genJsonItem(d, n, n.sons[namePos], skMacro)
  744. of nkTemplateDef:
  745. d.add genJsonItem(d, n, n.sons[namePos], skTemplate)
  746. of nkConverterDef:
  747. when useEffectSystem: documentRaises(d.cache, n)
  748. d.add genJsonItem(d, n, n.sons[namePos], skConverter)
  749. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  750. for i in countup(0, sonsLen(n) - 1):
  751. if n.sons[i].kind != nkCommentStmt:
  752. # order is always 'type var let const':
  753. d.add genJsonItem(d, n.sons[i], n.sons[i].sons[0],
  754. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  755. of nkStmtList:
  756. for i in countup(0, sonsLen(n) - 1):
  757. generateJson(d, n.sons[i], includeComments)
  758. of nkWhenStmt:
  759. # generate documentation for the first branch only:
  760. if not checkForFalse(n.sons[0].sons[0]):
  761. generateJson(d, lastSon(n.sons[0]), includeComments)
  762. else: discard
  763. proc genTagsItem(d: PDoc, n, nameNode: PNode, k: TSymKind): string =
  764. result = getName(d, nameNode) & "\n"
  765. proc generateTags*(d: PDoc, n: PNode, r: var Rope) =
  766. case n.kind
  767. of nkCommentStmt:
  768. if startsWith(n.comment, "##"):
  769. let stripped = n.comment.substr(2).strip
  770. r.add stripped
  771. of nkProcDef:
  772. when useEffectSystem: documentRaises(d.cache, n)
  773. r.add genTagsItem(d, n, n.sons[namePos], skProc)
  774. of nkFuncDef:
  775. when useEffectSystem: documentRaises(d.cache, n)
  776. r.add genTagsItem(d, n, n.sons[namePos], skFunc)
  777. of nkMethodDef:
  778. when useEffectSystem: documentRaises(d.cache, n)
  779. r.add genTagsItem(d, n, n.sons[namePos], skMethod)
  780. of nkIteratorDef:
  781. when useEffectSystem: documentRaises(d.cache, n)
  782. r.add genTagsItem(d, n, n.sons[namePos], skIterator)
  783. of nkMacroDef:
  784. r.add genTagsItem(d, n, n.sons[namePos], skMacro)
  785. of nkTemplateDef:
  786. r.add genTagsItem(d, n, n.sons[namePos], skTemplate)
  787. of nkConverterDef:
  788. when useEffectSystem: documentRaises(d.cache, n)
  789. r.add genTagsItem(d, n, n.sons[namePos], skConverter)
  790. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  791. for i in countup(0, sonsLen(n) - 1):
  792. if n.sons[i].kind != nkCommentStmt:
  793. # order is always 'type var let const':
  794. r.add genTagsItem(d, n.sons[i], n.sons[i].sons[0],
  795. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  796. of nkStmtList:
  797. for i in countup(0, sonsLen(n) - 1):
  798. generateTags(d, n.sons[i], r)
  799. of nkWhenStmt:
  800. # generate documentation for the first branch only:
  801. if not checkForFalse(n.sons[0].sons[0]):
  802. generateTags(d, lastSon(n.sons[0]), r)
  803. else: discard
  804. proc genSection(d: PDoc, kind: TSymKind) =
  805. const sectionNames: array[skTemp..skTemplate, string] = [
  806. "Exports", "Imports", "Types", "Vars", "Lets", "Consts", "Vars", "Procs", "Funcs",
  807. "Methods", "Iterators", "Converters", "Macros", "Templates"
  808. ]
  809. if d.section[kind] == nil: return
  810. var title = sectionNames[kind].rope
  811. d.section[kind] = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.section"), [
  812. "sectionid", "sectionTitle", "sectionTitleID", "content"], [
  813. ord(kind).rope, title, rope(ord(kind) + 50), d.section[kind]])
  814. d.toc[kind] = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.section.toc"), [
  815. "sectionid", "sectionTitle", "sectionTitleID", "content"], [
  816. ord(kind).rope, title, rope(ord(kind) + 50), d.toc[kind]])
  817. proc genOutFile(d: PDoc): Rope =
  818. var
  819. code, content: Rope
  820. title = ""
  821. var j = 0
  822. var tmp = ""
  823. renderTocEntries(d[], j, 1, tmp)
  824. var toc = tmp.rope
  825. for i in countup(low(TSymKind), high(TSymKind)):
  826. genSection(d, i)
  827. add(toc, d.toc[i])
  828. if toc != nil:
  829. toc = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.toc"), ["content"], [toc])
  830. for i in countup(low(TSymKind), high(TSymKind)): add(code, d.section[i])
  831. # Extract the title. Non API modules generate an entry in the index table.
  832. if d.meta[metaTitle].len != 0:
  833. title = d.meta[metaTitle]
  834. let external = AbsoluteFile(d.filename).relativeTo(d.conf.projectPath, '/').changeFileExt(HtmlExt).string
  835. setIndexTerm(d[], external, "", title)
  836. else:
  837. # Modules get an automatic title for the HTML, but no entry in the index.
  838. title = extractFilename(changeFileExt(d.filename, ""))
  839. let bodyname = if d.hasToc and not d.isPureRst: "doc.body_toc_group"
  840. elif d.hasToc: "doc.body_toc"
  841. else: "doc.body_no_toc"
  842. content = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, bodyname), ["title",
  843. "tableofcontents", "moduledesc", "date", "time", "content"],
  844. [title.rope, toc, d.modDesc, rope(getDateStr()),
  845. rope(getClockStr()), code])
  846. if optCompileOnly notin d.conf.globalOptions:
  847. # XXX what is this hack doing here? 'optCompileOnly' means raw output!?
  848. code = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.file"), ["title",
  849. "tableofcontents", "moduledesc", "date", "time",
  850. "content", "author", "version", "analytics"],
  851. [title.rope, toc, d.modDesc, rope(getDateStr()),
  852. rope(getClockStr()), content, d.meta[metaAuthor].rope,
  853. d.meta[metaVersion].rope, d.analytics.rope])
  854. else:
  855. code = content
  856. result = code
  857. proc generateIndex*(d: PDoc) =
  858. if optGenIndex in d.conf.globalOptions:
  859. let dir = if d.conf.outFile.isEmpty: d.conf.projectPath / RelativeDir"htmldocs"
  860. elif optWholeProject in d.conf.globalOptions: AbsoluteDir(d.conf.outFile)
  861. else: AbsoluteDir(d.conf.outFile.string.splitFile.dir)
  862. createDir(dir)
  863. let dest = dir / changeFileExt(relativeTo(AbsoluteFile d.filename,
  864. d.conf.projectPath), IndexExt)
  865. writeIndexFile(d[], dest.string)
  866. proc writeOutput*(d: PDoc, useWarning = false) =
  867. var content = genOutFile(d)
  868. if optStdout in d.conf.globalOptions:
  869. writeRope(stdout, content)
  870. else:
  871. template outfile: untyped = d.destFile
  872. #let outfile = getOutFile2(d.conf, shortenDir(d.conf, filename), outExt, "htmldocs")
  873. createDir(outfile.splitFile.dir)
  874. if not writeRope(content, outfile):
  875. rawMessage(d.conf, if useWarning: warnCannotOpenFile else: errCannotOpenFile,
  876. outfile.string)
  877. proc writeOutputJson*(d: PDoc, useWarning = false) =
  878. var modDesc: string
  879. for desc in d.modDesc:
  880. modDesc &= desc
  881. let content = %*{"orig": d.filename,
  882. "nimble": getPackageName(d.conf, d.filename),
  883. "moduleDescription": modDesc,
  884. "entries": d.jArray}
  885. if optStdout in d.conf.globalOptions:
  886. write(stdout, $content)
  887. else:
  888. var f: File
  889. if open(f, d.destFile.string, fmWrite):
  890. write(f, $content)
  891. close(f)
  892. else:
  893. localError(d.conf, newLineInfo(d.conf, AbsoluteFile d.filename, -1, -1),
  894. warnUser, "unable to open file \"" & d.destFile.string &
  895. "\" for writing")
  896. proc commandDoc*(cache: IdentCache, conf: ConfigRef) =
  897. var ast = parseFile(conf.projectMainIdx, cache, conf)
  898. if ast == nil: return
  899. var d = newDocumentor(conf.projectFull, cache, conf)
  900. d.hasToc = true
  901. generateDoc(d, ast, ast)
  902. writeOutput(d)
  903. generateIndex(d)
  904. proc commandRstAux(cache: IdentCache, conf: ConfigRef;
  905. filename: AbsoluteFile, outExt: string) =
  906. var filen = addFileExt(filename, "txt")
  907. var d = newDocumentor(filen, cache, conf, outExt)
  908. d.isPureRst = true
  909. var rst = parseRst(readFile(filen.string), filen.string, 0, 1, d.hasToc,
  910. {roSupportRawDirective}, conf)
  911. var modDesc = newStringOfCap(30_000)
  912. renderRstToOut(d[], rst, modDesc)
  913. d.modDesc = rope(modDesc)
  914. writeOutput(d)
  915. generateIndex(d)
  916. proc commandRst2Html*(cache: IdentCache, conf: ConfigRef) =
  917. commandRstAux(cache, conf, conf.projectFull, HtmlExt)
  918. proc commandRst2TeX*(cache: IdentCache, conf: ConfigRef) =
  919. commandRstAux(cache, conf, conf.projectFull, TexExt)
  920. proc commandJson*(cache: IdentCache, conf: ConfigRef) =
  921. var ast = parseFile(conf.projectMainIdx, cache, conf)
  922. if ast == nil: return
  923. var d = newDocumentor(conf.projectFull, cache, conf)
  924. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  925. status: int; content: string) =
  926. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  927. warnUser, "the ':test:' attribute is not supported by this backend")
  928. d.hasToc = true
  929. generateJson(d, ast)
  930. let json = d.jArray
  931. let content = rope(pretty(json))
  932. if optStdout in d.conf.globalOptions:
  933. writeRope(stdout, content)
  934. else:
  935. #echo getOutFile(gProjectFull, JsonExt)
  936. let filename = getOutFile(conf, RelativeFile conf.projectName, JsonExt)
  937. if not writeRope(content, filename):
  938. rawMessage(conf, errCannotOpenFile, filename.string)
  939. proc commandTags*(cache: IdentCache, conf: ConfigRef) =
  940. var ast = parseFile(conf.projectMainIdx, cache, conf)
  941. if ast == nil: return
  942. var d = newDocumentor(conf.projectFull, cache, conf)
  943. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  944. status: int; content: string) =
  945. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  946. warnUser, "the ':test:' attribute is not supported by this backend")
  947. d.hasToc = true
  948. var
  949. content: Rope
  950. generateTags(d, ast, content)
  951. if optStdout in d.conf.globalOptions:
  952. writeRope(stdout, content)
  953. else:
  954. #echo getOutFile(gProjectFull, TagsExt)
  955. let filename = getOutFile(conf, RelativeFile conf.projectName, TagsExt)
  956. if not writeRope(content, filename):
  957. rawMessage(conf, errCannotOpenFile, filename.string)
  958. proc commandBuildIndex*(cache: IdentCache, conf: ConfigRef) =
  959. var content = mergeIndexes(conf.projectFull.string).rope
  960. let code = ropeFormatNamedVars(conf, getConfigVar(conf, "doc.file"), ["title",
  961. "tableofcontents", "moduledesc", "date", "time",
  962. "content", "author", "version", "analytics"],
  963. ["Index".rope, nil, nil, rope(getDateStr()),
  964. rope(getClockStr()), content, nil, nil, nil])
  965. # no analytics because context is not available
  966. let filename = getOutFile(conf, RelativeFile"theindex", HtmlExt)
  967. if not writeRope(code, filename):
  968. rawMessage(conf, errCannotOpenFile, filename.string)