docgen.nim 76 KB

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