pegs.nim 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086
  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.} =
  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. # .. code-block::
  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. func mkEnter(hdName, body: NimNode): NimNode =
  832. template helper(hdName, body) {.dirty.} =
  833. template hdName(s, p, start) =
  834. let s {.inject.} = s
  835. let p {.inject.} = p
  836. let start {.inject.} = start
  837. body
  838. result = getAst(helper(hdName, body))
  839. template mkLeave(hdPostf, body) {.dirty.} =
  840. # this has to be dirty to be able to capture *result* as *length* in
  841. # *leaveXX* calls.
  842. template `leave hdPostf`(s, p, start, length) =
  843. body
  844. result = newStmtList()
  845. for topCall in handlers[0]:
  846. if topCall.kind notin nnkCallKinds:
  847. error("Call syntax expected.", topCall)
  848. let pegKind = topCall[0]
  849. if pegKind.kind notin {nnkIdent, nnkSym}:
  850. error("PegKind expected.", pegKind)
  851. if 2 == topCall.len:
  852. for hdDef in topCall[1]:
  853. if hdDef.kind notin nnkCallKinds:
  854. error("Call syntax expected.", hdDef)
  855. if hdDef[0].kind notin {nnkIdent, nnkSym}:
  856. error("Handler identifier expected.", hdDef[0])
  857. if 2 == hdDef.len:
  858. let hdPostf = substr(pegKind.strVal, 2)
  859. case hdDef[0].strVal
  860. of "enter":
  861. result.add mkEnter(newIdentNode("enter" & hdPostf), hdDef[1])
  862. of "leave":
  863. result.add getAst(mkLeave(ident(hdPostf), hdDef[1]))
  864. else:
  865. error(
  866. "Unsupported handler identifier, expected 'enter' or 'leave'.",
  867. hdDef[0]
  868. )
  869. template eventParser*(pegAst, handlers: untyped): (proc(s: string): int) =
  870. ## Generates an interpreting event parser *proc* according to the specified
  871. ## PEG AST and handler code blocks. The *proc* can be called with a string
  872. ## to be parsed and will execute the handler code blocks whenever their
  873. ## associated grammar element is matched. It returns -1 if the string does not
  874. ## match, else the length of the total match. The following example code
  875. ## evaluates an arithmetic expression defined by a simple PEG:
  876. ##
  877. ## .. code-block:: nim
  878. ## import std/[strutils, pegs]
  879. ##
  880. ## let
  881. ## pegAst = """
  882. ## Expr <- Sum
  883. ## Sum <- Product (('+' / '-')Product)*
  884. ## Product <- Value (('*' / '/')Value)*
  885. ## Value <- [0-9]+ / '(' Expr ')'
  886. ## """.peg
  887. ## txt = "(5+3)/2-7*22"
  888. ##
  889. ## var
  890. ## pStack: seq[string] = @[]
  891. ## valStack: seq[float] = @[]
  892. ## opStack = ""
  893. ## let
  894. ## parseArithExpr = pegAst.eventParser:
  895. ## pkNonTerminal:
  896. ## enter:
  897. ## pStack.add p.nt.name
  898. ## leave:
  899. ## pStack.setLen pStack.high
  900. ## if length > 0:
  901. ## let matchStr = s.substr(start, start+length-1)
  902. ## case p.nt.name
  903. ## of "Value":
  904. ## try:
  905. ## valStack.add matchStr.parseFloat
  906. ## echo valStack
  907. ## except ValueError:
  908. ## discard
  909. ## of "Sum", "Product":
  910. ## try:
  911. ## let val = matchStr.parseFloat
  912. ## except ValueError:
  913. ## if valStack.len > 1 and opStack.len > 0:
  914. ## valStack[^2] = case opStack[^1]
  915. ## of '+': valStack[^2] + valStack[^1]
  916. ## of '-': valStack[^2] - valStack[^1]
  917. ## of '*': valStack[^2] * valStack[^1]
  918. ## else: valStack[^2] / valStack[^1]
  919. ## valStack.setLen valStack.high
  920. ## echo valStack
  921. ## opStack.setLen opStack.high
  922. ## echo opStack
  923. ## pkChar:
  924. ## leave:
  925. ## if length == 1 and "Value" != pStack[^1]:
  926. ## let matchChar = s[start]
  927. ## opStack.add matchChar
  928. ## echo opStack
  929. ##
  930. ## let pLen = parseArithExpr(txt)
  931. ##
  932. ## The *handlers* parameter consists of code blocks for *PegKinds*,
  933. ## which define the grammar elements of interest. Each block can contain
  934. ## handler code to be executed when the parser enters and leaves text
  935. ## matching the grammar element. An *enter* handler can access the specific
  936. ## PEG AST node being matched as *p*, the entire parsed string as *s*
  937. ## and the position of the matched text segment in *s* as *start*. A *leave*
  938. ## handler can access *p*, *s*, *start* and also the length of the matched
  939. ## text segment as *length*. For an unsuccessful match, the *enter* and
  940. ## *leave* handlers will be executed, with *length* set to -1.
  941. ##
  942. ## Symbols declared in an *enter* handler can be made visible in the
  943. ## corresponding *leave* handler by annotating them with an *inject* pragma.
  944. proc rawParse(s: string, p: Peg, start: int, c: var Captures): int
  945. {.gensym.} =
  946. # binding from *macros*
  947. bind strVal
  948. mkHandlerTplts:
  949. handlers
  950. macro enter(pegKind, s, pegNode, start: untyped): untyped =
  951. # This is called by the matcher code in *matchOrParse* at the
  952. # start of the code for a grammar element of kind *pegKind*.
  953. # Expands to a call to the handler template if one was generated
  954. # by *mkHandlerTplts*.
  955. template mkDoEnter(hdPostf, s, pegNode, start) =
  956. when declared(`enter hdPostf`):
  957. `enter hdPostf`(s, pegNode, start):
  958. else:
  959. discard
  960. let hdPostf = ident(substr(strVal(pegKind), 2))
  961. getAst(mkDoEnter(hdPostf, s, pegNode, start))
  962. macro leave(pegKind, s, pegNode, start, length: untyped): untyped =
  963. # Like *enter*, but called at the end of the matcher code for
  964. # a grammar element of kind *pegKind*.
  965. template mkDoLeave(hdPostf, s, pegNode, start, length) =
  966. when declared(`leave hdPostf`):
  967. `leave hdPostf`(s, pegNode, start, length):
  968. else:
  969. discard
  970. let hdPostf = ident(substr(strVal(pegKind), 2))
  971. getAst(mkDoLeave(hdPostf, s, pegNode, start, length))
  972. matchOrParse(parseIt)
  973. parseIt(s, p, start, c)
  974. proc parser(s: string): int {.gensym.} =
  975. # the proc to be returned
  976. var
  977. ms: array[MaxSubpatterns, (int, int)]
  978. cs = Captures(matches: ms, ml: 0, origStart: 0)
  979. rawParse(s, pegAst, 0, cs)
  980. parser
  981. template fillMatches(s, caps, c) =
  982. for k in 0..c.ml-1:
  983. let startIdx = c.matches[k][0]
  984. let endIdx = c.matches[k][1]
  985. if startIdx != -1:
  986. caps[k] = substr(s, startIdx, endIdx)
  987. else:
  988. caps[k] = ""
  989. func matchLen*(s: string, pattern: Peg, matches: var openArray[string],
  990. start = 0): int {.rtl, extern: "npegs$1Capture".} =
  991. ## the same as ``match``, but it returns the length of the match,
  992. ## if there is no match, -1 is returned. Note that a match length
  993. ## of zero can happen. It's possible that a suffix of `s` remains
  994. ## that does not belong to the match.
  995. var c: Captures
  996. c.origStart = start
  997. result = rawMatch(s, pattern, start, c)
  998. if result >= 0: fillMatches(s, matches, c)
  999. func matchLen*(s: string, pattern: Peg,
  1000. start = 0): int {.rtl, extern: "npegs$1".} =
  1001. ## the same as ``match``, but it returns the length of the match,
  1002. ## if there is no match, -1 is returned. Note that a match length
  1003. ## of zero can happen. It's possible that a suffix of `s` remains
  1004. ## that does not belong to the match.
  1005. var c: Captures
  1006. c.origStart = start
  1007. result = rawMatch(s, pattern, start, c)
  1008. func match*(s: string, pattern: Peg, matches: var openArray[string],
  1009. start = 0): bool {.rtl, extern: "npegs$1Capture".} =
  1010. ## returns ``true`` if ``s[start..]`` matches the ``pattern`` and
  1011. ## the captured substrings in the array ``matches``. If it does not
  1012. ## match, nothing is written into ``matches`` and ``false`` is
  1013. ## returned.
  1014. result = matchLen(s, pattern, matches, start) != -1
  1015. func match*(s: string, pattern: Peg,
  1016. start = 0): bool {.rtl, extern: "npegs$1".} =
  1017. ## returns ``true`` if ``s`` matches the ``pattern`` beginning from ``start``.
  1018. result = matchLen(s, pattern, start) != -1
  1019. func find*(s: string, pattern: Peg, matches: var openArray[string],
  1020. start = 0): int {.rtl, extern: "npegs$1Capture".} =
  1021. ## returns the starting position of ``pattern`` in ``s`` and the captured
  1022. ## substrings in the array ``matches``. If it does not match, nothing
  1023. ## is written into ``matches`` and -1 is returned.
  1024. var c: Captures
  1025. c.origStart = start
  1026. for i in start .. s.len-1:
  1027. c.ml = 0
  1028. if rawMatch(s, pattern, i, c) >= 0:
  1029. fillMatches(s, matches, c)
  1030. return i
  1031. return -1
  1032. # could also use the pattern here: (!P .)* P
  1033. func findBounds*(s: string, pattern: Peg, matches: var openArray[string],
  1034. start = 0): tuple[first, last: int] {.
  1035. rtl, extern: "npegs$1Capture".} =
  1036. ## returns the starting position and end position of ``pattern`` in ``s``
  1037. ## and the captured
  1038. ## substrings in the array ``matches``. If it does not match, nothing
  1039. ## is written into ``matches`` and (-1,0) is returned.
  1040. var c: Captures
  1041. c.origStart = start
  1042. for i in start .. s.len-1:
  1043. c.ml = 0
  1044. var L = rawMatch(s, pattern, i, c)
  1045. if L >= 0:
  1046. fillMatches(s, matches, c)
  1047. return (i, i+L-1)
  1048. return (-1, 0)
  1049. func find*(s: string, pattern: Peg,
  1050. start = 0): int {.rtl, extern: "npegs$1".} =
  1051. ## returns the starting position of ``pattern`` in ``s``. If it does not
  1052. ## match, -1 is returned.
  1053. var c: Captures
  1054. c.origStart = start
  1055. for i in start .. s.len-1:
  1056. if rawMatch(s, pattern, i, c) >= 0: return i
  1057. return -1
  1058. iterator findAll*(s: string, pattern: Peg, start = 0): string =
  1059. ## yields all matching *substrings* of `s` that match `pattern`.
  1060. var c: Captures
  1061. c.origStart = start
  1062. var i = start
  1063. while i < s.len:
  1064. c.ml = 0
  1065. var L = rawMatch(s, pattern, i, c)
  1066. if L < 0:
  1067. inc(i, 1)
  1068. else:
  1069. yield substr(s, i, i+L-1)
  1070. inc(i, L)
  1071. func findAll*(s: string, pattern: Peg, start = 0): seq[string] {.
  1072. rtl, extern: "npegs$1".} =
  1073. ## returns all matching *substrings* of `s` that match `pattern`.
  1074. ## If it does not match, `@[]` is returned.
  1075. result = @[]
  1076. for it in findAll(s, pattern, start): result.add it
  1077. template `=~`*(s: string, pattern: Peg): bool =
  1078. ## This calls ``match`` with an implicit declared ``matches`` array that
  1079. ## can be used in the scope of the ``=~`` call:
  1080. ##
  1081. ## .. code-block:: nim
  1082. ##
  1083. ## if line =~ peg"\s* {\w+} \s* '=' \s* {\w+}":
  1084. ## # matches a key=value pair:
  1085. ## echo("Key: ", matches[0])
  1086. ## echo("Value: ", matches[1])
  1087. ## elif line =~ peg"\s*{'#'.*}":
  1088. ## # matches a comment
  1089. ## # note that the implicit ``matches`` array is different from the
  1090. ## # ``matches`` array of the first branch
  1091. ## echo("comment: ", matches[0])
  1092. ## else:
  1093. ## echo("syntax error")
  1094. ##
  1095. bind MaxSubpatterns
  1096. when not declaredInScope(matches):
  1097. var matches {.inject.}: array[0..MaxSubpatterns-1, string]
  1098. match(s, pattern, matches)
  1099. # ------------------------- more string handling ------------------------------
  1100. func contains*(s: string, pattern: Peg, start = 0): bool {.
  1101. rtl, extern: "npegs$1".} =
  1102. ## same as ``find(s, pattern, start) >= 0``
  1103. return find(s, pattern, start) >= 0
  1104. func contains*(s: string, pattern: Peg, matches: var openArray[string],
  1105. start = 0): bool {.rtl, extern: "npegs$1Capture".} =
  1106. ## same as ``find(s, pattern, matches, start) >= 0``
  1107. return find(s, pattern, matches, start) >= 0
  1108. func startsWith*(s: string, prefix: Peg, start = 0): bool {.
  1109. rtl, extern: "npegs$1".} =
  1110. ## returns true if `s` starts with the pattern `prefix`
  1111. result = matchLen(s, prefix, start) >= 0
  1112. func endsWith*(s: string, suffix: Peg, start = 0): bool {.
  1113. rtl, extern: "npegs$1".} =
  1114. ## returns true if `s` ends with the pattern `suffix`
  1115. var c: Captures
  1116. c.origStart = start
  1117. for i in start .. s.len-1:
  1118. if rawMatch(s, suffix, i, c) == s.len - i: return true
  1119. func replacef*(s: string, sub: Peg, by: string): string {.
  1120. rtl, extern: "npegs$1".} =
  1121. ## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by`
  1122. ## with the notation ``$i`` and ``$#`` (see strutils.`%`). Examples:
  1123. ##
  1124. ## .. code-block:: nim
  1125. ## "var1=key; var2=key2".replacef(peg"{\ident}'='{\ident}", "$1<-$2$2")
  1126. ##
  1127. ## Results in:
  1128. ##
  1129. ## .. code-block:: nim
  1130. ##
  1131. ## "var1<-keykey; val2<-key2key2"
  1132. result = ""
  1133. var i = 0
  1134. var caps: array[0..MaxSubpatterns-1, string]
  1135. var c: Captures
  1136. while i < s.len:
  1137. c.ml = 0
  1138. var x = rawMatch(s, sub, i, c)
  1139. if x <= 0:
  1140. add(result, s[i])
  1141. inc(i)
  1142. else:
  1143. fillMatches(s, caps, c)
  1144. addf(result, by, caps)
  1145. inc(i, x)
  1146. add(result, substr(s, i))
  1147. func replace*(s: string, sub: Peg, by = ""): string {.
  1148. rtl, extern: "npegs$1".} =
  1149. ## Replaces `sub` in `s` by the string `by`. Captures cannot be accessed
  1150. ## in `by`.
  1151. result = ""
  1152. var i = 0
  1153. var c: Captures
  1154. while i < s.len:
  1155. var x = rawMatch(s, sub, i, c)
  1156. if x <= 0:
  1157. add(result, s[i])
  1158. inc(i)
  1159. else:
  1160. add(result, by)
  1161. inc(i, x)
  1162. add(result, substr(s, i))
  1163. func parallelReplace*(s: string, subs: varargs[
  1164. tuple[pattern: Peg, repl: string]]): string {.
  1165. rtl, extern: "npegs$1".} =
  1166. ## Returns a modified copy of `s` with the substitutions in `subs`
  1167. ## applied in parallel.
  1168. result = ""
  1169. var i = 0
  1170. var c: Captures
  1171. var caps: array[0..MaxSubpatterns-1, string]
  1172. while i < s.len:
  1173. block searchSubs:
  1174. for j in 0..high(subs):
  1175. c.ml = 0
  1176. var x = rawMatch(s, subs[j][0], i, c)
  1177. if x > 0:
  1178. fillMatches(s, caps, c)
  1179. addf(result, subs[j][1], caps)
  1180. inc(i, x)
  1181. break searchSubs
  1182. add(result, s[i])
  1183. inc(i)
  1184. # copy the rest:
  1185. add(result, substr(s, i))
  1186. when not defined(nimHasEffectsOf):
  1187. {.pragma: effectsOf.}
  1188. func replace*(s: string, sub: Peg, cb: proc(
  1189. match: int, cnt: int, caps: openArray[string]): string): string {.
  1190. rtl, extern: "npegs$1cb", effectsOf: cb.} =
  1191. ## Replaces `sub` in `s` by the resulting strings from the callback.
  1192. ## The callback proc receives the index of the current match (starting with 0),
  1193. ## the count of captures and an open array with the captures of each match. Examples:
  1194. ##
  1195. ## .. code-block:: nim
  1196. ##
  1197. ## func handleMatches*(m: int, n: int, c: openArray[string]): string =
  1198. ## result = ""
  1199. ## if m > 0:
  1200. ## result.add ", "
  1201. ## result.add case n:
  1202. ## of 2: c[0].toLower & ": '" & c[1] & "'"
  1203. ## of 1: c[0].toLower & ": ''"
  1204. ## else: ""
  1205. ##
  1206. ## let s = "Var1=key1;var2=Key2; VAR3"
  1207. ## echo s.replace(peg"{\ident}('='{\ident})* ';'* \s*", handleMatches)
  1208. ##
  1209. ## Results in:
  1210. ##
  1211. ## .. code-block:: nim
  1212. ##
  1213. ## "var1: 'key1', var2: 'Key2', var3: ''"
  1214. result = ""
  1215. var i = 0
  1216. var caps: array[0..MaxSubpatterns-1, string]
  1217. var c: Captures
  1218. var m = 0
  1219. while i < s.len:
  1220. c.ml = 0
  1221. var x = rawMatch(s, sub, i, c)
  1222. if x <= 0:
  1223. add(result, s[i])
  1224. inc(i)
  1225. else:
  1226. fillMatches(s, caps, c)
  1227. add(result, cb(m, c.ml, caps))
  1228. inc(i, x)
  1229. inc(m)
  1230. add(result, substr(s, i))
  1231. when not defined(js):
  1232. proc transformFile*(infile, outfile: string,
  1233. subs: varargs[tuple[pattern: Peg, repl: string]]) {.
  1234. rtl, extern: "npegs$1".} =
  1235. ## reads in the file `infile`, performs a parallel replacement (calls
  1236. ## `parallelReplace`) and writes back to `outfile`. Raises ``IOError`` if an
  1237. ## error occurs. This is supposed to be used for quick scripting.
  1238. ##
  1239. ## **Note**: this proc does not exist while using the JS backend.
  1240. var x = readFile(infile)
  1241. writeFile(outfile, x.parallelReplace(subs))
  1242. iterator split*(s: string, sep: Peg): string =
  1243. ## Splits the string `s` into substrings.
  1244. ##
  1245. ## Substrings are separated by the PEG `sep`.
  1246. ## Examples:
  1247. ##
  1248. ## .. code-block:: nim
  1249. ## for word in split("00232this02939is39an22example111", peg"\d+"):
  1250. ## writeLine(stdout, word)
  1251. ##
  1252. ## Results in:
  1253. ##
  1254. ## .. code-block:: nim
  1255. ## "this"
  1256. ## "is"
  1257. ## "an"
  1258. ## "example"
  1259. ##
  1260. var c: Captures
  1261. var
  1262. first = 0
  1263. last = 0
  1264. while last < len(s):
  1265. c.ml = 0
  1266. var x = rawMatch(s, sep, last, c)
  1267. if x > 0: inc(last, x)
  1268. first = last
  1269. while last < len(s):
  1270. inc(last)
  1271. c.ml = 0
  1272. x = rawMatch(s, sep, last, c)
  1273. if x > 0: break
  1274. if first < last:
  1275. yield substr(s, first, last-1)
  1276. func split*(s: string, sep: Peg): seq[string] {.
  1277. rtl, extern: "npegs$1".} =
  1278. ## Splits the string `s` into substrings.
  1279. result = @[]
  1280. for it in split(s, sep): result.add it
  1281. # ------------------- scanner -------------------------------------------------
  1282. type
  1283. Modifier = enum
  1284. modNone,
  1285. modVerbatim,
  1286. modIgnoreCase,
  1287. modIgnoreStyle
  1288. TokKind = enum ## enumeration of all tokens
  1289. tkInvalid, ## invalid token
  1290. tkEof, ## end of file reached
  1291. tkAny, ## .
  1292. tkAnyRune, ## _
  1293. tkIdentifier, ## abc
  1294. tkStringLit, ## "abc" or 'abc'
  1295. tkCharSet, ## [^A-Z]
  1296. tkParLe, ## '('
  1297. tkParRi, ## ')'
  1298. tkCurlyLe, ## '{'
  1299. tkCurlyRi, ## '}'
  1300. tkCurlyAt, ## '{@}'
  1301. tkEmptyCurl, ## '{}'
  1302. tkArrow, ## '<-'
  1303. tkBar, ## '/'
  1304. tkStar, ## '*'
  1305. tkPlus, ## '+'
  1306. tkAmp, ## '&'
  1307. tkNot, ## '!'
  1308. tkOption, ## '?'
  1309. tkAt, ## '@'
  1310. tkBuiltin, ## \identifier
  1311. tkEscaped, ## \\
  1312. tkBackref, ## '$'
  1313. tkDollar, ## '$'
  1314. tkHat ## '^'
  1315. Token {.final.} = object ## a token
  1316. kind: TokKind ## the type of the token
  1317. modifier: Modifier
  1318. literal: string ## the parsed (string) literal
  1319. charset: set[char] ## if kind == tkCharSet
  1320. index: int ## if kind == tkBackref
  1321. PegLexer {.inheritable.} = object ## the lexer object.
  1322. bufpos: int ## the current position within the buffer
  1323. buf: string ## the buffer itself
  1324. lineNumber: int ## the current line number
  1325. lineStart: int ## index of last line start in buffer
  1326. colOffset: int ## column to add
  1327. filename: string
  1328. const
  1329. tokKindToStr: array[TokKind, string] = [
  1330. "invalid", "[EOF]", ".", "_", "identifier", "string literal",
  1331. "character set", "(", ")", "{", "}", "{@}", "{}",
  1332. "<-", "/", "*", "+", "&", "!", "?",
  1333. "@", "built-in", "escaped", "$", "$", "^"
  1334. ]
  1335. func handleCR(L: var PegLexer, pos: int): int =
  1336. assert(L.buf[pos] == '\c')
  1337. inc(L.lineNumber)
  1338. result = pos+1
  1339. if result < L.buf.len and L.buf[result] == '\L': inc(result)
  1340. L.lineStart = result
  1341. func handleLF(L: var PegLexer, pos: int): int =
  1342. assert(L.buf[pos] == '\L')
  1343. inc(L.lineNumber)
  1344. result = pos+1
  1345. L.lineStart = result
  1346. func init(L: var PegLexer, input, filename: string, line = 1, col = 0) =
  1347. L.buf = input
  1348. L.bufpos = 0
  1349. L.lineNumber = line
  1350. L.colOffset = col
  1351. L.lineStart = 0
  1352. L.filename = filename
  1353. func getColumn(L: PegLexer): int {.inline.} =
  1354. result = abs(L.bufpos - L.lineStart) + L.colOffset
  1355. func getLine(L: PegLexer): int {.inline.} =
  1356. result = L.lineNumber
  1357. func errorStr(L: PegLexer, msg: string, line = -1, col = -1): string =
  1358. var line = if line < 0: getLine(L) else: line
  1359. var col = if col < 0: getColumn(L) else: col
  1360. result = "$1($2, $3) Error: $4" % [L.filename, $line, $col, msg]
  1361. func getEscapedChar(c: var PegLexer, tok: var Token) =
  1362. inc(c.bufpos)
  1363. if c.bufpos >= len(c.buf):
  1364. tok.kind = tkInvalid
  1365. return
  1366. case c.buf[c.bufpos]
  1367. of 'r', 'R', 'c', 'C':
  1368. add(tok.literal, '\c')
  1369. inc(c.bufpos)
  1370. of 'l', 'L':
  1371. add(tok.literal, '\L')
  1372. inc(c.bufpos)
  1373. of 'f', 'F':
  1374. add(tok.literal, '\f')
  1375. inc(c.bufpos)
  1376. of 'e', 'E':
  1377. add(tok.literal, '\e')
  1378. inc(c.bufpos)
  1379. of 'a', 'A':
  1380. add(tok.literal, '\a')
  1381. inc(c.bufpos)
  1382. of 'b', 'B':
  1383. add(tok.literal, '\b')
  1384. inc(c.bufpos)
  1385. of 'v', 'V':
  1386. add(tok.literal, '\v')
  1387. inc(c.bufpos)
  1388. of 't', 'T':
  1389. add(tok.literal, '\t')
  1390. inc(c.bufpos)
  1391. of 'x', 'X':
  1392. inc(c.bufpos)
  1393. if c.bufpos >= len(c.buf):
  1394. tok.kind = tkInvalid
  1395. return
  1396. var xi = 0
  1397. if handleHexChar(c.buf[c.bufpos], xi):
  1398. inc(c.bufpos)
  1399. if handleHexChar(c.buf[c.bufpos], xi):
  1400. inc(c.bufpos)
  1401. if xi == 0: tok.kind = tkInvalid
  1402. else: add(tok.literal, chr(xi))
  1403. of '0'..'9':
  1404. var val = ord(c.buf[c.bufpos]) - ord('0')
  1405. inc(c.bufpos)
  1406. var i = 1
  1407. while (c.bufpos < len(c.buf)) and (i <= 3) and (c.buf[c.bufpos] in {'0'..'9'}):
  1408. val = val * 10 + ord(c.buf[c.bufpos]) - ord('0')
  1409. inc(c.bufpos)
  1410. inc(i)
  1411. if val > 0 and val <= 255: add(tok.literal, chr(val))
  1412. else: tok.kind = tkInvalid
  1413. of '\0'..'\31':
  1414. tok.kind = tkInvalid
  1415. elif c.buf[c.bufpos] in strutils.Letters:
  1416. tok.kind = tkInvalid
  1417. else:
  1418. add(tok.literal, c.buf[c.bufpos])
  1419. inc(c.bufpos)
  1420. func skip(c: var PegLexer) =
  1421. var pos = c.bufpos
  1422. while pos < c.buf.len:
  1423. case c.buf[pos]
  1424. of ' ', '\t':
  1425. inc(pos)
  1426. of '#':
  1427. while (pos < c.buf.len) and
  1428. not (c.buf[pos] in {'\c', '\L', '\0'}): inc(pos)
  1429. of '\c':
  1430. pos = handleCR(c, pos)
  1431. of '\L':
  1432. pos = handleLF(c, pos)
  1433. else:
  1434. break # EndOfFile also leaves the loop
  1435. c.bufpos = pos
  1436. func getString(c: var PegLexer, tok: var Token) =
  1437. tok.kind = tkStringLit
  1438. var pos = c.bufpos + 1
  1439. var quote = c.buf[pos-1]
  1440. while pos < c.buf.len:
  1441. case c.buf[pos]
  1442. of '\\':
  1443. c.bufpos = pos
  1444. getEscapedChar(c, tok)
  1445. pos = c.bufpos
  1446. of '\c', '\L', '\0':
  1447. tok.kind = tkInvalid
  1448. break
  1449. elif c.buf[pos] == quote:
  1450. inc(pos)
  1451. break
  1452. else:
  1453. add(tok.literal, c.buf[pos])
  1454. inc(pos)
  1455. c.bufpos = pos
  1456. func getDollar(c: var PegLexer, tok: var Token) =
  1457. var pos = c.bufpos + 1
  1458. var neg = false
  1459. if pos < c.buf.len and c.buf[pos] == '^':
  1460. neg = true
  1461. inc(pos)
  1462. if pos < c.buf.len and c.buf[pos] in {'0'..'9'}:
  1463. tok.kind = tkBackref
  1464. tok.index = 0
  1465. while pos < c.buf.len and c.buf[pos] in {'0'..'9'}:
  1466. tok.index = tok.index * 10 + ord(c.buf[pos]) - ord('0')
  1467. inc(pos)
  1468. if neg:
  1469. tok.index = -tok.index
  1470. else:
  1471. if neg:
  1472. dec(pos)
  1473. tok.kind = tkDollar
  1474. c.bufpos = pos
  1475. func getCharSet(c: var PegLexer, tok: var Token) =
  1476. tok.kind = tkCharSet
  1477. tok.charset = {}
  1478. var pos = c.bufpos + 1
  1479. var caret = false
  1480. if pos < c.buf.len:
  1481. if c.buf[pos] == '^':
  1482. inc(pos)
  1483. caret = true
  1484. while pos < c.buf.len:
  1485. var ch: char
  1486. case c.buf[pos]
  1487. of ']':
  1488. if pos < c.buf.len: inc(pos)
  1489. break
  1490. of '\\':
  1491. c.bufpos = pos
  1492. getEscapedChar(c, tok)
  1493. pos = c.bufpos
  1494. ch = tok.literal[tok.literal.len-1]
  1495. of '\C', '\L', '\0':
  1496. tok.kind = tkInvalid
  1497. break
  1498. else:
  1499. ch = c.buf[pos]
  1500. inc(pos)
  1501. incl(tok.charset, ch)
  1502. if c.buf[pos] == '-':
  1503. if pos+1 < c.buf.len and c.buf[pos+1] == ']':
  1504. incl(tok.charset, '-')
  1505. inc(pos)
  1506. else:
  1507. if pos+1 < c.buf.len:
  1508. inc(pos)
  1509. else:
  1510. break
  1511. var ch2: char
  1512. case c.buf[pos]
  1513. of '\\':
  1514. c.bufpos = pos
  1515. getEscapedChar(c, tok)
  1516. pos = c.bufpos
  1517. ch2 = tok.literal[tok.literal.len-1]
  1518. of '\C', '\L', '\0':
  1519. tok.kind = tkInvalid
  1520. break
  1521. else:
  1522. if pos+1 < c.buf.len:
  1523. ch2 = c.buf[pos]
  1524. inc(pos)
  1525. else:
  1526. break
  1527. for i in ord(ch)+1 .. ord(ch2):
  1528. incl(tok.charset, chr(i))
  1529. c.bufpos = pos
  1530. if caret: tok.charset = {'\1'..'\xFF'} - tok.charset
  1531. func getSymbol(c: var PegLexer, tok: var Token) =
  1532. var pos = c.bufpos
  1533. while pos < c.buf.len:
  1534. add(tok.literal, c.buf[pos])
  1535. inc(pos)
  1536. if pos < c.buf.len and c.buf[pos] notin strutils.IdentChars: break
  1537. c.bufpos = pos
  1538. tok.kind = tkIdentifier
  1539. func getBuiltin(c: var PegLexer, tok: var Token) =
  1540. if c.bufpos+1 < c.buf.len and c.buf[c.bufpos+1] in strutils.Letters:
  1541. inc(c.bufpos)
  1542. getSymbol(c, tok)
  1543. tok.kind = tkBuiltin
  1544. else:
  1545. tok.kind = tkEscaped
  1546. getEscapedChar(c, tok) # may set tok.kind to tkInvalid
  1547. func getTok(c: var PegLexer, tok: var Token) =
  1548. tok.kind = tkInvalid
  1549. tok.modifier = modNone
  1550. setLen(tok.literal, 0)
  1551. skip(c)
  1552. if c.bufpos >= c.buf.len:
  1553. tok.kind = tkEof
  1554. tok.literal = "[EOF]"
  1555. add(tok.literal, '\0')
  1556. inc(c.bufpos)
  1557. return
  1558. case c.buf[c.bufpos]
  1559. of '{':
  1560. inc(c.bufpos)
  1561. if c.buf[c.bufpos] == '@' and c.bufpos+2 < c.buf.len and
  1562. c.buf[c.bufpos+1] == '}':
  1563. tok.kind = tkCurlyAt
  1564. inc(c.bufpos, 2)
  1565. add(tok.literal, "{@}")
  1566. elif c.buf[c.bufpos] == '}' and c.bufpos < c.buf.len:
  1567. tok.kind = tkEmptyCurl
  1568. inc(c.bufpos)
  1569. add(tok.literal, "{}")
  1570. else:
  1571. tok.kind = tkCurlyLe
  1572. add(tok.literal, '{')
  1573. of '}':
  1574. tok.kind = tkCurlyRi
  1575. inc(c.bufpos)
  1576. add(tok.literal, '}')
  1577. of '[':
  1578. getCharSet(c, tok)
  1579. of '(':
  1580. tok.kind = tkParLe
  1581. inc(c.bufpos)
  1582. add(tok.literal, '(')
  1583. of ')':
  1584. tok.kind = tkParRi
  1585. inc(c.bufpos)
  1586. add(tok.literal, ')')
  1587. of '.':
  1588. tok.kind = tkAny
  1589. inc(c.bufpos)
  1590. add(tok.literal, '.')
  1591. of '_':
  1592. tok.kind = tkAnyRune
  1593. inc(c.bufpos)
  1594. add(tok.literal, '_')
  1595. of '\\':
  1596. getBuiltin(c, tok)
  1597. of '\'', '"': getString(c, tok)
  1598. of '$': getDollar(c, tok)
  1599. of 'a'..'z', 'A'..'Z', '\128'..'\255':
  1600. getSymbol(c, tok)
  1601. if c.bufpos >= c.buf.len:
  1602. return
  1603. if c.buf[c.bufpos] in {'\'', '"'} or
  1604. c.buf[c.bufpos] == '$' and c.bufpos+1 < c.buf.len and
  1605. c.buf[c.bufpos+1] in {'^', '0'..'9'}:
  1606. case tok.literal
  1607. of "i": tok.modifier = modIgnoreCase
  1608. of "y": tok.modifier = modIgnoreStyle
  1609. of "v": tok.modifier = modVerbatim
  1610. else: discard
  1611. setLen(tok.literal, 0)
  1612. if c.buf[c.bufpos] == '$':
  1613. getDollar(c, tok)
  1614. else:
  1615. getString(c, tok)
  1616. if tok.modifier == modNone: tok.kind = tkInvalid
  1617. of '+':
  1618. tok.kind = tkPlus
  1619. inc(c.bufpos)
  1620. add(tok.literal, '+')
  1621. of '*':
  1622. tok.kind = tkStar
  1623. inc(c.bufpos)
  1624. add(tok.literal, '+')
  1625. of '<':
  1626. if c.bufpos+2 < c.buf.len and c.buf[c.bufpos+1] == '-':
  1627. inc(c.bufpos, 2)
  1628. tok.kind = tkArrow
  1629. add(tok.literal, "<-")
  1630. else:
  1631. add(tok.literal, '<')
  1632. of '/':
  1633. tok.kind = tkBar
  1634. inc(c.bufpos)
  1635. add(tok.literal, '/')
  1636. of '?':
  1637. tok.kind = tkOption
  1638. inc(c.bufpos)
  1639. add(tok.literal, '?')
  1640. of '!':
  1641. tok.kind = tkNot
  1642. inc(c.bufpos)
  1643. add(tok.literal, '!')
  1644. of '&':
  1645. tok.kind = tkAmp
  1646. inc(c.bufpos)
  1647. add(tok.literal, '!')
  1648. of '@':
  1649. tok.kind = tkAt
  1650. inc(c.bufpos)
  1651. add(tok.literal, '@')
  1652. if c.buf[c.bufpos] == '@':
  1653. tok.kind = tkCurlyAt
  1654. inc(c.bufpos)
  1655. add(tok.literal, '@')
  1656. of '^':
  1657. tok.kind = tkHat
  1658. inc(c.bufpos)
  1659. add(tok.literal, '^')
  1660. else:
  1661. if c.bufpos >= c.buf.len:
  1662. tok.kind = tkEof
  1663. tok.literal = "[EOF]"
  1664. add(tok.literal, c.buf[c.bufpos])
  1665. inc(c.bufpos)
  1666. func arrowIsNextTok(c: PegLexer): bool =
  1667. # the only look ahead we need
  1668. var pos = c.bufpos
  1669. while pos < c.buf.len and c.buf[pos] in {'\t', ' '}: inc(pos)
  1670. if pos+1 >= c.buf.len:
  1671. return
  1672. result = c.buf[pos] == '<' and c.buf[pos+1] == '-'
  1673. # ----------------------------- parser ----------------------------------------
  1674. type
  1675. EInvalidPeg* = object of ValueError ## raised if an invalid
  1676. ## PEG has been detected
  1677. PegParser = object of PegLexer ## the PEG parser object
  1678. tok: Token
  1679. nonterms: seq[NonTerminal]
  1680. modifier: Modifier
  1681. captures: int
  1682. identIsVerbatim: bool
  1683. skip: Peg
  1684. func pegError(p: PegParser, msg: string, line = -1, col = -1) =
  1685. var e = (ref EInvalidPeg)(msg: errorStr(p, msg, line, col))
  1686. raise e
  1687. func getTok(p: var PegParser) =
  1688. getTok(p, p.tok)
  1689. if p.tok.kind == tkInvalid: pegError(p, "'" & p.tok.literal & "' is invalid token")
  1690. func eat(p: var PegParser, kind: TokKind) =
  1691. if p.tok.kind == kind: getTok(p)
  1692. else: pegError(p, tokKindToStr[kind] & " expected")
  1693. func parseExpr(p: var PegParser): Peg {.gcsafe.}
  1694. func getNonTerminal(p: var PegParser, name: string): NonTerminal =
  1695. for i in 0..high(p.nonterms):
  1696. result = p.nonterms[i]
  1697. if cmpIgnoreStyle(result.name, name) == 0: return
  1698. # forward reference:
  1699. result = newNonTerminal(name, getLine(p), getColumn(p))
  1700. add(p.nonterms, result)
  1701. func modifiedTerm(s: string, m: Modifier): Peg =
  1702. case m
  1703. of modNone, modVerbatim: result = term(s)
  1704. of modIgnoreCase: result = termIgnoreCase(s)
  1705. of modIgnoreStyle: result = termIgnoreStyle(s)
  1706. func modifiedBackref(s: int, m: Modifier): Peg =
  1707. var
  1708. reverse = s < 0
  1709. index = if reverse: -s else: s
  1710. case m
  1711. of modNone, modVerbatim: result = backref(index, reverse)
  1712. of modIgnoreCase: result = backrefIgnoreCase(index, reverse)
  1713. of modIgnoreStyle: result = backrefIgnoreStyle(index, reverse)
  1714. func builtin(p: var PegParser): Peg =
  1715. # do not use "y", "skip" or "i" as these would be ambiguous
  1716. case p.tok.literal
  1717. of "n": result = newLine()
  1718. of "d": result = charSet({'0'..'9'})
  1719. of "D": result = charSet({'\1'..'\xff'} - {'0'..'9'})
  1720. of "s": result = charSet({' ', '\9'..'\13'})
  1721. of "S": result = charSet({'\1'..'\xff'} - {' ', '\9'..'\13'})
  1722. of "w": result = charSet({'a'..'z', 'A'..'Z', '_', '0'..'9'})
  1723. of "W": result = charSet({'\1'..'\xff'} - {'a'..'z', 'A'..'Z', '_', '0'..'9'})
  1724. of "a": result = charSet({'a'..'z', 'A'..'Z'})
  1725. of "A": result = charSet({'\1'..'\xff'} - {'a'..'z', 'A'..'Z'})
  1726. of "ident": result = pegs.ident
  1727. of "letter": result = unicodeLetter()
  1728. of "upper": result = unicodeUpper()
  1729. of "lower": result = unicodeLower()
  1730. of "title": result = unicodeTitle()
  1731. of "white": result = unicodeWhitespace()
  1732. else: pegError(p, "unknown built-in: " & p.tok.literal)
  1733. func token(terminal: Peg, p: PegParser): Peg =
  1734. if p.skip.kind == pkEmpty: result = terminal
  1735. else: result = sequence(p.skip, terminal)
  1736. func primary(p: var PegParser): Peg =
  1737. case p.tok.kind
  1738. of tkAmp:
  1739. getTok(p)
  1740. return &primary(p)
  1741. of tkNot:
  1742. getTok(p)
  1743. return !primary(p)
  1744. of tkAt:
  1745. getTok(p)
  1746. return !*primary(p)
  1747. of tkCurlyAt:
  1748. getTok(p)
  1749. return !*\primary(p).token(p)
  1750. else: discard
  1751. case p.tok.kind
  1752. of tkIdentifier:
  1753. if p.identIsVerbatim:
  1754. var m = p.tok.modifier
  1755. if m == modNone: m = p.modifier
  1756. result = modifiedTerm(p.tok.literal, m).token(p)
  1757. getTok(p)
  1758. elif not arrowIsNextTok(p):
  1759. var nt = getNonTerminal(p, p.tok.literal)
  1760. {.cast(noSideEffect).}:
  1761. incl(nt.flags, ntUsed)
  1762. result = nonterminal(nt).token(p)
  1763. getTok(p)
  1764. else:
  1765. pegError(p, "expression expected, but found: " & p.tok.literal)
  1766. of tkStringLit:
  1767. var m = p.tok.modifier
  1768. if m == modNone: m = p.modifier
  1769. result = modifiedTerm(p.tok.literal, m).token(p)
  1770. getTok(p)
  1771. of tkCharSet:
  1772. if '\0' in p.tok.charset:
  1773. pegError(p, "binary zero ('\\0') not allowed in character class")
  1774. result = charSet(p.tok.charset).token(p)
  1775. getTok(p)
  1776. of tkParLe:
  1777. getTok(p)
  1778. result = parseExpr(p)
  1779. eat(p, tkParRi)
  1780. of tkCurlyLe:
  1781. getTok(p)
  1782. result = capture(parseExpr(p)).token(p)
  1783. eat(p, tkCurlyRi)
  1784. inc(p.captures)
  1785. of tkEmptyCurl:
  1786. result = capture()
  1787. getTok(p)
  1788. of tkAny:
  1789. result = any().token(p)
  1790. getTok(p)
  1791. of tkAnyRune:
  1792. result = anyRune().token(p)
  1793. getTok(p)
  1794. of tkBuiltin:
  1795. result = builtin(p).token(p)
  1796. getTok(p)
  1797. of tkEscaped:
  1798. result = term(p.tok.literal[0]).token(p)
  1799. getTok(p)
  1800. of tkDollar:
  1801. result = endAnchor()
  1802. getTok(p)
  1803. of tkHat:
  1804. result = startAnchor()
  1805. getTok(p)
  1806. of tkBackref:
  1807. if abs(p.tok.index) > p.captures or p.tok.index == 0:
  1808. pegError(p, "invalid back reference index: " & $p.tok.index)
  1809. var m = p.tok.modifier
  1810. if m == modNone: m = p.modifier
  1811. result = modifiedBackref(p.tok.index, m).token(p)
  1812. getTok(p)
  1813. else:
  1814. pegError(p, "expression expected, but found: " & p.tok.literal)
  1815. getTok(p) # we must consume a token here to prevent endless loops!
  1816. while true:
  1817. case p.tok.kind
  1818. of tkOption:
  1819. result = ?result
  1820. getTok(p)
  1821. of tkStar:
  1822. result = *result
  1823. getTok(p)
  1824. of tkPlus:
  1825. result = +result
  1826. getTok(p)
  1827. else: break
  1828. func seqExpr(p: var PegParser): Peg =
  1829. result = primary(p)
  1830. while true:
  1831. case p.tok.kind
  1832. of tkAmp, tkNot, tkAt, tkStringLit, tkCharSet, tkParLe, tkCurlyLe,
  1833. tkAny, tkAnyRune, tkBuiltin, tkEscaped, tkDollar, tkBackref,
  1834. tkHat, tkCurlyAt, tkEmptyCurl:
  1835. result = sequence(result, primary(p))
  1836. of tkIdentifier:
  1837. if not arrowIsNextTok(p):
  1838. result = sequence(result, primary(p))
  1839. else: break
  1840. else: break
  1841. func parseExpr(p: var PegParser): Peg =
  1842. result = seqExpr(p)
  1843. while p.tok.kind == tkBar:
  1844. getTok(p)
  1845. result = result / seqExpr(p)
  1846. func parseRule(p: var PegParser): NonTerminal =
  1847. if p.tok.kind == tkIdentifier and arrowIsNextTok(p):
  1848. result = getNonTerminal(p, p.tok.literal)
  1849. if ntDeclared in result.flags:
  1850. pegError(p, "attempt to redefine: " & result.name)
  1851. {.cast(noSideEffect).}:
  1852. result.line = getLine(p)
  1853. result.col = getColumn(p)
  1854. getTok(p)
  1855. eat(p, tkArrow)
  1856. {.cast(noSideEffect).}:
  1857. result.rule = parseExpr(p)
  1858. incl(result.flags, ntDeclared) # NOW inlining may be attempted
  1859. else:
  1860. pegError(p, "rule expected, but found: " & p.tok.literal)
  1861. func rawParse(p: var PegParser): Peg =
  1862. ## parses a rule or a PEG expression
  1863. while p.tok.kind == tkBuiltin:
  1864. case p.tok.literal
  1865. of "i":
  1866. p.modifier = modIgnoreCase
  1867. getTok(p)
  1868. of "y":
  1869. p.modifier = modIgnoreStyle
  1870. getTok(p)
  1871. of "skip":
  1872. getTok(p)
  1873. p.skip = ?primary(p)
  1874. else: break
  1875. if p.tok.kind == tkIdentifier and arrowIsNextTok(p):
  1876. result = parseRule(p).rule
  1877. while p.tok.kind != tkEof:
  1878. discard parseRule(p)
  1879. else:
  1880. p.identIsVerbatim = true
  1881. result = parseExpr(p)
  1882. if p.tok.kind != tkEof:
  1883. pegError(p, "EOF expected, but found: " & p.tok.literal)
  1884. for i in 0..high(p.nonterms):
  1885. var nt = p.nonterms[i]
  1886. if ntDeclared notin nt.flags:
  1887. pegError(p, "undeclared identifier: " & nt.name, nt.line, nt.col)
  1888. elif ntUsed notin nt.flags and i > 0:
  1889. pegError(p, "unused rule: " & nt.name, nt.line, nt.col)
  1890. func parsePeg*(pattern: string, filename = "pattern", line = 1, col = 0): Peg =
  1891. ## constructs a Peg object from `pattern`. `filename`, `line`, `col` are
  1892. ## used for error messages, but they only provide start offsets. `parsePeg`
  1893. ## keeps track of line and column numbers within `pattern`.
  1894. var p: PegParser
  1895. init(PegLexer(p), pattern, filename, line, col)
  1896. p.tok.kind = tkInvalid
  1897. p.tok.modifier = modNone
  1898. p.tok.literal = ""
  1899. p.tok.charset = {}
  1900. p.nonterms = @[]
  1901. p.identIsVerbatim = false
  1902. getTok(p)
  1903. result = rawParse(p)
  1904. func peg*(pattern: string): Peg =
  1905. ## constructs a Peg object from the `pattern`. The short name has been
  1906. ## chosen to encourage its use as a raw string modifier:
  1907. ##
  1908. ## peg"{\ident} \s* '=' \s* {.*}"
  1909. result = parsePeg(pattern, "pattern")
  1910. func escapePeg*(s: string): string =
  1911. ## escapes `s` so that it is matched verbatim when used as a peg.
  1912. result = ""
  1913. var inQuote = false
  1914. for c in items(s):
  1915. case c
  1916. of '\0'..'\31', '\'', '"', '\\':
  1917. if inQuote:
  1918. result.add('\'')
  1919. inQuote = false
  1920. result.add("\\x")
  1921. result.add(toHex(ord(c), 2))
  1922. else:
  1923. if not inQuote:
  1924. result.add('\'')
  1925. inQuote = true
  1926. result.add(c)
  1927. if inQuote: result.add('\'')