Add a command :l for loading a file into scope

Example:

nix-repl> :l <nixpkgs>

nix-repl> lib.range 0 10
[ 0 1 2 3 4 5 6 7 8 9 10 ]

nix-repl> :l <nixos>

nix-repl> config.boot.kernelModules
[ "vboxdrv" "vboxnetadp" ... ]
This commit is contained in:
Eelco Dolstra 2013-09-02 18:18:27 +02:00
parent 3202206d1d
commit 0f6279d874

View file

@ -8,6 +8,7 @@
#include "eval.hh" #include "eval.hh"
#include "eval-inline.hh" #include "eval-inline.hh"
#include "store-api.hh" #include "store-api.hh"
#include "common-opts.hh"
using namespace std; using namespace std;
using namespace nix; using namespace nix;
@ -28,7 +29,8 @@ struct NixRepl
NixRepl(); NixRepl();
void mainLoop(); void mainLoop();
void processLine(string line); void processLine(string line);
void addVar(const Symbol & name, Value * v); void addAttrsToScope(Value & attrs);
void addVarToScope(const Symbol & name, Value * v);
Expr * parseString(string s); Expr * parseString(string s);
void evalString(string s, Value & v); void evalString(string s, Value & v);
}; };
@ -51,6 +53,15 @@ bool getLine(string & line)
} }
string removeWhitespace(string s)
{
s = chomp(s);
size_t n = s.find_first_not_of(" \n\r\t");
if (n != string::npos) s = string(s, n);
return s;
}
NixRepl::NixRepl() NixRepl::NixRepl()
: staticEnv(false, &state.staticBaseEnv) : staticEnv(false, &state.staticBaseEnv)
{ {
@ -72,12 +83,8 @@ void NixRepl::mainLoop()
string line; string line;
if (!getLine(line)) break; if (!getLine(line)) break;
/* Remove preceeding whitespace. */
size_t n = line.find_first_not_of(" \n\r\t");
if (n != string::npos) line = string(line, n);
try { try {
processLine(line); processLine(removeWhitespace(line));
} catch (Error & e) { } catch (Error & e) {
printMsg(lvlError, e.msg()); printMsg(lvlError, e.msg());
} }
@ -94,9 +101,17 @@ void NixRepl::processLine(string line)
if (string(line, 0, 2) == ":a") { if (string(line, 0, 2) == ":a") {
Value v; Value v;
evalString(string(line, 2), v); evalString(string(line, 2), v);
state.forceAttrs(v); addAttrsToScope(v);
foreach (Bindings::iterator, i, *v.attrs) }
addVar(i->name, i->value);
else if (string(line, 0, 2) == ":l") {
state.resetFileCache();
Path path = lookupFileArg(state, removeWhitespace(string(line, 2)));
Value v, v2;
state.evalFile(path, v);
Bindings bindings;
state.autoCallFunction(bindings, v, v2);
addAttrsToScope(v2);
} }
else if (string(line, 0, 2) == ":t") { else if (string(line, 0, 2) == ":t") {
@ -118,7 +133,15 @@ void NixRepl::processLine(string line)
} }
void NixRepl::addVar(const Symbol & name, Value * v) void NixRepl::addAttrsToScope(Value & attrs)
{
state.forceAttrs(attrs);
foreach (Bindings::iterator, i, *attrs.attrs)
addVarToScope(i->name, i->value);
}
void NixRepl::addVarToScope(const Symbol & name, Value * v)
{ {
staticEnv.vars[name] = displ; staticEnv.vars[name] = displ;
env->values[displ++] = v; env->values[displ++] = v;