rst.nim 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803
  1. #
  2. #
  3. # Nim's Runtime Library
  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 module implements a `reStructuredText`:idx: (RST) and
  10. ## `Markdown`:idx: parser.
  11. ## User's manual on supported markup syntax and command line usage can be
  12. ## found in [Nim-flavored Markdown and reStructuredText](markdown_rst.html).
  13. ##
  14. ## * See also [Nim DocGen Tools Guide](docgen.html) for handling of
  15. ## ``.nim`` files.
  16. ## * See also [packages/docutils/rstgen module](rstgen.html) to know how to
  17. ## generate HTML or Latex strings (for embedding them into custom documents).
  18. ##
  19. ## Choice between Markdown and RST as well as optional additional features are
  20. ## turned on by passing ``options:`` [RstParseOptions] to [proc rstParse].
  21. import
  22. os, strutils, rstast, dochelpers, std/enumutils, algorithm, lists, sequtils,
  23. std/private/miscdollars, tables, strscans, rstidx
  24. from highlite import SourceLanguage, getSourceLanguage
  25. when defined(nimPreviewSlimSystem):
  26. import std/[assertions, syncio]
  27. type
  28. RstParseOption* = enum ## options for the RST parser
  29. roSupportSmilies, ## make the RST parser support smilies like ``:)``
  30. roSupportRawDirective, ## support the ``raw`` directive (don't support
  31. ## it for sandboxing)
  32. roSupportMarkdown, ## support additional features of Markdown
  33. roPreferMarkdown, ## parse as Markdown (keeping RST as "extension"
  34. ## to Markdown) -- implies `roSupportMarkdown`
  35. roNimFile ## set for Nim files where default interpreted
  36. ## text role should be :nim:
  37. roSandboxDisabled ## this option enables certain options
  38. ## (e.g. raw, include, importdoc)
  39. ## which are disabled by default as they can
  40. ## enable users to read arbitrary data and
  41. ## perform XSS if the parser is used in a web
  42. ## app.
  43. RstParseOptions* = set[RstParseOption]
  44. MsgClass* = enum
  45. mcHint = "Hint",
  46. mcWarning = "Warning",
  47. mcError = "Error"
  48. # keep the order in sync with compiler/docgen.nim and compiler/lineinfos.nim:
  49. MsgKind* = enum ## the possible messages
  50. meCannotOpenFile = "cannot open '$1'",
  51. meExpected = "'$1' expected",
  52. meMissingClosing = "$1",
  53. meGridTableNotImplemented = "grid table is not implemented",
  54. meMarkdownIllformedTable = "illformed delimiter row of a Markdown table",
  55. meIllformedTable = "Illformed table: $1",
  56. meNewSectionExpected = "new section expected $1",
  57. meGeneralParseError = "general parse error",
  58. meInvalidDirective = "invalid directive: '$1'",
  59. meInvalidField = "invalid field: $1",
  60. meFootnoteMismatch = "mismatch in number of footnotes and their refs: $1",
  61. mwRedefinitionOfLabel = "redefinition of label '$1'",
  62. mwUnknownSubstitution = "unknown substitution '$1'",
  63. mwAmbiguousLink = "ambiguous doc link $1",
  64. mwBrokenLink = "broken link '$1'",
  65. mwUnsupportedLanguage = "language '$1' not supported",
  66. mwUnsupportedField = "field '$1' not supported",
  67. mwRstStyle = "RST style: $1",
  68. mwUnusedImportdoc = "importdoc for '$1' is not used",
  69. meSandboxedDirective = "disabled directive: '$1'",
  70. MsgHandler* = proc (filename: string, line, col: int, msgKind: MsgKind,
  71. arg: string) {.closure, gcsafe.} ## what to do in case of an error
  72. FindFileHandler* = proc (filename: string): string {.closure, gcsafe.}
  73. FindRefFileHandler* =
  74. proc (targetRelPath: string):
  75. tuple[targetPath: string, linkRelPath: string] {.closure, gcsafe.}
  76. ## returns where .html or .idx file should be found by its relative path;
  77. ## `linkRelPath` is a prefix to be added before a link anchor from such file
  78. proc rstnodeToRefname*(n: PRstNode): string
  79. proc addNodes*(n: PRstNode): string
  80. proc getFieldValue*(n: PRstNode, fieldname: string): string {.gcsafe.}
  81. proc getArgument*(n: PRstNode): string
  82. # ----------------------------- scanner part --------------------------------
  83. const
  84. SymChars: set[char] = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF'}
  85. SmileyStartChars: set[char] = {':', ';', '8'}
  86. Smilies = {
  87. ":D": "icon_e_biggrin",
  88. ":-D": "icon_e_biggrin",
  89. ":)": "icon_e_smile",
  90. ":-)": "icon_e_smile",
  91. ";)": "icon_e_wink",
  92. ";-)": "icon_e_wink",
  93. ":(": "icon_e_sad",
  94. ":-(": "icon_e_sad",
  95. ":o": "icon_e_surprised",
  96. ":-o": "icon_e_surprised",
  97. ":shock:": "icon_eek",
  98. ":?": "icon_e_confused",
  99. ":-?": "icon_e_confused",
  100. ":-/": "icon_e_confused",
  101. "8-)": "icon_cool",
  102. ":lol:": "icon_lol",
  103. ":x": "icon_mad",
  104. ":-x": "icon_mad",
  105. ":P": "icon_razz",
  106. ":-P": "icon_razz",
  107. ":oops:": "icon_redface",
  108. ":cry:": "icon_cry",
  109. ":evil:": "icon_evil",
  110. ":twisted:": "icon_twisted",
  111. ":roll:": "icon_rolleyes",
  112. ":!:": "icon_exclaim",
  113. ":?:": "icon_question",
  114. ":idea:": "icon_idea",
  115. ":arrow:": "icon_arrow",
  116. ":|": "icon_neutral",
  117. ":-|": "icon_neutral",
  118. ":mrgreen:": "icon_mrgreen",
  119. ":geek:": "icon_e_geek",
  120. ":ugeek:": "icon_e_ugeek"
  121. }
  122. SandboxDirAllowlist = [
  123. "image", "code", "code-block", "admonition", "attention", "caution",
  124. "container", "contents", "danger", "default-role", "error", "figure",
  125. "hint", "important", "index", "note", "role", "tip", "title", "warning"]
  126. type
  127. TokType = enum
  128. tkEof, tkIndent,
  129. tkWhite, tkWord,
  130. tkAdornment, # used for chapter adornment, transitions and
  131. # horizontal table borders
  132. tkPunct, # one or many punctuation characters
  133. tkOther
  134. Token = object # a RST token
  135. kind*: TokType # the type of the token
  136. ival*: int # the indentation or parsed integer value
  137. symbol*: string # the parsed symbol as string
  138. line*, col*: int # line and column of the token
  139. TokenSeq = seq[Token]
  140. Lexer = object of RootObj
  141. buf*: cstring
  142. bufpos*: int
  143. line*, col*, baseIndent*: int
  144. adornmentLine*: bool
  145. escapeNext*: bool
  146. proc getThing(L: var Lexer, tok: var Token, s: set[char]) =
  147. tok.kind = tkWord
  148. tok.line = L.line
  149. tok.col = L.col
  150. var pos = L.bufpos
  151. while true:
  152. tok.symbol.add(L.buf[pos])
  153. inc pos
  154. if L.buf[pos] notin s: break
  155. inc L.col, pos - L.bufpos
  156. L.bufpos = pos
  157. proc isCurrentLineAdornment(L: var Lexer): bool =
  158. var pos = L.bufpos
  159. let c = L.buf[pos]
  160. while true:
  161. inc pos
  162. if L.buf[pos] in {'\c', '\l', '\0'}:
  163. break
  164. if c == '+': # grid table
  165. if L.buf[pos] notin {'-', '=', '+'}:
  166. return false
  167. else: # section adornment or table horizontal border
  168. if L.buf[pos] notin {c, ' ', '\t', '\v', '\f'}:
  169. return false
  170. result = true
  171. proc getPunctAdornment(L: var Lexer, tok: var Token) =
  172. if L.adornmentLine:
  173. tok.kind = tkAdornment
  174. else:
  175. tok.kind = tkPunct
  176. tok.line = L.line
  177. tok.col = L.col
  178. var pos = L.bufpos
  179. let c = L.buf[pos]
  180. if not L.escapeNext and (c != '\\' or L.adornmentLine):
  181. while true:
  182. tok.symbol.add(L.buf[pos])
  183. inc pos
  184. if L.buf[pos] != c: break
  185. elif L.escapeNext:
  186. tok.symbol.add(L.buf[pos])
  187. inc pos
  188. else: # not L.escapeNext and c == '\\' and not L.adornmentLine
  189. tok.symbol.add '\\'
  190. inc pos
  191. L.escapeNext = true
  192. inc L.col, pos - L.bufpos
  193. L.bufpos = pos
  194. if tok.symbol == "\\": tok.kind = tkPunct
  195. # nim extension: standalone \ can not be adornment
  196. proc getBracket(L: var Lexer, tok: var Token) =
  197. tok.kind = tkPunct
  198. tok.line = L.line
  199. tok.col = L.col
  200. tok.symbol.add(L.buf[L.bufpos])
  201. inc L.col
  202. inc L.bufpos
  203. proc getIndentAux(L: var Lexer, start: int): int =
  204. var pos = start
  205. # skip the newline (but include it in the token!)
  206. if L.buf[pos] == '\r':
  207. if L.buf[pos + 1] == '\n': inc pos, 2
  208. else: inc pos
  209. elif L.buf[pos] == '\n':
  210. inc pos
  211. while true:
  212. case L.buf[pos]
  213. of ' ', '\v', '\f':
  214. inc pos
  215. inc result
  216. of '\t':
  217. inc pos
  218. result = result - (result mod 8) + 8
  219. else:
  220. break # EndOfFile also leaves the loop
  221. if L.buf[pos] == '\0':
  222. result = 0
  223. elif L.buf[pos] == '\n' or L.buf[pos] == '\r':
  224. # look at the next line for proper indentation:
  225. result = getIndentAux(L, pos)
  226. L.bufpos = pos # no need to set back buf
  227. proc getIndent(L: var Lexer, tok: var Token) =
  228. tok.col = 0
  229. tok.kind = tkIndent # skip the newline (but include it in the token!)
  230. tok.ival = getIndentAux(L, L.bufpos)
  231. inc L.line
  232. tok.line = L.line
  233. L.col = tok.ival
  234. tok.ival = max(tok.ival - L.baseIndent, 0)
  235. tok.symbol = "\n" & spaces(tok.ival)
  236. proc rawGetTok(L: var Lexer, tok: var Token) =
  237. tok.symbol = ""
  238. tok.ival = 0
  239. if L.col == 0:
  240. L.adornmentLine = false
  241. var c = L.buf[L.bufpos]
  242. case c
  243. of 'a'..'z', 'A'..'Z', '\x80'..'\xFF', '0'..'9':
  244. getThing(L, tok, SymChars)
  245. of ' ', '\t', '\v', '\f':
  246. getThing(L, tok, {' ', '\t'})
  247. tok.kind = tkWhite
  248. if L.buf[L.bufpos] in {'\r', '\n'}:
  249. rawGetTok(L, tok) # ignore spaces before \n
  250. of '\r', '\n':
  251. getIndent(L, tok)
  252. L.adornmentLine = false
  253. of '!', '\"', '#', '$', '%', '&', '\'', '*', '+', ',', '-', '.',
  254. '/', ':', ';', '<', '=', '>', '?', '@', '\\', '^', '_', '`',
  255. '|', '~':
  256. if L.col == 0:
  257. L.adornmentLine = L.isCurrentLineAdornment()
  258. getPunctAdornment(L, tok)
  259. of '(', ')', '[', ']', '{', '}':
  260. getBracket(L, tok)
  261. else:
  262. tok.line = L.line
  263. tok.col = L.col
  264. if c == '\0':
  265. tok.kind = tkEof
  266. else:
  267. tok.kind = tkOther
  268. tok.symbol.add(c)
  269. inc L.bufpos
  270. inc L.col
  271. tok.col = max(tok.col - L.baseIndent, 0)
  272. proc getTokens(buffer: string, tokens: var TokenSeq) =
  273. var L: Lexer
  274. var length = tokens.len
  275. L.buf = cstring(buffer)
  276. L.line = 0 # skip UTF-8 BOM
  277. if L.buf[0] == '\xEF' and L.buf[1] == '\xBB' and L.buf[2] == '\xBF':
  278. inc L.bufpos, 3
  279. while true:
  280. inc length
  281. setLen(tokens, length)
  282. let toEscape = L.escapeNext
  283. rawGetTok(L, tokens[length - 1])
  284. if toEscape: L.escapeNext = false
  285. if tokens[length - 1].kind == tkEof: break
  286. if tokens[0].kind == tkWhite:
  287. # BUGFIX
  288. tokens[0].ival = tokens[0].symbol.len
  289. tokens[0].kind = tkIndent
  290. type
  291. LevelInfo = object
  292. symbol: char # adornment character
  293. hasOverline: bool # has also overline (besides underline)?
  294. line: int # the last line of this style occurrence
  295. # (for error message)
  296. hasPeers: bool # has headings on the same level of hierarchy?
  297. LiteralBlockKind = enum # RST-style literal blocks after `::`
  298. lbNone,
  299. lbIndentedLiteralBlock,
  300. lbQuotedLiteralBlock
  301. LevelMap = seq[LevelInfo] # Saves for each possible title adornment
  302. # style its level in the current document.
  303. SubstitutionKind = enum
  304. rstSubstitution = "substitution",
  305. hyperlinkAlias = "hyperlink alias",
  306. implicitHyperlinkAlias = "implicitly-generated hyperlink alias"
  307. Substitution = object
  308. kind*: SubstitutionKind
  309. key*: string
  310. value*: PRstNode
  311. info*: TLineInfo # place where the substitution was defined
  312. AnchorRule = enum
  313. arInternalRst, ## For automatically generated RST anchors (from
  314. ## headings, footnotes, inline internal targets):
  315. ## case-insensitive, 1-space-significant (by RST spec)
  316. arExternalRst, ## For external .nim doc comments or .rst/.md
  317. arNim ## For anchors generated by ``docgen.nim``: Nim-style case
  318. ## sensitivity, etc. (see `proc normalizeNimName`_ for details)
  319. arHyperlink, ## For links with manually set anchors in
  320. ## form `text <pagename.html#anchor>`_
  321. RstAnchorKind = enum
  322. manualDirectiveAnchor = "manual directive anchor",
  323. manualInlineAnchor = "manual inline anchor",
  324. footnoteAnchor = "footnote anchor",
  325. headlineAnchor = "implicitly-generated headline anchor"
  326. AnchorSubst = object
  327. info: TLineInfo # the file where the anchor was defined
  328. priority: int
  329. case kind: range[arInternalRst .. arNim]
  330. of arInternalRst:
  331. anchorType: RstAnchorKind
  332. target: PRstNode
  333. of arExternalRst:
  334. anchorTypeExt: RstAnchorKind
  335. refnameExt: string
  336. of arNim:
  337. module: FileIndex # anchor's module (generally not the same as file)
  338. tooltip: string # displayed tooltip for Nim-generated anchors
  339. langSym: LangSymbol
  340. refname: string # A reference name that will be inserted directly
  341. # into HTML/Latex.
  342. external: bool
  343. AnchorSubstTable = Table[string, seq[AnchorSubst]]
  344. # use `seq` to account for duplicate anchors
  345. FootnoteType = enum
  346. fnManualNumber, # manually numbered footnote like [3]
  347. fnAutoNumber, # auto-numbered footnote [#]
  348. fnAutoNumberLabel, # auto-numbered with label [#label]
  349. fnAutoSymbol, # auto-symbol footnote [*]
  350. fnCitation # simple text label like [citation2021]
  351. FootnoteSubst = tuple
  352. kind: FootnoteType # discriminator
  353. number: int # valid for fnManualNumber (always) and fnAutoNumber,
  354. # fnAutoNumberLabel after resolveSubs is called
  355. autoNumIdx: int # order of occurence: fnAutoNumber, fnAutoNumberLabel
  356. autoSymIdx: int # order of occurence: fnAutoSymbol
  357. label: string # valid for fnAutoNumberLabel
  358. RstFileTable* = object
  359. filenameToIdx*: Table[string, FileIndex]
  360. idxToFilename*: seq[string]
  361. ImportdocInfo = object
  362. used: bool # was this import used?
  363. fromInfo: TLineInfo # place of `.. importdoc::` directive
  364. idxPath: string # full path to ``.idx`` file
  365. linkRelPath: string # prefix before target anchor
  366. title: string # document title obtained from ``.idx``
  367. RstSharedState = object
  368. options*: RstParseOptions # parsing options
  369. hLevels: LevelMap # hierarchy of heading styles
  370. hTitleCnt: int # =0 if no title, =1 if only main title,
  371. # =2 if both title and subtitle are present
  372. hCurLevel: int # current section level
  373. currRole: string # current interpreted text role
  374. currRoleKind: RstNodeKind # ... and its node kind
  375. subs: seq[Substitution] # substitutions
  376. refs*: seq[Substitution] # references
  377. anchors*: AnchorSubstTable
  378. # internal target substitutions
  379. lineFootnoteNum: seq[TLineInfo] # footnote line, auto numbers .. [#]
  380. lineFootnoteNumRef: seq[TLineInfo] # footnote line, their reference [#]_
  381. currFootnoteNumRef: int # ... their counter for `resolveSubs`
  382. lineFootnoteSym: seq[TLineInfo] # footnote line, auto symbols .. [*]
  383. lineFootnoteSymRef: seq[TLineInfo] # footnote line, their reference [*]_
  384. currFootnoteSymRef: int # ... their counter for `resolveSubs`
  385. footnotes: seq[FootnoteSubst] # correspondence b/w footnote label,
  386. # number, order of occurrence
  387. msgHandler: MsgHandler # How to handle errors.
  388. findFile: FindFileHandler # How to find files for include.
  389. findRefFile: FindRefFileHandler
  390. # How to find files imported by importdoc.
  391. filenames*: RstFileTable # map file name <-> FileIndex (for storing
  392. # file names for warnings after 1st stage)
  393. currFileIdx*: FileIndex # current index in `filenames`
  394. tocPart*: seq[PRstNode] # all the headings of a document
  395. hasToc*: bool
  396. idxImports*: Table[string, ImportdocInfo]
  397. # map `importdoc`ed filename -> it's info
  398. nimFileImported*: bool # Was any ``.nim`` module `importdoc`ed ?
  399. PRstSharedState* = ref RstSharedState
  400. ManualAnchor = object
  401. alias: string # a (short) name that can substitute the `anchor`
  402. anchor: string # anchor = id = refname
  403. info: TLineInfo
  404. RstParser = object of RootObj
  405. idx*: int
  406. tok*: TokenSeq
  407. s*: PRstSharedState
  408. indentStack*: seq[int]
  409. line*, col*: int ## initial line/column of whole text or
  410. ## documenation fragment that will be added
  411. ## in case of error/warning reporting to
  412. ## (relative) line/column of the token.
  413. curAnchors*: seq[ManualAnchor]
  414. ## seq to accumulate aliases for anchors:
  415. ## because RST can have >1 alias per 1 anchor
  416. EParseError* = object of ValueError
  417. const
  418. LineRstInit* = 1 ## Initial line number for standalone RST text
  419. ColRstInit* = 0 ## Initial column number for standalone RST text
  420. ## (Nim global reporting adds ColOffset=1)
  421. ColRstOffset* = 1 ## 1: a replica of ColOffset for internal use
  422. template currentTok(p: RstParser): Token = p.tok[p.idx]
  423. template prevTok(p: RstParser): Token = p.tok[p.idx - 1]
  424. template nextTok(p: RstParser): Token = p.tok[p.idx + 1]
  425. proc whichMsgClass*(k: MsgKind): MsgClass =
  426. ## returns which message class `k` belongs to.
  427. case k.symbolName[1]
  428. of 'e', 'E': result = mcError
  429. of 'w', 'W': result = mcWarning
  430. of 'h', 'H': result = mcHint
  431. else: assert false, "msgkind does not fit naming scheme"
  432. proc defaultMsgHandler*(filename: string, line, col: int, msgkind: MsgKind,
  433. arg: string) =
  434. let mc = msgkind.whichMsgClass
  435. let a = $msgkind % arg
  436. var message: string
  437. toLocation(message, filename, line, col + ColRstOffset)
  438. message.add " $1: $2" % [$mc, a]
  439. if mc == mcError: raise newException(EParseError, message)
  440. else: writeLine(stdout, message)
  441. proc defaultFindFile*(filename: string): string =
  442. if fileExists(filename): result = filename
  443. else: result = ""
  444. proc defaultFindRefFile*(filename: string): (string, string) =
  445. (filename, "")
  446. proc defaultRole(options: RstParseOptions): string =
  447. if roNimFile in options: "nim" else: "literal"
  448. proc whichRoleAux(sym: string): RstNodeKind =
  449. let r = sym.toLowerAscii
  450. case r
  451. of "idx": result = rnIdx
  452. of "literal": result = rnInlineLiteral
  453. of "strong": result = rnStrongEmphasis
  454. of "emphasis": result = rnEmphasis
  455. of "sub", "subscript": result = rnSub
  456. of "sup", "superscript": result = rnSup
  457. # literal and code are the same in our implementation
  458. of "code": result = rnInlineLiteral
  459. of "program", "option", "tok": result = rnCodeFragment
  460. # c++ currently can be spelled only as cpp, c# only as csharp
  461. elif getSourceLanguage(r) != langNone:
  462. result = rnInlineCode
  463. else: # unknown role
  464. result = rnUnknownRole
  465. proc len(filenames: RstFileTable): int = filenames.idxToFilename.len
  466. proc addFilename*(s: PRstSharedState, file1: string): FileIndex =
  467. ## Returns index of filename, adding it if it has not been used before
  468. let nextIdx = s.filenames.len.FileIndex
  469. result = getOrDefault(s.filenames.filenameToIdx, file1, default = nextIdx)
  470. if result == nextIdx:
  471. s.filenames.filenameToIdx[file1] = result
  472. s.filenames.idxToFilename.add file1
  473. proc setCurrFilename*(s: PRstSharedState, file1: string) =
  474. s.currFileIdx = addFilename(s, file1)
  475. proc getFilename(filenames: RstFileTable, fid: FileIndex): string =
  476. doAssert(0 <= fid.int and fid.int < filenames.len,
  477. "incorrect FileIndex $1 (range 0..$2)" % [
  478. $fid.int, $(filenames.len - 1)])
  479. result = filenames.idxToFilename[fid.int]
  480. proc getFilename(s: PRstSharedState, subst: AnchorSubst): string =
  481. getFilename(s.filenames, subst.info.fileIndex)
  482. proc getModule(s: PRstSharedState, subst: AnchorSubst): string =
  483. result = getFilename(s.filenames, subst.module)
  484. proc currFilename(s: PRstSharedState): string =
  485. getFilename(s.filenames, s.currFileIdx)
  486. proc newRstSharedState*(options: RstParseOptions,
  487. filename: string,
  488. findFile: FindFileHandler,
  489. findRefFile: FindRefFileHandler,
  490. msgHandler: MsgHandler,
  491. hasToc: bool): PRstSharedState =
  492. let r = defaultRole(options)
  493. result = PRstSharedState(
  494. currRole: r,
  495. currRoleKind: whichRoleAux(r),
  496. options: options,
  497. msgHandler: if not isNil(msgHandler): msgHandler else: defaultMsgHandler,
  498. findFile: if not isNil(findFile): findFile else: defaultFindFile,
  499. findRefFile:
  500. if not isNil(findRefFile): findRefFile
  501. else: defaultFindRefFile,
  502. hasToc: hasToc
  503. )
  504. setCurrFilename(result, filename)
  505. proc curLine(p: RstParser): int = p.line + currentTok(p).line
  506. proc findRelativeFile(p: RstParser; filename: string): string =
  507. result = p.s.currFilename.splitFile.dir / filename
  508. if not fileExists(result):
  509. result = p.s.findFile(filename)
  510. proc rstMessage(p: RstParser, msgKind: MsgKind, arg: string) =
  511. p.s.msgHandler(p.s.currFilename, curLine(p),
  512. p.col + currentTok(p).col, msgKind, arg)
  513. proc rstMessage(s: PRstSharedState, msgKind: MsgKind, arg: string) =
  514. s.msgHandler(s.currFilename, LineRstInit, ColRstInit, msgKind, arg)
  515. proc rstMessage(s: PRstSharedState, msgKind: MsgKind, arg: string;
  516. line, col: int) =
  517. s.msgHandler(s.currFilename, line, col, msgKind, arg)
  518. proc rstMessage(s: PRstSharedState, filename: string, msgKind: MsgKind,
  519. arg: string) =
  520. s.msgHandler(filename, LineRstInit, ColRstInit, msgKind, arg)
  521. proc rstMessage*(filenames: RstFileTable, f: MsgHandler,
  522. info: TLineInfo, msgKind: MsgKind, arg: string) =
  523. ## Print warnings using `info`, i.e. in 2nd-pass warnings for
  524. ## footnotes/substitutions/references or from ``rstgen.nim``.
  525. let file = getFilename(filenames, info.fileIndex)
  526. f(file, info.line.int, info.col.int, msgKind, arg)
  527. proc rstMessage(p: RstParser, msgKind: MsgKind, arg: string, line, col: int) =
  528. p.s.msgHandler(p.s.currFilename, p.line + line,
  529. p.col + col, msgKind, arg)
  530. proc rstMessage(p: RstParser, msgKind: MsgKind) =
  531. p.s.msgHandler(p.s.currFilename, curLine(p),
  532. p.col + currentTok(p).col, msgKind,
  533. currentTok(p).symbol)
  534. proc currInd(p: RstParser): int =
  535. result = p.indentStack[high(p.indentStack)]
  536. proc pushInd(p: var RstParser, ind: int) =
  537. p.indentStack.add(ind)
  538. proc popInd(p: var RstParser) =
  539. if p.indentStack.len > 1: setLen(p.indentStack, p.indentStack.len - 1)
  540. # Working with indentation in rst.nim
  541. # -----------------------------------
  542. #
  543. # Every line break has an associated tkIndent.
  544. # The tokenizer writes back the first column of next non-blank line
  545. # in all preceeding tkIndent tokens to the `ival` field of tkIndent.
  546. #
  547. # RST document is separated into body elements (B.E.), every of which
  548. # has a dedicated handler proc (or block of logic when B.E. is a block quote)
  549. # that should follow the next rule:
  550. # Every B.E. handler proc should finish at tkIndent (newline)
  551. # after its B.E. finishes.
  552. # Then its callers (which is `parseSection` or another B.E. handler)
  553. # check for tkIndent ival (without necessity to advance `p.idx`)
  554. # and decide themselves whether they continue processing or also stop.
  555. #
  556. # An example::
  557. #
  558. # L RST text fragment indentation
  559. # +--------------------+
  560. # 1 | | <- (empty line at the start of file) no tokens
  561. # 2 |First paragraph. | <- tkIndent has ival=0, and next tkWord has col=0
  562. # 3 | | <- tkIndent has ival=0
  563. # 4 |* bullet item and | <- tkIndent has ival=0, and next tkPunct has col=0
  564. # 5 | its continuation | <- tkIndent has ival=2, and next tkWord has col=2
  565. # 6 | | <- tkIndent has ival=4
  566. # 7 | Block quote | <- tkIndent has ival=4, and next tkWord has col=4
  567. # 8 | | <- tkIndent has ival=0
  568. # 9 | | <- tkIndent has ival=0
  569. # 10|Final paragraph | <- tkIndent has ival=0, and tkWord has col=0
  570. # +--------------------+
  571. # C:01234
  572. #
  573. # Here parser starts with initial `indentStack=[0]` and then calls the
  574. # 1st `parseSection`:
  575. #
  576. # - `parseSection` calls `parseParagraph` and "First paragraph" is parsed
  577. # - bullet list handler is started at reaching ``*`` (L4 C0), it
  578. # starts bullet item logic (L4 C2), which calls `pushInd(p, ind=2)`,
  579. # then calls `parseSection` (2nd call, nested) which parses
  580. # paragraph "bullet list and its continuation" and then starts
  581. # a block quote logic (L7 C4).
  582. # The block quote logic calls calls `pushInd(p, ind=4)` and
  583. # calls `parseSection` again, so a (simplified) sequence of calls now is::
  584. #
  585. # parseSection -> parseBulletList ->
  586. # parseSection (+block quote logic) -> parseSection
  587. #
  588. # 3rd `parseSection` finishes, block quote logic calls `popInd(p)`,
  589. # it returns to bullet item logic, which sees that next tkIndent has
  590. # ival=0 and stops there since the required indentation for a bullet item
  591. # is 2 and 0<2; the bullet item logic calls `popInd(p)`.
  592. # Then bullet list handler checks that next tkWord (L10 C0) has the
  593. # right indentation but does not have ``*`` so stops at tkIndent (L10).
  594. # - 1st `parseSection` invocation calls `parseParagraph` and the
  595. # "Final paragraph" is parsed.
  596. #
  597. # If a B.E. handler has advanced `p.idx` past tkIndent to check
  598. # whether it should continue its processing or not, and decided not to,
  599. # then this B.E. handler should step back (e.g. do `dec p.idx`).
  600. proc initParser(p: var RstParser, sharedState: PRstSharedState) =
  601. p.indentStack = @[0]
  602. p.tok = @[]
  603. p.idx = 0
  604. p.col = ColRstInit
  605. p.line = LineRstInit
  606. p.s = sharedState
  607. proc addNodesAux(n: PRstNode, result: var string) =
  608. if n == nil:
  609. return
  610. if n.kind == rnLeaf:
  611. result.add(n.text)
  612. else:
  613. for i in 0 ..< n.len: addNodesAux(n.sons[i], result)
  614. proc addNodes(n: PRstNode): string =
  615. n.addNodesAux(result)
  616. proc linkName(n: PRstNode): string =
  617. ## Returns a normalized reference name, see:
  618. ## https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#reference-names
  619. n.addNodes.toLowerAscii
  620. proc rstnodeToRefnameAux(n: PRstNode, r: var string, b: var bool) =
  621. template special(s) =
  622. if b:
  623. r.add('-')
  624. b = false
  625. r.add(s)
  626. if n == nil: return
  627. if n.kind == rnLeaf:
  628. for i in 0 ..< n.text.len:
  629. case n.text[i]
  630. of '0'..'9':
  631. if b:
  632. r.add('-')
  633. b = false
  634. if r.len == 0: r.add('Z')
  635. r.add(n.text[i])
  636. of 'a'..'z', '\128'..'\255':
  637. if b:
  638. r.add('-')
  639. b = false
  640. r.add(n.text[i])
  641. of 'A'..'Z':
  642. if b:
  643. r.add('-')
  644. b = false
  645. r.add(chr(ord(n.text[i]) - ord('A') + ord('a')))
  646. of '$': special "dollar"
  647. of '%': special "percent"
  648. of '&': special "amp"
  649. of '^': special "roof"
  650. of '!': special "emark"
  651. of '?': special "qmark"
  652. of '*': special "star"
  653. of '+': special "plus"
  654. of '-': special "minus"
  655. of '/': special "slash"
  656. of '\\': special "backslash"
  657. of '=': special "eq"
  658. of '<': special "lt"
  659. of '>': special "gt"
  660. of '~': special "tilde"
  661. of ':': special "colon"
  662. of '.': special "dot"
  663. of '@': special "at"
  664. of '|': special "bar"
  665. else:
  666. if r.len > 0: b = true
  667. else:
  668. for i in 0 ..< n.len: rstnodeToRefnameAux(n.sons[i], r, b)
  669. proc rstnodeToRefname(n: PRstNode): string =
  670. var b = false
  671. rstnodeToRefnameAux(n, result, b)
  672. proc findSub(s: PRstSharedState, n: PRstNode): int =
  673. var key = addNodes(n)
  674. # the spec says: if no exact match, try one without case distinction:
  675. for i in countup(0, high(s.subs)):
  676. if key == s.subs[i].key:
  677. return i
  678. for i in countup(0, high(s.subs)):
  679. if cmpIgnoreStyle(key, s.subs[i].key) == 0:
  680. return i
  681. result = -1
  682. proc lineInfo(p: RstParser, iTok: int): TLineInfo =
  683. result.col = int16(p.col + p.tok[iTok].col)
  684. result.line = uint16(p.line + p.tok[iTok].line)
  685. result.fileIndex = p.s.currFileIdx
  686. proc lineInfo(p: RstParser): TLineInfo = lineInfo(p, p.idx)
  687. # TODO: we need this simplification because we don't preserve exact starting
  688. # token of currently parsed element:
  689. proc prevLineInfo(p: RstParser): TLineInfo = lineInfo(p, p.idx-1)
  690. proc setSub(p: var RstParser, key: string, value: PRstNode) =
  691. var length = p.s.subs.len
  692. for i in 0 ..< length:
  693. if key == p.s.subs[i].key:
  694. p.s.subs[i].value = value
  695. return
  696. p.s.subs.add(Substitution(key: key, value: value, info: prevLineInfo(p)))
  697. proc setRef(p: var RstParser, key: string, value: PRstNode,
  698. refType: SubstitutionKind) =
  699. var length = p.s.refs.len
  700. for i in 0 ..< length:
  701. if key == p.s.refs[i].key:
  702. if p.s.refs[i].value.addNodes != value.addNodes:
  703. rstMessage(p, mwRedefinitionOfLabel, key)
  704. p.s.refs[i].value = value
  705. return
  706. p.s.refs.add(Substitution(kind: refType, key: key, value: value,
  707. info: prevLineInfo(p)))
  708. proc findRef(s: PRstSharedState, key: string): seq[Substitution] =
  709. for i in countup(0, high(s.refs)):
  710. if key == s.refs[i].key:
  711. result.add s.refs[i]
  712. # Ambiguity in links: we don't follow procedure of removing implicit targets
  713. # defined in https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#implicit-hyperlink-targets
  714. # Instead we just give explicit links a higher priority than to implicit ones
  715. # and report ambiguities as warnings. Hopefully it is easy to remove
  716. # ambiguities manually. Nim auto-generated links from ``docgen.nim``
  717. # have lowest priority: 1 (for procs) and below for other symbol types.
  718. proc refPriority(k: SubstitutionKind): int =
  719. case k
  720. of rstSubstitution: result = 8
  721. of hyperlinkAlias: result = 7
  722. of implicitHyperlinkAlias: result = 2
  723. proc internalRefPriority(k: RstAnchorKind): int =
  724. case k
  725. of manualDirectiveAnchor: result = 6
  726. of manualInlineAnchor: result = 5
  727. of footnoteAnchor: result = 4
  728. of headlineAnchor: result = 3
  729. proc `$`(subst: AnchorSubst): string = # for debug
  730. let s =
  731. case subst.kind
  732. of arInternalRst: "type=" & $subst.anchorType
  733. of arExternalRst: "type=" & $subst.anchorTypeExt
  734. of arNim: "langsym=" & $subst.langSym
  735. result = "(kind=$1, priority=$2, $3)" % [$subst.kind, $subst.priority, s]
  736. proc addAnchorRst(p: var RstParser, name: string, target: PRstNode,
  737. anchorType: RstAnchorKind) =
  738. ## Associates node `target` (which has field `anchor`) with an
  739. ## alias `name` and updates the corresponding aliases in `p.curAnchors`.
  740. let prio = internalRefPriority(anchorType)
  741. for a in p.curAnchors:
  742. p.s.anchors.mgetOrPut(a.alias, newSeq[AnchorSubst]()).add(
  743. AnchorSubst(kind: arInternalRst, target: target, priority: prio,
  744. info: a.info, anchorType: manualDirectiveAnchor))
  745. if name != "":
  746. p.s.anchors.mgetOrPut(name, newSeq[AnchorSubst]()).add(
  747. AnchorSubst(kind: arInternalRst, target: target, priority: prio,
  748. info: prevLineInfo(p), anchorType: anchorType))
  749. p.curAnchors.setLen 0
  750. proc addAnchorExtRst(s: var PRstSharedState, key: string, refn: string,
  751. anchorType: RstAnchorKind, info: TLineInfo) =
  752. let name = key.toLowerAscii
  753. let prio = internalRefPriority(anchorType)
  754. s.anchors.mgetOrPut(name, newSeq[AnchorSubst]()).add(
  755. AnchorSubst(kind: arExternalRst, refnameExt: refn, priority: prio,
  756. info: info,
  757. anchorTypeExt: anchorType))
  758. proc addAnchorNim*(s: var PRstSharedState, external: bool, refn: string, tooltip: string,
  759. langSym: LangSymbol, priority: int,
  760. info: TLineInfo, module: FileIndex) =
  761. ## Adds an anchor `refn`, which follows
  762. ## the rule `arNim` (i.e. a symbol in ``*.nim`` file)
  763. s.anchors.mgetOrPut(langSym.name, newSeq[AnchorSubst]()).add(
  764. AnchorSubst(kind: arNim, external: external, refname: refn, langSym: langSym,
  765. tooltip: tooltip, priority: priority,
  766. info: info))
  767. proc findMainAnchorNim(s: PRstSharedState, signature: PRstNode,
  768. info: TLineInfo):
  769. seq[AnchorSubst] =
  770. var langSym: LangSymbol
  771. try:
  772. langSym = toLangSymbol(signature)
  773. except ValueError: # parsing failed, not a Nim symbol
  774. return
  775. let substitutions = s.anchors.getOrDefault(langSym.name,
  776. newSeq[AnchorSubst]())
  777. if substitutions.len == 0:
  778. return
  779. # logic to select only groups instead of concrete symbols
  780. # with overloads, note that the same symbol can be defined
  781. # in multiple modules and `importdoc`ed:
  782. type GroupKey = tuple[symKind: string, origModule: string]
  783. # map (symKind, file) (like "proc", "os.nim") -> found symbols/groups:
  784. var found: Table[GroupKey, seq[AnchorSubst]]
  785. for subst in substitutions:
  786. if subst.kind == arNim:
  787. if match(subst.langSym, langSym):
  788. let key: GroupKey = (subst.langSym.symKind, getModule(s, subst))
  789. found.mgetOrPut(key, newSeq[AnchorSubst]()).add subst
  790. for key, sList in found:
  791. if sList.len == 1:
  792. result.add sList[0]
  793. else: # > 1, there are overloads, potential ambiguity in this `symKind`
  794. if langSym.parametersProvided:
  795. # there are non-group signatures, select only them
  796. for s in sList:
  797. if not s.langSym.isGroup:
  798. result.add s
  799. else: # when there are many overloads a link like foo_ points to all
  800. # of them, so selecting the group
  801. var foundGroup = false
  802. for s in sList:
  803. if s.langSym.isGroup:
  804. result.add s
  805. foundGroup = true
  806. break
  807. doAssert(foundGroup,
  808. "docgen has not generated the group for $1 (file $2)" % [
  809. langSym.name, getModule(s, sList[0]) ])
  810. proc findMainAnchorRst(s: PRstSharedState, linkText: string, info: TLineInfo):
  811. seq[AnchorSubst] =
  812. let name = linkText.toLowerAscii
  813. let substitutions = s.anchors.getOrDefault(name, newSeq[AnchorSubst]())
  814. for s in substitutions:
  815. if s.kind in {arInternalRst, arExternalRst}:
  816. result.add s
  817. proc addFootnoteNumManual(p: var RstParser, num: int) =
  818. ## add manually-numbered footnote
  819. for fnote in p.s.footnotes:
  820. if fnote.number == num:
  821. rstMessage(p, mwRedefinitionOfLabel, $num)
  822. return
  823. p.s.footnotes.add((fnManualNumber, num, -1, -1, $num))
  824. proc addFootnoteNumAuto(p: var RstParser, label: string) =
  825. ## add auto-numbered footnote.
  826. ## Empty label [#] means it'll be resolved by the occurrence.
  827. if label == "": # simple auto-numbered [#]
  828. p.s.lineFootnoteNum.add lineInfo(p)
  829. p.s.footnotes.add((fnAutoNumber, -1, p.s.lineFootnoteNum.len, -1, label))
  830. else: # auto-numbered with label [#label]
  831. for fnote in p.s.footnotes:
  832. if fnote.label == label:
  833. rstMessage(p, mwRedefinitionOfLabel, label)
  834. return
  835. p.s.footnotes.add((fnAutoNumberLabel, -1, -1, -1, label))
  836. proc addFootnoteSymAuto(p: var RstParser) =
  837. p.s.lineFootnoteSym.add lineInfo(p)
  838. p.s.footnotes.add((fnAutoSymbol, -1, -1, p.s.lineFootnoteSym.len, ""))
  839. proc orderFootnotes(s: PRstSharedState) =
  840. ## numerate auto-numbered footnotes taking into account that all
  841. ## manually numbered ones always have preference.
  842. ## Save the result back to `s.footnotes`.
  843. # Report an error if found any mismatch in number of automatic footnotes
  844. proc listFootnotes(locations: seq[TLineInfo]): string =
  845. var lines: seq[string]
  846. for info in locations:
  847. if s.filenames.len > 1:
  848. let file = getFilename(s.filenames, info.fileIndex)
  849. lines.add file & ":"
  850. else: # no need to add file name here if there is only 1
  851. lines.add ""
  852. lines[^1].add $info.line
  853. result.add $lines.len & " (lines " & join(lines, ", ") & ")"
  854. if s.lineFootnoteNum.len != s.lineFootnoteNumRef.len:
  855. rstMessage(s, meFootnoteMismatch,
  856. "$1 != $2" % [listFootnotes(s.lineFootnoteNum),
  857. listFootnotes(s.lineFootnoteNumRef)] &
  858. " for auto-numbered footnotes")
  859. if s.lineFootnoteSym.len != s.lineFootnoteSymRef.len:
  860. rstMessage(s, meFootnoteMismatch,
  861. "$1 != $2" % [listFootnotes(s.lineFootnoteSym),
  862. listFootnotes(s.lineFootnoteSymRef)] &
  863. " for auto-symbol footnotes")
  864. var result: seq[FootnoteSubst]
  865. var manuallyN, autoN, autoSymbol: seq[FootnoteSubst]
  866. for fs in s.footnotes:
  867. if fs.kind == fnManualNumber: manuallyN.add fs
  868. elif fs.kind in {fnAutoNumber, fnAutoNumberLabel}: autoN.add fs
  869. else: autoSymbol.add fs
  870. if autoN.len == 0:
  871. result = manuallyN
  872. else:
  873. # fill gaps between manually numbered footnotes in ascending order
  874. manuallyN.sort() # sort by number - its first field
  875. var lst = initSinglyLinkedList[FootnoteSubst]()
  876. for elem in manuallyN: lst.append(elem)
  877. var firstAuto = 0
  878. if lst.head == nil or lst.head.value.number != 1:
  879. # no manual footnote [1], start numeration from 1 for auto-numbered
  880. lst.prepend (autoN[0].kind, 1, autoN[0].autoNumIdx, -1, autoN[0].label)
  881. firstAuto = 1
  882. var curNode = lst.head
  883. var nextNode: SinglyLinkedNode[FootnoteSubst]
  884. # go simultaneously through `autoN` and `lst` looking for gaps
  885. for (kind, x, autoNumIdx, y, label) in autoN[firstAuto .. ^1]:
  886. while (nextNode = curNode.next; nextNode != nil):
  887. if nextNode.value.number - curNode.value.number > 1:
  888. # gap found, insert new node `n` between curNode and nextNode:
  889. var n = newSinglyLinkedNode((kind, curNode.value.number + 1,
  890. autoNumIdx, -1, label))
  891. curNode.next = n
  892. n.next = nextNode
  893. curNode = n
  894. break
  895. else:
  896. curNode = nextNode
  897. if nextNode == nil: # no gap found, just append
  898. lst.append (kind, curNode.value.number + 1, autoNumIdx, -1, label)
  899. curNode = lst.tail
  900. result = lst.toSeq
  901. # we use ASCII symbols instead of those recommended in RST specification:
  902. const footnoteAutoSymbols = ["*", "^", "+", "=", "~", "$", "@", "%", "&"]
  903. for fs in autoSymbol:
  904. # assignment order: *, **, ***, ^, ^^, ^^^, ... &&&, ****, *****, ...
  905. let i = fs.autoSymIdx - 1
  906. let symbolNum = (i div 3) mod footnoteAutoSymbols.len
  907. let nSymbols = (1 + i mod 3) + 3 * (i div (3 * footnoteAutoSymbols.len))
  908. let label = footnoteAutoSymbols[symbolNum].repeat(nSymbols)
  909. result.add((fs.kind, -1, -1, fs.autoSymIdx, label))
  910. s.footnotes = result
  911. proc getFootnoteNum(s: PRstSharedState, label: string): int =
  912. ## get number from label. Must be called after `orderFootnotes`.
  913. result = -1
  914. for fnote in s.footnotes:
  915. if fnote.label == label:
  916. return fnote.number
  917. proc getFootnoteNum(s: PRstSharedState, order: int): int =
  918. ## get number from occurrence. Must be called after `orderFootnotes`.
  919. result = -1
  920. for fnote in s.footnotes:
  921. if fnote.autoNumIdx == order:
  922. return fnote.number
  923. proc getAutoSymbol(s: PRstSharedState, order: int): string =
  924. ## get symbol from occurrence of auto-symbol footnote.
  925. result = "???"
  926. for fnote in s.footnotes:
  927. if fnote.autoSymIdx == order:
  928. return fnote.label
  929. proc newRstNodeA(p: var RstParser, kind: RstNodeKind): PRstNode =
  930. ## create node and consume the current anchor
  931. result = newRstNode(kind)
  932. if p.curAnchors.len > 0:
  933. result.anchor = p.curAnchors[0].anchor
  934. addAnchorRst(p, "", result, manualDirectiveAnchor)
  935. template newLeaf(s: string): PRstNode = newRstLeaf(s)
  936. proc newLeaf(p: var RstParser): PRstNode =
  937. result = newLeaf(currentTok(p).symbol)
  938. proc validRefnamePunct(x: string): bool =
  939. ## https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#reference-names
  940. x.len == 1 and x[0] in {'-', '_', '.', ':', '+'}
  941. func getRefnameIdx(p: RstParser, startIdx: int): int =
  942. ## Gets last token index of a refname ("word" in RST terminology):
  943. ##
  944. ## reference names are single words consisting of alphanumerics plus
  945. ## isolated (no two adjacent) internal hyphens, underscores, periods,
  946. ## colons and plus signs; no whitespace or other characters are allowed.
  947. ##
  948. ## Refnames are used for:
  949. ## - reference names
  950. ## - role names
  951. ## - directive names
  952. ## - footnote labels
  953. ##
  954. # TODO: use this func in all other relevant places
  955. var j = startIdx
  956. if p.tok[j].kind == tkWord:
  957. inc j
  958. while p.tok[j].kind == tkPunct and validRefnamePunct(p.tok[j].symbol) and
  959. p.tok[j+1].kind == tkWord:
  960. inc j, 2
  961. result = j - 1
  962. func getRefname(p: RstParser, startIdx: int): (string, int) =
  963. let lastIdx = getRefnameIdx(p, startIdx)
  964. result[1] = lastIdx
  965. for j in startIdx..lastIdx:
  966. result[0].add p.tok[j].symbol
  967. proc getReferenceName(p: var RstParser, endStr: string): PRstNode =
  968. var res = newRstNode(rnInner)
  969. while true:
  970. case currentTok(p).kind
  971. of tkWord, tkOther, tkWhite:
  972. res.add(newLeaf(p))
  973. of tkPunct:
  974. if currentTok(p).symbol == endStr:
  975. inc p.idx
  976. break
  977. else:
  978. res.add(newLeaf(p))
  979. else:
  980. rstMessage(p, meExpected, endStr)
  981. break
  982. inc p.idx
  983. result = res
  984. proc untilEol(p: var RstParser): PRstNode =
  985. result = newRstNode(rnInner)
  986. while currentTok(p).kind notin {tkIndent, tkEof}:
  987. result.add(newLeaf(p))
  988. inc p.idx
  989. proc expect(p: var RstParser, tok: string) =
  990. if currentTok(p).symbol == tok: inc p.idx
  991. else: rstMessage(p, meExpected, tok)
  992. proc inlineMarkdownEnd(p: RstParser): bool =
  993. result = prevTok(p).kind notin {tkIndent, tkWhite}
  994. ## (For a special case of ` we don't allow spaces surrounding it
  995. ## unlike original Markdown because this behavior confusing/useless)
  996. proc inlineRstEnd(p: RstParser): bool =
  997. # rst rules: https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
  998. # Rule 2:
  999. result = prevTok(p).kind notin {tkIndent, tkWhite}
  1000. if not result: return
  1001. # Rule 7:
  1002. result = nextTok(p).kind in {tkIndent, tkWhite, tkEof} or
  1003. nextTok(p).symbol[0] in
  1004. {'\'', '\"', ')', ']', '}', '>', '-', '/', '\\', ':', '.', ',', ';', '!', '?', '_'}
  1005. proc isInlineMarkupEnd(p: RstParser, markup: string, exact: bool): bool =
  1006. if exact:
  1007. result = currentTok(p).symbol == markup
  1008. else:
  1009. result = currentTok(p).symbol.endsWith markup
  1010. if (not result) and markup == "``":
  1011. # check that escaping may have splitted `` to 2 tokens ` and `
  1012. result = currentTok(p).symbol == "`" and prevTok(p).symbol == "`"
  1013. if not result: return
  1014. # surroundings check
  1015. if markup in ["_", "__"]:
  1016. result = inlineRstEnd(p)
  1017. else:
  1018. if roPreferMarkdown in p.s.options: result = inlineMarkdownEnd(p)
  1019. else: result = inlineRstEnd(p)
  1020. proc rstRuleSurround(p: RstParser): bool =
  1021. result = true
  1022. # Rules 4 & 5:
  1023. if p.idx > 0:
  1024. var d: char
  1025. var c = prevTok(p).symbol[0]
  1026. case c
  1027. of '\'', '\"': d = c
  1028. of '(': d = ')'
  1029. of '[': d = ']'
  1030. of '{': d = '}'
  1031. of '<': d = '>'
  1032. else: d = '\0'
  1033. if d != '\0': result = nextTok(p).symbol[0] != d
  1034. proc inlineMarkdownStart(p: RstParser): bool =
  1035. result = nextTok(p).kind notin {tkIndent, tkWhite, tkEof}
  1036. if not result: return
  1037. # this rst rule is really nice, let us use it in Markdown mode too.
  1038. result = rstRuleSurround(p)
  1039. proc inlineRstStart(p: RstParser): bool =
  1040. ## rst rules: https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
  1041. # Rule 6
  1042. result = p.idx == 0 or prevTok(p).kind in {tkIndent, tkWhite} or
  1043. prevTok(p).symbol[0] in {'\'', '\"', '(', '[', '{', '<', '-', '/', ':', '_'}
  1044. if not result: return
  1045. # Rule 1:
  1046. result = nextTok(p).kind notin {tkIndent, tkWhite, tkEof}
  1047. if not result: return
  1048. result = rstRuleSurround(p)
  1049. proc isInlineMarkupStart(p: RstParser, markup: string): bool =
  1050. if markup != "_`":
  1051. result = currentTok(p).symbol == markup
  1052. else: # _` is a 2 token case
  1053. result = currentTok(p).symbol == "_" and nextTok(p).symbol == "`"
  1054. if not result: return
  1055. # surroundings check
  1056. if markup in ["_", "__", "[", "|"]:
  1057. # Note: we require space/punctuation even before [markdown link](...)
  1058. result = inlineRstStart(p)
  1059. else:
  1060. if roPreferMarkdown in p.s.options: result = inlineMarkdownStart(p)
  1061. else: result = inlineRstStart(p)
  1062. proc match(p: RstParser, start: int, expr: string): bool =
  1063. # regular expressions are:
  1064. # special char exact match
  1065. # 'w' tkWord
  1066. # ' ' tkWhite
  1067. # 'a' tkAdornment
  1068. # 'i' tkIndent
  1069. # 'I' tkIndent or tkEof
  1070. # 'p' tkPunct
  1071. # 'T' always true
  1072. # 'E' whitespace, indent or eof
  1073. # 'e' any enumeration sequence or '#' (for enumeration lists)
  1074. # 'x' a..z or '#' (for enumeration lists)
  1075. # 'n' 0..9 or '#' (for enumeration lists)
  1076. var i = 0
  1077. var j = start
  1078. var last = expr.len - 1
  1079. while i <= last:
  1080. case expr[i]
  1081. of 'w':
  1082. let lastIdx = getRefnameIdx(p, j)
  1083. result = lastIdx >= j
  1084. if result: j = lastIdx
  1085. of ' ': result = p.tok[j].kind == tkWhite
  1086. of 'i': result = p.tok[j].kind == tkIndent
  1087. of 'I': result = p.tok[j].kind in {tkIndent, tkEof}
  1088. of 'p': result = p.tok[j].kind == tkPunct
  1089. of 'a': result = p.tok[j].kind == tkAdornment
  1090. of 'o': result = p.tok[j].kind == tkOther
  1091. of 'T': result = true
  1092. of 'E': result = p.tok[j].kind in {tkEof, tkWhite, tkIndent}
  1093. of 'e', 'x', 'n':
  1094. result = p.tok[j].kind == tkWord or p.tok[j].symbol == "#"
  1095. if result:
  1096. case p.tok[j].symbol[0]
  1097. of '#': result = true
  1098. of 'a'..'z', 'A'..'Z':
  1099. result = expr[i] in {'e', 'x'} and p.tok[j].symbol.len == 1
  1100. of '0'..'9':
  1101. result = expr[i] in {'e', 'n'} and
  1102. allCharsInSet(p.tok[j].symbol, {'0'..'9'})
  1103. else: result = false
  1104. else:
  1105. var c = expr[i]
  1106. var length = 0
  1107. while i <= last and expr[i] == c:
  1108. inc i
  1109. inc length
  1110. dec i
  1111. result = p.tok[j].kind in {tkPunct, tkAdornment} and
  1112. p.tok[j].symbol.len == length and p.tok[j].symbol[0] == c
  1113. if not result: return
  1114. inc j
  1115. inc i
  1116. result = true
  1117. proc safeProtocol*(linkStr: var string): string =
  1118. # Returns link's protocol and, if it's not safe, clears `linkStr`
  1119. result = ""
  1120. if scanf(linkStr, "$w:", result):
  1121. # if it has a protocol at all, ensure that it's not 'javascript:' or worse:
  1122. if cmpIgnoreCase(result, "http") == 0 or
  1123. cmpIgnoreCase(result, "https") == 0 or
  1124. cmpIgnoreCase(result, "ftp") == 0:
  1125. discard "it's fine"
  1126. else:
  1127. linkStr = ""
  1128. proc fixupEmbeddedRef(p: var RstParser, n, a, b: PRstNode): bool =
  1129. # Returns `true` if the link belongs to an allowed protocol
  1130. var sep = - 1
  1131. for i in countdown(n.len - 2, 0):
  1132. if n.sons[i].text == "<":
  1133. sep = i
  1134. break
  1135. var incr = if sep > 0 and n.sons[sep - 1].text[0] == ' ': 2 else: 1
  1136. for i in countup(0, sep - incr): a.add(n.sons[i])
  1137. var linkStr = ""
  1138. for i in countup(sep + 1, n.len - 2): linkStr.add(n.sons[i].addNodes)
  1139. if linkStr != "":
  1140. let protocol = safeProtocol(linkStr)
  1141. result = linkStr != ""
  1142. if not result:
  1143. rstMessage(p, mwBrokenLink, protocol,
  1144. p.tok[p.idx-3].line, p.tok[p.idx-3].col)
  1145. b.add newLeaf(linkStr)
  1146. proc whichRole(p: RstParser, sym: string): RstNodeKind =
  1147. result = whichRoleAux(sym)
  1148. if result == rnUnknownRole:
  1149. rstMessage(p, mwUnsupportedLanguage, sym)
  1150. proc toInlineCode(n: PRstNode, language: string): PRstNode =
  1151. ## Creates rnInlineCode and attaches `n` contents as code (in 3rd son).
  1152. result = newRstNode(rnInlineCode, info=n.info)
  1153. let args = newRstNode(rnDirArg)
  1154. var lang = language
  1155. if language == "cpp": lang = "c++"
  1156. elif language == "csharp": lang = "c#"
  1157. args.add newLeaf(lang)
  1158. result.add args
  1159. result.add PRstNode(nil)
  1160. var lb = newRstNode(rnLiteralBlock)
  1161. var s: string
  1162. for i in n.sons:
  1163. assert i.kind == rnLeaf
  1164. s.add i.text
  1165. lb.add newLeaf(s)
  1166. result.add lb
  1167. proc toOtherRole(n: PRstNode, kind: RstNodeKind, roleName: string): PRstNode =
  1168. let newN = newRstNode(rnInner, n.sons)
  1169. let newSons = @[newN, newLeaf(roleName)]
  1170. result = newRstNode(kind, newSons)
  1171. proc parsePostfix(p: var RstParser, n: PRstNode): PRstNode =
  1172. ## Finalizes node `n` that was tentatively determined as interpreted text.
  1173. var newKind = n.kind
  1174. var newSons = n.sons
  1175. proc finalizeInterpreted(node: PRstNode, newKind: RstNodeKind,
  1176. newSons: seq[PRstNode], roleName: string):
  1177. PRstNode {.nimcall.} =
  1178. # fixes interpreted text (`x` or `y`:role:) to proper internal AST format
  1179. if newKind in {rnUnknownRole, rnCodeFragment}:
  1180. result = node.toOtherRole(newKind, roleName)
  1181. elif newKind == rnInlineCode:
  1182. result = node.toInlineCode(language=roleName)
  1183. else:
  1184. result = newRstNode(newKind, newSons)
  1185. if isInlineMarkupEnd(p, "_", exact=true) or
  1186. isInlineMarkupEnd(p, "__", exact=true):
  1187. inc p.idx
  1188. if p.tok[p.idx-2].symbol == "`" and p.tok[p.idx-3].symbol == ">":
  1189. var a = newRstNode(rnInner)
  1190. var b = newRstNode(rnInner)
  1191. if fixupEmbeddedRef(p, n, a, b):
  1192. if a.len == 0: # e.g. `<a_named_relative_link>`_
  1193. newKind = rnStandaloneHyperlink
  1194. newSons = @[b]
  1195. else: # e.g. `link title <http://site>`_
  1196. newKind = rnHyperlink
  1197. newSons = @[a, b]
  1198. setRef(p, rstnodeToRefname(a), b, implicitHyperlinkAlias)
  1199. else: # include as plain text, not a link
  1200. newKind = rnInner
  1201. newSons = n.sons
  1202. result = newRstNode(newKind, newSons)
  1203. else: # some link that will be resolved in `resolveSubs`
  1204. newKind = rnRstRef
  1205. result = newRstNode(newKind, sons=newSons, info=n.info)
  1206. elif match(p, p.idx, ":w:"):
  1207. # a role:
  1208. let (roleName, lastIdx) = getRefname(p, p.idx+1)
  1209. newKind = whichRole(p, roleName)
  1210. result = n.finalizeInterpreted(newKind, newSons, roleName)
  1211. p.idx = lastIdx + 2
  1212. else:
  1213. result = n.finalizeInterpreted(p.s.currRoleKind, newSons, p.s.currRole)
  1214. proc matchVerbatim(p: RstParser, start: int, expr: string): int =
  1215. result = start
  1216. var j = 0
  1217. while j < expr.len and result < p.tok.len and
  1218. continuesWith(expr, p.tok[result].symbol, j):
  1219. inc j, p.tok[result].symbol.len
  1220. inc result
  1221. if j < expr.len: result = 0
  1222. proc parseSmiley(p: var RstParser): PRstNode =
  1223. if currentTok(p).symbol[0] notin SmileyStartChars: return
  1224. for key, val in items(Smilies):
  1225. let m = matchVerbatim(p, p.idx, key)
  1226. if m > 0:
  1227. p.idx = m
  1228. result = newRstNode(rnSmiley)
  1229. result.text = val
  1230. return
  1231. proc isUrl(p: RstParser, i: int): bool =
  1232. result = p.tok[i+1].symbol == ":" and p.tok[i+2].symbol == "//" and
  1233. p.tok[i+3].kind == tkWord and
  1234. p.tok[i].symbol in ["http", "https", "ftp", "telnet", "file"]
  1235. proc checkParen(token: Token, parensStack: var seq[char]): bool {.inline.} =
  1236. ## Returns `true` iff `token` is a closing parenthesis for some
  1237. ## previous opening parenthesis saved in `parensStack`.
  1238. ## This is according Markdown balanced parentheses rule
  1239. ## (https://spec.commonmark.org/0.29/#link-destination)
  1240. ## to allow links like
  1241. ## https://en.wikipedia.org/wiki/APL_(programming_language),
  1242. ## we use it for RST also.
  1243. result = false
  1244. if token.kind == tkPunct:
  1245. let c = token.symbol[0]
  1246. if c in {'(', '[', '{'}: # push
  1247. parensStack.add c
  1248. elif c in {')', ']', '}'}: # try pop
  1249. # a case like ([) inside a link is allowed and [ is also `pop`ed:
  1250. for i in countdown(parensStack.len - 1, 0):
  1251. if (parensStack[i] == '(' and c == ')' or
  1252. parensStack[i] == '[' and c == ']' or
  1253. parensStack[i] == '{' and c == '}'):
  1254. parensStack.setLen i
  1255. result = true
  1256. break
  1257. proc parseUrl(p: var RstParser): PRstNode =
  1258. ## https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#standalone-hyperlinks
  1259. result = newRstNode(rnStandaloneHyperlink)
  1260. var lastIdx = p.idx
  1261. var closedParenIdx = p.idx - 1 # for balanced parens rule
  1262. var parensStack: seq[char]
  1263. while p.tok[lastIdx].kind in {tkWord, tkPunct, tkOther}:
  1264. let isClosing = checkParen(p.tok[lastIdx], parensStack)
  1265. if isClosing:
  1266. closedParenIdx = lastIdx
  1267. inc lastIdx
  1268. dec lastIdx
  1269. # standalone URL can not end with punctuation in RST
  1270. while lastIdx > closedParenIdx and p.tok[lastIdx].kind == tkPunct and
  1271. p.tok[lastIdx].symbol != "/":
  1272. dec lastIdx
  1273. var s = ""
  1274. for i in p.idx .. lastIdx: s.add p.tok[i].symbol
  1275. result.add s
  1276. p.idx = lastIdx + 1
  1277. proc parseWordOrRef(p: var RstParser, father: PRstNode) =
  1278. ## Parses a normal word or may be a reference or URL.
  1279. if nextTok(p).kind != tkPunct: # <- main path, a normal word
  1280. father.add newLeaf(p)
  1281. inc p.idx
  1282. elif isUrl(p, p.idx): # URL http://something
  1283. father.add parseUrl(p)
  1284. else:
  1285. # check for reference (probably, long one like some.ref.with.dots_ )
  1286. var saveIdx = p.idx
  1287. var reference: PRstNode = nil
  1288. inc p.idx
  1289. while currentTok(p).kind in {tkWord, tkPunct}:
  1290. if currentTok(p).kind == tkPunct:
  1291. if isInlineMarkupEnd(p, "_", exact=true):
  1292. reference = newRstNode(rnRstRef, info=lineInfo(p, saveIdx))
  1293. break
  1294. if not validRefnamePunct(currentTok(p).symbol):
  1295. break
  1296. inc p.idx
  1297. if reference != nil:
  1298. for i in saveIdx..p.idx-1: reference.add newLeaf(p.tok[i].symbol)
  1299. father.add reference
  1300. inc p.idx # skip final _
  1301. else: # 1 normal word
  1302. father.add newLeaf(p.tok[saveIdx].symbol)
  1303. p.idx = saveIdx + 1
  1304. proc parseBackslash(p: var RstParser, father: PRstNode) =
  1305. assert(currentTok(p).kind == tkPunct)
  1306. if currentTok(p).symbol == "\\":
  1307. # XXX: Unicode?
  1308. inc p.idx
  1309. if currentTok(p).kind != tkWhite: father.add(newLeaf(p))
  1310. if currentTok(p).kind != tkEof: inc p.idx
  1311. else:
  1312. father.add(newLeaf(p))
  1313. inc p.idx
  1314. proc parseUntil(p: var RstParser, father: PRstNode, postfix: string,
  1315. interpretBackslash: bool) =
  1316. let
  1317. line = currentTok(p).line
  1318. col = currentTok(p).col
  1319. inc p.idx
  1320. while true:
  1321. case currentTok(p).kind
  1322. of tkPunct:
  1323. if isInlineMarkupEnd(p, postfix, exact=false):
  1324. let l = currentTok(p).symbol.len
  1325. if l > postfix.len:
  1326. # handle cases like *emphasis with stars****. (It's valid RST!)
  1327. father.add newLeaf(currentTok(p).symbol[0 ..< l - postfix.len])
  1328. elif postfix == "``" and currentTok(p).symbol == "`" and
  1329. prevTok(p).symbol == "`":
  1330. # handle cases like ``literal\`` - delete ` already added after \
  1331. father.sons.setLen(father.sons.len - 1)
  1332. inc p.idx
  1333. break
  1334. else:
  1335. if postfix == "`":
  1336. if currentTok(p).symbol == "\\":
  1337. if nextTok(p).symbol == "\\":
  1338. father.add newLeaf("\\")
  1339. father.add newLeaf("\\")
  1340. inc p.idx, 2
  1341. elif nextTok(p).symbol == "`": # escape `
  1342. father.add newLeaf("`")
  1343. inc p.idx, 2
  1344. else:
  1345. father.add newLeaf("\\")
  1346. inc p.idx
  1347. else:
  1348. father.add(newLeaf(p))
  1349. inc p.idx
  1350. else:
  1351. if interpretBackslash:
  1352. parseBackslash(p, father)
  1353. else:
  1354. father.add(newLeaf(p))
  1355. inc p.idx
  1356. of tkAdornment, tkWord, tkOther:
  1357. father.add(newLeaf(p))
  1358. inc p.idx
  1359. of tkIndent:
  1360. father.add newLeaf(" ")
  1361. inc p.idx
  1362. if currentTok(p).kind == tkIndent:
  1363. rstMessage(p, meExpected, postfix, line, col)
  1364. break
  1365. of tkWhite:
  1366. father.add newLeaf(" ")
  1367. inc p.idx
  1368. else: rstMessage(p, meExpected, postfix, line, col)
  1369. proc parseMarkdownCodeblockFields(p: var RstParser): PRstNode =
  1370. ## Parses additional (after language string) code block parameters
  1371. ## in a format *suggested* in the `CommonMark Spec`_ with handling of `"`.
  1372. if currentTok(p).kind == tkIndent:
  1373. result = nil
  1374. else:
  1375. result = newRstNode(rnFieldList)
  1376. while currentTok(p).kind != tkIndent:
  1377. if currentTok(p).kind == tkWhite:
  1378. inc p.idx
  1379. else:
  1380. let field = newRstNode(rnField)
  1381. var fieldName = ""
  1382. while currentTok(p).kind notin {tkWhite, tkIndent, tkEof} and
  1383. currentTok(p).symbol != "=":
  1384. fieldName.add currentTok(p).symbol
  1385. inc p.idx
  1386. field.add(newRstNode(rnFieldName, @[newLeaf(fieldName)]))
  1387. if currentTok(p).kind == tkWhite: inc p.idx
  1388. let fieldBody = newRstNode(rnFieldBody)
  1389. if currentTok(p).symbol == "=":
  1390. inc p.idx
  1391. if currentTok(p).kind == tkWhite: inc p.idx
  1392. var fieldValue = ""
  1393. if currentTok(p).symbol == "\"":
  1394. while true:
  1395. fieldValue.add currentTok(p).symbol
  1396. inc p.idx
  1397. if currentTok(p).kind == tkEof:
  1398. rstMessage(p, meExpected, "\"")
  1399. elif currentTok(p).symbol == "\"":
  1400. fieldValue.add "\""
  1401. inc p.idx
  1402. break
  1403. else:
  1404. while currentTok(p).kind notin {tkWhite, tkIndent, tkEof}:
  1405. fieldValue.add currentTok(p).symbol
  1406. inc p.idx
  1407. fieldBody.add newLeaf(fieldValue)
  1408. field.add(fieldBody)
  1409. result.add(field)
  1410. proc mayLoadFile(p: RstParser, result: var PRstNode) =
  1411. var filename = strip(getFieldValue(result, "file"),
  1412. chars = Whitespace + {'"'})
  1413. if filename != "":
  1414. if roSandboxDisabled notin p.s.options:
  1415. let tok = p.tok[p.idx-2]
  1416. rstMessage(p, meSandboxedDirective, "file", tok.line, tok.col)
  1417. var path = p.findRelativeFile(filename)
  1418. if path == "": rstMessage(p, meCannotOpenFile, filename)
  1419. var n = newRstNode(rnLiteralBlock)
  1420. n.add newLeaf(readFile(path))
  1421. result.sons[2] = n
  1422. proc defaultCodeLangNim(p: RstParser, result: var PRstNode) =
  1423. # Create a field block if the input block didn't have any.
  1424. if result.sons[1].isNil: result.sons[1] = newRstNode(rnFieldList)
  1425. assert result.sons[1].kind == rnFieldList
  1426. # Hook the extra field and specify the Nim language as value.
  1427. var extraNode = newRstNode(rnField, info=lineInfo(p))
  1428. extraNode.add(newRstNode(rnFieldName))
  1429. extraNode.add(newRstNode(rnFieldBody))
  1430. extraNode.sons[0].add newLeaf("default-language")
  1431. extraNode.sons[1].add newLeaf("Nim")
  1432. result.sons[1].add(extraNode)
  1433. proc parseMarkdownCodeblock(p: var RstParser): PRstNode =
  1434. result = newRstNodeA(p, rnCodeBlock)
  1435. result.sons.setLen(3)
  1436. let line = curLine(p)
  1437. let baseCol = currentTok(p).col
  1438. let baseSym = currentTok(p).symbol # usually just ```
  1439. inc p.idx
  1440. result.info = lineInfo(p)
  1441. var args = newRstNode(rnDirArg)
  1442. if currentTok(p).kind == tkWord:
  1443. args.add(newLeaf(p))
  1444. inc p.idx
  1445. result.sons[1] = parseMarkdownCodeblockFields(p)
  1446. mayLoadFile(p, result)
  1447. else:
  1448. args = nil
  1449. var n = newLeaf("")
  1450. while true:
  1451. if currentTok(p).kind == tkEof:
  1452. rstMessage(p, meMissingClosing,
  1453. "$1 (started at line $2)" % [baseSym, $line])
  1454. break
  1455. elif nextTok(p).kind in {tkPunct, tkAdornment} and
  1456. nextTok(p).symbol[0] == baseSym[0] and
  1457. nextTok(p).symbol.len >= baseSym.len:
  1458. inc p.idx, 2
  1459. break
  1460. elif currentTok(p).kind == tkIndent:
  1461. n.text.add "\n"
  1462. if currentTok(p).ival > baseCol:
  1463. n.text.add " ".repeat(currentTok(p).ival - baseCol)
  1464. elif currentTok(p).ival < baseCol:
  1465. rstMessage(p, mwRstStyle,
  1466. "unexpected de-indentation in Markdown code block")
  1467. inc p.idx
  1468. else:
  1469. n.text.add(currentTok(p).symbol)
  1470. inc p.idx
  1471. result.sons[0] = args
  1472. if result.sons[2] == nil:
  1473. var lb = newRstNode(rnLiteralBlock)
  1474. lb.add(n)
  1475. result.sons[2] = lb
  1476. if result.sons[0].isNil and roNimFile in p.s.options:
  1477. defaultCodeLangNim(p, result)
  1478. proc parseMarkdownLink(p: var RstParser; father: PRstNode): bool =
  1479. # Parses Markdown link. If it's Pandoc auto-link then its second
  1480. # son (target) will be in tokenized format (rnInner with leafs).
  1481. var desc = newRstNode(rnInner)
  1482. var i = p.idx
  1483. var parensStack: seq[char]
  1484. template parse(endToken, dest) =
  1485. parensStack.setLen 0
  1486. inc i # skip begin token
  1487. while true:
  1488. if p.tok[i].kind == tkEof: return false
  1489. if p.tok[i].kind == tkIndent and p.tok[i+1].kind == tkIndent:
  1490. return false
  1491. let isClosing = checkParen(p.tok[i], parensStack)
  1492. if p.tok[i].symbol == endToken and not isClosing:
  1493. break
  1494. let symbol = if p.tok[i].kind == tkIndent: " " else: p.tok[i].symbol
  1495. when dest is string: dest.add symbol
  1496. else: dest.add newLeaf(symbol)
  1497. inc i
  1498. inc i # skip end token
  1499. parse("]", desc)
  1500. if p.tok[i].symbol == "(":
  1501. var link = ""
  1502. let linkIdx = i + 1
  1503. parse(")", link)
  1504. # only commit if we detected no syntax error:
  1505. let protocol = safeProtocol(link)
  1506. if link == "":
  1507. result = false
  1508. rstMessage(p, mwBrokenLink, protocol,
  1509. p.tok[linkIdx].line, p.tok[linkIdx].col)
  1510. else:
  1511. let child = newRstNode(rnHyperlink)
  1512. child.add newLeaf(desc.addNodes)
  1513. child.add link
  1514. father.add child
  1515. p.idx = i
  1516. result = true
  1517. elif roPreferMarkdown in p.s.options:
  1518. # Use Pandoc's implicit_header_references extension
  1519. var n = newRstNode(rnPandocRef)
  1520. if p.tok[i].symbol == "[":
  1521. var link = newRstNode(rnInner)
  1522. let targetIdx = i + 1
  1523. parse("]", link)
  1524. n.add desc
  1525. if link.len != 0: # [description][target]
  1526. n.add link
  1527. n.info = lineInfo(p, targetIdx)
  1528. else: # [description=target][]
  1529. n.add desc
  1530. n.info = lineInfo(p, p.idx + 1)
  1531. else: # [description=target]
  1532. n.add desc
  1533. n.add desc # target is the same as description
  1534. n.info = lineInfo(p, p.idx + 1)
  1535. father.add n
  1536. p.idx = i
  1537. result = true
  1538. else:
  1539. result = false
  1540. proc getFootnoteType(label: PRstNode): (FootnoteType, int) =
  1541. if label.sons.len >= 1 and label.sons[0].kind == rnLeaf and
  1542. label.sons[0].text == "#":
  1543. if label.sons.len == 1:
  1544. result = (fnAutoNumber, -1)
  1545. else:
  1546. result = (fnAutoNumberLabel, -1)
  1547. elif label.len == 1 and label.sons[0].kind == rnLeaf and
  1548. label.sons[0].text == "*":
  1549. result = (fnAutoSymbol, -1)
  1550. elif label.len == 1 and label.sons[0].kind == rnLeaf:
  1551. try:
  1552. result = (fnManualNumber, parseInt(label.sons[0].text))
  1553. except ValueError:
  1554. result = (fnCitation, -1)
  1555. else:
  1556. result = (fnCitation, -1)
  1557. proc parseFootnoteName(p: var RstParser, reference: bool): PRstNode =
  1558. ## parse footnote/citation label. Precondition: start at `[`.
  1559. ## Label text should be valid ref. name symbol, otherwise nil is returned.
  1560. var i = p.idx + 1
  1561. result = newRstNode(rnInner)
  1562. while true:
  1563. if p.tok[i].kind in {tkEof, tkIndent, tkWhite}:
  1564. return nil
  1565. if p.tok[i].kind == tkPunct:
  1566. case p.tok[i].symbol:
  1567. of "]":
  1568. if i > p.idx + 1 and (not reference or (p.tok[i+1].kind == tkPunct and p.tok[i+1].symbol == "_")):
  1569. inc i # skip ]
  1570. if reference: inc i # skip _
  1571. break # to succeed, it's a footnote/citation indeed
  1572. else:
  1573. return nil
  1574. of "#":
  1575. if i != p.idx + 1:
  1576. return nil
  1577. of "*":
  1578. if i != p.idx + 1 and p.tok[i].kind != tkPunct and p.tok[i+1].symbol != "]":
  1579. return nil
  1580. else:
  1581. if not validRefnamePunct(p.tok[i].symbol):
  1582. return nil
  1583. result.add newLeaf(p.tok[i].symbol)
  1584. inc i
  1585. p.idx = i
  1586. proc isMarkdownCodeBlock(p: RstParser, idx: int): bool =
  1587. let tok = p.tok[idx]
  1588. template allowedSymbol: bool =
  1589. (tok.symbol[0] == '`' or
  1590. roPreferMarkdown in p.s.options and tok.symbol[0] == '~')
  1591. result = (roSupportMarkdown in p.s.options and
  1592. tok.kind in {tkPunct, tkAdornment} and
  1593. allowedSymbol and
  1594. tok.symbol.len >= 3)
  1595. proc isMarkdownCodeBlock(p: RstParser): bool =
  1596. isMarkdownCodeBlock(p, p.idx)
  1597. proc parseInline(p: var RstParser, father: PRstNode) =
  1598. var n: PRstNode # to be used in `if` condition
  1599. let saveIdx = p.idx
  1600. case currentTok(p).kind
  1601. of tkPunct:
  1602. if isInlineMarkupStart(p, "***"):
  1603. var n = newRstNode(rnTripleEmphasis)
  1604. parseUntil(p, n, "***", true)
  1605. father.add(n)
  1606. elif isInlineMarkupStart(p, "**"):
  1607. var n = newRstNode(rnStrongEmphasis)
  1608. parseUntil(p, n, "**", true)
  1609. father.add(n)
  1610. elif isInlineMarkupStart(p, "*"):
  1611. var n = newRstNode(rnEmphasis)
  1612. parseUntil(p, n, "*", true)
  1613. father.add(n)
  1614. elif isInlineMarkupStart(p, "_`"):
  1615. var n = newRstNode(rnInlineTarget)
  1616. inc p.idx
  1617. parseUntil(p, n, "`", false)
  1618. n.anchor = rstnodeToRefname(n)
  1619. addAnchorRst(p, name = linkName(n), target = n,
  1620. anchorType=manualInlineAnchor)
  1621. father.add(n)
  1622. elif isMarkdownCodeBlock(p):
  1623. father.add(parseMarkdownCodeblock(p))
  1624. elif isInlineMarkupStart(p, "``"):
  1625. var n = newRstNode(rnInlineLiteral)
  1626. parseUntil(p, n, "``", false)
  1627. father.add(n)
  1628. elif match(p, p.idx, ":w:") and
  1629. (var lastIdx = getRefnameIdx(p, p.idx + 1);
  1630. p.tok[lastIdx+2].symbol == "`"):
  1631. let (roleName, _) = getRefname(p, p.idx+1)
  1632. let k = whichRole(p, roleName)
  1633. var n = newRstNode(k)
  1634. p.idx = lastIdx + 2
  1635. if k == rnInlineCode:
  1636. n = n.toInlineCode(language=roleName)
  1637. parseUntil(p, n, "`", false) # bug #17260
  1638. if k in {rnUnknownRole, rnCodeFragment}:
  1639. n = n.toOtherRole(k, roleName)
  1640. father.add(n)
  1641. elif isInlineMarkupStart(p, "`"):
  1642. var n = newRstNode(rnInterpretedText, info=lineInfo(p, p.idx+1))
  1643. parseUntil(p, n, "`", false) # bug #17260
  1644. n = parsePostfix(p, n)
  1645. father.add(n)
  1646. elif isInlineMarkupStart(p, "|"):
  1647. var n = newRstNode(rnSubstitutionReferences, info=lineInfo(p, p.idx+1))
  1648. parseUntil(p, n, "|", false)
  1649. father.add(n)
  1650. elif roSupportMarkdown in p.s.options and
  1651. currentTok(p).symbol == "[" and nextTok(p).symbol != "[" and
  1652. parseMarkdownLink(p, father):
  1653. discard "parseMarkdownLink already processed it"
  1654. elif isInlineMarkupStart(p, "[") and nextTok(p).symbol != "[" and
  1655. (n = parseFootnoteName(p, reference=true); n != nil):
  1656. var nn = newRstNode(rnFootnoteRef)
  1657. nn.info = lineInfo(p, saveIdx+1)
  1658. nn.add n
  1659. let (fnType, _) = getFootnoteType(n)
  1660. case fnType
  1661. of fnAutoSymbol:
  1662. p.s.lineFootnoteSymRef.add lineInfo(p)
  1663. of fnAutoNumber:
  1664. p.s.lineFootnoteNumRef.add lineInfo(p)
  1665. else: discard
  1666. father.add(nn)
  1667. else:
  1668. if roSupportSmilies in p.s.options:
  1669. let n = parseSmiley(p)
  1670. if n != nil:
  1671. father.add(n)
  1672. return
  1673. parseBackslash(p, father)
  1674. of tkWord:
  1675. if roSupportSmilies in p.s.options:
  1676. let n = parseSmiley(p)
  1677. if n != nil:
  1678. father.add(n)
  1679. return
  1680. parseWordOrRef(p, father)
  1681. of tkAdornment, tkOther, tkWhite:
  1682. if isMarkdownCodeBlock(p):
  1683. father.add(parseMarkdownCodeblock(p))
  1684. return
  1685. if roSupportSmilies in p.s.options:
  1686. let n = parseSmiley(p)
  1687. if n != nil:
  1688. father.add(n)
  1689. return
  1690. father.add(newLeaf(p))
  1691. inc p.idx
  1692. else: discard
  1693. proc getDirective(p: var RstParser): string =
  1694. result = ""
  1695. if currentTok(p).kind == tkWhite:
  1696. let (name, lastIdx) = getRefname(p, p.idx + 1)
  1697. let afterIdx = lastIdx + 1
  1698. if name.len > 0:
  1699. if p.tok[afterIdx].symbol == "::":
  1700. result = name
  1701. p.idx = afterIdx + 1
  1702. if currentTok(p).kind == tkWhite:
  1703. inc p.idx
  1704. elif currentTok(p).kind != tkIndent:
  1705. rstMessage(p, mwRstStyle,
  1706. "whitespace or newline expected after directive " & name)
  1707. result = result.toLowerAscii()
  1708. elif p.tok[afterIdx].symbol == ":":
  1709. rstMessage(p, mwRstStyle,
  1710. "double colon :: may be missing at end of '" & name & "'",
  1711. p.tok[afterIdx].line, p.tok[afterIdx].col)
  1712. elif p.tok[afterIdx].kind == tkPunct and p.tok[afterIdx].symbol[0] == ':':
  1713. rstMessage(p, mwRstStyle,
  1714. "too many colons for a directive (should be ::)",
  1715. p.tok[afterIdx].line, p.tok[afterIdx].col)
  1716. proc parseComment(p: var RstParser, col: int): PRstNode =
  1717. if currentTok(p).kind != tkEof and nextTok(p).kind == tkIndent:
  1718. inc p.idx # empty comment
  1719. else:
  1720. while currentTok(p).kind != tkEof:
  1721. if currentTok(p).kind == tkIndent and currentTok(p).ival > col or
  1722. currentTok(p).kind != tkIndent and currentTok(p).col > col:
  1723. inc p.idx
  1724. else:
  1725. break
  1726. result = nil
  1727. proc parseLine(p: var RstParser, father: PRstNode) =
  1728. while true:
  1729. case currentTok(p).kind
  1730. of tkWhite, tkWord, tkOther, tkPunct: parseInline(p, father)
  1731. else: break
  1732. proc parseUntilNewline(p: var RstParser, father: PRstNode) =
  1733. while true:
  1734. case currentTok(p).kind
  1735. of tkWhite, tkWord, tkAdornment, tkOther, tkPunct: parseInline(p, father)
  1736. of tkEof, tkIndent: break
  1737. proc parseSection(p: var RstParser, result: PRstNode) {.gcsafe.}
  1738. proc tokenAfterNewline(p: RstParser, start: int): int =
  1739. result = start
  1740. while true:
  1741. case p.tok[result].kind
  1742. of tkEof:
  1743. break
  1744. of tkIndent:
  1745. inc result
  1746. break
  1747. else: inc result
  1748. proc tokenAfterNewline(p: RstParser): int {.inline.} =
  1749. result = tokenAfterNewline(p, p.idx)
  1750. proc getWrappableIndent(p: RstParser): int =
  1751. ## Gets baseline indentation for bodies of field lists and directives.
  1752. ## Handles situations like this (with possible de-indent in [case.3])::
  1753. ##
  1754. ## :field: definition [case.1]
  1755. ##
  1756. ## currInd currentTok(p).col
  1757. ## | |
  1758. ## v v
  1759. ##
  1760. ## .. Note:: defItem: [case.2]
  1761. ## definition
  1762. ##
  1763. ## ^
  1764. ## |
  1765. ## nextIndent
  1766. ##
  1767. ## .. Note:: - point1 [case.3]
  1768. ## - point 2
  1769. ##
  1770. ## ^
  1771. ## |
  1772. ## nextIndent
  1773. if currentTok(p).kind == tkIndent:
  1774. result = currentTok(p).ival
  1775. else:
  1776. var nextIndent = p.tok[tokenAfterNewline(p)-1].ival
  1777. if nextIndent <= currInd(p): # parse only this line [case.1]
  1778. result = currentTok(p).col
  1779. elif nextIndent >= currentTok(p).col: # may be a definition list [case.2]
  1780. result = currentTok(p).col
  1781. else:
  1782. result = nextIndent # allow parsing next lines [case.3]
  1783. proc getMdBlockIndent(p: RstParser): int =
  1784. ## Markdown version of `getWrappableIndent`.
  1785. if currentTok(p).kind == tkIndent:
  1786. result = currentTok(p).ival
  1787. else:
  1788. var nextIndent = p.tok[tokenAfterNewline(p)-1].ival
  1789. # TODO: Markdown-compliant definition should allow nextIndent == currInd(p):
  1790. if nextIndent <= currInd(p): # parse only this line
  1791. result = currentTok(p).col
  1792. else:
  1793. result = nextIndent # allow parsing next lines [case.3]
  1794. template isRst(p: RstParser): bool = roPreferMarkdown notin p.s.options
  1795. template isMd(p: RstParser): bool = roPreferMarkdown in p.s.options
  1796. proc parseField(p: var RstParser): PRstNode =
  1797. ## Returns a parsed rnField node.
  1798. ##
  1799. ## rnField nodes have two children nodes, a rnFieldName and a rnFieldBody.
  1800. result = newRstNode(rnField, info=lineInfo(p))
  1801. var col = currentTok(p).col
  1802. var fieldname = newRstNode(rnFieldName)
  1803. parseUntil(p, fieldname, ":", false)
  1804. var fieldbody = newRstNode(rnFieldBody)
  1805. if currentTok(p).kind == tkWhite: inc p.idx
  1806. let indent = getWrappableIndent(p)
  1807. if indent > col:
  1808. pushInd(p, indent)
  1809. parseSection(p, fieldbody)
  1810. popInd(p)
  1811. result.add(fieldname)
  1812. result.add(fieldbody)
  1813. proc parseFields(p: var RstParser): PRstNode =
  1814. ## Parses fields for a section or directive block.
  1815. ##
  1816. ## This proc may return nil if the parsing doesn't find anything of value,
  1817. ## otherwise it will return a node of rnFieldList type with children.
  1818. result = nil
  1819. var atStart = p.idx == 0 and p.tok[0].symbol == ":"
  1820. if currentTok(p).kind == tkIndent and nextTok(p).symbol == ":" or
  1821. atStart:
  1822. var col = if atStart: currentTok(p).col else: currentTok(p).ival
  1823. result = newRstNodeA(p, rnFieldList)
  1824. if not atStart: inc p.idx
  1825. while true:
  1826. result.add(parseField(p))
  1827. if currentTok(p).kind == tkIndent and currentTok(p).ival == col and
  1828. nextTok(p).symbol == ":":
  1829. inc p.idx
  1830. else:
  1831. break
  1832. proc getFieldValue*(n: PRstNode): string =
  1833. ## Returns the value of a specific ``rnField`` node.
  1834. ##
  1835. ## This proc will assert if the node is not of the expected type. The empty
  1836. ## string will be returned as a minimum. Any value in the rst will be
  1837. ## stripped form leading/trailing whitespace.
  1838. assert n.kind == rnField
  1839. assert n.len == 2
  1840. assert n.sons[0].kind == rnFieldName
  1841. assert n.sons[1].kind == rnFieldBody
  1842. result = addNodes(n.sons[1]).strip
  1843. proc getFieldValue(n: PRstNode, fieldname: string): string =
  1844. if n.sons[1] == nil: return
  1845. if n.sons[1].kind != rnFieldList:
  1846. #InternalError("getFieldValue (2): " & $n.sons[1].kind)
  1847. # We don't like internal errors here anymore as that would break the forum!
  1848. return
  1849. for i in 0 ..< n.sons[1].len:
  1850. var f = n.sons[1].sons[i]
  1851. if cmpIgnoreStyle(addNodes(f.sons[0]), fieldname) == 0:
  1852. result = addNodes(f.sons[1])
  1853. if result == "": result = "\x01\x01" # indicates that the field exists
  1854. return
  1855. proc getArgument(n: PRstNode): string =
  1856. if n.sons[0] == nil: result = ""
  1857. else: result = addNodes(n.sons[0])
  1858. proc parseDotDot(p: var RstParser): PRstNode {.gcsafe.}
  1859. proc parseLiteralBlock(p: var RstParser): PRstNode =
  1860. result = newRstNodeA(p, rnLiteralBlock)
  1861. var n = newLeaf("")
  1862. if currentTok(p).kind == tkIndent:
  1863. var indent = currentTok(p).ival
  1864. while currentTok(p).kind == tkIndent: inc p.idx # skip blank lines
  1865. while true:
  1866. case currentTok(p).kind
  1867. of tkEof:
  1868. break
  1869. of tkIndent:
  1870. if currentTok(p).ival < indent:
  1871. break
  1872. else:
  1873. n.text.add("\n")
  1874. n.text.add(spaces(currentTok(p).ival - indent))
  1875. inc p.idx
  1876. else:
  1877. n.text.add(currentTok(p).symbol)
  1878. inc p.idx
  1879. else:
  1880. while currentTok(p).kind notin {tkIndent, tkEof}:
  1881. n.text.add(currentTok(p).symbol)
  1882. inc p.idx
  1883. result.add(n)
  1884. proc parseQuotedLiteralBlock(p: var RstParser): PRstNode =
  1885. result = newRstNodeA(p, rnLiteralBlock)
  1886. var n = newLeaf("")
  1887. if currentTok(p).kind == tkIndent:
  1888. var indent = currInd(p)
  1889. while currentTok(p).kind == tkIndent: inc p.idx # skip blank lines
  1890. var quoteSym = currentTok(p).symbol[0]
  1891. while true:
  1892. case currentTok(p).kind
  1893. of tkEof:
  1894. break
  1895. of tkIndent:
  1896. if currentTok(p).ival < indent:
  1897. break
  1898. elif currentTok(p).ival == indent:
  1899. if nextTok(p).kind == tkPunct and nextTok(p).symbol[0] == quoteSym:
  1900. n.text.add("\n")
  1901. inc p.idx
  1902. elif nextTok(p).kind == tkIndent:
  1903. break
  1904. else:
  1905. rstMessage(p, mwRstStyle, "no newline after quoted literal block")
  1906. break
  1907. else:
  1908. rstMessage(p, mwRstStyle,
  1909. "unexpected indentation in quoted literal block")
  1910. break
  1911. else:
  1912. n.text.add(currentTok(p).symbol)
  1913. inc p.idx
  1914. result.add(n)
  1915. proc parseRstLiteralBlock(p: var RstParser, kind: LiteralBlockKind): PRstNode =
  1916. if kind == lbIndentedLiteralBlock:
  1917. result = parseLiteralBlock(p)
  1918. else:
  1919. result = parseQuotedLiteralBlock(p)
  1920. proc getLevel(p: var RstParser, c: char, hasOverline: bool): int =
  1921. ## Returns (preliminary) heading level corresponding to `c` and
  1922. ## `hasOverline`. If level does not exist, add it first.
  1923. for i, hType in p.s.hLevels:
  1924. if hType.symbol == c and hType.hasOverline == hasOverline:
  1925. p.s.hLevels[i].line = curLine(p)
  1926. p.s.hLevels[i].hasPeers = true
  1927. return i
  1928. p.s.hLevels.add LevelInfo(symbol: c, hasOverline: hasOverline,
  1929. line: curLine(p), hasPeers: false)
  1930. result = p.s.hLevels.len - 1
  1931. proc countTitles(s: PRstSharedState, n: PRstNode) =
  1932. ## Fill `s.hTitleCnt`
  1933. if n == nil: return
  1934. for node in n.sons:
  1935. if node != nil:
  1936. if node.kind notin {rnOverline, rnSubstitutionDef, rnDefaultRole}:
  1937. break
  1938. if node.kind == rnOverline:
  1939. if s.hLevels[s.hTitleCnt].hasPeers:
  1940. break
  1941. inc s.hTitleCnt
  1942. if s.hTitleCnt >= 2:
  1943. break
  1944. proc isAdornmentHeadline(p: RstParser, adornmentIdx: int): bool =
  1945. ## check that underline/overline length is enough for the heading.
  1946. ## No support for Unicode.
  1947. if p.tok[adornmentIdx].symbol in ["::", "..", "|"]:
  1948. return false
  1949. if isMarkdownCodeBlock(p, adornmentIdx):
  1950. return false
  1951. var headlineLen = 0
  1952. var failure = ""
  1953. if p.idx < adornmentIdx: # check for underline
  1954. if p.idx > 0:
  1955. headlineLen = currentTok(p).col - p.tok[adornmentIdx].col
  1956. if headlineLen > 0:
  1957. rstMessage(p, mwRstStyle, "indentation of heading text allowed" &
  1958. " only for overline titles")
  1959. for i in p.idx ..< adornmentIdx-1: # adornmentIdx-1 is a linebreak
  1960. headlineLen += p.tok[i].symbol.len
  1961. result = p.tok[adornmentIdx].symbol.len >= headlineLen and headlineLen != 0
  1962. if not result:
  1963. failure = "(underline '" & p.tok[adornmentIdx].symbol & "' is too short)"
  1964. else: # p.idx == adornmentIdx, at overline. Check overline and underline
  1965. var i = p.idx + 2
  1966. headlineLen = p.tok[i].col - p.tok[adornmentIdx].col
  1967. while p.tok[i].kind notin {tkEof, tkIndent}:
  1968. headlineLen += p.tok[i].symbol.len
  1969. inc i
  1970. result = p.tok[adornmentIdx].symbol.len >= headlineLen and
  1971. headlineLen != 0
  1972. if result:
  1973. result = result and p.tok[i].kind == tkIndent and
  1974. p.tok[i+1].kind == tkAdornment and
  1975. p.tok[i+1].symbol == p.tok[adornmentIdx].symbol
  1976. if not result:
  1977. failure = "(underline '" & p.tok[i+1].symbol & "' does not match " &
  1978. "overline '" & p.tok[adornmentIdx].symbol & "')"
  1979. else:
  1980. failure = "(overline '" & p.tok[adornmentIdx].symbol & "' is too short)"
  1981. if not result:
  1982. rstMessage(p, meNewSectionExpected, failure)
  1983. proc isLineBlock(p: RstParser): bool =
  1984. var j = tokenAfterNewline(p)
  1985. result = currentTok(p).col == p.tok[j].col and p.tok[j].symbol == "|" or
  1986. p.tok[j].col > currentTok(p).col or
  1987. p.tok[j].symbol == "\n"
  1988. proc isMarkdownBlockQuote(p: RstParser): bool =
  1989. result = currentTok(p).symbol[0] == '>'
  1990. proc whichRstLiteralBlock(p: RstParser): LiteralBlockKind =
  1991. ## Checks that the following tokens are either Indented Literal Block or
  1992. ## Quoted Literal Block (which is not quite the same as Markdown quote block).
  1993. ## https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#quoted-literal-blocks
  1994. if currentTok(p).symbol == "::" and nextTok(p).kind == tkIndent:
  1995. if currInd(p) > nextTok(p).ival:
  1996. result = lbNone
  1997. if currInd(p) < nextTok(p).ival:
  1998. result = lbIndentedLiteralBlock
  1999. elif currInd(p) == nextTok(p).ival:
  2000. var i = p.idx + 1
  2001. while p.tok[i].kind == tkIndent: inc i
  2002. const validQuotingCharacters = {
  2003. '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-',
  2004. '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^',
  2005. '_', '`', '{', '|', '}', '~'}
  2006. if p.tok[i].kind in {tkPunct, tkAdornment} and
  2007. p.tok[i].symbol[0] in validQuotingCharacters:
  2008. result = lbQuotedLiteralBlock
  2009. else:
  2010. result = lbNone
  2011. else:
  2012. result = lbNone
  2013. proc predNL(p: RstParser): bool =
  2014. result = true
  2015. if p.idx > 0:
  2016. result = prevTok(p).kind == tkIndent and
  2017. prevTok(p).ival == currInd(p)
  2018. proc isDefList(p: RstParser): bool =
  2019. var j = tokenAfterNewline(p)
  2020. result = currentTok(p).col < p.tok[j].col and
  2021. p.tok[j].kind in {tkWord, tkOther, tkPunct} and
  2022. p.tok[j - 2].symbol != "::"
  2023. proc `$`(t: Token): string = # for debugging only
  2024. result = "(" & $t.kind & " line=" & $t.line & " col=" & $t.col
  2025. if t.kind == tkIndent: result = result & " ival=" & $t.ival & ")"
  2026. else: result = result & " symbol=" & t.symbol & ")"
  2027. proc skipNewlines(p: RstParser, j: int): int =
  2028. result = j
  2029. while p.tok[result].kind != tkEof and p.tok[result].kind == tkIndent:
  2030. inc result # skip blank lines
  2031. proc skipNewlines(p: var RstParser) =
  2032. p.idx = skipNewlines(p, p.idx)
  2033. const maxMdRelInd = 3 ## In Markdown: maximum indentation that does not yet
  2034. ## make the indented block a code
  2035. proc isMdRelInd(outerInd, nestedInd: int): bool =
  2036. result = outerInd <= nestedInd and nestedInd <= outerInd + maxMdRelInd
  2037. proc isMdDefBody(p: RstParser, j: int, termCol: int): bool =
  2038. let defCol = p.tok[j].col
  2039. result = p.tok[j].symbol == ":" and
  2040. isMdRelInd(termCol, defCol) and
  2041. p.tok[j+1].kind == tkWhite and
  2042. p.tok[j+2].kind in {tkWord, tkOther, tkPunct}
  2043. proc isMdDefListItem(p: RstParser, idx: int): bool =
  2044. var j = tokenAfterNewline(p, idx)
  2045. j = skipNewlines(p, j)
  2046. let termCol = p.tok[j].col
  2047. result = isMdRelInd(currInd(p), termCol) and
  2048. isMdDefBody(p, j, termCol)
  2049. proc isOptionList(p: RstParser): bool =
  2050. result = match(p, p.idx, "-w") or match(p, p.idx, "--w") or
  2051. match(p, p.idx, "/w") or match(p, p.idx, "//w")
  2052. proc isMarkdownHeadlinePattern(s: string): bool =
  2053. if s.len >= 1 and s.len <= 6:
  2054. for c in s:
  2055. if c != '#': return false
  2056. result = true
  2057. proc isMarkdownHeadline(p: RstParser): bool =
  2058. if roSupportMarkdown in p.s.options:
  2059. if isMarkdownHeadlinePattern(currentTok(p).symbol) and nextTok(p).kind == tkWhite:
  2060. if p.tok[p.idx+2].kind in {tkWord, tkOther, tkPunct}:
  2061. result = true
  2062. proc findPipe(p: RstParser, start: int): bool =
  2063. var i = start
  2064. while true:
  2065. if p.tok[i].symbol == "|": return true
  2066. if p.tok[i].kind in {tkIndent, tkEof}: return false
  2067. inc i
  2068. proc whichSection(p: RstParser): RstNodeKind =
  2069. if currentTok(p).kind in {tkAdornment, tkPunct}:
  2070. # for punctuation sequences that can be both tkAdornment and tkPunct
  2071. if isMarkdownCodeBlock(p):
  2072. return rnCodeBlock
  2073. elif isRst(p) and currentTok(p).symbol == "::":
  2074. return rnLiteralBlock
  2075. elif currentTok(p).symbol == ".." and
  2076. nextTok(p).kind in {tkWhite, tkIndent}:
  2077. return rnDirective
  2078. case currentTok(p).kind
  2079. of tkAdornment:
  2080. if match(p, p.idx + 1, "iI") and currentTok(p).symbol.len >= 4:
  2081. result = rnTransition
  2082. elif match(p, p.idx, "+a+"):
  2083. result = rnGridTable
  2084. rstMessage(p, meGridTableNotImplemented)
  2085. elif match(p, p.idx + 1, " a"): result = rnTable
  2086. elif currentTok(p).symbol == "|" and isLineBlock(p):
  2087. result = rnLineBlock
  2088. elif roSupportMarkdown in p.s.options and isMarkdownBlockQuote(p):
  2089. result = rnMarkdownBlockQuote
  2090. elif match(p, p.idx + 1, "i") and isAdornmentHeadline(p, p.idx):
  2091. result = rnOverline
  2092. else:
  2093. result = rnLeaf
  2094. of tkPunct:
  2095. if isMarkdownHeadline(p):
  2096. result = rnMarkdownHeadline
  2097. elif roSupportMarkdown in p.s.options and predNL(p) and
  2098. match(p, p.idx, "| w") and findPipe(p, p.idx+3):
  2099. result = rnMarkdownTable
  2100. elif currentTok(p).symbol == "|" and isLineBlock(p):
  2101. result = rnLineBlock
  2102. elif roSupportMarkdown in p.s.options and isMarkdownBlockQuote(p):
  2103. result = rnMarkdownBlockQuote
  2104. elif match(p, tokenAfterNewline(p), "aI") and
  2105. isAdornmentHeadline(p, tokenAfterNewline(p)):
  2106. result = rnHeadline
  2107. elif currentTok(p).symbol in ["+", "*", "-"] and nextTok(p).kind == tkWhite:
  2108. result = rnBulletList
  2109. elif match(p, p.idx, ":w:E"):
  2110. # (currentTok(p).symbol == ":")
  2111. result = rnFieldList
  2112. elif match(p, p.idx, "(e) ") or match(p, p.idx, "e) ") or
  2113. match(p, p.idx, "e. "):
  2114. result = rnEnumList
  2115. elif isOptionList(p):
  2116. result = rnOptionList
  2117. elif isRst(p) and isDefList(p):
  2118. result = rnDefList
  2119. elif isMd(p) and isMdDefListItem(p, p.idx):
  2120. result = rnMdDefList
  2121. else:
  2122. result = rnParagraph
  2123. of tkWord, tkOther, tkWhite:
  2124. let tokIdx = tokenAfterNewline(p)
  2125. if match(p, tokIdx, "aI"):
  2126. if isAdornmentHeadline(p, tokIdx): result = rnHeadline
  2127. else: result = rnParagraph
  2128. elif match(p, p.idx, "e) ") or match(p, p.idx, "e. "): result = rnEnumList
  2129. elif isRst(p) and isDefList(p): result = rnDefList
  2130. elif isMd(p) and isMdDefListItem(p, p.idx):
  2131. result = rnMdDefList
  2132. else: result = rnParagraph
  2133. else: result = rnLeaf
  2134. proc parseLineBlock(p: var RstParser): PRstNode =
  2135. ## Returns rnLineBlock with all sons of type rnLineBlockItem
  2136. result = nil
  2137. if nextTok(p).kind in {tkWhite, tkIndent}:
  2138. var col = currentTok(p).col
  2139. result = newRstNodeA(p, rnLineBlock)
  2140. while true:
  2141. var item = newRstNode(rnLineBlockItem)
  2142. if nextTok(p).kind == tkWhite:
  2143. if nextTok(p).symbol.len > 1: # pass additional indentation after '| '
  2144. item.lineIndent = nextTok(p).symbol
  2145. inc p.idx, 2
  2146. pushInd(p, p.tok[p.idx].col)
  2147. parseSection(p, item)
  2148. popInd(p)
  2149. else: # tkIndent => add an empty line
  2150. item.lineIndent = "\n"
  2151. inc p.idx, 1
  2152. result.add(item)
  2153. if currentTok(p).kind == tkIndent and currentTok(p).ival == col and
  2154. nextTok(p).symbol == "|" and
  2155. p.tok[p.idx + 2].kind in {tkWhite, tkIndent}:
  2156. inc p.idx, 1
  2157. else:
  2158. break
  2159. proc parseDoc(p: var RstParser): PRstNode {.gcsafe.}
  2160. proc getQuoteSymbol(p: RstParser, idx: int): tuple[sym: string, depth: int, tokens: int] =
  2161. result = ("", 0, 0)
  2162. var i = idx
  2163. result.sym &= p.tok[i].symbol
  2164. result.depth += p.tok[i].symbol.len
  2165. inc result.tokens
  2166. inc i
  2167. while p.tok[i].kind == tkWhite and i+1 < p.tok.len and
  2168. p.tok[i+1].kind == tkPunct and p.tok[i+1].symbol[0] == '>':
  2169. result.sym &= p.tok[i].symbol
  2170. result.sym &= p.tok[i+1].symbol
  2171. result.depth += p.tok[i+1].symbol.len
  2172. inc result.tokens, 2
  2173. inc i, 2
  2174. proc parseMarkdownQuoteSegment(p: var RstParser, curSym: string, col: int):
  2175. PRstNode =
  2176. ## We define *segment* as a group of lines that starts with exactly the
  2177. ## same quote symbol. If the following lines don't contain any `>` (*lazy*
  2178. ## continuation) they considered as continuation of the current segment.
  2179. var q: RstParser # to delete `>` at a start of line and then parse normally
  2180. initParser(q, p.s)
  2181. q.col = p.col
  2182. q.line = p.line
  2183. var minCol = int.high # minimum colum num in the segment
  2184. while true: # move tokens of segment from `p` to `q` skipping `curSym`
  2185. case currentTok(p).kind
  2186. of tkEof:
  2187. break
  2188. of tkIndent:
  2189. if nextTok(p).kind in {tkIndent, tkEof}:
  2190. break
  2191. else:
  2192. if nextTok(p).symbol[0] == '>':
  2193. var (quoteSym, _, quoteTokens) = getQuoteSymbol(p, p.idx + 1)
  2194. if quoteSym == curSym: # the segment continues
  2195. var iTok = tokenAfterNewline(p, p.idx+1)
  2196. if p.tok[iTok].kind notin {tkEof, tkIndent} and
  2197. p.tok[iTok].symbol[0] != '>':
  2198. rstMessage(p, mwRstStyle,
  2199. "two or more quoted lines are followed by unquoted line " &
  2200. $(curLine(p) + 1))
  2201. break
  2202. q.tok.add currentTok(p)
  2203. var ival = currentTok(p).ival + quoteSym.len
  2204. inc p.idx, (1 + quoteTokens) # skip newline and > > >
  2205. if currentTok(p).kind == tkWhite:
  2206. ival += currentTok(p).symbol.len
  2207. inc p.idx
  2208. # fix up previous `tkIndent`s to ival (as if >>> were not there)
  2209. var j = q.tok.len - 1
  2210. while j >= 0 and q.tok[j].kind == tkIndent:
  2211. q.tok[j].ival = ival
  2212. dec j
  2213. else: # next segment started
  2214. break
  2215. elif currentTok(p).ival < col:
  2216. break
  2217. else: # the segment continues, a case like:
  2218. # > beginning
  2219. # continuation
  2220. q.tok.add currentTok(p)
  2221. inc p.idx
  2222. else:
  2223. if currentTok(p).col < minCol: minCol = currentTok(p).col
  2224. q.tok.add currentTok(p)
  2225. inc p.idx
  2226. q.indentStack = @[minCol]
  2227. # if initial indentation `minCol` is > 0 then final newlines
  2228. # should be omitted so that parseDoc could advance to the end of tokens:
  2229. var j = q.tok.len - 1
  2230. while q.tok[j].kind == tkIndent: dec j
  2231. q.tok.setLen (j+1)
  2232. q.tok.add Token(kind: tkEof, line: currentTok(p).line)
  2233. result = parseDoc(q)
  2234. proc parseMarkdownBlockQuote(p: var RstParser): PRstNode =
  2235. var (curSym, quotationDepth, quoteTokens) = getQuoteSymbol(p, p.idx)
  2236. let col = currentTok(p).col
  2237. result = newRstNodeA(p, rnMarkdownBlockQuote)
  2238. inc p.idx, quoteTokens # skip first >
  2239. while true:
  2240. var item = newRstNode(rnMarkdownBlockQuoteItem)
  2241. item.quotationDepth = quotationDepth
  2242. if currentTok(p).kind == tkWhite: inc p.idx
  2243. item.add parseMarkdownQuoteSegment(p, curSym, col)
  2244. result.add(item)
  2245. if currentTok(p).kind == tkIndent and currentTok(p).ival == col and
  2246. nextTok(p).kind != tkEof and nextTok(p).symbol[0] == '>':
  2247. (curSym, quotationDepth, quoteTokens) = getQuoteSymbol(p, p.idx + 1)
  2248. inc p.idx, (1 + quoteTokens) # skip newline and > > >
  2249. else:
  2250. break
  2251. proc parseParagraph(p: var RstParser, result: PRstNode) =
  2252. while true:
  2253. case currentTok(p).kind
  2254. of tkIndent:
  2255. if nextTok(p).kind == tkIndent:
  2256. inc p.idx
  2257. break # blank line breaks paragraph for both Md & Rst
  2258. elif currentTok(p).ival == currInd(p) or (
  2259. isMd(p) and currentTok(p).ival > currInd(p)):
  2260. # (Md allows adding additional indentation inside paragraphs)
  2261. inc p.idx
  2262. case whichSection(p)
  2263. of rnParagraph, rnLeaf, rnHeadline, rnMarkdownHeadline,
  2264. rnOverline, rnDirective:
  2265. result.add newLeaf(" ")
  2266. of rnLineBlock:
  2267. result.addIfNotNil(parseLineBlock(p))
  2268. of rnMarkdownBlockQuote:
  2269. result.addIfNotNil(parseMarkdownBlockQuote(p))
  2270. else:
  2271. dec p.idx # allow subsequent block to be parsed as another section
  2272. break
  2273. else:
  2274. break
  2275. of tkPunct:
  2276. if isRst(p) and (
  2277. let literalBlockKind = whichRstLiteralBlock(p);
  2278. literalBlockKind != lbNone):
  2279. result.add newLeaf(":")
  2280. inc p.idx # skip '::'
  2281. result.add(parseRstLiteralBlock(p, literalBlockKind))
  2282. break
  2283. else:
  2284. parseInline(p, result)
  2285. of tkWhite, tkWord, tkAdornment, tkOther:
  2286. parseInline(p, result)
  2287. else: break
  2288. proc checkHeadingHierarchy(p: RstParser, lvl: int) =
  2289. if lvl - p.s.hCurLevel > 1: # broken hierarchy!
  2290. proc descr(l: int): string =
  2291. (if p.s.hLevels[l].hasOverline: "overline " else: "underline ") &
  2292. repeat(p.s.hLevels[l].symbol, 5)
  2293. var msg = "(section level inconsistent: "
  2294. msg.add descr(lvl) & " unexpectedly found, " &
  2295. "while the following intermediate section level(s) are missing on lines "
  2296. msg.add $p.s.hLevels[p.s.hCurLevel].line & ".." & $curLine(p) & ":"
  2297. for l in p.s.hCurLevel+1 .. lvl-1:
  2298. msg.add " " & descr(l)
  2299. if l != lvl-1: msg.add ","
  2300. rstMessage(p, meNewSectionExpected, msg & ")")
  2301. proc parseHeadline(p: var RstParser): PRstNode =
  2302. if isMarkdownHeadline(p):
  2303. result = newRstNode(rnMarkdownHeadline)
  2304. # Note that level hierarchy is not checked for markdown headings
  2305. result.level = currentTok(p).symbol.len
  2306. assert(nextTok(p).kind == tkWhite)
  2307. inc p.idx, 2
  2308. parseUntilNewline(p, result)
  2309. else:
  2310. result = newRstNode(rnHeadline)
  2311. parseUntilNewline(p, result)
  2312. assert(currentTok(p).kind == tkIndent)
  2313. assert(nextTok(p).kind == tkAdornment)
  2314. var c = nextTok(p).symbol[0]
  2315. inc p.idx, 2
  2316. result.level = getLevel(p, c, hasOverline=false)
  2317. checkHeadingHierarchy(p, result.level)
  2318. p.s.hCurLevel = result.level
  2319. addAnchorRst(p, linkName(result), result, anchorType=headlineAnchor)
  2320. p.s.tocPart.add result
  2321. proc parseOverline(p: var RstParser): PRstNode =
  2322. var c = currentTok(p).symbol[0]
  2323. inc p.idx, 2
  2324. result = newRstNode(rnOverline)
  2325. while true:
  2326. parseUntilNewline(p, result)
  2327. if currentTok(p).kind == tkIndent:
  2328. inc p.idx
  2329. if prevTok(p).ival > currInd(p):
  2330. result.add newLeaf(" ")
  2331. else:
  2332. break
  2333. else:
  2334. break
  2335. result.level = getLevel(p, c, hasOverline=true)
  2336. checkHeadingHierarchy(p, result.level)
  2337. p.s.hCurLevel = result.level
  2338. if currentTok(p).kind == tkAdornment:
  2339. inc p.idx
  2340. if currentTok(p).kind == tkIndent: inc p.idx
  2341. addAnchorRst(p, linkName(result), result, anchorType=headlineAnchor)
  2342. p.s.tocPart.add result
  2343. proc fixHeadlines(s: PRstSharedState) =
  2344. # Fix up section levels depending on presence of a title and subtitle:
  2345. for n in s.tocPart:
  2346. if n.kind in {rnHeadline, rnOverline}:
  2347. if s.hTitleCnt == 2:
  2348. if n.level == 1: # it's the subtitle
  2349. n.level = 0
  2350. elif n.level >= 2: # normal sections, start numbering from 1
  2351. n.level -= 1
  2352. elif s.hTitleCnt == 0:
  2353. n.level += 1
  2354. # Set headline anchors:
  2355. for iHeading in 0 .. s.tocPart.high:
  2356. let n: PRstNode = s.tocPart[iHeading]
  2357. if n.level >= 1:
  2358. n.anchor = rstnodeToRefname(n)
  2359. # Fix anchors for uniqueness if `.. contents::` is present
  2360. if s.hasToc:
  2361. # Find the last higher level section for unique reference name
  2362. var sectionPrefix = ""
  2363. for i in countdown(iHeading - 1, 0):
  2364. if s.tocPart[i].level >= 1 and s.tocPart[i].level < n.level:
  2365. sectionPrefix = rstnodeToRefname(s.tocPart[i]) & "-"
  2366. break
  2367. if sectionPrefix != "":
  2368. n.anchor = sectionPrefix & n.anchor
  2369. s.tocPart.setLen 0
  2370. type
  2371. ColSpec = object
  2372. start, stop: int
  2373. RstCols = seq[ColSpec]
  2374. ColumnLimits = tuple # for Markdown
  2375. first, last: int
  2376. ColSeq = seq[ColumnLimits]
  2377. proc tokStart(p: RstParser, idx: int): int =
  2378. result = p.tok[idx].col
  2379. proc tokStart(p: RstParser): int =
  2380. result = tokStart(p, p.idx)
  2381. proc tokEnd(p: RstParser, idx: int): int =
  2382. result = p.tok[idx].col + p.tok[idx].symbol.len - 1
  2383. proc tokEnd(p: RstParser): int =
  2384. result = tokEnd(p, p.idx)
  2385. proc getColumns(p: RstParser, cols: var RstCols, startIdx: int): int =
  2386. # Fills table column specification (or separator) `cols` and returns
  2387. # the next parser index after it.
  2388. var L = 0
  2389. result = startIdx
  2390. while true:
  2391. inc L
  2392. setLen(cols, L)
  2393. cols[L - 1].start = tokStart(p, result)
  2394. cols[L - 1].stop = tokEnd(p, result)
  2395. assert(p.tok[result].kind == tkAdornment)
  2396. inc result
  2397. if p.tok[result].kind != tkWhite: break
  2398. inc result
  2399. if p.tok[result].kind != tkAdornment: break
  2400. if p.tok[result].kind == tkIndent: inc result
  2401. proc checkColumns(p: RstParser, cols: RstCols) =
  2402. var i = p.idx
  2403. if p.tok[i].symbol[0] != '=':
  2404. rstMessage(p, mwRstStyle,
  2405. "only tables with `=` columns specification are allowed")
  2406. for col in 0 ..< cols.len:
  2407. if tokEnd(p, i) != cols[col].stop:
  2408. rstMessage(p, meIllformedTable,
  2409. "end of table column #$1 should end at position $2" % [
  2410. $(col+1), $(cols[col].stop+ColRstOffset)],
  2411. p.tok[i].line, tokEnd(p, i))
  2412. inc i
  2413. if col == cols.len - 1:
  2414. if p.tok[i].kind == tkWhite:
  2415. inc i
  2416. if p.tok[i].kind notin {tkIndent, tkEof}:
  2417. rstMessage(p, meIllformedTable, "extraneous column specification")
  2418. elif p.tok[i].kind == tkWhite:
  2419. inc i
  2420. else:
  2421. rstMessage(p, meIllformedTable, "no enough table columns",
  2422. p.tok[i].line, p.tok[i].col)
  2423. proc getSpans(p: RstParser, nextLine: int,
  2424. cols: RstCols, unitedCols: RstCols): seq[int] =
  2425. ## Calculates how many columns a joined cell occupies.
  2426. if unitedCols.len > 0:
  2427. result = newSeq[int](unitedCols.len)
  2428. var
  2429. iCell = 0
  2430. jCell = 0
  2431. uCell = 0
  2432. while jCell < cols.len:
  2433. if cols[jCell].stop < unitedCols[uCell].stop:
  2434. inc jCell
  2435. elif cols[jCell].stop == unitedCols[uCell].stop:
  2436. result[uCell] = jCell - iCell + 1
  2437. iCell = jCell + 1
  2438. jCell = jCell + 1
  2439. inc uCell
  2440. else:
  2441. rstMessage(p, meIllformedTable,
  2442. "spanning underline does not match main table columns",
  2443. p.tok[nextLine].line, p.tok[nextLine].col)
  2444. proc parseSimpleTableRow(p: var RstParser, cols: RstCols, colChar: char): PRstNode =
  2445. ## Parses 1 row in RST simple table.
  2446. # Consider that columns may be spanning (united by using underline like ----):
  2447. let nextLine = tokenAfterNewline(p)
  2448. var unitedCols: RstCols
  2449. var afterSpan: int
  2450. if p.tok[nextLine].kind == tkAdornment and p.tok[nextLine].symbol[0] == '-':
  2451. afterSpan = getColumns(p, unitedCols, nextLine)
  2452. if unitedCols == cols and p.tok[nextLine].symbol[0] == colChar:
  2453. # legacy rst.nim compat.: allow punctuation like `----` in main boundaries
  2454. afterSpan = nextLine
  2455. unitedCols.setLen 0
  2456. else:
  2457. afterSpan = nextLine
  2458. template colEnd(i): int =
  2459. if i == cols.len - 1: high(int) # last column has no limit
  2460. elif unitedCols.len > 0: unitedCols[i].stop else: cols[i].stop
  2461. template colStart(i): int =
  2462. if unitedCols.len > 0: unitedCols[i].start else: cols[i].start
  2463. var row = newSeq[string](if unitedCols.len > 0: unitedCols.len else: cols.len)
  2464. var spans: seq[int] = getSpans(p, nextLine, cols, unitedCols)
  2465. let line = currentTok(p).line
  2466. # Iterate over the lines a single cell may span:
  2467. while true:
  2468. var nCell = 0
  2469. # distribute tokens between cells in the current line:
  2470. while currentTok(p).kind notin {tkIndent, tkEof}:
  2471. if tokEnd(p) <= colEnd(nCell):
  2472. if tokStart(p) < colStart(nCell):
  2473. if currentTok(p).kind != tkWhite:
  2474. rstMessage(p, meIllformedTable,
  2475. "this word crosses table column from the left")
  2476. else:
  2477. inc p.idx
  2478. else:
  2479. row[nCell].add(currentTok(p).symbol)
  2480. inc p.idx
  2481. else:
  2482. if tokStart(p) < colEnd(nCell) and currentTok(p).kind != tkWhite:
  2483. rstMessage(p, meIllformedTable,
  2484. "this word crosses table column from the right")
  2485. inc nCell
  2486. if currentTok(p).kind == tkIndent: inc p.idx
  2487. if tokEnd(p) <= colEnd(0): break
  2488. # Continued current cells because the 1st column is empty.
  2489. if currentTok(p).kind in {tkEof, tkAdornment}:
  2490. break
  2491. for nCell in countup(1, high(row)): row[nCell].add('\n')
  2492. result = newRstNode(rnTableRow)
  2493. var q: RstParser
  2494. for uCell in 0 ..< row.len:
  2495. initParser(q, p.s)
  2496. q.col = colStart(uCell)
  2497. q.line = line - 1
  2498. getTokens(row[uCell], q.tok)
  2499. let cell = newRstNode(rnTableDataCell)
  2500. cell.span = if spans.len == 0: 0 else: spans[uCell]
  2501. cell.add(parseDoc(q))
  2502. result.add(cell)
  2503. if afterSpan > p.idx:
  2504. p.idx = afterSpan
  2505. proc parseSimpleTable(p: var RstParser): PRstNode =
  2506. var cols: RstCols
  2507. result = newRstNodeA(p, rnTable)
  2508. let startIdx = getColumns(p, cols, p.idx)
  2509. let colChar = currentTok(p).symbol[0]
  2510. checkColumns(p, cols)
  2511. p.idx = startIdx
  2512. result.colCount = cols.len
  2513. while true:
  2514. if currentTok(p).kind == tkAdornment:
  2515. checkColumns(p, cols)
  2516. p.idx = tokenAfterNewline(p)
  2517. if currentTok(p).kind in {tkEof, tkIndent}:
  2518. # skip last adornment line:
  2519. break
  2520. if result.sons.len > 0: result.sons[^1].endsHeader = true
  2521. # fix rnTableDataCell -> rnTableHeaderCell for previous table rows:
  2522. for nRow in 0 ..< result.sons.len:
  2523. for nCell in 0 ..< result.sons[nRow].len:
  2524. template cell: PRstNode = result.sons[nRow].sons[nCell]
  2525. cell = PRstNode(kind: rnTableHeaderCell, sons: cell.sons,
  2526. span: cell.span, anchor: cell.anchor)
  2527. if currentTok(p).kind == tkEof: break
  2528. let tabRow = parseSimpleTableRow(p, cols, colChar)
  2529. result.add tabRow
  2530. proc readTableRow(p: var RstParser): ColSeq =
  2531. if currentTok(p).symbol == "|": inc p.idx
  2532. while currentTok(p).kind notin {tkIndent, tkEof}:
  2533. var limits: ColumnLimits
  2534. limits.first = p.idx
  2535. while currentTok(p).kind notin {tkIndent, tkEof}:
  2536. if currentTok(p).symbol == "|" and prevTok(p).symbol != "\\": break
  2537. inc p.idx
  2538. limits.last = p.idx
  2539. result.add(limits)
  2540. if currentTok(p).kind in {tkIndent, tkEof}: break
  2541. inc p.idx
  2542. p.idx = tokenAfterNewline(p)
  2543. proc getColContents(p: var RstParser, colLim: ColumnLimits): string =
  2544. for i in colLim.first ..< colLim.last:
  2545. result.add(p.tok[i].symbol)
  2546. result.strip
  2547. proc isValidDelimiterRow(p: var RstParser, colNum: int): bool =
  2548. let row = readTableRow(p)
  2549. if row.len != colNum: return false
  2550. for limits in row:
  2551. let content = getColContents(p, limits)
  2552. if content.len < 3 or not (content.startsWith("--") or content.startsWith(":-")):
  2553. return false
  2554. return true
  2555. proc parseMarkdownTable(p: var RstParser): PRstNode =
  2556. var
  2557. row: ColSeq
  2558. a, b: PRstNode
  2559. q: RstParser
  2560. result = newRstNodeA(p, rnMarkdownTable)
  2561. proc parseRow(p: var RstParser, cellKind: RstNodeKind, result: PRstNode) =
  2562. row = readTableRow(p)
  2563. if result.colCount == 0: result.colCount = row.len # table header
  2564. elif row.len < result.colCount: row.setLen(result.colCount)
  2565. a = newRstNode(rnTableRow)
  2566. for j in 0 ..< result.colCount:
  2567. b = newRstNode(cellKind)
  2568. initParser(q, p.s)
  2569. q.col = p.col
  2570. q.line = currentTok(p).line - 1
  2571. getTokens(getColContents(p, row[j]), q.tok)
  2572. b.add(parseDoc(q))
  2573. a.add(b)
  2574. result.add(a)
  2575. parseRow(p, rnTableHeaderCell, result)
  2576. if not isValidDelimiterRow(p, result.colCount):
  2577. rstMessage(p, meMarkdownIllformedTable)
  2578. while predNL(p) and currentTok(p).symbol == "|":
  2579. parseRow(p, rnTableDataCell, result)
  2580. proc parseTransition(p: var RstParser): PRstNode =
  2581. result = newRstNodeA(p, rnTransition)
  2582. inc p.idx
  2583. if currentTok(p).kind == tkIndent: inc p.idx
  2584. if currentTok(p).kind == tkIndent: inc p.idx
  2585. proc parseBulletList(p: var RstParser): PRstNode =
  2586. result = nil
  2587. if nextTok(p).kind == tkWhite:
  2588. var bullet = currentTok(p).symbol
  2589. var col = currentTok(p).col
  2590. result = newRstNodeA(p, rnBulletList)
  2591. pushInd(p, p.tok[p.idx + 2].col)
  2592. inc p.idx, 2
  2593. while true:
  2594. var item = newRstNode(rnBulletItem)
  2595. parseSection(p, item)
  2596. result.add(item)
  2597. if currentTok(p).kind == tkIndent and currentTok(p).ival == col and
  2598. nextTok(p).symbol == bullet and
  2599. p.tok[p.idx + 2].kind == tkWhite:
  2600. inc p.idx, 3
  2601. else:
  2602. break
  2603. popInd(p)
  2604. proc parseOptionList(p: var RstParser): PRstNode =
  2605. result = newRstNodeA(p, rnOptionList)
  2606. let col = currentTok(p).col
  2607. var order = 1
  2608. while true:
  2609. if currentTok(p).col == col and isOptionList(p):
  2610. var a = newRstNode(rnOptionGroup)
  2611. var b = newRstNode(rnDescription)
  2612. var c = newRstNode(rnOptionListItem)
  2613. if match(p, p.idx, "//w"): inc p.idx
  2614. while currentTok(p).kind notin {tkIndent, tkEof}:
  2615. if currentTok(p).kind == tkWhite and currentTok(p).symbol.len > 1:
  2616. inc p.idx
  2617. break
  2618. a.add(newLeaf(p))
  2619. inc p.idx
  2620. var j = tokenAfterNewline(p)
  2621. if j > 0 and p.tok[j - 1].kind == tkIndent and p.tok[j - 1].ival > currInd(p):
  2622. pushInd(p, p.tok[j - 1].ival)
  2623. parseSection(p, b)
  2624. popInd(p)
  2625. else:
  2626. parseLine(p, b)
  2627. while currentTok(p).kind == tkIndent: inc p.idx
  2628. c.add(a)
  2629. c.add(b)
  2630. c.order = order; inc order
  2631. result.add(c)
  2632. else:
  2633. if currentTok(p).kind != tkEof: dec p.idx # back to tkIndent
  2634. break
  2635. proc parseMdDefinitionList(p: var RstParser): PRstNode =
  2636. ## Parses (Pandoc/kramdown/PHPextra) Mardkown definition lists.
  2637. result = newRstNodeA(p, rnMdDefList)
  2638. let termCol = currentTok(p).col
  2639. while true:
  2640. var item = newRstNode(rnDefItem)
  2641. var term = newRstNode(rnDefName)
  2642. parseLine(p, term)
  2643. skipNewlines(p)
  2644. inc p.idx, 2 # skip ":" and space
  2645. item.add(term)
  2646. while true:
  2647. var def = newRstNode(rnDefBody)
  2648. let indent = getMdBlockIndent(p)
  2649. pushInd(p, indent)
  2650. parseSection(p, def)
  2651. popInd(p)
  2652. item.add(def)
  2653. let j = skipNewlines(p, p.idx)
  2654. if isMdDefBody(p, j, termCol): # parse next definition body
  2655. p.idx = j + 2 # skip ":" and space
  2656. else:
  2657. break
  2658. result.add(item)
  2659. let j = skipNewlines(p, p.idx)
  2660. if p.tok[j].col == termCol and isMdDefListItem(p, j):
  2661. p.idx = j # parse next item
  2662. else:
  2663. break
  2664. proc parseDefinitionList(p: var RstParser): PRstNode =
  2665. result = nil
  2666. var j = tokenAfterNewline(p) - 1
  2667. if j >= 1 and p.tok[j].kind == tkIndent and
  2668. p.tok[j].ival > currInd(p) and p.tok[j - 1].symbol != "::":
  2669. var col = currentTok(p).col
  2670. result = newRstNodeA(p, rnDefList)
  2671. while true:
  2672. if isOptionList(p):
  2673. break # option list has priority over def.list
  2674. j = p.idx
  2675. var a = newRstNode(rnDefName)
  2676. parseLine(p, a)
  2677. if currentTok(p).kind == tkIndent and
  2678. currentTok(p).ival > currInd(p) and
  2679. nextTok(p).symbol != "::" and
  2680. nextTok(p).kind notin {tkIndent, tkEof}:
  2681. pushInd(p, currentTok(p).ival)
  2682. var b = newRstNode(rnDefBody)
  2683. parseSection(p, b)
  2684. var c = newRstNode(rnDefItem)
  2685. c.add(a)
  2686. c.add(b)
  2687. result.add(c)
  2688. popInd(p)
  2689. else:
  2690. p.idx = j
  2691. break
  2692. if currentTok(p).kind == tkIndent and currentTok(p).ival == col:
  2693. inc p.idx
  2694. j = tokenAfterNewline(p) - 1
  2695. if j >= 1 and p.tok[j].kind == tkIndent and p.tok[j].ival > col and
  2696. p.tok[j-1].symbol != "::" and p.tok[j+1].kind != tkIndent:
  2697. discard
  2698. else:
  2699. break
  2700. if result.len == 0: result = nil
  2701. proc parseEnumList(p: var RstParser): PRstNode =
  2702. const
  2703. wildcards: array[0..5, string] = ["(n) ", "n) ", "n. ",
  2704. "(x) ", "x) ", "x. "]
  2705. # enumerator patterns, where 'x' means letter and 'n' means number
  2706. wildToken: array[0..5, int] = [4, 3, 3, 4, 3, 3] # number of tokens
  2707. wildIndex: array[0..5, int] = [1, 0, 0, 1, 0, 0]
  2708. # position of enumeration sequence (number/letter) in enumerator
  2709. let col = currentTok(p).col
  2710. var w = 0
  2711. while w < wildcards.len:
  2712. if match(p, p.idx, wildcards[w]): break
  2713. inc w
  2714. assert w < wildcards.len
  2715. proc checkAfterNewline(p: RstParser, report: bool): bool =
  2716. ## If no indentation on the next line then parse as a normal paragraph
  2717. ## according to the RST spec. And report a warning with suggestions
  2718. let j = tokenAfterNewline(p, start=p.idx+1)
  2719. let requiredIndent = p.tok[p.idx+wildToken[w]].col
  2720. if p.tok[j].kind notin {tkIndent, tkEof} and
  2721. p.tok[j].col < requiredIndent and
  2722. (p.tok[j].col > col or
  2723. (p.tok[j].col == col and not match(p, j, wildcards[w]))):
  2724. if report:
  2725. let n = p.line + p.tok[j].line
  2726. let msg = "\n" & """
  2727. not enough indentation on line $2
  2728. (should be at column $3 if it's a continuation of enum. list),
  2729. or no blank line after line $1 (if it should be the next paragraph),
  2730. or no escaping \ at the beginning of line $1
  2731. (if lines $1..$2 are a normal paragraph, not enum. list)""".dedent
  2732. let c = p.col + requiredIndent + ColRstOffset
  2733. rstMessage(p, mwRstStyle, msg % [$(n-1), $n, $c],
  2734. p.tok[j].line, p.tok[j].col)
  2735. result = false
  2736. else:
  2737. result = true
  2738. if not checkAfterNewline(p, report = true):
  2739. return nil
  2740. result = newRstNodeA(p, rnEnumList)
  2741. let autoEnums = if roSupportMarkdown in p.s.options: @["#", "1"] else: @["#"]
  2742. var prevAE = "" # so as not allow mixing auto-enumerators `1` and `#`
  2743. var curEnum = 1
  2744. for i in 0 ..< wildToken[w]-1: # add first enumerator with (, ), and .
  2745. if p.tok[p.idx + i].symbol == "#":
  2746. prevAE = "#"
  2747. result.labelFmt.add "1"
  2748. else:
  2749. result.labelFmt.add p.tok[p.idx + i].symbol
  2750. var prevEnum = p.tok[p.idx + wildIndex[w]].symbol
  2751. inc p.idx, wildToken[w]
  2752. while true:
  2753. var item = newRstNode(rnEnumItem)
  2754. pushInd(p, currentTok(p).col)
  2755. parseSection(p, item)
  2756. popInd(p)
  2757. result.add(item)
  2758. if currentTok(p).kind == tkIndent and currentTok(p).ival == col and
  2759. match(p, p.idx+1, wildcards[w]):
  2760. # don't report to avoid duplication of warning since for
  2761. # subsequent enum. items parseEnumList will be called second time:
  2762. if not checkAfterNewline(p, report = false):
  2763. break
  2764. let enumerator = p.tok[p.idx + 1 + wildIndex[w]].symbol
  2765. # check that it's in sequence: enumerator == next(prevEnum)
  2766. if "n" in wildcards[w]: # arabic numeral
  2767. let prevEnumI = try: parseInt(prevEnum) except ValueError: 1
  2768. if enumerator in autoEnums:
  2769. if prevAE != "" and enumerator != prevAE:
  2770. break
  2771. prevAE = enumerator
  2772. curEnum = prevEnumI + 1
  2773. else: curEnum = (try: parseInt(enumerator) except ValueError: 1)
  2774. if curEnum - prevEnumI != 1:
  2775. break
  2776. prevEnum = enumerator
  2777. else: # a..z
  2778. let prevEnumI = ord(prevEnum[0])
  2779. if enumerator == "#": curEnum = prevEnumI + 1
  2780. else: curEnum = ord(enumerator[0])
  2781. if curEnum - prevEnumI != 1:
  2782. break
  2783. prevEnum = $chr(curEnum)
  2784. inc p.idx, 1 + wildToken[w]
  2785. else:
  2786. break
  2787. proc sonKind(father: PRstNode, i: int): RstNodeKind =
  2788. result = rnLeaf
  2789. if i < father.len: result = father.sons[i].kind
  2790. proc parseSection(p: var RstParser, result: PRstNode) =
  2791. ## parse top-level RST elements: sections, transitions and body elements.
  2792. while true:
  2793. var leave = false
  2794. assert(p.idx >= 0)
  2795. while currentTok(p).kind == tkIndent:
  2796. if currInd(p) == currentTok(p).ival:
  2797. inc p.idx
  2798. elif currentTok(p).ival > currInd(p):
  2799. if roPreferMarkdown in p.s.options: # Markdown => normal paragraphs
  2800. if currentTok(p).ival - currInd(p) >= 4:
  2801. result.add parseLiteralBlock(p)
  2802. else:
  2803. pushInd(p, currentTok(p).ival)
  2804. parseSection(p, result)
  2805. popInd(p)
  2806. else: # RST mode => block quotes
  2807. pushInd(p, currentTok(p).ival)
  2808. var a = newRstNodeA(p, rnBlockQuote)
  2809. parseSection(p, a)
  2810. result.add(a)
  2811. popInd(p)
  2812. else:
  2813. while currentTok(p).kind != tkEof and nextTok(p).kind == tkIndent:
  2814. inc p.idx # skip blank lines
  2815. leave = true
  2816. break
  2817. if leave or currentTok(p).kind == tkEof: break
  2818. var a: PRstNode = nil
  2819. var k = whichSection(p)
  2820. case k
  2821. of rnLiteralBlock:
  2822. inc p.idx # skip '::'
  2823. a = parseLiteralBlock(p)
  2824. of rnBulletList: a = parseBulletList(p)
  2825. of rnLineBlock: a = parseLineBlock(p)
  2826. of rnMarkdownBlockQuote: a = parseMarkdownBlockQuote(p)
  2827. of rnDirective: a = parseDotDot(p)
  2828. of rnEnumList: a = parseEnumList(p)
  2829. of rnLeaf: rstMessage(p, meNewSectionExpected, "(syntax error)")
  2830. of rnParagraph: discard
  2831. of rnDefList: a = parseDefinitionList(p)
  2832. of rnMdDefList: a = parseMdDefinitionList(p)
  2833. of rnFieldList:
  2834. if p.idx > 0: dec p.idx
  2835. a = parseFields(p)
  2836. of rnTransition: a = parseTransition(p)
  2837. of rnHeadline, rnMarkdownHeadline: a = parseHeadline(p)
  2838. of rnOverline: a = parseOverline(p)
  2839. of rnTable: a = parseSimpleTable(p)
  2840. of rnMarkdownTable: a = parseMarkdownTable(p)
  2841. of rnOptionList: a = parseOptionList(p)
  2842. else:
  2843. #InternalError("rst.parseSection()")
  2844. discard
  2845. if a == nil and k != rnDirective:
  2846. a = newRstNodeA(p, rnParagraph)
  2847. parseParagraph(p, a)
  2848. result.addIfNotNil(a)
  2849. if sonKind(result, 0) == rnParagraph and sonKind(result, 1) != rnParagraph:
  2850. result.sons[0] = newRstNode(rnInner, result.sons[0].sons,
  2851. anchor=result.sons[0].anchor)
  2852. proc parseSectionWrapper(p: var RstParser): PRstNode =
  2853. result = newRstNode(rnInner)
  2854. parseSection(p, result)
  2855. while result.kind == rnInner and result.len == 1:
  2856. result = result.sons[0]
  2857. proc parseDoc(p: var RstParser): PRstNode =
  2858. result = parseSectionWrapper(p)
  2859. if currentTok(p).kind != tkEof:
  2860. rstMessage(p, meGeneralParseError)
  2861. type
  2862. DirFlag = enum
  2863. hasArg, hasOptions, argIsFile, argIsWord
  2864. DirFlags = set[DirFlag]
  2865. SectionParser = proc (p: var RstParser): PRstNode {.nimcall, gcsafe.}
  2866. proc parseDirective(p: var RstParser, k: RstNodeKind, flags: DirFlags): PRstNode =
  2867. ## Parses arguments and options for a directive block.
  2868. ##
  2869. ## A directive block will always have three sons: the arguments for the
  2870. ## directive (rnDirArg), the options (rnFieldList) and the directive
  2871. ## content block. This proc parses the two first nodes, the 3rd is left to
  2872. ## the outer `parseDirective` call.
  2873. ##
  2874. ## Both rnDirArg and rnFieldList children nodes might be nil, so you need to
  2875. ## check them before accessing.
  2876. result = newRstNodeA(p, k)
  2877. if k == rnCodeBlock: result.info = lineInfo(p)
  2878. var args: PRstNode = nil
  2879. var options: PRstNode = nil
  2880. if hasArg in flags:
  2881. args = newRstNode(rnDirArg)
  2882. if argIsFile in flags:
  2883. while true:
  2884. case currentTok(p).kind
  2885. of tkWord, tkOther, tkPunct, tkAdornment:
  2886. args.add(newLeaf(p))
  2887. inc p.idx
  2888. else: break
  2889. elif argIsWord in flags:
  2890. while currentTok(p).kind == tkWhite: inc p.idx
  2891. if currentTok(p).kind == tkWord:
  2892. args.add(newLeaf(p))
  2893. inc p.idx
  2894. else:
  2895. args = nil
  2896. else:
  2897. parseLine(p, args)
  2898. result.add(args)
  2899. if hasOptions in flags:
  2900. if currentTok(p).kind == tkIndent and currentTok(p).ival > currInd(p) and
  2901. nextTok(p).symbol == ":":
  2902. pushInd(p, currentTok(p).ival)
  2903. options = parseFields(p)
  2904. popInd(p)
  2905. result.add(options)
  2906. proc indFollows(p: RstParser): bool =
  2907. result = currentTok(p).kind == tkIndent and currentTok(p).ival > currInd(p)
  2908. proc parseBlockContent(p: var RstParser, father: var PRstNode,
  2909. contentParser: SectionParser): bool {.gcsafe.} =
  2910. ## parse the final content part of explicit markup blocks (directives,
  2911. ## footnotes, etc). Returns true if succeeded.
  2912. if currentTok(p).kind != tkIndent or indFollows(p):
  2913. let blockIndent = getWrappableIndent(p)
  2914. pushInd(p, blockIndent)
  2915. let content = contentParser(p)
  2916. popInd(p)
  2917. father.add content
  2918. result = true
  2919. proc parseDirective(p: var RstParser, k: RstNodeKind, flags: DirFlags,
  2920. contentParser: SectionParser): PRstNode =
  2921. ## A helper proc that does main work for specific directive procs.
  2922. ## Always returns a generic rnDirective tree with these 3 children:
  2923. ##
  2924. ## 1) rnDirArg
  2925. ## 2) rnFieldList
  2926. ## 3) a node returned by `contentParser`.
  2927. ##
  2928. ## .. warning:: Any of the 3 children may be nil.
  2929. result = parseDirective(p, k, flags)
  2930. if not isNil(contentParser) and
  2931. parseBlockContent(p, result, contentParser):
  2932. discard "result is updated by parseBlockContent"
  2933. else:
  2934. result.add(PRstNode(nil))
  2935. proc parseDirBody(p: var RstParser, contentParser: SectionParser): PRstNode =
  2936. if indFollows(p):
  2937. pushInd(p, currentTok(p).ival)
  2938. result = contentParser(p)
  2939. popInd(p)
  2940. proc dirInclude(p: var RstParser): PRstNode =
  2941. ##
  2942. ## The following options are recognized:
  2943. ##
  2944. ## :start-after: text to find in the external data file
  2945. ##
  2946. ## Only the content after the first occurrence of the specified
  2947. ## text will be included. If text is not found inclusion will
  2948. ## start from beginning of the file
  2949. ##
  2950. ## :end-before: text to find in the external data file
  2951. ##
  2952. ## Only the content before the first occurrence of the specified
  2953. ## text (but after any after text) will be included. If text is
  2954. ## not found inclusion will happen until the end of the file.
  2955. #literal : flag (empty)
  2956. # The entire included text is inserted into the document as a single
  2957. # literal block (useful for program listings).
  2958. #encoding : name of text encoding
  2959. # The text encoding of the external data file. Defaults to the document's
  2960. # encoding (if specified).
  2961. #
  2962. result = nil
  2963. var n = parseDirective(p, rnDirective, {hasArg, argIsFile, hasOptions}, nil)
  2964. var filename = strip(addNodes(n.sons[0]))
  2965. var path = p.findRelativeFile(filename)
  2966. if path == "":
  2967. rstMessage(p, meCannotOpenFile, filename)
  2968. else:
  2969. # XXX: error handling; recursive file inclusion!
  2970. if getFieldValue(n, "literal") != "":
  2971. result = newRstNode(rnLiteralBlock)
  2972. result.add newLeaf(readFile(path))
  2973. else:
  2974. let inputString = readFile(path)
  2975. let startPosition =
  2976. block:
  2977. let searchFor = n.getFieldValue("start-after").strip()
  2978. if searchFor != "":
  2979. let pos = inputString.find(searchFor)
  2980. if pos != -1: pos + searchFor.len
  2981. else: 0
  2982. else:
  2983. 0
  2984. let endPosition =
  2985. block:
  2986. let searchFor = n.getFieldValue("end-before").strip()
  2987. if searchFor != "":
  2988. let pos = inputString.find(searchFor, start = startPosition)
  2989. if pos != -1: pos - 1
  2990. else: 0
  2991. else:
  2992. inputString.len - 1
  2993. var q: RstParser
  2994. initParser(q, p.s)
  2995. let saveFileIdx = p.s.currFileIdx
  2996. setCurrFilename(p.s, path)
  2997. getTokens(
  2998. inputString[startPosition..endPosition],
  2999. q.tok)
  3000. # workaround a GCC bug; more like the interior pointer bug?
  3001. #if find(q.tok[high(q.tok)].symbol, "\0\x01\x02") > 0:
  3002. # InternalError("Too many binary zeros in include file")
  3003. result = parseDoc(q)
  3004. p.s.currFileIdx = saveFileIdx
  3005. proc dirCodeBlock(p: var RstParser, nimExtension = false): PRstNode =
  3006. ## Parses a code block.
  3007. ##
  3008. ## Code blocks are rnDirective trees with a `kind` of rnCodeBlock. See the
  3009. ## description of ``parseDirective`` for further structure information.
  3010. ##
  3011. ## Code blocks can come in two forms, the standard `code directive
  3012. ## <http://docutils.sourceforge.net/docs/ref/rst/directives.html#code>`_ and
  3013. ## the nim extension ``.. code-block::``. If the block is an extension, we
  3014. ## want the default language syntax highlighting to be Nim, so we create a
  3015. ## fake internal field to communicate with the generator. The field is named
  3016. ## ``default-language``, which is unlikely to collide with a field specified
  3017. ## by any random rst input file.
  3018. ##
  3019. ## As an extension this proc will process the ``file`` extension field and if
  3020. ## present will replace the code block with the contents of the referenced
  3021. ## file. This behaviour is disabled in sandboxed mode and can be re-enabled
  3022. ## with the `roSandboxDisabled` flag.
  3023. result = parseDirective(p, rnCodeBlock, {hasArg, hasOptions}, parseLiteralBlock)
  3024. mayLoadFile(p, result)
  3025. # Extend the field block if we are using our custom Nim extension.
  3026. if nimExtension:
  3027. defaultCodeLangNim(p, result)
  3028. proc dirContainer(p: var RstParser): PRstNode =
  3029. result = parseDirective(p, rnContainer, {hasArg}, parseSectionWrapper)
  3030. assert(result.len == 3)
  3031. proc dirImage(p: var RstParser): PRstNode =
  3032. result = parseDirective(p, rnImage, {hasOptions, hasArg, argIsFile}, nil)
  3033. proc dirFigure(p: var RstParser): PRstNode =
  3034. result = parseDirective(p, rnFigure, {hasOptions, hasArg, argIsFile},
  3035. parseSectionWrapper)
  3036. proc dirTitle(p: var RstParser): PRstNode =
  3037. result = parseDirective(p, rnTitle, {hasArg}, nil)
  3038. proc dirContents(p: var RstParser): PRstNode =
  3039. result = parseDirective(p, rnContents, {hasArg}, nil)
  3040. p.s.hasToc = true
  3041. proc dirIndex(p: var RstParser): PRstNode =
  3042. result = parseDirective(p, rnIndex, {}, parseSectionWrapper)
  3043. proc dirAdmonition(p: var RstParser, d: string): PRstNode =
  3044. result = parseDirective(p, rnAdmonition, {}, parseSectionWrapper)
  3045. result.adType = d
  3046. proc dirDefaultRole(p: var RstParser): PRstNode =
  3047. result = parseDirective(p, rnDefaultRole, {hasArg}, nil)
  3048. if result.sons[0].len == 0: p.s.currRole = defaultRole(p.s.options)
  3049. else:
  3050. assert result.sons[0].sons[0].kind == rnLeaf
  3051. p.s.currRole = result.sons[0].sons[0].text
  3052. p.s.currRoleKind = whichRole(p, p.s.currRole)
  3053. proc dirRole(p: var RstParser): PRstNode =
  3054. result = parseDirective(p, rnDirective, {hasArg, hasOptions}, nil)
  3055. # just check that language is supported, TODO: real role association
  3056. let lang = getFieldValue(result, "language").strip
  3057. if lang != "" and getSourceLanguage(lang) == langNone:
  3058. rstMessage(p, mwUnsupportedLanguage, lang)
  3059. proc dirRawAux(p: var RstParser, result: var PRstNode, kind: RstNodeKind,
  3060. contentParser: SectionParser) =
  3061. var filename = getFieldValue(result, "file")
  3062. if filename.len > 0:
  3063. var path = p.findRelativeFile(filename)
  3064. if path.len == 0:
  3065. rstMessage(p, meCannotOpenFile, filename)
  3066. else:
  3067. var f = readFile(path)
  3068. result = newRstNode(kind)
  3069. result.add newLeaf(f)
  3070. else:
  3071. result = newRstNode(kind, result.sons)
  3072. result.add(parseDirBody(p, contentParser))
  3073. proc dirRaw(p: var RstParser): PRstNode =
  3074. #
  3075. #The following options are recognized:
  3076. #
  3077. #file : string (newlines removed)
  3078. # The local filesystem path of a raw data file to be included.
  3079. #
  3080. # html
  3081. # latex
  3082. result = parseDirective(p, rnDirective, {hasOptions, hasArg, argIsWord})
  3083. if result.sons[0] != nil:
  3084. if cmpIgnoreCase(result.sons[0].sons[0].text, "html") == 0:
  3085. dirRawAux(p, result, rnRawHtml, parseLiteralBlock)
  3086. elif cmpIgnoreCase(result.sons[0].sons[0].text, "latex") == 0:
  3087. dirRawAux(p, result, rnRawLatex, parseLiteralBlock)
  3088. else:
  3089. rstMessage(p, meInvalidDirective, result.sons[0].sons[0].text)
  3090. else:
  3091. dirRawAux(p, result, rnRaw, parseSectionWrapper)
  3092. proc dirImportdoc(p: var RstParser): PRstNode =
  3093. result = parseDirective(p, rnDirective, {}, parseLiteralBlock)
  3094. assert result.sons[2].kind == rnLiteralBlock
  3095. assert result.sons[2].sons[0].kind == rnLeaf
  3096. let filenames: seq[string] = split(result.sons[2].sons[0].text, seps = {','})
  3097. proc rmSpaces(s: string): string = s.split.join("")
  3098. for origFilename in filenames:
  3099. p.s.idxImports[origFilename.rmSpaces] = ImportdocInfo(fromInfo: lineInfo(p))
  3100. proc selectDir(p: var RstParser, d: string): PRstNode =
  3101. result = nil
  3102. let tok = p.tok[p.idx-2] # report on directive in ".. directive::"
  3103. if roSandboxDisabled notin p.s.options:
  3104. if d notin SandboxDirAllowlist:
  3105. rstMessage(p, meSandboxedDirective, d, tok.line, tok.col)
  3106. case d
  3107. of "admonition", "attention", "caution": result = dirAdmonition(p, d)
  3108. of "code": result = dirCodeBlock(p)
  3109. of "code-block": result = dirCodeBlock(p, nimExtension = true)
  3110. of "container": result = dirContainer(p)
  3111. of "contents": result = dirContents(p)
  3112. of "danger": result = dirAdmonition(p, d)
  3113. of "default-role": result = dirDefaultRole(p)
  3114. of "error": result = dirAdmonition(p, d)
  3115. of "figure": result = dirFigure(p)
  3116. of "hint": result = dirAdmonition(p, d)
  3117. of "image": result = dirImage(p)
  3118. of "important": result = dirAdmonition(p, d)
  3119. of "importdoc": result = dirImportdoc(p)
  3120. of "include": result = dirInclude(p)
  3121. of "index": result = dirIndex(p)
  3122. of "note": result = dirAdmonition(p, d)
  3123. of "raw":
  3124. if roSupportRawDirective in p.s.options:
  3125. result = dirRaw(p)
  3126. else:
  3127. rstMessage(p, meInvalidDirective, d)
  3128. of "role": result = dirRole(p)
  3129. of "tip": result = dirAdmonition(p, d)
  3130. of "title": result = dirTitle(p)
  3131. of "warning": result = dirAdmonition(p, d)
  3132. else:
  3133. rstMessage(p, meInvalidDirective, d, tok.line, tok.col)
  3134. proc prefix(ftnType: FootnoteType): string =
  3135. case ftnType
  3136. of fnManualNumber: result = "footnote-"
  3137. of fnAutoNumber: result = "footnoteauto-"
  3138. of fnAutoNumberLabel: result = "footnote-"
  3139. of fnAutoSymbol: result = "footnotesym-"
  3140. of fnCitation: result = "citation-"
  3141. proc parseFootnote(p: var RstParser): PRstNode {.gcsafe.} =
  3142. ## Parses footnotes and citations, always returns 2 sons:
  3143. ##
  3144. ## 1) footnote label, always containing rnInner with 1 or more sons
  3145. ## 2) footnote body, which may be nil
  3146. inc p.idx
  3147. let label = parseFootnoteName(p, reference=false)
  3148. if label == nil:
  3149. dec p.idx
  3150. return nil
  3151. result = newRstNode(rnFootnote)
  3152. result.add label
  3153. let (fnType, i) = getFootnoteType(label)
  3154. var name = ""
  3155. var anchor = fnType.prefix
  3156. case fnType
  3157. of fnManualNumber:
  3158. addFootnoteNumManual(p, i)
  3159. anchor.add $i
  3160. of fnAutoNumber, fnAutoNumberLabel:
  3161. name = rstnodeToRefname(label)
  3162. addFootnoteNumAuto(p, name)
  3163. if fnType == fnAutoNumberLabel:
  3164. anchor.add name
  3165. else: # fnAutoNumber
  3166. result.order = p.s.lineFootnoteNum.len
  3167. anchor.add $result.order
  3168. of fnAutoSymbol:
  3169. addFootnoteSymAuto(p)
  3170. result.order = p.s.lineFootnoteSym.len
  3171. anchor.add $p.s.lineFootnoteSym.len
  3172. of fnCitation:
  3173. anchor.add rstnodeToRefname(label)
  3174. addAnchorRst(p, anchor, target = result, anchorType = footnoteAnchor)
  3175. result.anchor = anchor
  3176. if currentTok(p).kind == tkWhite: inc p.idx
  3177. discard parseBlockContent(p, result, parseSectionWrapper)
  3178. if result.len < 2:
  3179. result.add nil
  3180. proc parseDotDot(p: var RstParser): PRstNode =
  3181. # parse "explicit markup blocks"
  3182. result = nil
  3183. var n: PRstNode # to store result, workaround for bug 16855
  3184. var col = currentTok(p).col
  3185. inc p.idx
  3186. var d = getDirective(p)
  3187. if d != "":
  3188. pushInd(p, col)
  3189. result = selectDir(p, d)
  3190. popInd(p)
  3191. elif match(p, p.idx, " _"):
  3192. # hyperlink target:
  3193. inc p.idx, 2
  3194. var ending = ":"
  3195. if currentTok(p).symbol == "`":
  3196. inc p.idx
  3197. ending = "`"
  3198. var a = getReferenceName(p, ending)
  3199. if ending == "`":
  3200. if currentTok(p).symbol == ":":
  3201. inc p.idx
  3202. else:
  3203. rstMessage(p, meExpected, ":")
  3204. if currentTok(p).kind == tkWhite: inc p.idx
  3205. var b = untilEol(p)
  3206. if len(b) == 0: # set internal anchor
  3207. p.curAnchors.add ManualAnchor(
  3208. alias: linkName(a), anchor: rstnodeToRefname(a), info: prevLineInfo(p)
  3209. )
  3210. else: # external hyperlink
  3211. setRef(p, rstnodeToRefname(a), b, refType=hyperlinkAlias)
  3212. elif match(p, p.idx, " |"):
  3213. # substitution definitions:
  3214. inc p.idx, 2
  3215. var a = getReferenceName(p, "|")
  3216. var b: PRstNode
  3217. if currentTok(p).kind == tkWhite: inc p.idx
  3218. if cmpIgnoreStyle(currentTok(p).symbol, "replace") == 0:
  3219. inc p.idx
  3220. expect(p, "::")
  3221. b = untilEol(p)
  3222. elif cmpIgnoreStyle(currentTok(p).symbol, "image") == 0:
  3223. inc p.idx
  3224. b = dirImage(p)
  3225. else:
  3226. rstMessage(p, meInvalidDirective, currentTok(p).symbol)
  3227. setSub(p, addNodes(a), b)
  3228. elif match(p, p.idx, " [") and
  3229. (n = parseFootnote(p); n != nil):
  3230. result = n
  3231. else:
  3232. result = parseComment(p, col)
  3233. proc rstParsePass1*(fragment: string,
  3234. line, column: int,
  3235. sharedState: PRstSharedState): PRstNode =
  3236. ## Parses an RST `fragment`.
  3237. ## The result should be further processed by
  3238. ## preparePass2_ and resolveSubs_ (which is pass 2).
  3239. var p: RstParser
  3240. initParser(p, sharedState)
  3241. p.line = line
  3242. p.col = column
  3243. getTokens(fragment, p.tok)
  3244. result = parseDoc(p)
  3245. proc extractLinkEnd(x: string): string =
  3246. ## From links like `path/to/file.html#/%` extract `file.html#/%`.
  3247. let i = find(x, '#')
  3248. let last =
  3249. if i >= 0: i
  3250. else: x.len - 1
  3251. let j = rfind(x, '/', start=0, last=last)
  3252. if j >= 0:
  3253. result = x[j+1 .. ^1]
  3254. else:
  3255. result = x
  3256. proc loadIdxFile(s: var PRstSharedState, origFilename: string) =
  3257. doAssert roSandboxDisabled in s.options
  3258. var info: TLineInfo
  3259. info.fileIndex = addFilename(s, origFilename)
  3260. var (dir, basename, ext) = origFilename.splitFile
  3261. if ext notin [".md", ".rst", ".nim", ""]:
  3262. rstMessage(s.filenames, s.msgHandler, s.idxImports[origFilename].fromInfo,
  3263. meCannotOpenFile, origFilename & ": unknown extension")
  3264. let idxFilename = dir / basename & ".idx"
  3265. let (idxPath, linkRelPath) = s.findRefFile(idxFilename)
  3266. s.idxImports[origFilename].linkRelPath = linkRelPath
  3267. var
  3268. fileEntries: seq[IndexEntry]
  3269. title: IndexEntry
  3270. try:
  3271. (fileEntries, title) = parseIdxFile(idxPath)
  3272. except IOError:
  3273. rstMessage(s.filenames, s.msgHandler, s.idxImports[origFilename].fromInfo,
  3274. meCannotOpenFile, idxPath)
  3275. except ValueError as e:
  3276. s.msgHandler(idxPath, LineRstInit, ColRstInit, meInvalidField, e.msg)
  3277. var isMarkup = false # for sanity check to avoid mixing .md <-> .nim
  3278. for entry in fileEntries:
  3279. # Though target .idx already has inside it the path to HTML relative
  3280. # project's root, we won't rely on it and use `linkRelPath` instead.
  3281. let refn = extractLinkEnd(entry.link)
  3282. # select either markup (rst/md) or Nim cases:
  3283. if entry.kind in {ieMarkupTitle, ieNimTitle}:
  3284. s.idxImports[origFilename].title = entry.keyword
  3285. case entry.kind
  3286. of ieIdxRole, ieHeading, ieMarkupTitle:
  3287. if ext == ".nim" and entry.kind == ieMarkupTitle:
  3288. rstMessage(s, idxPath, meInvalidField,
  3289. $ieMarkupTitle & " in supposedly .nim-derived file")
  3290. if entry.kind == ieMarkupTitle:
  3291. isMarkup = true
  3292. info.line = entry.line.uint16
  3293. addAnchorExtRst(s, key = entry.keyword, refn = refn,
  3294. anchorType = headlineAnchor, info=info)
  3295. of ieNim, ieNimGroup, ieNimTitle:
  3296. if ext in [".md", ".rst"] or isMarkup:
  3297. rstMessage(s, idxPath, meInvalidField,
  3298. $entry.kind & " in supposedly markup-derived file")
  3299. s.nimFileImported = true
  3300. var langSym: LangSymbol
  3301. if entry.kind in {ieNim, ieNimTitle}:
  3302. var q: RstParser
  3303. initParser(q, s)
  3304. info.line = entry.line.uint16
  3305. setLen(q.tok, 0)
  3306. q.idx = 0
  3307. getTokens(entry.linkTitle, q.tok)
  3308. var sons = newSeq[PRstNode](q.tok.len)
  3309. for i in 0 ..< q.tok.len: sons[i] = newLeaf(q.tok[i].symbol)
  3310. let linkTitle = newRstNode(rnInner, sons)
  3311. langSym = linkTitle.toLangSymbol
  3312. else: # entry.kind == ieNimGroup
  3313. langSym = langSymbolGroup(kind=entry.linkTitle, name=entry.keyword)
  3314. addAnchorNim(s, external = true, refn = refn, tooltip = entry.linkDesc,
  3315. langSym = langSym, priority = -4, # lowest
  3316. info = info, module = info.fileIndex)
  3317. doAssert s.idxImports[origFilename].title != ""
  3318. proc preparePass2*(s: var PRstSharedState, mainNode: PRstNode, importdoc = true) =
  3319. ## Records titles in node `mainNode` and orders footnotes.
  3320. countTitles(s, mainNode)
  3321. fixHeadlines(s)
  3322. orderFootnotes(s)
  3323. if importdoc:
  3324. for origFilename in s.idxImports.keys:
  3325. loadIdxFile(s, origFilename)
  3326. proc resolveLink(s: PRstSharedState, n: PRstNode) : PRstNode =
  3327. # Associate this link alias with its target and change node kind to
  3328. # rnHyperlink or rnInternalRef appropriately.
  3329. var desc, alias: PRstNode
  3330. if n.kind == rnPandocRef: # link like [desc][alias]
  3331. desc = n.sons[0]
  3332. alias = n.sons[1]
  3333. else: # n.kind == rnRstRef, link like `desc=alias`_
  3334. desc = n
  3335. alias = n
  3336. type LinkDef = object
  3337. ar: AnchorRule
  3338. priority: int
  3339. tooltip: string
  3340. target: PRstNode
  3341. info: TLineInfo
  3342. externFilename: string
  3343. # when external anchor: origin filename where anchor was defined
  3344. isTitle: bool
  3345. proc cmp(x, y: LinkDef): int =
  3346. result = cmp(x.priority, y.priority)
  3347. if result == 0:
  3348. result = cmp(x.target, y.target)
  3349. var foundLinks: seq[LinkDef]
  3350. let refn = rstnodeToRefname(alias)
  3351. var hyperlinks = findRef(s, refn)
  3352. for y in hyperlinks:
  3353. foundLinks.add LinkDef(ar: arHyperlink, priority: refPriority(y.kind),
  3354. target: y.value, info: y.info,
  3355. tooltip: "(" & $y.kind & ")")
  3356. let substRst = findMainAnchorRst(s, alias.addNodes, n.info)
  3357. template getExternFilename(subst: AnchorSubst): string =
  3358. if subst.kind == arExternalRst or
  3359. (subst.kind == arNim and subst.external):
  3360. getFilename(s, subst)
  3361. else: ""
  3362. for subst in substRst:
  3363. var refname, fullRefname: string
  3364. if subst.kind == arInternalRst:
  3365. refname = subst.target.anchor
  3366. fullRefname = refname
  3367. else: # arExternalRst
  3368. refname = subst.refnameExt
  3369. fullRefname = s.idxImports[getFilename(s, subst)].linkRelPath &
  3370. "/" & refname
  3371. let anchorType =
  3372. if subst.kind == arInternalRst: subst.anchorType
  3373. else: subst.anchorTypeExt # arExternalRst
  3374. foundLinks.add LinkDef(ar: subst.kind, priority: subst.priority,
  3375. target: newLeaf(fullRefname),
  3376. info: subst.info,
  3377. externFilename: getExternFilename(subst),
  3378. isTitle: isDocumentationTitle(refname),
  3379. tooltip: "(" & $anchorType & ")")
  3380. # find anchors automatically generated from Nim symbols
  3381. if roNimFile in s.options or s.nimFileImported:
  3382. let substNim = findMainAnchorNim(s, signature=alias, n.info)
  3383. for subst in substNim:
  3384. let fullRefname =
  3385. if subst.external:
  3386. s.idxImports[getFilename(s, subst)].linkRelPath &
  3387. "/" & subst.refname
  3388. else: subst.refname
  3389. foundLinks.add LinkDef(ar: subst.kind, priority: subst.priority,
  3390. target: newLeaf(fullRefname),
  3391. externFilename: getExternFilename(subst),
  3392. isTitle: isDocumentationTitle(subst.refname),
  3393. info: subst.info, tooltip: subst.tooltip)
  3394. foundLinks.sort(cmp = cmp, order = Descending)
  3395. let aliasStr = addNodes(alias)
  3396. if foundLinks.len >= 1:
  3397. if foundLinks[0].externFilename != "":
  3398. s.idxImports[foundLinks[0].externFilename].used = true
  3399. let kind = if foundLinks[0].ar in {arHyperlink, arExternalRst}: rnHyperlink
  3400. elif foundLinks[0].ar == arNim:
  3401. if foundLinks[0].externFilename == "": rnNimdocRef
  3402. else: rnHyperlink
  3403. else: rnInternalRef
  3404. result = newRstNode(kind)
  3405. let documentName = # filename without ext for `.nim`, title for `.md`
  3406. if foundLinks[0].ar == arNim:
  3407. changeFileExt(foundLinks[0].externFilename.extractFilename, "")
  3408. elif foundLinks[0].externFilename != "":
  3409. s.idxImports[foundLinks[0].externFilename].title
  3410. else: foundLinks[0].externFilename.extractFilename
  3411. let linkText =
  3412. if foundLinks[0].externFilename != "":
  3413. if foundLinks[0].isTitle: newLeaf(addNodes(desc))
  3414. else: newLeaf(documentName & ": " & addNodes(desc))
  3415. else:
  3416. newRstNode(rnInner, desc.sons)
  3417. result.sons = @[linkText, foundLinks[0].target]
  3418. if kind == rnNimdocRef: result.tooltip = foundLinks[0].tooltip
  3419. if foundLinks.len > 1: # report ambiguous link
  3420. var targets = newSeq[string]()
  3421. for l in foundLinks:
  3422. var t = " "
  3423. if s.filenames.len > 1:
  3424. t.add getFilename(s.filenames, l.info.fileIndex)
  3425. let n = l.info.line
  3426. let c = l.info.col + ColRstOffset
  3427. t.add "($1, $2): $3" % [$n, $c, l.tooltip]
  3428. targets.add t
  3429. rstMessage(s.filenames, s.msgHandler, n.info, mwAmbiguousLink,
  3430. "`$1`\n clash:\n$2" % [
  3431. aliasStr, targets.join("\n")])
  3432. else: # nothing found
  3433. result = n
  3434. rstMessage(s.filenames, s.msgHandler, n.info, mwBrokenLink, aliasStr)
  3435. proc resolveSubs*(s: PRstSharedState, n: PRstNode): PRstNode =
  3436. ## Makes pass 2 of RST parsing.
  3437. ## Resolves substitutions and anchor aliases, groups footnotes.
  3438. ## Takes input node `n` and returns the same node with recursive
  3439. ## substitutions in `n.sons` to `result`.
  3440. result = n
  3441. if n == nil: return
  3442. case n.kind
  3443. of rnSubstitutionReferences:
  3444. var x = findSub(s, n)
  3445. if x >= 0:
  3446. result = s.subs[x].value
  3447. else:
  3448. var key = addNodes(n)
  3449. var e = getEnv(key)
  3450. if e != "": result = newLeaf(e)
  3451. else: rstMessage(s.filenames, s.msgHandler, n.info,
  3452. mwUnknownSubstitution, key)
  3453. of rnRstRef, rnPandocRef:
  3454. result = resolveLink(s, n)
  3455. of rnFootnote:
  3456. var (fnType, num) = getFootnoteType(n.sons[0])
  3457. case fnType
  3458. of fnManualNumber, fnCitation:
  3459. discard "no need to alter fixed text"
  3460. of fnAutoNumberLabel, fnAutoNumber:
  3461. if fnType == fnAutoNumberLabel:
  3462. let labelR = rstnodeToRefname(n.sons[0])
  3463. num = getFootnoteNum(s, labelR)
  3464. else:
  3465. num = getFootnoteNum(s, n.order)
  3466. var nn = newRstNode(rnInner)
  3467. nn.add newLeaf($num)
  3468. result.sons[0] = nn
  3469. of fnAutoSymbol:
  3470. let sym = getAutoSymbol(s, n.order)
  3471. n.sons[0].sons[0].text = sym
  3472. n.sons[1] = resolveSubs(s, n.sons[1])
  3473. of rnFootnoteRef:
  3474. var (fnType, num) = getFootnoteType(n.sons[0])
  3475. template addLabel(number: int | string) =
  3476. var nn = newRstNode(rnInner)
  3477. nn.add newLeaf($number)
  3478. result.add(nn)
  3479. var refn = fnType.prefix
  3480. # create new rnFootnoteRef, add final label, and finalize target refn:
  3481. result = newRstNode(rnFootnoteRef, info = n.info)
  3482. case fnType
  3483. of fnManualNumber:
  3484. addLabel num
  3485. refn.add $num
  3486. of fnAutoNumber:
  3487. inc s.currFootnoteNumRef
  3488. addLabel getFootnoteNum(s, s.currFootnoteNumRef)
  3489. refn.add $s.currFootnoteNumRef
  3490. of fnAutoNumberLabel:
  3491. addLabel getFootnoteNum(s, rstnodeToRefname(n))
  3492. refn.add rstnodeToRefname(n)
  3493. of fnAutoSymbol:
  3494. inc s.currFootnoteSymRef
  3495. addLabel getAutoSymbol(s, s.currFootnoteSymRef)
  3496. refn.add $s.currFootnoteSymRef
  3497. of fnCitation:
  3498. result.add n.sons[0]
  3499. refn.add rstnodeToRefname(n)
  3500. # TODO: correctly report ambiguities
  3501. let anchorInfo = findMainAnchorRst(s, refn, n.info)
  3502. if anchorInfo.len != 0:
  3503. result.add newLeaf(anchorInfo[0].target.anchor) # add link
  3504. else:
  3505. rstMessage(s.filenames, s.msgHandler, n.info, mwBrokenLink, refn)
  3506. result.add newLeaf(refn) # add link
  3507. of rnLeaf:
  3508. discard
  3509. else:
  3510. var regroup = false
  3511. for i in 0 ..< n.len:
  3512. n.sons[i] = resolveSubs(s, n.sons[i])
  3513. if n.sons[i] != nil and n.sons[i].kind == rnFootnote:
  3514. regroup = true
  3515. if regroup: # group footnotes together into rnFootnoteGroup
  3516. var newSons: seq[PRstNode]
  3517. var i = 0
  3518. while i < n.len:
  3519. if n.sons[i] != nil and n.sons[i].kind == rnFootnote:
  3520. var grp = newRstNode(rnFootnoteGroup)
  3521. while i < n.len and n.sons[i].kind == rnFootnote:
  3522. grp.sons.add n.sons[i]
  3523. inc i
  3524. newSons.add grp
  3525. else:
  3526. newSons.add n.sons[i]
  3527. inc i
  3528. result.sons = newSons
  3529. proc completePass2*(s: PRstSharedState) =
  3530. for (filename, importdocInfo) in s.idxImports.pairs:
  3531. if not importdocInfo.used:
  3532. rstMessage(s.filenames, s.msgHandler, importdocInfo.fromInfo,
  3533. mwUnusedImportdoc, filename)
  3534. proc rstParse*(text, filename: string,
  3535. line, column: int,
  3536. options: RstParseOptions,
  3537. findFile: FindFileHandler = nil,
  3538. findRefFile: FindRefFileHandler = nil,
  3539. msgHandler: MsgHandler = nil):
  3540. tuple[node: PRstNode, filenames: RstFileTable, hasToc: bool] =
  3541. ## Parses the whole `text`. The result is ready for `rstgen.renderRstToOut`,
  3542. ## note that 2nd tuple element should be fed to `initRstGenerator`
  3543. ## argument `filenames` (it is being filled here at least with `filename`
  3544. ## and possibly with other files from RST ``.. include::`` statement).
  3545. var sharedState = newRstSharedState(options, filename, findFile, findRefFile,
  3546. msgHandler, hasToc=false)
  3547. let unresolved = rstParsePass1(text, line, column, sharedState)
  3548. preparePass2(sharedState, unresolved)
  3549. result.node = resolveSubs(sharedState, unresolved)
  3550. completePass2(sharedState)
  3551. result.filenames = sharedState.filenames
  3552. result.hasToc = sharedState.hasToc