rst.nim 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801
  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: break
  2271. else:
  2272. break
  2273. of tkPunct:
  2274. if isRst(p) and (
  2275. let literalBlockKind = whichRstLiteralBlock(p);
  2276. literalBlockKind != lbNone):
  2277. result.add newLeaf(":")
  2278. inc p.idx # skip '::'
  2279. result.add(parseRstLiteralBlock(p, literalBlockKind))
  2280. break
  2281. else:
  2282. parseInline(p, result)
  2283. of tkWhite, tkWord, tkAdornment, tkOther:
  2284. parseInline(p, result)
  2285. else: break
  2286. proc checkHeadingHierarchy(p: RstParser, lvl: int) =
  2287. if lvl - p.s.hCurLevel > 1: # broken hierarchy!
  2288. proc descr(l: int): string =
  2289. (if p.s.hLevels[l].hasOverline: "overline " else: "underline ") &
  2290. repeat(p.s.hLevels[l].symbol, 5)
  2291. var msg = "(section level inconsistent: "
  2292. msg.add descr(lvl) & " unexpectedly found, " &
  2293. "while the following intermediate section level(s) are missing on lines "
  2294. msg.add $p.s.hLevels[p.s.hCurLevel].line & ".." & $curLine(p) & ":"
  2295. for l in p.s.hCurLevel+1 .. lvl-1:
  2296. msg.add " " & descr(l)
  2297. if l != lvl-1: msg.add ","
  2298. rstMessage(p, meNewSectionExpected, msg & ")")
  2299. proc parseHeadline(p: var RstParser): PRstNode =
  2300. if isMarkdownHeadline(p):
  2301. result = newRstNode(rnMarkdownHeadline)
  2302. # Note that level hierarchy is not checked for markdown headings
  2303. result.level = currentTok(p).symbol.len
  2304. assert(nextTok(p).kind == tkWhite)
  2305. inc p.idx, 2
  2306. parseUntilNewline(p, result)
  2307. else:
  2308. result = newRstNode(rnHeadline)
  2309. parseUntilNewline(p, result)
  2310. assert(currentTok(p).kind == tkIndent)
  2311. assert(nextTok(p).kind == tkAdornment)
  2312. var c = nextTok(p).symbol[0]
  2313. inc p.idx, 2
  2314. result.level = getLevel(p, c, hasOverline=false)
  2315. checkHeadingHierarchy(p, result.level)
  2316. p.s.hCurLevel = result.level
  2317. addAnchorRst(p, linkName(result), result, anchorType=headlineAnchor)
  2318. p.s.tocPart.add result
  2319. proc parseOverline(p: var RstParser): PRstNode =
  2320. var c = currentTok(p).symbol[0]
  2321. inc p.idx, 2
  2322. result = newRstNode(rnOverline)
  2323. while true:
  2324. parseUntilNewline(p, result)
  2325. if currentTok(p).kind == tkIndent:
  2326. inc p.idx
  2327. if prevTok(p).ival > currInd(p):
  2328. result.add newLeaf(" ")
  2329. else:
  2330. break
  2331. else:
  2332. break
  2333. result.level = getLevel(p, c, hasOverline=true)
  2334. checkHeadingHierarchy(p, result.level)
  2335. p.s.hCurLevel = result.level
  2336. if currentTok(p).kind == tkAdornment:
  2337. inc p.idx
  2338. if currentTok(p).kind == tkIndent: inc p.idx
  2339. addAnchorRst(p, linkName(result), result, anchorType=headlineAnchor)
  2340. p.s.tocPart.add result
  2341. proc fixHeadlines(s: PRstSharedState) =
  2342. # Fix up section levels depending on presence of a title and subtitle:
  2343. for n in s.tocPart:
  2344. if n.kind in {rnHeadline, rnOverline}:
  2345. if s.hTitleCnt == 2:
  2346. if n.level == 1: # it's the subtitle
  2347. n.level = 0
  2348. elif n.level >= 2: # normal sections, start numbering from 1
  2349. n.level -= 1
  2350. elif s.hTitleCnt == 0:
  2351. n.level += 1
  2352. # Set headline anchors:
  2353. for iHeading in 0 .. s.tocPart.high:
  2354. let n: PRstNode = s.tocPart[iHeading]
  2355. if n.level >= 1:
  2356. n.anchor = rstnodeToRefname(n)
  2357. # Fix anchors for uniqueness if `.. contents::` is present
  2358. if s.hasToc:
  2359. # Find the last higher level section for unique reference name
  2360. var sectionPrefix = ""
  2361. for i in countdown(iHeading - 1, 0):
  2362. if s.tocPart[i].level >= 1 and s.tocPart[i].level < n.level:
  2363. sectionPrefix = rstnodeToRefname(s.tocPart[i]) & "-"
  2364. break
  2365. if sectionPrefix != "":
  2366. n.anchor = sectionPrefix & n.anchor
  2367. s.tocPart.setLen 0
  2368. type
  2369. ColSpec = object
  2370. start, stop: int
  2371. RstCols = seq[ColSpec]
  2372. ColumnLimits = tuple # for Markdown
  2373. first, last: int
  2374. ColSeq = seq[ColumnLimits]
  2375. proc tokStart(p: RstParser, idx: int): int =
  2376. result = p.tok[idx].col
  2377. proc tokStart(p: RstParser): int =
  2378. result = tokStart(p, p.idx)
  2379. proc tokEnd(p: RstParser, idx: int): int =
  2380. result = p.tok[idx].col + p.tok[idx].symbol.len - 1
  2381. proc tokEnd(p: RstParser): int =
  2382. result = tokEnd(p, p.idx)
  2383. proc getColumns(p: RstParser, cols: var RstCols, startIdx: int): int =
  2384. # Fills table column specification (or separator) `cols` and returns
  2385. # the next parser index after it.
  2386. var L = 0
  2387. result = startIdx
  2388. while true:
  2389. inc L
  2390. setLen(cols, L)
  2391. cols[L - 1].start = tokStart(p, result)
  2392. cols[L - 1].stop = tokEnd(p, result)
  2393. assert(p.tok[result].kind == tkAdornment)
  2394. inc result
  2395. if p.tok[result].kind != tkWhite: break
  2396. inc result
  2397. if p.tok[result].kind != tkAdornment: break
  2398. if p.tok[result].kind == tkIndent: inc result
  2399. proc checkColumns(p: RstParser, cols: RstCols) =
  2400. var i = p.idx
  2401. if p.tok[i].symbol[0] != '=':
  2402. rstMessage(p, mwRstStyle,
  2403. "only tables with `=` columns specification are allowed")
  2404. for col in 0 ..< cols.len:
  2405. if tokEnd(p, i) != cols[col].stop:
  2406. rstMessage(p, meIllformedTable,
  2407. "end of table column #$1 should end at position $2" % [
  2408. $(col+1), $(cols[col].stop+ColRstOffset)],
  2409. p.tok[i].line, tokEnd(p, i))
  2410. inc i
  2411. if col == cols.len - 1:
  2412. if p.tok[i].kind == tkWhite:
  2413. inc i
  2414. if p.tok[i].kind notin {tkIndent, tkEof}:
  2415. rstMessage(p, meIllformedTable, "extraneous column specification")
  2416. elif p.tok[i].kind == tkWhite:
  2417. inc i
  2418. else:
  2419. rstMessage(p, meIllformedTable, "no enough table columns",
  2420. p.tok[i].line, p.tok[i].col)
  2421. proc getSpans(p: RstParser, nextLine: int,
  2422. cols: RstCols, unitedCols: RstCols): seq[int] =
  2423. ## Calculates how many columns a joined cell occupies.
  2424. if unitedCols.len > 0:
  2425. result = newSeq[int](unitedCols.len)
  2426. var
  2427. iCell = 0
  2428. jCell = 0
  2429. uCell = 0
  2430. while jCell < cols.len:
  2431. if cols[jCell].stop < unitedCols[uCell].stop:
  2432. inc jCell
  2433. elif cols[jCell].stop == unitedCols[uCell].stop:
  2434. result[uCell] = jCell - iCell + 1
  2435. iCell = jCell + 1
  2436. jCell = jCell + 1
  2437. inc uCell
  2438. else:
  2439. rstMessage(p, meIllformedTable,
  2440. "spanning underline does not match main table columns",
  2441. p.tok[nextLine].line, p.tok[nextLine].col)
  2442. proc parseSimpleTableRow(p: var RstParser, cols: RstCols, colChar: char): PRstNode =
  2443. ## Parses 1 row in RST simple table.
  2444. # Consider that columns may be spanning (united by using underline like ----):
  2445. let nextLine = tokenAfterNewline(p)
  2446. var unitedCols: RstCols
  2447. var afterSpan: int
  2448. if p.tok[nextLine].kind == tkAdornment and p.tok[nextLine].symbol[0] == '-':
  2449. afterSpan = getColumns(p, unitedCols, nextLine)
  2450. if unitedCols == cols and p.tok[nextLine].symbol[0] == colChar:
  2451. # legacy rst.nim compat.: allow punctuation like `----` in main boundaries
  2452. afterSpan = nextLine
  2453. unitedCols.setLen 0
  2454. else:
  2455. afterSpan = nextLine
  2456. template colEnd(i): int =
  2457. if i == cols.len - 1: high(int) # last column has no limit
  2458. elif unitedCols.len > 0: unitedCols[i].stop else: cols[i].stop
  2459. template colStart(i): int =
  2460. if unitedCols.len > 0: unitedCols[i].start else: cols[i].start
  2461. var row = newSeq[string](if unitedCols.len > 0: unitedCols.len else: cols.len)
  2462. var spans: seq[int] = getSpans(p, nextLine, cols, unitedCols)
  2463. let line = currentTok(p).line
  2464. # Iterate over the lines a single cell may span:
  2465. while true:
  2466. var nCell = 0
  2467. # distribute tokens between cells in the current line:
  2468. while currentTok(p).kind notin {tkIndent, tkEof}:
  2469. if tokEnd(p) <= colEnd(nCell):
  2470. if tokStart(p) < colStart(nCell):
  2471. if currentTok(p).kind != tkWhite:
  2472. rstMessage(p, meIllformedTable,
  2473. "this word crosses table column from the left")
  2474. else:
  2475. inc p.idx
  2476. else:
  2477. row[nCell].add(currentTok(p).symbol)
  2478. inc p.idx
  2479. else:
  2480. if tokStart(p) < colEnd(nCell) and currentTok(p).kind != tkWhite:
  2481. rstMessage(p, meIllformedTable,
  2482. "this word crosses table column from the right")
  2483. inc nCell
  2484. if currentTok(p).kind == tkIndent: inc p.idx
  2485. if tokEnd(p) <= colEnd(0): break
  2486. # Continued current cells because the 1st column is empty.
  2487. if currentTok(p).kind in {tkEof, tkAdornment}:
  2488. break
  2489. for nCell in countup(1, high(row)): row[nCell].add('\n')
  2490. result = newRstNode(rnTableRow)
  2491. var q: RstParser
  2492. for uCell in 0 ..< row.len:
  2493. initParser(q, p.s)
  2494. q.col = colStart(uCell)
  2495. q.line = line - 1
  2496. getTokens(row[uCell], q.tok)
  2497. let cell = newRstNode(rnTableDataCell)
  2498. cell.span = if spans.len == 0: 0 else: spans[uCell]
  2499. cell.add(parseDoc(q))
  2500. result.add(cell)
  2501. if afterSpan > p.idx:
  2502. p.idx = afterSpan
  2503. proc parseSimpleTable(p: var RstParser): PRstNode =
  2504. var cols: RstCols
  2505. result = newRstNodeA(p, rnTable)
  2506. let startIdx = getColumns(p, cols, p.idx)
  2507. let colChar = currentTok(p).symbol[0]
  2508. checkColumns(p, cols)
  2509. p.idx = startIdx
  2510. result.colCount = cols.len
  2511. while true:
  2512. if currentTok(p).kind == tkAdornment:
  2513. checkColumns(p, cols)
  2514. p.idx = tokenAfterNewline(p)
  2515. if currentTok(p).kind in {tkEof, tkIndent}:
  2516. # skip last adornment line:
  2517. break
  2518. if result.sons.len > 0: result.sons[^1].endsHeader = true
  2519. # fix rnTableDataCell -> rnTableHeaderCell for previous table rows:
  2520. for nRow in 0 ..< result.sons.len:
  2521. for nCell in 0 ..< result.sons[nRow].len:
  2522. template cell: PRstNode = result.sons[nRow].sons[nCell]
  2523. cell = PRstNode(kind: rnTableHeaderCell, sons: cell.sons,
  2524. span: cell.span, anchor: cell.anchor)
  2525. if currentTok(p).kind == tkEof: break
  2526. let tabRow = parseSimpleTableRow(p, cols, colChar)
  2527. result.add tabRow
  2528. proc readTableRow(p: var RstParser): ColSeq =
  2529. if currentTok(p).symbol == "|": inc p.idx
  2530. while currentTok(p).kind notin {tkIndent, tkEof}:
  2531. var limits: ColumnLimits
  2532. limits.first = p.idx
  2533. while currentTok(p).kind notin {tkIndent, tkEof}:
  2534. if currentTok(p).symbol == "|" and prevTok(p).symbol != "\\": break
  2535. inc p.idx
  2536. limits.last = p.idx
  2537. result.add(limits)
  2538. if currentTok(p).kind in {tkIndent, tkEof}: break
  2539. inc p.idx
  2540. p.idx = tokenAfterNewline(p)
  2541. proc getColContents(p: var RstParser, colLim: ColumnLimits): string =
  2542. for i in colLim.first ..< colLim.last:
  2543. result.add(p.tok[i].symbol)
  2544. result.strip
  2545. proc isValidDelimiterRow(p: var RstParser, colNum: int): bool =
  2546. let row = readTableRow(p)
  2547. if row.len != colNum: return false
  2548. for limits in row:
  2549. let content = getColContents(p, limits)
  2550. if content.len < 3 or not (content.startsWith("--") or content.startsWith(":-")):
  2551. return false
  2552. return true
  2553. proc parseMarkdownTable(p: var RstParser): PRstNode =
  2554. var
  2555. row: ColSeq
  2556. a, b: PRstNode
  2557. q: RstParser
  2558. result = newRstNodeA(p, rnMarkdownTable)
  2559. proc parseRow(p: var RstParser, cellKind: RstNodeKind, result: PRstNode) =
  2560. row = readTableRow(p)
  2561. if result.colCount == 0: result.colCount = row.len # table header
  2562. elif row.len < result.colCount: row.setLen(result.colCount)
  2563. a = newRstNode(rnTableRow)
  2564. for j in 0 ..< result.colCount:
  2565. b = newRstNode(cellKind)
  2566. initParser(q, p.s)
  2567. q.col = p.col
  2568. q.line = currentTok(p).line - 1
  2569. getTokens(getColContents(p, row[j]), q.tok)
  2570. b.add(parseDoc(q))
  2571. a.add(b)
  2572. result.add(a)
  2573. parseRow(p, rnTableHeaderCell, result)
  2574. if not isValidDelimiterRow(p, result.colCount):
  2575. rstMessage(p, meMarkdownIllformedTable)
  2576. while predNL(p) and currentTok(p).symbol == "|":
  2577. parseRow(p, rnTableDataCell, result)
  2578. proc parseTransition(p: var RstParser): PRstNode =
  2579. result = newRstNodeA(p, rnTransition)
  2580. inc p.idx
  2581. if currentTok(p).kind == tkIndent: inc p.idx
  2582. if currentTok(p).kind == tkIndent: inc p.idx
  2583. proc parseBulletList(p: var RstParser): PRstNode =
  2584. result = nil
  2585. if nextTok(p).kind == tkWhite:
  2586. var bullet = currentTok(p).symbol
  2587. var col = currentTok(p).col
  2588. result = newRstNodeA(p, rnBulletList)
  2589. pushInd(p, p.tok[p.idx + 2].col)
  2590. inc p.idx, 2
  2591. while true:
  2592. var item = newRstNode(rnBulletItem)
  2593. parseSection(p, item)
  2594. result.add(item)
  2595. if currentTok(p).kind == tkIndent and currentTok(p).ival == col and
  2596. nextTok(p).symbol == bullet and
  2597. p.tok[p.idx + 2].kind == tkWhite:
  2598. inc p.idx, 3
  2599. else:
  2600. break
  2601. popInd(p)
  2602. proc parseOptionList(p: var RstParser): PRstNode =
  2603. result = newRstNodeA(p, rnOptionList)
  2604. let col = currentTok(p).col
  2605. var order = 1
  2606. while true:
  2607. if currentTok(p).col == col and isOptionList(p):
  2608. var a = newRstNode(rnOptionGroup)
  2609. var b = newRstNode(rnDescription)
  2610. var c = newRstNode(rnOptionListItem)
  2611. if match(p, p.idx, "//w"): inc p.idx
  2612. while currentTok(p).kind notin {tkIndent, tkEof}:
  2613. if currentTok(p).kind == tkWhite and currentTok(p).symbol.len > 1:
  2614. inc p.idx
  2615. break
  2616. a.add(newLeaf(p))
  2617. inc p.idx
  2618. var j = tokenAfterNewline(p)
  2619. if j > 0 and p.tok[j - 1].kind == tkIndent and p.tok[j - 1].ival > currInd(p):
  2620. pushInd(p, p.tok[j - 1].ival)
  2621. parseSection(p, b)
  2622. popInd(p)
  2623. else:
  2624. parseLine(p, b)
  2625. while currentTok(p).kind == tkIndent: inc p.idx
  2626. c.add(a)
  2627. c.add(b)
  2628. c.order = order; inc order
  2629. result.add(c)
  2630. else:
  2631. if currentTok(p).kind != tkEof: dec p.idx # back to tkIndent
  2632. break
  2633. proc parseMdDefinitionList(p: var RstParser): PRstNode =
  2634. ## Parses (Pandoc/kramdown/PHPextra) Mardkown definition lists.
  2635. result = newRstNodeA(p, rnMdDefList)
  2636. let termCol = currentTok(p).col
  2637. while true:
  2638. var item = newRstNode(rnDefItem)
  2639. var term = newRstNode(rnDefName)
  2640. parseLine(p, term)
  2641. skipNewlines(p)
  2642. inc p.idx, 2 # skip ":" and space
  2643. item.add(term)
  2644. while true:
  2645. var def = newRstNode(rnDefBody)
  2646. let indent = getMdBlockIndent(p)
  2647. pushInd(p, indent)
  2648. parseSection(p, def)
  2649. popInd(p)
  2650. item.add(def)
  2651. let j = skipNewlines(p, p.idx)
  2652. if isMdDefBody(p, j, termCol): # parse next definition body
  2653. p.idx = j + 2 # skip ":" and space
  2654. else:
  2655. break
  2656. result.add(item)
  2657. let j = skipNewlines(p, p.idx)
  2658. if p.tok[j].col == termCol and isMdDefListItem(p, j):
  2659. p.idx = j # parse next item
  2660. else:
  2661. break
  2662. proc parseDefinitionList(p: var RstParser): PRstNode =
  2663. result = nil
  2664. var j = tokenAfterNewline(p) - 1
  2665. if j >= 1 and p.tok[j].kind == tkIndent and
  2666. p.tok[j].ival > currInd(p) and p.tok[j - 1].symbol != "::":
  2667. var col = currentTok(p).col
  2668. result = newRstNodeA(p, rnDefList)
  2669. while true:
  2670. if isOptionList(p):
  2671. break # option list has priority over def.list
  2672. j = p.idx
  2673. var a = newRstNode(rnDefName)
  2674. parseLine(p, a)
  2675. if currentTok(p).kind == tkIndent and
  2676. currentTok(p).ival > currInd(p) and
  2677. nextTok(p).symbol != "::" and
  2678. nextTok(p).kind notin {tkIndent, tkEof}:
  2679. pushInd(p, currentTok(p).ival)
  2680. var b = newRstNode(rnDefBody)
  2681. parseSection(p, b)
  2682. var c = newRstNode(rnDefItem)
  2683. c.add(a)
  2684. c.add(b)
  2685. result.add(c)
  2686. popInd(p)
  2687. else:
  2688. p.idx = j
  2689. break
  2690. if currentTok(p).kind == tkIndent and currentTok(p).ival == col:
  2691. inc p.idx
  2692. j = tokenAfterNewline(p) - 1
  2693. if j >= 1 and p.tok[j].kind == tkIndent and p.tok[j].ival > col and
  2694. p.tok[j-1].symbol != "::" and p.tok[j+1].kind != tkIndent:
  2695. discard
  2696. else:
  2697. break
  2698. if result.len == 0: result = nil
  2699. proc parseEnumList(p: var RstParser): PRstNode =
  2700. const
  2701. wildcards: array[0..5, string] = ["(n) ", "n) ", "n. ",
  2702. "(x) ", "x) ", "x. "]
  2703. # enumerator patterns, where 'x' means letter and 'n' means number
  2704. wildToken: array[0..5, int] = [4, 3, 3, 4, 3, 3] # number of tokens
  2705. wildIndex: array[0..5, int] = [1, 0, 0, 1, 0, 0]
  2706. # position of enumeration sequence (number/letter) in enumerator
  2707. let col = currentTok(p).col
  2708. var w = 0
  2709. while w < wildcards.len:
  2710. if match(p, p.idx, wildcards[w]): break
  2711. inc w
  2712. assert w < wildcards.len
  2713. proc checkAfterNewline(p: RstParser, report: bool): bool =
  2714. ## If no indentation on the next line then parse as a normal paragraph
  2715. ## according to the RST spec. And report a warning with suggestions
  2716. let j = tokenAfterNewline(p, start=p.idx+1)
  2717. let requiredIndent = p.tok[p.idx+wildToken[w]].col
  2718. if p.tok[j].kind notin {tkIndent, tkEof} and
  2719. p.tok[j].col < requiredIndent and
  2720. (p.tok[j].col > col or
  2721. (p.tok[j].col == col and not match(p, j, wildcards[w]))):
  2722. if report:
  2723. let n = p.line + p.tok[j].line
  2724. let msg = "\n" & """
  2725. not enough indentation on line $2
  2726. (should be at column $3 if it's a continuation of enum. list),
  2727. or no blank line after line $1 (if it should be the next paragraph),
  2728. or no escaping \ at the beginning of line $1
  2729. (if lines $1..$2 are a normal paragraph, not enum. list)""".dedent
  2730. let c = p.col + requiredIndent + ColRstOffset
  2731. rstMessage(p, mwRstStyle, msg % [$(n-1), $n, $c],
  2732. p.tok[j].line, p.tok[j].col)
  2733. result = false
  2734. else:
  2735. result = true
  2736. if not checkAfterNewline(p, report = true):
  2737. return nil
  2738. result = newRstNodeA(p, rnEnumList)
  2739. let autoEnums = if roSupportMarkdown in p.s.options: @["#", "1"] else: @["#"]
  2740. var prevAE = "" # so as not allow mixing auto-enumerators `1` and `#`
  2741. var curEnum = 1
  2742. for i in 0 ..< wildToken[w]-1: # add first enumerator with (, ), and .
  2743. if p.tok[p.idx + i].symbol == "#":
  2744. prevAE = "#"
  2745. result.labelFmt.add "1"
  2746. else:
  2747. result.labelFmt.add p.tok[p.idx + i].symbol
  2748. var prevEnum = p.tok[p.idx + wildIndex[w]].symbol
  2749. inc p.idx, wildToken[w]
  2750. while true:
  2751. var item = newRstNode(rnEnumItem)
  2752. pushInd(p, currentTok(p).col)
  2753. parseSection(p, item)
  2754. popInd(p)
  2755. result.add(item)
  2756. if currentTok(p).kind == tkIndent and currentTok(p).ival == col and
  2757. match(p, p.idx+1, wildcards[w]):
  2758. # don't report to avoid duplication of warning since for
  2759. # subsequent enum. items parseEnumList will be called second time:
  2760. if not checkAfterNewline(p, report = false):
  2761. break
  2762. let enumerator = p.tok[p.idx + 1 + wildIndex[w]].symbol
  2763. # check that it's in sequence: enumerator == next(prevEnum)
  2764. if "n" in wildcards[w]: # arabic numeral
  2765. let prevEnumI = try: parseInt(prevEnum) except ValueError: 1
  2766. if enumerator in autoEnums:
  2767. if prevAE != "" and enumerator != prevAE:
  2768. break
  2769. prevAE = enumerator
  2770. curEnum = prevEnumI + 1
  2771. else: curEnum = (try: parseInt(enumerator) except ValueError: 1)
  2772. if curEnum - prevEnumI != 1:
  2773. break
  2774. prevEnum = enumerator
  2775. else: # a..z
  2776. let prevEnumI = ord(prevEnum[0])
  2777. if enumerator == "#": curEnum = prevEnumI + 1
  2778. else: curEnum = ord(enumerator[0])
  2779. if curEnum - prevEnumI != 1:
  2780. break
  2781. prevEnum = $chr(curEnum)
  2782. inc p.idx, 1 + wildToken[w]
  2783. else:
  2784. break
  2785. proc sonKind(father: PRstNode, i: int): RstNodeKind =
  2786. result = rnLeaf
  2787. if i < father.len: result = father.sons[i].kind
  2788. proc parseSection(p: var RstParser, result: PRstNode) =
  2789. ## parse top-level RST elements: sections, transitions and body elements.
  2790. while true:
  2791. var leave = false
  2792. assert(p.idx >= 0)
  2793. while currentTok(p).kind == tkIndent:
  2794. if currInd(p) == currentTok(p).ival:
  2795. inc p.idx
  2796. elif currentTok(p).ival > currInd(p):
  2797. if roPreferMarkdown in p.s.options: # Markdown => normal paragraphs
  2798. if currentTok(p).ival - currInd(p) >= 4:
  2799. result.add parseLiteralBlock(p)
  2800. else:
  2801. pushInd(p, currentTok(p).ival)
  2802. parseSection(p, result)
  2803. popInd(p)
  2804. else: # RST mode => block quotes
  2805. pushInd(p, currentTok(p).ival)
  2806. var a = newRstNodeA(p, rnBlockQuote)
  2807. parseSection(p, a)
  2808. result.add(a)
  2809. popInd(p)
  2810. else:
  2811. while currentTok(p).kind != tkEof and nextTok(p).kind == tkIndent:
  2812. inc p.idx # skip blank lines
  2813. leave = true
  2814. break
  2815. if leave or currentTok(p).kind == tkEof: break
  2816. var a: PRstNode = nil
  2817. var k = whichSection(p)
  2818. case k
  2819. of rnLiteralBlock:
  2820. inc p.idx # skip '::'
  2821. a = parseLiteralBlock(p)
  2822. of rnBulletList: a = parseBulletList(p)
  2823. of rnLineBlock: a = parseLineBlock(p)
  2824. of rnMarkdownBlockQuote: a = parseMarkdownBlockQuote(p)
  2825. of rnDirective: a = parseDotDot(p)
  2826. of rnEnumList: a = parseEnumList(p)
  2827. of rnLeaf: rstMessage(p, meNewSectionExpected, "(syntax error)")
  2828. of rnParagraph: discard
  2829. of rnDefList: a = parseDefinitionList(p)
  2830. of rnMdDefList: a = parseMdDefinitionList(p)
  2831. of rnFieldList:
  2832. if p.idx > 0: dec p.idx
  2833. a = parseFields(p)
  2834. of rnTransition: a = parseTransition(p)
  2835. of rnHeadline, rnMarkdownHeadline: a = parseHeadline(p)
  2836. of rnOverline: a = parseOverline(p)
  2837. of rnTable: a = parseSimpleTable(p)
  2838. of rnMarkdownTable: a = parseMarkdownTable(p)
  2839. of rnOptionList: a = parseOptionList(p)
  2840. else:
  2841. #InternalError("rst.parseSection()")
  2842. discard
  2843. if a == nil and k != rnDirective:
  2844. a = newRstNodeA(p, rnParagraph)
  2845. parseParagraph(p, a)
  2846. result.addIfNotNil(a)
  2847. if sonKind(result, 0) == rnParagraph and sonKind(result, 1) != rnParagraph:
  2848. result.sons[0] = newRstNode(rnInner, result.sons[0].sons,
  2849. anchor=result.sons[0].anchor)
  2850. proc parseSectionWrapper(p: var RstParser): PRstNode =
  2851. result = newRstNode(rnInner)
  2852. parseSection(p, result)
  2853. while result.kind == rnInner and result.len == 1:
  2854. result = result.sons[0]
  2855. proc parseDoc(p: var RstParser): PRstNode =
  2856. result = parseSectionWrapper(p)
  2857. if currentTok(p).kind != tkEof:
  2858. rstMessage(p, meGeneralParseError)
  2859. type
  2860. DirFlag = enum
  2861. hasArg, hasOptions, argIsFile, argIsWord
  2862. DirFlags = set[DirFlag]
  2863. SectionParser = proc (p: var RstParser): PRstNode {.nimcall, gcsafe.}
  2864. proc parseDirective(p: var RstParser, k: RstNodeKind, flags: DirFlags): PRstNode =
  2865. ## Parses arguments and options for a directive block.
  2866. ##
  2867. ## A directive block will always have three sons: the arguments for the
  2868. ## directive (rnDirArg), the options (rnFieldList) and the directive
  2869. ## content block. This proc parses the two first nodes, the 3rd is left to
  2870. ## the outer `parseDirective` call.
  2871. ##
  2872. ## Both rnDirArg and rnFieldList children nodes might be nil, so you need to
  2873. ## check them before accessing.
  2874. result = newRstNodeA(p, k)
  2875. if k == rnCodeBlock: result.info = lineInfo(p)
  2876. var args: PRstNode = nil
  2877. var options: PRstNode = nil
  2878. if hasArg in flags:
  2879. args = newRstNode(rnDirArg)
  2880. if argIsFile in flags:
  2881. while true:
  2882. case currentTok(p).kind
  2883. of tkWord, tkOther, tkPunct, tkAdornment:
  2884. args.add(newLeaf(p))
  2885. inc p.idx
  2886. else: break
  2887. elif argIsWord in flags:
  2888. while currentTok(p).kind == tkWhite: inc p.idx
  2889. if currentTok(p).kind == tkWord:
  2890. args.add(newLeaf(p))
  2891. inc p.idx
  2892. else:
  2893. args = nil
  2894. else:
  2895. parseLine(p, args)
  2896. result.add(args)
  2897. if hasOptions in flags:
  2898. if currentTok(p).kind == tkIndent and currentTok(p).ival > currInd(p) and
  2899. nextTok(p).symbol == ":":
  2900. pushInd(p, currentTok(p).ival)
  2901. options = parseFields(p)
  2902. popInd(p)
  2903. result.add(options)
  2904. proc indFollows(p: RstParser): bool =
  2905. result = currentTok(p).kind == tkIndent and currentTok(p).ival > currInd(p)
  2906. proc parseBlockContent(p: var RstParser, father: var PRstNode,
  2907. contentParser: SectionParser): bool {.gcsafe.} =
  2908. ## parse the final content part of explicit markup blocks (directives,
  2909. ## footnotes, etc). Returns true if succeeded.
  2910. if currentTok(p).kind != tkIndent or indFollows(p):
  2911. let blockIndent = getWrappableIndent(p)
  2912. pushInd(p, blockIndent)
  2913. let content = contentParser(p)
  2914. popInd(p)
  2915. father.add content
  2916. result = true
  2917. proc parseDirective(p: var RstParser, k: RstNodeKind, flags: DirFlags,
  2918. contentParser: SectionParser): PRstNode =
  2919. ## A helper proc that does main work for specific directive procs.
  2920. ## Always returns a generic rnDirective tree with these 3 children:
  2921. ##
  2922. ## 1) rnDirArg
  2923. ## 2) rnFieldList
  2924. ## 3) a node returned by `contentParser`.
  2925. ##
  2926. ## .. warning:: Any of the 3 children may be nil.
  2927. result = parseDirective(p, k, flags)
  2928. if not isNil(contentParser) and
  2929. parseBlockContent(p, result, contentParser):
  2930. discard "result is updated by parseBlockContent"
  2931. else:
  2932. result.add(PRstNode(nil))
  2933. proc parseDirBody(p: var RstParser, contentParser: SectionParser): PRstNode =
  2934. if indFollows(p):
  2935. pushInd(p, currentTok(p).ival)
  2936. result = contentParser(p)
  2937. popInd(p)
  2938. proc dirInclude(p: var RstParser): PRstNode =
  2939. ##
  2940. ## The following options are recognized:
  2941. ##
  2942. ## :start-after: text to find in the external data file
  2943. ##
  2944. ## Only the content after the first occurrence of the specified
  2945. ## text will be included. If text is not found inclusion will
  2946. ## start from beginning of the file
  2947. ##
  2948. ## :end-before: text to find in the external data file
  2949. ##
  2950. ## Only the content before the first occurrence of the specified
  2951. ## text (but after any after text) will be included. If text is
  2952. ## not found inclusion will happen until the end of the file.
  2953. #literal : flag (empty)
  2954. # The entire included text is inserted into the document as a single
  2955. # literal block (useful for program listings).
  2956. #encoding : name of text encoding
  2957. # The text encoding of the external data file. Defaults to the document's
  2958. # encoding (if specified).
  2959. #
  2960. result = nil
  2961. var n = parseDirective(p, rnDirective, {hasArg, argIsFile, hasOptions}, nil)
  2962. var filename = strip(addNodes(n.sons[0]))
  2963. var path = p.findRelativeFile(filename)
  2964. if path == "":
  2965. rstMessage(p, meCannotOpenFile, filename)
  2966. else:
  2967. # XXX: error handling; recursive file inclusion!
  2968. if getFieldValue(n, "literal") != "":
  2969. result = newRstNode(rnLiteralBlock)
  2970. result.add newLeaf(readFile(path))
  2971. else:
  2972. let inputString = readFile(path)
  2973. let startPosition =
  2974. block:
  2975. let searchFor = n.getFieldValue("start-after").strip()
  2976. if searchFor != "":
  2977. let pos = inputString.find(searchFor)
  2978. if pos != -1: pos + searchFor.len
  2979. else: 0
  2980. else:
  2981. 0
  2982. let endPosition =
  2983. block:
  2984. let searchFor = n.getFieldValue("end-before").strip()
  2985. if searchFor != "":
  2986. let pos = inputString.find(searchFor, start = startPosition)
  2987. if pos != -1: pos - 1
  2988. else: 0
  2989. else:
  2990. inputString.len - 1
  2991. var q: RstParser
  2992. initParser(q, p.s)
  2993. let saveFileIdx = p.s.currFileIdx
  2994. setCurrFilename(p.s, path)
  2995. getTokens(
  2996. inputString[startPosition..endPosition],
  2997. q.tok)
  2998. # workaround a GCC bug; more like the interior pointer bug?
  2999. #if find(q.tok[high(q.tok)].symbol, "\0\x01\x02") > 0:
  3000. # InternalError("Too many binary zeros in include file")
  3001. result = parseDoc(q)
  3002. p.s.currFileIdx = saveFileIdx
  3003. proc dirCodeBlock(p: var RstParser, nimExtension = false): PRstNode =
  3004. ## Parses a code block.
  3005. ##
  3006. ## Code blocks are rnDirective trees with a `kind` of rnCodeBlock. See the
  3007. ## description of ``parseDirective`` for further structure information.
  3008. ##
  3009. ## Code blocks can come in two forms, the standard `code directive
  3010. ## <http://docutils.sourceforge.net/docs/ref/rst/directives.html#code>`_ and
  3011. ## the nim extension ``.. code-block::``. If the block is an extension, we
  3012. ## want the default language syntax highlighting to be Nim, so we create a
  3013. ## fake internal field to communicate with the generator. The field is named
  3014. ## ``default-language``, which is unlikely to collide with a field specified
  3015. ## by any random rst input file.
  3016. ##
  3017. ## As an extension this proc will process the ``file`` extension field and if
  3018. ## present will replace the code block with the contents of the referenced
  3019. ## file. This behaviour is disabled in sandboxed mode and can be re-enabled
  3020. ## with the `roSandboxDisabled` flag.
  3021. result = parseDirective(p, rnCodeBlock, {hasArg, hasOptions}, parseLiteralBlock)
  3022. mayLoadFile(p, result)
  3023. # Extend the field block if we are using our custom Nim extension.
  3024. if nimExtension:
  3025. defaultCodeLangNim(p, result)
  3026. proc dirContainer(p: var RstParser): PRstNode =
  3027. result = parseDirective(p, rnContainer, {hasArg}, parseSectionWrapper)
  3028. assert(result.len == 3)
  3029. proc dirImage(p: var RstParser): PRstNode =
  3030. result = parseDirective(p, rnImage, {hasOptions, hasArg, argIsFile}, nil)
  3031. proc dirFigure(p: var RstParser): PRstNode =
  3032. result = parseDirective(p, rnFigure, {hasOptions, hasArg, argIsFile},
  3033. parseSectionWrapper)
  3034. proc dirTitle(p: var RstParser): PRstNode =
  3035. result = parseDirective(p, rnTitle, {hasArg}, nil)
  3036. proc dirContents(p: var RstParser): PRstNode =
  3037. result = parseDirective(p, rnContents, {hasArg}, nil)
  3038. p.s.hasToc = true
  3039. proc dirIndex(p: var RstParser): PRstNode =
  3040. result = parseDirective(p, rnIndex, {}, parseSectionWrapper)
  3041. proc dirAdmonition(p: var RstParser, d: string): PRstNode =
  3042. result = parseDirective(p, rnAdmonition, {}, parseSectionWrapper)
  3043. result.adType = d
  3044. proc dirDefaultRole(p: var RstParser): PRstNode =
  3045. result = parseDirective(p, rnDefaultRole, {hasArg}, nil)
  3046. if result.sons[0].len == 0: p.s.currRole = defaultRole(p.s.options)
  3047. else:
  3048. assert result.sons[0].sons[0].kind == rnLeaf
  3049. p.s.currRole = result.sons[0].sons[0].text
  3050. p.s.currRoleKind = whichRole(p, p.s.currRole)
  3051. proc dirRole(p: var RstParser): PRstNode =
  3052. result = parseDirective(p, rnDirective, {hasArg, hasOptions}, nil)
  3053. # just check that language is supported, TODO: real role association
  3054. let lang = getFieldValue(result, "language").strip
  3055. if lang != "" and getSourceLanguage(lang) == langNone:
  3056. rstMessage(p, mwUnsupportedLanguage, lang)
  3057. proc dirRawAux(p: var RstParser, result: var PRstNode, kind: RstNodeKind,
  3058. contentParser: SectionParser) =
  3059. var filename = getFieldValue(result, "file")
  3060. if filename.len > 0:
  3061. var path = p.findRelativeFile(filename)
  3062. if path.len == 0:
  3063. rstMessage(p, meCannotOpenFile, filename)
  3064. else:
  3065. var f = readFile(path)
  3066. result = newRstNode(kind)
  3067. result.add newLeaf(f)
  3068. else:
  3069. result = newRstNode(kind, result.sons)
  3070. result.add(parseDirBody(p, contentParser))
  3071. proc dirRaw(p: var RstParser): PRstNode =
  3072. #
  3073. #The following options are recognized:
  3074. #
  3075. #file : string (newlines removed)
  3076. # The local filesystem path of a raw data file to be included.
  3077. #
  3078. # html
  3079. # latex
  3080. result = parseDirective(p, rnDirective, {hasOptions, hasArg, argIsWord})
  3081. if result.sons[0] != nil:
  3082. if cmpIgnoreCase(result.sons[0].sons[0].text, "html") == 0:
  3083. dirRawAux(p, result, rnRawHtml, parseLiteralBlock)
  3084. elif cmpIgnoreCase(result.sons[0].sons[0].text, "latex") == 0:
  3085. dirRawAux(p, result, rnRawLatex, parseLiteralBlock)
  3086. else:
  3087. rstMessage(p, meInvalidDirective, result.sons[0].sons[0].text)
  3088. else:
  3089. dirRawAux(p, result, rnRaw, parseSectionWrapper)
  3090. proc dirImportdoc(p: var RstParser): PRstNode =
  3091. result = parseDirective(p, rnDirective, {}, parseLiteralBlock)
  3092. assert result.sons[2].kind == rnLiteralBlock
  3093. assert result.sons[2].sons[0].kind == rnLeaf
  3094. let filenames: seq[string] = split(result.sons[2].sons[0].text, seps = {','})
  3095. proc rmSpaces(s: string): string = s.split.join("")
  3096. for origFilename in filenames:
  3097. p.s.idxImports[origFilename.rmSpaces] = ImportdocInfo(fromInfo: lineInfo(p))
  3098. proc selectDir(p: var RstParser, d: string): PRstNode =
  3099. result = nil
  3100. let tok = p.tok[p.idx-2] # report on directive in ".. directive::"
  3101. if roSandboxDisabled notin p.s.options:
  3102. if d notin SandboxDirAllowlist:
  3103. rstMessage(p, meSandboxedDirective, d, tok.line, tok.col)
  3104. case d
  3105. of "admonition", "attention", "caution": result = dirAdmonition(p, d)
  3106. of "code": result = dirCodeBlock(p)
  3107. of "code-block": result = dirCodeBlock(p, nimExtension = true)
  3108. of "container": result = dirContainer(p)
  3109. of "contents": result = dirContents(p)
  3110. of "danger": result = dirAdmonition(p, d)
  3111. of "default-role": result = dirDefaultRole(p)
  3112. of "error": result = dirAdmonition(p, d)
  3113. of "figure": result = dirFigure(p)
  3114. of "hint": result = dirAdmonition(p, d)
  3115. of "image": result = dirImage(p)
  3116. of "important": result = dirAdmonition(p, d)
  3117. of "importdoc": result = dirImportdoc(p)
  3118. of "include": result = dirInclude(p)
  3119. of "index": result = dirIndex(p)
  3120. of "note": result = dirAdmonition(p, d)
  3121. of "raw":
  3122. if roSupportRawDirective in p.s.options:
  3123. result = dirRaw(p)
  3124. else:
  3125. rstMessage(p, meInvalidDirective, d)
  3126. of "role": result = dirRole(p)
  3127. of "tip": result = dirAdmonition(p, d)
  3128. of "title": result = dirTitle(p)
  3129. of "warning": result = dirAdmonition(p, d)
  3130. else:
  3131. rstMessage(p, meInvalidDirective, d, tok.line, tok.col)
  3132. proc prefix(ftnType: FootnoteType): string =
  3133. case ftnType
  3134. of fnManualNumber: result = "footnote-"
  3135. of fnAutoNumber: result = "footnoteauto-"
  3136. of fnAutoNumberLabel: result = "footnote-"
  3137. of fnAutoSymbol: result = "footnotesym-"
  3138. of fnCitation: result = "citation-"
  3139. proc parseFootnote(p: var RstParser): PRstNode {.gcsafe.} =
  3140. ## Parses footnotes and citations, always returns 2 sons:
  3141. ##
  3142. ## 1) footnote label, always containing rnInner with 1 or more sons
  3143. ## 2) footnote body, which may be nil
  3144. inc p.idx
  3145. let label = parseFootnoteName(p, reference=false)
  3146. if label == nil:
  3147. dec p.idx
  3148. return nil
  3149. result = newRstNode(rnFootnote)
  3150. result.add label
  3151. let (fnType, i) = getFootnoteType(label)
  3152. var name = ""
  3153. var anchor = fnType.prefix
  3154. case fnType
  3155. of fnManualNumber:
  3156. addFootnoteNumManual(p, i)
  3157. anchor.add $i
  3158. of fnAutoNumber, fnAutoNumberLabel:
  3159. name = rstnodeToRefname(label)
  3160. addFootnoteNumAuto(p, name)
  3161. if fnType == fnAutoNumberLabel:
  3162. anchor.add name
  3163. else: # fnAutoNumber
  3164. result.order = p.s.lineFootnoteNum.len
  3165. anchor.add $result.order
  3166. of fnAutoSymbol:
  3167. addFootnoteSymAuto(p)
  3168. result.order = p.s.lineFootnoteSym.len
  3169. anchor.add $p.s.lineFootnoteSym.len
  3170. of fnCitation:
  3171. anchor.add rstnodeToRefname(label)
  3172. addAnchorRst(p, anchor, target = result, anchorType = footnoteAnchor)
  3173. result.anchor = anchor
  3174. if currentTok(p).kind == tkWhite: inc p.idx
  3175. discard parseBlockContent(p, result, parseSectionWrapper)
  3176. if result.len < 2:
  3177. result.add nil
  3178. proc parseDotDot(p: var RstParser): PRstNode =
  3179. # parse "explicit markup blocks"
  3180. result = nil
  3181. var n: PRstNode # to store result, workaround for bug 16855
  3182. var col = currentTok(p).col
  3183. inc p.idx
  3184. var d = getDirective(p)
  3185. if d != "":
  3186. pushInd(p, col)
  3187. result = selectDir(p, d)
  3188. popInd(p)
  3189. elif match(p, p.idx, " _"):
  3190. # hyperlink target:
  3191. inc p.idx, 2
  3192. var ending = ":"
  3193. if currentTok(p).symbol == "`":
  3194. inc p.idx
  3195. ending = "`"
  3196. var a = getReferenceName(p, ending)
  3197. if ending == "`":
  3198. if currentTok(p).symbol == ":":
  3199. inc p.idx
  3200. else:
  3201. rstMessage(p, meExpected, ":")
  3202. if currentTok(p).kind == tkWhite: inc p.idx
  3203. var b = untilEol(p)
  3204. if len(b) == 0: # set internal anchor
  3205. p.curAnchors.add ManualAnchor(
  3206. alias: linkName(a), anchor: rstnodeToRefname(a), info: prevLineInfo(p)
  3207. )
  3208. else: # external hyperlink
  3209. setRef(p, rstnodeToRefname(a), b, refType=hyperlinkAlias)
  3210. elif match(p, p.idx, " |"):
  3211. # substitution definitions:
  3212. inc p.idx, 2
  3213. var a = getReferenceName(p, "|")
  3214. var b: PRstNode
  3215. if currentTok(p).kind == tkWhite: inc p.idx
  3216. if cmpIgnoreStyle(currentTok(p).symbol, "replace") == 0:
  3217. inc p.idx
  3218. expect(p, "::")
  3219. b = untilEol(p)
  3220. elif cmpIgnoreStyle(currentTok(p).symbol, "image") == 0:
  3221. inc p.idx
  3222. b = dirImage(p)
  3223. else:
  3224. rstMessage(p, meInvalidDirective, currentTok(p).symbol)
  3225. setSub(p, addNodes(a), b)
  3226. elif match(p, p.idx, " [") and
  3227. (n = parseFootnote(p); n != nil):
  3228. result = n
  3229. else:
  3230. result = parseComment(p, col)
  3231. proc rstParsePass1*(fragment: string,
  3232. line, column: int,
  3233. sharedState: PRstSharedState): PRstNode =
  3234. ## Parses an RST `fragment`.
  3235. ## The result should be further processed by
  3236. ## preparePass2_ and resolveSubs_ (which is pass 2).
  3237. var p: RstParser
  3238. initParser(p, sharedState)
  3239. p.line = line
  3240. p.col = column
  3241. getTokens(fragment, p.tok)
  3242. result = parseDoc(p)
  3243. proc extractLinkEnd(x: string): string =
  3244. ## From links like `path/to/file.html#/%` extract `file.html#/%`.
  3245. let i = find(x, '#')
  3246. let last =
  3247. if i >= 0: i
  3248. else: x.len - 1
  3249. let j = rfind(x, '/', start=0, last=last)
  3250. if j >= 0:
  3251. result = x[j+1 .. ^1]
  3252. else:
  3253. result = x
  3254. proc loadIdxFile(s: var PRstSharedState, origFilename: string) =
  3255. doAssert roSandboxDisabled in s.options
  3256. var info: TLineInfo
  3257. info.fileIndex = addFilename(s, origFilename)
  3258. var (dir, basename, ext) = origFilename.splitFile
  3259. if ext notin [".md", ".rst", ".nim", ""]:
  3260. rstMessage(s.filenames, s.msgHandler, s.idxImports[origFilename].fromInfo,
  3261. meCannotOpenFile, origFilename & ": unknown extension")
  3262. let idxFilename = dir / basename & ".idx"
  3263. let (idxPath, linkRelPath) = s.findRefFile(idxFilename)
  3264. s.idxImports[origFilename].linkRelPath = linkRelPath
  3265. var
  3266. fileEntries: seq[IndexEntry]
  3267. title: IndexEntry
  3268. try:
  3269. (fileEntries, title) = parseIdxFile(idxPath)
  3270. except IOError:
  3271. rstMessage(s.filenames, s.msgHandler, s.idxImports[origFilename].fromInfo,
  3272. meCannotOpenFile, idxPath)
  3273. except ValueError as e:
  3274. s.msgHandler(idxPath, LineRstInit, ColRstInit, meInvalidField, e.msg)
  3275. var isMarkup = false # for sanity check to avoid mixing .md <-> .nim
  3276. for entry in fileEntries:
  3277. # Though target .idx already has inside it the path to HTML relative
  3278. # project's root, we won't rely on it and use `linkRelPath` instead.
  3279. let refn = extractLinkEnd(entry.link)
  3280. # select either markup (rst/md) or Nim cases:
  3281. if entry.kind in {ieMarkupTitle, ieNimTitle}:
  3282. s.idxImports[origFilename].title = entry.keyword
  3283. case entry.kind
  3284. of ieIdxRole, ieHeading, ieMarkupTitle:
  3285. if ext == ".nim" and entry.kind == ieMarkupTitle:
  3286. rstMessage(s, idxPath, meInvalidField,
  3287. $ieMarkupTitle & " in supposedly .nim-derived file")
  3288. if entry.kind == ieMarkupTitle:
  3289. isMarkup = true
  3290. info.line = entry.line.uint16
  3291. addAnchorExtRst(s, key = entry.keyword, refn = refn,
  3292. anchorType = headlineAnchor, info=info)
  3293. of ieNim, ieNimGroup, ieNimTitle:
  3294. if ext in [".md", ".rst"] or isMarkup:
  3295. rstMessage(s, idxPath, meInvalidField,
  3296. $entry.kind & " in supposedly markup-derived file")
  3297. s.nimFileImported = true
  3298. var langSym: LangSymbol
  3299. if entry.kind in {ieNim, ieNimTitle}:
  3300. var q: RstParser
  3301. initParser(q, s)
  3302. info.line = entry.line.uint16
  3303. setLen(q.tok, 0)
  3304. q.idx = 0
  3305. getTokens(entry.linkTitle, q.tok)
  3306. var sons = newSeq[PRstNode](q.tok.len)
  3307. for i in 0 ..< q.tok.len: sons[i] = newLeaf(q.tok[i].symbol)
  3308. let linkTitle = newRstNode(rnInner, sons)
  3309. langSym = linkTitle.toLangSymbol
  3310. else: # entry.kind == ieNimGroup
  3311. langSym = langSymbolGroup(kind=entry.linkTitle, name=entry.keyword)
  3312. addAnchorNim(s, external = true, refn = refn, tooltip = entry.linkDesc,
  3313. langSym = langSym, priority = -4, # lowest
  3314. info = info, module = info.fileIndex)
  3315. doAssert s.idxImports[origFilename].title != ""
  3316. proc preparePass2*(s: var PRstSharedState, mainNode: PRstNode, importdoc = true) =
  3317. ## Records titles in node `mainNode` and orders footnotes.
  3318. countTitles(s, mainNode)
  3319. fixHeadlines(s)
  3320. orderFootnotes(s)
  3321. if importdoc:
  3322. for origFilename in s.idxImports.keys:
  3323. loadIdxFile(s, origFilename)
  3324. proc resolveLink(s: PRstSharedState, n: PRstNode) : PRstNode =
  3325. # Associate this link alias with its target and change node kind to
  3326. # rnHyperlink or rnInternalRef appropriately.
  3327. var desc, alias: PRstNode
  3328. if n.kind == rnPandocRef: # link like [desc][alias]
  3329. desc = n.sons[0]
  3330. alias = n.sons[1]
  3331. else: # n.kind == rnRstRef, link like `desc=alias`_
  3332. desc = n
  3333. alias = n
  3334. type LinkDef = object
  3335. ar: AnchorRule
  3336. priority: int
  3337. tooltip: string
  3338. target: PRstNode
  3339. info: TLineInfo
  3340. externFilename: string
  3341. # when external anchor: origin filename where anchor was defined
  3342. isTitle: bool
  3343. proc cmp(x, y: LinkDef): int =
  3344. result = cmp(x.priority, y.priority)
  3345. if result == 0:
  3346. result = cmp(x.target, y.target)
  3347. var foundLinks: seq[LinkDef]
  3348. let refn = rstnodeToRefname(alias)
  3349. var hyperlinks = findRef(s, refn)
  3350. for y in hyperlinks:
  3351. foundLinks.add LinkDef(ar: arHyperlink, priority: refPriority(y.kind),
  3352. target: y.value, info: y.info,
  3353. tooltip: "(" & $y.kind & ")")
  3354. let substRst = findMainAnchorRst(s, alias.addNodes, n.info)
  3355. template getExternFilename(subst: AnchorSubst): string =
  3356. if subst.kind == arExternalRst or
  3357. (subst.kind == arNim and subst.external):
  3358. getFilename(s, subst)
  3359. else: ""
  3360. for subst in substRst:
  3361. var refname, fullRefname: string
  3362. if subst.kind == arInternalRst:
  3363. refname = subst.target.anchor
  3364. fullRefname = refname
  3365. else: # arExternalRst
  3366. refname = subst.refnameExt
  3367. fullRefname = s.idxImports[getFilename(s, subst)].linkRelPath &
  3368. "/" & refname
  3369. let anchorType =
  3370. if subst.kind == arInternalRst: subst.anchorType
  3371. else: subst.anchorTypeExt # arExternalRst
  3372. foundLinks.add LinkDef(ar: subst.kind, priority: subst.priority,
  3373. target: newLeaf(fullRefname),
  3374. info: subst.info,
  3375. externFilename: getExternFilename(subst),
  3376. isTitle: isDocumentationTitle(refname),
  3377. tooltip: "(" & $anchorType & ")")
  3378. # find anchors automatically generated from Nim symbols
  3379. if roNimFile in s.options or s.nimFileImported:
  3380. let substNim = findMainAnchorNim(s, signature=alias, n.info)
  3381. for subst in substNim:
  3382. let fullRefname =
  3383. if subst.external:
  3384. s.idxImports[getFilename(s, subst)].linkRelPath &
  3385. "/" & subst.refname
  3386. else: subst.refname
  3387. foundLinks.add LinkDef(ar: subst.kind, priority: subst.priority,
  3388. target: newLeaf(fullRefname),
  3389. externFilename: getExternFilename(subst),
  3390. isTitle: isDocumentationTitle(subst.refname),
  3391. info: subst.info, tooltip: subst.tooltip)
  3392. foundLinks.sort(cmp = cmp, order = Descending)
  3393. let aliasStr = addNodes(alias)
  3394. if foundLinks.len >= 1:
  3395. if foundLinks[0].externFilename != "":
  3396. s.idxImports[foundLinks[0].externFilename].used = true
  3397. let kind = if foundLinks[0].ar in {arHyperlink, arExternalRst}: rnHyperlink
  3398. elif foundLinks[0].ar == arNim:
  3399. if foundLinks[0].externFilename == "": rnNimdocRef
  3400. else: rnHyperlink
  3401. else: rnInternalRef
  3402. result = newRstNode(kind)
  3403. let documentName = # filename without ext for `.nim`, title for `.md`
  3404. if foundLinks[0].ar == arNim:
  3405. changeFileExt(foundLinks[0].externFilename.extractFilename, "")
  3406. elif foundLinks[0].externFilename != "":
  3407. s.idxImports[foundLinks[0].externFilename].title
  3408. else: foundLinks[0].externFilename.extractFilename
  3409. let linkText =
  3410. if foundLinks[0].externFilename != "":
  3411. if foundLinks[0].isTitle: newLeaf(addNodes(desc))
  3412. else: newLeaf(documentName & ": " & addNodes(desc))
  3413. else:
  3414. newRstNode(rnInner, desc.sons)
  3415. result.sons = @[linkText, foundLinks[0].target]
  3416. if kind == rnNimdocRef: result.tooltip = foundLinks[0].tooltip
  3417. if foundLinks.len > 1: # report ambiguous link
  3418. var targets = newSeq[string]()
  3419. for l in foundLinks:
  3420. var t = " "
  3421. if s.filenames.len > 1:
  3422. t.add getFilename(s.filenames, l.info.fileIndex)
  3423. let n = l.info.line
  3424. let c = l.info.col + ColRstOffset
  3425. t.add "($1, $2): $3" % [$n, $c, l.tooltip]
  3426. targets.add t
  3427. rstMessage(s.filenames, s.msgHandler, n.info, mwAmbiguousLink,
  3428. "`$1`\n clash:\n$2" % [
  3429. aliasStr, targets.join("\n")])
  3430. else: # nothing found
  3431. result = n
  3432. rstMessage(s.filenames, s.msgHandler, n.info, mwBrokenLink, aliasStr)
  3433. proc resolveSubs*(s: PRstSharedState, n: PRstNode): PRstNode =
  3434. ## Makes pass 2 of RST parsing.
  3435. ## Resolves substitutions and anchor aliases, groups footnotes.
  3436. ## Takes input node `n` and returns the same node with recursive
  3437. ## substitutions in `n.sons` to `result`.
  3438. result = n
  3439. if n == nil: return
  3440. case n.kind
  3441. of rnSubstitutionReferences:
  3442. var x = findSub(s, n)
  3443. if x >= 0:
  3444. result = s.subs[x].value
  3445. else:
  3446. var key = addNodes(n)
  3447. var e = getEnv(key)
  3448. if e != "": result = newLeaf(e)
  3449. else: rstMessage(s.filenames, s.msgHandler, n.info,
  3450. mwUnknownSubstitution, key)
  3451. of rnRstRef, rnPandocRef:
  3452. result = resolveLink(s, n)
  3453. of rnFootnote:
  3454. var (fnType, num) = getFootnoteType(n.sons[0])
  3455. case fnType
  3456. of fnManualNumber, fnCitation:
  3457. discard "no need to alter fixed text"
  3458. of fnAutoNumberLabel, fnAutoNumber:
  3459. if fnType == fnAutoNumberLabel:
  3460. let labelR = rstnodeToRefname(n.sons[0])
  3461. num = getFootnoteNum(s, labelR)
  3462. else:
  3463. num = getFootnoteNum(s, n.order)
  3464. var nn = newRstNode(rnInner)
  3465. nn.add newLeaf($num)
  3466. result.sons[0] = nn
  3467. of fnAutoSymbol:
  3468. let sym = getAutoSymbol(s, n.order)
  3469. n.sons[0].sons[0].text = sym
  3470. n.sons[1] = resolveSubs(s, n.sons[1])
  3471. of rnFootnoteRef:
  3472. var (fnType, num) = getFootnoteType(n.sons[0])
  3473. template addLabel(number: int | string) =
  3474. var nn = newRstNode(rnInner)
  3475. nn.add newLeaf($number)
  3476. result.add(nn)
  3477. var refn = fnType.prefix
  3478. # create new rnFootnoteRef, add final label, and finalize target refn:
  3479. result = newRstNode(rnFootnoteRef, info = n.info)
  3480. case fnType
  3481. of fnManualNumber:
  3482. addLabel num
  3483. refn.add $num
  3484. of fnAutoNumber:
  3485. inc s.currFootnoteNumRef
  3486. addLabel getFootnoteNum(s, s.currFootnoteNumRef)
  3487. refn.add $s.currFootnoteNumRef
  3488. of fnAutoNumberLabel:
  3489. addLabel getFootnoteNum(s, rstnodeToRefname(n))
  3490. refn.add rstnodeToRefname(n)
  3491. of fnAutoSymbol:
  3492. inc s.currFootnoteSymRef
  3493. addLabel getAutoSymbol(s, s.currFootnoteSymRef)
  3494. refn.add $s.currFootnoteSymRef
  3495. of fnCitation:
  3496. result.add n.sons[0]
  3497. refn.add rstnodeToRefname(n)
  3498. # TODO: correctly report ambiguities
  3499. let anchorInfo = findMainAnchorRst(s, refn, n.info)
  3500. if anchorInfo.len != 0:
  3501. result.add newLeaf(anchorInfo[0].target.anchor) # add link
  3502. else:
  3503. rstMessage(s.filenames, s.msgHandler, n.info, mwBrokenLink, refn)
  3504. result.add newLeaf(refn) # add link
  3505. of rnLeaf:
  3506. discard
  3507. else:
  3508. var regroup = false
  3509. for i in 0 ..< n.len:
  3510. n.sons[i] = resolveSubs(s, n.sons[i])
  3511. if n.sons[i] != nil and n.sons[i].kind == rnFootnote:
  3512. regroup = true
  3513. if regroup: # group footnotes together into rnFootnoteGroup
  3514. var newSons: seq[PRstNode]
  3515. var i = 0
  3516. while i < n.len:
  3517. if n.sons[i] != nil and n.sons[i].kind == rnFootnote:
  3518. var grp = newRstNode(rnFootnoteGroup)
  3519. while i < n.len and n.sons[i].kind == rnFootnote:
  3520. grp.sons.add n.sons[i]
  3521. inc i
  3522. newSons.add grp
  3523. else:
  3524. newSons.add n.sons[i]
  3525. inc i
  3526. result.sons = newSons
  3527. proc completePass2*(s: PRstSharedState) =
  3528. for (filename, importdocInfo) in s.idxImports.pairs:
  3529. if not importdocInfo.used:
  3530. rstMessage(s.filenames, s.msgHandler, importdocInfo.fromInfo,
  3531. mwUnusedImportdoc, filename)
  3532. proc rstParse*(text, filename: string,
  3533. line, column: int,
  3534. options: RstParseOptions,
  3535. findFile: FindFileHandler = nil,
  3536. findRefFile: FindRefFileHandler = nil,
  3537. msgHandler: MsgHandler = nil):
  3538. tuple[node: PRstNode, filenames: RstFileTable, hasToc: bool] =
  3539. ## Parses the whole `text`. The result is ready for `rstgen.renderRstToOut`,
  3540. ## note that 2nd tuple element should be fed to `initRstGenerator`
  3541. ## argument `filenames` (it is being filled here at least with `filename`
  3542. ## and possibly with other files from RST ``.. include::`` statement).
  3543. var sharedState = newRstSharedState(options, filename, findFile, findRefFile,
  3544. msgHandler, hasToc=false)
  3545. let unresolved = rstParsePass1(text, line, column, sharedState)
  3546. preparePass2(sharedState, unresolved)
  3547. result.node = resolveSubs(sharedState, unresolved)
  3548. completePass2(sharedState)
  3549. result.filenames = sharedState.filenames
  3550. result.hasToc = sharedState.hasToc