pegs.nim 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085
  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. ## Simple PEG (Parsing expression grammar) matching. Uses no memorization, but
  10. ## uses superoperators and symbol inlining to improve performance. Note:
  11. ## Matching performance is hopefully competitive with optimized regular
  12. ## expression engines.
  13. ##
  14. ## .. include:: ../../doc/pegdocs.txt
  15. ##
  16. include "system/inclrtl"
  17. when defined(nimPreviewSlimSystem):
  18. import std/[syncio, assertions]
  19. const
  20. useUnicode = true ## change this to deactivate proper UTF-8 support
  21. import std/[strutils, macros]
  22. import std/private/decode_helpers
  23. when useUnicode:
  24. import std/unicode
  25. export unicode.`==`
  26. const
  27. InlineThreshold = 5 ## number of leaves; -1 to disable inlining
  28. MaxSubpatterns* = 20 ## defines the maximum number of subpatterns that
  29. ## can be captured. More subpatterns cannot be captured!
  30. type
  31. PegKind* = enum
  32. pkEmpty,
  33. pkAny, ## any character (.)
  34. pkAnyRune, ## any Unicode character (_)
  35. pkNewLine, ## CR-LF, LF, CR
  36. pkLetter, ## Unicode letter
  37. pkLower, ## Unicode lower case letter
  38. pkUpper, ## Unicode upper case letter
  39. pkTitle, ## Unicode title character
  40. pkWhitespace, ## Unicode whitespace character
  41. pkTerminal,
  42. pkTerminalIgnoreCase,
  43. pkTerminalIgnoreStyle,
  44. pkChar, ## single character to match
  45. pkCharChoice,
  46. pkNonTerminal,
  47. pkSequence, ## a b c ... --> Internal DSL: peg(a, b, c)
  48. pkOrderedChoice, ## a / b / ... --> Internal DSL: a / b or /[a, b, c]
  49. pkGreedyRep, ## a* --> Internal DSL: *a
  50. ## a+ --> (a a*)
  51. pkGreedyRepChar, ## x* where x is a single character (superop)
  52. pkGreedyRepSet, ## [set]* (superop)
  53. pkGreedyAny, ## .* or _* (superop)
  54. pkOption, ## a? --> Internal DSL: ?a
  55. pkAndPredicate, ## &a --> Internal DSL: &a
  56. pkNotPredicate, ## !a --> Internal DSL: !a
  57. pkCapture, ## {a} --> Internal DSL: capture(a)
  58. pkBackRef, ## $i --> Internal DSL: backref(i)
  59. pkBackRefIgnoreCase,
  60. pkBackRefIgnoreStyle,
  61. pkSearch, ## @a --> Internal DSL: !*a
  62. pkCapturedSearch, ## {@} a --> Internal DSL: !*\a
  63. pkRule, ## a <- b
  64. pkList, ## a, b
  65. pkStartAnchor ## ^ --> Internal DSL: startAnchor()
  66. NonTerminalFlag* = enum
  67. ntDeclared, ntUsed
  68. NonTerminalObj = object ## represents a non terminal symbol
  69. name: string ## the name of the symbol
  70. line: int ## line the symbol has been declared/used in
  71. col: int ## column the symbol has been declared/used in
  72. flags: set[NonTerminalFlag] ## the nonterminal's flags
  73. rule: Peg ## the rule that the symbol refers to
  74. Peg* {.shallow.} = object ## type that represents a PEG
  75. case kind: PegKind
  76. of pkEmpty..pkWhitespace: nil
  77. of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string
  78. of pkChar, pkGreedyRepChar: ch: char
  79. of pkCharChoice, pkGreedyRepSet: charChoice: ref set[char]
  80. of pkNonTerminal: nt: NonTerminal
  81. of pkBackRef..pkBackRefIgnoreStyle: index: range[-MaxSubpatterns..MaxSubpatterns-1]
  82. else: sons: seq[Peg]
  83. NonTerminal* = ref NonTerminalObj
  84. func kind*(p: Peg): PegKind = p.kind
  85. ## Returns the *PegKind* of a given *Peg* object.
  86. func term*(p: Peg): string = p.term
  87. ## Returns the *string* representation of a given *Peg* variant object
  88. ## where present.
  89. func ch*(p: Peg): char = p.ch
  90. ## Returns the *char* representation of a given *Peg* variant object
  91. ## where present.
  92. func charChoice*(p: Peg): ref set[char] = p.charChoice
  93. ## Returns the *charChoice* field of a given *Peg* variant object
  94. ## where present.
  95. func nt*(p: Peg): NonTerminal = p.nt
  96. ## Returns the *NonTerminal* object of a given *Peg* variant object
  97. ## where present.
  98. func index*(p: Peg): range[-MaxSubpatterns..MaxSubpatterns-1] = p.index
  99. ## Returns the back-reference index of a captured sub-pattern in the
  100. ## *Captures* object for a given *Peg* variant object where present.
  101. iterator items*(p: Peg): Peg {.inline.} =
  102. ## Yields the child nodes of a *Peg* variant object where present.
  103. for s in p.sons:
  104. yield s
  105. iterator pairs*(p: Peg): (int, Peg) {.inline.} =
  106. ## Yields the indices and child nodes of a *Peg* variant object where present.
  107. for i in 0 ..< p.sons.len:
  108. yield (i, p.sons[i])
  109. func name*(nt: NonTerminal): string = nt.name
  110. ## Gets the name of the symbol represented by the parent *Peg* object variant
  111. ## of a given *NonTerminal*.
  112. func line*(nt: NonTerminal): int = nt.line
  113. ## Gets the line number of the definition of the parent *Peg* object variant
  114. ## of a given *NonTerminal*.
  115. func col*(nt: NonTerminal): int = nt.col
  116. ## Gets the column number of the definition of the parent *Peg* object variant
  117. ## of a given *NonTerminal*.
  118. func flags*(nt: NonTerminal): set[NonTerminalFlag] = nt.flags
  119. ## Gets the *NonTerminalFlag*-typed flags field of the parent *Peg* variant
  120. ## object of a given *NonTerminal*.
  121. func rule*(nt: NonTerminal): Peg = nt.rule
  122. ## Gets the *Peg* object representing the rule definition of the parent *Peg*
  123. ## object variant of a given *NonTerminal*.
  124. func term*(t: string): Peg {.rtl, extern: "npegs$1Str".} =
  125. ## constructs a PEG from a terminal string
  126. if t.len != 1:
  127. result = Peg(kind: pkTerminal, term: t)
  128. else:
  129. result = Peg(kind: pkChar, ch: t[0])
  130. func termIgnoreCase*(t: string): Peg {.
  131. rtl, extern: "npegs$1".} =
  132. ## constructs a PEG from a terminal string; ignore case for matching
  133. result = Peg(kind: pkTerminalIgnoreCase, term: t)
  134. func termIgnoreStyle*(t: string): Peg {.
  135. rtl, extern: "npegs$1".} =
  136. ## constructs a PEG from a terminal string; ignore style for matching
  137. result = Peg(kind: pkTerminalIgnoreStyle, term: t)
  138. func term*(t: char): Peg {.rtl, extern: "npegs$1Char".} =
  139. ## constructs a PEG from a terminal char
  140. assert t != '\0'
  141. result = Peg(kind: pkChar, ch: t)
  142. func charSet*(s: set[char]): Peg {.rtl, extern: "npegs$1".} =
  143. ## constructs a PEG from a character set `s`
  144. assert '\0' notin s
  145. result = Peg(kind: pkCharChoice)
  146. {.cast(noSideEffect).}:
  147. new(result.charChoice)
  148. result.charChoice[] = s
  149. func len(a: Peg): int {.inline.} = return a.sons.len
  150. func add(d: var Peg, s: Peg) {.inline.} = add(d.sons, s)
  151. func addChoice(dest: var Peg, elem: Peg) =
  152. var L = dest.len-1
  153. if L >= 0 and dest.sons[L].kind == pkCharChoice:
  154. # caution! Do not introduce false aliasing here!
  155. case elem.kind
  156. of pkCharChoice:
  157. dest.sons[L] = charSet(dest.sons[L].charChoice[] + elem.charChoice[])
  158. of pkChar:
  159. dest.sons[L] = charSet(dest.sons[L].charChoice[] + {elem.ch})
  160. else: add(dest, elem)
  161. else: add(dest, elem)
  162. template multipleOp(k: PegKind, localOpt: untyped) =
  163. result = Peg(kind: k, sons: @[])
  164. for x in items(a):
  165. if x.kind == k:
  166. for y in items(x.sons):
  167. localOpt(result, y)
  168. else:
  169. localOpt(result, x)
  170. if result.len == 1:
  171. result = result.sons[0]
  172. func `/`*(a: varargs[Peg]): Peg {.
  173. rtl, extern: "npegsOrderedChoice".} =
  174. ## constructs an ordered choice with the PEGs in `a`
  175. multipleOp(pkOrderedChoice, addChoice)
  176. func addSequence(dest: var Peg, elem: Peg) =
  177. var L = dest.len-1
  178. if L >= 0 and dest.sons[L].kind == pkTerminal:
  179. # caution! Do not introduce false aliasing here!
  180. case elem.kind
  181. of pkTerminal:
  182. dest.sons[L] = term(dest.sons[L].term & elem.term)
  183. of pkChar:
  184. dest.sons[L] = term(dest.sons[L].term & elem.ch)
  185. else: add(dest, elem)
  186. else: add(dest, elem)
  187. func sequence*(a: varargs[Peg]): Peg {.
  188. rtl, extern: "npegs$1".} =
  189. ## constructs a sequence with all the PEGs from `a`
  190. multipleOp(pkSequence, addSequence)
  191. func `?`*(a: Peg): Peg {.rtl, extern: "npegsOptional".} =
  192. ## constructs an optional for the PEG `a`
  193. if a.kind in {pkOption, pkGreedyRep, pkGreedyAny, pkGreedyRepChar,
  194. pkGreedyRepSet}:
  195. # a* ? --> a*
  196. # a? ? --> a?
  197. result = a
  198. else:
  199. result = Peg(kind: pkOption, sons: @[a])
  200. func `*`*(a: Peg): Peg {.rtl, extern: "npegsGreedyRep".} =
  201. ## constructs a "greedy repetition" for the PEG `a`
  202. case a.kind
  203. of pkGreedyRep, pkGreedyRepChar, pkGreedyRepSet, pkGreedyAny, pkOption:
  204. raiseAssert "unreachable" # produces endless loop!
  205. of pkChar:
  206. result = Peg(kind: pkGreedyRepChar, ch: a.ch)
  207. of pkCharChoice:
  208. result = Peg(kind: pkGreedyRepSet, charChoice: a.charChoice)
  209. of pkAny, pkAnyRune:
  210. result = Peg(kind: pkGreedyAny)
  211. else:
  212. result = Peg(kind: pkGreedyRep, sons: @[a])
  213. func `!*`*(a: Peg): Peg {.rtl, extern: "npegsSearch".} =
  214. ## constructs a "search" for the PEG `a`
  215. result = Peg(kind: pkSearch, sons: @[a])
  216. func `!*\`*(a: Peg): Peg {.rtl,
  217. extern: "npgegsCapturedSearch".} =
  218. ## constructs a "captured search" for the PEG `a`
  219. result = Peg(kind: pkCapturedSearch, sons: @[a])
  220. func `+`*(a: Peg): Peg {.rtl, extern: "npegsGreedyPosRep".} =
  221. ## constructs a "greedy positive repetition" with the PEG `a`
  222. return sequence(a, *a)
  223. func `&`*(a: Peg): Peg {.rtl, extern: "npegsAndPredicate".} =
  224. ## constructs an "and predicate" with the PEG `a`
  225. result = Peg(kind: pkAndPredicate, sons: @[a])
  226. func `!`*(a: Peg): Peg {.rtl, extern: "npegsNotPredicate".} =
  227. ## constructs a "not predicate" with the PEG `a`
  228. result = Peg(kind: pkNotPredicate, sons: @[a])
  229. func any*: Peg {.inline.} =
  230. ## constructs the PEG `any character`:idx: (``.``)
  231. result = Peg(kind: pkAny)
  232. func anyRune*: Peg {.inline.} =
  233. ## constructs the PEG `any rune`:idx: (``_``)
  234. result = Peg(kind: pkAnyRune)
  235. func newLine*: Peg {.inline.} =
  236. ## constructs the PEG `newline`:idx: (``\n``)
  237. result = Peg(kind: pkNewLine)
  238. func unicodeLetter*: Peg {.inline.} =
  239. ## constructs the PEG ``\letter`` which matches any Unicode letter.
  240. result = Peg(kind: pkLetter)
  241. func unicodeLower*: Peg {.inline.} =
  242. ## constructs the PEG ``\lower`` which matches any Unicode lowercase letter.
  243. result = Peg(kind: pkLower)
  244. func unicodeUpper*: Peg {.inline.} =
  245. ## constructs the PEG ``\upper`` which matches any Unicode uppercase letter.
  246. result = Peg(kind: pkUpper)
  247. func unicodeTitle*: Peg {.inline.} =
  248. ## constructs the PEG ``\title`` which matches any Unicode title letter.
  249. result = Peg(kind: pkTitle)
  250. func unicodeWhitespace*: Peg {.inline.} =
  251. ## constructs the PEG ``\white`` which matches any Unicode
  252. ## whitespace character.
  253. result = Peg(kind: pkWhitespace)
  254. func startAnchor*: Peg {.inline.} =
  255. ## constructs the PEG ``^`` which matches the start of the input.
  256. result = Peg(kind: pkStartAnchor)
  257. func endAnchor*: Peg {.inline.} =
  258. ## constructs the PEG ``$`` which matches the end of the input.
  259. result = !any()
  260. func capture*(a: Peg = Peg(kind: pkEmpty)): Peg {.rtl, extern: "npegsCapture".} =
  261. ## constructs a capture with the PEG `a`
  262. result = Peg(kind: pkCapture, sons: @[a])
  263. func backref*(index: range[1..MaxSubpatterns], reverse: bool = false): Peg {.
  264. rtl, extern: "npegs$1".} =
  265. ## constructs a back reference of the given `index`. `index` starts counting
  266. ## from 1. `reverse` specifies whether indexing starts from the end of the
  267. ## capture list.
  268. result = Peg(kind: pkBackRef, index: (if reverse: -index else: index - 1))
  269. func backrefIgnoreCase*(index: range[1..MaxSubpatterns], reverse: bool = false): Peg {.
  270. rtl, extern: "npegs$1".} =
  271. ## constructs a back reference of the given `index`. `index` starts counting
  272. ## from 1. `reverse` specifies whether indexing starts from the end of the
  273. ## capture list. Ignores case for matching.
  274. result = Peg(kind: pkBackRefIgnoreCase, index: (if reverse: -index else: index - 1))
  275. func backrefIgnoreStyle*(index: range[1..MaxSubpatterns], reverse: bool = false): Peg {.
  276. rtl, extern: "npegs$1".} =
  277. ## constructs a back reference of the given `index`. `index` starts counting
  278. ## from 1. `reverse` specifies whether indexing starts from the end of the
  279. ## capture list. Ignores style for matching.
  280. result = Peg(kind: pkBackRefIgnoreStyle, index: (if reverse: -index else: index - 1))
  281. func spaceCost(n: Peg): int =
  282. case n.kind
  283. of pkEmpty: result = 0
  284. of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar,
  285. pkGreedyRepChar, pkCharChoice, pkGreedyRepSet,
  286. pkAny..pkWhitespace, pkGreedyAny, pkBackRef..pkBackRefIgnoreStyle:
  287. result = 1
  288. of pkNonTerminal:
  289. # we cannot inline a rule with a non-terminal
  290. result = InlineThreshold+1
  291. else:
  292. result = 0
  293. for i in 0..n.len-1:
  294. inc(result, spaceCost(n.sons[i]))
  295. if result >= InlineThreshold: break
  296. func nonterminal*(n: NonTerminal): Peg {.
  297. rtl, extern: "npegs$1".} =
  298. ## constructs a PEG that consists of the nonterminal symbol
  299. assert n != nil
  300. if ntDeclared in n.flags and spaceCost(n.rule) < InlineThreshold:
  301. when false: echo "inlining symbol: ", n.name
  302. result = n.rule # inlining of rule enables better optimizations
  303. else:
  304. result = Peg(kind: pkNonTerminal, nt: n)
  305. func newNonTerminal*(name: string, line, column: int): NonTerminal {.
  306. rtl, extern: "npegs$1".} =
  307. ## constructs a nonterminal symbol
  308. result = NonTerminal(name: name, line: line, col: column)
  309. template letters*: Peg =
  310. ## expands to ``charset({'A'..'Z', 'a'..'z'})``
  311. charSet({'A'..'Z', 'a'..'z'})
  312. template digits*: Peg =
  313. ## expands to ``charset({'0'..'9'})``
  314. charSet({'0'..'9'})
  315. template whitespace*: Peg =
  316. ## expands to ``charset({' ', '\9'..'\13'})``
  317. charSet({' ', '\9'..'\13'})
  318. template identChars*: Peg =
  319. ## expands to ``charset({'a'..'z', 'A'..'Z', '0'..'9', '_'})``
  320. charSet({'a'..'z', 'A'..'Z', '0'..'9', '_'})
  321. template identStartChars*: Peg =
  322. ## expands to ``charset({'A'..'Z', 'a'..'z', '_'})``
  323. charSet({'a'..'z', 'A'..'Z', '_'})
  324. template ident*: Peg =
  325. ## same as ``[a-zA-Z_][a-zA-z_0-9]*``; standard identifier
  326. sequence(charSet({'a'..'z', 'A'..'Z', '_'}),
  327. *charSet({'a'..'z', 'A'..'Z', '0'..'9', '_'}))
  328. template natural*: Peg =
  329. ## same as ``\d+``
  330. +digits
  331. # ------------------------- debugging -----------------------------------------
  332. func esc(c: char, reserved = {'\0'..'\255'}): string =
  333. case c
  334. of '\b': result = "\\b"
  335. of '\t': result = "\\t"
  336. of '\c': result = "\\c"
  337. of '\L': result = "\\l"
  338. of '\v': result = "\\v"
  339. of '\f': result = "\\f"
  340. of '\e': result = "\\e"
  341. of '\a': result = "\\a"
  342. of '\\': result = "\\\\"
  343. of 'a'..'z', 'A'..'Z', '0'..'9', '_': result = $c
  344. elif c < ' ' or c >= '\127': result = '\\' & $ord(c)
  345. elif c in reserved: result = '\\' & c
  346. else: result = $c
  347. func singleQuoteEsc(c: char): string = return "'" & esc(c, {'\''}) & "'"
  348. func singleQuoteEsc(str: string): string =
  349. result = "'"
  350. for c in items(str): add result, esc(c, {'\''})
  351. add result, '\''
  352. func charSetEscAux(cc: set[char]): string =
  353. const reserved = {'^', '-', ']'}
  354. result = ""
  355. var c1 = 0
  356. while c1 <= 0xff:
  357. if chr(c1) in cc:
  358. var c2 = c1
  359. while c2 < 0xff and chr(succ(c2)) in cc: inc(c2)
  360. if c1 == c2:
  361. add result, esc(chr(c1), reserved)
  362. elif c2 == succ(c1):
  363. add result, esc(chr(c1), reserved) & esc(chr(c2), reserved)
  364. else:
  365. add result, esc(chr(c1), reserved) & '-' & esc(chr(c2), reserved)
  366. c1 = c2
  367. inc(c1)
  368. func charSetEsc(cc: set[char]): string =
  369. if card(cc) >= 128+64:
  370. result = "[^" & charSetEscAux({'\1'..'\xFF'} - cc) & ']'
  371. else:
  372. result = '[' & charSetEscAux(cc) & ']'
  373. func toStrAux(r: Peg, res: var string) =
  374. case r.kind
  375. of pkEmpty: add(res, "()")
  376. of pkAny: add(res, '.')
  377. of pkAnyRune: add(res, '_')
  378. of pkLetter: add(res, "\\letter")
  379. of pkLower: add(res, "\\lower")
  380. of pkUpper: add(res, "\\upper")
  381. of pkTitle: add(res, "\\title")
  382. of pkWhitespace: add(res, "\\white")
  383. of pkNewLine: add(res, "\\n")
  384. of pkTerminal: add(res, singleQuoteEsc(r.term))
  385. of pkTerminalIgnoreCase:
  386. add(res, 'i')
  387. add(res, singleQuoteEsc(r.term))
  388. of pkTerminalIgnoreStyle:
  389. add(res, 'y')
  390. add(res, singleQuoteEsc(r.term))
  391. of pkChar: add(res, singleQuoteEsc(r.ch))
  392. of pkCharChoice: add(res, charSetEsc(r.charChoice[]))
  393. of pkNonTerminal: add(res, r.nt.name)
  394. of pkSequence:
  395. add(res, '(')
  396. toStrAux(r.sons[0], res)
  397. for i in 1 .. high(r.sons):
  398. add(res, ' ')
  399. toStrAux(r.sons[i], res)
  400. add(res, ')')
  401. of pkOrderedChoice:
  402. add(res, '(')
  403. toStrAux(r.sons[0], res)
  404. for i in 1 .. high(r.sons):
  405. add(res, " / ")
  406. toStrAux(r.sons[i], res)
  407. add(res, ')')
  408. of pkGreedyRep:
  409. toStrAux(r.sons[0], res)
  410. add(res, '*')
  411. of pkGreedyRepChar:
  412. add(res, singleQuoteEsc(r.ch))
  413. add(res, '*')
  414. of pkGreedyRepSet:
  415. add(res, charSetEsc(r.charChoice[]))
  416. add(res, '*')
  417. of pkGreedyAny:
  418. add(res, ".*")
  419. of pkOption:
  420. toStrAux(r.sons[0], res)
  421. add(res, '?')
  422. of pkAndPredicate:
  423. add(res, '&')
  424. toStrAux(r.sons[0], res)
  425. of pkNotPredicate:
  426. add(res, '!')
  427. toStrAux(r.sons[0], res)
  428. of pkSearch:
  429. add(res, '@')
  430. toStrAux(r.sons[0], res)
  431. of pkCapturedSearch:
  432. add(res, "{@}")
  433. toStrAux(r.sons[0], res)
  434. of pkCapture:
  435. add(res, '{')
  436. toStrAux(r.sons[0], res)
  437. add(res, '}')
  438. of pkBackRef:
  439. add(res, '$')
  440. add(res, $r.index)
  441. of pkBackRefIgnoreCase:
  442. add(res, "i$")
  443. add(res, $r.index)
  444. of pkBackRefIgnoreStyle:
  445. add(res, "y$")
  446. add(res, $r.index)
  447. of pkRule:
  448. toStrAux(r.sons[0], res)
  449. add(res, " <- ")
  450. toStrAux(r.sons[1], res)
  451. of pkList:
  452. for i in 0 .. high(r.sons):
  453. toStrAux(r.sons[i], res)
  454. add(res, "\n")
  455. of pkStartAnchor:
  456. add(res, '^')
  457. func `$` *(r: Peg): string {.rtl, extern: "npegsToString".} =
  458. ## converts a PEG to its string representation
  459. result = ""
  460. toStrAux(r, result)
  461. # --------------------- core engine -------------------------------------------
  462. type
  463. Captures* = object ## contains the captured substrings.
  464. matches: array[0..MaxSubpatterns-1, tuple[first, last: int]]
  465. ml: int
  466. origStart: int
  467. func bounds*(c: Captures,
  468. i: range[0..MaxSubpatterns-1]): tuple[first, last: int] =
  469. ## returns the bounds ``[first..last]`` of the `i`'th capture.
  470. result = c.matches[i]
  471. when not useUnicode:
  472. type
  473. Rune = char
  474. template fastRuneAt(s, i, ch) =
  475. ch = s[i]
  476. inc(i)
  477. template runeLenAt(s, i): untyped = 1
  478. func isAlpha(a: char): bool {.inline.} = return a in {'a'..'z', 'A'..'Z'}
  479. func isUpper(a: char): bool {.inline.} = return a in {'A'..'Z'}
  480. func isLower(a: char): bool {.inline.} = return a in {'a'..'z'}
  481. func isTitle(a: char): bool {.inline.} = return false
  482. func isWhiteSpace(a: char): bool {.inline.} = return a in {' ', '\9'..'\13'}
  483. template matchOrParse(mopProc: untyped) =
  484. # Used to make the main matcher proc *rawMatch* as well as event parser
  485. # procs. For the former, *enter* and *leave* event handler code generators
  486. # are provided which just return *discard*.
  487. proc mopProc(s: string, p: Peg, start: int, c: var Captures): int {.gcsafe, raises: [].} =
  488. result = 0
  489. proc matchBackRef(s: string, p: Peg, start: int, c: var Captures): int =
  490. # Parse handler code must run in an *of* clause of its own for each
  491. # *PegKind*, so we encapsulate the identical clause body for
  492. # *pkBackRef..pkBackRefIgnoreStyle* here.
  493. var index = p.index
  494. if index < 0: index.inc(c.ml)
  495. if index < 0 or index >= c.ml: return -1
  496. var (a, b) = c.matches[index]
  497. var n: Peg
  498. case p.kind
  499. of pkBackRef:
  500. n = Peg(kind: pkTerminal, term: s.substr(a, b))
  501. of pkBackRefIgnoreStyle:
  502. n = Peg(kind: pkTerminalIgnoreStyle, term: s.substr(a, b))
  503. of pkBackRefIgnoreCase:
  504. n = Peg(kind: pkTerminalIgnoreCase, term: s.substr(a, b))
  505. else: raiseAssert "impossible case"
  506. mopProc(s, n, start, c)
  507. case p.kind
  508. of pkEmpty:
  509. enter(pkEmpty, s, p, start)
  510. result = 0 # match of length 0
  511. leave(pkEmpty, s, p, start, result)
  512. of pkAny:
  513. enter(pkAny, s, p, start)
  514. if start < s.len: result = 1
  515. else: result = -1
  516. leave(pkAny, s, p, start, result)
  517. of pkAnyRune:
  518. enter(pkAnyRune, s, p, start)
  519. if start < s.len:
  520. result = runeLenAt(s, start)
  521. else:
  522. result = -1
  523. leave(pkAnyRune, s, p, start, result)
  524. of pkLetter:
  525. enter(pkLetter, s, p, start)
  526. if start < s.len:
  527. var a: Rune
  528. result = start
  529. fastRuneAt(s, result, a)
  530. if isAlpha(a): dec(result, start)
  531. else: result = -1
  532. else:
  533. result = -1
  534. leave(pkLetter, s, p, start, result)
  535. of pkLower:
  536. enter(pkLower, s, p, start)
  537. if start < s.len:
  538. var a: Rune
  539. result = start
  540. fastRuneAt(s, result, a)
  541. if isLower(a): dec(result, start)
  542. else: result = -1
  543. else:
  544. result = -1
  545. leave(pkLower, s, p, start, result)
  546. of pkUpper:
  547. enter(pkUpper, s, p, start)
  548. if start < s.len:
  549. var a: Rune
  550. result = start
  551. fastRuneAt(s, result, a)
  552. if isUpper(a): dec(result, start)
  553. else: result = -1
  554. else:
  555. result = -1
  556. leave(pkUpper, s, p, start, result)
  557. of pkTitle:
  558. enter(pkTitle, s, p, start)
  559. if start < s.len:
  560. var a: Rune
  561. result = start
  562. fastRuneAt(s, result, a)
  563. if isTitle(a): dec(result, start)
  564. else: result = -1
  565. else:
  566. result = -1
  567. leave(pkTitle, s, p, start, result)
  568. of pkWhitespace:
  569. enter(pkWhitespace, s, p, start)
  570. if start < s.len:
  571. var a: Rune
  572. result = start
  573. fastRuneAt(s, result, a)
  574. if isWhiteSpace(a): dec(result, start)
  575. else: result = -1
  576. else:
  577. result = -1
  578. leave(pkWhitespace, s, p, start, result)
  579. of pkGreedyAny:
  580. enter(pkGreedyAny, s, p, start)
  581. result = len(s) - start
  582. leave(pkGreedyAny, s, p, start, result)
  583. of pkNewLine:
  584. enter(pkNewLine, s, p, start)
  585. if start < s.len and s[start] == '\L': result = 1
  586. elif start < s.len and s[start] == '\C':
  587. if start+1 < s.len and s[start+1] == '\L': result = 2
  588. else: result = 1
  589. else: result = -1
  590. leave(pkNewLine, s, p, start, result)
  591. of pkTerminal:
  592. enter(pkTerminal, s, p, start)
  593. result = len(p.term)
  594. for i in 0..result-1:
  595. if start+i >= s.len or p.term[i] != s[start+i]:
  596. result = -1
  597. break
  598. leave(pkTerminal, s, p, start, result)
  599. of pkTerminalIgnoreCase:
  600. enter(pkTerminalIgnoreCase, s, p, start)
  601. var
  602. i = 0
  603. a, b: Rune
  604. result = start
  605. while i < len(p.term):
  606. if result >= s.len:
  607. result = -1
  608. break
  609. fastRuneAt(p.term, i, a)
  610. fastRuneAt(s, result, b)
  611. if toLower(a) != toLower(b):
  612. result = -1
  613. break
  614. dec(result, start)
  615. leave(pkTerminalIgnoreCase, s, p, start, result)
  616. of pkTerminalIgnoreStyle:
  617. enter(pkTerminalIgnoreStyle, s, p, start)
  618. var
  619. i = 0
  620. a, b: Rune = default(Rune)
  621. result = start
  622. while i < len(p.term):
  623. while i < len(p.term):
  624. fastRuneAt(p.term, i, a)
  625. if a != Rune('_'): break
  626. while result < s.len:
  627. fastRuneAt(s, result, b)
  628. if b != Rune('_'): break
  629. if result >= s.len:
  630. if i >= p.term.len: break
  631. else:
  632. result = -1
  633. break
  634. elif toLower(a) != toLower(b):
  635. result = -1
  636. break
  637. dec(result, start)
  638. leave(pkTerminalIgnoreStyle, s, p, start, result)
  639. of pkChar:
  640. enter(pkChar, s, p, start)
  641. if start < s.len and p.ch == s[start]: result = 1
  642. else: result = -1
  643. leave(pkChar, s, p, start, result)
  644. of pkCharChoice:
  645. enter(pkCharChoice, s, p, start)
  646. if start < s.len and contains(p.charChoice[], s[start]): result = 1
  647. else: result = -1
  648. leave(pkCharChoice, s, p, start, result)
  649. of pkNonTerminal:
  650. enter(pkNonTerminal, s, p, start)
  651. var oldMl = c.ml
  652. when false: echo "enter: ", p.nt.name
  653. result = mopProc(s, p.nt.rule, start, c)
  654. when false: echo "leave: ", p.nt.name
  655. if result < 0: c.ml = oldMl
  656. leave(pkNonTerminal, s, p, start, result)
  657. of pkSequence:
  658. enter(pkSequence, s, p, start)
  659. var oldMl = c.ml
  660. result = 0
  661. for i in 0..high(p.sons):
  662. var x = mopProc(s, p.sons[i], start+result, c)
  663. if x < 0:
  664. c.ml = oldMl
  665. result = -1
  666. break
  667. else: inc(result, x)
  668. leave(pkSequence, s, p, start, result)
  669. of pkOrderedChoice:
  670. enter(pkOrderedChoice, s, p, start)
  671. var oldMl = c.ml
  672. for i in 0..high(p.sons):
  673. result = mopProc(s, p.sons[i], start, c)
  674. if result >= 0: break
  675. c.ml = oldMl
  676. leave(pkOrderedChoice, s, p, start, result)
  677. of pkSearch:
  678. enter(pkSearch, s, p, start)
  679. var oldMl = c.ml
  680. result = 0
  681. while start+result <= s.len:
  682. var x = mopProc(s, p.sons[0], start+result, c)
  683. if x >= 0:
  684. inc(result, x)
  685. leave(pkSearch, s, p, start, result)
  686. return
  687. inc(result)
  688. result = -1
  689. c.ml = oldMl
  690. leave(pkSearch, s, p, start, result)
  691. of pkCapturedSearch:
  692. enter(pkCapturedSearch, s, p, start)
  693. var idx = c.ml # reserve a slot for the subpattern
  694. inc(c.ml)
  695. result = 0
  696. while start+result <= s.len:
  697. var x = mopProc(s, p.sons[0], start+result, c)
  698. if x >= 0:
  699. if idx < MaxSubpatterns:
  700. c.matches[idx] = (start, start+result-1)
  701. #else: silently ignore the capture
  702. inc(result, x)
  703. leave(pkCapturedSearch, s, p, start, result)
  704. return
  705. inc(result)
  706. result = -1
  707. c.ml = idx
  708. leave(pkCapturedSearch, s, p, start, result)
  709. of pkGreedyRep:
  710. enter(pkGreedyRep, s, p, start)
  711. result = 0
  712. while true:
  713. var x = mopProc(s, p.sons[0], start+result, c)
  714. # if x == 0, we have an endless loop; so the correct behaviour would be
  715. # not to break. But endless loops can be easily introduced:
  716. # ``(comment / \w*)*`` is such an example. Breaking for x == 0 does the
  717. # expected thing in this case.
  718. if x <= 0: break
  719. inc(result, x)
  720. leave(pkGreedyRep, s, p, start, result)
  721. of pkGreedyRepChar:
  722. enter(pkGreedyRepChar, s, p, start)
  723. result = 0
  724. var ch = p.ch
  725. while start+result < s.len and ch == s[start+result]: inc(result)
  726. leave(pkGreedyRepChar, s, p, start, result)
  727. of pkGreedyRepSet:
  728. enter(pkGreedyRepSet, s, p, start)
  729. result = 0
  730. while start+result < s.len and contains(p.charChoice[], s[start+result]):
  731. inc(result)
  732. leave(pkGreedyRepSet, s, p, start, result)
  733. of pkOption:
  734. enter(pkOption, s, p, start)
  735. result = max(0, mopProc(s, p.sons[0], start, c))
  736. leave(pkOption, s, p, start, result)
  737. of pkAndPredicate:
  738. enter(pkAndPredicate, s, p, start)
  739. var oldMl = c.ml
  740. result = mopProc(s, p.sons[0], start, c)
  741. if result >= 0: result = 0 # do not consume anything
  742. else: c.ml = oldMl
  743. leave(pkAndPredicate, s, p, start, result)
  744. of pkNotPredicate:
  745. enter(pkNotPredicate, s, p, start)
  746. var oldMl = c.ml
  747. result = mopProc(s, p.sons[0], start, c)
  748. if result < 0: result = 0
  749. else:
  750. c.ml = oldMl
  751. result = -1
  752. leave(pkNotPredicate, s, p, start, result)
  753. of pkCapture:
  754. enter(pkCapture, s, p, start)
  755. if p.sons.len == 0 or p.sons[0].kind == pkEmpty:
  756. # empty capture removes last match
  757. dec(c.ml)
  758. c.matches[c.ml] = (0, 0)
  759. result = 0 # match of length 0
  760. else:
  761. var idx = c.ml # reserve a slot for the subpattern
  762. result = mopProc(s, p.sons[0], start, c)
  763. if result >= 0:
  764. if idx < MaxSubpatterns:
  765. if idx != c.ml:
  766. for i in countdown(c.ml, idx):
  767. c.matches[i+1] = c.matches[i]
  768. c.matches[idx] = (start, start+result-1)
  769. #else: silently ignore the capture
  770. inc(c.ml)
  771. leave(pkCapture, s, p, start, result)
  772. of pkBackRef:
  773. enter(pkBackRef, s, p, start)
  774. result = matchBackRef(s, p, start, c)
  775. leave(pkBackRef, s, p, start, result)
  776. of pkBackRefIgnoreCase:
  777. enter(pkBackRefIgnoreCase, s, p, start)
  778. result = matchBackRef(s, p, start, c)
  779. leave(pkBackRefIgnoreCase, s, p, start, result)
  780. of pkBackRefIgnoreStyle:
  781. enter(pkBackRefIgnoreStyle, s, p, start)
  782. result = matchBackRef(s, p, start, c)
  783. leave(pkBackRefIgnoreStyle, s, p, start, result)
  784. of pkStartAnchor:
  785. enter(pkStartAnchor, s, p, start)
  786. if c.origStart == start: result = 0
  787. else: result = -1
  788. leave(pkStartAnchor, s, p, start, result)
  789. of pkRule, pkList: assert false
  790. func rawMatch*(s: string, p: Peg, start: int, c: var Captures): int
  791. {.rtl, extern: "npegs$1".} =
  792. ## low-level matching proc that implements the PEG interpreter. Use this
  793. ## for maximum efficiency (every other PEG operation ends up calling this
  794. ## proc).
  795. ## Returns -1 if it does not match, else the length of the match
  796. # Set the handler generators to produce do-nothing handlers.
  797. template enter(pk, s, p, start) =
  798. discard
  799. template leave(pk, s, p, start, length) =
  800. discard
  801. matchOrParse(matchIt)
  802. {.cast(noSideEffect).}:
  803. # This cast is allowed because the `matchOrParse` template is used for
  804. # both matching and parsing, but side effects are only possible when it's
  805. # used by `eventParser`.
  806. result = matchIt(s, p, start, c)
  807. macro mkHandlerTplts(handlers: untyped): untyped =
  808. # Transforms the handler spec in *handlers* into handler templates.
  809. # The AST structure of *handlers[0]*:
  810. #
  811. # ```
  812. # StmtList
  813. # Call
  814. # Ident "pkNonTerminal"
  815. # StmtList
  816. # Call
  817. # Ident "enter"
  818. # StmtList
  819. # <handler code block>
  820. # Call
  821. # Ident "leave"
  822. # StmtList
  823. # <handler code block>
  824. # Call
  825. # Ident "pkChar"
  826. # StmtList
  827. # Call
  828. # Ident "leave"
  829. # StmtList
  830. # <handler code block>
  831. # ...
  832. # ```
  833. func mkEnter(hdName, body: NimNode): NimNode =
  834. template helper(hdName, body) {.dirty.} =
  835. template hdName(s, p, start) =
  836. let s {.inject.} = s
  837. let p {.inject.} = p
  838. let start {.inject.} = start
  839. body
  840. result = getAst(helper(hdName, body))
  841. template mkLeave(hdPostf, body) {.dirty.} =
  842. # this has to be dirty to be able to capture *result* as *length* in
  843. # *leaveXX* calls.
  844. template `leave hdPostf`(s, p, start, length) =
  845. body
  846. result = newStmtList()
  847. for topCall in handlers[0]:
  848. if topCall.kind notin nnkCallKinds:
  849. error("Call syntax expected.", topCall)
  850. let pegKind = topCall[0]
  851. if pegKind.kind notin {nnkIdent, nnkSym}:
  852. error("PegKind expected.", pegKind)
  853. if 2 == topCall.len:
  854. for hdDef in topCall[1]:
  855. if hdDef.kind notin nnkCallKinds:
  856. error("Call syntax expected.", hdDef)
  857. if hdDef[0].kind notin {nnkIdent, nnkSym}:
  858. error("Handler identifier expected.", hdDef[0])
  859. if 2 == hdDef.len:
  860. let hdPostf = substr(pegKind.strVal, 2)
  861. case hdDef[0].strVal
  862. of "enter":
  863. result.add mkEnter(newIdentNode("enter" & hdPostf), hdDef[1])
  864. of "leave":
  865. result.add getAst(mkLeave(ident(hdPostf), hdDef[1]))
  866. else:
  867. error(
  868. "Unsupported handler identifier, expected 'enter' or 'leave'.",
  869. hdDef[0]
  870. )
  871. template eventParser*(pegAst, handlers: untyped): (proc(s: string): int) =
  872. ## Generates an interpreting event parser *proc* according to the specified
  873. ## PEG AST and handler code blocks. The *proc* can be called with a string
  874. ## to be parsed and will execute the handler code blocks whenever their
  875. ## associated grammar element is matched. It returns -1 if the string does not
  876. ## match, else the length of the total match. The following example code
  877. ## evaluates an arithmetic expression defined by a simple PEG:
  878. ##
  879. ## ```nim
  880. ## import std/[strutils, pegs]
  881. ##
  882. ## let
  883. ## pegAst = """
  884. ## Expr <- Sum
  885. ## Sum <- Product (('+' / '-')Product)*
  886. ## Product <- Value (('*' / '/')Value)*
  887. ## Value <- [0-9]+ / '(' Expr ')'
  888. ## """.peg
  889. ## txt = "(5+3)/2-7*22"
  890. ##
  891. ## var
  892. ## pStack: seq[string] = @[]
  893. ## valStack: seq[float] = @[]
  894. ## opStack = ""
  895. ## let
  896. ## parseArithExpr = pegAst.eventParser:
  897. ## pkNonTerminal:
  898. ## enter:
  899. ## pStack.add p.nt.name
  900. ## leave:
  901. ## pStack.setLen pStack.high
  902. ## if length > 0:
  903. ## let matchStr = s.substr(start, start+length-1)
  904. ## case p.nt.name
  905. ## of "Value":
  906. ## try:
  907. ## valStack.add matchStr.parseFloat
  908. ## echo valStack
  909. ## except ValueError:
  910. ## discard
  911. ## of "Sum", "Product":
  912. ## try:
  913. ## let val = matchStr.parseFloat
  914. ## except ValueError:
  915. ## if valStack.len > 1 and opStack.len > 0:
  916. ## valStack[^2] = case opStack[^1]
  917. ## of '+': valStack[^2] + valStack[^1]
  918. ## of '-': valStack[^2] - valStack[^1]
  919. ## of '*': valStack[^2] * valStack[^1]
  920. ## else: valStack[^2] / valStack[^1]
  921. ## valStack.setLen valStack.high
  922. ## echo valStack
  923. ## opStack.setLen opStack.high
  924. ## echo opStack
  925. ## pkChar:
  926. ## leave:
  927. ## if length == 1 and "Value" != pStack[^1]:
  928. ## let matchChar = s[start]
  929. ## opStack.add matchChar
  930. ## echo opStack
  931. ##
  932. ## let pLen = parseArithExpr(txt)
  933. ## ```
  934. ##
  935. ## The *handlers* parameter consists of code blocks for *PegKinds*,
  936. ## which define the grammar elements of interest. Each block can contain
  937. ## handler code to be executed when the parser enters and leaves text
  938. ## matching the grammar element. An *enter* handler can access the specific
  939. ## PEG AST node being matched as *p*, the entire parsed string as *s*
  940. ## and the position of the matched text segment in *s* as *start*. A *leave*
  941. ## handler can access *p*, *s*, *start* and also the length of the matched
  942. ## text segment as *length*. For an unsuccessful match, the *enter* and
  943. ## *leave* handlers will be executed, with *length* set to -1.
  944. ##
  945. ## Symbols declared in an *enter* handler can be made visible in the
  946. ## corresponding *leave* handler by annotating them with an *inject* pragma.
  947. proc rawParse(s: string, p: Peg, start: int, c: var Captures): int
  948. {.gensym.} =
  949. # binding from *macros*
  950. bind strVal
  951. mkHandlerTplts:
  952. handlers
  953. macro enter(pegKind, s, pegNode, start: untyped): untyped =
  954. # This is called by the matcher code in *matchOrParse* at the
  955. # start of the code for a grammar element of kind *pegKind*.
  956. # Expands to a call to the handler template if one was generated
  957. # by *mkHandlerTplts*.
  958. template mkDoEnter(hdPostf, s, pegNode, start) =
  959. when declared(`enter hdPostf`):
  960. `enter hdPostf`(s, pegNode, start)
  961. else:
  962. discard
  963. let hdPostf = ident(substr($pegKind, 2))
  964. getAst(mkDoEnter(hdPostf, s, pegNode, start))
  965. macro leave(pegKind, s, pegNode, start, length: untyped): untyped =
  966. # Like *enter*, but called at the end of the matcher code for
  967. # a grammar element of kind *pegKind*.
  968. template mkDoLeave(hdPostf, s, pegNode, start, length) =
  969. when declared(`leave hdPostf`):
  970. `leave hdPostf`(s, pegNode, start, length)
  971. else:
  972. discard
  973. let hdPostf = ident(substr($pegKind, 2))
  974. getAst(mkDoLeave(hdPostf, s, pegNode, start, length))
  975. matchOrParse(parseIt)
  976. parseIt(s, p, start, c)
  977. proc parser(s: string): int {.gensym.} =
  978. # the proc to be returned
  979. var
  980. ms: array[MaxSubpatterns, (int, int)] = default(array[MaxSubpatterns, (int, int)])
  981. cs = Captures(matches: ms, ml: 0, origStart: 0)
  982. rawParse(s, pegAst, 0, cs)
  983. parser
  984. template fillMatches(s, caps, c) =
  985. for k in 0..c.ml-1:
  986. let startIdx = c.matches[k][0]
  987. let endIdx = c.matches[k][1]
  988. if startIdx != -1:
  989. caps[k] = substr(s, startIdx, endIdx)
  990. else:
  991. caps[k] = ""
  992. func matchLen*(s: string, pattern: Peg, matches: var openArray[string],
  993. start = 0): int {.rtl, extern: "npegs$1Capture".} =
  994. ## the same as ``match``, but it returns the length of the match,
  995. ## if there is no match, -1 is returned. Note that a match length
  996. ## of zero can happen. It's possible that a suffix of `s` remains
  997. ## that does not belong to the match.
  998. var c: Captures = Captures(origStart: start)
  999. result = rawMatch(s, pattern, start, c)
  1000. if result >= 0: fillMatches(s, matches, c)
  1001. func matchLen*(s: string, pattern: Peg,
  1002. start = 0): int {.rtl, extern: "npegs$1".} =
  1003. ## the same as ``match``, but it returns the length of the match,
  1004. ## if there is no match, -1 is returned. Note that a match length
  1005. ## of zero can happen. It's possible that a suffix of `s` remains
  1006. ## that does not belong to the match.
  1007. var c: Captures = Captures(origStart: start)
  1008. result = rawMatch(s, pattern, start, c)
  1009. func match*(s: string, pattern: Peg, matches: var openArray[string],
  1010. start = 0): bool {.rtl, extern: "npegs$1Capture".} =
  1011. ## returns ``true`` if ``s[start..]`` matches the ``pattern`` and
  1012. ## the captured substrings in the array ``matches``. If it does not
  1013. ## match, nothing is written into ``matches`` and ``false`` is
  1014. ## returned.
  1015. result = matchLen(s, pattern, matches, start) != -1
  1016. func match*(s: string, pattern: Peg,
  1017. start = 0): bool {.rtl, extern: "npegs$1".} =
  1018. ## returns ``true`` if ``s`` matches the ``pattern`` beginning from ``start``.
  1019. result = matchLen(s, pattern, start) != -1
  1020. func find*(s: string, pattern: Peg, matches: var openArray[string],
  1021. start = 0): int {.rtl, extern: "npegs$1Capture".} =
  1022. ## returns the starting position of ``pattern`` in ``s`` and the captured
  1023. ## substrings in the array ``matches``. If it does not match, nothing
  1024. ## is written into ``matches`` and -1 is returned.
  1025. var c: Captures = Captures(origStart: start)
  1026. for i in start .. s.len-1:
  1027. c.ml = 0
  1028. if rawMatch(s, pattern, i, c) >= 0:
  1029. fillMatches(s, matches, c)
  1030. return i
  1031. return -1
  1032. # could also use the pattern here: (!P .)* P
  1033. func findBounds*(s: string, pattern: Peg, matches: var openArray[string],
  1034. start = 0): tuple[first, last: int] {.
  1035. rtl, extern: "npegs$1Capture".} =
  1036. ## returns the starting position and end position of ``pattern`` in ``s``
  1037. ## and the captured
  1038. ## substrings in the array ``matches``. If it does not match, nothing
  1039. ## is written into ``matches`` and (-1,0) is returned.
  1040. var c: Captures = Captures(origStart: start)
  1041. for i in start .. s.len-1:
  1042. c.ml = 0
  1043. var L = rawMatch(s, pattern, i, c)
  1044. if L >= 0:
  1045. fillMatches(s, matches, c)
  1046. return (i, i+L-1)
  1047. return (-1, 0)
  1048. func find*(s: string, pattern: Peg,
  1049. start = 0): int {.rtl, extern: "npegs$1".} =
  1050. ## returns the starting position of ``pattern`` in ``s``. If it does not
  1051. ## match, -1 is returned.
  1052. var c: Captures = Captures(origStart: start)
  1053. for i in start .. s.len-1:
  1054. if rawMatch(s, pattern, i, c) >= 0: return i
  1055. return -1
  1056. iterator findAll*(s: string, pattern: Peg, start = 0): string =
  1057. ## yields all matching *substrings* of `s` that match `pattern`.
  1058. var c: Captures = Captures(origStart: start)
  1059. var i = start
  1060. while i < s.len:
  1061. c.ml = 0
  1062. var L = rawMatch(s, pattern, i, c)
  1063. if L < 0:
  1064. inc(i, 1)
  1065. else:
  1066. yield substr(s, i, i+L-1)
  1067. inc(i, L)
  1068. func findAll*(s: string, pattern: Peg, start = 0): seq[string] {.
  1069. rtl, extern: "npegs$1".} =
  1070. ## returns all matching *substrings* of `s` that match `pattern`.
  1071. ## If it does not match, `@[]` is returned.
  1072. result = @[]
  1073. for it in findAll(s, pattern, start): result.add it
  1074. template `=~`*(s: string, pattern: Peg): bool =
  1075. ## This calls ``match`` with an implicit declared ``matches`` array that
  1076. ## can be used in the scope of the ``=~`` call:
  1077. ##
  1078. ## ```nim
  1079. ## if line =~ peg"\s* {\w+} \s* '=' \s* {\w+}":
  1080. ## # matches a key=value pair:
  1081. ## echo("Key: ", matches[0])
  1082. ## echo("Value: ", matches[1])
  1083. ## elif line =~ peg"\s*{'#'.*}":
  1084. ## # matches a comment
  1085. ## # note that the implicit ``matches`` array is different from the
  1086. ## # ``matches`` array of the first branch
  1087. ## echo("comment: ", matches[0])
  1088. ## else:
  1089. ## echo("syntax error")
  1090. ## ```
  1091. bind MaxSubpatterns
  1092. when not declaredInScope(matches):
  1093. var matches {.inject.} = default(array[0..MaxSubpatterns-1, string])
  1094. match(s, pattern, matches)
  1095. # ------------------------- more string handling ------------------------------
  1096. func contains*(s: string, pattern: Peg, start = 0): bool {.
  1097. rtl, extern: "npegs$1".} =
  1098. ## same as ``find(s, pattern, start) >= 0``
  1099. return find(s, pattern, start) >= 0
  1100. func contains*(s: string, pattern: Peg, matches: var openArray[string],
  1101. start = 0): bool {.rtl, extern: "npegs$1Capture".} =
  1102. ## same as ``find(s, pattern, matches, start) >= 0``
  1103. return find(s, pattern, matches, start) >= 0
  1104. func startsWith*(s: string, prefix: Peg, start = 0): bool {.
  1105. rtl, extern: "npegs$1".} =
  1106. ## returns true if `s` starts with the pattern `prefix`
  1107. result = matchLen(s, prefix, start) >= 0
  1108. func endsWith*(s: string, suffix: Peg, start = 0): bool {.
  1109. rtl, extern: "npegs$1".} =
  1110. ## returns true if `s` ends with the pattern `suffix`
  1111. result = false
  1112. var c: Captures = Captures(origStart: start)
  1113. for i in start .. s.len-1:
  1114. if rawMatch(s, suffix, i, c) == s.len - i: return true
  1115. func replacef*(s: string, sub: Peg, by: string): string {.
  1116. rtl, extern: "npegs$1".} =
  1117. ## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by`
  1118. ## with the notation ``$i`` and ``$#`` (see strutils.`%`). Examples:
  1119. ##
  1120. ## ```nim
  1121. ## "var1=key; var2=key2".replacef(peg"{\ident}'='{\ident}", "$1<-$2$2")
  1122. ## ```
  1123. ##
  1124. ## Results in:
  1125. ##
  1126. ## ```nim
  1127. ## "var1<-keykey; val2<-key2key2"
  1128. ## ```
  1129. result = ""
  1130. var i = 0
  1131. var caps: array[0..MaxSubpatterns-1, string] = default(array[0..MaxSubpatterns-1, string])
  1132. var c: Captures = default(Captures)
  1133. while i < s.len:
  1134. c.ml = 0
  1135. var x = rawMatch(s, sub, i, c)
  1136. if x <= 0:
  1137. add(result, s[i])
  1138. inc(i)
  1139. else:
  1140. fillMatches(s, caps, c)
  1141. addf(result, by, caps)
  1142. inc(i, x)
  1143. add(result, substr(s, i))
  1144. func replace*(s: string, sub: Peg, by = ""): string {.
  1145. rtl, extern: "npegs$1".} =
  1146. ## Replaces `sub` in `s` by the string `by`. Captures cannot be accessed
  1147. ## in `by`.
  1148. result = ""
  1149. var i = 0
  1150. var c: Captures = default(Captures)
  1151. while i < s.len:
  1152. var x = rawMatch(s, sub, i, c)
  1153. if x <= 0:
  1154. add(result, s[i])
  1155. inc(i)
  1156. else:
  1157. add(result, by)
  1158. inc(i, x)
  1159. add(result, substr(s, i))
  1160. func parallelReplace*(s: string, subs: varargs[
  1161. tuple[pattern: Peg, repl: string]]): string {.
  1162. rtl, extern: "npegs$1".} =
  1163. ## Returns a modified copy of `s` with the substitutions in `subs`
  1164. ## applied in parallel.
  1165. result = ""
  1166. var i = 0
  1167. var c: Captures = default(Captures)
  1168. var caps: array[0..MaxSubpatterns-1, string] = default(array[0..MaxSubpatterns-1, string])
  1169. while i < s.len:
  1170. block searchSubs:
  1171. for j in 0..high(subs):
  1172. c.ml = 0
  1173. var x = rawMatch(s, subs[j][0], i, c)
  1174. if x > 0:
  1175. fillMatches(s, caps, c)
  1176. addf(result, subs[j][1], caps)
  1177. inc(i, x)
  1178. break searchSubs
  1179. add(result, s[i])
  1180. inc(i)
  1181. # copy the rest:
  1182. add(result, substr(s, i))
  1183. when not defined(nimHasEffectsOf):
  1184. {.pragma: effectsOf.}
  1185. func replace*(s: string, sub: Peg, cb: proc(
  1186. match: int, cnt: int, caps: openArray[string]): string): string {.
  1187. rtl, extern: "npegs$1cb", effectsOf: cb.} =
  1188. ## Replaces `sub` in `s` by the resulting strings from the callback.
  1189. ## The callback proc receives the index of the current match (starting with 0),
  1190. ## the count of captures and an open array with the captures of each match. Examples:
  1191. ##
  1192. ## ```nim
  1193. ## func handleMatches*(m: int, n: int, c: openArray[string]): string =
  1194. ## result = ""
  1195. ## if m > 0:
  1196. ## result.add ", "
  1197. ## result.add case n:
  1198. ## of 2: c[0].toLower & ": '" & c[1] & "'"
  1199. ## of 1: c[0].toLower & ": ''"
  1200. ## else: ""
  1201. ##
  1202. ## let s = "Var1=key1;var2=Key2; VAR3"
  1203. ## echo s.replace(peg"{\ident}('='{\ident})* ';'* \s*", handleMatches)
  1204. ## ```
  1205. ##
  1206. ## Results in:
  1207. ##
  1208. ## ```nim
  1209. ## "var1: 'key1', var2: 'Key2', var3: ''"
  1210. ## ```
  1211. result = ""
  1212. var i = 0
  1213. var caps: array[0..MaxSubpatterns-1, string] = default(array[0..MaxSubpatterns-1, string])
  1214. var c: Captures = default(Captures)
  1215. var m = 0
  1216. while i < s.len:
  1217. c.ml = 0
  1218. var x = rawMatch(s, sub, i, c)
  1219. if x <= 0:
  1220. add(result, s[i])
  1221. inc(i)
  1222. else:
  1223. fillMatches(s, caps, c)
  1224. add(result, cb(m, c.ml, caps))
  1225. inc(i, x)
  1226. inc(m)
  1227. add(result, substr(s, i))
  1228. when not defined(js):
  1229. proc transformFile*(infile, outfile: string,
  1230. subs: varargs[tuple[pattern: Peg, repl: string]]) {.
  1231. rtl, extern: "npegs$1".} =
  1232. ## reads in the file `infile`, performs a parallel replacement (calls
  1233. ## `parallelReplace`) and writes back to `outfile`. Raises ``IOError`` if an
  1234. ## error occurs. This is supposed to be used for quick scripting.
  1235. ##
  1236. ## **Note**: this proc does not exist while using the JS backend.
  1237. var x = readFile(infile)
  1238. writeFile(outfile, x.parallelReplace(subs))
  1239. iterator split*(s: string, sep: Peg): string =
  1240. ## Splits the string `s` into substrings.
  1241. ##
  1242. ## Substrings are separated by the PEG `sep`.
  1243. ## Examples:
  1244. ##
  1245. ## ```nim
  1246. ## for word in split("00232this02939is39an22example111", peg"\d+"):
  1247. ## writeLine(stdout, word)
  1248. ## ```
  1249. ##
  1250. ## Results in:
  1251. ##
  1252. ## ```nim
  1253. ## "this"
  1254. ## "is"
  1255. ## "an"
  1256. ## "example"
  1257. ## ```
  1258. var c: Captures = default(Captures)
  1259. var
  1260. first = 0
  1261. last = 0
  1262. while last < len(s):
  1263. c.ml = 0
  1264. var x = rawMatch(s, sep, last, c)
  1265. if x > 0: inc(last, x)
  1266. first = last
  1267. while last < len(s):
  1268. inc(last)
  1269. c.ml = 0
  1270. x = rawMatch(s, sep, last, c)
  1271. if x > 0: break
  1272. if first < last:
  1273. yield substr(s, first, last-1)
  1274. func split*(s: string, sep: Peg): seq[string] {.
  1275. rtl, extern: "npegs$1".} =
  1276. ## Splits the string `s` into substrings.
  1277. result = @[]
  1278. for it in split(s, sep): result.add it
  1279. # ------------------- scanner -------------------------------------------------
  1280. type
  1281. Modifier = enum
  1282. modNone,
  1283. modVerbatim,
  1284. modIgnoreCase,
  1285. modIgnoreStyle
  1286. TokKind = enum ## enumeration of all tokens
  1287. tkInvalid, ## invalid token
  1288. tkEof, ## end of file reached
  1289. tkAny, ## .
  1290. tkAnyRune, ## _
  1291. tkIdentifier, ## abc
  1292. tkStringLit, ## "abc" or 'abc'
  1293. tkCharSet, ## [^A-Z]
  1294. tkParLe, ## '('
  1295. tkParRi, ## ')'
  1296. tkCurlyLe, ## '{'
  1297. tkCurlyRi, ## '}'
  1298. tkCurlyAt, ## '{@}'
  1299. tkEmptyCurl, ## '{}'
  1300. tkArrow, ## '<-'
  1301. tkBar, ## '/'
  1302. tkStar, ## '*'
  1303. tkPlus, ## '+'
  1304. tkAmp, ## '&'
  1305. tkNot, ## '!'
  1306. tkOption, ## '?'
  1307. tkAt, ## '@'
  1308. tkBuiltin, ## \identifier
  1309. tkEscaped, ## \\
  1310. tkBackref, ## '$'
  1311. tkDollar, ## '$'
  1312. tkHat ## '^'
  1313. Token {.final.} = object ## a token
  1314. kind: TokKind ## the type of the token
  1315. modifier: Modifier
  1316. literal: string ## the parsed (string) literal
  1317. charset: set[char] ## if kind == tkCharSet
  1318. index: int ## if kind == tkBackref
  1319. PegLexer {.inheritable.} = object ## the lexer object.
  1320. bufpos: int ## the current position within the buffer
  1321. buf: string ## the buffer itself
  1322. lineNumber: int ## the current line number
  1323. lineStart: int ## index of last line start in buffer
  1324. colOffset: int ## column to add
  1325. filename: string
  1326. const
  1327. tokKindToStr: array[TokKind, string] = [
  1328. "invalid", "[EOF]", ".", "_", "identifier", "string literal",
  1329. "character set", "(", ")", "{", "}", "{@}", "{}",
  1330. "<-", "/", "*", "+", "&", "!", "?",
  1331. "@", "built-in", "escaped", "$", "$", "^"
  1332. ]
  1333. func handleCR(L: var PegLexer, pos: int): int =
  1334. assert(L.buf[pos] == '\c')
  1335. inc(L.lineNumber)
  1336. result = pos+1
  1337. if result < L.buf.len and L.buf[result] == '\L': inc(result)
  1338. L.lineStart = result
  1339. func handleLF(L: var PegLexer, pos: int): int =
  1340. assert(L.buf[pos] == '\L')
  1341. inc(L.lineNumber)
  1342. result = pos+1
  1343. L.lineStart = result
  1344. func init(L: var PegLexer, input, filename: string, line = 1, col = 0) =
  1345. L.buf = input
  1346. L.bufpos = 0
  1347. L.lineNumber = line
  1348. L.colOffset = col
  1349. L.lineStart = 0
  1350. L.filename = filename
  1351. func getColumn(L: PegLexer): int {.inline.} =
  1352. result = abs(L.bufpos - L.lineStart) + L.colOffset
  1353. func getLine(L: PegLexer): int {.inline.} =
  1354. result = L.lineNumber
  1355. func errorStr(L: PegLexer, msg: string, line = -1, col = -1): string =
  1356. var line = if line < 0: getLine(L) else: line
  1357. var col = if col < 0: getColumn(L) else: col
  1358. result = "$1($2, $3) Error: $4" % [L.filename, $line, $col, msg]
  1359. func getEscapedChar(c: var PegLexer, tok: var Token) =
  1360. inc(c.bufpos)
  1361. if c.bufpos >= len(c.buf):
  1362. tok.kind = tkInvalid
  1363. return
  1364. case c.buf[c.bufpos]
  1365. of 'r', 'R', 'c', 'C':
  1366. add(tok.literal, '\c')
  1367. inc(c.bufpos)
  1368. of 'l', 'L':
  1369. add(tok.literal, '\L')
  1370. inc(c.bufpos)
  1371. of 'f', 'F':
  1372. add(tok.literal, '\f')
  1373. inc(c.bufpos)
  1374. of 'e', 'E':
  1375. add(tok.literal, '\e')
  1376. inc(c.bufpos)
  1377. of 'a', 'A':
  1378. add(tok.literal, '\a')
  1379. inc(c.bufpos)
  1380. of 'b', 'B':
  1381. add(tok.literal, '\b')
  1382. inc(c.bufpos)
  1383. of 'v', 'V':
  1384. add(tok.literal, '\v')
  1385. inc(c.bufpos)
  1386. of 't', 'T':
  1387. add(tok.literal, '\t')
  1388. inc(c.bufpos)
  1389. of 'x', 'X':
  1390. inc(c.bufpos)
  1391. if c.bufpos >= len(c.buf):
  1392. tok.kind = tkInvalid
  1393. return
  1394. var xi = 0
  1395. if handleHexChar(c.buf[c.bufpos], xi):
  1396. inc(c.bufpos)
  1397. if handleHexChar(c.buf[c.bufpos], xi):
  1398. inc(c.bufpos)
  1399. if xi == 0: tok.kind = tkInvalid
  1400. else: add(tok.literal, chr(xi))
  1401. of '0'..'9':
  1402. var val = ord(c.buf[c.bufpos]) - ord('0')
  1403. inc(c.bufpos)
  1404. var i = 1
  1405. while (c.bufpos < len(c.buf)) and (i <= 3) and (c.buf[c.bufpos] in {'0'..'9'}):
  1406. val = val * 10 + ord(c.buf[c.bufpos]) - ord('0')
  1407. inc(c.bufpos)
  1408. inc(i)
  1409. if val > 0 and val <= 255: add(tok.literal, chr(val))
  1410. else: tok.kind = tkInvalid
  1411. of '\0'..'\31':
  1412. tok.kind = tkInvalid
  1413. elif c.buf[c.bufpos] in strutils.Letters:
  1414. tok.kind = tkInvalid
  1415. else:
  1416. add(tok.literal, c.buf[c.bufpos])
  1417. inc(c.bufpos)
  1418. func skip(c: var PegLexer) =
  1419. var pos = c.bufpos
  1420. while pos < c.buf.len:
  1421. case c.buf[pos]
  1422. of ' ', '\t':
  1423. inc(pos)
  1424. of '#':
  1425. while (pos < c.buf.len) and
  1426. not (c.buf[pos] in {'\c', '\L', '\0'}): inc(pos)
  1427. of '\c':
  1428. pos = handleCR(c, pos)
  1429. of '\L':
  1430. pos = handleLF(c, pos)
  1431. else:
  1432. break # EndOfFile also leaves the loop
  1433. c.bufpos = pos
  1434. func getString(c: var PegLexer, tok: var Token) =
  1435. tok.kind = tkStringLit
  1436. var pos = c.bufpos + 1
  1437. var quote = c.buf[pos-1]
  1438. while pos < c.buf.len:
  1439. case c.buf[pos]
  1440. of '\\':
  1441. c.bufpos = pos
  1442. getEscapedChar(c, tok)
  1443. pos = c.bufpos
  1444. of '\c', '\L', '\0':
  1445. tok.kind = tkInvalid
  1446. break
  1447. elif c.buf[pos] == quote:
  1448. inc(pos)
  1449. break
  1450. else:
  1451. add(tok.literal, c.buf[pos])
  1452. inc(pos)
  1453. c.bufpos = pos
  1454. func getDollar(c: var PegLexer, tok: var Token) =
  1455. var pos = c.bufpos + 1
  1456. var neg = false
  1457. if pos < c.buf.len and c.buf[pos] == '^':
  1458. neg = true
  1459. inc(pos)
  1460. if pos < c.buf.len and c.buf[pos] in {'0'..'9'}:
  1461. tok.kind = tkBackref
  1462. tok.index = 0
  1463. while pos < c.buf.len and c.buf[pos] in {'0'..'9'}:
  1464. tok.index = tok.index * 10 + ord(c.buf[pos]) - ord('0')
  1465. inc(pos)
  1466. if neg:
  1467. tok.index = -tok.index
  1468. else:
  1469. if neg:
  1470. dec(pos)
  1471. tok.kind = tkDollar
  1472. c.bufpos = pos
  1473. func getCharSet(c: var PegLexer, tok: var Token) =
  1474. tok.kind = tkCharSet
  1475. tok.charset = {}
  1476. var pos = c.bufpos + 1
  1477. var caret = false
  1478. if pos < c.buf.len:
  1479. if c.buf[pos] == '^':
  1480. inc(pos)
  1481. caret = true
  1482. while pos < c.buf.len:
  1483. var ch: char
  1484. case c.buf[pos]
  1485. of ']':
  1486. if pos < c.buf.len: inc(pos)
  1487. break
  1488. of '\\':
  1489. c.bufpos = pos
  1490. getEscapedChar(c, tok)
  1491. pos = c.bufpos
  1492. ch = tok.literal[tok.literal.len-1]
  1493. of '\C', '\L', '\0':
  1494. tok.kind = tkInvalid
  1495. break
  1496. else:
  1497. ch = c.buf[pos]
  1498. inc(pos)
  1499. incl(tok.charset, ch)
  1500. if c.buf[pos] == '-':
  1501. if pos+1 < c.buf.len and c.buf[pos+1] == ']':
  1502. incl(tok.charset, '-')
  1503. inc(pos)
  1504. else:
  1505. if pos+1 < c.buf.len:
  1506. inc(pos)
  1507. else:
  1508. break
  1509. var ch2: char
  1510. case c.buf[pos]
  1511. of '\\':
  1512. c.bufpos = pos
  1513. getEscapedChar(c, tok)
  1514. pos = c.bufpos
  1515. ch2 = tok.literal[tok.literal.len-1]
  1516. of '\C', '\L', '\0':
  1517. tok.kind = tkInvalid
  1518. break
  1519. else:
  1520. if pos+1 < c.buf.len:
  1521. ch2 = c.buf[pos]
  1522. inc(pos)
  1523. else:
  1524. break
  1525. for i in ord(ch)+1 .. ord(ch2):
  1526. incl(tok.charset, chr(i))
  1527. c.bufpos = pos
  1528. if caret: tok.charset = {'\1'..'\xFF'} - tok.charset
  1529. func getSymbol(c: var PegLexer, tok: var Token) =
  1530. var pos = c.bufpos
  1531. while pos < c.buf.len:
  1532. add(tok.literal, c.buf[pos])
  1533. inc(pos)
  1534. if pos < c.buf.len and c.buf[pos] notin strutils.IdentChars: break
  1535. c.bufpos = pos
  1536. tok.kind = tkIdentifier
  1537. func getBuiltin(c: var PegLexer, tok: var Token) =
  1538. if c.bufpos+1 < c.buf.len and c.buf[c.bufpos+1] in strutils.Letters:
  1539. inc(c.bufpos)
  1540. getSymbol(c, tok)
  1541. tok.kind = tkBuiltin
  1542. else:
  1543. tok.kind = tkEscaped
  1544. getEscapedChar(c, tok) # may set tok.kind to tkInvalid
  1545. func getTok(c: var PegLexer, tok: var Token) =
  1546. tok.kind = tkInvalid
  1547. tok.modifier = modNone
  1548. setLen(tok.literal, 0)
  1549. skip(c)
  1550. if c.bufpos >= c.buf.len:
  1551. tok.kind = tkEof
  1552. tok.literal = "[EOF]"
  1553. add(tok.literal, '\0')
  1554. inc(c.bufpos)
  1555. return
  1556. case c.buf[c.bufpos]
  1557. of '{':
  1558. inc(c.bufpos)
  1559. if c.buf[c.bufpos] == '@' and c.bufpos+2 < c.buf.len and
  1560. c.buf[c.bufpos+1] == '}':
  1561. tok.kind = tkCurlyAt
  1562. inc(c.bufpos, 2)
  1563. add(tok.literal, "{@}")
  1564. elif c.buf[c.bufpos] == '}' and c.bufpos < c.buf.len:
  1565. tok.kind = tkEmptyCurl
  1566. inc(c.bufpos)
  1567. add(tok.literal, "{}")
  1568. else:
  1569. tok.kind = tkCurlyLe
  1570. add(tok.literal, '{')
  1571. of '}':
  1572. tok.kind = tkCurlyRi
  1573. inc(c.bufpos)
  1574. add(tok.literal, '}')
  1575. of '[':
  1576. getCharSet(c, tok)
  1577. of '(':
  1578. tok.kind = tkParLe
  1579. inc(c.bufpos)
  1580. add(tok.literal, '(')
  1581. of ')':
  1582. tok.kind = tkParRi
  1583. inc(c.bufpos)
  1584. add(tok.literal, ')')
  1585. of '.':
  1586. tok.kind = tkAny
  1587. inc(c.bufpos)
  1588. add(tok.literal, '.')
  1589. of '_':
  1590. tok.kind = tkAnyRune
  1591. inc(c.bufpos)
  1592. add(tok.literal, '_')
  1593. of '\\':
  1594. getBuiltin(c, tok)
  1595. of '\'', '"': getString(c, tok)
  1596. of '$': getDollar(c, tok)
  1597. of 'a'..'z', 'A'..'Z', '\128'..'\255':
  1598. getSymbol(c, tok)
  1599. if c.bufpos >= c.buf.len:
  1600. return
  1601. if c.buf[c.bufpos] in {'\'', '"'} or
  1602. c.buf[c.bufpos] == '$' and c.bufpos+1 < c.buf.len and
  1603. c.buf[c.bufpos+1] in {'^', '0'..'9'}:
  1604. case tok.literal
  1605. of "i": tok.modifier = modIgnoreCase
  1606. of "y": tok.modifier = modIgnoreStyle
  1607. of "v": tok.modifier = modVerbatim
  1608. else: discard
  1609. setLen(tok.literal, 0)
  1610. if c.buf[c.bufpos] == '$':
  1611. getDollar(c, tok)
  1612. else:
  1613. getString(c, tok)
  1614. if tok.modifier == modNone: tok.kind = tkInvalid
  1615. of '+':
  1616. tok.kind = tkPlus
  1617. inc(c.bufpos)
  1618. add(tok.literal, '+')
  1619. of '*':
  1620. tok.kind = tkStar
  1621. inc(c.bufpos)
  1622. add(tok.literal, '+')
  1623. of '<':
  1624. if c.bufpos+2 < c.buf.len and c.buf[c.bufpos+1] == '-':
  1625. inc(c.bufpos, 2)
  1626. tok.kind = tkArrow
  1627. add(tok.literal, "<-")
  1628. else:
  1629. add(tok.literal, '<')
  1630. of '/':
  1631. tok.kind = tkBar
  1632. inc(c.bufpos)
  1633. add(tok.literal, '/')
  1634. of '?':
  1635. tok.kind = tkOption
  1636. inc(c.bufpos)
  1637. add(tok.literal, '?')
  1638. of '!':
  1639. tok.kind = tkNot
  1640. inc(c.bufpos)
  1641. add(tok.literal, '!')
  1642. of '&':
  1643. tok.kind = tkAmp
  1644. inc(c.bufpos)
  1645. add(tok.literal, '!')
  1646. of '@':
  1647. tok.kind = tkAt
  1648. inc(c.bufpos)
  1649. add(tok.literal, '@')
  1650. if c.buf[c.bufpos] == '@':
  1651. tok.kind = tkCurlyAt
  1652. inc(c.bufpos)
  1653. add(tok.literal, '@')
  1654. of '^':
  1655. tok.kind = tkHat
  1656. inc(c.bufpos)
  1657. add(tok.literal, '^')
  1658. else:
  1659. if c.bufpos >= c.buf.len:
  1660. tok.kind = tkEof
  1661. tok.literal = "[EOF]"
  1662. add(tok.literal, c.buf[c.bufpos])
  1663. inc(c.bufpos)
  1664. func arrowIsNextTok(c: PegLexer): bool =
  1665. # the only look ahead we need
  1666. var pos = c.bufpos
  1667. while pos < c.buf.len and c.buf[pos] in {'\t', ' '}: inc(pos)
  1668. if pos+1 >= c.buf.len:
  1669. return
  1670. result = c.buf[pos] == '<' and c.buf[pos+1] == '-'
  1671. # ----------------------------- parser ----------------------------------------
  1672. type
  1673. EInvalidPeg* = object of ValueError ## raised if an invalid
  1674. ## PEG has been detected
  1675. PegParser = object of PegLexer ## the PEG parser object
  1676. tok: Token
  1677. nonterms: seq[NonTerminal]
  1678. modifier: Modifier
  1679. captures: int
  1680. identIsVerbatim: bool
  1681. skip: Peg
  1682. func pegError(p: PegParser, msg: string, line = -1, col = -1) {.noreturn.} =
  1683. var e = (ref EInvalidPeg)(msg: errorStr(p, msg, line, col))
  1684. raise e
  1685. func getTok(p: var PegParser) =
  1686. getTok(p, p.tok)
  1687. if p.tok.kind == tkInvalid: pegError(p, "'" & p.tok.literal & "' is invalid token")
  1688. func eat(p: var PegParser, kind: TokKind) =
  1689. if p.tok.kind == kind: getTok(p)
  1690. else: pegError(p, tokKindToStr[kind] & " expected")
  1691. func parseExpr(p: var PegParser): Peg {.gcsafe.}
  1692. func getNonTerminal(p: var PegParser, name: string): NonTerminal =
  1693. for i in 0..high(p.nonterms):
  1694. result = p.nonterms[i]
  1695. if cmpIgnoreStyle(result.name, name) == 0: return
  1696. # forward reference:
  1697. result = newNonTerminal(name, getLine(p), getColumn(p))
  1698. add(p.nonterms, result)
  1699. func modifiedTerm(s: string, m: Modifier): Peg =
  1700. case m
  1701. of modNone, modVerbatim: result = term(s)
  1702. of modIgnoreCase: result = termIgnoreCase(s)
  1703. of modIgnoreStyle: result = termIgnoreStyle(s)
  1704. func modifiedBackref(s: int, m: Modifier): Peg =
  1705. var
  1706. reverse = s < 0
  1707. index = if reverse: -s else: s
  1708. case m
  1709. of modNone, modVerbatim: result = backref(index, reverse)
  1710. of modIgnoreCase: result = backrefIgnoreCase(index, reverse)
  1711. of modIgnoreStyle: result = backrefIgnoreStyle(index, reverse)
  1712. func builtin(p: var PegParser): Peg =
  1713. # do not use "y", "skip" or "i" as these would be ambiguous
  1714. case p.tok.literal
  1715. of "n": result = newLine()
  1716. of "d": result = charSet({'0'..'9'})
  1717. of "D": result = charSet({'\1'..'\xff'} - {'0'..'9'})
  1718. of "s": result = charSet({' ', '\9'..'\13'})
  1719. of "S": result = charSet({'\1'..'\xff'} - {' ', '\9'..'\13'})
  1720. of "w": result = charSet({'a'..'z', 'A'..'Z', '_', '0'..'9'})
  1721. of "W": result = charSet({'\1'..'\xff'} - {'a'..'z', 'A'..'Z', '_', '0'..'9'})
  1722. of "a": result = charSet({'a'..'z', 'A'..'Z'})
  1723. of "A": result = charSet({'\1'..'\xff'} - {'a'..'z', 'A'..'Z'})
  1724. of "ident": result = pegs.ident
  1725. of "letter": result = unicodeLetter()
  1726. of "upper": result = unicodeUpper()
  1727. of "lower": result = unicodeLower()
  1728. of "title": result = unicodeTitle()
  1729. of "white": result = unicodeWhitespace()
  1730. else: pegError(p, "unknown built-in: " & p.tok.literal)
  1731. func token(terminal: Peg, p: PegParser): Peg =
  1732. if p.skip.kind == pkEmpty: result = terminal
  1733. else: result = sequence(p.skip, terminal)
  1734. func primary(p: var PegParser): Peg =
  1735. case p.tok.kind
  1736. of tkAmp:
  1737. getTok(p)
  1738. return &primary(p)
  1739. of tkNot:
  1740. getTok(p)
  1741. return !primary(p)
  1742. of tkAt:
  1743. getTok(p)
  1744. return !*primary(p)
  1745. of tkCurlyAt:
  1746. getTok(p)
  1747. return !*\primary(p).token(p)
  1748. else: discard
  1749. case p.tok.kind
  1750. of tkIdentifier:
  1751. if p.identIsVerbatim:
  1752. var m = p.tok.modifier
  1753. if m == modNone: m = p.modifier
  1754. result = modifiedTerm(p.tok.literal, m).token(p)
  1755. getTok(p)
  1756. elif not arrowIsNextTok(p):
  1757. var nt = getNonTerminal(p, p.tok.literal)
  1758. {.cast(noSideEffect).}:
  1759. incl(nt.flags, ntUsed)
  1760. result = nonterminal(nt).token(p)
  1761. getTok(p)
  1762. else:
  1763. pegError(p, "expression expected, but found: " & p.tok.literal)
  1764. of tkStringLit:
  1765. var m = p.tok.modifier
  1766. if m == modNone: m = p.modifier
  1767. result = modifiedTerm(p.tok.literal, m).token(p)
  1768. getTok(p)
  1769. of tkCharSet:
  1770. if '\0' in p.tok.charset:
  1771. pegError(p, "binary zero ('\\0') not allowed in character class")
  1772. result = charSet(p.tok.charset).token(p)
  1773. getTok(p)
  1774. of tkParLe:
  1775. getTok(p)
  1776. result = parseExpr(p)
  1777. eat(p, tkParRi)
  1778. of tkCurlyLe:
  1779. getTok(p)
  1780. result = capture(parseExpr(p)).token(p)
  1781. eat(p, tkCurlyRi)
  1782. inc(p.captures)
  1783. of tkEmptyCurl:
  1784. result = capture()
  1785. getTok(p)
  1786. of tkAny:
  1787. result = any().token(p)
  1788. getTok(p)
  1789. of tkAnyRune:
  1790. result = anyRune().token(p)
  1791. getTok(p)
  1792. of tkBuiltin:
  1793. result = builtin(p).token(p)
  1794. getTok(p)
  1795. of tkEscaped:
  1796. result = term(p.tok.literal[0]).token(p)
  1797. getTok(p)
  1798. of tkDollar:
  1799. result = endAnchor()
  1800. getTok(p)
  1801. of tkHat:
  1802. result = startAnchor()
  1803. getTok(p)
  1804. of tkBackref:
  1805. if abs(p.tok.index) > p.captures or p.tok.index == 0:
  1806. pegError(p, "invalid back reference index: " & $p.tok.index)
  1807. var m = p.tok.modifier
  1808. if m == modNone: m = p.modifier
  1809. result = modifiedBackref(p.tok.index, m).token(p)
  1810. getTok(p)
  1811. else:
  1812. pegError(p, "expression expected, but found: " & p.tok.literal)
  1813. # getTok(p) # we must consume a token here to prevent endless loops!
  1814. while true:
  1815. case p.tok.kind
  1816. of tkOption:
  1817. result = ?result
  1818. getTok(p)
  1819. of tkStar:
  1820. result = *result
  1821. getTok(p)
  1822. of tkPlus:
  1823. result = +result
  1824. getTok(p)
  1825. else: break
  1826. func seqExpr(p: var PegParser): Peg =
  1827. result = primary(p)
  1828. while true:
  1829. case p.tok.kind
  1830. of tkAmp, tkNot, tkAt, tkStringLit, tkCharSet, tkParLe, tkCurlyLe,
  1831. tkAny, tkAnyRune, tkBuiltin, tkEscaped, tkDollar, tkBackref,
  1832. tkHat, tkCurlyAt, tkEmptyCurl:
  1833. result = sequence(result, primary(p))
  1834. of tkIdentifier:
  1835. if not arrowIsNextTok(p):
  1836. result = sequence(result, primary(p))
  1837. else: break
  1838. else: break
  1839. func parseExpr(p: var PegParser): Peg =
  1840. result = seqExpr(p)
  1841. while p.tok.kind == tkBar:
  1842. getTok(p)
  1843. result = result / seqExpr(p)
  1844. func parseRule(p: var PegParser): NonTerminal =
  1845. if p.tok.kind == tkIdentifier and arrowIsNextTok(p):
  1846. result = getNonTerminal(p, p.tok.literal)
  1847. if ntDeclared in result.flags:
  1848. pegError(p, "attempt to redefine: " & result.name)
  1849. {.cast(noSideEffect).}:
  1850. result.line = getLine(p)
  1851. result.col = getColumn(p)
  1852. getTok(p)
  1853. eat(p, tkArrow)
  1854. {.cast(noSideEffect).}:
  1855. result.rule = parseExpr(p)
  1856. incl(result.flags, ntDeclared) # NOW inlining may be attempted
  1857. else:
  1858. pegError(p, "rule expected, but found: " & p.tok.literal)
  1859. func rawParse(p: var PegParser): Peg =
  1860. ## parses a rule or a PEG expression
  1861. while p.tok.kind == tkBuiltin:
  1862. case p.tok.literal
  1863. of "i":
  1864. p.modifier = modIgnoreCase
  1865. getTok(p)
  1866. of "y":
  1867. p.modifier = modIgnoreStyle
  1868. getTok(p)
  1869. of "skip":
  1870. getTok(p)
  1871. p.skip = ?primary(p)
  1872. else: break
  1873. if p.tok.kind == tkIdentifier and arrowIsNextTok(p):
  1874. result = parseRule(p).rule
  1875. while p.tok.kind != tkEof:
  1876. discard parseRule(p)
  1877. else:
  1878. p.identIsVerbatim = true
  1879. result = parseExpr(p)
  1880. if p.tok.kind != tkEof:
  1881. pegError(p, "EOF expected, but found: " & p.tok.literal)
  1882. for i in 0..high(p.nonterms):
  1883. var nt = p.nonterms[i]
  1884. if ntDeclared notin nt.flags:
  1885. pegError(p, "undeclared identifier: " & nt.name, nt.line, nt.col)
  1886. elif ntUsed notin nt.flags and i > 0:
  1887. pegError(p, "unused rule: " & nt.name, nt.line, nt.col)
  1888. func parsePeg*(pattern: string, filename = "pattern", line = 1, col = 0): Peg =
  1889. ## constructs a Peg object from `pattern`. `filename`, `line`, `col` are
  1890. ## used for error messages, but they only provide start offsets. `parsePeg`
  1891. ## keeps track of line and column numbers within `pattern`.
  1892. var p: PegParser = default(PegParser)
  1893. init(PegLexer(p), pattern, filename, line, col)
  1894. p.tok.kind = tkInvalid
  1895. p.tok.modifier = modNone
  1896. p.tok.literal = ""
  1897. p.tok.charset = {}
  1898. p.nonterms = @[]
  1899. p.identIsVerbatim = false
  1900. getTok(p)
  1901. result = rawParse(p)
  1902. func peg*(pattern: string): Peg =
  1903. ## constructs a Peg object from the `pattern`. The short name has been
  1904. ## chosen to encourage its use as a raw string modifier:
  1905. ##
  1906. ## peg"{\ident} \s* '=' \s* {.*}"
  1907. result = parsePeg(pattern, "pattern")
  1908. func escapePeg*(s: string): string =
  1909. ## escapes `s` so that it is matched verbatim when used as a peg.
  1910. result = ""
  1911. var inQuote = false
  1912. for c in items(s):
  1913. case c
  1914. of '\0'..'\31', '\'', '"', '\\':
  1915. if inQuote:
  1916. result.add('\'')
  1917. inQuote = false
  1918. result.add("\\x")
  1919. result.add(toHex(ord(c), 2))
  1920. else:
  1921. if not inQuote:
  1922. result.add('\'')
  1923. inQuote = true
  1924. result.add(c)
  1925. if inQuote: result.add('\'')