docgen.nim 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 genRecComment(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 notin {nkEmpty..nkNilLit, nkEnumTy, nkTupleTy}:
  233. for i in countup(0, len(n)-1):
  234. result = genRecComment(d, n.sons[i])
  235. if result != nil: return
  236. else:
  237. when defined(nimNoNilSeqs): n.comment = ""
  238. else: n.comment = nil
  239. proc getPlainDocstring(n: PNode): string =
  240. ## Gets the plain text docstring of a node non destructively.
  241. ##
  242. ## You need to call this before genRecComment, whose side effects are removal
  243. ## of comments from the tree. The proc will recursively scan and return all
  244. ## the concatenated ``##`` comments of the node.
  245. result = ""
  246. if n == nil: return
  247. if startsWith(n.comment, "##"):
  248. result = n.comment
  249. if result.len < 1:
  250. for i in countup(0, safeLen(n)-1):
  251. result = getPlainDocstring(n.sons[i])
  252. if result.len > 0: return
  253. proc belongsToPackage(conf: ConfigRef; module: PSym): bool =
  254. result = module.kind == skModule and module.owner != nil and
  255. module.owner.id == conf.mainPackageId
  256. proc externalDep(d: PDoc; module: PSym): string =
  257. if optWholeProject in d.conf.globalOptions:
  258. let full = AbsoluteFile toFullPath(d.conf, FileIndex module.position)
  259. let tmp = getOutFile2(d.conf, full.relativeTo(d.conf.projectPath), HtmlExt,
  260. RelativeDir"htmldocs", sfMainModule notin module.flags)
  261. result = relativeTo(tmp, d.thisDir, '/').string
  262. else:
  263. result = extractFilename toFullPath(d.conf, FileIndex module.position)
  264. proc nodeToHighlightedHtml(d: PDoc; n: PNode; result: var Rope; renderFlags: TRenderFlags = {}) =
  265. var r: TSrcGen
  266. var literal = ""
  267. initTokRender(r, n, renderFlags)
  268. var kind = tkEof
  269. while true:
  270. getNextTok(r, kind, literal)
  271. case kind
  272. of tkEof:
  273. break
  274. of tkComment:
  275. dispA(d.conf, result, "<span class=\"Comment\">$1</span>", "\\spanComment{$1}",
  276. [rope(esc(d.target, literal))])
  277. of tokKeywordLow..tokKeywordHigh:
  278. dispA(d.conf, result, "<span class=\"Keyword\">$1</span>", "\\spanKeyword{$1}",
  279. [rope(literal)])
  280. of tkOpr:
  281. dispA(d.conf, result, "<span class=\"Operator\">$1</span>", "\\spanOperator{$1}",
  282. [rope(esc(d.target, literal))])
  283. of tkStrLit..tkTripleStrLit:
  284. dispA(d.conf, result, "<span class=\"StringLit\">$1</span>",
  285. "\\spanStringLit{$1}", [rope(esc(d.target, literal))])
  286. of tkCharLit:
  287. dispA(d.conf, result, "<span class=\"CharLit\">$1</span>", "\\spanCharLit{$1}",
  288. [rope(esc(d.target, literal))])
  289. of tkIntLit..tkUInt64Lit:
  290. dispA(d.conf, result, "<span class=\"DecNumber\">$1</span>",
  291. "\\spanDecNumber{$1}", [rope(esc(d.target, literal))])
  292. of tkFloatLit..tkFloat128Lit:
  293. dispA(d.conf, result, "<span class=\"FloatNumber\">$1</span>",
  294. "\\spanFloatNumber{$1}", [rope(esc(d.target, literal))])
  295. of tkSymbol:
  296. let s = getTokSym(r)
  297. if s != nil and s.kind == skType and sfExported in s.flags and
  298. s.owner != nil and belongsToPackage(d.conf, s.owner) and
  299. d.target == outHtml:
  300. let external = externalDep(d, s.owner)
  301. result.addf "<a href=\"$1#$2\"><span class=\"Identifier\">$3</span></a>",
  302. [rope changeFileExt(external, "html"), rope literal,
  303. rope(esc(d.target, literal))]
  304. else:
  305. dispA(d.conf, result, "<span class=\"Identifier\">$1</span>",
  306. "\\spanIdentifier{$1}", [rope(esc(d.target, literal))])
  307. of tkSpaces, tkInvalid:
  308. add(result, literal)
  309. of tkCurlyDotLe:
  310. dispA(d.conf, result, "<span>" & # This span is required for the JS to work properly
  311. """<span class="Other">{</span><span class="Other pragmadots">...</span><span class="Other">}</span>
  312. </span>
  313. <span class="pragmawrap">
  314. <span class="Other">$1</span>
  315. <span class="pragma">""".replace("\n", ""), # Must remove newlines because wrapped in a <pre>
  316. "\\spanOther{$1}",
  317. [rope(esc(d.target, literal))])
  318. of tkCurlyDotRi:
  319. dispA(d.conf, result, """
  320. </span>
  321. <span class="Other">$1</span>
  322. </span>""".replace("\n", ""),
  323. "\\spanOther{$1}",
  324. [rope(esc(d.target, literal))])
  325. of tkParLe, tkParRi, tkBracketLe, tkBracketRi, tkCurlyLe, tkCurlyRi,
  326. tkBracketDotLe, tkBracketDotRi, tkParDotLe,
  327. tkParDotRi, tkComma, tkSemiColon, tkColon, tkEquals, tkDot, tkDotDot,
  328. tkAccent, tkColonColon,
  329. tkGStrLit, tkGTripleStrLit, tkInfixOpr, tkPrefixOpr, tkPostfixOpr,
  330. tkBracketLeColon:
  331. dispA(d.conf, result, "<span class=\"Other\">$1</span>", "\\spanOther{$1}",
  332. [rope(esc(d.target, literal))])
  333. proc testExample(d: PDoc; ex: PNode) =
  334. if d.conf.errorCounter > 0: return
  335. let outputDir = d.conf.getNimcacheDir / RelativeDir"runnableExamples"
  336. createDir(outputDir)
  337. inc d.exampleCounter
  338. let outp = outputDir / RelativeFile(extractFilename(d.filename.changeFileExt"" &
  339. "_examples" & $d.exampleCounter & ".nim"))
  340. #let nimcache = outp.changeFileExt"" & "_nimcache"
  341. renderModule(ex, d.filename, outp.string, conf = d.conf)
  342. let backend = if isDefined(d.conf, "js"): "js"
  343. elif isDefined(d.conf, "cpp"): "cpp"
  344. elif isDefined(d.conf, "objc"): "objc"
  345. else: "c"
  346. if os.execShellCmd(os.getAppFilename() & " " & backend &
  347. " --path:" & quoteShell(d.conf.projectPath) &
  348. " --nimcache:" & quoteShell(outputDir) &
  349. " -r " & quoteShell(outp)) != 0:
  350. quit "[Examples] failed: see " & outp.string
  351. else:
  352. # keep generated source file `outp` to allow inspection.
  353. rawMessage(d.conf, hintSuccess, ["runnableExamples: " & outp.string])
  354. removeFile(outp.changeFileExt(ExeExt))
  355. proc extractImports(n: PNode; result: PNode) =
  356. if n.kind in {nkImportStmt, nkImportExceptStmt, nkFromStmt}:
  357. result.add copyTree(n)
  358. n.kind = nkEmpty
  359. return
  360. for i in 0..<n.safeLen: extractImports(n[i], result)
  361. proc prepareExamples(d: PDoc; n: PNode) =
  362. var runnableExamples = newTree(nkStmtList,
  363. newTree(nkImportStmt, newStrNode(nkStrLit, d.filename)))
  364. runnableExamples.info = n.info
  365. let imports = newTree(nkStmtList)
  366. var savedLastSon = copyTree n.lastSon
  367. extractImports(savedLastSon, imports)
  368. for imp in imports: runnableExamples.add imp
  369. runnableExamples.add newTree(nkBlockStmt, newNode(nkEmpty), copyTree savedLastSon)
  370. testExample(d, runnableExamples)
  371. proc getAllRunnableExamplesRec(d: PDoc; n, orig: PNode; dest: var Rope) =
  372. if n.info.fileIndex != orig.info.fileIndex: return
  373. case n.kind
  374. of nkCallKinds:
  375. if isRunnableExamples(n[0]) and
  376. n.len >= 2 and n.lastSon.kind == nkStmtList:
  377. prepareExamples(d, n)
  378. dispA(d.conf, dest, "\n<p><strong class=\"examples_text\">$1</strong></p>\n",
  379. "\n\\textbf{$1}\n", [rope"Examples:"])
  380. inc d.listingCounter
  381. let id = $d.listingCounter
  382. dest.add(d.config.getOrDefault"doc.listing_start" % [id, "langNim"])
  383. # this is a rather hacky way to get rid of the initial indentation
  384. # that the renderer currently produces:
  385. var i = 0
  386. var body = n.lastSon
  387. if body.len == 1 and body.kind == nkStmtList and
  388. body.lastSon.kind == nkStmtList:
  389. body = body.lastSon
  390. for b in body:
  391. if i > 0: dest.add "\n"
  392. inc i
  393. nodeToHighlightedHtml(d, b, dest, {})
  394. dest.add(d.config.getOrDefault"doc.listing_end" % id)
  395. else: discard
  396. for i in 0 ..< n.safeLen:
  397. getAllRunnableExamplesRec(d, n[i], orig, dest)
  398. proc getAllRunnableExamples(d: PDoc; n: PNode; dest: var Rope) =
  399. getAllRunnableExamplesRec(d, n, n, dest)
  400. when false:
  401. proc findDocComment(n: PNode): PNode =
  402. if n == nil: return nil
  403. if not isNil(n.comment) and startsWith(n.comment, "##"): return n
  404. for i in countup(0, safeLen(n)-1):
  405. result = findDocComment(n.sons[i])
  406. if result != nil: return
  407. proc extractDocComment*(s: PSym, d: PDoc): string =
  408. let n = findDocComment(s.ast)
  409. result = ""
  410. if not n.isNil:
  411. if not d.isNil:
  412. var dummyHasToc: bool
  413. renderRstToOut(d[], parseRst(n.comment, toFilename(d.conf, n.info),
  414. toLinenumber(n.info), toColumn(n.info),
  415. dummyHasToc, d.options + {roSkipPounds}),
  416. result)
  417. else:
  418. result = n.comment.substr(2).replace("\n##", "\n").strip
  419. proc isVisible(d: PDoc; n: PNode): bool =
  420. result = false
  421. if n.kind == nkPostfix:
  422. if n.len == 2 and n.sons[0].kind == nkIdent:
  423. var v = n.sons[0].ident
  424. result = v.id == ord(wStar) or v.id == ord(wMinus)
  425. elif n.kind == nkSym:
  426. # we cannot generate code for forwarded symbols here as we have no
  427. # exception tracking information here. Instead we copy over the comment
  428. # from the proc header.
  429. result = {sfExported, sfFromGeneric, sfForward}*n.sym.flags == {sfExported}
  430. if result and containsOrIncl(d.emitted, n.sym.id):
  431. result = false
  432. elif n.kind == nkPragmaExpr:
  433. result = isVisible(d, n.sons[0])
  434. proc getName(d: PDoc, n: PNode, splitAfter = -1): string =
  435. case n.kind
  436. of nkPostfix: result = getName(d, n.sons[1], splitAfter)
  437. of nkPragmaExpr: result = getName(d, n.sons[0], splitAfter)
  438. of nkSym: result = esc(d.target, n.sym.renderDefinitionName, splitAfter)
  439. of nkIdent: result = esc(d.target, n.ident.s, splitAfter)
  440. of nkAccQuoted:
  441. result = esc(d.target, "`")
  442. for i in 0..<n.len: result.add(getName(d, n[i], splitAfter))
  443. result.add esc(d.target, "`")
  444. of nkOpenSymChoice, nkClosedSymChoice:
  445. result = getName(d, n[0], splitAfter)
  446. else:
  447. result = ""
  448. proc getNameIdent(cache: IdentCache; n: PNode): PIdent =
  449. case n.kind
  450. of nkPostfix: result = getNameIdent(cache, n.sons[1])
  451. of nkPragmaExpr: result = getNameIdent(cache, n.sons[0])
  452. of nkSym: result = n.sym.name
  453. of nkIdent: result = n.ident
  454. of nkAccQuoted:
  455. var r = ""
  456. for i in 0..<n.len: r.add(getNameIdent(cache, n[i]).s)
  457. result = getIdent(cache, r)
  458. of nkOpenSymChoice, nkClosedSymChoice:
  459. result = getNameIdent(cache, n[0])
  460. else:
  461. result = nil
  462. proc getRstName(n: PNode): PRstNode =
  463. case n.kind
  464. of nkPostfix: result = getRstName(n.sons[1])
  465. of nkPragmaExpr: result = getRstName(n.sons[0])
  466. of nkSym: result = newRstNode(rnLeaf, n.sym.renderDefinitionName)
  467. of nkIdent: result = newRstNode(rnLeaf, n.ident.s)
  468. of nkAccQuoted:
  469. result = getRstName(n.sons[0])
  470. for i in 1 ..< n.len: result.text.add(getRstName(n[i]).text)
  471. of nkOpenSymChoice, nkClosedSymChoice:
  472. result = getRstName(n[0])
  473. else:
  474. result = nil
  475. proc newUniquePlainSymbol(d: PDoc, original: string): string =
  476. ## Returns a new unique plain symbol made up from the original.
  477. ##
  478. ## When a collision is found in the seenSymbols table, new numerical variants
  479. ## with underscore + number will be generated.
  480. if not d.seenSymbols.hasKey(original):
  481. result = original
  482. d.seenSymbols[original] = ""
  483. return
  484. # Iterate over possible numeric variants of the original name.
  485. var count = 2
  486. while true:
  487. result = original & "_" & $count
  488. if not d.seenSymbols.hasKey(result):
  489. d.seenSymbols[result] = ""
  490. break
  491. count += 1
  492. proc complexName(k: TSymKind, n: PNode, baseName: string): string =
  493. ## Builds a complex unique href name for the node.
  494. ##
  495. ## Pass as ``baseName`` the plain symbol obtained from the nodeName. The
  496. ## format of the returned symbol will be ``baseName(.callable type)?,(param
  497. ## type)?(,param type)*``. The callable type part will be added only if the
  498. ## node is not a proc, as those are the common ones. The suffix will be a dot
  499. ## and a single letter representing the type of the callable. The parameter
  500. ## types will be added with a preceding dash. Return types won't be added.
  501. ##
  502. ## If you modify the output of this proc, please update the anchor generation
  503. ## section of ``doc/docgen.txt``.
  504. result = baseName
  505. case k:
  506. of skProc, skFunc: result.add(defaultParamSeparator)
  507. of skMacro: result.add(".m" & defaultParamSeparator)
  508. of skMethod: result.add(".e" & defaultParamSeparator)
  509. of skIterator: result.add(".i" & defaultParamSeparator)
  510. of skTemplate: result.add(".t" & defaultParamSeparator)
  511. of skConverter: result.add(".c" & defaultParamSeparator)
  512. else: discard
  513. if len(n) > paramsPos and n[paramsPos].kind == nkFormalParams:
  514. result.add(renderParamTypes(n[paramsPos]))
  515. proc isCallable(n: PNode): bool =
  516. ## Returns true if `n` contains a callable node.
  517. case n.kind
  518. of nkProcDef, nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef,
  519. nkConverterDef, nkFuncDef: result = true
  520. else:
  521. result = false
  522. proc docstringSummary(rstText: string): string =
  523. ## Returns just the first line or a brief chunk of text from a rst string.
  524. ##
  525. ## Most docstrings will contain a one liner summary, so stripping at the
  526. ## first newline is usually fine. If after that the content is still too big,
  527. ## it is stripped at the first comma, colon or dot, usual english sentence
  528. ## separators.
  529. ##
  530. ## No guarantees are made on the size of the output, but it should be small.
  531. ## Also, we hope to not break the rst, but maybe we do. If there is any
  532. ## trimming done, an ellipsis unicode char is added.
  533. const maxDocstringChars = 100
  534. assert(rstText.len < 2 or (rstText[0] == '#' and rstText[1] == '#'))
  535. result = rstText.substr(2).strip
  536. var pos = result.find('\L')
  537. if pos > 0:
  538. result.delete(pos, result.len - 1)
  539. result.add("…")
  540. if pos < maxDocstringChars:
  541. return
  542. # Try to keep trimming at other natural boundaries.
  543. pos = result.find({'.', ',', ':'})
  544. let last = result.len - 1
  545. if pos > 0 and pos < last:
  546. result.delete(pos, last)
  547. result.add("…")
  548. proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind) =
  549. if not isVisible(d, nameNode): return
  550. let
  551. name = getName(d, nameNode)
  552. nameRope = name.rope
  553. var plainDocstring = getPlainDocstring(n) # call here before genRecComment!
  554. var result: Rope = nil
  555. var literal, plainName = ""
  556. var kind = tkEof
  557. var comm = genRecComment(d, n) # call this here for the side-effect!
  558. getAllRunnableExamples(d, n, comm)
  559. var r: TSrcGen
  560. # Obtain the plain rendered string for hyperlink titles.
  561. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments,
  562. renderNoPragmas, renderNoProcDefs})
  563. while true:
  564. getNextTok(r, kind, literal)
  565. if kind == tkEof:
  566. break
  567. plainName.add(literal)
  568. nodeToHighlightedHtml(d, n, result, {renderNoBody, renderNoComments,
  569. renderDocComments, renderSyms})
  570. inc(d.id)
  571. let
  572. plainNameRope = rope(xmltree.escape(plainName.strip))
  573. cleanPlainSymbol = renderPlainSymbolName(nameNode)
  574. complexSymbol = complexName(k, n, cleanPlainSymbol)
  575. plainSymbolRope = rope(cleanPlainSymbol)
  576. plainSymbolEncRope = rope(encodeUrl(cleanPlainSymbol))
  577. itemIDRope = rope(d.id)
  578. symbolOrId = d.newUniquePlainSymbol(complexSymbol)
  579. symbolOrIdRope = symbolOrId.rope
  580. symbolOrIdEncRope = encodeUrl(symbolOrId).rope
  581. var seeSrcRope: Rope = nil
  582. let docItemSeeSrc = getConfigVar(d.conf, "doc.item.seesrc")
  583. if docItemSeeSrc.len > 0:
  584. let path = relativeTo(AbsoluteFile toFullPath(d.conf, n.info), AbsoluteDir getCurrentDir(), '/')
  585. when false:
  586. let cwd = canonicalizePath(d.conf, getCurrentDir())
  587. var path = toFullPath(d.conf, n.info)
  588. if path.startsWith(cwd):
  589. path = path[cwd.len+1 .. ^1].replace('\\', '/')
  590. let gitUrl = getConfigVar(d.conf, "git.url")
  591. if gitUrl.len > 0:
  592. let commit = getConfigVar(d.conf, "git.commit", "master")
  593. let develBranch = getConfigVar(d.conf, "git.devel", "devel")
  594. dispA(d.conf, seeSrcRope, "$1", "", [ropeFormatNamedVars(d.conf, docItemSeeSrc,
  595. ["path", "line", "url", "commit", "devel"], [rope path.string,
  596. rope($n.info.line), rope gitUrl, rope commit, rope develBranch])])
  597. add(d.section[k], ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.item"),
  598. ["name", "header", "desc", "itemID", "header_plain", "itemSym",
  599. "itemSymOrID", "itemSymEnc", "itemSymOrIDEnc", "seeSrc"],
  600. [nameRope, result, comm, itemIDRope, plainNameRope, plainSymbolRope,
  601. symbolOrIdRope, plainSymbolEncRope, symbolOrIdEncRope, seeSrcRope]))
  602. let external = AbsoluteFile(d.filename).relativeTo(d.conf.projectPath, '/').changeFileExt(HtmlExt).string
  603. var attype: Rope
  604. if k in routineKinds and nameNode.kind == nkSym:
  605. let att = attachToType(d, nameNode.sym)
  606. if att != nil:
  607. attype = rope esc(d.target, att.name.s)
  608. elif k == skType and nameNode.kind == nkSym and nameNode.sym.typ.kind in {tyEnum, tyBool}:
  609. let etyp = nameNode.sym.typ
  610. for e in etyp.n:
  611. if e.sym.kind != skEnumField: continue
  612. let plain = renderPlainSymbolName(e)
  613. let symbolOrId = d.newUniquePlainSymbol(plain)
  614. setIndexTerm(d[], external, symbolOrId, plain, nameNode.sym.name.s & '.' & plain,
  615. xmltree.escape(getPlainDocstring(e).docstringSummary))
  616. add(d.toc[k], ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.item.toc"),
  617. ["name", "header", "desc", "itemID", "header_plain", "itemSym",
  618. "itemSymOrID", "itemSymEnc", "itemSymOrIDEnc", "attype"],
  619. [rope(getName(d, nameNode, d.splitAfter)), result, comm,
  620. itemIDRope, plainNameRope, plainSymbolRope, symbolOrIdRope,
  621. plainSymbolEncRope, symbolOrIdEncRope, attype]))
  622. # Ironically for types the complexSymbol is *cleaner* than the plainName
  623. # because it doesn't include object fields or documentation comments. So we
  624. # use the plain one for callable elements, and the complex for the rest.
  625. var linkTitle = changeFileExt(extractFilename(d.filename), "") & ": "
  626. if n.isCallable: linkTitle.add(xmltree.escape(plainName.strip))
  627. else: linkTitle.add(xmltree.escape(complexSymbol.strip))
  628. setIndexTerm(d[], external, symbolOrId, name, linkTitle,
  629. xmltree.escape(plainDocstring.docstringSummary))
  630. if k == skType and nameNode.kind == nkSym:
  631. d.types.strTableAdd nameNode.sym
  632. proc genJsonItem(d: PDoc, n, nameNode: PNode, k: TSymKind): JsonNode =
  633. if not isVisible(d, nameNode): return
  634. var
  635. name = getName(d, nameNode)
  636. comm = $genRecComment(d, n)
  637. r: TSrcGen
  638. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments})
  639. result = %{ "name": %name, "type": %($k), "line": %n.info.line.int,
  640. "col": %n.info.col}
  641. if comm.len > 0:
  642. result["description"] = %comm
  643. if r.buf.len > 0:
  644. result["code"] = %r.buf
  645. proc checkForFalse(n: PNode): bool =
  646. result = n.kind == nkIdent and cmpIgnoreStyle(n.ident.s, "false") == 0
  647. proc traceDeps(d: PDoc, it: PNode) =
  648. const k = skModule
  649. if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
  650. let sep = it[0]
  651. let dir = it[1]
  652. let a = newNodeI(nkInfix, it.info)
  653. a.add sep
  654. a.add dir
  655. a.add sep # dummy entry, replaced in the loop
  656. for x in it[2]:
  657. a.sons[2] = x
  658. traceDeps(d, a)
  659. elif it.kind == nkSym and belongsToPackage(d.conf, it.sym):
  660. let external = externalDep(d, it.sym)
  661. if d.section[k] != nil: add(d.section[k], ", ")
  662. dispA(d.conf, d.section[k],
  663. "<a class=\"reference external\" href=\"$2\">$1</a>",
  664. "$1", [rope esc(d.target, changeFileExt(external, "")),
  665. rope changeFileExt(external, "html")])
  666. proc exportSym(d: PDoc; s: PSym) =
  667. const k = exportSection
  668. if s.kind == skModule and belongsToPackage(d.conf, s):
  669. let external = externalDep(d, s)
  670. if d.section[k] != nil: add(d.section[k], ", ")
  671. dispA(d.conf, d.section[k],
  672. "<a class=\"reference external\" href=\"$2\">$1</a>",
  673. "$1", [rope esc(d.target, changeFileExt(external, "")),
  674. rope changeFileExt(external, "html")])
  675. elif s.kind != skModule and s.owner != nil:
  676. let module = originatingModule(s)
  677. if belongsToPackage(d.conf, module):
  678. let external = externalDep(d, module)
  679. if d.section[k] != nil: add(d.section[k], ", ")
  680. # XXX proper anchor generation here
  681. dispA(d.conf, d.section[k],
  682. "<a href=\"$2#$1\"><span class=\"Identifier\">$1</span></a>",
  683. "$1", [rope esc(d.target, s.name.s),
  684. rope changeFileExt(external, "html")])
  685. proc generateDoc*(d: PDoc, n, orig: PNode) =
  686. if orig.info.fileIndex != n.info.fileIndex: return
  687. case n.kind
  688. of nkCommentStmt: add(d.modDesc, genComment(d, n))
  689. of nkProcDef:
  690. when useEffectSystem: documentRaises(d.cache, n)
  691. genItem(d, n, n.sons[namePos], skProc)
  692. of nkFuncDef:
  693. when useEffectSystem: documentRaises(d.cache, n)
  694. genItem(d, n, n.sons[namePos], skFunc)
  695. of nkMethodDef:
  696. when useEffectSystem: documentRaises(d.cache, n)
  697. genItem(d, n, n.sons[namePos], skMethod)
  698. of nkIteratorDef:
  699. when useEffectSystem: documentRaises(d.cache, n)
  700. genItem(d, n, n.sons[namePos], skIterator)
  701. of nkMacroDef: genItem(d, n, n.sons[namePos], skMacro)
  702. of nkTemplateDef: genItem(d, n, n.sons[namePos], skTemplate)
  703. of nkConverterDef:
  704. when useEffectSystem: documentRaises(d.cache, n)
  705. genItem(d, n, n.sons[namePos], skConverter)
  706. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  707. for i in countup(0, sonsLen(n) - 1):
  708. if n.sons[i].kind != nkCommentStmt:
  709. # order is always 'type var let const':
  710. genItem(d, n.sons[i], n.sons[i].sons[0],
  711. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  712. of nkStmtList:
  713. for i in countup(0, sonsLen(n) - 1): generateDoc(d, n.sons[i], orig)
  714. of nkWhenStmt:
  715. # generate documentation for the first branch only:
  716. if not checkForFalse(n.sons[0].sons[0]):
  717. generateDoc(d, lastSon(n.sons[0]), orig)
  718. of nkImportStmt:
  719. for it in n: traceDeps(d, it)
  720. of nkExportStmt:
  721. for it in n:
  722. if it.kind == nkSym: exportSym(d, it.sym)
  723. of nkExportExceptStmt: discard "transformed into nkExportStmt by semExportExcept"
  724. of nkFromStmt, nkImportExceptStmt: traceDeps(d, n.sons[0])
  725. of nkCallKinds:
  726. var comm: Rope = nil
  727. getAllRunnableExamples(d, n, comm)
  728. if comm != nil: add(d.modDesc, comm)
  729. else: discard
  730. proc add(d: PDoc; j: JsonNode) =
  731. if j != nil: d.jArray.add j
  732. proc generateJson*(d: PDoc, n: PNode, includeComments: bool = true) =
  733. case n.kind
  734. of nkCommentStmt:
  735. if includeComments:
  736. d.add %*{"comment": genComment(d, n)}
  737. else:
  738. add(d.modDesc, genComment(d, n))
  739. of nkProcDef:
  740. when useEffectSystem: documentRaises(d.cache, n)
  741. d.add genJsonItem(d, n, n.sons[namePos], skProc)
  742. of nkFuncDef:
  743. when useEffectSystem: documentRaises(d.cache, n)
  744. d.add genJsonItem(d, n, n.sons[namePos], skFunc)
  745. of nkMethodDef:
  746. when useEffectSystem: documentRaises(d.cache, n)
  747. d.add genJsonItem(d, n, n.sons[namePos], skMethod)
  748. of nkIteratorDef:
  749. when useEffectSystem: documentRaises(d.cache, n)
  750. d.add genJsonItem(d, n, n.sons[namePos], skIterator)
  751. of nkMacroDef:
  752. d.add genJsonItem(d, n, n.sons[namePos], skMacro)
  753. of nkTemplateDef:
  754. d.add genJsonItem(d, n, n.sons[namePos], skTemplate)
  755. of nkConverterDef:
  756. when useEffectSystem: documentRaises(d.cache, n)
  757. d.add genJsonItem(d, n, n.sons[namePos], skConverter)
  758. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  759. for i in countup(0, sonsLen(n) - 1):
  760. if n.sons[i].kind != nkCommentStmt:
  761. # order is always 'type var let const':
  762. d.add genJsonItem(d, n.sons[i], n.sons[i].sons[0],
  763. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  764. of nkStmtList:
  765. for i in countup(0, sonsLen(n) - 1):
  766. generateJson(d, n.sons[i], includeComments)
  767. of nkWhenStmt:
  768. # generate documentation for the first branch only:
  769. if not checkForFalse(n.sons[0].sons[0]):
  770. generateJson(d, lastSon(n.sons[0]), includeComments)
  771. else: discard
  772. proc genTagsItem(d: PDoc, n, nameNode: PNode, k: TSymKind): string =
  773. result = getName(d, nameNode) & "\n"
  774. proc generateTags*(d: PDoc, n: PNode, r: var Rope) =
  775. case n.kind
  776. of nkCommentStmt:
  777. if startsWith(n.comment, "##"):
  778. let stripped = n.comment.substr(2).strip
  779. r.add stripped
  780. of nkProcDef:
  781. when useEffectSystem: documentRaises(d.cache, n)
  782. r.add genTagsItem(d, n, n.sons[namePos], skProc)
  783. of nkFuncDef:
  784. when useEffectSystem: documentRaises(d.cache, n)
  785. r.add genTagsItem(d, n, n.sons[namePos], skFunc)
  786. of nkMethodDef:
  787. when useEffectSystem: documentRaises(d.cache, n)
  788. r.add genTagsItem(d, n, n.sons[namePos], skMethod)
  789. of nkIteratorDef:
  790. when useEffectSystem: documentRaises(d.cache, n)
  791. r.add genTagsItem(d, n, n.sons[namePos], skIterator)
  792. of nkMacroDef:
  793. r.add genTagsItem(d, n, n.sons[namePos], skMacro)
  794. of nkTemplateDef:
  795. r.add genTagsItem(d, n, n.sons[namePos], skTemplate)
  796. of nkConverterDef:
  797. when useEffectSystem: documentRaises(d.cache, n)
  798. r.add genTagsItem(d, n, n.sons[namePos], skConverter)
  799. of nkTypeSection, nkVarSection, nkLetSection, nkConstSection:
  800. for i in countup(0, sonsLen(n) - 1):
  801. if n.sons[i].kind != nkCommentStmt:
  802. # order is always 'type var let const':
  803. r.add genTagsItem(d, n.sons[i], n.sons[i].sons[0],
  804. succ(skType, ord(n.kind)-ord(nkTypeSection)))
  805. of nkStmtList:
  806. for i in countup(0, sonsLen(n) - 1):
  807. generateTags(d, n.sons[i], r)
  808. of nkWhenStmt:
  809. # generate documentation for the first branch only:
  810. if not checkForFalse(n.sons[0].sons[0]):
  811. generateTags(d, lastSon(n.sons[0]), r)
  812. else: discard
  813. proc genSection(d: PDoc, kind: TSymKind) =
  814. const sectionNames: array[skTemp..skTemplate, string] = [
  815. "Exports", "Imports", "Types", "Vars", "Lets", "Consts", "Vars", "Procs", "Funcs",
  816. "Methods", "Iterators", "Converters", "Macros", "Templates"
  817. ]
  818. if d.section[kind] == nil: return
  819. var title = sectionNames[kind].rope
  820. d.section[kind] = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.section"), [
  821. "sectionid", "sectionTitle", "sectionTitleID", "content"], [
  822. ord(kind).rope, title, rope(ord(kind) + 50), d.section[kind]])
  823. d.toc[kind] = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.section.toc"), [
  824. "sectionid", "sectionTitle", "sectionTitleID", "content"], [
  825. ord(kind).rope, title, rope(ord(kind) + 50), d.toc[kind]])
  826. proc genOutFile(d: PDoc): Rope =
  827. var
  828. code, content: Rope
  829. title = ""
  830. var j = 0
  831. var tmp = ""
  832. renderTocEntries(d[], j, 1, tmp)
  833. var toc = tmp.rope
  834. for i in countup(low(TSymKind), high(TSymKind)):
  835. genSection(d, i)
  836. add(toc, d.toc[i])
  837. if toc != nil:
  838. toc = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.toc"), ["content"], [toc])
  839. for i in countup(low(TSymKind), high(TSymKind)): add(code, d.section[i])
  840. # Extract the title. Non API modules generate an entry in the index table.
  841. if d.meta[metaTitle].len != 0:
  842. title = d.meta[metaTitle]
  843. let external = AbsoluteFile(d.filename).relativeTo(d.conf.projectPath, '/').changeFileExt(HtmlExt).string
  844. setIndexTerm(d[], external, "", title)
  845. else:
  846. # Modules get an automatic title for the HTML, but no entry in the index.
  847. title = "Module " & extractFilename(changeFileExt(d.filename, ""))
  848. let bodyname = if d.hasToc and not d.isPureRst: "doc.body_toc_group"
  849. elif d.hasToc: "doc.body_toc"
  850. else: "doc.body_no_toc"
  851. content = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, bodyname), ["title",
  852. "tableofcontents", "moduledesc", "date", "time", "content"],
  853. [title.rope, toc, d.modDesc, rope(getDateStr()),
  854. rope(getClockStr()), code])
  855. if optCompileOnly notin d.conf.globalOptions:
  856. # XXX what is this hack doing here? 'optCompileOnly' means raw output!?
  857. code = ropeFormatNamedVars(d.conf, getConfigVar(d.conf, "doc.file"), ["title",
  858. "tableofcontents", "moduledesc", "date", "time",
  859. "content", "author", "version", "analytics"],
  860. [title.rope, toc, d.modDesc, rope(getDateStr()),
  861. rope(getClockStr()), content, d.meta[metaAuthor].rope,
  862. d.meta[metaVersion].rope, d.analytics.rope])
  863. else:
  864. code = content
  865. result = code
  866. proc generateIndex*(d: PDoc) =
  867. if optGenIndex in d.conf.globalOptions:
  868. let dir = if d.conf.outFile.isEmpty: d.conf.projectPath / RelativeDir"htmldocs"
  869. elif optWholeProject in d.conf.globalOptions: AbsoluteDir(d.conf.outFile)
  870. else: AbsoluteDir(d.conf.outFile.string.splitFile.dir)
  871. createDir(dir)
  872. let dest = dir / changeFileExt(relativeTo(AbsoluteFile d.filename,
  873. d.conf.projectPath), IndexExt)
  874. writeIndexFile(d[], dest.string)
  875. proc writeOutput*(d: PDoc, useWarning = false) =
  876. var content = genOutFile(d)
  877. if optStdout in d.conf.globalOptions:
  878. writeRope(stdout, content)
  879. else:
  880. template outfile: untyped = d.destFile
  881. #let outfile = getOutFile2(d.conf, shortenDir(d.conf, filename), outExt, "htmldocs")
  882. createDir(outfile.splitFile.dir)
  883. if not writeRope(content, outfile):
  884. rawMessage(d.conf, if useWarning: warnCannotOpenFile else: errCannotOpenFile,
  885. outfile.string)
  886. proc writeOutputJson*(d: PDoc, useWarning = false) =
  887. var modDesc: string
  888. for desc in d.modDesc:
  889. modDesc &= desc
  890. let content = %*{"orig": d.filename,
  891. "nimble": getPackageName(d.conf, d.filename),
  892. "moduleDescription": modDesc,
  893. "entries": d.jArray}
  894. if optStdout in d.conf.globalOptions:
  895. write(stdout, $content)
  896. else:
  897. var f: File
  898. if open(f, d.destFile.string, fmWrite):
  899. write(f, $content)
  900. close(f)
  901. else:
  902. localError(d.conf, newLineInfo(d.conf, AbsoluteFile d.filename, -1, -1),
  903. warnUser, "unable to open file \"" & d.destFile.string &
  904. "\" for writing")
  905. proc commandDoc*(cache: IdentCache, conf: ConfigRef) =
  906. var ast = parseFile(conf.projectMainIdx, cache, conf)
  907. if ast == nil: return
  908. var d = newDocumentor(conf.projectFull, cache, conf)
  909. d.hasToc = true
  910. generateDoc(d, ast, ast)
  911. writeOutput(d)
  912. generateIndex(d)
  913. proc commandRstAux(cache: IdentCache, conf: ConfigRef;
  914. filename: AbsoluteFile, outExt: string) =
  915. var filen = addFileExt(filename, "txt")
  916. var d = newDocumentor(filen, cache, conf, outExt)
  917. d.isPureRst = true
  918. var rst = parseRst(readFile(filen.string), filen.string, 0, 1, d.hasToc,
  919. {roSupportRawDirective}, conf)
  920. var modDesc = newStringOfCap(30_000)
  921. renderRstToOut(d[], rst, modDesc)
  922. d.modDesc = rope(modDesc)
  923. writeOutput(d)
  924. generateIndex(d)
  925. proc commandRst2Html*(cache: IdentCache, conf: ConfigRef) =
  926. commandRstAux(cache, conf, conf.projectFull, HtmlExt)
  927. proc commandRst2TeX*(cache: IdentCache, conf: ConfigRef) =
  928. commandRstAux(cache, conf, conf.projectFull, TexExt)
  929. proc commandJson*(cache: IdentCache, conf: ConfigRef) =
  930. var ast = parseFile(conf.projectMainIdx, cache, conf)
  931. if ast == nil: return
  932. var d = newDocumentor(conf.projectFull, cache, conf)
  933. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  934. status: int; content: string) =
  935. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  936. warnUser, "the ':test:' attribute is not supported by this backend")
  937. d.hasToc = true
  938. generateJson(d, ast)
  939. let json = d.jArray
  940. let content = rope(pretty(json))
  941. if optStdout in d.conf.globalOptions:
  942. writeRope(stdout, content)
  943. else:
  944. #echo getOutFile(gProjectFull, JsonExt)
  945. let filename = getOutFile(conf, RelativeFile conf.projectName, JsonExt)
  946. if not writeRope(content, filename):
  947. rawMessage(conf, errCannotOpenFile, filename.string)
  948. proc commandTags*(cache: IdentCache, conf: ConfigRef) =
  949. var ast = parseFile(conf.projectMainIdx, cache, conf)
  950. if ast == nil: return
  951. var d = newDocumentor(conf.projectFull, cache, conf)
  952. d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
  953. status: int; content: string) =
  954. localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
  955. warnUser, "the ':test:' attribute is not supported by this backend")
  956. d.hasToc = true
  957. var
  958. content: Rope
  959. generateTags(d, ast, content)
  960. if optStdout in d.conf.globalOptions:
  961. writeRope(stdout, content)
  962. else:
  963. #echo getOutFile(gProjectFull, TagsExt)
  964. let filename = getOutFile(conf, RelativeFile conf.projectName, TagsExt)
  965. if not writeRope(content, filename):
  966. rawMessage(conf, errCannotOpenFile, filename.string)
  967. proc commandBuildIndex*(cache: IdentCache, conf: ConfigRef) =
  968. var content = mergeIndexes(conf.projectFull.string).rope
  969. let code = ropeFormatNamedVars(conf, getConfigVar(conf, "doc.file"), ["title",
  970. "tableofcontents", "moduledesc", "date", "time",
  971. "content", "author", "version", "analytics"],
  972. ["Index".rope, nil, nil, rope(getDateStr()),
  973. rope(getClockStr()), content, nil, nil, nil])
  974. # no analytics because context is not available
  975. let filename = getOutFile(conf, RelativeFile"theindex", HtmlExt)
  976. if not writeRope(code, filename):
  977. rawMessage(conf, errCannotOpenFile, filename.string)