mirror of
https://github.com/NixOS/nix
synced 2025-06-28 17:51:15 +02:00
Add primop ‘scopedImport’
‘scopedImport’ works like ‘import’, except that it takes a set of attributes to be added to the lexical scope of the expression, essentially extending or overriding the builtin variables. For instance, the expression scopedImport { x = 1; } ./foo.nix where foo.nix contains ‘x’, will evaluate to 1. This has a few applications: * It allows getting rid of function argument specifications in package expressions. For instance, a package expression like: { stdenv, fetchurl, libfoo }: stdenv.mkDerivation { ... buildInputs = [ libfoo ]; } can now we written as just stdenv.mkDerivation { ... buildInputs = [ libfoo ]; } and imported in all-packages.nix as: bar = scopedImport pkgs ./bar.nix; So whereas we once had dependencies listed in three places (buildInputs, the function, and the call site), they now only need to appear in one place. * It allows overriding builtin functions. For instance, to trace all calls to ‘map’: let overrides = { map = f: xs: builtins.trace "map called!" (map f xs); # Ensure that our override gets propagated by calls to # import/scopedImport. import = fn: scopedImport overrides fn; scopedImport = attrs: fn: scopedImport (overrides // attrs) fn; # Also update ‘builtins’. builtins = builtins // overrides; }; in scopedImport overrides ./bla.nix * Similarly, it allows extending the set of builtin functions. For instance, during Nixpkgs/NixOS evaluation, the Nixpkgs library functions could be added to the default scope. There is a downside: calls to scopedImport are not memoized, unlike import. So importing a file multiple times leads to multiple parsings / evaluations. It would be possible to construct the AST only once, but that would require careful handling of variables/environments.
This commit is contained in:
parent
f0fdbd0897
commit
c273c15cb1
8 changed files with 50 additions and 3 deletions
|
@ -592,7 +592,13 @@ Path resolveExprPath(Path path)
|
|||
|
||||
Expr * EvalState::parseExprFromFile(const Path & path)
|
||||
{
|
||||
return parse(readFile(path).c_str(), path, dirOf(path), staticBaseEnv);
|
||||
return parseExprFromFile(path, staticBaseEnv);
|
||||
}
|
||||
|
||||
|
||||
Expr * EvalState::parseExprFromFile(const Path & path, StaticEnv & staticEnv)
|
||||
{
|
||||
return parse(readFile(path).c_str(), path, dirOf(path), staticEnv);
|
||||
}
|
||||
|
||||
|
||||
|
@ -608,7 +614,7 @@ Expr * EvalState::parseExprFromString(const string & s, const Path & basePath)
|
|||
}
|
||||
|
||||
|
||||
void EvalState::addToSearchPath(const string & s, bool warn)
|
||||
void EvalState::addToSearchPath(const string & s, bool warn)
|
||||
{
|
||||
size_t pos = s.find('=');
|
||||
string prefix;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue