about summary refs log tree commit diff
path: root/src/libexpr/primops.cc
diff options
context:
space:
mode:
authorEelco Dolstra <e.dolstra@tudelft.nl>2007-01-29T14·23+0000
committerEelco Dolstra <e.dolstra@tudelft.nl>2007-01-29T14·23+0000
commit7349bd0176b8a8ced3a017bb5d0e9ebb30570722 (patch)
tree0c550418b620ecd81d386089b59e8d0272c0c565 /src/libexpr/primops.cc
parent7dedbd896ade732ab2fe88a5fe88e069cb329fa5 (diff)
New primitives:
* `sub' to subtract two numbers.
* `stringLength' to get the length of a string.
* `substring' to get a substring of a string.  These should be enough
  to allow most string operations to be expressed.

Diffstat (limited to 'src/libexpr/primops.cc')
-rw-r--r--src/libexpr/primops.cc44
1 files changed, 43 insertions, 1 deletions
diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc
index b80e20692127..01806a6c9493 100644
--- a/src/libexpr/primops.cc
+++ b/src/libexpr/primops.cc
@@ -723,6 +723,14 @@ static Expr primAdd(EvalState & state, const ATermVector & args)
 }
 
 
+static Expr primSub(EvalState & state, const ATermVector & args)
+{
+    int i1 = evalInt(state, args[0]);
+    int i2 = evalInt(state, args[1]);
+    return makeInt(i1 - i2);
+}
+
+
 static Expr primLessThan(EvalState & state, const ATermVector & args)
 {
     int i1 = evalInt(state, args[0]);
@@ -779,6 +787,36 @@ static Expr primFilterSource(EvalState & state, const ATermVector & args)
 }
 
 
+/*************************************************************
+ * String manipulation
+ *************************************************************/
+
+
+/* `substr start len str' returns the substring of `str' starting at
+   character position `min(start, stringLength str)' inclusive and
+   ending at `min(start + len, stringLength str)'.  `start' must be
+   non-negative. */
+static Expr prim_substring(EvalState & state, const ATermVector & args)
+{
+    int start = evalInt(state, args[0]);
+    int len = evalInt(state, args[1]);
+    PathSet context;
+    string s = coerceToString(state, args[2], context);
+
+    if (start < 0) throw EvalError("negative start position in `substring'");
+
+    return makeStr(string(s, start, len), context);
+}
+
+
+static Expr prim_stringLength(EvalState & state, const ATermVector & args)
+{
+    PathSet context;
+    string s = coerceToString(state, args[0], context);
+    return makeInt(s.size());
+}
+
+
 void EvalState::addPrimOps()
 {
     addPrimOp("builtins", 0, primBuiltins);
@@ -813,10 +851,14 @@ void EvalState::addPrimOps()
     addPrimOp("removeAttrs", 2, primRemoveAttrs);
     addPrimOp("relativise", 2, primRelativise);
     addPrimOp("__add", 2, primAdd);
+    addPrimOp("__sub", 2, primSub);
     addPrimOp("__lessThan", 2, primLessThan);
     addPrimOp("__toFile", 2, primToFile);
     addPrimOp("__filterSource", 2, primFilterSource);
+
+    addPrimOp("__substring", 3, prim_substring);
+    addPrimOp("__stringLength", 1, prim_stringLength);
 }
 
- 
+
 }