summary refs log tree commit diff stats
path: root/lib/impure/nre/src/private/util.nim
diff options
context:
space:
mode:
Diffstat (limited to 'lib/impure/nre/src/private/util.nim')
-rw-r--r--lib/impure/nre/src/private/util.nim62
1 files changed, 62 insertions, 0 deletions
diff --git a/lib/impure/nre/src/private/util.nim b/lib/impure/nre/src/private/util.nim
new file mode 100644
index 000000000..00fd40fac
--- /dev/null
+++ b/lib/impure/nre/src/private/util.nim
@@ -0,0 +1,62 @@
+import tables
+
+proc fget*[K, V](self: Table[K, V], key: K): V =
+  if self.hasKey(key):
+    return self[key]
+  else:
+    raise newException(KeyError, "Key does not exist in table: " & $key)
+
+const Ident = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'}
+const StartIdent = Ident - {'0'..'9'}
+
+proc checkNil(arg: string): string =
+  if arg == nil:
+    raise newException(ValueError, "Cannot use nil capture")
+  else:
+    return arg
+
+template formatStr*(howExpr, namegetter, idgetter: expr): expr =
+  let how = howExpr
+  var val = newStringOfCap(how.len)
+  var i = 0
+  var lastNum = 1
+
+  while i < how.len:
+    if how[i] != '$':
+      val.add(how[i])
+      i += 1
+    else:
+      if how[i + 1] == '$':
+        val.add('$')
+        i += 2
+      elif how[i + 1] == '#':
+        var id {.inject.} = lastNum
+        val.add(checkNil(idgetter))
+        lastNum += 1
+        i += 2
+      elif how[i + 1] in {'0'..'9'}:
+        i += 1
+        var id {.inject.} = 0
+        while i < how.len and how[i] in {'0'..'9'}:
+          id += (id * 10) + (ord(how[i]) - ord('0'))
+          i += 1
+        val.add(checkNil(idgetter))
+        lastNum = id + 1
+      elif how[i + 1] in StartIdent:
+        i += 1
+        var name {.inject.} = ""
+        while i < how.len and how[i] in Ident:
+          name.add(how[i])
+          i += 1
+        val.add(checkNil(namegetter))
+      elif how[i + 1] == '{':
+        i += 2
+        var name {.inject.} = ""
+        while i < how.len and how[i] != '}':
+          name.add(how[i])
+          i += 1
+        i += 1
+        val.add(checkNil(namegetter))
+      else:
+        raise newException(Exception, "Syntax error in format string at " & $i)
+  val
'n205' href='#n205'>205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235