From 05d02f798f65bf18e8ca71f3d23bfdf9df63fb7c Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Thu, 24 Oct 2013 02:49:13 +0200 Subject: Add a typeOf primop We already have some primops for determining the type of a value, such as isString, but they're incomplete: for instance, there is no isPath. Rather than adding more isBla functions, the generic typeOf function returns a string representing the type of the argument (e.g. "int"). --- src/libexpr/primops.cc | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) (limited to 'src/libexpr/primops.cc') diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 30dd15ac0..badff1ca3 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -92,6 +92,30 @@ static void prim_import(EvalState & state, Value * * args, Value & v) } +/* Return a string representing the type of the expression. */ +static void prim_typeOf(EvalState & state, Value * * args, Value & v) +{ + state.forceValue(*args[0]); + string t; + switch (args[0]->type) { + case tInt: t = "int"; break; + case tBool: t = "bool"; break; + case tString: t = "string"; break; + case tPath: t = "path"; break; + case tNull: t = "null"; break; + case tAttrs: t = "attrs"; break; + case tList: t = "list"; break; + case tLambda: + case tPrimOp: + case tPrimOpApp: + t = "lambda"; + break; + default: abort(); + } + mkString(v, state.symbols.create(t)); +} + + /* Determine whether the argument is the null value. */ static void prim_isNull(EvalState & state, Value * * args, Value & v) { @@ -108,7 +132,7 @@ static void prim_isFunction(EvalState & state, Value * * args, Value & v) } -/* Determine whether the argument is an Int. */ +/* Determine whether the argument is an integer. */ static void prim_isInt(EvalState & state, Value * * args, Value & v) { state.forceValue(*args[0]); @@ -116,7 +140,7 @@ static void prim_isInt(EvalState & state, Value * * args, Value & v) } -/* Determine whether the argument is an String. */ +/* Determine whether the argument is a string. */ static void prim_isString(EvalState & state, Value * * args, Value & v) { state.forceValue(*args[0]); @@ -124,7 +148,7 @@ static void prim_isString(EvalState & state, Value * * args, Value & v) } -/* Determine whether the argument is an Bool. */ +/* Determine whether the argument is a Boolean. */ static void prim_isBool(EvalState & state, Value * * args, Value & v) { state.forceValue(*args[0]); @@ -1189,6 +1213,7 @@ void EvalState::createBaseEnv() // Miscellaneous addPrimOp("import", 1, prim_import); + addPrimOp("__typeOf", 1, prim_typeOf); addPrimOp("isNull", 1, prim_isNull); addPrimOp("__isFunction", 1, prim_isFunction); addPrimOp("__isString", 1, prim_isString); -- cgit v1.2.3