pegs.nim 65 KB

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