about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorEelco Dolstra <eelco.dolstra@logicblox.com>2015-07-17T17·24+0200
committerEelco Dolstra <eelco.dolstra@logicblox.com>2015-07-17T18·13+0200
commit6bd2c7bb386de16310fa5534275e6e638be60862 (patch)
tree0a12144dfb4e8d1b069bc09d583b522b5c158b28 /src
parent1511aa9f488ba0762c2da0bf8ab61b5fde47305d (diff)
OCD: foreach -> C++11 ranged for
Diffstat (limited to 'src')
-rw-r--r--src/download-via-ssh/download-via-ssh.cc8
-rw-r--r--src/libexpr/attr-path.cc5
-rw-r--r--src/libexpr/eval.cc90
-rw-r--r--src/libexpr/get-drvs.cc20
-rw-r--r--src/libexpr/names.cc4
-rw-r--r--src/libexpr/nixexpr.cc92
-rw-r--r--src/libexpr/parser.y20
-rw-r--r--src/libexpr/primops.cc95
-rw-r--r--src/libexpr/value-to-json.cc28
-rw-r--r--src/libexpr/value-to-xml.cc40
-rw-r--r--src/libstore/build.cc204
-rw-r--r--src/libstore/derivations.cc38
-rw-r--r--src/libstore/gc.cc43
-rw-r--r--src/libstore/globals.cc16
-rw-r--r--src/libstore/local-store.cc146
-rw-r--r--src/libstore/misc.cc86
-rw-r--r--src/libstore/optimise-store.cc14
-rw-r--r--src/libstore/pathlocks.cc27
-rw-r--r--src/libstore/references.cc20
-rw-r--r--src/libstore/remote-store.cc28
-rw-r--r--src/libstore/store-api.cc44
-rw-r--r--src/libutil/serialise.cc4
-rw-r--r--src/libutil/util.cc8
-rw-r--r--src/libutil/util.hh7
-rw-r--r--src/libutil/xml-writer.cc8
-rw-r--r--src/nix-daemon/nix-daemon.cc18
-rw-r--r--src/nix-env/nix-env.cc260
-rw-r--r--src/nix-env/user-env.cc44
-rw-r--r--src/nix-instantiate/nix-instantiate.cc16
-rw-r--r--src/nix-store/nix-store.cc290
30 files changed, 849 insertions, 874 deletions
diff --git a/src/download-via-ssh/download-via-ssh.cc b/src/download-via-ssh/download-via-ssh.cc
index f71cf56507..73f8860948 100644
--- a/src/download-via-ssh/download-via-ssh.cc
+++ b/src/download-via-ssh/download-via-ssh.cc
@@ -64,8 +64,8 @@ static void query(std::pair<FdSink, FdSource> & pipes)
             writeStrings(tokenized, pipes.first);
             pipes.first.flush();
             PathSet paths = readStrings<PathSet>(pipes.second);
-            foreach (PathSet::iterator, i, paths)
-                std::cout << *i << std::endl;
+            for (auto & i : paths)
+                std::cout << i << std::endl;
         } else if (cmd == "info") {
             writeInt(cmdQueryPathInfos, pipes.first);
             writeStrings(tokenized, pipes.first);
@@ -80,8 +80,8 @@ static void query(std::pair<FdSink, FdSource> & pipes)
                 std::cout << deriver << std::endl;
                 PathSet references = readStorePaths<PathSet>(pipes.second);
                 std::cout << references.size() << std::endl;
-                foreach (PathSet::iterator, i, references)
-                    std::cout << *i << std::endl;
+                for (auto & i : references)
+                    std::cout << i << std::endl;
                 std::cout << readLongLong(pipes.second) << std::endl;
                 std::cout << readLongLong(pipes.second) << std::endl;
             }
diff --git a/src/libexpr/attr-path.cc b/src/libexpr/attr-path.cc
index fdd61a5fd3..a4945111e0 100644
--- a/src/libexpr/attr-path.cc
+++ b/src/libexpr/attr-path.cc
@@ -42,11 +42,10 @@ Value * findAlongAttrPath(EvalState & state, const string & attrPath,
 
     Value * v = &vIn;
 
-    foreach (Strings::iterator, i, tokens) {
+    for (auto & attr : tokens) {
 
-        /* Is *i an index (integer) or a normal attribute name? */
+        /* Is i an index (integer) or a normal attribute name? */
         enum { apAttr, apIndex } apType = apAttr;
-        string attr = *i;
         unsigned int attrIndex;
         if (string2Int(attr, attrIndex)) apType = apIndex;
 
diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc
index 7b74d99b19..b1436b842d 100644
--- a/src/libexpr/eval.cc
+++ b/src/libexpr/eval.cc
@@ -98,8 +98,8 @@ static void printValue(std::ostream & str, std::set<const Value *> & active, con
         str << "{ ";
         typedef std::map<string, Value *> Sorted;
         Sorted sorted;
-        foreach (Bindings::iterator, i, *v.attrs)
-            sorted[i->name] = i->value;
+        for (auto & i : *v.attrs)
+            sorted[i.name] = i.value;
         for (auto & i : sorted) {
             str << i.first << " = ";
             printValue(str, active, *i.second);
@@ -442,8 +442,8 @@ void mkString(Value & v, const string & s, const PathSet & context)
         unsigned int n = 0;
         v.string.context = (const char * *)
             allocBytes((context.size() + 1) * sizeof(char *));
-        foreach (PathSet::const_iterator, i, context)
-            v.string.context[n++] = dupString(i->c_str());
+        for (auto & i : context)
+            v.string.context[n++] = dupString(i.c_str());
         v.string.context[n] = 0;
     }
 }
@@ -723,15 +723,15 @@ void ExprAttrs::eval(EvalState & state, Env & env, Value & v)
            environment, while the inherited attributes are evaluated
            in the original environment. */
         unsigned int displ = 0;
-        foreach (AttrDefs::iterator, i, attrs) {
+        for (auto & i : attrs) {
             Value * vAttr;
-            if (hasOverrides && !i->second.inherited) {
+            if (hasOverrides && !i.second.inherited) {
                 vAttr = state.allocValue();
-                mkThunk(*vAttr, env2, i->second.e);
+                mkThunk(*vAttr, env2, i.second.e);
             } else
-                vAttr = i->second.e->maybeThunk(state, i->second.inherited ? env : env2);
+                vAttr = i.second.e->maybeThunk(state, i.second.inherited ? env : env2);
             env2.values[displ++] = vAttr;
-            v.attrs->push_back(Attr(i->first, vAttr, &i->second.pos));
+            v.attrs->push_back(Attr(i.first, vAttr, &i.second.pos));
         }
 
         /* If the rec contains an attribute called `__overrides', then
@@ -762,13 +762,13 @@ void ExprAttrs::eval(EvalState & state, Env & env, Value & v)
     }
 
     else
-        foreach (AttrDefs::iterator, i, attrs)
-            v.attrs->push_back(Attr(i->first, i->second.e->maybeThunk(state, env), &i->second.pos));
+        for (auto & i : attrs)
+            v.attrs->push_back(Attr(i.first, i.second.e->maybeThunk(state, env), &i.second.pos));
 
     /* Dynamic attrs apply *after* rec and __overrides. */
-    foreach (DynamicAttrDefs::iterator, i, dynamicAttrs) {
+    for (auto & i : dynamicAttrs) {
         Value nameVal;
-        i->nameExpr->eval(state, *dynamicEnv, nameVal);
+        i.nameExpr->eval(state, *dynamicEnv, nameVal);
         state.forceValue(nameVal);
         if (nameVal.type == tNull)
             continue;
@@ -776,11 +776,11 @@ void ExprAttrs::eval(EvalState & state, Env & env, Value & v)
         Symbol nameSym = state.symbols.create(nameVal.string.s);
         Bindings::iterator j = v.attrs->find(nameSym);
         if (j != v.attrs->end())
-            throwEvalError("dynamic attribute ‘%1%’ at %2% already defined at %3%", nameSym, i->pos, *j->pos);
+            throwEvalError("dynamic attribute ‘%1%’ at %2% already defined at %3%", nameSym, i.pos, *j->pos);
 
-        i->valueExpr->setName(nameSym);
+        i.valueExpr->setName(nameSym);
         /* Keep sorted order so find can catch duplicates */
-        v.attrs->push_back(Attr(nameSym, i->valueExpr->maybeThunk(state, *dynamicEnv), &i->pos));
+        v.attrs->push_back(Attr(nameSym, i.valueExpr->maybeThunk(state, *dynamicEnv), &i.pos));
         v.attrs->sort(); // FIXME: inefficient
     }
 }
@@ -797,8 +797,8 @@ void ExprLet::eval(EvalState & state, Env & env, Value & v)
        while the inherited attributes are evaluated in the original
        environment. */
     unsigned int displ = 0;
-    foreach (ExprAttrs::AttrDefs::iterator, i, attrs->attrs)
-        env2.values[displ++] = i->second.e->maybeThunk(state, i->second.inherited ? env : env2);
+    for (auto & i : attrs->attrs)
+        env2.values[displ++] = i.second.e->maybeThunk(state, i.second.inherited ? env : env2);
 
     body->eval(state, env2, v);
 }
@@ -849,10 +849,10 @@ void ExprSelect::eval(EvalState & state, Env & env, Value & v)
 
     try {
 
-        foreach (AttrPath::const_iterator, i, attrPath) {
+        for (auto & i : attrPath) {
             nrLookups++;
             Bindings::iterator j;
-            Symbol name = getName(*i, state, env);
+            Symbol name = getName(i, state, env);
             if (def) {
                 state.forceValue(*vAttrs);
                 if (vAttrs->type != tAttrs ||
@@ -891,10 +891,10 @@ void ExprOpHasAttr::eval(EvalState & state, Env & env, Value & v)
 
     e->eval(state, env, vTmp);
 
-    foreach (AttrPath::const_iterator, i, attrPath) {
+    for (auto & i : attrPath) {
         state.forceValue(*vAttrs);
         Bindings::iterator j;
-        Symbol name = getName(*i, state, env);
+        Symbol name = getName(i, state, env);
         if (vAttrs->type != tAttrs ||
             (j = vAttrs->attrs->find(name)) == vAttrs->attrs->end())
         {
@@ -1007,12 +1007,12 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po
            there is no matching actual argument but the formal
            argument has a default, use the default. */
         unsigned int attrsUsed = 0;
-        foreach (Formals::Formals_::iterator, i, lambda.formals->formals) {
-            Bindings::iterator j = arg.attrs->find(i->name);
+        for (auto & i : lambda.formals->formals) {
+            Bindings::iterator j = arg.attrs->find(i.name);
             if (j == arg.attrs->end()) {
-                if (!i->def) throwTypeError("%1% called without required argument ‘%2%’, at %3%",
-                    lambda, i->name, pos);
-                env2.values[displ++] = i->def->maybeThunk(*this, env2);
+                if (!i.def) throwTypeError("%1% called without required argument ‘%2%’, at %3%",
+                    lambda, i.name, pos);
+                env2.values[displ++] = i.def->maybeThunk(*this, env2);
             } else {
                 attrsUsed++;
                 env2.values[displ++] = j->value;
@@ -1024,9 +1024,9 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po
         if (!lambda.formals->ellipsis && attrsUsed != arg.attrs->size()) {
             /* Nope, so show the first unexpected argument to the
                user. */
-            foreach (Bindings::iterator, i, *arg.attrs)
-                if (lambda.formals->argNames.find(i->name) == lambda.formals->argNames.end())
-                    throwTypeError("%1% called with unexpected argument ‘%2%’, at %3%", lambda, i->name, pos);
+            for (auto & i : *arg.attrs)
+                if (lambda.formals->argNames.find(i.name) == lambda.formals->argNames.end())
+                    throwTypeError("%1% called with unexpected argument ‘%2%’, at %3%", lambda, i.name, pos);
             abort(); // can't happen
         }
     }
@@ -1068,12 +1068,12 @@ void EvalState::autoCallFunction(Bindings & args, Value & fun, Value & res)
     Value * actualArgs = allocValue();
     mkAttrs(*actualArgs, fun.lambda.fun->formals->formals.size());
 
-    foreach (Formals::Formals_::iterator, i, fun.lambda.fun->formals->formals) {
-        Bindings::iterator j = args.find(i->name);
+    for (auto & i : fun.lambda.fun->formals->formals) {
+        Bindings::iterator j = args.find(i.name);
         if (j != args.end())
             actualArgs->attrs->push_back(*j);
-        else if (!i->def)
-            throwTypeError("cannot auto-call a function that has an argument without a default value (‘%1%’)", i->name);
+        else if (!i.def)
+            throwTypeError("cannot auto-call a function that has an argument without a default value (‘%1%’)", i.name);
     }
 
     actualArgs->attrs->sort();
@@ -1229,9 +1229,9 @@ void ExprConcatStrings::eval(EvalState & state, Env & env, Value & v)
     bool first = !forceString;
     ValueType firstType = tString;
 
-    foreach (vector<Expr *>::iterator, i, *es) {
+    for (auto & i : *es) {
         Value vTmp;
-        (*i)->eval(state, env, vTmp);
+        i->eval(state, env, vTmp);
 
         /* If the first element is a path, then the result will also
            be a path, we don't copy anything (yet - that's done later,
@@ -1583,25 +1583,25 @@ void EvalState::printStats()
         printMsg(v, format("calls to %1% primops:") % primOpCalls.size());
         typedef std::multimap<unsigned int, Symbol> PrimOpCalls_;
         PrimOpCalls_ primOpCalls_;
-        foreach (PrimOpCalls::iterator, i, primOpCalls)
-            primOpCalls_.insert(std::pair<unsigned int, Symbol>(i->second, i->first));
-        foreach_reverse (PrimOpCalls_::reverse_iterator, i, primOpCalls_)
+        for (auto & i : primOpCalls)
+            primOpCalls_.insert(std::pair<unsigned int, Symbol>(i.second, i.first));
+        for (auto i = primOpCalls_.rbegin(); i != primOpCalls_.rend(); ++i)
             printMsg(v, format("%1$10d %2%") % i->first % i->second);
 
         printMsg(v, format("calls to %1% functions:") % functionCalls.size());
         typedef std::multimap<unsigned int, ExprLambda *> FunctionCalls_;
         FunctionCalls_ functionCalls_;
-        foreach (FunctionCalls::iterator, i, functionCalls)
-            functionCalls_.insert(std::pair<unsigned int, ExprLambda *>(i->second, i->first));
-        foreach_reverse (FunctionCalls_::reverse_iterator, i, functionCalls_)
+        for (auto & i : functionCalls)
+            functionCalls_.insert(std::pair<unsigned int, ExprLambda *>(i.second, i.first));
+        for (auto i = functionCalls_.rbegin(); i != functionCalls_.rend(); ++i)
             printMsg(v, format("%1$10d %2%") % i->first % i->second->showNamePos());
 
         printMsg(v, format("evaluations of %1% attributes:") % attrSelects.size());
         typedef std::multimap<unsigned int, Pos> AttrSelects_;
         AttrSelects_ attrSelects_;
-        foreach (AttrSelects::iterator, i, attrSelects)
-            attrSelects_.insert(std::pair<unsigned int, Pos>(i->second, i->first));
-        foreach_reverse (AttrSelects_::reverse_iterator, i, attrSelects_)
+        for (auto & i : attrSelects)
+            attrSelects_.insert(std::pair<unsigned int, Pos>(i.second, i.first));
+        for (auto i = attrSelects_.rbegin(); i != attrSelects_.rend(); ++i)
             printMsg(v, format("%1$10d %2%") % i->first % i->second);
 
     }
diff --git a/src/libexpr/get-drvs.cc b/src/libexpr/get-drvs.cc
index 1c9fa02a36..b7c3b0d33b 100644
--- a/src/libexpr/get-drvs.cc
+++ b/src/libexpr/get-drvs.cc
@@ -85,8 +85,8 @@ StringSet DrvInfo::queryMetaNames()
 {
     StringSet res;
     if (!getMeta()) return res;
-    foreach (Bindings::iterator, i, *meta)
-        res.insert(i->name);
+    for (auto & i : *meta)
+        res.insert(i.name);
     return res;
 }
 
@@ -102,8 +102,8 @@ bool DrvInfo::checkMeta(Value & v)
     else if (v.type == tAttrs) {
         Bindings::iterator i = v.attrs->find(state->sOutPath);
         if (i != v.attrs->end()) return false;
-        foreach (Bindings::iterator, i, *v.attrs)
-            if (!checkMeta(*i->value)) return false;
+        for (auto & i : *v.attrs)
+            if (!checkMeta(*i.value)) return false;
         return true;
     }
     else return v.type == tInt || v.type == tBool || v.type == tString;
@@ -255,13 +255,13 @@ static void getDerivations(EvalState & state, Value & vIn,
            precedence). */
         typedef std::map<string, Symbol> SortedSymbols;
         SortedSymbols attrs;
-        foreach (Bindings::iterator, i, *v.attrs)
-            attrs.insert(std::pair<string, Symbol>(i->name, i->name));
+        for (auto & i : *v.attrs)
+            attrs.insert(std::pair<string, Symbol>(i.name, i.name));
 
-        foreach (SortedSymbols::iterator, i, attrs) {
-            startNest(nest, lvlDebug, format("evaluating attribute ‘%1%’") % i->first);
-            string pathPrefix2 = addToPath(pathPrefix, i->first);
-            Value & v2(*v.attrs->find(i->second)->value);
+        for (auto & i : attrs) {
+            startNest(nest, lvlDebug, format("evaluating attribute ‘%1%’") % i.first);
+            string pathPrefix2 = addToPath(pathPrefix, i.first);
+            Value & v2(*v.attrs->find(i.second)->value);
             if (combineChannels)
                 getDerivations(state, v2, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
             else if (getDerivation(state, v2, pathPrefix2, drvs, done, ignoreAssertionFailures)) {
diff --git a/src/libexpr/names.cc b/src/libexpr/names.cc
index cda5aa1952..7bca9b6550 100644
--- a/src/libexpr/names.cc
+++ b/src/libexpr/names.cc
@@ -98,8 +98,8 @@ int compareVersions(const string & v1, const string & v2)
 DrvNames drvNamesFromArgs(const Strings & opArgs)
 {
     DrvNames result;
-    foreach (Strings::const_iterator, i, opArgs)
-        result.push_back(DrvName(*i));
+    for (auto & i : opArgs)
+        result.push_back(DrvName(i));
     return result;
 }
 
diff --git a/src/libexpr/nixexpr.cc b/src/libexpr/nixexpr.cc
index 43f3161f8b..35db52a13a 100644
--- a/src/libexpr/nixexpr.cc
+++ b/src/libexpr/nixexpr.cc
@@ -97,21 +97,21 @@ void ExprAttrs::show(std::ostream & str)
 {
     if (recursive) str << "rec ";
     str << "{ ";
-    foreach (AttrDefs::iterator, i, attrs)
-        if (i->second.inherited)
-            str << "inherit " << i->first << " " << "; ";
+    for (auto & i : attrs)
+        if (i.second.inherited)
+            str << "inherit " << i.first << " " << "; ";
         else
-            str << i->first << " = " << *i->second.e << "; ";
-    foreach (DynamicAttrDefs::iterator, i, dynamicAttrs)
-        str << "\"${" << *i->nameExpr << "}\" = " << *i->valueExpr << "; ";
+            str << i.first << " = " << *i.second.e << "; ";
+    for (auto & i : dynamicAttrs)
+        str << "\"${" << *i.nameExpr << "}\" = " << *i.valueExpr << "; ";
     str << "}";
 }
 
 void ExprList::show(std::ostream & str)
 {
     str << "[ ";
-    foreach (vector<Expr *>::iterator, i, elems)
-        str << "(" << **i << ") ";
+    for (auto & i : elems)
+        str << "(" << *i << ") ";
     str << "]";
 }
 
@@ -121,10 +121,10 @@ void ExprLambda::show(std::ostream & str)
     if (matchAttrs) {
         str << "{ ";
         bool first = true;
-        foreach (Formals::Formals_::iterator, i, formals->formals) {
+        for (auto & i : formals->formals) {
             if (first) first = false; else str << ", ";
-            str << i->name;
-            if (i->def) str << " ? " << *i->def;
+            str << i.name;
+            if (i.def) str << " ? " << *i.def;
         }
         if (formals->ellipsis) {
             if (!first) str << ", ";
@@ -140,12 +140,12 @@ void ExprLambda::show(std::ostream & str)
 void ExprLet::show(std::ostream & str)
 {
     str << "(let ";
-    foreach (ExprAttrs::AttrDefs::iterator, i, attrs->attrs)
-        if (i->second.inherited) {
-            str << "inherit " << i->first << "; ";
+    for (auto & i : attrs->attrs)
+        if (i.second.inherited) {
+            str << "inherit " << i.first << "; ";
         }
         else
-            str << i->first << " = " << *i->second.e << "; ";
+            str << i.first << " = " << *i.second.e << "; ";
     str << "in " << *body << ")";
 }
 
@@ -173,9 +173,9 @@ void ExprConcatStrings::show(std::ostream & str)
 {
     bool first = true;
     str << "(";
-    foreach (vector<Expr *>::iterator, i, *es) {
+    for (auto & i : *es) {
         if (first) first = false; else str << " + ";
-        str << **i;
+        str << *i;
     }
     str << ")";
 }
@@ -267,17 +267,17 @@ void ExprSelect::bindVars(const StaticEnv & env)
 {
     e->bindVars(env);
     if (def) def->bindVars(env);
-    foreach (AttrPath::iterator, i, attrPath)
-        if (!i->symbol.set())
-            i->expr->bindVars(env);
+    for (auto & i : attrPath)
+        if (!i.symbol.set())
+            i.expr->bindVars(env);
 }
 
 void ExprOpHasAttr::bindVars(const StaticEnv & env)
 {
     e->bindVars(env);
-    foreach (AttrPath::iterator, i, attrPath)
-        if (!i->symbol.set())
-            i->expr->bindVars(env);
+    for (auto & i : attrPath)
+        if (!i.symbol.set())
+            i.expr->bindVars(env);
 }
 
 void ExprAttrs::bindVars(const StaticEnv & env)
@@ -289,27 +289,27 @@ void ExprAttrs::bindVars(const StaticEnv & env)
         dynamicEnv = &newEnv;
 
         unsigned int displ = 0;
-        foreach (AttrDefs::iterator, i, attrs)
-            newEnv.vars[i->first] = i->second.displ = displ++;
+        for (auto & i : attrs)
+            newEnv.vars[i.first] = i.second.displ = displ++;
 
-        foreach (AttrDefs::iterator, i, attrs)
-            i->second.e->bindVars(i->second.inherited ? env : newEnv);
+        for (auto & i : attrs)
+            i.second.e->bindVars(i.second.inherited ? env : newEnv);
     }
 
     else
-        foreach (AttrDefs::iterator, i, attrs)
-            i->second.e->bindVars(env);
+        for (auto & i : attrs)
+            i.second.e->bindVars(env);
 
-    foreach (DynamicAttrDefs::iterator, i, dynamicAttrs) {
-        i->nameExpr->bindVars(*dynamicEnv);
-        i->valueExpr->bindVars(*dynamicEnv);
+    for (auto & i : dynamicAttrs) {
+        i.nameExpr->bindVars(*dynamicEnv);
+        i.valueExpr->bindVars(*dynamicEnv);
     }
 }
 
 void ExprList::bindVars(const StaticEnv & env)
 {
-    foreach (vector<Expr *>::iterator, i, elems)
-        (*i)->bindVars(env);
+    for (auto & i : elems)
+        i->bindVars(env);
 }
 
 void ExprLambda::bindVars(const StaticEnv & env)
@@ -321,11 +321,11 @@ void ExprLambda::bindVars(const StaticEnv & env)
     if (!arg.empty()) newEnv.vars[arg] = displ++;
 
     if (matchAttrs) {
-        foreach (Formals::Formals_::iterator, i, formals->formals)
-            newEnv.vars[i->name] = displ++;
+        for (auto & i : formals->formals)
+            newEnv.vars[i.name] = displ++;
 
-        foreach (Formals::Formals_::iterator, i, formals->formals)
-            if (i->def) i->def->bindVars(newEnv);
+        for (auto & i : formals->formals)
+            if (i.def) i.def->bindVars(newEnv);
     }
 
     body->bindVars(newEnv);
@@ -336,11 +336,11 @@ void ExprLet::bindVars(const StaticEnv & env)
     StaticEnv newEnv(false, &env);
 
     unsigned int displ = 0;
-    foreach (ExprAttrs::AttrDefs::iterator, i, attrs->attrs)
-        newEnv.vars[i->first] = i->second.displ = displ++;
+    for (auto & i : attrs->attrs)
+        newEnv.vars[i.first] = i.second.displ = displ++;
 
-    foreach (ExprAttrs::AttrDefs::iterator, i, attrs->attrs)
-        i->second.e->bindVars(i->second.inherited ? env : newEnv);
+    for (auto & i : attrs->attrs)
+        i.second.e->bindVars(i.second.inherited ? env : newEnv);
 
     body->bindVars(newEnv);
 }
@@ -384,8 +384,8 @@ void ExprOpNot::bindVars(const StaticEnv & env)
 
 void ExprConcatStrings::bindVars(const StaticEnv & env)
 {
-    foreach (vector<Expr *>::iterator, i, *es)
-        (*i)->bindVars(env);
+    for (auto & i : *es)
+        i->bindVars(env);
 }
 
 void ExprPos::bindVars(const StaticEnv & env)
@@ -419,8 +419,8 @@ string ExprLambda::showNamePos() const
 size_t SymbolTable::totalSize() const
 {
     size_t n = 0;
-    foreach (Symbols::const_iterator, i, symbols)
-        n += i->size();
+    for (auto & i : symbols)
+        n += i.size();
     return n;
 }
 
diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y
index 1f830b7e3c..d34882f361 100644
--- a/src/libexpr/parser.y
+++ b/src/libexpr/parser.y
@@ -136,8 +136,8 @@ static Expr * stripIndentation(const Pos & pos, SymbolTable & symbols, vector<Ex
     bool atStartOfLine = true; /* = seen only whitespace in the current line */
     unsigned int minIndent = 1000000;
     unsigned int curIndent = 0;
-    foreach (vector<Expr *>::iterator, i, es) {
-        ExprIndStr * e = dynamic_cast<ExprIndStr *>(*i);
+    for (auto & i : es) {
+        ExprIndStr * e = dynamic_cast<ExprIndStr *>(i);
         if (!e) {
             /* Anti-quotations end the current start-of-line whitespace. */
             if (atStartOfLine) {
@@ -419,20 +419,20 @@ binds
   : binds attrpath '=' expr ';' { $$ = $1; addAttr($$, *$2, $4, makeCurPos(@2, data)); }
   | binds INHERIT attrs ';'
     { $$ = $1;
-      foreach (AttrPath::iterator, i, *$3) {
-          if ($$->attrs.find(i->symbol) != $$->attrs.end())
-              dupAttr(i->symbol, makeCurPos(@3, data), $$->attrs[i->symbol].pos);
+      for (auto & i : *$3) {
+          if ($$->attrs.find(i.symbol) != $$->attrs.end())
+              dupAttr(i.symbol, makeCurPos(@3, data), $$->attrs[i.symbol].pos);
           Pos pos = makeCurPos(@3, data);
-          $$->attrs[i->symbol] = ExprAttrs::AttrDef(new ExprVar(CUR_POS, i->symbol), pos, true);
+          $$->attrs[i.symbol] = ExprAttrs::AttrDef(new ExprVar(CUR_POS, i.symbol), pos, true);
       }
     }
   | binds INHERIT '(' expr ')' attrs ';'
     { $$ = $1;
       /* !!! Should ensure sharing of the expression in $4. */
-      foreach (AttrPath::iterator, i, *$6) {
-          if ($$->attrs.find(i->symbol) != $$->attrs.end())
-              dupAttr(i->symbol, makeCurPos(@6, data), $$->attrs[i->symbol].pos);
-          $$->attrs[i->symbol] = ExprAttrs::AttrDef(new ExprSelect(CUR_POS, $4, i->symbol), makeCurPos(@6, data));
+      for (auto & i : *$6) {
+          if ($$->attrs.find(i.symbol) != $$->attrs.end())
+              dupAttr(i.symbol, makeCurPos(@6, data), $$->attrs[i.symbol].pos);
+          $$->attrs[i.symbol] = ExprAttrs::AttrDef(new ExprSelect(CUR_POS, $4, i.symbol), makeCurPos(@6, data));
       }
     }
   | { $$ = new ExprAttrs; }
diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc
index 355b81adf7..c36a68ce08 100644
--- a/src/libexpr/primops.cc
+++ b/src/libexpr/primops.cc
@@ -330,8 +330,8 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
     /* Create the result list. */
     state.mkList(v, res.size());
     unsigned int n = 0;
-    foreach (ValueList::iterator, i, res)
-        v.list.elems[n++] = *i;
+    for (auto & i : res)
+        v.list.elems[n++] = i;
 }
 
 
@@ -477,24 +477,24 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
     StringSet outputs;
     outputs.insert("out");
 
-    foreach (Bindings::iterator, i, *args[0]->attrs) {
-        if (i->name == state.sIgnoreNulls) continue;
-        string key = i->name;
+    for (auto & i : *args[0]->attrs) {
+        if (i.name == state.sIgnoreNulls) continue;
+        string key = i.name;
         startNest(nest, lvlVomit, format("processing attribute ‘%1%’") % key);
 
         try {
 
             if (ignoreNulls) {
-                state.forceValue(*i->value);
-                if (i->value->type == tNull) continue;
+                state.forceValue(*i.value);
+                if (i.value->type == tNull) continue;
             }
 
             /* The `args' attribute is special: it supplies the
                command-line arguments to the builder. */
             if (key == "args") {
-                state.forceList(*i->value, pos);
-                for (unsigned int n = 0; n < i->value->list.length; ++n) {
-                    string s = state.coerceToString(posDrvName, *i->value->list.elems[n], context, true);
+                state.forceList(*i.value, pos);
+                for (unsigned int n = 0; n < i.value->list.length; ++n) {
+                    string s = state.coerceToString(posDrvName, *i.value->list.elems[n], context, true);
                     drv.args.push_back(s);
                 }
             }
@@ -502,11 +502,11 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
             /* All other attributes are passed to the builder through
                the environment. */
             else {
-                string s = state.coerceToString(posDrvName, *i->value, context, true);
+                string s = state.coerceToString(posDrvName, *i.value, context, true);
                 drv.env[key] = s;
                 if (key == "builder") drv.builder = s;
-                else if (i->name == state.sSystem) drv.platform = s;
-                else if (i->name == state.sName) {
+                else if (i.name == state.sSystem) drv.platform = s;
+                else if (i.name == state.sName) {
                     drvName = s;
                     printMsg(lvlVomit, format("derivation name is ‘%1%’") % drvName);
                 }
@@ -520,17 +520,17 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
                 else if (key == "outputs") {
                     Strings tmp = tokenizeString<Strings>(s);
                     outputs.clear();
-                    foreach (Strings::iterator, j, tmp) {
-                        if (outputs.find(*j) != outputs.end())
-                            throw EvalError(format("duplicate derivation output ‘%1%’, at %2%") % *j % posDrvName);
-                        /* !!! Check whether *j is a valid attribute
+                    for (auto & j : tmp) {
+                        if (outputs.find(j) != outputs.end())
+                            throw EvalError(format("duplicate derivation output ‘%1%’, at %2%") % j % posDrvName);
+                        /* !!! Check whether j is a valid attribute
                            name. */
                         /* Derivations cannot be named ‘drv’, because
                            then we'd have an attribute ‘drvPath’ in
                            the resulting set. */
-                        if (*j == "drv")
+                        if (j == "drv")
                             throw EvalError(format("invalid derivation output name ‘drv’, at %1%") % posDrvName);
-                        outputs.insert(*j);
+                        outputs.insert(j);
                     }
                     if (outputs.empty())
                         throw EvalError(format("derivation cannot have an empty set of outputs, at %1%") % posDrvName);
@@ -547,8 +547,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
     /* Everything in the context of the strings in the derivation
        attributes should be added as dependencies of the resulting
        derivation. */
-    foreach (PathSet::iterator, i, context) {
-        Path path = *i;
+    for (auto & path : context) {
 
         /* Paths marked with `=' denote that the path of a derivation
            is explicitly passed to the builder.  Since that allows the
@@ -560,10 +559,10 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
         if (path.at(0) == '=') {
             /* !!! This doesn't work if readOnlyMode is set. */
             PathSet refs; computeFSClosure(*store, string(path, 1), refs);
-            foreach (PathSet::iterator, j, refs) {
-                drv.inputSrcs.insert(*j);
-                if (isDerivation(*j))
-                    drv.inputDrvs[*j] = store->queryDerivationOutputNames(*j);
+            for (auto & j : refs) {
+                drv.inputSrcs.insert(j);
+                if (isDerivation(j))
+                    drv.inputDrvs[j] = store->queryDerivationOutputNames(j);
             }
         }
 
@@ -622,20 +621,20 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
            are empty, and the corresponding environment variables have
            an empty value.  This ensures that changes in the set of
            output names do get reflected in the hash. */
-        foreach (StringSet::iterator, i, outputs) {
-            drv.env[*i] = "";
-            drv.outputs[*i] = DerivationOutput("", "", "");
+        for (auto & i : outputs) {
+            drv.env[i] = "";
+            drv.outputs[i] = DerivationOutput("", "", "");
         }
 
         /* Use the masked derivation expression to compute the output
            path. */
         Hash h = hashDerivationModulo(*store, drv);
 
-        foreach (DerivationOutputs::iterator, i, drv.outputs)
-            if (i->second.path == "") {
-                Path outPath = makeOutputPath(i->first, h, drvName);
-                drv.env[i->first] = outPath;
-                i->second.path = outPath;
+        for (auto & i : drv.outputs)
+            if (i.second.path == "") {
+                Path outPath = makeOutputPath(i.first, h, drvName);
+                drv.env[i.first] = outPath;
+                i.second.path = outPath;
             }
     }
 
@@ -652,9 +651,9 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
 
     state.mkAttrs(v, 1 + drv.outputs.size());
     mkString(*state.allocAttr(v, state.sDrvPath), drvPath, singleton<PathSet>("=" + drvPath));
-    foreach (DerivationOutputs::iterator, i, drv.outputs) {
-        mkString(*state.allocAttr(v, state.symbols.create(i->first)),
-            i->second.path, singleton<PathSet>("!" + i->first + "!" + drvPath));
+    for (auto & i : drv.outputs) {
+        mkString(*state.allocAttr(v, state.symbols.create(i.first)),
+            i.second.path, singleton<PathSet>("!" + i.first + "!" + drvPath));
     }
     v.attrs->sort();
 }
@@ -871,8 +870,7 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu
 
     PathSet refs;
 
-    foreach (PathSet::iterator, i, context) {
-        Path path = *i;
+    for (auto path : context) {
         if (path.at(0) == '=') path = string(path, 1);
         if (isDerivation(path))
             throw EvalError(format("in ‘toFile’: the file ‘%1%’ cannot refer to derivation outputs, at %2%") % name % pos);
@@ -1057,9 +1055,9 @@ static void prim_removeAttrs(EvalState & state, const Pos & pos, Value * * args,
        to sort v.attrs because it's a subset of an already sorted
        vector. */
     state.mkAttrs(v, args[0]->attrs->size());
-    foreach (Bindings::iterator, i, *args[0]->attrs) {
-        if (names.find(i->name) == names.end())
-            v.attrs->push_back(*i);
+    for (auto & i : *args[0]->attrs) {
+        if (names.find(i.name) == names.end())
+            v.attrs->push_back(i);
     }
 }
 
@@ -1111,8 +1109,8 @@ static void prim_intersectAttrs(EvalState & state, const Pos & pos, Value * * ar
 
     state.mkAttrs(v, std::min(args[0]->attrs->size(), args[1]->attrs->size()));
 
-    foreach (Bindings::iterator, i, *args[0]->attrs) {
-        Bindings::iterator j = args[1]->attrs->find(i->name);
+    for (auto & i : *args[0]->attrs) {
+        Bindings::iterator j = args[1]->attrs->find(i.name);
         if (j != args[1]->attrs->end())
             v.attrs->push_back(*j);
     }
@@ -1173,9 +1171,9 @@ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args
     }
 
     state.mkAttrs(v, args[0]->lambda.fun->formals->formals.size());
-    foreach (Formals::Formals_::iterator, i, args[0]->lambda.fun->formals->formals)
+    for (auto & i : args[0]->lambda.fun->formals->formals)
         // !!! should optimise booleans (allocate only once)
-        mkBool(*state.allocAttr(v, i->name), i->def);
+        mkBool(*state.allocAttr(v, i.name), i.def);
     v.attrs->sort();
 }
 
@@ -1407,11 +1405,8 @@ static void prim_unsafeDiscardOutputDependency(EvalState & state, const Pos & po
     string s = state.coerceToString(pos, *args[0], context);
 
     PathSet context2;
-    foreach (PathSet::iterator, i, context) {
-        Path p = *i;
-        if (p.at(0) == '=') p = "~" + string(p, 1);
-        context2.insert(p);
-    }
+    for (auto & p : context)
+        context2.insert(p.at(0) == '=' ? "~" + string(p, 1) : p);
 
     mkString(v, s, context2);
 }
diff --git a/src/libexpr/value-to-json.cc b/src/libexpr/value-to-json.cc
index cdb7134187..b08d824975 100644
--- a/src/libexpr/value-to-json.cc
+++ b/src/libexpr/value-to-json.cc
@@ -12,14 +12,14 @@ namespace nix {
 void escapeJSON(std::ostream & str, const string & s)
 {
     str << "\"";
-    foreach (string::const_iterator, i, s)
-        if (*i == '\"' || *i == '\\') str << "\\" << *i;
-        else if (*i == '\n') str << "\\n";
-        else if (*i == '\r') str << "\\r";
-        else if (*i == '\t') str << "\\t";
-        else if (*i >= 0 && *i < 32)
-            str << "\\u" << std::setfill('0') << std::setw(4) << std::hex << (uint16_t) *i << std::dec;
-        else str << *i;
+    for (auto & i : s)
+        if (i == '\"' || i == '\\') str << "\\" << i;
+        else if (i == '\n') str << "\\n";
+        else if (i == '\r') str << "\\r";
+        else if (i == '\t') str << "\\t";
+        else if (i >= 0 && i < 32)
+            str << "\\u" << std::setfill('0') << std::setw(4) << std::hex << (uint16_t) i << std::dec;
+        else str << i;
     str << "\"";
 }
 
@@ -59,11 +59,11 @@ void printValueAsJSON(EvalState & state, bool strict,
             if (i == v.attrs->end()) {
                 JSONObject json(str);
                 StringSet names;
-                foreach (Bindings::iterator, i, *v.attrs)
-                    names.insert(i->name);
-                foreach (StringSet::iterator, i, names) {
-                    Attr & a(*v.attrs->find(state.symbols.create(*i)));
-                    json.attr(*i);
+                for (auto & j : *v.attrs)
+                    names.insert(j.name);
+                for (auto & j : names) {
+                    Attr & a(*v.attrs->find(state.symbols.create(j)));
+                    json.attr(j);
                     printValueAsJSON(state, strict, *a.value, str, context);
                 }
             } else
@@ -80,7 +80,7 @@ void printValueAsJSON(EvalState & state, bool strict,
             break;
         }
 
-	case tExternal:
+        case tExternal:
             v.external->printValueAsJSON(state, strict, str, context);
             break;
 
diff --git a/src/libexpr/value-to-xml.cc b/src/libexpr/value-to-xml.cc
index bbbb7039bf..9cb04bad37 100644
--- a/src/libexpr/value-to-xml.cc
+++ b/src/libexpr/value-to-xml.cc
@@ -8,7 +8,7 @@
 
 namespace nix {
 
-    
+
 static XMLAttrs singletonAttrs(const string & name, const string & value)
 {
     XMLAttrs attrs;
@@ -33,17 +33,17 @@ static void showAttrs(EvalState & state, bool strict, bool location,
     Bindings & attrs, XMLWriter & doc, PathSet & context, PathSet & drvsSeen)
 {
     StringSet names;
-    
-    foreach (Bindings::iterator, i, attrs)
-        names.insert(i->name);
-    
-    foreach (StringSet::iterator, i, names) {
-        Attr & a(*attrs.find(state.symbols.create(*i)));
-        
+
+    for (auto & i : attrs)
+        names.insert(i.name);
+
+    for (auto & i : names) {
+        Attr & a(*attrs.find(state.symbols.create(i)));
+
         XMLAttrs xmlAttrs;
-        xmlAttrs["name"] = *i;
+        xmlAttrs["name"] = i;
         if (location && a.pos != &noPos) posToXML(xmlAttrs, *a.pos);
-        
+
         XMLOpenElement _(doc, "attr", xmlAttrs);
         printValueAsXML(state, strict, location,
             *a.value, doc, context, drvsSeen);
@@ -57,7 +57,7 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
     checkInterrupt();
 
     if (strict) state.forceValue(v);
-        
+
     switch (v.type) {
 
         case tInt:
@@ -85,7 +85,7 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
         case tAttrs:
             if (state.isDerivation(v)) {
                 XMLAttrs xmlAttrs;
-            
+
                 Bindings::iterator a = v.attrs->find(state.symbols.create("derivation"));
 
                 Path drvPath;
@@ -95,7 +95,7 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
                     if (a->value->type == tString)
                         xmlAttrs["drvPath"] = drvPath = a->value->string.s;
                 }
-        
+
                 a = v.attrs->find(state.sOutPath);
                 if (a != v.attrs->end()) {
                     if (strict) state.forceValue(*a->value);
@@ -116,7 +116,7 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
                 XMLOpenElement _(doc, "attrs");
                 showAttrs(state, strict, location, *v.attrs, doc, context, drvsSeen);
             }
-            
+
             break;
 
         case tList: {
@@ -130,17 +130,17 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
             XMLAttrs xmlAttrs;
             if (location) posToXML(xmlAttrs, v.lambda.fun->pos);
             XMLOpenElement _(doc, "function", xmlAttrs);
-            
+
             if (v.lambda.fun->matchAttrs) {
                 XMLAttrs attrs;
                 if (!v.lambda.fun->arg.empty()) attrs["name"] = v.lambda.fun->arg;
                 if (v.lambda.fun->formals->ellipsis) attrs["ellipsis"] = "1";
                 XMLOpenElement _(doc, "attrspat", attrs);
-                foreach (Formals::Formals_::iterator, i, v.lambda.fun->formals->formals)
-                    doc.writeEmptyElement("attr", singletonAttrs("name", i->name));
+                for (auto & i : v.lambda.fun->formals->formals)
+                    doc.writeEmptyElement("attr", singletonAttrs("name", i.name));
             } else
                 doc.writeEmptyElement("varpat", singletonAttrs("name", v.lambda.fun->arg));
-            
+
             break;
         }
 
@@ -166,9 +166,9 @@ void printValueAsXML(EvalState & state, bool strict, bool location,
 {
     XMLWriter doc(true, out);
     XMLOpenElement root(doc, "expr");
-    PathSet drvsSeen;    
+    PathSet drvsSeen;
     printValueAsXML(state, strict, location, v, doc, context, drvsSeen);
 }
 
- 
+
 }
diff --git a/src/libstore/build.cc b/src/libstore/build.cc
index 5e2e7d89a3..8f1d5b2c89 100644
--- a/src/libstore/build.cc
+++ b/src/libstore/build.cc
@@ -331,8 +331,8 @@ void addToWeakGoals(WeakGoals & goals, GoalPtr p)
 {
     // FIXME: necessary?
     // FIXME: O(n)
-    foreach (WeakGoals::iterator, i, goals)
-        if (i->lock() == p) return;
+    for (auto & i : goals)
+        if (i.lock() == p) return;
     goals.push_back(p);
 }
 
@@ -362,11 +362,10 @@ void Goal::waiteeDone(GoalPtr waitee, ExitCode result)
 
         /* If we failed and keepGoing is not set, we remove all
            remaining waitees. */
-        foreach (Goals::iterator, i, waitees) {
-            GoalPtr goal = *i;
+        for (auto & goal : waitees) {
             WeakGoals waiters2;
-            foreach (WeakGoals::iterator, j, goal->waiters)
-                if (j->lock() != shared_from_this()) waiters2.push_back(*j);
+            for (auto & j : goal->waiters)
+                if (j.lock() != shared_from_this()) waiters2.push_back(j);
             goal->waiters = waiters2;
         }
         waitees.clear();
@@ -382,8 +381,8 @@ void Goal::amDone(ExitCode result)
     assert(exitCode == ecBusy);
     assert(result == ecSuccess || result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure);
     exitCode = result;
-    foreach (WeakGoals::iterator, i, waiters) {
-        GoalPtr goal = i->lock();
+    for (auto & i : waiters) {
+        GoalPtr goal = i.lock();
         if (goal) goal->waiteeDone(shared_from_this(), result);
     }
     waiters.clear();
@@ -509,13 +508,13 @@ void UserLock::acquire()
 
     /* Find a user account that isn't currently in use for another
        build. */
-    foreach (Strings::iterator, i, users) {
-        debug(format("trying user ‘%1%’") % *i);
+    for (auto & i : users) {
+        debug(format("trying user ‘%1%’") % i);
 
-        struct passwd * pw = getpwnam(i->c_str());
+        struct passwd * pw = getpwnam(i.c_str());
         if (!pw)
             throw Error(format("the user ‘%1%’ in the group ‘%2%’ does not exist")
-                % *i % settings.buildUsersGroup);
+                % i % settings.buildUsersGroup);
 
         createDirs(settings.nixStateDir + "/userpool");
 
@@ -533,7 +532,7 @@ void UserLock::acquire()
         if (lockFile(fd, ltWrite, false)) {
             fdUserLock = fd.borrow();
             lockedPaths.insert(fnUserLock);
-            user = *i;
+            user = i;
             uid = pw->pw_uid;
 
             /* Sanity check... */
@@ -669,12 +668,12 @@ typedef map<string, string> HashRewrites;
 
 string rewriteHashes(string s, const HashRewrites & rewrites)
 {
-    foreach (HashRewrites::const_iterator, i, rewrites) {
-        assert(i->first.size() == i->second.size());
+    for (auto & i : rewrites) {
+        assert(i.first.size() == i.second.size());
         size_t j = 0;
-        while ((j = s.find(i->first, j)) != string::npos) {
+        while ((j = s.find(i.first, j)) != string::npos) {
             debug(format("rewriting @ %1%") % j);
-            s.replace(j, i->second.size(), i->second);
+            s.replace(j, i.second.size(), i.second);
         }
     }
     return s;
@@ -962,9 +961,9 @@ void DerivationGoal::addWantedOutputs(const StringSet & outputs)
         wantedOutputs.clear();
         needRestart = true;
     } else
-        foreach (StringSet::const_iterator, i, outputs)
-            if (wantedOutputs.find(*i) == wantedOutputs.end()) {
-                wantedOutputs.insert(*i);
+        for (auto & i : outputs)
+            if (wantedOutputs.find(i) == wantedOutputs.end()) {
+                wantedOutputs.insert(i);
                 needRestart = true;
             }
 }
@@ -1307,7 +1306,7 @@ void DerivationGoal::tryToBuild()
 
     missingPaths = outputPaths(*drv);
     if (buildMode != bmCheck)
-        foreach (PathSet::iterator, i, validPaths) missingPaths.erase(*i);
+        for (auto & i : validPaths) missingPaths.erase(i);
 
     /* If any of the outputs already exist but are not valid, delete
        them. */
@@ -1469,9 +1468,9 @@ void DerivationGoal::buildDone()
             /* Move paths out of the chroot for easier debugging of
                build failures. */
             if (useChroot && buildMode == bmNormal)
-                foreach (PathSet::iterator, i, missingPaths)
-                    if (pathExists(chrootRootDir + *i))
-                        rename((chrootRootDir + *i).c_str(), i->c_str());
+                for (auto & i : missingPaths)
+                    if (pathExists(chrootRootDir + i))
+                        rename((chrootRootDir + i).c_str(), i.c_str());
 
             if (diskFull)
                 printMsg(lvlError, "note: build failure may have been caused by lack of free disk space");
@@ -1490,8 +1489,8 @@ void DerivationGoal::buildDone()
         }
 
         /* Delete unused redirected outputs (when doing hash rewriting). */
-        foreach (RedirectedOutputs::iterator, i, redirectedOutputs)
-            if (pathExists(i->second)) deletePath(i->second);
+        for (auto & i : redirectedOutputs)
+            if (pathExists(i.second)) deletePath(i.second);
 
         /* Delete the chroot (if we were using one). */
         autoDelChroot.reset(); /* this runs the destructor */
@@ -1566,7 +1565,7 @@ HookReply DerivationGoal::tryBuildHook()
        required from the build machine.  (The hook could parse the
        drv file itself, but this is easier.) */
     Strings features = tokenizeString<Strings>(get(drv->env, "requiredSystemFeatures"));
-    foreach (Strings::iterator, i, features) checkStoreName(*i); /* !!! abuse */
+    for (auto & i : features) checkStoreName(i); /* !!! abuse */
 
     /* Send the request to the hook. */
     writeLine(worker.hook->toHook.writeSide, (format("%1% %2% %3% %4%")
@@ -1608,13 +1607,13 @@ HookReply DerivationGoal::tryBuildHook()
     computeFSClosure(worker.store, drvPath, allInputs);
 
     string s;
-    foreach (PathSet::iterator, i, allInputs) { s += *i; s += ' '; }
+    for (auto & i : allInputs) { s += i; s += ' '; }
     writeLine(hook->toHook.writeSide, s);
 
     /* Tell the hooks the missing outputs that have to be copied back
        from the remote system. */
     s = "";
-    foreach (PathSet::iterator, i, missingPaths) { s += *i; s += ' '; }
+    for (auto & i : missingPaths) { s += i; s += ' '; }
     writeLine(hook->toHook.writeSide, s);
 
     hook->toHook.writeSide.close();
@@ -1742,7 +1741,7 @@ void DerivationGoal::startBuilder()
        already know the cryptographic hash of the output). */
     if (fixedOutput) {
         Strings varNames = tokenizeString<Strings>(get(drv->env, "impureEnvVars"));
-        foreach (Strings::iterator, i, varNames) env[*i] = getEnv(*i);
+        for (auto & i : varNames) env[i] = getEnv(i);
     }
 
     /* The `exportReferencesGraph' feature allows the references graph
@@ -1778,9 +1777,9 @@ void DerivationGoal::startBuilder()
         computeFSClosure(worker.store, storePath, paths);
         paths2 = paths;
 
-        foreach (PathSet::iterator, j, paths2) {
-            if (isDerivation(*j)) {
-                Derivation drv = derivationFromPath(worker.store, *j);
+        for (auto & j : paths2) {
+            if (isDerivation(j)) {
+                Derivation drv = derivationFromPath(worker.store, j);
                 for (auto & k : drv.outputs)
                     computeFSClosure(worker.store, k.second.path, paths);
             }
@@ -1951,28 +1950,28 @@ void DerivationGoal::startBuilder()
         if (chown(chrootStoreDir.c_str(), 0, buildUser.getGID()) == -1)
             throw SysError(format("cannot change ownership of ‘%1%’") % chrootStoreDir);
 
-        foreach (PathSet::iterator, i, inputPaths) {
+        for (auto & i : inputPaths) {
             struct stat st;
-            if (lstat(i->c_str(), &st))
-                throw SysError(format("getting attributes of path ‘%1%’") % *i);
+            if (lstat(i.c_str(), &st))
+                throw SysError(format("getting attributes of path ‘%1%’") % i);
             if (S_ISDIR(st.st_mode))
-                dirsInChroot[*i] = *i;
+                dirsInChroot[i] = i;
             else {
-                Path p = chrootRootDir + *i;
-                if (link(i->c_str(), p.c_str()) == -1) {
+                Path p = chrootRootDir + i;
+                if (link(i.c_str(), p.c_str()) == -1) {
                     /* Hard-linking fails if we exceed the maximum
                        link count on a file (e.g. 32000 of ext3),
                        which is quite possible after a `nix-store
                        --optimise'. */
                     if (errno != EMLINK)
-                        throw SysError(format("linking ‘%1%’ to ‘%2%’") % p % *i);
+                        throw SysError(format("linking ‘%1%’ to ‘%2%’") % p % i);
                     StringSink sink;
-                    dumpPath(*i, sink);
+                    dumpPath(i, sink);
                     StringSource source(sink.s);
                     restorePath(p, source);
                 }
 
-                regularInputPaths.insert(*i);
+                regularInputPaths.insert(i);
             }
         }
 
@@ -2007,16 +2006,16 @@ void DerivationGoal::startBuilder()
            contents of the new outputs to replace the dummy strings
            with the actual hashes. */
         if (validPaths.size() > 0)
-            foreach (PathSet::iterator, i, validPaths)
-                addHashRewrite(*i);
+            for (auto & i : validPaths)
+                addHashRewrite(i);
 
         /* If we're repairing, then we don't want to delete the
            corrupt outputs in advance.  So rewrite them as well. */
         if (buildMode == bmRepair)
-            foreach (PathSet::iterator, i, missingPaths)
-                if (worker.store.isValidPath(*i) && pathExists(*i)) {
-                    addHashRewrite(*i);
-                    redirectedBadOutputs.insert(*i);
+            for (auto & i : missingPaths)
+                if (worker.store.isValidPath(i) && pathExists(i)) {
+                    addHashRewrite(i);
+                    redirectedBadOutputs.insert(i);
                 }
     }
 
@@ -2190,8 +2189,8 @@ void DerivationGoal::runChild()
                local to the namespace, though, so setting MS_PRIVATE
                does not affect the outside world. */
             Strings mounts = tokenizeString<Strings>(readFile("/proc/self/mountinfo", true), "\n");
-            foreach (Strings::iterator, i, mounts) {
-                vector<string> fields = tokenizeString<vector<string> >(*i, " ");
+            for (auto & i : mounts) {
+                vector<string> fields = tokenizeString<vector<string> >(i, " ");
                 string fs = decodeOctalEscaped(fields.at(4));
                 if (mount(0, fs.c_str(), 0, MS_PRIVATE, 0) == -1)
                     throw SysError(format("unable to make filesystem ‘%1%’ private") % fs);
@@ -2239,10 +2238,10 @@ void DerivationGoal::runChild()
             /* Bind-mount all the directories from the "host"
                filesystem that we want in the chroot
                environment. */
-            foreach (DirsInChroot::iterator, i, dirsInChroot) {
+            for (auto & i : dirsInChroot) {
                 struct stat st;
-                Path source = i->second;
-                Path target = chrootRootDir + i->first;
+                Path source = i.second;
+                Path target = chrootRootDir + i.first;
                 if (source == "/proc") continue; // backwards compatibility
                 debug(format("bind mounting ‘%1%’ to ‘%2%’") % source % target);
                 if (stat(source.c_str(), &st) == -1)
@@ -2340,8 +2339,8 @@ void DerivationGoal::runChild()
 
         /* Fill in the environment. */
         Strings envStrs;
-        foreach (Environment::const_iterator, i, env)
-            envStrs.push_back(rewriteHashes(i->first + "=" + i->second, rewritesToTmp));
+        for (auto & i : env)
+            envStrs.push_back(rewriteHashes(i.first + "=" + i.second, rewritesToTmp));
 
         /* If we are running in `build-users' mode, then switch to the
            user we allocated above.  Make sure that we drop all root
@@ -2522,14 +2521,13 @@ PathSet parseReferenceSpecifiers(const BasicDerivation & drv, string attr)
 {
     PathSet result;
     Paths paths = tokenizeString<Paths>(attr);
-    foreach (Strings::iterator, i, paths) {
-        if (isStorePath(*i))
-            result.insert(*i);
-        else if (drv.outputs.find(*i) != drv.outputs.end())
-            result.insert(drv.outputs.find(*i)->second.path);
+    for (auto & i : paths) {
+        if (isStorePath(i))
+            result.insert(i);
+        else if (drv.outputs.find(i) != drv.outputs.end())
+            result.insert(drv.outputs.find(i)->second.path);
         else throw BuildError(
-            format("derivation contains an illegal reference specifier ‘%1%’")
-            % *i);
+            format("derivation contains an illegal reference specifier ‘%1%’") % i);
     }
     return result;
 }
@@ -2666,12 +2664,12 @@ void DerivationGoal::registerOutputs()
 
         /* For debugging, print out the referenced and unreferenced
            paths. */
-        foreach (PathSet::iterator, i, inputPaths) {
-            PathSet::iterator j = references.find(*i);
+        for (auto & i : inputPaths) {
+            PathSet::iterator j = references.find(i);
             if (j == references.end())
-                debug(format("unreferenced input: ‘%1%’") % *i);
+                debug(format("unreferenced input: ‘%1%’") % i);
             else
-                debug(format("referenced input: ‘%1%’") % *i);
+                debug(format("referenced input: ‘%1%’") % i);
         }
 
         /* Enforce `allowedReferences' and friends. */
@@ -3044,9 +3042,9 @@ void SubstitutionGoal::tryNext()
 
     /* To maintain the closure invariant, we first have to realise the
        paths referenced by this one. */
-    foreach (PathSet::iterator, i, info.references)
-        if (*i != storePath) /* ignore self-references */
-            addWaitee(worker.makeSubstitutionGoal(*i));
+    for (auto & i : info.references)
+        if (i != storePath) /* ignore self-references */
+            addWaitee(worker.makeSubstitutionGoal(i));
 
     if (waitees.empty()) /* to prevent hang (no wake-up event) */
         referencesValid();
@@ -3065,9 +3063,9 @@ void SubstitutionGoal::referencesValid()
         return;
     }
 
-    foreach (PathSet::iterator, i, info.references)
-        if (*i != storePath) /* ignore self-references */
-            assert(worker.store.isValidPath(*i));
+    for (auto & i : info.references)
+        if (i != storePath) /* ignore self-references */
+            assert(worker.store.isValidPath(i));
 
     state = &SubstitutionGoal::tryToRun;
     worker.wakeUp(shared_from_this());
@@ -3359,8 +3357,8 @@ void Worker::removeGoal(GoalPtr goal)
     }
 
     /* Wake up goals waiting for any goal to finish. */
-    foreach (WeakGoals::iterator, i, waitingForAnyGoal) {
-        GoalPtr goal = i->lock();
+    for (auto & i : waitingForAnyGoal) {
+        GoalPtr goal = i.lock();
         if (goal) wakeUp(goal);
     }
 
@@ -3413,8 +3411,8 @@ void Worker::childTerminated(pid_t pid, bool wakeSleepers)
     if (wakeSleepers) {
 
         /* Wake up goals waiting for a build slot. */
-        foreach (WeakGoals::iterator, i, wantingToBuild) {
-            GoalPtr goal = i->lock();
+        for (auto & i : wantingToBuild) {
+            GoalPtr goal = i.lock();
             if (goal) wakeUp(goal);
         }
 
@@ -3449,7 +3447,7 @@ void Worker::waitForAWhile(GoalPtr goal)
 
 void Worker::run(const Goals & _topGoals)
 {
-    foreach (Goals::iterator, i,  _topGoals) topGoals.insert(*i);
+    for (auto & i : _topGoals) topGoals.insert(i);
 
     startNest(nest, lvlDebug, format("entered goal loop"));
 
@@ -3515,12 +3513,12 @@ void Worker::waitForInput()
        deadline for any child. */
     assert(sizeof(time_t) >= sizeof(long));
     time_t nearest = LONG_MAX; // nearest deadline
-    foreach (Children::iterator, i, children) {
-        if (!i->second.respectTimeouts) continue;
+    for (auto & i : children) {
+        if (!i.second.respectTimeouts) continue;
         if (settings.maxSilentTime != 0)
-            nearest = std::min(nearest, i->second.lastOutput + settings.maxSilentTime);
+            nearest = std::min(nearest, i.second.lastOutput + settings.maxSilentTime);
         if (settings.buildTimeout != 0)
-            nearest = std::min(nearest, i->second.timeStarted + settings.buildTimeout);
+            nearest = std::min(nearest, i.second.timeStarted + settings.buildTimeout);
     }
     if (nearest != LONG_MAX) {
         timeout.tv_sec = std::max((time_t) 1, nearest - before);
@@ -3545,10 +3543,10 @@ void Worker::waitForInput()
     fd_set fds;
     FD_ZERO(&fds);
     int fdMax = 0;
-    foreach (Children::iterator, i, children) {
-        foreach (set<int>::iterator, j, i->second.fds) {
-            FD_SET(*j, &fds);
-            if (*j >= fdMax) fdMax = *j + 1;
+    for (auto & i : children) {
+        for (auto & j : i.second.fds) {
+            FD_SET(j, &fds);
+            if (j >= fdMax) fdMax = j + 1;
         }
     }
 
@@ -3566,34 +3564,34 @@ void Worker::waitForInput()
        careful that we don't keep iterators alive across calls to
        cancel(). */
     set<pid_t> pids;
-    foreach (Children::iterator, i, children) pids.insert(i->first);
+    for (auto & i : children) pids.insert(i.first);
 
-    foreach (set<pid_t>::iterator, i, pids) {
+    for (auto & i : pids) {
         checkInterrupt();
-        Children::iterator j = children.find(*i);
+        Children::iterator j = children.find(i);
         if (j == children.end()) continue; // child destroyed
         GoalPtr goal = j->second.goal.lock();
         assert(goal);
 
         set<int> fds2(j->second.fds);
-        foreach (set<int>::iterator, k, fds2) {
-            if (FD_ISSET(*k, &fds)) {
+        for (auto & k : fds2) {
+            if (FD_ISSET(k, &fds)) {
                 unsigned char buffer[4096];
-                ssize_t rd = read(*k, buffer, sizeof(buffer));
+                ssize_t rd = read(k, buffer, sizeof(buffer));
                 if (rd == -1) {
                     if (errno != EINTR)
                         throw SysError(format("reading from %1%")
                             % goal->getName());
                 } else if (rd == 0) {
                     debug(format("%1%: got EOF") % goal->getName());
-                    goal->handleEOF(*k);
-                    j->second.fds.erase(*k);
+                    goal->handleEOF(k);
+                    j->second.fds.erase(k);
                 } else {
                     printMsg(lvlVomit, format("%1%: read %2% bytes")
                         % goal->getName() % rd);
                     string data((char *) buffer, rd);
                     j->second.lastOutput = after;
-                    goal->handleChildOutput(*k, data);
+                    goal->handleChildOutput(k, data);
                 }
             }
         }
@@ -3625,8 +3623,8 @@ void Worker::waitForInput()
 
     if (!waitingForAWhile.empty() && lastWokenUp + settings.pollInterval <= after) {
         lastWokenUp = after;
-        foreach (WeakGoals::iterator, i, waitingForAWhile) {
-            GoalPtr goal = i->lock();
+        for (auto & i : waitingForAWhile) {
+            GoalPtr goal = i.lock();
             if (goal) wakeUp(goal);
         }
         waitingForAWhile.clear();
@@ -3650,22 +3648,22 @@ void LocalStore::buildPaths(const PathSet & drvPaths, BuildMode buildMode)
     Worker worker(*this);
 
     Goals goals;
-    foreach (PathSet::const_iterator, i, drvPaths) {
-        DrvPathWithOutputs i2 = parseDrvPathWithOutputs(*i);
+    for (auto & i : drvPaths) {
+        DrvPathWithOutputs i2 = parseDrvPathWithOutputs(i);
         if (isDerivation(i2.first))
             goals.insert(worker.makeDerivationGoal(i2.first, i2.second, buildMode));
         else
-            goals.insert(worker.makeSubstitutionGoal(*i, buildMode));
+            goals.insert(worker.makeSubstitutionGoal(i, buildMode));
     }
 
     worker.run(goals);
 
     PathSet failed;
-    foreach (Goals::iterator, i, goals)
-        if ((*i)->getExitCode() == Goal::ecFailed) {
-            DerivationGoal * i2 = dynamic_cast<DerivationGoal *>(i->get());
+    for (auto & i : goals)
+        if (i->getExitCode() == Goal::ecFailed) {
+            DerivationGoal * i2 = dynamic_cast<DerivationGoal *>(i.get());
             if (i2) failed.insert(i2->getDrvPath());
-            else failed.insert(dynamic_cast<SubstitutionGoal *>(i->get())->getStorePath());
+            else failed.insert(dynamic_cast<SubstitutionGoal *>(i.get())->getStorePath());
         }
 
     if (!failed.empty())
diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc
index db35af6cbc..7959d5bfc3 100644
--- a/src/libstore/derivations.cc
+++ b/src/libstore/derivations.cc
@@ -32,8 +32,8 @@ Path writeDerivation(StoreAPI & store,
 {
     PathSet references;
     references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
-    foreach (DerivationInputs::const_iterator, i, drv.inputDrvs)
-        references.insert(i->first);
+    for (auto & i : drv.inputDrvs)
+        references.insert(i.first);
     /* Note that the outputs of a derivation are *not* references
        (that can be missing (of course) and should not necessarily be
        held during a garbage collection). */
@@ -156,21 +156,21 @@ string unparseDerivation(const Derivation & drv)
     s += "Derive([";
 
     bool first = true;
-    foreach (DerivationOutputs::const_iterator, i, drv.outputs) {
+    for (auto & i : drv.outputs) {
         if (first) first = false; else s += ',';
-        s += '('; printString(s, i->first);
-        s += ','; printString(s, i->second.path);
-        s += ','; printString(s, i->second.hashAlgo);
-        s += ','; printString(s, i->second.hash);
+        s += '('; printString(s, i.first);
+        s += ','; printString(s, i.second.path);
+        s += ','; printString(s, i.second.hashAlgo);
+        s += ','; printString(s, i.second.hash);
         s += ')';
     }
 
     s += "],[";
     first = true;
-    foreach (DerivationInputs::const_iterator, i, drv.inputDrvs) {
+    for (auto & i : drv.inputDrvs) {
         if (first) first = false; else s += ',';
-        s += '('; printString(s, i->first);
-        s += ','; printStrings(s, i->second.begin(), i->second.end());
+        s += '('; printString(s, i.first);
+        s += ','; printStrings(s, i.second.begin(), i.second.end());
         s += ')';
     }
 
@@ -183,10 +183,10 @@ string unparseDerivation(const Derivation & drv)
 
     s += ",[";
     first = true;
-    foreach (StringPairs::const_iterator, i, drv.env) {
+    for (auto & i : drv.env) {
         if (first) first = false; else s += ',';
-        s += '('; printString(s, i->first);
-        s += ','; printString(s, i->second);
+        s += '('; printString(s, i.first);
+        s += ','; printString(s, i.second);
         s += ')';
     }
 
@@ -247,15 +247,15 @@ Hash hashDerivationModulo(StoreAPI & store, Derivation drv)
     /* For other derivations, replace the inputs paths with recursive
        calls to this function.*/
     DerivationInputs inputs2;
-    foreach (DerivationInputs::const_iterator, i, drv.inputDrvs) {
-        Hash h = drvHashes[i->first];
+    for (auto & i : drv.inputDrvs) {
+        Hash h = drvHashes[i.first];
         if (h.type == htUnknown) {
-            assert(store.isValidPath(i->first));
-            Derivation drv2 = readDerivation(i->first);
+            assert(store.isValidPath(i.first));
+            Derivation drv2 = readDerivation(i.first);
             h = hashDerivationModulo(store, drv2);
-            drvHashes[i->first] = h;
+            drvHashes[i.first] = h;
         }
-        inputs2[printHash(h)] = i->second;
+        inputs2[printHash(h)] = i.second;
     }
     drv.inputDrvs = inputs2;
 
diff --git a/src/libstore/gc.cc b/src/libstore/gc.cc
index 8d7da67f52..998a7516a1 100644
--- a/src/libstore/gc.cc
+++ b/src/libstore/gc.cc
@@ -350,15 +350,14 @@ static void addAdditionalRoots(StoreAPI & store, PathSet & roots)
 
     StringSet paths = tokenizeString<StringSet>(result, "\n");
 
-    foreach (StringSet::iterator, i, paths) {
-        if (isInStore(*i)) {
-            Path path = toStorePath(*i);
+    for (auto & i : paths)
+        if (isInStore(i)) {
+            Path path = toStorePath(i);
             if (roots.find(path) == roots.end() && store.isValidPath(path)) {
                 debug(format("got additional root ‘%1%’") % path);
                 roots.insert(path);
             }
         }
-    }
 }
 
 
@@ -408,8 +407,8 @@ void LocalStore::deletePathRecursive(GCState & state, const Path & path)
     if (isValidPath(path)) {
         PathSet referrers;
         queryReferrers(path, referrers);
-        foreach (PathSet::iterator, i, referrers)
-            if (*i != path) deletePathRecursive(state, *i);
+        for (auto & i : referrers)
+            if (i != path) deletePathRecursive(state, i);
         size = queryPathInfo(path).narSize;
         invalidatePathChecked(path);
     }
@@ -487,22 +486,22 @@ bool LocalStore::canReachRoot(GCState & state, PathSet & visited, const Path & p
        don't delete the derivation if any of the outputs are alive. */
     if (state.gcKeepDerivations && isDerivation(path)) {
         PathSet outputs = queryDerivationOutputs(path);
-        foreach (PathSet::iterator, i, outputs)
-            if (isValidPath(*i) && queryDeriver(*i) == path)
-                incoming.insert(*i);
+        for (auto & i : outputs)
+            if (isValidPath(i) && queryDeriver(i) == path)
+                incoming.insert(i);
     }
 
     /* If gc-keep-outputs is set, then don't delete this path if there
        are derivers of this path that are not garbage. */
     if (state.gcKeepOutputs) {
         PathSet derivers = queryValidDerivers(path);
-        foreach (PathSet::iterator, i, derivers)
-            incoming.insert(*i);
+        for (auto & i : derivers)
+            incoming.insert(i);
     }
 
-    foreach (PathSet::iterator, i, incoming)
-        if (*i != path)
-            if (canReachRoot(state, visited, *i)) {
+    for (auto & i : incoming)
+        if (i != path)
+            if (canReachRoot(state, visited, i)) {
                 state.alive.insert(path);
                 return true;
             }
@@ -622,7 +621,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
     printMsg(lvlError, format("finding garbage collector roots..."));
     Roots rootMap = options.ignoreLiveness ? Roots() : findRoots();
 
-    foreach (Roots::iterator, i, rootMap) state.roots.insert(i->second);
+    for (auto & i : rootMap) state.roots.insert(i.second);
 
     /* Add additional roots returned by the program specified by the
        NIX_ROOT_FINDER environment variable.  This is typically used
@@ -659,11 +658,11 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
 
     if (options.action == GCOptions::gcDeleteSpecific) {
 
-        foreach (PathSet::iterator, i, options.pathsToDelete) {
-            assertStorePath(*i);
-            tryToDelete(state, *i);
-            if (state.dead.find(*i) == state.dead.end())
-                throw Error(format("cannot delete path ‘%1%’ since it is still alive") % *i);
+        for (auto & i : options.pathsToDelete) {
+            assertStorePath(i);
+            tryToDelete(state, i);
+            if (state.dead.find(i) == state.dead.end())
+                throw Error(format("cannot delete path ‘%1%’ since it is still alive") % i);
         }
 
     } else if (options.maxFreed > 0) {
@@ -707,8 +706,8 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
             vector<Path> entries_(entries.begin(), entries.end());
             random_shuffle(entries_.begin(), entries_.end());
 
-            foreach (vector<Path>::iterator, i, entries_)
-                tryToDelete(state, *i);
+            for (auto & i : entries_)
+                tryToDelete(state, i);
 
         } catch (GCLimitReached & e) {
         }
diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc
index 50374f782d..73f8489438 100644
--- a/src/libstore/globals.cc
+++ b/src/libstore/globals.cc
@@ -248,12 +248,12 @@ template<class N> void Settings::_get(N & res, const string & name)
 string Settings::pack()
 {
     string s;
-    foreach (SettingsMap::iterator, i, settings) {
-        if (i->first.find('\n') != string::npos ||
-            i->first.find('=') != string::npos ||
-            i->second.find('\n') != string::npos)
+    for (auto & i : settings) {
+        if (i.first.find('\n') != string::npos ||
+            i.first.find('=') != string::npos ||
+            i.second.find('\n') != string::npos)
             throw Error("illegal option name/value");
-        s += i->first; s += '='; s += i->second; s += '\n';
+        s += i.first; s += '='; s += i.second; s += '\n';
     }
     return s;
 }
@@ -261,11 +261,11 @@ string Settings::pack()
 
 void Settings::unpack(const string & pack) {
     Strings lines = tokenizeString<Strings>(pack, "\n");
-    foreach (Strings::iterator, i, lines) {
-        string::size_type eq = i->find('=');
+    for (auto & i : lines) {
+        string::size_type eq = i.find('=');
         if (eq == string::npos)
             throw Error("illegal option name/value");
-        set(i->substr(0, eq), i->substr(eq + 1));
+        set(i.substr(0, eq), i.substr(eq + 1));
     }
 }
 
diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc
index 074c3394ff..319f1c719f 100644
--- a/src/libstore/local-store.cc
+++ b/src/libstore/local-store.cc
@@ -367,13 +367,13 @@ LocalStore::LocalStore(bool reserveSpace)
 LocalStore::~LocalStore()
 {
     try {
-        foreach (RunningSubstituters::iterator, i, runningSubstituters) {
-            if (i->second.disabled) continue;
-            i->second.to.close();
-            i->second.from.close();
-            i->second.error.close();
-            if (i->second.pid != -1)
-                i->second.pid.wait(true);
+        for (auto & i : runningSubstituters) {
+            if (i.second.disabled) continue;
+            i.second.to.close();
+            i.second.from.close();
+            i.second.error.close();
+            if (i.second.pid != -1)
+                i.second.pid.wait(true);
         }
     } catch (...) {
         ignoreException();
@@ -671,19 +671,19 @@ void LocalStore::checkDerivationOutputs(const Path & drvPath, const Derivation &
 
     else {
         Derivation drvCopy(drv);
-        foreach (DerivationOutputs::iterator, i, drvCopy.outputs) {
-            i->second.path = "";
-            drvCopy.env[i->first] = "";
+        for (auto & i : drvCopy.outputs) {
+            i.second.path = "";
+            drvCopy.env[i.first] = "";
         }
 
         Hash h = hashDerivationModulo(*this, drvCopy);
 
-        foreach (DerivationOutputs::const_iterator, i, drv.outputs) {
-            Path outPath = makeOutputPath(i->first, h, drvName);
-            StringPairs::const_iterator j = drv.env.find(i->first);
-            if (i->second.path != outPath || j == drv.env.end() || j->second != outPath)
+        for (auto & i : drv.outputs) {
+            Path outPath = makeOutputPath(i.first, h, drvName);
+            StringPairs::const_iterator j = drv.env.find(i.first);
+            if (i.second.path != outPath || j == drv.env.end() || j->second != outPath)
                 throw Error(format("derivation ‘%1%’ has incorrect output ‘%2%’, should be ‘%3%’")
-                    % drvPath % i->second.path % outPath);
+                    % drvPath % i.second.path % outPath);
         }
     }
 }
@@ -721,11 +721,11 @@ unsigned long long LocalStore::addValidPath(const ValidPathInfo & info, bool che
            registration above is undone. */
         if (checkOutputs) checkDerivationOutputs(info.path, drv);
 
-        foreach (DerivationOutputs::iterator, i, drv.outputs) {
+        for (auto & i : drv.outputs) {
             SQLiteStmtUse use(stmtAddDerivationOutput);
             stmtAddDerivationOutput.bind(id);
-            stmtAddDerivationOutput.bind(i->first);
-            stmtAddDerivationOutput.bind(i->second.path);
+            stmtAddDerivationOutput.bind(i.first);
+            stmtAddDerivationOutput.bind(i.second.path);
             if (sqlite3_step(stmtAddDerivationOutput) != SQLITE_DONE)
                 throwSQLiteError(db, format("adding derivation output for ‘%1%’ in database") % info.path);
         }
@@ -796,11 +796,11 @@ void LocalStore::clearFailedPaths(const PathSet & paths)
     retry_sqlite {
         SQLiteTxn txn(db);
 
-        foreach (PathSet::const_iterator, i, paths) {
+        for (auto & i : paths) {
             SQLiteStmtUse use(stmtClearFailedPath);
-            stmtClearFailedPath.bind(*i);
+            stmtClearFailedPath.bind(i);
             if (sqlite3_step(stmtClearFailedPath) != SQLITE_DONE)
-                throwSQLiteError(db, format("clearing failed path ‘%1%’ in database") % *i);
+                throwSQLiteError(db, format("clearing failed path ‘%1%’ in database") % i);
         }
 
         txn.commit();
@@ -923,8 +923,8 @@ PathSet LocalStore::queryValidPaths(const PathSet & paths)
 {
     retry_sqlite {
         PathSet res;
-        foreach (PathSet::const_iterator, i, paths)
-            if (isValidPath_(*i)) res.insert(*i);
+        for (auto & i : paths)
+            if (isValidPath_(i)) res.insert(i);
         return res;
     } end_retry_sqlite;
 }
@@ -1212,14 +1212,14 @@ template<class T> T LocalStore::getIntLineFromSubstituter(RunningSubstituter & r
 PathSet LocalStore::querySubstitutablePaths(const PathSet & paths)
 {
     PathSet res;
-    foreach (Paths::iterator, i, settings.substituters) {
+    for (auto & i : settings.substituters) {
         if (res.size() == paths.size()) break;
-        RunningSubstituter & run(runningSubstituters[*i]);
-        startSubstituter(*i, run);
+        RunningSubstituter & run(runningSubstituters[i]);
+        startSubstituter(i, run);
         if (run.disabled) continue;
         string s = "have ";
-        foreach (PathSet::const_iterator, j, paths)
-            if (res.find(*j) == res.end()) { s += *j; s += " "; }
+        for (auto & j : paths)
+            if (res.find(j) == res.end()) { s += j; s += " "; }
         writeLine(run.to, s);
         while (true) {
             /* FIXME: we only read stderr when an error occurs, so
@@ -1243,8 +1243,8 @@ void LocalStore::querySubstitutablePathInfos(const Path & substituter,
     if (run.disabled) return;
 
     string s = "info ";
-    foreach (PathSet::const_iterator, i, paths)
-        if (infos.find(*i) == infos.end()) { s += *i; s += " "; }
+    for (auto & i : paths)
+        if (infos.find(i) == infos.end()) { s += i; s += " "; }
     writeLine(run.to, s);
 
     while (true) {
@@ -1272,9 +1272,9 @@ void LocalStore::querySubstitutablePathInfos(const PathSet & paths,
     SubstitutablePathInfos & infos)
 {
     PathSet todo = paths;
-    foreach (Paths::iterator, i, settings.substituters) {
+    for (auto & i : settings.substituters) {
         if (todo.empty()) break;
-        querySubstitutablePathInfos(*i, todo, infos);
+        querySubstitutablePathInfos(i, todo, infos);
     }
 }
 
@@ -1304,30 +1304,30 @@ void LocalStore::registerValidPaths(const ValidPathInfos & infos)
         SQLiteTxn txn(db);
         PathSet paths;
 
-        foreach (ValidPathInfos::const_iterator, i, infos) {
-            assert(i->hash.type == htSHA256);
-            if (isValidPath_(i->path))
-                updatePathInfo(*i);
+        for (auto & i : infos) {
+            assert(i.hash.type == htSHA256);
+            if (isValidPath_(i.path))
+                updatePathInfo(i);
             else
-                addValidPath(*i, false);
-            paths.insert(i->path);
+                addValidPath(i, false);
+            paths.insert(i.path);
         }
 
-        foreach (ValidPathInfos::const_iterator, i, infos) {
-            unsigned long long referrer = queryValidPathId(i->path);
-            foreach (PathSet::iterator, j, i->references)
-                addReference(referrer, queryValidPathId(*j));
+        for (auto & i : infos) {
+            unsigned long long referrer = queryValidPathId(i.path);
+            for (auto & j : i.references)
+                addReference(referrer, queryValidPathId(j));
         }
 
         /* Check that the derivation outputs are correct.  We can't do
            this in addValidPath() above, because the references might
            not be valid yet. */
-        foreach (ValidPathInfos::const_iterator, i, infos)
-            if (isDerivation(i->path)) {
+        for (auto & i : infos)
+            if (isDerivation(i.path)) {
                 // FIXME: inefficient; we already loaded the
                 // derivation in addValidPath().
-                Derivation drv = readDerivation(i->path);
-                checkDerivationOutputs(i->path, drv);
+                Derivation drv = readDerivation(i.path);
+                checkDerivationOutputs(i.path, drv);
             }
 
         /* Do a topological sort of the paths.  This will throw an
@@ -1761,8 +1761,8 @@ bool LocalStore::verifyStore(bool checkContents, bool repair)
 
     PathSet validPaths2 = queryAllValidPaths(), validPaths, done;
 
-    foreach (PathSet::iterator, i, validPaths2)
-        verifyPath(*i, store, done, validPaths, repair, errors);
+    for (auto & i : validPaths2)
+        verifyPath(i, store, done, validPaths, repair, errors);
 
     /* Release the GC lock so that checking content hashes (which can
        take ages) doesn't block the GC or builds. */
@@ -1774,33 +1774,33 @@ bool LocalStore::verifyStore(bool checkContents, bool repair)
 
         Hash nullHash(htSHA256);
 
-        foreach (PathSet::iterator, i, validPaths) {
+        for (auto & i : validPaths) {
             try {
-                ValidPathInfo info = queryPathInfo(*i);
+                ValidPathInfo info = queryPathInfo(i);
 
                 /* Check the content hash (optionally - slow). */
-                printMsg(lvlTalkative, format("checking contents of ‘%1%’") % *i);
-                HashResult current = hashPath(info.hash.type, *i);
+                printMsg(lvlTalkative, format("checking contents of ‘%1%’") % i);
+                HashResult current = hashPath(info.hash.type, i);
 
                 if (info.hash != nullHash && info.hash != current.first) {
                     printMsg(lvlError, format("path ‘%1%’ was modified! "
                             "expected hash ‘%2%’, got ‘%3%’")
-                        % *i % printHash(info.hash) % printHash(current.first));
-                    if (repair) repairPath(*i); else errors = true;
+                        % i % printHash(info.hash) % printHash(current.first));
+                    if (repair) repairPath(i); else errors = true;
                 } else {
 
                     bool update = false;
 
                     /* Fill in missing hashes. */
                     if (info.hash == nullHash) {
-                        printMsg(lvlError, format("fixing missing hash on ‘%1%’") % *i);
+                        printMsg(lvlError, format("fixing missing hash on ‘%1%’") % i);
                         info.hash = current.first;
                         update = true;
                     }
 
                     /* Fill in missing narSize fields (from old stores). */
                     if (info.narSize == 0) {
-                        printMsg(lvlError, format("updating size field on ‘%1%’ to %2%") % *i % current.second);
+                        printMsg(lvlError, format("updating size field on ‘%1%’ to %2%") % i % current.second);
                         info.narSize = current.second;
                         update = true;
                     }
@@ -1812,7 +1812,7 @@ bool LocalStore::verifyStore(bool checkContents, bool repair)
             } catch (Error & e) {
                 /* It's possible that the path got GC'ed, so ignore
                    errors on invalid paths. */
-                if (isValidPath(*i))
+                if (isValidPath(i))
                     printMsg(lvlError, format("error: %1%") % e.msg());
                 else
                     printMsg(lvlError, format("warning: %1%") % e.msg());
@@ -1844,10 +1844,10 @@ void LocalStore::verifyPath(const Path & path, const PathSet & store,
            first, then we can invalidate this path as well. */
         bool canInvalidate = true;
         PathSet referrers; queryReferrers(path, referrers);
-        foreach (PathSet::iterator, i, referrers)
-            if (*i != path) {
-                verifyPath(*i, store, done, validPaths, repair, errors);
-                if (validPaths.find(*i) != validPaths.end())
+        for (auto & i : referrers)
+            if (i != path) {
+                verifyPath(i, store, done, validPaths, repair, errors);
+                if (validPaths.find(i) != validPaths.end())
                     canInvalidate = false;
             }
 
@@ -1925,12 +1925,12 @@ ValidPathInfo LocalStore::queryPathInfoOld(const Path & path)
     /* Parse it. */
     Strings lines = tokenizeString<Strings>(info, "\n");
 
-    foreach (Strings::iterator, i, lines) {
-        string::size_type p = i->find(':');
+    for (auto & i : lines) {
+        string::size_type p = i.find(':');
         if (p == string::npos)
-            throw Error(format("corrupt line in ‘%1%’: %2%") % infoFile % *i);
-        string name(*i, 0, p);
-        string value(*i, p + 2);
+            throw Error(format("corrupt line in ‘%1%’: %2%") % infoFile % i);
+        string name(i, 0, p);
+        string value(i, p + 2);
         if (name == "References") {
             Strings refs = tokenizeString<Strings>(value, " ");
             res.references = PathSet(refs.begin(), refs.end());
@@ -1960,18 +1960,18 @@ void LocalStore::upgradeStore6()
 
     SQLiteTxn txn(db);
 
-    foreach (PathSet::iterator, i, validPaths) {
-        addValidPath(queryPathInfoOld(*i), false);
+    for (auto & i : validPaths) {
+        addValidPath(queryPathInfoOld(i), false);
         std::cerr << ".";
     }
 
     std::cerr << "|";
 
-    foreach (PathSet::iterator, i, validPaths) {
-        ValidPathInfo info = queryPathInfoOld(*i);
-        unsigned long long referrer = queryValidPathId(*i);
-        foreach (PathSet::iterator, j, info.references)
-            addReference(referrer, queryValidPathId(*j));
+    for (auto & i : validPaths) {
+        ValidPathInfo info = queryPathInfoOld(i);
+        unsigned long long referrer = queryValidPathId(i);
+        for (auto & j : info.references)
+            addReference(referrer, queryValidPathId(j));
         std::cerr << ".";
     }
 
diff --git a/src/libstore/misc.cc b/src/libstore/misc.cc
index 736434ca48..61a976c02f 100644
--- a/src/libstore/misc.cc
+++ b/src/libstore/misc.cc
@@ -28,15 +28,15 @@ void computeFSClosure(StoreAPI & store, const Path & path,
 
         if (includeOutputs) {
             PathSet derivers = store.queryValidDerivers(path);
-            foreach (PathSet::iterator, i, derivers)
-                edges.insert(*i);
+            for (auto & i : derivers)
+                edges.insert(i);
         }
 
         if (includeDerivers && isDerivation(path)) {
             PathSet outputs = store.queryDerivationOutputs(path);
-            foreach (PathSet::iterator, i, outputs)
-                if (store.isValidPath(*i) && store.queryDeriver(*i) == path)
-                    edges.insert(*i);
+            for (auto & i : outputs)
+                if (store.isValidPath(i) && store.queryDeriver(i) == path)
+                    edges.insert(i);
         }
 
     } else {
@@ -44,8 +44,8 @@ void computeFSClosure(StoreAPI & store, const Path & path,
 
         if (includeOutputs && isDerivation(path)) {
             PathSet outputs = store.queryDerivationOutputs(path);
-            foreach (PathSet::iterator, i, outputs)
-                if (store.isValidPath(*i)) edges.insert(*i);
+            for (auto & i : outputs)
+                if (store.isValidPath(i)) edges.insert(i);
         }
 
         if (includeDerivers) {
@@ -54,15 +54,15 @@ void computeFSClosure(StoreAPI & store, const Path & path,
         }
     }
 
-    foreach (PathSet::iterator, i, edges)
-        computeFSClosure(store, *i, paths, flipDirection, includeOutputs, includeDerivers);
+    for (auto & i : edges)
+        computeFSClosure(store, i, paths, flipDirection, includeOutputs, includeDerivers);
 }
 
 
 Path findOutput(const Derivation & drv, string id)
 {
-    foreach (DerivationOutputs::const_iterator, i, drv.outputs)
-        if (i->first == id) return i->second.path;
+    for (auto & i : drv.outputs)
+        if (i.first == id) return i.second.path;
     throw Error(format("derivation has no output ‘%1%’") % id);
 }
 
@@ -98,36 +98,36 @@ void queryMissing(StoreAPI & store, const PathSet & targets,
 
         PathSet query, todoDrv, todoNonDrv;
 
-        foreach (PathSet::iterator, i, todo) {
-            if (done.find(*i) != done.end()) continue;
-            done.insert(*i);
+        for (auto & i : todo) {
+            if (done.find(i) != done.end()) continue;
+            done.insert(i);
 
-            DrvPathWithOutputs i2 = parseDrvPathWithOutputs(*i);
+            DrvPathWithOutputs i2 = parseDrvPathWithOutputs(i);
 
             if (isDerivation(i2.first)) {
                 if (!store.isValidPath(i2.first)) {
                     // FIXME: we could try to substitute p.
-                    unknown.insert(*i);
+                    unknown.insert(i);
                     continue;
                 }
                 Derivation drv = derivationFromPath(store, i2.first);
 
                 PathSet invalid;
-                foreach (DerivationOutputs::iterator, j, drv.outputs)
-                    if (wantOutput(j->first, i2.second)
-                        && !store.isValidPath(j->second.path))
-                        invalid.insert(j->second.path);
+                for (auto & j : drv.outputs)
+                    if (wantOutput(j.first, i2.second)
+                        && !store.isValidPath(j.second.path))
+                        invalid.insert(j.second.path);
                 if (invalid.empty()) continue;
 
-                todoDrv.insert(*i);
+                todoDrv.insert(i);
                 if (settings.useSubstitutes && substitutesAllowed(drv))
                     query.insert(invalid.begin(), invalid.end());
             }
 
             else {
-                if (store.isValidPath(*i)) continue;
-                query.insert(*i);
-                todoNonDrv.insert(*i);
+                if (store.isValidPath(i)) continue;
+                query.insert(i);
+                todoNonDrv.insert(i);
             }
         }
 
@@ -136,8 +136,8 @@ void queryMissing(StoreAPI & store, const PathSet & targets,
         SubstitutablePathInfos infos;
         store.querySubstitutablePathInfos(query, infos);
 
-        foreach (PathSet::iterator, i, todoDrv) {
-            DrvPathWithOutputs i2 = parseDrvPathWithOutputs(*i);
+        for (auto & i : todoDrv) {
+            DrvPathWithOutputs i2 = parseDrvPathWithOutputs(i);
 
             // FIXME: cache this
             Derivation drv = derivationFromPath(store, i2.first);
@@ -145,13 +145,13 @@ void queryMissing(StoreAPI & store, const PathSet & targets,
             PathSet outputs;
             bool mustBuild = false;
             if (settings.useSubstitutes && substitutesAllowed(drv)) {
-                foreach (DerivationOutputs::iterator, j, drv.outputs) {
-                    if (!wantOutput(j->first, i2.second)) continue;
-                    if (!store.isValidPath(j->second.path)) {
-                        if (infos.find(j->second.path) == infos.end())
+                for (auto & j : drv.outputs) {
+                    if (!wantOutput(j.first, i2.second)) continue;
+                    if (!store.isValidPath(j.second.path)) {
+                        if (infos.find(j.second.path) == infos.end())
                             mustBuild = true;
                         else
-                            outputs.insert(j->second.path);
+                            outputs.insert(j.second.path);
                     }
                 }
             } else
@@ -160,22 +160,22 @@ void queryMissing(StoreAPI & store, const PathSet & targets,
             if (mustBuild) {
                 willBuild.insert(i2.first);
                 todo.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
-                foreach (DerivationInputs::iterator, j, drv.inputDrvs)
-                    todo.insert(makeDrvPathWithOutputs(j->first, j->second));
+                for (auto & j : drv.inputDrvs)
+                    todo.insert(makeDrvPathWithOutputs(j.first, j.second));
             } else
                 todoNonDrv.insert(outputs.begin(), outputs.end());
         }
 
-        foreach (PathSet::iterator, i, todoNonDrv) {
-            done.insert(*i);
-            SubstitutablePathInfos::iterator info = infos.find(*i);
+        for (auto & i : todoNonDrv) {
+            done.insert(i);
+            SubstitutablePathInfos::iterator info = infos.find(i);
             if (info != infos.end()) {
-                willSubstitute.insert(*i);
+                willSubstitute.insert(i);
                 downloadSize += info->second.downloadSize;
                 narSize += info->second.narSize;
                 todo.insert(info->second.references.begin(), info->second.references.end());
             } else
-                unknown.insert(*i);
+                unknown.insert(i);
         }
     }
 }
@@ -196,11 +196,11 @@ static void dfsVisit(StoreAPI & store, const PathSet & paths,
     if (store.isValidPath(path))
         store.queryReferences(path, references);
 
-    foreach (PathSet::iterator, i, references)
+    for (auto & i : references)
         /* Don't traverse into paths that don't exist.  That can
            happen due to substitutes for non-existent paths. */
-        if (*i != path && paths.find(*i) != paths.end())
-            dfsVisit(store, paths, *i, visited, sorted, parents);
+        if (i != path && paths.find(i) != paths.end())
+            dfsVisit(store, paths, i, visited, sorted, parents);
 
     sorted.push_front(path);
     parents.erase(path);
@@ -211,8 +211,8 @@ Paths topoSortPaths(StoreAPI & store, const PathSet & paths)
 {
     Paths sorted;
     PathSet visited, parents;
-    foreach (PathSet::const_iterator, i, paths)
-        dfsVisit(store, paths, *i, visited, sorted, parents);
+    for (auto & i : paths)
+        dfsVisit(store, paths, i, visited, sorted, parents);
     return sorted;
 }
 
diff --git a/src/libstore/optimise-store.cc b/src/libstore/optimise-store.cc
index 55c252b9b2..6f66961792 100644
--- a/src/libstore/optimise-store.cc
+++ b/src/libstore/optimise-store.cc
@@ -99,8 +99,8 @@ void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHa
 
     if (S_ISDIR(st.st_mode)) {
         Strings names = readDirectoryIgnoringInodes(path, inodeHash);
-        foreach (Strings::iterator, i, names)
-            optimisePath_(stats, path + "/" + *i, inodeHash);
+        for (auto & i : names)
+            optimisePath_(stats, path + "/" + i, inodeHash);
         return;
     }
 
@@ -218,11 +218,11 @@ void LocalStore::optimiseStore(OptimiseStats & stats)
     PathSet paths = queryAllValidPaths();
     InodeHash inodeHash = loadInodeHash();
 
-    foreach (PathSet::iterator, i, paths) {
-        addTempRoot(*i);
-        if (!isValidPath(*i)) continue; /* path was GC'ed, probably */
-        startNest(nest, lvlChatty, format("hashing files in ‘%1%’") % *i);
-        optimisePath_(stats, *i, inodeHash);
+    for (auto & i : paths) {
+        addTempRoot(i);
+        if (!isValidPath(i)) continue; /* path was GC'ed, probably */
+        startNest(nest, lvlChatty, format("hashing files in ‘%1%’") % i);
+        optimisePath_(stats, i, inodeHash);
     }
 }
 
diff --git a/src/libstore/pathlocks.cc b/src/libstore/pathlocks.cc
index 9db37e8f9a..1c87034f8e 100644
--- a/src/libstore/pathlocks.cc
+++ b/src/libstore/pathlocks.cc
@@ -60,7 +60,7 @@ bool lockFile(int fd, LockType lockType, bool wait)
         while (fcntl(fd, F_SETLK, &lock) != 0) {
             checkInterrupt();
             if (errno == EACCES || errno == EAGAIN) return false;
-            if (errno != EINTR) 
+            if (errno != EINTR)
                 throw SysError(format("acquiring/releasing lock"));
         }
     }
@@ -94,7 +94,7 @@ bool PathLocks::lockPaths(const PathSet & _paths,
     const string & waitMsg, bool wait)
 {
     assert(fds.empty());
-    
+
     /* Note that `fds' is built incrementally so that the destructor
        will only release those locks that we have already acquired. */
 
@@ -102,11 +102,10 @@ bool PathLocks::lockPaths(const PathSet & _paths,
        the same order, thus preventing deadlocks. */
     Paths paths(_paths.begin(), _paths.end());
     paths.sort();
-    
+
     /* Acquire the lock for each path. */
-    foreach (Paths::iterator, i, paths) {
+    for (auto & path : paths) {
         checkInterrupt();
-        Path path = *i;
         Path lockPath = path + ".lock";
 
         debug(format("locking path ‘%1%’") % path);
@@ -115,11 +114,11 @@ bool PathLocks::lockPaths(const PathSet & _paths,
             throw Error("deadlock: trying to re-acquire self-held lock");
 
         AutoCloseFD fd;
-        
+
         while (1) {
 
             /* Open/create the lock file. */
-	    fd = openLockFile(lockPath, true);
+            fd = openLockFile(lockPath, true);
 
             /* Acquire an exclusive lock. */
             if (!lockFile(fd, ltWrite, false)) {
@@ -168,15 +167,15 @@ PathLocks::~PathLocks()
 
 void PathLocks::unlock()
 {
-    foreach (list<FDPair>::iterator, i, fds) {
-        if (deletePaths) deleteLockFile(i->second, i->first);
+    for (auto & i : fds) {
+        if (deletePaths) deleteLockFile(i.second, i.first);
 
-        lockedPaths.erase(i->second);
-        if (close(i->first) == -1)
+        lockedPaths.erase(i.second);
+        if (close(i.first) == -1)
             printMsg(lvlError,
-                format("error (ignored): cannot close lock file on ‘%1%’") % i->second);
+                format("error (ignored): cannot close lock file on ‘%1%’") % i.second);
 
-        debug(format("lock released on ‘%1%’") % i->second);
+        debug(format("lock released on ‘%1%’") % i.second);
     }
 
     fds.clear();
@@ -195,5 +194,5 @@ bool pathIsLockedByMe(const Path & path)
     return lockedPaths.find(lockPath) != lockedPaths.end();
 }
 
- 
+
 }
diff --git a/src/libstore/references.cc b/src/libstore/references.cc
index 521244a313..33eab5a240 100644
--- a/src/libstore/references.cc
+++ b/src/libstore/references.cc
@@ -13,7 +13,7 @@ namespace nix {
 static unsigned int refLength = 32; /* characters */
 
 
-static void search(const unsigned char * s, unsigned int len, 
+static void search(const unsigned char * s, unsigned int len,
     StringSet & hashes, StringSet & seen)
 {
     static bool initialised = false;
@@ -24,7 +24,7 @@ static void search(const unsigned char * s, unsigned int len,
             isBase32[(unsigned char) base32Chars[i]] = true;
         initialised = true;
     }
-    
+
     for (unsigned int i = 0; i + refLength <= len; ) {
         int j;
         bool match = true;
@@ -56,7 +56,7 @@ struct RefScanSink : Sink
     string tail;
 
     RefScanSink() : hashSink(htSHA256) { }
-    
+
     void operator () (const unsigned char * data, size_t len);
 };
 
@@ -89,17 +89,17 @@ PathSet scanForReferences(const string & path,
     /* For efficiency (and a higher hit rate), just search for the
        hash part of the file name.  (This assumes that all references
        have the form `HASH-bla'). */
-    foreach (PathSet::const_iterator, i, refs) {
-        string baseName = baseNameOf(*i);
+    for (auto & i : refs) {
+        string baseName = baseNameOf(i);
         string::size_type pos = baseName.find('-');
         if (pos == string::npos)
-            throw Error(format("bad reference ‘%1%’") % *i);
+            throw Error(format("bad reference ‘%1%’") % i);
         string s = string(baseName, 0, pos);
         assert(s.size() == refLength);
         assert(backMap.find(s) == backMap.end());
         // parseHash(htSHA256, s);
         sink.hashes.insert(s);
-        backMap[s] = *i;
+        backMap[s] = i;
     }
 
     /* Look for the hashes in the NAR dump of the path. */
@@ -107,14 +107,14 @@ PathSet scanForReferences(const string & path,
 
     /* Map the hashes found back to their store paths. */
     PathSet found;
-    foreach (StringSet::iterator, i, sink.seen) {
+    for (auto & i : sink.seen) {
         std::map<string, Path>::iterator j;
-        if ((j = backMap.find(*i)) == backMap.end()) abort();
+        if ((j = backMap.find(i)) == backMap.end()) abort();
         found.insert(j->second);
     }
 
     hash = sink.hashSink.finish();
-        
+
     return found;
 }
 
diff --git a/src/libstore/remote-store.cc b/src/libstore/remote-store.cc
index acabd6cf00..6b9d5cb253 100644
--- a/src/libstore/remote-store.cc
+++ b/src/libstore/remote-store.cc
@@ -31,7 +31,7 @@ Path readStorePath(Source & from)
 template<class T> T readStorePaths(Source & from)
 {
     T paths = readStrings<T>(from);
-    foreach (typename T::iterator, i, paths) assertStorePath(*i);
+    for (auto & i : paths) assertStorePath(i);
     return paths;
 }
 
@@ -166,9 +166,9 @@ void RemoteStore::setOptions()
         if (overrides["ssh-auth-sock"] == "")
             overrides["ssh-auth-sock"] = getEnv("SSH_AUTH_SOCK");
         writeInt(overrides.size(), to);
-        foreach (Settings::SettingsMap::iterator, i, overrides) {
-            writeString(i->first, to);
-            writeString(i->second, to);
+        for (auto & i : overrides) {
+            writeString(i.first, to);
+            writeString(i.second, to);
         }
     }
 
@@ -192,8 +192,8 @@ PathSet RemoteStore::queryValidPaths(const PathSet & paths)
     openConnection();
     if (GET_PROTOCOL_MINOR(daemonVersion) < 12) {
         PathSet res;
-        foreach (PathSet::const_iterator, i, paths)
-            if (isValidPath(*i)) res.insert(*i);
+        for (auto & i : paths)
+            if (isValidPath(i)) res.insert(i);
         return res;
     } else {
         writeInt(wopQueryValidPaths, to);
@@ -218,11 +218,11 @@ PathSet RemoteStore::querySubstitutablePaths(const PathSet & paths)
     openConnection();
     if (GET_PROTOCOL_MINOR(daemonVersion) < 12) {
         PathSet res;
-        foreach (PathSet::const_iterator, i, paths) {
+        for (auto & i : paths) {
             writeInt(wopHasSubstitutes, to);
-            writeString(*i, to);
+            writeString(i, to);
             processStderr();
-            if (readInt(from)) res.insert(*i);
+            if (readInt(from)) res.insert(i);
         }
         return res;
     } else {
@@ -245,10 +245,10 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet & paths,
 
     if (GET_PROTOCOL_MINOR(daemonVersion) < 12) {
 
-        foreach (PathSet::const_iterator, i, paths) {
+        for (auto & i : paths) {
             SubstitutablePathInfo info;
             writeInt(wopQuerySubstitutablePathInfo, to);
-            writeString(*i, to);
+            writeString(i, to);
             processStderr();
             unsigned int reply = readInt(from);
             if (reply == 0) continue;
@@ -257,7 +257,7 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet & paths,
             info.references = readStorePaths<PathSet>(from);
             info.downloadSize = readLongLong(from);
             info.narSize = GET_PROTOCOL_MINOR(daemonVersion) >= 7 ? readLongLong(from) : 0;
-            infos[*i] = info;
+            infos[i] = info;
         }
 
     } else {
@@ -473,8 +473,8 @@ void RemoteStore::buildPaths(const PathSet & drvPaths, BuildMode buildMode)
         /* For backwards compatibility with old daemons, strip output
            identifiers. */
         PathSet drvPaths2;
-        foreach (PathSet::const_iterator, i, drvPaths)
-            drvPaths2.insert(string(*i, 0, i->find('!')));
+        for (auto & i : drvPaths)
+            drvPaths2.insert(string(i, 0, i.find('!')));
         writeStrings(drvPaths2, to);
     }
     processStderr();
diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc
index d3cbd1e7de..80f17d109a 100644
--- a/src/libstore/store-api.cc
+++ b/src/libstore/store-api.cc
@@ -82,14 +82,14 @@ void checkStoreName(const string & name)
        reasons (e.g., "." and ".."). */
     if (string(name, 0, 1) == ".")
         throw Error(format("illegal name: ‘%1%’") % name);
-    foreach (string::const_iterator, i, name)
-        if (!((*i >= 'A' && *i <= 'Z') ||
-              (*i >= 'a' && *i <= 'z') ||
-              (*i >= '0' && *i <= '9') ||
-              validChars.find(*i) != string::npos))
+    for (auto & i : name)
+        if (!((i >= 'A' && i <= 'Z') ||
+              (i >= 'a' && i <= 'z') ||
+              (i >= '0' && i <= '9') ||
+              validChars.find(i) != string::npos))
         {
             throw Error(format("invalid character ‘%1%’ in name ‘%2%’")
-                % *i % name);
+                % i % name);
         }
 }
 
@@ -101,22 +101,22 @@ void checkStoreName(const string & name)
    where
 
    <store> = the location of the Nix store, usually /nix/store
-   
+
    <name> = a human readable name for the path, typically obtained
      from the name attribute of the derivation, or the name of the
      source file from which the store path is created.  For derivation
      outputs other than the default "out" output, the string "-<id>"
      is suffixed to <name>.
-     
+
    <h> = base-32 representation of the first 160 bits of a SHA-256
      hash of <s>; the hash part of the store name
-     
+
    <s> = the string "<type>:sha256:<h2>:<store>:<name>";
      note that it includes the location of the store as well as the
      name to make sure that changes to either of those are reflected
      in the hash (e.g. you won't get /nix/store/<h>-name1 and
      /nix/store/<h>-name2 with equal hash parts).
-     
+
    <type> = one of:
      "text:<r1>:<r2>:...<rN>"
        for plain text files written to the store using
@@ -219,9 +219,9 @@ Path computeStorePathForText(const string & name, const string & s,
        hacky, but we can't put them in `s' since that would be
        ambiguous. */
     string type = "text";
-    foreach (PathSet::const_iterator, i, references) {
+    for (auto & i : references) {
         type += ":";
-        type += *i;
+        type += i;
     }
     return makeStorePath(type, hash, name);
 }
@@ -234,11 +234,11 @@ string StoreAPI::makeValidityRegistration(const PathSet & paths,
     bool showDerivers, bool showHash)
 {
     string s = "";
-    
-    foreach (PathSet::iterator, i, paths) {
-        s += *i + "\n";
 
-        ValidPathInfo info = queryPathInfo(*i);
+    for (auto & i : paths) {
+        s += i + "\n";
+
+        ValidPathInfo info = queryPathInfo(i);
 
         if (showHash) {
             s += printHash(info.hash) + "\n";
@@ -250,8 +250,8 @@ string StoreAPI::makeValidityRegistration(const PathSet & paths,
 
         s += (format("%1%\n") % info.references.size()).str();
 
-        foreach (PathSet::iterator, j, info.references)
-            s += *j + "\n";
+        for (auto & j : info.references)
+            s += j + "\n";
     }
 
     return s;
@@ -286,9 +286,9 @@ ValidPathInfo decodeValidPathInfo(std::istream & str, bool hashGiven)
 string showPaths(const PathSet & paths)
 {
     string s;
-    foreach (PathSet::const_iterator, i, paths) {
+    for (auto & i : paths) {
         if (s.size() != 0) s += ", ";
-        s += "‘" + *i + "’";
+        s += "‘" + i + "’";
     }
     return s;
 }
@@ -297,9 +297,9 @@ string showPaths(const PathSet & paths)
 void exportPaths(StoreAPI & store, const Paths & paths,
     bool sign, Sink & sink)
 {
-    foreach (Paths::const_iterator, i, paths) {
+    for (auto & i : paths) {
         writeInt(1, sink);
-        store.exportPath(*i, sign, sink);
+        store.exportPath(i, sign, sink);
     }
     writeInt(0, sink);
 }
diff --git a/src/libutil/serialise.cc b/src/libutil/serialise.cc
index aa16a20e6d..7892271028 100644
--- a/src/libutil/serialise.cc
+++ b/src/libutil/serialise.cc
@@ -200,8 +200,8 @@ Sink & operator << (Sink & out, const string & s)
 template<class T> void writeStrings(const T & ss, Sink & sink)
 {
     writeInt(ss.size(), sink);
-    foreach (typename T::const_iterator, i, ss)
-        writeString(*i, sink);
+    for (auto & i : ss)
+        writeString(i, sink);
 }
 
 template void writeStrings(const Paths & ss, Sink & sink);
diff --git a/src/libutil/util.cc b/src/libutil/util.cc
index 596b79e10e..f54fd5fb62 100644
--- a/src/libutil/util.cc
+++ b/src/libutil/util.cc
@@ -1060,9 +1060,9 @@ template vector<string> tokenizeString(const string & s, const string & separato
 string concatStringsSep(const string & sep, const Strings & ss)
 {
     string s;
-    foreach (Strings::const_iterator, i, ss) {
+    for (auto & i : ss) {
         if (s.size() != 0) s += sep;
-        s += *i;
+        s += i;
     }
     return s;
 }
@@ -1071,9 +1071,9 @@ string concatStringsSep(const string & sep, const Strings & ss)
 string concatStringsSep(const string & sep, const StringSet & ss)
 {
     string s;
-    foreach (StringSet::const_iterator, i, ss) {
+    for (auto & i : ss) {
         if (s.size() != 0) s += sep;
-        s += *i;
+        s += i;
     }
     return s;
 }
diff --git a/src/libutil/util.hh b/src/libutil/util.hh
index 187e05ece0..980cdf4cb7 100644
--- a/src/libutil/util.hh
+++ b/src/libutil/util.hh
@@ -15,13 +15,6 @@
 namespace nix {
 
 
-#define foreach(it_type, it, collection)                                \
-    for (it_type it = (collection).begin(); it != (collection).end(); ++it)
-
-#define foreach_reverse(it_type, it, collection)                                \
-    for (it_type it = (collection).rbegin(); it != (collection).rend(); ++it)
-
-
 /* Return an environment variable. */
 string getEnv(const string & key, const string & def = "");
 
diff --git a/src/libutil/xml-writer.cc b/src/libutil/xml-writer.cc
index 01794001b2..98bd058d18 100644
--- a/src/libutil/xml-writer.cc
+++ b/src/libutil/xml-writer.cc
@@ -73,10 +73,10 @@ void XMLWriter::writeEmptyElement(const string & name,
 
 void XMLWriter::writeAttrs(const XMLAttrs & attrs)
 {
-    for (XMLAttrs::const_iterator i = attrs.begin(); i != attrs.end(); ++i) {
-        output << " " << i->first << "=\"";
-        for (unsigned int j = 0; j < i->second.size(); ++j) {
-            char c = i->second[j];
+    for (auto & i : attrs) {
+        output << " " << i.first << "=\"";
+        for (unsigned int j = 0; j < i.second.size(); ++j) {
+            char c = i.second[j];
             if (c == '"') output << "&quot;";
             else if (c == '<') output << "&lt;";
             else if (c == '>') output << "&gt;";
diff --git a/src/nix-daemon/nix-daemon.cc b/src/nix-daemon/nix-daemon.cc
index ad8b0d133d..02d552a62f 100644
--- a/src/nix-daemon/nix-daemon.cc
+++ b/src/nix-daemon/nix-daemon.cc
@@ -367,9 +367,9 @@ static void performOp(bool trusted, unsigned int clientVersion,
         Roots roots = store->findRoots();
         stopWork();
         writeInt(roots.size(), to);
-        for (Roots::iterator i = roots.begin(); i != roots.end(); ++i) {
-            writeString(i->first, to);
-            writeString(i->second, to);
+        for (auto & i : roots) {
+            writeString(i.first, to);
+            writeString(i.second, to);
         }
         break;
     }
@@ -464,12 +464,12 @@ static void performOp(bool trusted, unsigned int clientVersion,
         store->querySubstitutablePathInfos(paths, infos);
         stopWork();
         writeInt(infos.size(), to);
-        foreach (SubstitutablePathInfos::iterator, i, infos) {
-            writeString(i->first, to);
-            writeString(i->second.deriver, to);
-            writeStrings(i->second.references, to);
-            writeLongLong(i->second.downloadSize, to);
-            writeLongLong(i->second.narSize, to);
+        for (auto & i : infos) {
+            writeString(i.first, to);
+            writeString(i.second.deriver, to);
+            writeStrings(i.second.references, to);
+            writeLongLong(i.second.downloadSize, to);
+            writeLongLong(i.second.narSize, to);
         }
         break;
     }
diff --git a/src/nix-env/nix-env.cc b/src/nix-env/nix-env.cc
index 3f82345ce4..c5c7d2ccc7 100644
--- a/src/nix-env/nix-env.cc
+++ b/src/nix-env/nix-env.cc
@@ -232,9 +232,9 @@ static bool isPrebuilt(EvalState & state, DrvInfo & elem)
 static void checkSelectorUse(DrvNames & selectors)
 {
     /* Check that all selectors have been used. */
-    foreach (DrvNames::iterator, i, selectors)
-        if (i->hits == 0 && i->fullName != "*")
-            throw Error(format("selector ‘%1%’ matches no derivations") % i->fullName);
+    for (auto & i : selectors)
+        if (i.hits == 0 && i.fullName != "*")
+            throw Error(format("selector ‘%1%’ matches no derivations") % i.fullName);
 }
 
 
@@ -248,7 +248,7 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems,
     DrvInfos elems;
     set<unsigned int> done;
 
-    foreach (DrvNames::iterator, i, selectors) {
+    for (auto & i : selectors) {
         typedef list<std::pair<DrvInfo, unsigned int> > Matches;
         Matches matches;
         unsigned int n = 0;
@@ -256,8 +256,8 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems,
              j != allElems.end(); ++j, ++n)
         {
             DrvName drvName(j->name);
-            if (i->matches(drvName)) {
-                i->hits++;
+            if (i.matches(drvName)) {
+                i.hits++;
                 matches.push_back(std::pair<DrvInfo, unsigned int>(*j, n));
             }
         }
@@ -276,47 +276,47 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems,
             Newest newest;
             StringSet multiple;
 
-            for (Matches::iterator j = matches.begin(); j != matches.end(); ++j) {
-                DrvName drvName(j->first.name);
+            for (auto & j : matches) {
+                DrvName drvName(j.first.name);
                 int d = 1;
 
                 Newest::iterator k = newest.find(drvName.name);
 
                 if (k != newest.end()) {
-                    d = j->first.system == k->second.first.system ? 0 :
-                        j->first.system == settings.thisSystem ? 1 :
+                    d = j.first.system == k->second.first.system ? 0 :
+                        j.first.system == settings.thisSystem ? 1 :
                         k->second.first.system == settings.thisSystem ? -1 : 0;
                     if (d == 0)
-                        d = comparePriorities(state, j->first, k->second.first);
+                        d = comparePriorities(state, j.first, k->second.first);
                     if (d == 0)
                         d = compareVersions(drvName.version, DrvName(k->second.first.name).version);
                 }
 
                 if (d > 0) {
                     newest.erase(drvName.name);
-                    newest.insert(Newest::value_type(drvName.name, *j));
-                    multiple.erase(j->first.name);
+                    newest.insert(Newest::value_type(drvName.name, j));
+                    multiple.erase(j.first.name);
                 } else if (d == 0) {
-                    multiple.insert(j->first.name);
+                    multiple.insert(j.first.name);
                 }
             }
 
             matches.clear();
-            for (Newest::iterator j = newest.begin(); j != newest.end(); ++j) {
-                if (multiple.find(j->second.first.name) != multiple.end())
+            for (auto & j : newest) {
+                if (multiple.find(j.second.first.name) != multiple.end())
                     printMsg(lvlInfo,
                         format("warning: there are multiple derivations named ‘%1%’; using the first one")
-                        % j->second.first.name);
-                matches.push_back(j->second);
+                        % j.second.first.name);
+                matches.push_back(j.second);
             }
         }
 
         /* Insert only those elements in the final list that we
            haven't inserted before. */
-        for (Matches::iterator j = matches.begin(); j != matches.end(); ++j)
-            if (done.find(j->second) == done.end()) {
-                done.insert(j->second);
-                elems.push_back(j->first);
+        for (auto & j : matches)
+            if (done.find(j.second) == done.end()) {
+                done.insert(j.second);
+                elems.push_back(j.first);
             }
     }
 
@@ -370,8 +370,8 @@ static void queryInstSources(EvalState & state,
             Value vArg;
             loadSourceExpr(state, instSource.nixExprPath, vArg);
 
-            foreach (Strings::const_iterator, i, args) {
-                Expr * eFun = state.parseExprFromString(*i, absPath("."));
+            for (auto & i : args) {
+                Expr * eFun = state.parseExprFromString(i, absPath("."));
                 Value vFun, vTmp;
                 state.eval(eFun, vFun);
                 mkApp(vTmp, vFun, vArg);
@@ -386,8 +386,8 @@ static void queryInstSources(EvalState & state,
            derivations). */
         case srcStorePaths: {
 
-            foreach (Strings::const_iterator, i, args) {
-                Path path = followLinksToStorePath(*i);
+            for (auto & i : args) {
+                Path path = followLinksToStorePath(i);
 
                 string name = baseNameOf(path);
                 string::size_type dash = name.find('-');
@@ -424,8 +424,8 @@ static void queryInstSources(EvalState & state,
         case srcAttrPath: {
             Value vRoot;
             loadSourceExpr(state, instSource.nixExprPath, vRoot);
-            foreach (Strings::const_iterator, i, args) {
-                Value & v(*findAlongAttrPath(state, *i, *instSource.autoArgs, vRoot));
+            for (auto & i : args) {
+                Value & v(*findAlongAttrPath(state, i, *instSource.autoArgs, vRoot));
                 getDerivations(state, v, "", *instSource.autoArgs, elems, true);
             }
             break;
@@ -437,12 +437,12 @@ static void queryInstSources(EvalState & state,
 static void printMissing(EvalState & state, DrvInfos & elems)
 {
     PathSet targets;
-    foreach (DrvInfos::iterator, i, elems) {
-        Path drvPath = i->queryDrvPath();
+    for (auto & i : elems) {
+        Path drvPath = i.queryDrvPath();
         if (drvPath != "")
             targets.insert(drvPath);
         else
-            targets.insert(i->queryOutPath());
+            targets.insert(i.queryOutPath());
     }
 
     printMissing(*store, targets);
@@ -465,19 +465,19 @@ static void installDerivations(Globals & globals,
     queryInstSources(*globals.state, globals.instSource, args, newElemsTmp, true);
 
     /* If --prebuilt-only is given, filter out source-only packages. */
-    foreach (DrvInfos::iterator, i, newElemsTmp)
-        if (!globals.prebuiltOnly || isPrebuilt(*globals.state, *i))
-            newElems.push_back(*i);
+    for (auto & i : newElemsTmp)
+        if (!globals.prebuiltOnly || isPrebuilt(*globals.state, i))
+            newElems.push_back(i);
 
     StringSet newNames;
-    for (DrvInfos::iterator i = newElems.begin(); i != newElems.end(); ++i) {
+    for (auto & i : newElems) {
         /* `forceName' is a hack to get package names right in some
            one-click installs, namely those where the name used in the
            path is not the one we want (e.g., `java-front' versus
            `java-front-0.9pre15899'). */
         if (globals.forceName != "")
-            i->name = globals.forceName;
-        newNames.insert(DrvName(i->name).name);
+            i.name = globals.forceName;
+        newNames.insert(DrvName(i.name).name);
     }
 
 
@@ -491,18 +491,18 @@ static void installDerivations(Globals & globals,
         if (!globals.removeAll) {
             DrvInfos installedElems = queryInstalled(*globals.state, profile);
 
-            foreach (DrvInfos::iterator, i, installedElems) {
-                DrvName drvName(i->name);
+            for (auto & i : installedElems) {
+                DrvName drvName(i.name);
                 if (!globals.preserveInstalled &&
                     newNames.find(drvName.name) != newNames.end() &&
-                    !keep(*i))
-                    printMsg(lvlInfo, format("replacing old ‘%1%’") % i->name);
+                    !keep(i))
+                    printMsg(lvlInfo, format("replacing old ‘%1%’") % i.name);
                 else
-                    allElems.push_back(*i);
+                    allElems.push_back(i);
             }
 
-            foreach (DrvInfos::iterator, i, newElems)
-                printMsg(lvlInfo, format("installing ‘%1%’") % i->name);
+            for (auto & i : newElems)
+                printMsg(lvlInfo, format("installing ‘%1%’") % i.name);
         }
 
         printMissing(*globals.state, newElems);
@@ -555,13 +555,13 @@ static void upgradeDerivations(Globals & globals,
 
         /* Go through all installed derivations. */
         DrvInfos newElems;
-        foreach (DrvInfos::iterator, i, installedElems) {
-            DrvName drvName(i->name);
+        for (auto & i : installedElems) {
+            DrvName drvName(i.name);
 
             try {
 
-                if (keep(*i)) {
-                    newElems.push_back(*i);
+                if (keep(i)) {
+                    newElems.push_back(i);
                     continue;
                 }
 
@@ -573,10 +573,10 @@ static void upgradeDerivations(Globals & globals,
                    take the one with the highest version. */
                 DrvInfos::iterator bestElem = availElems.end();
                 DrvName bestName;
-                foreach (DrvInfos::iterator, j, availElems) {
+                for (auto j = availElems.begin(); j != availElems.end(); ++j) {
                     DrvName newName(j->name);
                     if (newName.name == drvName.name) {
-                        int d = comparePriorities(*globals.state, *i, *j);
+                        int d = comparePriorities(*globals.state, i, *j);
                         if (d == 0) d = compareVersions(drvName.version, newName.version);
                         if ((upgradeType == utLt && d < 0) ||
                             (upgradeType == utLeq && d <= 0) ||
@@ -597,17 +597,17 @@ static void upgradeDerivations(Globals & globals,
                 }
 
                 if (bestElem != availElems.end() &&
-                    i->queryOutPath() !=
+                    i.queryOutPath() !=
                     bestElem->queryOutPath())
                 {
                     printMsg(lvlInfo,
                         format("upgrading ‘%1%’ to ‘%2%’")
-                        % i->name % bestElem->name);
+                        % i.name % bestElem->name);
                     newElems.push_back(*bestElem);
-                } else newElems.push_back(*i);
+                } else newElems.push_back(i);
 
             } catch (Error & e) {
-                e.addPrefix(format("while trying to find an upgrade for ‘%1%’:\n") % i->name);
+                e.addPrefix(format("while trying to find an upgrade for ‘%1%’:\n") % i.name);
                 throw;
             }
         }
@@ -666,13 +666,13 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs)
         DrvInfos installedElems = queryInstalled(*globals.state, globals.profile);
 
         /* Update all matching derivations. */
-        foreach (DrvInfos::iterator, i, installedElems) {
-            DrvName drvName(i->name);
-            foreach (DrvNames::iterator, j, selectors)
-                if (j->matches(drvName)) {
-                    printMsg(lvlInfo, format("setting flag on ‘%1%’") % i->name);
-                    j->hits++;
-                    setMetaFlag(*globals.state, *i, flagName, flagValue);
+        for (auto & i : installedElems) {
+            DrvName drvName(i.name);
+            for (auto & j : selectors)
+                if (j.matches(drvName)) {
+                    printMsg(lvlInfo, format("setting flag on ‘%1%’") % i.name);
+                    j.hits++;
+                    setMetaFlag(*globals.state, i, flagName, flagValue);
                     break;
                 }
         }
@@ -732,20 +732,20 @@ static void uninstallDerivations(Globals & globals, Strings & selectors,
         DrvInfos installedElems = queryInstalled(*globals.state, profile);
         DrvInfos newElems;
 
-        foreach (DrvInfos::iterator, i, installedElems) {
-            DrvName drvName(i->name);
+        for (auto & i : installedElems) {
+            DrvName drvName(i.name);
             bool found = false;
-            foreach (Strings::iterator, j, selectors)
+            for (auto & j : selectors)
                 /* !!! the repeated calls to followLinksToStorePath()
                    are expensive, should pre-compute them. */
-                if ((isPath(*j) && i->queryOutPath() == followLinksToStorePath(*j))
-                    || DrvName(*j).matches(drvName))
+                if ((isPath(j) && i.queryOutPath() == followLinksToStorePath(j))
+                    || DrvName(j).matches(drvName))
                 {
-                    printMsg(lvlInfo, format("uninstalling ‘%1%’") % i->name);
+                    printMsg(lvlInfo, format("uninstalling ‘%1%’") % i.name);
                     found = true;
                     break;
                 }
-            if (!found) newElems.push_back(*i);
+            if (!found) newElems.push_back(i);
         }
 
         if (globals.dryRun) return;
@@ -788,18 +788,18 @@ void printTable(Table & table)
     vector<unsigned int> widths;
     widths.resize(nrColumns);
 
-    foreach (Table::iterator, i, table) {
-        assert(i->size() == nrColumns);
+    for (auto & i : table) {
+        assert(i.size() == nrColumns);
         Strings::iterator j;
         unsigned int column;
-        for (j = i->begin(), column = 0; j != i->end(); ++j, ++column)
+        for (j = i.begin(), column = 0; j != i.end(); ++j, ++column)
             if (j->size() > widths[column]) widths[column] = j->size();
     }
 
-    foreach (Table::iterator, i, table) {
+    for (auto & i : table) {
         Strings::iterator j;
         unsigned int column;
-        for (j = i->begin(), column = 0; j != i->end(); ++j, ++column) {
+        for (j = i.begin(), column = 0; j != i.end(); ++j, ++column) {
             string s = *j;
             replace(s.begin(), s.end(), '\n', ' ');
             cout << s;
@@ -828,8 +828,8 @@ static VersionDiff compareVersionAgainstSet(
     VersionDiff diff = cvUnavail;
     version = "?";
 
-    for (DrvInfos::const_iterator i = elems.begin(); i != elems.end(); ++i) {
-        DrvName name2(i->name);
+    for (auto & i : elems) {
+        DrvName name2(i.name);
         if (name.name == name2.name) {
             int d = compareVersions(name.version, name2.version);
             if (d < 0) {
@@ -855,21 +855,21 @@ static VersionDiff compareVersionAgainstSet(
 static void queryJSON(Globals & globals, vector<DrvInfo> & elems)
 {
     JSONObject topObj(cout);
-    foreach (vector<DrvInfo>::iterator, i, elems) {
-        topObj.attr(i->attrPath);
+    for (auto & i : elems) {
+        topObj.attr(i.attrPath);
         JSONObject pkgObj(cout);
 
-        pkgObj.attr("name", i->name);
-        pkgObj.attr("system", i->system);
+        pkgObj.attr("name", i.name);
+        pkgObj.attr("system", i.system);
 
         pkgObj.attr("meta");
         JSONObject metaObj(cout);
-        StringSet metaNames = i->queryMetaNames();
-        foreach (StringSet::iterator, j, metaNames) {
-            metaObj.attr(*j);
-            Value * v = i->queryMeta(*j);
+        StringSet metaNames = i.queryMetaNames();
+        for (auto & j : metaNames) {
+            metaObj.attr(j);
+            Value * v = i.queryMeta(j);
             if (!v) {
-                printMsg(lvlError, format("derivation ‘%1%’ has invalid meta attribute ‘%2%’") % i->name % *j);
+                printMsg(lvlError, format("derivation ‘%1%’ has invalid meta attribute ‘%2%’") % i.name % j);
                 cout << "null";
             } else {
                 PathSet context;
@@ -944,8 +944,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
     /* Sort them by name. */
     /* !!! */
     vector<DrvInfo> elems;
-    for (DrvInfos::iterator i = elems_.begin(); i != elems_.end(); ++i)
-        elems.push_back(*i);
+    for (auto & i : elems_) elems.push_back(i);
     sort(elems.begin(), elems.end(), cmpElemByName);
 
 
@@ -954,9 +953,8 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
     PathSet installed; /* installed paths */
 
     if (printStatus) {
-        for (DrvInfos::iterator i = installedElems.begin();
-             i != installedElems.end(); ++i)
-            installed.insert(i->queryOutPath());
+        for (auto & i : installedElems)
+            installed.insert(i.queryOutPath());
     }
 
 
@@ -964,12 +962,12 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
     PathSet validPaths, substitutablePaths;
     if (printStatus || globals.prebuiltOnly) {
         PathSet paths;
-        foreach (vector<DrvInfo>::iterator, i, elems)
+        for (auto & i : elems)
             try {
-                paths.insert(i->queryOutPath());
+                paths.insert(i.queryOutPath());
             } catch (AssertionError & e) {
-                printMsg(lvlTalkative, format("skipping derivation named ‘%1%’ which gives an assertion failure") % i->name);
-                i->setFailed();
+                printMsg(lvlTalkative, format("skipping derivation named ‘%1%’ which gives an assertion failure") % i.name);
+                i.setFailed();
             }
         validPaths = store->queryValidPaths(paths);
         substitutablePaths = store->querySubstitutablePaths(paths);
@@ -990,15 +988,15 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
     XMLWriter xml(true, *(xmlOutput ? &cout : &dummy));
     XMLOpenElement xmlRoot(xml, "items");
 
-    foreach (vector<DrvInfo>::iterator, i, elems) {
+    for (auto & i : elems) {
         try {
-            if (i->hasFailed()) continue;
+            if (i.hasFailed()) continue;
 
-            startNest(nest, lvlDebug, format("outputting query result ‘%1%’") % i->attrPath);
+            startNest(nest, lvlDebug, format("outputting query result ‘%1%’") % i.attrPath);
 
             if (globals.prebuiltOnly &&
-                validPaths.find(i->queryOutPath()) == validPaths.end() &&
-                substitutablePaths.find(i->queryOutPath()) == substitutablePaths.end())
+                validPaths.find(i.queryOutPath()) == validPaths.end() &&
+                substitutablePaths.find(i.queryOutPath()) == substitutablePaths.end())
                 continue;
 
             /* For table output. */
@@ -1008,7 +1006,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
             XMLAttrs attrs;
 
             if (printStatus) {
-                Path outPath = i->queryOutPath();
+                Path outPath = i.queryOutPath();
                 bool hasSubs = substitutablePaths.find(outPath) != substitutablePaths.end();
                 bool isInstalled = installed.find(outPath) != installed.end();
                 bool isValid = validPaths.find(outPath) != validPaths.end();
@@ -1024,14 +1022,14 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
             }
 
             if (xmlOutput)
-                attrs["attrPath"] = i->attrPath;
+                attrs["attrPath"] = i.attrPath;
             else if (printAttrPath)
-                columns.push_back(i->attrPath);
+                columns.push_back(i.attrPath);
 
             if (xmlOutput)
-                attrs["name"] = i->name;
+                attrs["name"] = i.name;
             else if (printName)
-                columns.push_back(i->name);
+                columns.push_back(i.name);
 
             if (compareVersions) {
                 /* Compare this element against the versions of the
@@ -1039,7 +1037,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
                    elements, or the set of installed elements.  !!!
                    This is O(N * M), should be O(N * lg M). */
                 string version;
-                VersionDiff diff = compareVersionAgainstSet(*i, otherElems, version);
+                VersionDiff diff = compareVersionAgainstSet(i, otherElems, version);
 
                 char ch;
                 switch (diff) {
@@ -1064,13 +1062,13 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
             }
 
             if (xmlOutput) {
-                if (i->system != "") attrs["system"] = i->system;
+                if (i.system != "") attrs["system"] = i.system;
             }
             else if (printSystem)
-                columns.push_back(i->system);
+                columns.push_back(i.system);
 
             if (printDrvPath) {
-                string drvPath = i->queryDrvPath();
+                string drvPath = i.queryDrvPath();
                 if (xmlOutput) {
                     if (drvPath != "") attrs["drvPath"] = drvPath;
                 } else
@@ -1078,18 +1076,18 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
             }
 
             if (printOutPath && !xmlOutput) {
-                DrvInfo::Outputs outputs = i->queryOutputs();
+                DrvInfo::Outputs outputs = i.queryOutputs();
                 string s;
-                foreach (DrvInfo::Outputs::iterator, j, outputs) {
+                for (auto & j : outputs) {
                     if (!s.empty()) s += ';';
-                    if (j->first != "out") { s += j->first; s += "="; }
-                    s += j->second;
+                    if (j.first != "out") { s += j.first; s += "="; }
+                    s += j.second;
                 }
                 columns.push_back(s);
             }
 
             if (printDescription) {
-                string descr = i->queryMetaString("description");
+                string descr = i.queryMetaString("description");
                 if (xmlOutput) {
                     if (descr != "") attrs["description"] = descr;
                 } else
@@ -1100,22 +1098,22 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
                 if (printOutPath || printMeta) {
                     XMLOpenElement item(xml, "item", attrs);
                     if (printOutPath) {
-                        DrvInfo::Outputs outputs = i->queryOutputs();
-                        foreach (DrvInfo::Outputs::iterator, j, outputs) {
+                        DrvInfo::Outputs outputs = i.queryOutputs();
+                        for (auto & j : outputs) {
                             XMLAttrs attrs2;
-                            attrs2["name"] = j->first;
-                            attrs2["path"] = j->second;
+                            attrs2["name"] = j.first;
+                            attrs2["path"] = j.second;
                             xml.writeEmptyElement("output", attrs2);
                         }
                     }
                     if (printMeta) {
-                        StringSet metaNames = i->queryMetaNames();
-                        foreach (StringSet::iterator, j, metaNames) {
+                        StringSet metaNames = i.queryMetaNames();
+                        for (auto & j : metaNames) {
                             XMLAttrs attrs2;
-                            attrs2["name"] = *j;
-                            Value * v = i->queryMeta(*j);
+                            attrs2["name"] = j;
+                            Value * v = i.queryMeta(j);
                             if (!v)
-                                printMsg(lvlError, format("derivation ‘%1%’ has invalid meta attribute ‘%2%’") % i->name % *j);
+                                printMsg(lvlError, format("derivation ‘%1%’ has invalid meta attribute ‘%2%’") % i.name % j);
                             else {
                                 if (v->type == tString) {
                                     attrs2["type"] = "string";
@@ -1150,9 +1148,9 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
             cout.flush();
 
         } catch (AssertionError & e) {
-            printMsg(lvlTalkative, format("skipping derivation named ‘%1%’ which gives an assertion failure") % i->name);
+            printMsg(lvlTalkative, format("skipping derivation named ‘%1%’ which gives an assertion failure") % i.name);
         } catch (Error & e) {
-            e.addPrefix(format("while querying the derivation named ‘%1%’:\n") % i->name);
+            e.addPrefix(format("while querying the derivation named ‘%1%’:\n") % i.name);
             throw;
         }
     }
@@ -1187,10 +1185,10 @@ static void switchGeneration(Globals & globals, int dstGen)
     Generations gens = findGenerations(globals.profile, curGen);
 
     Generation dst;
-    for (Generations::iterator i = gens.begin(); i != gens.end(); ++i)
-        if ((dstGen == prevGen && i->number < curGen) ||
-            (dstGen >= 0 && i->number == dstGen))
-            dst = *i;
+    for (auto & i : gens)
+        if ((dstGen == prevGen && i.number < curGen) ||
+            (dstGen >= 0 && i.number == dstGen))
+            dst = i;
 
     if (!dst) {
         if (dstGen == prevGen)
@@ -1250,14 +1248,14 @@ static void opListGenerations(Globals & globals, Strings opFlags, Strings opArgs
 
     RunPager pager;
 
-    for (Generations::iterator i = gens.begin(); i != gens.end(); ++i) {
+    for (auto & i : gens) {
         tm t;
-        if (!localtime_r(&i->creationTime, &t)) throw Error("cannot convert time");
+        if (!localtime_r(&i.creationTime, &t)) throw Error("cannot convert time");
         cout << format("%|4|   %|4|-%|02|-%|02| %|02|:%|02|:%|02|   %||\n")
-            % i->number
+            % i.number
             % (t.tm_year + 1900) % (t.tm_mon + 1) % t.tm_mday
             % t.tm_hour % t.tm_min % t.tm_sec
-            % (i->number == curGen ? "(current)" : "");
+            % (i.number == curGen ? "(current)" : "");
     }
 }
 
diff --git a/src/nix-env/user-env.cc b/src/nix-env/user-env.cc
index 3bc31b9eaf..35b1628e3c 100644
--- a/src/nix-env/user-env.cc
+++ b/src/nix-env/user-env.cc
@@ -33,9 +33,9 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
     /* Build the components in the user environment, if they don't
        exist already. */
     PathSet drvsToBuild;
-    foreach (DrvInfos::iterator, i, elems)
-        if (i->queryDrvPath() != "")
-            drvsToBuild.insert(i->queryDrvPath());
+    for (auto & i : elems)
+        if (i.queryDrvPath() != "")
+            drvsToBuild.insert(i.queryDrvPath());
 
     debug(format("building user environment dependencies"));
     store->buildPaths(drvsToBuild, state.repair ? bmRepair : bmNormal);
@@ -45,51 +45,51 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
     Value manifest;
     state.mkList(manifest, elems.size());
     unsigned int n = 0;
-    foreach (DrvInfos::iterator, i, elems) {
+    for (auto & i : elems) {
         /* Create a pseudo-derivation containing the name, system,
            output paths, and optionally the derivation path, as well
            as the meta attributes. */
-        Path drvPath = keepDerivations ? i->queryDrvPath() : "";
+        Path drvPath = keepDerivations ? i.queryDrvPath() : "";
 
         Value & v(*state.allocValue());
         manifest.list.elems[n++] = &v;
         state.mkAttrs(v, 16);
 
         mkString(*state.allocAttr(v, state.sType), "derivation");
-        mkString(*state.allocAttr(v, state.sName), i->name);
-        if (!i->system.empty())
-            mkString(*state.allocAttr(v, state.sSystem), i->system);
-        mkString(*state.allocAttr(v, state.sOutPath), i->queryOutPath());
+        mkString(*state.allocAttr(v, state.sName), i.name);
+        if (!i.system.empty())
+            mkString(*state.allocAttr(v, state.sSystem), i.system);
+        mkString(*state.allocAttr(v, state.sOutPath), i.queryOutPath());
         if (drvPath != "")
-            mkString(*state.allocAttr(v, state.sDrvPath), i->queryDrvPath());
+            mkString(*state.allocAttr(v, state.sDrvPath), i.queryDrvPath());
 
         // Copy each output.
-        DrvInfo::Outputs outputs = i->queryOutputs();
+        DrvInfo::Outputs outputs = i.queryOutputs();
         Value & vOutputs = *state.allocAttr(v, state.sOutputs);
         state.mkList(vOutputs, outputs.size());
         unsigned int m = 0;
-        foreach (DrvInfo::Outputs::iterator, j, outputs) {
-            mkString(*(vOutputs.list.elems[m++] = state.allocValue()), j->first);
-            Value & vOutputs = *state.allocAttr(v, state.symbols.create(j->first));
+        for (auto & j : outputs) {
+            mkString(*(vOutputs.list.elems[m++] = state.allocValue()), j.first);
+            Value & vOutputs = *state.allocAttr(v, state.symbols.create(j.first));
             state.mkAttrs(vOutputs, 2);
-            mkString(*state.allocAttr(vOutputs, state.sOutPath), j->second);
+            mkString(*state.allocAttr(vOutputs, state.sOutPath), j.second);
 
             /* This is only necessary when installing store paths, e.g.,
                `nix-env -i /nix/store/abcd...-foo'. */
-            store->addTempRoot(j->second);
-            store->ensurePath(j->second);
+            store->addTempRoot(j.second);
+            store->ensurePath(j.second);
 
-            references.insert(j->second);
+            references.insert(j.second);
         }
 
         // Copy the meta attributes.
         Value & vMeta = *state.allocAttr(v, state.sMeta);
         state.mkAttrs(vMeta, 16);
-        StringSet metaNames = i->queryMetaNames();
-        foreach (StringSet::iterator, j, metaNames) {
-            Value * v = i->queryMeta(*j);
+        StringSet metaNames = i.queryMetaNames();
+        for (auto & j : metaNames) {
+            Value * v = i.queryMeta(j);
             if (!v) continue;
-            vMeta.attrs->push_back(Attr(state.symbols.create(*j), v));
+            vMeta.attrs->push_back(Attr(state.symbols.create(j), v));
         }
         vMeta.attrs->sort();
         v.attrs->sort();
diff --git a/src/nix-instantiate/nix-instantiate.cc b/src/nix-instantiate/nix-instantiate.cc
index bea04180e5..b6845197ec 100644
--- a/src/nix-instantiate/nix-instantiate.cc
+++ b/src/nix-instantiate/nix-instantiate.cc
@@ -45,8 +45,8 @@ void processExpr(EvalState & state, const Strings & attrPaths,
     Value vRoot;
     state.eval(e, vRoot);
 
-    foreach (Strings::const_iterator, i, attrPaths) {
-        Value & v(*findAlongAttrPath(state, *i, autoArgs, vRoot));
+    for (auto & i : attrPaths) {
+        Value & v(*findAlongAttrPath(state, i, autoArgs, vRoot));
         state.forceValue(v);
 
         PathSet context;
@@ -67,11 +67,11 @@ void processExpr(EvalState & state, const Strings & attrPaths,
         } else {
             DrvInfos drvs;
             getDerivations(state, v, "", autoArgs, drvs, false);
-            foreach (DrvInfos::iterator, i, drvs) {
-                Path drvPath = i->queryDrvPath();
+            for (auto & i : drvs) {
+                Path drvPath = i.queryDrvPath();
 
                 /* What output do we want? */
-                string outputName = i->queryOutputName();
+                string outputName = i.queryOutputName();
                 if (outputName == "")
                     throw Error(format("derivation ‘%1%’ lacks an ‘outputName’ attribute ") % drvPath);
 
@@ -168,9 +168,9 @@ int main(int argc, char * * argv)
         if (attrPaths.empty()) attrPaths.push_back("");
 
         if (findFile) {
-            foreach (Strings::iterator, i, files) {
-                Path p = state.findFile(*i);
-                if (p == "") throw Error(format("unable to find ‘%1%’") % *i);
+            for (auto & i : files) {
+                Path p = state.findFile(i);
+                if (p == "") throw Error(format("unable to find ‘%1%’") % i);
                 std::cout << p << std::endl;
             }
             return;
diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc
index 434aefba48..2d2437c752 100644
--- a/src/nix-store/nix-store.cc
+++ b/src/nix-store/nix-store.cc
@@ -69,13 +69,13 @@ static PathSet realisePath(Path path, bool build = true)
         rootNr++;
 
         if (p.second.empty())
-            foreach (DerivationOutputs::iterator, i, drv.outputs) p.second.insert(i->first);
+            for (auto & i : drv.outputs) p.second.insert(i.first);
 
         PathSet outputs;
-        foreach (StringSet::iterator, j, p.second) {
-            DerivationOutputs::iterator i = drv.outputs.find(*j);
+        for (auto & j : p.second) {
+            DerivationOutputs::iterator i = drv.outputs.find(j);
             if (i == drv.outputs.end())
-                throw Error(format("derivation ‘%1%’ does not have an output named ‘%2%’") % p.first % *j);
+                throw Error(format("derivation ‘%1%’ does not have an output named ‘%2%’") % p.first % j);
             Path outPath = i->second.path;
             if (gcRoot == "")
                 printGCWarning();
@@ -113,16 +113,16 @@ static void opRealise(Strings opFlags, Strings opArgs)
     BuildMode buildMode = bmNormal;
     bool ignoreUnknown = false;
 
-    foreach (Strings::iterator, i, opFlags)
-        if (*i == "--dry-run") dryRun = true;
-        else if (*i == "--repair") buildMode = bmRepair;
-        else if (*i == "--check") buildMode = bmCheck;
-        else if (*i == "--ignore-unknown") ignoreUnknown = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--dry-run") dryRun = true;
+        else if (i == "--repair") buildMode = bmRepair;
+        else if (i == "--check") buildMode = bmCheck;
+        else if (i == "--ignore-unknown") ignoreUnknown = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     Paths paths;
-    foreach (Strings::iterator, i, opArgs) {
-        DrvPathWithOutputs p = parseDrvPathWithOutputs(*i);
+    for (auto & i : opArgs) {
+        DrvPathWithOutputs p = parseDrvPathWithOutputs(i);
         paths.push_back(makeDrvPathWithOutputs(followLinksToStorePath(p.first), p.second));
     }
 
@@ -133,8 +133,8 @@ static void opRealise(Strings opFlags, Strings opArgs)
 
     if (ignoreUnknown) {
         Paths paths2;
-        foreach (Paths::iterator, i, paths)
-            if (unknown.find(*i) == unknown.end()) paths2.push_back(*i);
+        for (auto & i : paths)
+            if (unknown.find(i) == unknown.end()) paths2.push_back(i);
         paths = paths2;
         unknown = PathSet();
     }
@@ -148,11 +148,11 @@ static void opRealise(Strings opFlags, Strings opArgs)
     store->buildPaths(PathSet(paths.begin(), paths.end()), buildMode);
 
     if (!ignoreUnknown)
-        foreach (Paths::iterator, i, paths) {
-            PathSet paths = realisePath(*i, false);
+        for (auto & i : paths) {
+            PathSet paths = realisePath(i, false);
             if (!noOutput)
-                foreach (PathSet::iterator, j, paths)
-                    cout << format("%1%\n") % *j;
+                for (auto & j : paths)
+                    cout << format("%1%\n") % j;
         }
 }
 
@@ -173,10 +173,9 @@ static void opAddFixed(Strings opFlags, Strings opArgs)
 {
     bool recursive = false;
 
-    for (Strings::iterator i = opFlags.begin();
-         i != opFlags.end(); ++i)
-        if (*i == "--recursive") recursive = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--recursive") recursive = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     if (opArgs.empty())
         throw UsageError("first argument must be hash algorithm");
@@ -194,10 +193,9 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs)
 {
     bool recursive = false;
 
-    for (Strings::iterator i = opFlags.begin();
-         i != opFlags.end(); ++i)
-        if (*i == "--recursive") recursive = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto i : opFlags)
+        if (i == "--recursive") recursive = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     if (opArgs.size() != 3)
         throw UsageError(format("‘--print-fixed-path’ requires three arguments"));
@@ -219,8 +217,8 @@ static PathSet maybeUseOutputs(const Path & storePath, bool useOutput, bool forc
     if (useOutput && isDerivation(storePath)) {
         Derivation drv = derivationFromPath(*store, storePath);
         PathSet outputs;
-        foreach (DerivationOutputs::iterator, i, drv.outputs)
-            outputs.insert(i->second.path);
+        for (auto & i : drv.outputs)
+            outputs.insert(i.second.path);
         return outputs;
     }
     else return singleton<PathSet>(storePath);
@@ -257,8 +255,8 @@ static void printTree(const Path & path,
     Paths sorted = topoSortPaths(*store, references);
     reverse(sorted.begin(), sorted.end());
 
-    foreach (Paths::iterator, i, sorted) {
-        Paths::iterator j = i; ++j;
+    for (auto i = sorted.begin(); i != sorted.end(); ++i) {
+        auto j = i; ++j;
         printTree(*i, tailPad + treeConn,
             j == sorted.end() ? tailPad + treeNull : tailPad + treeLine,
             done);
@@ -279,34 +277,34 @@ static void opQuery(Strings opFlags, Strings opArgs)
     bool forceRealise = false;
     string bindingName;
 
-    foreach (Strings::iterator, i, opFlags) {
+    for (auto & i : opFlags) {
         QueryType prev = query;
-        if (*i == "--outputs") query = qOutputs;
-        else if (*i == "--requisites" || *i == "-R") query = qRequisites;
-        else if (*i == "--references") query = qReferences;
-        else if (*i == "--referrers" || *i == "--referers") query = qReferrers;
-        else if (*i == "--referrers-closure" || *i == "--referers-closure") query = qReferrersClosure;
-        else if (*i == "--deriver" || *i == "-d") query = qDeriver;
-        else if (*i == "--binding" || *i == "-b") {
+        if (i == "--outputs") query = qOutputs;
+        else if (i == "--requisites" || i == "-R") query = qRequisites;
+        else if (i == "--references") query = qReferences;
+        else if (i == "--referrers" || i == "--referers") query = qReferrers;
+        else if (i == "--referrers-closure" || i == "--referers-closure") query = qReferrersClosure;
+        else if (i == "--deriver" || i == "-d") query = qDeriver;
+        else if (i == "--binding" || i == "-b") {
             if (opArgs.size() == 0)
                 throw UsageError("expected binding name");
             bindingName = opArgs.front();
             opArgs.pop_front();
             query = qBinding;
         }
-        else if (*i == "--hash") query = qHash;
-        else if (*i == "--size") query = qSize;
-        else if (*i == "--tree") query = qTree;
-        else if (*i == "--graph") query = qGraph;
-        else if (*i == "--xml") query = qXml;
-        else if (*i == "--resolve") query = qResolve;
-        else if (*i == "--roots") query = qRoots;
-        else if (*i == "--use-output" || *i == "-u") useOutput = true;
-        else if (*i == "--force-realise" || *i == "--force-realize" || *i == "-f") forceRealise = true;
-        else if (*i == "--include-outputs") includeOutputs = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+        else if (i == "--hash") query = qHash;
+        else if (i == "--size") query = qSize;
+        else if (i == "--tree") query = qTree;
+        else if (i == "--graph") query = qGraph;
+        else if (i == "--xml") query = qXml;
+        else if (i == "--resolve") query = qResolve;
+        else if (i == "--roots") query = qRoots;
+        else if (i == "--use-output" || i == "-u") useOutput = true;
+        else if (i == "--force-realise" || i == "--force-realize" || i == "-f") forceRealise = true;
+        else if (i == "--include-outputs") includeOutputs = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
         if (prev != qDefault && prev != query)
-            throw UsageError(format("query type ‘%1%’ conflicts with earlier flag") % *i);
+            throw UsageError(format("query type ‘%1%’ conflicts with earlier flag") % i);
     }
 
     if (query == qDefault) query = qOutputs;
@@ -316,12 +314,12 @@ static void opQuery(Strings opFlags, Strings opArgs)
     switch (query) {
 
         case qOutputs: {
-            foreach (Strings::iterator, i, opArgs) {
-                *i = followLinksToStorePath(*i);
-                if (forceRealise) realisePath(*i);
-                Derivation drv = derivationFromPath(*store, *i);
-                foreach (DerivationOutputs::iterator, j, drv.outputs)
-                    cout << format("%1%\n") % j->second.path;
+            for (auto & i : opArgs) {
+                i = followLinksToStorePath(i);
+                if (forceRealise) realisePath(i);
+                Derivation drv = derivationFromPath(*store, i);
+                for (auto & j : drv.outputs)
+                    cout << format("%1%\n") % j.second.path;
             }
             break;
         }
@@ -331,13 +329,13 @@ static void opQuery(Strings opFlags, Strings opArgs)
         case qReferrers:
         case qReferrersClosure: {
             PathSet paths;
-            foreach (Strings::iterator, i, opArgs) {
-                PathSet ps = maybeUseOutputs(followLinksToStorePath(*i), useOutput, forceRealise);
-                foreach (PathSet::iterator, j, ps) {
-                    if (query == qRequisites) computeFSClosure(*store, *j, paths, false, includeOutputs);
-                    else if (query == qReferences) store->queryReferences(*j, paths);
-                    else if (query == qReferrers) store->queryReferrers(*j, paths);
-                    else if (query == qReferrersClosure) computeFSClosure(*store, *j, paths, true);
+            for (auto & i : opArgs) {
+                PathSet ps = maybeUseOutputs(followLinksToStorePath(i), useOutput, forceRealise);
+                for (auto & j : ps) {
+                    if (query == qRequisites) computeFSClosure(*store, j, paths, false, includeOutputs);
+                    else if (query == qReferences) store->queryReferences(j, paths);
+                    else if (query == qReferrers) store->queryReferrers(j, paths);
+                    else if (query == qReferrersClosure) computeFSClosure(*store, j, paths, true);
                 }
             }
             Paths sorted = topoSortPaths(*store, paths);
@@ -348,16 +346,16 @@ static void opQuery(Strings opFlags, Strings opArgs)
         }
 
         case qDeriver:
-            foreach (Strings::iterator, i, opArgs) {
-                Path deriver = store->queryDeriver(followLinksToStorePath(*i));
+            for (auto & i : opArgs) {
+                Path deriver = store->queryDeriver(followLinksToStorePath(i));
                 cout << format("%1%\n") %
                     (deriver == "" ? "unknown-deriver" : deriver);
             }
             break;
 
         case qBinding:
-            foreach (Strings::iterator, i, opArgs) {
-                Path path = useDeriver(followLinksToStorePath(*i));
+            for (auto & i : opArgs) {
+                Path path = useDeriver(followLinksToStorePath(i));
                 Derivation drv = derivationFromPath(*store, path);
                 StringPairs::iterator j = drv.env.find(bindingName);
                 if (j == drv.env.end())
@@ -369,10 +367,10 @@ static void opQuery(Strings opFlags, Strings opArgs)
 
         case qHash:
         case qSize:
-            foreach (Strings::iterator, i, opArgs) {
-                PathSet paths = maybeUseOutputs(followLinksToStorePath(*i), useOutput, forceRealise);
-                foreach (PathSet::iterator, j, paths) {
-                    ValidPathInfo info = store->queryPathInfo(*j);
+            for (auto & i : opArgs) {
+                PathSet paths = maybeUseOutputs(followLinksToStorePath(i), useOutput, forceRealise);
+                for (auto & j : paths) {
+                    ValidPathInfo info = store->queryPathInfo(j);
                     if (query == qHash) {
                         assert(info.hash.type == htSHA256);
                         cout << format("sha256:%1%\n") % printHash32(info.hash);
@@ -384,15 +382,15 @@ static void opQuery(Strings opFlags, Strings opArgs)
 
         case qTree: {
             PathSet done;
-            foreach (Strings::iterator, i, opArgs)
-                printTree(followLinksToStorePath(*i), "", "", done);
+            for (auto & i : opArgs)
+                printTree(followLinksToStorePath(i), "", "", done);
             break;
         }
 
         case qGraph: {
             PathSet roots;
-            foreach (Strings::iterator, i, opArgs) {
-                PathSet paths = maybeUseOutputs(followLinksToStorePath(*i), useOutput, forceRealise);
+            for (auto & i : opArgs) {
+                PathSet paths = maybeUseOutputs(followLinksToStorePath(i), useOutput, forceRealise);
                 roots.insert(paths.begin(), paths.end());
             }
             printDotGraph(roots);
@@ -401,8 +399,8 @@ static void opQuery(Strings opFlags, Strings opArgs)
 
         case qXml: {
             PathSet roots;
-            foreach (Strings::iterator, i, opArgs) {
-                PathSet paths = maybeUseOutputs(followLinksToStorePath(*i), useOutput, forceRealise);
+            for (auto & i : opArgs) {
+                PathSet paths = maybeUseOutputs(followLinksToStorePath(i), useOutput, forceRealise);
                 roots.insert(paths.begin(), paths.end());
             }
             printXmlGraph(roots);
@@ -410,23 +408,23 @@ static void opQuery(Strings opFlags, Strings opArgs)
         }
 
         case qResolve: {
-            foreach (Strings::iterator, i, opArgs)
-                cout << format("%1%\n") % followLinksToStorePath(*i);
+            for (auto & i : opArgs)
+                cout << format("%1%\n") % followLinksToStorePath(i);
             break;
         }
 
         case qRoots: {
             PathSet referrers;
-            foreach (Strings::iterator, i, opArgs) {
-                PathSet paths = maybeUseOutputs(followLinksToStorePath(*i), useOutput, forceRealise);
-                foreach (PathSet::iterator, j, paths)
-                    computeFSClosure(*store, *j, referrers, true,
+            for (auto & i : opArgs) {
+                PathSet paths = maybeUseOutputs(followLinksToStorePath(i), useOutput, forceRealise);
+                for (auto & j : paths)
+                    computeFSClosure(*store, j, referrers, true,
                         settings.gcKeepOutputs, settings.gcKeepDerivations);
             }
             Roots roots = store->findRoots();
-            foreach (Roots::iterator, i, roots)
-                if (referrers.find(i->second) != referrers.end())
-                    cout << format("%1%\n") % i->first;
+            for (auto & i : roots)
+                if (referrers.find(i.second) != referrers.end())
+                    cout << format("%1%\n") % i.first;
             break;
         }
 
@@ -439,8 +437,8 @@ static void opQuery(Strings opFlags, Strings opArgs)
 static string shellEscape(const string & s)
 {
     string r;
-    foreach (string::const_iterator, i, s)
-        if (*i == '\'') r += "'\\''"; else r += *i;
+    for (auto & i : s)
+        if (i == '\'') r += "'\\''"; else r += i;
     return r;
 }
 
@@ -455,15 +453,17 @@ static void opPrintEnv(Strings opFlags, Strings opArgs)
 
     /* Print each environment variable in the derivation in a format
        that can be sourced by the shell. */
-    foreach (StringPairs::iterator, i, drv.env)
-        cout << format("export %1%; %1%='%2%'\n") % i->first % shellEscape(i->second);
+    for (auto & i : drv.env)
+        cout << format("export %1%; %1%='%2%'\n") % i.first % shellEscape(i.second);
 
     /* Also output the arguments.  This doesn't preserve whitespace in
        arguments. */
     cout << "export _args; _args='";
-    foreach (Strings::iterator, i, drv.args) {
-        if (i != drv.args.begin()) cout << ' ';
-        cout << shellEscape(*i);
+    bool first = true;
+    for (auto & i : drv.args) {
+        if (!first) cout << ' ';
+        first = false;
+        cout << shellEscape(i);
     }
     cout << "'\n";
 }
@@ -475,8 +475,8 @@ static void opReadLog(Strings opFlags, Strings opArgs)
 
     RunPager pager;
 
-    foreach (Strings::iterator, i, opArgs) {
-        Path path = useDeriver(followLinksToStorePath(*i));
+    for (auto & i : opArgs) {
+        Path path = useDeriver(followLinksToStorePath(i));
 
         string baseName = baseNameOf(path);
         bool found = false;
@@ -547,8 +547,8 @@ static void opDumpDB(Strings opFlags, Strings opArgs)
     if (!opArgs.empty())
         throw UsageError("no arguments expected");
     PathSet validPaths = store->queryAllValidPaths();
-    foreach (PathSet::iterator, i, validPaths)
-        cout << store->makeValidityRegistration(singleton<PathSet>(*i), true, true);
+    for (auto & i : validPaths)
+        cout << store->makeValidityRegistration(singleton<PathSet>(i), true, true);
 }
 
 
@@ -590,11 +590,10 @@ static void opRegisterValidity(Strings opFlags, Strings opArgs)
     bool reregister = false; // !!! maybe this should be the default
     bool hashGiven = false;
 
-    for (Strings::iterator i = opFlags.begin();
-         i != opFlags.end(); ++i)
-        if (*i == "--reregister") reregister = true;
-        else if (*i == "--hash-given") hashGiven = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--reregister") reregister = true;
+        else if (i == "--hash-given") hashGiven = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     if (!opArgs.empty()) throw UsageError("no arguments expected");
 
@@ -606,15 +605,12 @@ static void opCheckValidity(Strings opFlags, Strings opArgs)
 {
     bool printInvalid = false;
 
-    for (Strings::iterator i = opFlags.begin();
-         i != opFlags.end(); ++i)
-        if (*i == "--print-invalid") printInvalid = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--print-invalid") printInvalid = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
-    for (Strings::iterator i = opArgs.begin();
-         i != opArgs.end(); ++i)
-    {
-        Path path = followLinksToStorePath(*i);
+    for (auto & i : opArgs) {
+        Path path = followLinksToStorePath(i);
         if (!store->isValidPath(path)) {
             if (printInvalid)
                 cout << format("%1%\n") % path;
@@ -634,7 +630,7 @@ static void opGC(Strings opFlags, Strings opArgs)
     GCResults results;
 
     /* Do what? */
-    foreach (Strings::iterator, i, opFlags)
+    for (auto i = opFlags.begin(); i != opFlags.end(); ++i)
         if (*i == "--print-roots") printRoots = true;
         else if (*i == "--print-live") options.action = GCOptions::gcReturnLive;
         else if (*i == "--print-dead") options.action = GCOptions::gcReturnDead;
@@ -649,8 +645,8 @@ static void opGC(Strings opFlags, Strings opArgs)
 
     if (printRoots) {
         Roots roots = store->findRoots();
-        foreach (Roots::iterator, i, roots)
-            cout << i->first << " -> " << i->second << std::endl;
+        for (auto & i : roots)
+            cout << i.first << " -> " << i.second << std::endl;
     }
 
     else {
@@ -658,8 +654,8 @@ static void opGC(Strings opFlags, Strings opArgs)
         store->collectGarbage(options, results);
 
         if (options.action != GCOptions::gcDeleteDead)
-            foreach (PathSet::iterator, i, results.paths)
-                cout << *i << std::endl;
+            for (auto & i : results.paths)
+                cout << i << std::endl;
     }
 }
 
@@ -672,12 +668,12 @@ static void opDelete(Strings opFlags, Strings opArgs)
     GCOptions options;
     options.action = GCOptions::gcDeleteSpecific;
 
-    foreach (Strings::iterator, i, opFlags)
-        if (*i == "--ignore-liveness") options.ignoreLiveness = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--ignore-liveness") options.ignoreLiveness = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
-    foreach (Strings::iterator, i, opArgs)
-        options.pathsToDelete.insert(followLinksToStorePath(*i));
+    for (auto & i : opArgs)
+        options.pathsToDelete.insert(followLinksToStorePath(i));
 
     GCResults results;
     PrintFreed freed(true, results);
@@ -713,10 +709,9 @@ static void opRestore(Strings opFlags, Strings opArgs)
 static void opExport(Strings opFlags, Strings opArgs)
 {
     bool sign = false;
-    for (Strings::iterator i = opFlags.begin();
-         i != opFlags.end(); ++i)
-        if (*i == "--sign") sign = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--sign") sign = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     FdSink sink(STDOUT_FILENO);
     Paths sorted = topoSortPaths(*store, PathSet(opArgs.begin(), opArgs.end()));
@@ -728,17 +723,17 @@ static void opExport(Strings opFlags, Strings opArgs)
 static void opImport(Strings opFlags, Strings opArgs)
 {
     bool requireSignature = false;
-    foreach (Strings::iterator, i, opFlags)
-        if (*i == "--require-signature") requireSignature = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--require-signature") requireSignature = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     if (!opArgs.empty()) throw UsageError("no arguments expected");
 
     FdSource source(STDIN_FILENO);
     Paths paths = store->importPaths(requireSignature, source);
 
-    foreach (Paths::iterator, i, paths)
-        cout << format("%1%\n") % *i << std::flush;
+    for (auto & i : paths)
+        cout << format("%1%\n") % i << std::flush;
 }
 
 
@@ -762,11 +757,10 @@ static void opVerify(Strings opFlags, Strings opArgs)
     bool checkContents = false;
     bool repair = false;
 
-    for (Strings::iterator i = opFlags.begin();
-         i != opFlags.end(); ++i)
-        if (*i == "--check-contents") checkContents = true;
-        else if (*i == "--repair") repair = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--check-contents") checkContents = true;
+        else if (i == "--repair") repair = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     if (store->verifyStore(checkContents, repair)) {
         printMsg(lvlError, "warning: not all errors were fixed");
@@ -783,8 +777,8 @@ static void opVerifyPath(Strings opFlags, Strings opArgs)
 
     int status = 0;
 
-    foreach (Strings::iterator, i, opArgs) {
-        Path path = followLinksToStorePath(*i);
+    for (auto & i : opArgs) {
+        Path path = followLinksToStorePath(i);
         printMsg(lvlTalkative, format("checking path ‘%1%’...") % path);
         ValidPathInfo info = store->queryPathInfo(path);
         HashResult current = hashPath(info.hash.type, path);
@@ -807,8 +801,8 @@ static void opRepairPath(Strings opFlags, Strings opArgs)
     if (!opFlags.empty())
         throw UsageError("no flags expected");
 
-    foreach (Strings::iterator, i, opArgs) {
-        Path path = followLinksToStorePath(*i);
+    for (auto & i : opArgs) {
+        Path path = followLinksToStorePath(i);
         ensureLocalStore().repairPath(path);
     }
 }
@@ -828,8 +822,8 @@ static void opQueryFailedPaths(Strings opFlags, Strings opArgs)
     if (!opArgs.empty() || !opFlags.empty())
         throw UsageError("no arguments expected");
     PathSet failed = store->queryFailedPaths();
-    foreach (PathSet::iterator, i, failed)
-        cout << format("%1%\n") % *i;
+    for (auto & i : failed)
+        cout << format("%1%\n") % i;
 }
 
 
@@ -845,9 +839,9 @@ static void opClearFailedPaths(Strings opFlags, Strings opArgs)
 static void opServe(Strings opFlags, Strings opArgs)
 {
     bool writeAllowed = false;
-    foreach (Strings::iterator, i, opFlags)
-        if (*i == "--write") writeAllowed = true;
-        else throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        if (i == "--write") writeAllowed = true;
+        else throw UsageError(format("unknown flag ‘%1%’") % i);
 
     if (!opArgs.empty()) throw UsageError("no arguments expected");
 
@@ -919,10 +913,10 @@ static void opServe(Strings opFlags, Strings opArgs)
             case cmdQueryPathInfos: {
                 PathSet paths = readStorePaths<PathSet>(in);
                 // !!! Maybe we want a queryPathInfos?
-                foreach (PathSet::iterator, i, paths) {
-                    if (!store->isValidPath(*i))
+                for (auto & i : paths) {
+                    if (!store->isValidPath(i))
                         continue;
-                    ValidPathInfo info = store->queryPathInfo(*i);
+                    ValidPathInfo info = store->queryPathInfo(i);
                     writeString(info.path, out);
                     writeString(info.deriver, out);
                     writeStrings(info.references, out);
@@ -1012,8 +1006,8 @@ static void opServe(Strings opFlags, Strings opArgs)
 
 static void opGenerateBinaryCacheKey(Strings opFlags, Strings opArgs)
 {
-    foreach (Strings::iterator, i, opFlags)
-        throw UsageError(format("unknown flag ‘%1%’") % *i);
+    for (auto & i : opFlags)
+        throw UsageError(format("unknown flag ‘%1%’") % i);
 
     if (opArgs.size() != 3) throw UsageError("three arguments expected");
     auto i = opArgs.begin();