pegs.nim 67 KB

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