summary refs log tree commit diff stats
path: root/lib/pure/pegs.nim
diff options
context:
space:
mode:
authorAndreas Rumpf <andreas@andreas-desktop>2010-03-01 19:37:33 +0100
committerAndreas Rumpf <andreas@andreas-desktop>2010-03-01 19:37:33 +0100
commit4ee65a08ddc7605b0bc1424642a46bace60a09e8 (patch)
treed9a6cd0e0746ebbd8541a42efae604f2062b3037 /lib/pure/pegs.nim
parentdf672f5b9a3439e2c6e92c90b7d1cdbc37ad197b (diff)
downloadNim-4ee65a08ddc7605b0bc1424642a46bace60a09e8.tar.gz
further enhancements for the GTK wrapper
Diffstat (limited to 'lib/pure/pegs.nim')
-rwxr-xr-xlib/pure/pegs.nim20
1 files changed, 20 insertions, 0 deletions
diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim
index 201f13111..e5a655b2e 100755
--- a/lib/pure/pegs.nim
+++ b/lib/pure/pegs.nim
@@ -1371,7 +1371,27 @@ proc peg*(pattern: string): TPeg =
   ##   peg"{\ident} \s* '=' \s* {.*}"
   result = parsePeg(pattern, "pattern")
 
+proc escapePeg*(s: string): string = 
+  ## escapes `s` so that it is matched verbatim when used as a peg.
+  result = ""
+  var inQuote = false
+  for c in items(s):  
+    case c
+    of '\0'..'\31', '\'', '"', '\\': 
+      if inQuote: 
+        result.add('\'')
+        inQuote = false
+      result.add("\\x")
+      result.add(toHex(ord(c), 2))
+    else:
+      if not inQuote: 
+        result.add('\'')
+        inQuote = true
+      result.add(c)
+  if inQuote: result.add('\'')
+
 when isMainModule:
+  assert escapePeg("abc''def'") == r"'abc'\x27\x27'def'\x27"
   assert match("(a b c)", peg"'(' @ ')'")
   assert match("W_HI_Le", peg"\y 'while'")
   assert(not match("W_HI_L", peg"\y 'while'"))