pegs.nim 67 KB

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