docgen.nim 74 KB

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