about summary refs log tree commit diff
path: root/third_party/nix
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@google.com>2020-05-20T21·27+0100
committerVincent Ambo <tazjin@google.com>2020-05-20T21·27+0100
commit689ef502f5b0655c9923ed77da2ae3504630f473 (patch)
tree3e331c153646f136875f047cc3b9f0aad8c86341 /third_party/nix
parentd331d3a0b5c497a46e2636f308234be66566c04c (diff)
refactor(3p/nix): Apply clang-tidy's readability-* fixes r/788
This applies the readability fixes listed here:

https://clang.llvm.org/extra/clang-tidy/checks/list.html
Diffstat (limited to 'third_party/nix')
-rw-r--r--third_party/nix/src/build-remote/build-remote.cc8
-rw-r--r--third_party/nix/src/libexpr/common-eval-args.cc3
-rw-r--r--third_party/nix/src/libexpr/eval.cc88
-rw-r--r--third_party/nix/src/libexpr/eval.hh4
-rw-r--r--third_party/nix/src/libexpr/get-drvs.cc42
-rw-r--r--third_party/nix/src/libexpr/json-to-value.cc11
-rw-r--r--third_party/nix/src/libexpr/names.cc25
-rw-r--r--third_party/nix/src/libexpr/nixexpr.cc14
-rw-r--r--third_party/nix/src/libexpr/primops.cc61
-rw-r--r--third_party/nix/src/libexpr/value-to-xml.cc2
-rw-r--r--third_party/nix/src/libmain/shared.cc21
-rw-r--r--third_party/nix/src/libmain/stack.cc6
-rw-r--r--third_party/nix/src/libstore/binary-cache-store.cc8
-rw-r--r--third_party/nix/src/libstore/build.cc115
-rw-r--r--third_party/nix/src/libstore/crypto.cc2
-rw-r--r--third_party/nix/src/libstore/crypto.hh4
-rw-r--r--third_party/nix/src/libstore/derivations.cc15
-rw-r--r--third_party/nix/src/libstore/download.cc33
-rw-r--r--third_party/nix/src/libstore/export-import.cc2
-rw-r--r--third_party/nix/src/libstore/gc.cc20
-rw-r--r--third_party/nix/src/libstore/globals.cc9
-rw-r--r--third_party/nix/src/libstore/globals.hh4
-rw-r--r--third_party/nix/src/libstore/legacy-ssh-store.cc16
-rw-r--r--third_party/nix/src/libstore/local-binary-cache-store.cc2
-rw-r--r--third_party/nix/src/libstore/local-fs-store.cc10
-rw-r--r--third_party/nix/src/libstore/local-store.cc71
-rw-r--r--third_party/nix/src/libstore/local-store.hh21
-rw-r--r--third_party/nix/src/libstore/machines.cc6
-rw-r--r--third_party/nix/src/libstore/misc.cc15
-rw-r--r--third_party/nix/src/libstore/nar-accessor.cc4
-rw-r--r--third_party/nix/src/libstore/nar-info-disk-cache.cc13
-rw-r--r--third_party/nix/src/libstore/nar-info.cc4
-rw-r--r--third_party/nix/src/libstore/optimise-store.cc16
-rw-r--r--third_party/nix/src/libstore/parsed-derivations.cc61
-rw-r--r--third_party/nix/src/libstore/pathlocks.cc5
-rw-r--r--third_party/nix/src/libstore/profiles.cc7
-rw-r--r--third_party/nix/src/libstore/remote-fs-accessor.cc8
-rw-r--r--third_party/nix/src/libstore/remote-store.cc60
-rw-r--r--third_party/nix/src/libstore/remote-store.hh2
-rw-r--r--third_party/nix/src/libstore/sqlite.cc9
-rw-r--r--third_party/nix/src/libstore/ssh.cc11
-rw-r--r--third_party/nix/src/libstore/store-api.cc51
-rw-r--r--third_party/nix/src/libstore/store-api.hh4
-rw-r--r--third_party/nix/src/libutil/archive.cc20
-rw-r--r--third_party/nix/src/libutil/args.cc18
-rw-r--r--third_party/nix/src/libutil/compression.cc48
-rw-r--r--third_party/nix/src/libutil/config.cc4
-rw-r--r--third_party/nix/src/libutil/hash.cc10
-rw-r--r--third_party/nix/src/libutil/json.cc6
-rw-r--r--third_party/nix/src/libutil/serialise.cc14
-rw-r--r--third_party/nix/src/libutil/thread-pool.cc10
-rw-r--r--third_party/nix/src/libutil/util.cc95
-rw-r--r--third_party/nix/src/libutil/util.hh4
-rw-r--r--third_party/nix/src/nix-build/nix-build.cc103
-rw-r--r--third_party/nix/src/nix-channel/nix-channel.cc4
-rw-r--r--third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc2
-rw-r--r--third_party/nix/src/nix-daemon/nix-daemon.cc64
-rw-r--r--third_party/nix/src/nix-env/nix-env.cc78
-rw-r--r--third_party/nix/src/nix-env/user-env.cc27
-rw-r--r--third_party/nix/src/nix-instantiate/nix-instantiate.cc6
-rw-r--r--third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc5
-rw-r--r--third_party/nix/src/nix-store/graphml.cc2
-rw-r--r--third_party/nix/src/nix-store/nix-store.cc80
-rw-r--r--third_party/nix/src/nix/build.cc4
-rw-r--r--third_party/nix/src/nix/command.cc5
-rw-r--r--third_party/nix/src/nix/doctor.cc8
-rw-r--r--third_party/nix/src/nix/installables.cc17
-rw-r--r--third_party/nix/src/nix/log.cc2
-rw-r--r--third_party/nix/src/nix/main.cc6
-rw-r--r--third_party/nix/src/nix/path-info.cc2
-rw-r--r--third_party/nix/src/nix/repl.cc60
-rw-r--r--third_party/nix/src/nix/run.cc8
-rw-r--r--third_party/nix/src/nix/search.cc15
-rw-r--r--third_party/nix/src/nix/show-derivation.cc2
-rw-r--r--third_party/nix/src/nix/sigs.cc4
-rw-r--r--third_party/nix/src/nix/upgrade-nix.cc6
-rw-r--r--third_party/nix/src/nix/verify.cc7
-rw-r--r--third_party/nix/src/nix/why-depends.cc6
78 files changed, 858 insertions, 787 deletions
diff --git a/third_party/nix/src/build-remote/build-remote.cc b/third_party/nix/src/build-remote/build-remote.cc
index 70776b132d14..2802b49ac8ea 100644
--- a/third_party/nix/src/build-remote/build-remote.cc
+++ b/third_party/nix/src/build-remote/build-remote.cc
@@ -40,7 +40,7 @@ static AutoCloseFD openSlotLock(const Machine& m, unsigned long long slot) {
 
 static bool allSupportedLocally(const std::set<std::string>& requiredFeatures) {
   for (auto& feature : requiredFeatures) {
-    if (!settings.systemFeatures.get().count(feature)) {
+    if (settings.systemFeatures.get().count(feature) == 0u) {
       return false;
     }
   }
@@ -60,7 +60,7 @@ static int _main(int argc, char* argv[]) {
     FdSource source(STDIN_FILENO);
 
     /* Read the parent's settings. */
-    while (readInt(source)) {
+    while (readInt(source) != 0u) {
       auto name = readString(source);
       auto value = readString(source);
       settings.set(name, value);
@@ -106,7 +106,7 @@ static int _main(int argc, char* argv[]) {
       auto requiredFeatures = readStrings<std::set<std::string>>(source);
 
       auto canBuildLocally =
-          amWilling &&
+          (amWilling != 0u) &&
           (neededSystem == settings.thisSystem ||
            settings.extraPlatforms.get().count(neededSystem) > 0) &&
           allSupportedLocally(requiredFeatures);
@@ -196,7 +196,7 @@ static int _main(int argc, char* argv[]) {
           if (hasPrefix(bestMachine->storeUri, "ssh://")) {
             storeParams["max-connections"] = "1";
             storeParams["log-fd"] = "4";
-            if (bestMachine->sshKey != "") {
+            if (!bestMachine->sshKey.empty()) {
               storeParams["ssh-key"] = bestMachine->sshKey;
             }
           }
diff --git a/third_party/nix/src/libexpr/common-eval-args.cc b/third_party/nix/src/libexpr/common-eval-args.cc
index 7af4d6b276db..7a87841c9b77 100644
--- a/third_party/nix/src/libexpr/common-eval-args.cc
+++ b/third_party/nix/src/libexpr/common-eval-args.cc
@@ -53,7 +53,8 @@ Path lookupFileArg(EvalState& state, string s) {
     CachedDownloadRequest request(s);
     request.unpack = true;
     return getDownloader()->downloadCached(state.store, request).path;
-  } else if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') {
+  }
+  if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') {
     Path p = s.substr(1, s.size() - 2);
     return state.findFile(p);
   } else {
diff --git a/third_party/nix/src/libexpr/eval.cc b/third_party/nix/src/libexpr/eval.cc
index 44f55dd68786..4be301167be9 100644
--- a/third_party/nix/src/libexpr/eval.cc
+++ b/third_party/nix/src/libexpr/eval.cc
@@ -37,7 +37,7 @@ static char* dupString(const char* s) {
 #else
   t = strdup(s);
 #endif
-  if (!t) {
+  if (t == nullptr) {
     throw std::bad_alloc();
   }
   return t;
@@ -62,7 +62,7 @@ static void printValue(std::ostream& str, std::set<const Value*>& active,
       break;
     case tString:
       str << "\"";
-      for (const char* i = v.string.s; *i; i++) {
+      for (const char* i = v.string.s; *i != 0; i++) {
         if (*i == '\"' || *i == '\\') {
           str << "\\" << *i;
         } else if (*i == '\n') {
@@ -151,7 +151,7 @@ string showType(const Value& v) {
     case tBool:
       return "a boolean";
     case tString:
-      return v.string.context ? "a string with context" : "a string";
+      return v.string.context != nullptr ? "a string with context" : "a string";
     case tPath:
       return "a path";
     case tNull:
@@ -194,12 +194,11 @@ static void* oomHandler(size_t requested) {
 static Symbol getName(const AttrName& name, EvalState& state, Env& env) {
   if (name.symbol.set()) {
     return name.symbol;
-  } else {
-    Value nameValue;
-    name.expr->eval(state, env, nameValue);
-    state.forceStringNoCtx(nameValue);
-    return state.symbols.create(nameValue.string.s);
   }
+  Value nameValue;
+  name.expr->eval(state, env, nameValue);
+  state.forceStringNoCtx(nameValue);
+  return state.symbols.create(nameValue.string.s);
 }
 
 static bool gcInitialised = false;
@@ -233,7 +232,7 @@ void initGC() {
      that GC_expand_hp() causes a lot of virtual, but not physical
      (resident) memory to be allocated.  This might be a problem on
      systems that don't overcommit. */
-  if (!getenv("GC_INITIAL_HEAP_SIZE")) {
+  if (getenv("GC_INITIAL_HEAP_SIZE") == nullptr) {
     size_t size = 32 * 1024 * 1024;
 #if HAVE_SYSCONF && defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
     size_t maxSize = 384 * 1024 * 1024;
@@ -436,7 +435,7 @@ void EvalState::checkURI(const std::string& uri) {
      'https://' as prefixes for any http/https URI. */
   for (auto& prefix : evalSettings.allowedUris.get()) {
     if (uri == prefix ||
-        (uri.size() > prefix.size() && prefix.size() > 0 &&
+        (uri.size() > prefix.size() && !prefix.empty() &&
          hasPrefix(uri, prefix) &&
          (prefix[prefix.size() - 1] == '/' || uri[prefix.size()] == '/'))) {
       return;
@@ -583,7 +582,7 @@ Value& mkString(Value& v, const string& s, const PathSet& context) {
 void mkPath(Value& v, const char* s) { mkPathNoCopy(v, dupString(s)); }
 
 inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) {
-  for (size_t l = var.level; l; --l, env = env->up) {
+  for (size_t l = var.level; l != 0u; --l, env = env->up) {
     ;
   }
 
@@ -603,16 +602,16 @@ inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) {
     }
     Bindings::iterator j = env->values[0]->attrs->find(var.name);
     if (j != env->values[0]->attrs->end()) {
-      if (countCalls && j->pos) {
+      if (countCalls && (j->pos != nullptr)) {
         attrSelects[*j->pos]++;
       }
       return j->value;
     }
-    if (!env->prevWith) {
+    if (env->prevWith == 0u) {
       throwUndefinedVarError("undefined variable '%1%' at %2%", var.name,
                              var.pos);
     }
-    for (size_t l = env->prevWith; l; --l, env = env->up) {
+    for (size_t l = env->prevWith; l != 0u; --l, env = env->up) {
       ;
     }
   }
@@ -657,7 +656,7 @@ void EvalState::mkList(Value& v, size_t size) {
     v.type = tListN;
     v.bigList.size = size;
     v.bigList.elems =
-        size ? (Value**)allocBytes(size * sizeof(Value*)) : nullptr;
+        size != 0u ? (Value**)allocBytes(size * sizeof(Value*)) : nullptr;
   }
   nrListElems += size;
 }
@@ -674,7 +673,7 @@ static inline void mkThunk(Value& v, Env& env, Expr* expr) {
 void EvalState::mkThunk_(Value& v, Expr* expr) { mkThunk(v, baseEnv, expr); }
 
 void EvalState::mkPos(Value& v, Pos* pos) {
-  if (pos && pos->file.set()) {
+  if ((pos != nullptr) && pos->file.set()) {
     mkAttrs(v, 3);
     mkString(*allocAttr(v, sFile), pos->file);
     mkInt(*allocAttr(v, sLine), pos->line);
@@ -701,7 +700,7 @@ Value* ExprVar::maybeThunk(EvalState& state, Env& env) {
   Value* v = state.lookupVar(&env, *this, true);
   /* The value might not be initialised in the environment yet.
      In that case, ignore it. */
-  if (v) {
+  if (v != nullptr) {
     nrAvoided++;
     return v;
   }
@@ -751,7 +750,7 @@ void EvalState::evalFile(const Path& path_, Value& v) {
     e = j->second;
   }
 
-  if (!e) {
+  if (e == nullptr) {
     e = parseExprFromFile(checkSourcePath(path2));
   }
 
@@ -966,7 +965,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
       nrLookups++;
       Bindings::iterator j;
       Symbol name = getName(i, state, env);
-      if (def) {
+      if (def != nullptr) {
         state.forceValue(*vAttrs, pos);
         if (vAttrs->type != tAttrs ||
             (j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) {
@@ -981,7 +980,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
       }
       vAttrs = j->value;
       pos2 = j->pos;
-      if (state.countCalls && pos2) {
+      if (state.countCalls && (pos2 != nullptr)) {
         state.attrSelects[*pos2]++;
       }
     }
@@ -989,7 +988,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
     state.forceValue(*vAttrs, (pos2 != nullptr ? *pos2 : this->pos));
 
   } catch (Error& e) {
-    if (pos2 && pos2->file != state.sDerivationNix) {
+    if ((pos2 != nullptr) && pos2->file != state.sDerivationNix) {
       addErrorPrefix(e, "while evaluating the attribute '%1%' at %2%:\n",
                      showAttrPath(state, env, attrPath), *pos2);
     }
@@ -1013,9 +1012,8 @@ void ExprOpHasAttr::eval(EvalState& state, Env& env, Value& v) {
         (j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) {
       mkBool(v, false);
       return;
-    } else {
-      vAttrs = j->value;
     }
+    vAttrs = j->value;
   }
 
   mkBool(v, true);
@@ -1133,7 +1131,7 @@ void EvalState::callFunction(Value& fun, Value& arg, Value& v, const Pos& pos) {
     for (auto& i : lambda.formals->formals) {
       Bindings::iterator j = arg.attrs->find(i.name);
       if (j == arg.attrs->end()) {
-        if (!i.def) {
+        if (i.def == nullptr) {
           throwTypeError("%1% called without required argument '%2%', at %3%",
                          lambda, i.name, pos);
         }
@@ -1209,7 +1207,7 @@ void EvalState::autoCallFunction(Bindings& args, Value& fun, Value& res) {
     Bindings::iterator j = args.find(i.name);
     if (j != args.end()) {
       actualArgs->attrs->push_back(*j);
-    } else if (!i.def) {
+    } else if (i.def == nullptr) {
       throwTypeError(
           "cannot auto-call a function that has an argument without a default "
           "value ('%1%')",
@@ -1278,17 +1276,18 @@ void ExprOpImpl::eval(EvalState& state, Env& env, Value& v) {
 }
 
 void ExprOpUpdate::eval(EvalState& state, Env& env, Value& v) {
-  Value v1, v2;
+  Value v1;
+  Value v2;
   state.evalAttrs(env, e1, v1);
   state.evalAttrs(env, e2, v2);
 
   state.nrOpUpdates++;
 
-  if (v1.attrs->size() == 0) {
+  if (v1.attrs->empty()) {
     v = v2;
     return;
   }
-  if (v2.attrs->size() == 0) {
+  if (v2.attrs->empty()) {
     v = v1;
     return;
   }
@@ -1341,12 +1340,12 @@ void EvalState::concatLists(Value& v, size_t nrLists, Value** lists,
     forceList(*lists[n], pos);
     auto l = lists[n]->listSize();
     len += l;
-    if (l) {
+    if (l != 0u) {
       nonEmpty = lists[n];
     }
   }
 
-  if (nonEmpty && len == nonEmpty->listSize()) {
+  if ((nonEmpty != nullptr) && len == nonEmpty->listSize()) {
     v = *nonEmpty;
     return;
   }
@@ -1355,7 +1354,7 @@ void EvalState::concatLists(Value& v, size_t nrLists, Value** lists,
   auto out = v.listElems();
   for (size_t n = 0, pos = 0; n < nrLists; ++n) {
     auto l = lists[n]->listSize();
-    if (l) {
+    if (l != 0u) {
       memcpy(out + pos, lists[n]->listElems(), l * sizeof(Value*));
     }
     pos += l;
@@ -1479,7 +1478,8 @@ NixFloat EvalState::forceFloat(Value& v, const Pos& pos) {
   forceValue(v, pos);
   if (v.type == tInt) {
     return v.integer;
-  } else if (v.type != tFloat) {
+  }
+  if (v.type != tFloat) {
     throwTypeError("value is %1% while a float was expected, at %2%", v, pos);
   }
   return v.fpoint;
@@ -1520,8 +1520,8 @@ string EvalState::forceString(Value& v, const Pos& pos) {
 }
 
 void copyContext(const Value& v, PathSet& context) {
-  if (v.string.context) {
-    for (const char** p = v.string.context; *p; ++p) {
+  if (v.string.context != nullptr) {
+    for (const char** p = v.string.context; *p != nullptr; ++p) {
       context.insert(*p);
     }
   }
@@ -1535,7 +1535,7 @@ string EvalState::forceString(Value& v, PathSet& context, const Pos& pos) {
 
 string EvalState::forceStringNoCtx(Value& v, const Pos& pos) {
   string s = forceString(v, pos);
-  if (v.string.context) {
+  if (v.string.context != nullptr) {
     if (pos) {
       throwEvalError(
           "the string '%1%' is not allowed to refer to a store path (such as "
@@ -1657,7 +1657,7 @@ string EvalState::copyPathToStore(PathSet& context, const Path& path) {
   }
 
   Path dstPath;
-  if (srcToStore[path] != "") {
+  if (!srcToStore[path].empty()) {
     dstPath = srcToStore[path];
   } else {
     dstPath =
@@ -1678,7 +1678,7 @@ string EvalState::copyPathToStore(PathSet& context, const Path& path) {
 
 Path EvalState::coerceToPath(const Pos& pos, Value& v, PathSet& context) {
   string path = coerceToString(pos, v, context, false, false);
-  if (path == "" || path[0] != '/') {
+  if (path.empty() || path[0] != '/') {
     throwEvalError("string '%1%' doesn't represent an absolute path, at %2%",
                    path, pos);
   }
@@ -1754,7 +1754,8 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
       }
 
       /* Otherwise, compare the attributes one by one. */
-      Bindings::iterator i, j;
+      Bindings::iterator i;
+      Bindings::iterator j;
       for (i = v1.attrs->begin(), j = v2.attrs->begin(); i != v1.attrs->end();
            ++i, ++j) {
         if (i->name != j->name || !eqValues(*i->value, *j->value)) {
@@ -1796,7 +1797,8 @@ void EvalState::printStats() {
       nrAttrsets * sizeof(Bindings) + nrAttrsInAttrsets * sizeof(Attr);
 
 #if HAVE_BOEHMGC
-  GC_word heapSize, totalBytes;
+  GC_word heapSize;
+  GC_word totalBytes;
   GC_get_heap_usage_safe(&heapSize, nullptr, nullptr, nullptr, &totalBytes);
 #endif
   if (showStats) {
@@ -1927,8 +1929,8 @@ size_t valueSize(Value& v) {
     switch (v.type) {
       case tString:
         sz += doString(v.string.s);
-        if (v.string.context) {
-          for (const char** p = v.string.context; *p; ++p) {
+        if (v.string.context != nullptr) {
+          for (const char** p = v.string.context; *p != nullptr; ++p) {
             sz += doString(*p);
           }
         }
@@ -1993,13 +1995,13 @@ size_t valueSize(Value& v) {
 
     if (env.type != Env::HasWithExpr) {
       for (size_t i = 0; i < env.size; ++i) {
-        if (env.values[i]) {
+        if (env.values[i] != nullptr) {
           sz += doValue(*env.values[i]);
         }
       }
     }
 
-    if (env.up) {
+    if (env.up != nullptr) {
       sz += doEnv(*env.up);
     }
 
diff --git a/third_party/nix/src/libexpr/eval.hh b/third_party/nix/src/libexpr/eval.hh
index a74bd2dfd3f9..48c67b62295d 100644
--- a/third_party/nix/src/libexpr/eval.hh
+++ b/third_party/nix/src/libexpr/eval.hh
@@ -257,9 +257,9 @@ class EvalState {
 
   Value* allocAttr(Value& vAttrs, const Symbol& name);
 
-  Bindings* allocBindings(size_t capacity);
+  static Bindings* allocBindings(size_t capacity);
 
-  void mkList(Value& v, size_t length);
+  void mkList(Value& v, size_t size);
   void mkAttrs(Value& v, size_t capacity);
   void mkThunk_(Value& v, Expr* expr);
   void mkPos(Value& v, Pos* pos);
diff --git a/third_party/nix/src/libexpr/get-drvs.cc b/third_party/nix/src/libexpr/get-drvs.cc
index aa73c01fd1f2..c4afc0fb45eb 100644
--- a/third_party/nix/src/libexpr/get-drvs.cc
+++ b/third_party/nix/src/libexpr/get-drvs.cc
@@ -45,7 +45,7 @@ DrvInfo::DrvInfo(EvalState& state, ref<Store> store,
 }
 
 string DrvInfo::queryName() const {
-  if (name == "" && attrs) {
+  if (name.empty() && (attrs != nullptr)) {
     auto i = attrs->find(state->sName);
     if (i == attrs->end()) {
       throw TypeError("derivation name missing");
@@ -56,7 +56,7 @@ string DrvInfo::queryName() const {
 }
 
 string DrvInfo::querySystem() const {
-  if (system == "" && attrs) {
+  if (system.empty() && (attrs != nullptr)) {
     auto i = attrs->find(state->sSystem);
     system = i == attrs->end() ? "unknown"
                                : state->forceStringNoCtx(*i->value, *i->pos);
@@ -65,7 +65,7 @@ string DrvInfo::querySystem() const {
 }
 
 string DrvInfo::queryDrvPath() const {
-  if (drvPath == "" && attrs) {
+  if (drvPath.empty() && (attrs != nullptr)) {
     Bindings::iterator i = attrs->find(state->sDrvPath);
     PathSet context;
     drvPath = i != attrs->end()
@@ -76,7 +76,7 @@ string DrvInfo::queryDrvPath() const {
 }
 
 string DrvInfo::queryOutPath() const {
-  if (outPath == "" && attrs) {
+  if (outPath.empty() && (attrs != nullptr)) {
     Bindings::iterator i = attrs->find(state->sOutPath);
     PathSet context;
     outPath = i != attrs->end()
@@ -90,7 +90,8 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
   if (outputs.empty()) {
     /* Get the ‘outputs’ list. */
     Bindings::iterator i;
-    if (attrs && (i = attrs->find(state->sOutputs)) != attrs->end()) {
+    if ((attrs != nullptr) &&
+        (i = attrs->find(state->sOutputs)) != attrs->end()) {
       state->forceList(*i->value, *i->pos);
 
       /* For each output... */
@@ -117,13 +118,13 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
       outputs["out"] = queryOutPath();
     }
   }
-  if (!onlyOutputsToInstall || !attrs) {
+  if (!onlyOutputsToInstall || (attrs == nullptr)) {
     return outputs;
   }
 
   /* Check for `meta.outputsToInstall` and return `outputs` reduced to that. */
   const Value* outTI = queryMeta("outputsToInstall");
-  if (!outTI) {
+  if (outTI == nullptr) {
     return outputs;
   }
   const auto errMsg = Error("this derivation has bad 'meta.outputsToInstall'");
@@ -147,7 +148,7 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
 }
 
 string DrvInfo::queryOutputName() const {
-  if (outputName == "" && attrs) {
+  if (outputName.empty() && (attrs != nullptr)) {
     Bindings::iterator i = attrs->find(state->sOutputName);
     outputName = i != attrs->end() ? state->forceStringNoCtx(*i->value) : "";
   }
@@ -155,10 +156,10 @@ string DrvInfo::queryOutputName() const {
 }
 
 Bindings* DrvInfo::getMeta() {
-  if (meta) {
+  if (meta != nullptr) {
     return meta;
   }
-  if (!attrs) {
+  if (attrs == nullptr) {
     return nullptr;
   }
   Bindings::iterator a = attrs->find(state->sMeta);
@@ -172,7 +173,7 @@ Bindings* DrvInfo::getMeta() {
 
 StringSet DrvInfo::queryMetaNames() {
   StringSet res;
-  if (!getMeta()) {
+  if (getMeta() == nullptr) {
     return res;
   }
   for (auto& i : *meta) {
@@ -190,7 +191,8 @@ bool DrvInfo::checkMeta(Value& v) {
       }
     }
     return true;
-  } else if (v.type == tAttrs) {
+  }
+  if (v.type == tAttrs) {
     Bindings::iterator i = v.attrs->find(state->sOutPath);
     if (i != v.attrs->end()) {
       return false;
@@ -208,7 +210,7 @@ bool DrvInfo::checkMeta(Value& v) {
 }
 
 Value* DrvInfo::queryMeta(const string& name) {
-  if (!getMeta()) {
+  if (getMeta() == nullptr) {
     return nullptr;
   }
   Bindings::iterator a = meta->find(state->symbols.create(name));
@@ -220,7 +222,7 @@ Value* DrvInfo::queryMeta(const string& name) {
 
 string DrvInfo::queryMetaString(const string& name) {
   Value* v = queryMeta(name);
-  if (!v || v->type != tString) {
+  if ((v == nullptr) || v->type != tString) {
     return "";
   }
   return v->string.s;
@@ -228,7 +230,7 @@ string DrvInfo::queryMetaString(const string& name) {
 
 NixInt DrvInfo::queryMetaInt(const string& name, NixInt def) {
   Value* v = queryMeta(name);
-  if (!v) {
+  if (v == nullptr) {
     return def;
   }
   if (v->type == tInt) {
@@ -247,7 +249,7 @@ NixInt DrvInfo::queryMetaInt(const string& name, NixInt def) {
 
 NixFloat DrvInfo::queryMetaFloat(const string& name, NixFloat def) {
   Value* v = queryMeta(name);
-  if (!v) {
+  if (v == nullptr) {
     return def;
   }
   if (v->type == tFloat) {
@@ -266,7 +268,7 @@ NixFloat DrvInfo::queryMetaFloat(const string& name, NixFloat def) {
 
 bool DrvInfo::queryMetaBool(const string& name, bool def) {
   Value* v = queryMeta(name);
-  if (!v) {
+  if (v == nullptr) {
     return def;
   }
   if (v->type == tBool) {
@@ -288,16 +290,16 @@ bool DrvInfo::queryMetaBool(const string& name, bool def) {
 void DrvInfo::setMeta(const string& name, Value* v) {
   getMeta();
   Bindings* old = meta;
-  meta = state->allocBindings(1 + (old ? old->size() : 0));
+  meta = state->allocBindings(1 + (old != nullptr ? old->size() : 0));
   Symbol sym = state->symbols.create(name);
-  if (old) {
+  if (old != nullptr) {
     for (auto i : *old) {
       if (i.name != sym) {
         meta->push_back(i);
       }
     }
   }
-  if (v) {
+  if (v != nullptr) {
     meta->push_back(Attr(sym, v));
   }
   meta->sort();
diff --git a/third_party/nix/src/libexpr/json-to-value.cc b/third_party/nix/src/libexpr/json-to-value.cc
index 122bd2ad3147..68f016904ef7 100644
--- a/third_party/nix/src/libexpr/json-to-value.cc
+++ b/third_party/nix/src/libexpr/json-to-value.cc
@@ -16,7 +16,7 @@ static string parseJSONString(const char*& s) {
     throw JSONParseError("expected JSON string");
   }
   while (*s != '"') {
-    if (!*s) {
+    if (*s == 0) {
       throw JSONParseError("got end-of-string in JSON string");
     }
     if (*s == '\\') {
@@ -57,7 +57,7 @@ static string parseJSONString(const char*& s) {
 static void parseJSON(EvalState& state, const char*& s, Value& v) {
   skipWhitespace(s);
 
-  if (!*s) {
+  if (*s == 0) {
     throw JSONParseError("expected JSON value");
   }
 
@@ -127,12 +127,13 @@ static void parseJSON(EvalState& state, const char*& s, Value& v) {
     mkString(v, parseJSONString(s));
   }
 
-  else if (isdigit(*s) || *s == '-' || *s == '.') {
+  else if ((isdigit(*s) != 0) || *s == '-' || *s == '.') {
     // Buffer into a string first, then use built-in C++ conversions
     std::string tmp_number;
     ValueType number_type = tInt;
 
-    while (isdigit(*s) || *s == '-' || *s == '.' || *s == 'e' || *s == 'E') {
+    while ((isdigit(*s) != 0) || *s == '-' || *s == '.' || *s == 'e' ||
+           *s == 'E') {
       if (*s == '.' || *s == 'e' || *s == 'E') {
         number_type = tFloat;
       }
@@ -176,7 +177,7 @@ void parseJSON(EvalState& state, const string& s_, Value& v) {
   const char* s = s_.c_str();
   parseJSON(state, s, v);
   skipWhitespace(s);
-  if (*s) {
+  if (*s != 0) {
     throw JSONParseError(
         format("expected end-of-string while parsing JSON value: %1%") % s);
   }
diff --git a/third_party/nix/src/libexpr/names.cc b/third_party/nix/src/libexpr/names.cc
index ecad90c960af..f559c13a6115 100644
--- a/third_party/nix/src/libexpr/names.cc
+++ b/third_party/nix/src/libexpr/names.cc
@@ -17,7 +17,7 @@ DrvName::DrvName(const string& s) : hits(0) {
   name = fullName = s;
   for (unsigned int i = 0; i < s.size(); ++i) {
     /* !!! isalpha/isdigit are affected by the locale. */
-    if (s[i] == '-' && i + 1 < s.size() && !isalpha(s[i + 1])) {
+    if (s[i] == '-' && i + 1 < s.size() && (isalpha(s[i + 1]) == 0)) {
       name = string(s, 0, i);
       version = string(s, i + 1);
       break;
@@ -34,10 +34,7 @@ bool DrvName::matches(DrvName& n) {
       return false;
     }
   }
-  if (version != "" && version != n.version) {
-    return false;
-  }
-  return true;
+  return !(!version.empty() && version != n.version);
 }
 
 string nextComponent(string::const_iterator& p,
@@ -55,12 +52,12 @@ string nextComponent(string::const_iterator& p,
      of digits.  Otherwise, consume the longest sequence of
      non-digit, non-separator characters. */
   string s;
-  if (isdigit(*p)) {
-    while (p != end && isdigit(*p)) {
+  if (isdigit(*p) != 0) {
+    while (p != end && (isdigit(*p) != 0)) {
       s += *p++;
     }
   } else {
-    while (p != end && (!isdigit(*p) && *p != '.' && *p != '-')) {
+    while (p != end && ((isdigit(*p) == 0) && *p != '.' && *p != '-')) {
       s += *p++;
     }
   }
@@ -69,12 +66,15 @@ string nextComponent(string::const_iterator& p,
 }
 
 static bool componentsLT(const string& c1, const string& c2) {
-  int n1, n2;
-  bool c1Num = string2Int(c1, n1), c2Num = string2Int(c2, n2);
+  int n1;
+  int n2;
+  bool c1Num = string2Int(c1, n1);
+  bool c2Num = string2Int(c2, n2);
 
   if (c1Num && c2Num) {
     return n1 < n2;
-  } else if (c1 == "" && c2Num) {
+  }
+  if (c1.empty() && c2Num) {
     return true;
   } else if (c1 == "pre" && c2 != "pre") {
     return true;
@@ -99,7 +99,8 @@ int compareVersions(const string& v1, const string& v2) {
     string c2 = nextComponent(p2, v2.end());
     if (componentsLT(c1, c2)) {
       return -1;
-    } else if (componentsLT(c2, c1)) {
+    }
+    if (componentsLT(c2, c1)) {
       return 1;
     }
   }
diff --git a/third_party/nix/src/libexpr/nixexpr.cc b/third_party/nix/src/libexpr/nixexpr.cc
index 55b9d545778c..22be923404a0 100644
--- a/third_party/nix/src/libexpr/nixexpr.cc
+++ b/third_party/nix/src/libexpr/nixexpr.cc
@@ -73,7 +73,7 @@ void ExprVar::show(std::ostream& str) const { str << name; }
 
 void ExprSelect::show(std::ostream& str) const {
   str << "(" << *e << ")." << showAttrPath(attrPath);
-  if (def) {
+  if (def != nullptr) {
     str << " or (" << *def << ")";
   }
 }
@@ -121,7 +121,7 @@ void ExprLambda::show(std::ostream& str) const {
         str << ", ";
       }
       str << i.name;
-      if (i.def) {
+      if (i.def != nullptr) {
         str << " ? " << *i.def;
       }
     }
@@ -233,7 +233,8 @@ void ExprVar::bindVars(const StaticEnv& env) {
   const StaticEnv* curEnv;
   unsigned int level;
   int withLevel = -1;
-  for (curEnv = &env, level = 0; curEnv; curEnv = curEnv->up, level++) {
+  for (curEnv = &env, level = 0; curEnv != nullptr;
+       curEnv = curEnv->up, level++) {
     if (curEnv->isWith) {
       if (withLevel == -1) {
         withLevel = level;
@@ -263,7 +264,7 @@ void ExprVar::bindVars(const StaticEnv& env) {
 
 void ExprSelect::bindVars(const StaticEnv& env) {
   e->bindVars(env);
-  if (def) {
+  if (def != nullptr) {
     def->bindVars(env);
   }
   for (auto& i : attrPath) {
@@ -332,7 +333,7 @@ void ExprLambda::bindVars(const StaticEnv& env) {
     }
 
     for (auto& i : formals->formals) {
-      if (i.def) {
+      if (i.def != nullptr) {
         i.def->bindVars(newEnv);
       }
     }
@@ -363,7 +364,8 @@ void ExprWith::bindVars(const StaticEnv& env) {
   const StaticEnv* curEnv;
   unsigned int level;
   prevWith = 0;
-  for (curEnv = &env, level = 1; curEnv; curEnv = curEnv->up, level++) {
+  for (curEnv = &env, level = 1; curEnv != nullptr;
+       curEnv = curEnv->up, level++) {
     if (curEnv->isWith) {
       prevWith = level;
       break;
diff --git a/third_party/nix/src/libexpr/primops.cc b/third_party/nix/src/libexpr/primops.cc
index d576d4b61905..7b73bec03525 100644
--- a/third_party/nix/src/libexpr/primops.cc
+++ b/third_party/nix/src/libexpr/primops.cc
@@ -37,9 +37,8 @@ std::pair<string, string> decodeContext(const string& s) {
     size_t index = s.find("!", 1);
     return std::pair<string, string>(string(s, index + 1),
                                      string(s, 1, index - 1));
-  } else {
-    return std::pair<string, string>(s.at(0) == '/' ? s : string(s, 1), "");
   }
+  return std::pair<string, string>(s.at(0) == '/' ? s : string(s, 1), "");
 }
 
 InvalidPathError::InvalidPathError(const Path& path)
@@ -83,8 +82,11 @@ void EvalState::realiseContext(const PathSet& context) {
   }
 
   /* For performance, prefetch all substitute info. */
-  PathSet willBuild, willSubstitute, unknown;
-  unsigned long long downloadSize, narSize;
+  PathSet willBuild;
+  PathSet willSubstitute;
+  PathSet unknown;
+  unsigned long long downloadSize;
+  unsigned long long narSize;
   store->queryMissing(drvs, willBuild, willSubstitute, unknown, downloadSize,
                       narSize);
   store->buildPaths(drvs);
@@ -181,22 +183,21 @@ void prim_importNative(EvalState& state, const Pos& pos, Value** args,
   string sym = state.forceStringNoCtx(*args[1], pos);
 
   void* handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL);
-  if (!handle) {
+  if (handle == nullptr) {
     throw EvalError(format("could not open '%1%': %2%") % path % dlerror());
   }
 
   dlerror();
   auto func = (ValueInitializer)dlsym(handle, sym.c_str());
-  if (!func) {
+  if (func == nullptr) {
     char* message = dlerror();
-    if (message) {
+    if (message != nullptr) {
       throw EvalError(format("could not load symbol '%1%' from '%2%': %3%") %
                       sym % path % message);
-    } else {
-      throw EvalError(format("symbol '%1%' from '%2%' resolved to NULL when a "
-                             "function pointer was expected") %
-                      sym % path);
     }
+    throw EvalError(format("symbol '%1%' from '%2%' resolved to NULL when a "
+                           "function pointer was expected") %
+                    sym % path);
   }
 
   (func)(state, v);
@@ -765,11 +766,11 @@ static void prim_derivationStrict(EvalState& state, const Pos& pos,
   }
 
   /* Do we have all required attributes? */
-  if (drv.builder == "") {
+  if (drv.builder.empty()) {
     throw EvalError(format("required attribute 'builder' missing, at %1%") %
                     posDrvName);
   }
-  if (drv.platform == "") {
+  if (drv.platform.empty()) {
     throw EvalError(format("required attribute 'system' missing, at %1%") %
                     posDrvName);
   }
@@ -822,7 +823,7 @@ static void prim_derivationStrict(EvalState& state, const Pos& pos,
     Hash h = hashDerivationModulo(*state.store, drv);
 
     for (auto& i : drv.outputs) {
-      if (i.second.path == "") {
+      if (i.second.path.empty()) {
         Path outPath = state.store->makeOutputPath(i.first, h, drvName);
         if (!jsonObject) {
           drv.env[i.first] = outPath;
@@ -1134,7 +1135,7 @@ static void addPath(EvalState& state, const Pos& pos, const string& name,
   const auto path = evalSettings.pureEval && expectedHash
                         ? path_
                         : state.checkSourcePath(path_);
-  PathFilter filter = filterFun ? ([&](const Path& path) {
+  PathFilter filter = filterFun != nullptr ? ([&](const Path& path) {
     auto st = lstat(path);
 
     /* Call the filter function.  The first argument is the path,
@@ -1159,7 +1160,7 @@ static void addPath(EvalState& state, const Pos& pos, const string& name,
 
     return state.forceBool(res, pos);
   })
-                                : defaultPathFilter;
+                                           : defaultPathFilter;
 
   Path expectedStorePath;
   if (expectedHash) {
@@ -1305,7 +1306,7 @@ void prim_getAttr(EvalState& state, const Pos& pos, Value** args, Value& v) {
     throw EvalError(format("attribute '%1%' missing, at %2%") % attr % pos);
   }
   // !!! add to stack trace?
-  if (state.countCalls && i->pos) {
+  if (state.countCalls && (i->pos != nullptr)) {
     state.attrSelects[*i->pos]++;
   }
   state.forceValue(*i->value);
@@ -1485,7 +1486,7 @@ static void prim_functionArgs(EvalState& state, const Pos& pos, Value** args,
   state.mkAttrs(v, args[0]->lambda.fun->formals->formals.size());
   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 != nullptr);
   }
   v.attrs->sort();
 }
@@ -1634,7 +1635,7 @@ static void prim_foldlStrict(EvalState& state, const Pos& pos, Value** args,
   state.forceFunction(*args[0], pos);
   state.forceList(*args[2], pos);
 
-  if (args[2]->listSize()) {
+  if (args[2]->listSize() != 0u) {
     Value* vCur = args[1];
 
     for (unsigned int n = 0; n < args[2]->listSize(); ++n) {
@@ -1716,7 +1717,8 @@ static void prim_sort(EvalState& state, const Pos& pos, Value** args,
       return CompareValues()(a, b);
     }
 
-    Value vTmp1, vTmp2;
+    Value vTmp1;
+    Value vTmp2;
     state.callFunction(*args[0], *a, vTmp1, pos);
     state.callFunction(vTmp1, *b, vTmp2, pos);
     return state.forceBool(vTmp2, pos);
@@ -1735,7 +1737,8 @@ static void prim_partition(EvalState& state, const Pos& pos, Value** args,
 
   auto len = args[1]->listSize();
 
-  ValueVector right, wrong;
+  ValueVector right;
+  ValueVector wrong;
 
   for (unsigned int n = 0; n < len; ++n) {
     auto vElem = args[1]->listElems()[n];
@@ -1754,14 +1757,14 @@ static void prim_partition(EvalState& state, const Pos& pos, Value** args,
   Value* vRight = state.allocAttr(v, state.sRight);
   auto rsize = right.size();
   state.mkList(*vRight, rsize);
-  if (rsize) {
+  if (rsize != 0u) {
     memcpy(vRight->listElems(), right.data(), sizeof(Value*) * rsize);
   }
 
   Value* vWrong = state.allocAttr(v, state.sWrong);
   auto wsize = wrong.size();
   state.mkList(*vWrong, wsize);
-  if (wsize) {
+  if (wsize != 0u) {
     memcpy(vWrong->listElems(), wrong.data(), sizeof(Value*) * wsize);
   }
 
@@ -1790,7 +1793,7 @@ static void prim_concatMap(EvalState& state, const Pos& pos, Value** args,
   auto out = v.listElems();
   for (unsigned int n = 0, pos = 0; n < nrLists; ++n) {
     auto l = lists[n].listSize();
-    if (l) {
+    if (l != 0u) {
       memcpy(out + pos, lists[n].listElems(), l * sizeof(Value*));
     }
     pos += l;
@@ -1971,9 +1974,8 @@ static void prim_match(EvalState& state, const Pos& pos, Value** args,
       // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
       throw EvalError("memory limit exceeded by regular expression '%s', at %s",
                       re, pos);
-    } else {
-      throw EvalError("invalid regular expression '%s', at %s", re, pos);
     }
+    throw EvalError("invalid regular expression '%s', at %s", re, pos);
   }
 }
 
@@ -2039,9 +2041,8 @@ static void prim_split(EvalState& state, const Pos& pos, Value** args,
       // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
       throw EvalError("memory limit exceeded by regular expression '%s', at %s",
                       re, pos);
-    } else {
-      throw EvalError("invalid regular expression '%s', at %s", re, pos);
     }
+    throw EvalError("invalid regular expression '%s', at %s", re, pos);
   }
 }
 
@@ -2246,7 +2247,7 @@ static void prim_fetchTarball(EvalState& state, const Pos& pos, Value** args,
 RegisterPrimOp::PrimOps* RegisterPrimOp::primOps;
 
 RegisterPrimOp::RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun) {
-  if (!primOps) {
+  if (primOps == nullptr) {
     primOps = new PrimOps;
   }
   primOps->emplace_back(name, arity, fun);
@@ -2444,7 +2445,7 @@ void EvalState::createBaseEnv() {
   }
   addConstant("__nixPath", v);
 
-  if (RegisterPrimOp::primOps) {
+  if (RegisterPrimOp::primOps != nullptr) {
     for (auto& primOp : *RegisterPrimOp::primOps) {
       addPrimOp(std::get<0>(primOp), std::get<1>(primOp), std::get<2>(primOp));
     }
diff --git a/third_party/nix/src/libexpr/value-to-xml.cc b/third_party/nix/src/libexpr/value-to-xml.cc
index 44dede487541..7fab6e2ffe5e 100644
--- a/third_party/nix/src/libexpr/value-to-xml.cc
+++ b/third_party/nix/src/libexpr/value-to-xml.cc
@@ -111,7 +111,7 @@ static void printValueAsXML(EvalState& state, bool strict, bool location,
 
         XMLOpenElement _(doc, "derivation", xmlAttrs);
 
-        if (drvPath != "" && drvsSeen.find(drvPath) == drvsSeen.end()) {
+        if (!drvPath.empty() && drvsSeen.find(drvPath) == drvsSeen.end()) {
           drvsSeen.insert(drvPath);
           showAttrs(state, strict, location, *v.attrs, doc, context, drvsSeen);
         } else {
diff --git a/third_party/nix/src/libmain/shared.cc b/third_party/nix/src/libmain/shared.cc
index 8ff7cebbee4d..5c2084691144 100644
--- a/third_party/nix/src/libmain/shared.cc
+++ b/third_party/nix/src/libmain/shared.cc
@@ -37,8 +37,11 @@ void printGCWarning() {
 }
 
 void printMissing(ref<Store> store, const PathSet& paths) {
-  unsigned long long downloadSize, narSize;
-  PathSet willBuild, willSubstitute, unknown;
+  unsigned long long downloadSize;
+  unsigned long long narSize;
+  PathSet willBuild;
+  PathSet willSubstitute;
+  PathSet unknown;
   store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize,
                       narSize);
   printMissing(store, willBuild, willSubstitute, unknown, downloadSize,
@@ -129,13 +132,13 @@ void initNix() {
   sigemptyset(&act.sa_mask);
   act.sa_handler = SIG_DFL;
   act.sa_flags = 0;
-  if (sigaction(SIGCHLD, &act, nullptr)) {
+  if (sigaction(SIGCHLD, &act, nullptr) != 0) {
     throw SysError("resetting SIGCHLD");
   }
 
   /* Install a dummy SIGUSR1 handler for use with pthread_kill(). */
   act.sa_handler = sigHandler;
-  if (sigaction(SIGUSR1, &act, nullptr)) {
+  if (sigaction(SIGUSR1, &act, nullptr) != 0) {
     throw SysError("handling SIGUSR1");
   }
 
@@ -319,7 +322,7 @@ int handleExceptions(const string& programName, std::function<void()> fun) {
     return 1;
   } catch (BaseError& e) {
     LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg();
-    if (e.prefix() != "" && !settings.showTrace) {
+    if (!e.prefix().empty() && !settings.showTrace) {
       LOG(INFO) << "(use '--show-trace' to show detailed location information)";
     }
     return e.status;
@@ -335,11 +338,11 @@ int handleExceptions(const string& programName, std::function<void()> fun) {
 }
 
 RunPager::RunPager() {
-  if (!isatty(STDOUT_FILENO)) {
+  if (isatty(STDOUT_FILENO) == 0) {
     return;
   }
   char* pager = getenv("NIX_PAGER");
-  if (!pager) {
+  if (pager == nullptr) {
     pager = getenv("PAGER");
   }
   if (pager && ((string)pager == "" || (string)pager == "cat")) {
@@ -353,11 +356,11 @@ RunPager::RunPager() {
     if (dup2(toPager.readSide.get(), STDIN_FILENO) == -1) {
       throw SysError("dupping stdin");
     }
-    if (!getenv("LESS")) {
+    if (getenv("LESS") == nullptr) {
       setenv("LESS", "FRSXMK", 1);
     }
     restoreSignals();
-    if (pager) {
+    if (pager != nullptr) {
       execl("/bin/sh", "sh", "-c", pager, nullptr);
     }
     execlp("pager", "pager", nullptr);
diff --git a/third_party/nix/src/libmain/stack.cc b/third_party/nix/src/libmain/stack.cc
index 87018b975c29..f100b39156e4 100644
--- a/third_party/nix/src/libmain/stack.cc
+++ b/third_party/nix/src/libmain/stack.cc
@@ -40,7 +40,7 @@ static void sigsegvHandler(int signo, siginfo_t* info, void* ctx) {
   sigfillset(&act.sa_mask);
   act.sa_handler = SIG_DFL;
   act.sa_flags = 0;
-  if (sigaction(SIGSEGV, &act, nullptr)) {
+  if (sigaction(SIGSEGV, &act, nullptr) != 0) {
     abort();
   }
 }
@@ -54,7 +54,7 @@ void detectStackOverflow() {
   stack.ss_size = 4096 * 4 + MINSIGSTKSZ;
   static auto stackBuf = std::make_unique<std::vector<char>>(stack.ss_size);
   stack.ss_sp = stackBuf->data();
-  if (!stack.ss_sp) {
+  if (stack.ss_sp == nullptr) {
     throw Error("cannot allocate alternative stack");
   }
   stack.ss_flags = 0;
@@ -66,7 +66,7 @@ void detectStackOverflow() {
   sigfillset(&act.sa_mask);
   act.sa_sigaction = sigsegvHandler;
   act.sa_flags = SA_SIGINFO | SA_ONSTACK;
-  if (sigaction(SIGSEGV, &act, nullptr)) {
+  if (sigaction(SIGSEGV, &act, nullptr) != 0) {
     throw SysError("resetting SIGSEGV");
   }
 #endif
diff --git a/third_party/nix/src/libstore/binary-cache-store.cc b/third_party/nix/src/libstore/binary-cache-store.cc
index bed4e717eb2f..b0d8c81d80e4 100644
--- a/third_party/nix/src/libstore/binary-cache-store.cc
+++ b/third_party/nix/src/libstore/binary-cache-store.cc
@@ -120,7 +120,7 @@ void BinaryCacheStore::addToStore(const ValidPathInfo& info,
                                   const ref<std::string>& nar,
                                   RepairFlag repair, CheckSigsFlag checkSigs,
                                   std::shared_ptr<FSAccessor> accessor) {
-  if (!repair && isValidPath(info.path)) {
+  if ((repair == 0u) && isValidPath(info.path)) {
     return;
   }
 
@@ -206,7 +206,7 @@ void BinaryCacheStore::addToStore(const ValidPathInfo& info,
                                       : compression == "bzip2"
                                             ? ".bz2"
                                             : compression == "br" ? ".br" : "");
-  if (repair || !fileExists(narInfo->url)) {
+  if ((repair != 0u) || !fileExists(narInfo->url)) {
     stats.narWrite++;
     upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
   } else {
@@ -323,7 +323,7 @@ Path BinaryCacheStore::addTextToStore(const string& name, const string& s,
   info.path = computeStorePathForText(name, s, references);
   info.references = references;
 
-  if (repair || !isValidPath(info.path)) {
+  if ((repair != 0u) || !isValidPath(info.path)) {
     StringSink sink;
     dumpString(s, sink);
     addToStore(info, sink.s, repair, CheckSigs, nullptr);
@@ -362,7 +362,7 @@ std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const Path& path) {
     try {
       auto info = queryPathInfo(path);
       // FIXME: add a "Log" field to .narinfo
-      if (info->deriver == "") {
+      if (info->deriver.empty()) {
         return nullptr;
       }
       drvPath = info->deriver;
diff --git a/third_party/nix/src/libstore/build.cc b/third_party/nix/src/libstore/build.cc
index efc1e5a1263e..389c99f06c01 100644
--- a/third_party/nix/src/libstore/build.cc
+++ b/third_party/nix/src/libstore/build.cc
@@ -458,7 +458,7 @@ void handleDiffHook(uid_t uid, uid_t gid, Path tryA, Path tryB, Path drvPath,
                             statusToString(diffRes.first)));
       }
 
-      if (diffRes.second != "") {
+      if (!diffRes.second.empty()) {
         LOG(ERROR) << chomp(diffRes.second);
       }
     } catch (Error& error) {
@@ -512,7 +512,7 @@ UserLock::UserLock() {
 
   /* Get the members of the build-users-group. */
   struct group* gr = getgrnam(settings.buildUsersGroup.get().c_str());
-  if (!gr) {
+  if (gr == nullptr) {
     throw Error(
         format(
             "the group '%1%' specified in 'build-users-group' does not exist") %
@@ -522,7 +522,7 @@ UserLock::UserLock() {
 
   /* Copy the result of getgrnam. */
   Strings users;
-  for (char** p = gr->gr_mem; *p; ++p) {
+  for (char** p = gr->gr_mem; *p != nullptr; ++p) {
     DLOG(INFO) << "found build user " << *p;
     users.push_back(*p);
   }
@@ -538,7 +538,7 @@ UserLock::UserLock() {
     DLOG(INFO) << "trying user " << i;
 
     struct passwd* pw = getpwnam(i.c_str());
-    if (!pw) {
+    if (pw == nullptr) {
       throw Error(format("the user '%1%' in the group '%2%' does not exist") %
                   i % settings.buildUsersGroup);
     }
@@ -550,7 +550,7 @@ UserLock::UserLock() {
 
     {
       auto lockedPaths(lockedPaths_.lock());
-      if (lockedPaths->count(fnUserLock)) {
+      if (lockedPaths->count(fnUserLock) != 0u) {
         /* We already have a lock on this one. */
         continue;
       }
@@ -937,7 +937,7 @@ class DerivationGoal : public Goal {
   /* Run the builder's process. */
   void runChild();
 
-  friend int childEntry(void*);
+  friend int childEntry(void* /*arg*/);
 
   /* Check that the derivation outputs all exist and register them
      as valid. */
@@ -1149,7 +1149,7 @@ void DerivationGoal::haveDerivation() {
   PathSet invalidOutputs = checkPathValidity(false, buildMode == bmRepair);
 
   /* If they are all valid, then we're done. */
-  if (invalidOutputs.size() == 0 && buildMode == bmNormal) {
+  if (invalidOutputs.empty() && buildMode == bmNormal) {
     done(BuildResult::AlreadyValid);
     return;
   }
@@ -1297,7 +1297,7 @@ void DerivationGoal::repairClosure() {
     LOG(ERROR) << "found corrupted or missing path '" << i
                << "' in the output closure of '" << drvPath << "'";
     Path drvPath2 = outputsToDrv[i];
-    if (drvPath2 == "") {
+    if (drvPath2.empty()) {
       addWaitee(worker.makeSubstitutionGoal(i, Repair));
     } else {
       addWaitee(worker.makeDerivationGoal(drvPath2, PathSet(), bmRepair));
@@ -1676,7 +1676,7 @@ MakeError(NotDeterministic, BuildError)
         }
 
         ~LogSink() override {
-          if (currentLine != "") {
+          if (!currentLine.empty()) {
             currentLine += '\n';
             flushLine();
           }
@@ -1733,7 +1733,7 @@ MakeError(NotDeterministic, BuildError)
     }
 
     else {
-      st = dynamic_cast<NotDeterministic*>(&e)
+      st = dynamic_cast<NotDeterministic*>(&e) != nullptr
                ? BuildResult::NotDeterministic
                : statusOk(status)
                      ? BuildResult::OutputRejected
@@ -1774,17 +1774,17 @@ HookReply DerivationGoal::tryBuildHook() {
       if (string(s, 0, 2) == "# ") {
         reply = string(s, 2);
         break;
-      } else {
-        s += "\n";
-        std::cerr << s;
       }
+      s += "\n";
+      std::cerr << s;
     }
 
     DLOG(INFO) << "hook reply is " << reply;
 
     if (reply == "decline") {
       return rpDecline;
-    } else if (reply == "decline-permanently") {
+    }
+    if (reply == "decline-permanently") {
       worker.tryBuildHook = false;
       worker.hook = nullptr;
       return rpDecline;
@@ -1799,9 +1799,8 @@ HookReply DerivationGoal::tryBuildHook() {
                  << chomp(drainFD(worker.hook->fromHook.readSide.get()));
       worker.hook = nullptr;
       return rpDecline;
-    } else {
-      throw;
     }
+    throw;
   }
 
   hook = std::move(worker.hook);
@@ -1854,7 +1853,7 @@ PathSet DerivationGoal::exportReferences(PathSet storePaths) {
 
     storePath = worker.store.toStorePath(storePath);
 
-    if (!inputPaths.count(storePath)) {
+    if (inputPaths.count(storePath) == 0u) {
       throw BuildError(
           "cannot export references of path '%s' because it is not in the "
           "input closure of the derivation",
@@ -1897,7 +1896,7 @@ static void preloadNSS() {
 
     if (getaddrinfo("this.pre-initializes.the.dns.resolvers.invalid.", "http",
                     nullptr, &res) != 0) {
-      if (res) {
+      if (res != nullptr) {
         freeaddrinfo(res);
       }
     }
@@ -2167,7 +2166,7 @@ void DerivationGoal::startBuilder() {
     for (auto& i : inputPaths) {
       Path r = worker.store.toRealPath(i);
       struct stat st;
-      if (lstat(r.c_str(), &st)) {
+      if (lstat(r.c_str(), &st) != 0) {
         throw SysError(format("getting attributes of path '%1%'") % i);
       }
       if (S_ISDIR(st.st_mode)) {
@@ -2222,7 +2221,7 @@ void DerivationGoal::startBuilder() {
        corresponding to the valid outputs, and rewrite the
        contents of the new outputs to replace the dummy strings
        with the actual hashes. */
-    if (validPaths.size() > 0) {
+    if (!validPaths.empty()) {
       for (auto& i : validPaths) {
         addHashRewrite(i);
       }
@@ -2241,7 +2240,7 @@ void DerivationGoal::startBuilder() {
   }
 
   if (useChroot && settings.preBuildHook != "" &&
-      dynamic_cast<Derivation*>(drv.get())) {
+      (dynamic_cast<Derivation*>(drv.get()) != nullptr)) {
     DLOG(INFO) << "executing pre-build hook '" << settings.preBuildHook << "'";
     auto args =
         useChroot ? Strings({drvPath, chrootRootDir}) : Strings({drvPath});
@@ -2260,7 +2259,7 @@ void DerivationGoal::startBuilder() {
           throw Error(format("unknown pre-build hook command '%1%'") % line);
         }
       } else if (state == stExtraChrootDirs) {
-        if (line == "") {
+        if (line.empty()) {
           state = stBegin;
         } else {
           auto p = line.find('=');
@@ -2291,15 +2290,15 @@ void DerivationGoal::startBuilder() {
   std::string slaveName(ptsname(builderOut.readSide.get()));
 
   if (buildUser) {
-    if (chmod(slaveName.c_str(), 0600)) {
+    if (chmod(slaveName.c_str(), 0600) != 0) {
       throw SysError("changing mode of pseudoterminal slave");
     }
 
-    if (chown(slaveName.c_str(), buildUser->getUID(), 0)) {
+    if (chown(slaveName.c_str(), buildUser->getUID(), 0) != 0) {
       throw SysError("changing owner of pseudoterminal slave");
     }
   } else {
-    if (grantpt(builderOut.readSide.get())) {
+    if (grantpt(builderOut.readSide.get()) != 0) {
       throw SysError("granting access to pseudoterminal slave");
     }
   }
@@ -2311,7 +2310,7 @@ void DerivationGoal::startBuilder() {
         dirsInChroot[slaveName] = {slaveName, false};
 #endif
 
-  if (unlockpt(builderOut.readSide.get())) {
+  if (unlockpt(builderOut.readSide.get()) != 0) {
     throw SysError("unlocking pseudoterminal");
   }
 
@@ -2322,13 +2321,13 @@ void DerivationGoal::startBuilder() {
 
   // Put the pt into raw mode to prevent \n -> \r\n translation.
   struct termios term;
-  if (tcgetattr(builderOut.writeSide.get(), &term)) {
+  if (tcgetattr(builderOut.writeSide.get(), &term) != 0) {
     throw SysError("getting pseudoterminal attributes");
   }
 
   cfmakeraw(&term);
 
-  if (tcsetattr(builderOut.writeSide.get(), TCSANOW, &term)) {
+  if (tcsetattr(builderOut.writeSide.get(), TCSANOW, &term) != 0) {
     throw SysError("putting pseudoterminal into raw mode");
   }
 
@@ -2750,7 +2749,7 @@ void setupSeccomp() {
 #if HAVE_SECCOMP
   scmp_filter_ctx ctx;
 
-  if (!(ctx = seccomp_init(SCMP_ACT_ALLOW))) {
+  if ((ctx = seccomp_init(SCMP_ACT_ALLOW)) == nullptr) {
     throw SysError("unable to initialize seccomp mode 2");
   }
 
@@ -2911,7 +2910,7 @@ void DerivationGoal::runChild() {
         createDirs(chrootRootDir + "/dev/shm");
         createDirs(chrootRootDir + "/dev/pts");
         ss.push_back("/dev/full");
-        if (settings.systemFeatures.get().count("kvm") &&
+        if ((settings.systemFeatures.get().count("kvm") != 0u) &&
             pathExists("/dev/kvm")) {
           ss.push_back("/dev/kvm");
         }
@@ -2960,9 +2959,8 @@ void DerivationGoal::runChild() {
         if (stat(source.c_str(), &st) == -1) {
           if (optional && errno == ENOENT) {
             return;
-          } else {
-            throw SysError("getting attributes of path '%1%'", source);
           }
+          throw SysError("getting attributes of path '%1%'", source);
         }
         if (S_ISDIR(st.st_mode)) {
           createDirs(target);
@@ -3005,7 +3003,7 @@ void DerivationGoal::runChild() {
          if /dev/ptx/ptmx exists). */
       if (pathExists("/dev/pts/ptmx") &&
           !pathExists(chrootRootDir + "/dev/ptmx") &&
-          !dirsInChroot.count("/dev/pts")) {
+          (dirsInChroot.count("/dev/pts") == 0u)) {
         if (mount("none", (chrootRootDir + "/dev/pts").c_str(), "devpts", 0,
                   "newinstance,mode=0620") == 0) {
           createSymlink("/dev/pts/ptmx", chrootRootDir + "/dev/ptmx");
@@ -3078,8 +3076,8 @@ void DerivationGoal::runChild() {
     uname(&utsbuf);
     if (drv->platform == "i686-linux" &&
         (settings.thisSystem == "x86_64-linux" ||
-         (!strcmp(utsbuf.sysname, "Linux") &&
-          !strcmp(utsbuf.machine, "x86_64")))) {
+         ((strcmp(utsbuf.sysname, "Linux") == 0) &&
+          (strcmp(utsbuf.machine, "x86_64") == 0)))) {
       if (personality(PER_LINUX32) == -1) {
         throw SysError("cannot set i686-linux personality");
       }
@@ -3422,7 +3420,7 @@ void DerivationGoal::registerOutputs() {
           pathExists(redirected)) {
         replaceValidPath(path, redirected);
       }
-      if (buildMode == bmCheck && redirected != "") {
+      if (buildMode == bmCheck && !redirected.empty()) {
         actualPath = redirected;
       }
     }
@@ -3442,7 +3440,7 @@ void DerivationGoal::registerOutputs() {
        that means that someone else can have interfered with the
        build.  Also, the output should be owned by the build
        user. */
-    if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) ||
+    if ((!S_ISLNK(st.st_mode) && ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0u)) ||
         (buildUser && st.st_uid != buildUser->getUID())) {
       throw BuildError(format("suspicious ownership or permission on '%1%'; "
                               "rejecting this build output") %
@@ -3555,7 +3553,7 @@ void DerivationGoal::registerOutputs() {
         if (settings.runDiffHook || settings.keepFailed) {
           Path dst = worker.store.toRealPath(path + checkSuffix);
           deletePath(dst);
-          if (rename(actualPath.c_str(), dst.c_str())) {
+          if (rename(actualPath.c_str(), dst.c_str()) != 0) {
             throw SysError(format("renaming '%1%' to '%2%'") % actualPath %
                            dst);
           }
@@ -3568,11 +3566,10 @@ void DerivationGoal::registerOutputs() {
               format("derivation '%1%' may not be deterministic: output '%2%' "
                      "differs from '%3%'") %
               drvPath % path % dst);
-        } else {
-          throw NotDeterministic(format("derivation '%1%' may not be "
-                                        "deterministic: output '%2%' differs") %
-                                 drvPath % path);
         }
+        throw NotDeterministic(format("derivation '%1%' may not be "
+                                      "deterministic: output '%2%' differs") %
+                               drvPath % path);
       }
 
       /* Since we verified the build, it's now ultimately
@@ -3665,7 +3662,7 @@ void DerivationGoal::registerOutputs() {
       Path prev = i.second.path + checkSuffix;
       deletePath(prev);
       Path dst = i.second.path + checkSuffix;
-      if (rename(i.second.path.c_str(), dst.c_str())) {
+      if (rename(i.second.path.c_str(), dst.c_str()) != 0) {
         throw SysError(format("renaming '%1%' to '%2%'") % i.second.path % dst);
       }
     }
@@ -3791,11 +3788,11 @@ void DerivationGoal::checkOutputs(
 
         for (auto& i : used) {
           if (allowed) {
-            if (!spec.count(i)) {
+            if (spec.count(i) == 0u) {
               badPaths.insert(i);
             }
           } else {
-            if (spec.count(i)) {
+            if (spec.count(i) != 0u) {
               badPaths.insert(i);
             }
           }
@@ -3889,7 +3886,7 @@ Path DerivationGoal::openLogFile() {
   string baseName = baseNameOf(drvPath);
 
   /* Create a log file. */
-  Path dir = fmt("%s/%s/%s/", worker.store.logDir, worker.store.drvsLogDir,
+  Path dir = fmt("%s/%s/%s/", worker.store.logDir, nix::LocalStore::drvsLogDir,
                  string(baseName, 0, 2));
   createDirs(dir);
 
@@ -3927,7 +3924,7 @@ void DerivationGoal::closeLogFile() {
 }
 
 void DerivationGoal::deleteTmpDir(bool force) {
-  if (tmpDir != "") {
+  if (!tmpDir.empty()) {
     /* Don't keep temporary directories for builtins because they
        might have privileged stuff (like a copy of netrc). */
     if (settings.keepFailed && !force && !drv->isBuiltin()) {
@@ -4165,7 +4162,7 @@ void SubstitutionGoal::init() {
   worker.store.addTempRoot(storePath);
 
   /* If the path already exists we're done. */
-  if (!repair && worker.store.isValidPath(storePath)) {
+  if ((repair == 0u) && worker.store.isValidPath(storePath)) {
     amDone(ecSuccess);
     return;
   }
@@ -4186,7 +4183,7 @@ void SubstitutionGoal::init() {
 void SubstitutionGoal::tryNext() {
   trace("trying next substituter");
 
-  if (subs.size() == 0) {
+  if (subs.empty()) {
     /* None left.  Terminate this goal and let someone else deal
        with it. */
     DLOG(WARNING)
@@ -4241,7 +4238,7 @@ void SubstitutionGoal::tryNext() {
       worker.expectedNarSize, info->narSize);
 
   maintainExpectedDownload =
-      narInfo && narInfo->fileSize
+      narInfo && (narInfo->fileSize != 0u)
           ? std::make_unique<MaintainCount<uint64_t>>(
                 worker.expectedDownloadSize, narInfo->fileSize)
           : nullptr;
@@ -4250,7 +4247,8 @@ void SubstitutionGoal::tryNext() {
      signature. LocalStore::addToStore() also checks for this, but
      only after we've downloaded the path. */
   if (worker.store.requireSigs && !sub->isTrusted &&
-      !info->checkSignatures(worker.store, worker.store.getPublicKeys())) {
+      (info->checkSignatures(worker.store, worker.store.getPublicKeys()) ==
+       0u)) {
     LOG(WARNING) << "substituter '" << sub->getUri()
                  << "' does not have a valid signature for path '" << storePath
                  << "'";
@@ -4804,10 +4802,10 @@ unsigned int Worker::exitStatus() {
     mask |= 0x08;  // 104
   }
 
-  if (mask) {
+  if (mask != 0u) {
     mask |= 0x60;
   }
-  return mask ? mask : 1;
+  return mask != 0u ? mask : 1;
 }
 
 bool Worker::pathContentsGood(const Path& path) {
@@ -4839,8 +4837,11 @@ void Worker::markContentsGood(const Path& path) {
 //////////////////////////////////////////////////////////////////////
 
 static void primeCache(Store& store, const PathSet& paths) {
-  PathSet willBuild, willSubstitute, unknown;
-  unsigned long long downloadSize, narSize;
+  PathSet willBuild;
+  PathSet willSubstitute;
+  PathSet unknown;
+  unsigned long long downloadSize;
+  unsigned long long narSize;
   store.queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize,
                      narSize);
 
@@ -4876,7 +4877,7 @@ void LocalStore::buildPaths(const PathSet& drvPaths, BuildMode buildMode) {
   for (auto& i : goals) {
     if (i->getExitCode() != Goal::ecSuccess) {
       auto* i2 = dynamic_cast<DerivationGoal*>(i.get());
-      if (i2) {
+      if (i2 != nullptr) {
         failed.insert(i2->getDrvPath());
       } else {
         failed.insert(dynamic_cast<SubstitutionGoal*>(i.get())->getStorePath());
@@ -4939,7 +4940,7 @@ void LocalStore::repairPath(const Path& path) {
     /* Since substituting the path didn't work, if we have a valid
        deriver, then rebuild the deriver. */
     auto deriver = queryPathInfo(path)->deriver;
-    if (deriver != "" && isValidPath(deriver)) {
+    if (!deriver.empty() && isValidPath(deriver)) {
       goals.clear();
       goals.insert(worker.makeDerivationGoal(deriver, StringSet(), bmRepair));
       worker.run(goals);
diff --git a/third_party/nix/src/libstore/crypto.cc b/third_party/nix/src/libstore/crypto.cc
index f26cabdf6dc7..2fbc30fb3161 100644
--- a/third_party/nix/src/libstore/crypto.cc
+++ b/third_party/nix/src/libstore/crypto.cc
@@ -23,7 +23,7 @@ Key::Key(const string& s) {
   name = ss.first;
   key = ss.second;
 
-  if (name == "" || key == "") {
+  if (name.empty() || key.empty()) {
     throw Error("secret key is corrupt");
   }
 
diff --git a/third_party/nix/src/libstore/crypto.hh b/third_party/nix/src/libstore/crypto.hh
index 637099231dc0..ef578db6d055 100644
--- a/third_party/nix/src/libstore/crypto.hh
+++ b/third_party/nix/src/libstore/crypto.hh
@@ -24,13 +24,13 @@ struct SecretKey : Key {
   SecretKey(const std::string& s);
 
   /* Return a detached signature of the given string. */
-  std::string signDetached(const std::string& s) const;
+  std::string signDetached(const std::string& data) const;
 
   PublicKey toPublicKey() const;
 };
 
 struct PublicKey : Key {
-  PublicKey(const std::string& data);
+  PublicKey(const std::string& s);
 
  private:
   PublicKey(const std::string& name, const std::string& key) : Key(name, key) {}
diff --git a/third_party/nix/src/libstore/derivations.cc b/third_party/nix/src/libstore/derivations.cc
index 2955056e06ea..029c14640b7a 100644
--- a/third_party/nix/src/libstore/derivations.cc
+++ b/third_party/nix/src/libstore/derivations.cc
@@ -90,7 +90,7 @@ static string parseString(std::istream& str) {
 
 static Path parsePath(std::istream& str) {
   string s = parseString(str);
-  if (s.size() == 0 || s[0] != '/') {
+  if (s.empty() || s[0] != '/') {
     throw FormatError(format("bad path '%1%' in derivation") % s);
   }
   return s;
@@ -197,7 +197,7 @@ Derivation Store::derivationFromPath(const Path& drvPath) {
 
 static void printString(string& res, const string& s) {
   res += '"';
-  for (const char* i = s.c_str(); *i; i++) {
+  for (const char* i = s.c_str(); *i != 0; i++) {
     if (*i == '\"' || *i == '\\') {
       res += "\\";
       res += *i;
@@ -303,7 +303,7 @@ bool isDerivation(const string& fileName) {
 
 bool BasicDerivation::isFixedOutput() const {
   return outputs.size() == 1 && outputs.begin()->first == "out" &&
-         outputs.begin()->second.hash != "";
+         !outputs.begin()->second.hash.empty();
 }
 
 DrvHashes drvHashes;
@@ -356,10 +356,11 @@ Hash hashDerivationModulo(Store& store, Derivation drv) {
 
 DrvPathWithOutputs parseDrvPathWithOutputs(const string& s) {
   size_t n = s.find("!");
-  return n == s.npos ? DrvPathWithOutputs(s, std::set<string>())
-                     : DrvPathWithOutputs(string(s, 0, n),
-                                          tokenizeString<std::set<string> >(
-                                              string(s, n + 1), ","));
+  return n == std::string::npos
+             ? DrvPathWithOutputs(s, std::set<string>())
+             : DrvPathWithOutputs(
+                   string(s, 0, n),
+                   tokenizeString<std::set<string> >(string(s, n + 1), ","));
 }
 
 Path makeDrvPathWithOutputs(const Path& drvPath,
diff --git a/third_party/nix/src/libstore/download.cc b/third_party/nix/src/libstore/download.cc
index eb7095ee146a..752f546a584b 100644
--- a/third_party/nix/src/libstore/download.cc
+++ b/third_party/nix/src/libstore/download.cc
@@ -39,9 +39,8 @@ std::string resolveUri(const std::string& uri) {
   if (uri.compare(0, 8, "channel:") == 0) {
     return "https://nixos.org/channels/" + std::string(uri, 8) +
            "/nixexprs.tar.xz";
-  } else {
-    return uri;
   }
+  return uri;
 }
 
 struct CurlDownloader : public Downloader {
@@ -111,13 +110,13 @@ struct CurlDownloader : public Downloader {
     }
 
     ~DownloadItem() {
-      if (req) {
+      if (req != nullptr) {
         if (active) {
           curl_multi_remove_handle(downloader.curlm, req);
         }
         curl_easy_cleanup(req);
       }
-      if (requestHeaders) {
+      if (requestHeaders != nullptr) {
         curl_slist_free_all(requestHeaders);
       }
       try {
@@ -214,13 +213,13 @@ struct CurlDownloader : public Downloader {
       return ((DownloadItem*)userp)->headerCallback(contents, size, nmemb);
     }
 
-    int progressCallback(double dltotal, double dlnow) {
+    static int progressCallback(double dltotal, double dlnow) {
       try {
         // TODO(tazjin): this had activity nonsense, clean it up
       } catch (nix::Interrupted&) {
         assert(_isInterrupted);
       }
-      return _isInterrupted;
+      return static_cast<int>(_isInterrupted);
     }
 
     static int progressCallbackWrapper(void* userp, double dltotal,
@@ -255,7 +254,7 @@ struct CurlDownloader : public Downloader {
     }
 
     void init() {
-      if (!req) {
+      if (req == nullptr) {
         req = curl_easy_init();
       }
 
@@ -314,7 +313,7 @@ struct CurlDownloader : public Downloader {
       }
 
       if (request.verifyTLS) {
-        if (settings.caFile != "") {
+        if (!settings.caFile.empty()) {
           curl_easy_setopt(req, CURLOPT_CAINFO, settings.caFile.c_str());
         }
       } else {
@@ -335,7 +334,7 @@ struct CurlDownloader : public Downloader {
                        settings.netrcFile.get().c_str());
       curl_easy_setopt(req, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
 
-      if (writtenToSink) {
+      if (writtenToSink != 0) {
         curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink);
       }
 
@@ -349,7 +348,7 @@ struct CurlDownloader : public Downloader {
 
       char* effectiveUriCStr;
       curl_easy_getinfo(req, CURLINFO_EFFECTIVE_URL, &effectiveUriCStr);
-      if (effectiveUriCStr) {
+      if (effectiveUriCStr != nullptr) {
         result.effectiveUri = effectiveUriCStr;
       }
 
@@ -461,10 +460,10 @@ struct CurlDownloader : public Downloader {
             (!this->request.dataCallback || writtenToSink == 0 ||
              (acceptRanges && encoding.empty()))) {
           int ms = request.baseRetryTimeMs *
-                   std::pow(2.0f, attempt - 1 +
+                   std::pow(2.0F, attempt - 1 +
                                       std::uniform_real_distribution<>(
                                           0.0, 0.5)(downloader.mt19937));
-          if (writtenToSink) {
+          if (writtenToSink != 0) {
             LOG(WARNING) << exc.what() << "; retrying from offset "
                          << writtenToSink << " in " << ms << "ms";
           } else {
@@ -528,7 +527,7 @@ struct CurlDownloader : public Downloader {
 
     workerThread.join();
 
-    if (curlm) {
+    if (curlm != nullptr) {
       curl_multi_cleanup(curlm);
     }
   }
@@ -567,7 +566,7 @@ struct CurlDownloader : public Downloader {
       /* Set the promises of any finished requests. */
       CURLMsg* msg;
       int left;
-      while ((msg = curl_multi_info_read(curlm, &left))) {
+      while ((msg = curl_multi_info_read(curlm, &left)) != nullptr) {
         if (msg->msg == CURLMSG_DONE) {
           auto i = items.find(msg->easy_handle);
           assert(i != items.end());
@@ -605,7 +604,7 @@ struct CurlDownloader : public Downloader {
       /* Add new curl requests from the incoming requests queue,
          except for requests that are embargoed (waiting for a
          retry timeout to expire). */
-      if (extraFDs[0].revents & CURL_WAIT_POLLIN) {
+      if ((extraFDs[0].revents & CURL_WAIT_POLLIN) != 0) {
         char buf[1024];
         auto res = read(extraFDs[0].fd, buf, sizeof(buf));
         if (res == -1 && errno != EINTR) {
@@ -863,7 +862,7 @@ CachedDownloadResult Downloader::downloadCached(
   auto url = resolveUri(request.uri);
 
   auto name = request.name;
-  if (name == "") {
+  if (name.empty()) {
     auto p = url.rfind('/');
     if (p != string::npos) {
       name = string(url, p + 1);
@@ -987,7 +986,7 @@ CachedDownloadResult Downloader::downloadCached(
     storePath = unpackedStorePath;
   }
 
-  if (expectedStorePath != "" && storePath != expectedStorePath) {
+  if (!expectedStorePath.empty() && storePath != expectedStorePath) {
     unsigned int statusCode = 102;
     Hash gotHash =
         request.unpack
diff --git a/third_party/nix/src/libstore/export-import.cc b/third_party/nix/src/libstore/export-import.cc
index de68304e3141..1974773ba135 100644
--- a/third_party/nix/src/libstore/export-import.cc
+++ b/third_party/nix/src/libstore/export-import.cc
@@ -87,7 +87,7 @@ Paths Store::importPaths(Source& source, std::shared_ptr<FSAccessor> accessor,
     info.references = readStorePaths<PathSet>(*this, source);
 
     info.deriver = readString(source);
-    if (info.deriver != "") {
+    if (!info.deriver.empty()) {
       assertStorePath(info.deriver);
     }
 
diff --git a/third_party/nix/src/libstore/gc.cc b/third_party/nix/src/libstore/gc.cc
index a0c84dc0a518..bc3393265e48 100644
--- a/third_party/nix/src/libstore/gc.cc
+++ b/third_party/nix/src/libstore/gc.cc
@@ -236,7 +236,8 @@ void LocalStore::findTempRoots(FDs& fds, Roots& tempRoots, bool censor) {
     string contents = readFile(fd->get());
 
     /* Extract the roots. */
-    string::size_type pos = 0, end;
+    string::size_type pos = 0;
+    string::size_type end;
 
     while ((end = contents.find((char)0, pos)) != string::npos) {
       Path root(contents, pos, end - pos);
@@ -542,7 +543,7 @@ void LocalStore::deletePathRecursive(GCState& state, const Path& path) {
   Path realPath = realStoreDir + "/" + baseNameOf(path);
 
   struct stat st;
-  if (lstat(realPath.c_str(), &st)) {
+  if (lstat(realPath.c_str(), &st) != 0) {
     if (errno == ENOENT) {
       return;
     }
@@ -567,7 +568,7 @@ void LocalStore::deletePathRecursive(GCState& state, const Path& path) {
         throw SysError(format("making '%1%' writable") % realPath);
       }
       Path tmp = trashDir + "/" + baseNameOf(path);
-      if (rename(realPath.c_str(), tmp.c_str())) {
+      if (rename(realPath.c_str(), tmp.c_str()) != 0) {
         throw SysError(format("unable to rename '%1%' to '%2%'") % realPath %
                        tmp);
       }
@@ -593,19 +594,19 @@ void LocalStore::deletePathRecursive(GCState& state, const Path& path) {
 
 bool LocalStore::canReachRoot(GCState& state, PathSet& visited,
                               const Path& path) {
-  if (visited.count(path)) {
+  if (visited.count(path) != 0u) {
     return false;
   }
 
-  if (state.alive.count(path)) {
+  if (state.alive.count(path) != 0u) {
     return true;
   }
 
-  if (state.dead.count(path)) {
+  if (state.dead.count(path) != 0u) {
     return false;
   }
 
-  if (state.roots.count(path)) {
+  if (state.roots.count(path) != 0u) {
     DLOG(INFO) << "cannot delete '" << path << "' because it's a root";
     state.alive.insert(path);
     return true;
@@ -713,7 +714,8 @@ void LocalStore::removeUnusedLinks(const GCState& state) {
     throw SysError(format("opening directory '%1%'") % linksDir);
   }
 
-  long long actualSize = 0, unsharedSize = 0;
+  long long actualSize = 0;
+  long long unsharedSize = 0;
 
   struct dirent* dirent;
   while (errno = 0, dirent = readdir(dir.get())) {
@@ -930,7 +932,7 @@ void LocalStore::autoGC(bool sync) {
     }
 
     struct statvfs st;
-    if (statvfs(realStoreDir.c_str(), &st)) {
+    if (statvfs(realStoreDir.c_str(), &st) != 0) {
       throw SysError("getting filesystem info about '%s'", realStoreDir);
     }
 
diff --git a/third_party/nix/src/libstore/globals.cc b/third_party/nix/src/libstore/globals.cc
index ade200f135ae..57ba8cff6434 100644
--- a/third_party/nix/src/libstore/globals.cc
+++ b/third_party/nix/src/libstore/globals.cc
@@ -46,7 +46,7 @@ Settings::Settings()
   lockCPU = getEnv("NIX_AFFINITY_HACK", "1") == "1";
 
   caFile = getEnv("NIX_SSL_CERT_FILE", getEnv("SSL_CERT_FILE", ""));
-  if (caFile == "") {
+  if (caFile.empty()) {
     for (auto& fn :
          {"/etc/ssl/certs/ca-certificates.crt",
           "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"}) {
@@ -59,7 +59,7 @@ Settings::Settings()
 
   /* Backwards compatibility. */
   auto s = getEnv("NIX_REMOTE_SYSTEMS");
-  if (s != "") {
+  if (!s.empty()) {
     Strings ss;
     for (auto& p : tokenizeString<Strings>(s, ":")) {
       ss.push_back("@" + p);
@@ -128,7 +128,8 @@ template <>
 std::string BaseSetting<SandboxMode>::to_string() {
   if (value == smEnabled) {
     return "true";
-  } else if (value == smRelaxed) {
+  }
+  if (value == smRelaxed) {
     return "relaxed";
   } else if (value == smDisabled) {
     return "false";
@@ -189,7 +190,7 @@ void initPlugins() {
       /* handle is purposefully leaked as there may be state in the
          DSO needed by the action of the plugin. */
       void* handle = dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
-      if (!handle) {
+      if (handle == nullptr) {
         throw Error("could not dynamically open plugin file '%s': %s", file,
                     dlerror());
       }
diff --git a/third_party/nix/src/libstore/globals.hh b/third_party/nix/src/libstore/globals.hh
index 924e8a0165f8..8e04b0937457 100644
--- a/third_party/nix/src/libstore/globals.hh
+++ b/third_party/nix/src/libstore/globals.hh
@@ -25,9 +25,9 @@ struct MaxBuildJobsSetting : public BaseSetting<unsigned int> {
 };
 
 class Settings : public Config {
-  unsigned int getDefaultCores();
+  static unsigned int getDefaultCores();
 
-  StringSet getDefaultSystemFeatures();
+  static StringSet getDefaultSystemFeatures();
 
  public:
   Settings();
diff --git a/third_party/nix/src/libstore/legacy-ssh-store.cc b/third_party/nix/src/libstore/legacy-ssh-store.cc
index 7723581136d8..9a84e0295657 100644
--- a/third_party/nix/src/libstore/legacy-ssh-store.cc
+++ b/third_party/nix/src/libstore/legacy-ssh-store.cc
@@ -58,7 +58,7 @@ struct LegacySSHStore : public Store {
     auto conn = make_ref<Connection>();
     conn->sshConn = master.startCommand(
         fmt("%s --serve --write", remoteProgram) +
-        (remoteStore.get() == ""
+        (remoteStore.get().empty()
              ? ""
              : " --store " + shellEscape(remoteStore.get())));
     conn->to = FdSink(conn->sshConn->in.get());
@@ -120,7 +120,7 @@ struct LegacySSHStore : public Store {
       }
 
       auto s = readString(conn->from);
-      assert(s == "");
+      assert(s.empty());
 
       callback(std::move(info));
     } catch (...) {
@@ -139,8 +139,8 @@ struct LegacySSHStore : public Store {
     if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 5) {
       conn->to << cmdAddToStoreNar << info.path << info.deriver
                << info.narHash.to_string(Base16, false) << info.references
-               << info.registrationTime << info.narSize << info.ultimate
-               << info.sigs << info.ca;
+               << info.registrationTime << info.narSize
+               << static_cast<uint64_t>(info.ultimate) << info.sigs << info.ca;
       try {
         copyNAR(source, conn->to);
       } catch (...) {
@@ -201,7 +201,8 @@ struct LegacySSHStore : public Store {
       conn->to << settings.maxLogSize;
     }
     if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3) {
-      conn->to << settings.buildRepeat << settings.enforceDeterminism;
+      conn->to << settings.buildRepeat
+               << static_cast<uint64_t>(settings.enforceDeterminism);
     }
 
     conn->to.flush();
@@ -231,7 +232,8 @@ struct LegacySSHStore : public Store {
 
     auto conn(connections->get());
 
-    conn->to << cmdQueryClosure << includeOutputs << paths;
+    conn->to << cmdQueryClosure << static_cast<uint64_t>(includeOutputs)
+             << paths;
     conn->to.flush();
 
     auto res = readStorePaths<PathSet>(*this, conn->from);
@@ -243,7 +245,7 @@ struct LegacySSHStore : public Store {
                                                     NoSubstitute) override {
     auto conn(connections->get());
 
-    conn->to << cmdQueryValidPaths << false  // lock
+    conn->to << cmdQueryValidPaths << 0u  // lock
              << maybeSubstitute << paths;
     conn->to.flush();
 
diff --git a/third_party/nix/src/libstore/local-binary-cache-store.cc b/third_party/nix/src/libstore/local-binary-cache-store.cc
index 58ce7c091147..00bb21eb24fe 100644
--- a/third_party/nix/src/libstore/local-binary-cache-store.cc
+++ b/third_party/nix/src/libstore/local-binary-cache-store.cc
@@ -59,7 +59,7 @@ static void atomicWrite(const Path& path, const std::string& s) {
   Path tmp = path + ".tmp." + std::to_string(getpid());
   AutoDelete del(tmp, false);
   writeFile(tmp, s);
-  if (rename(tmp.c_str(), path.c_str())) {
+  if (rename(tmp.c_str(), path.c_str()) != 0) {
     throw SysError(format("renaming '%1%' to '%2%'") % tmp % path);
   }
   del.cancel();
diff --git a/third_party/nix/src/libstore/local-fs-store.cc b/third_party/nix/src/libstore/local-fs-store.cc
index f3ac5b3663ff..9a5ea153869a 100644
--- a/third_party/nix/src/libstore/local-fs-store.cc
+++ b/third_party/nix/src/libstore/local-fs-store.cc
@@ -27,7 +27,7 @@ struct LocalStoreAccessor : public FSAccessor {
     auto realPath = toRealPath(path);
 
     struct stat st;
-    if (lstat(realPath.c_str(), &st)) {
+    if (lstat(realPath.c_str(), &st) != 0) {
       if (errno == ENOENT || errno == ENOTDIR) {
         return {Type::tMissing, 0, false};
       }
@@ -42,7 +42,7 @@ struct LocalStoreAccessor : public FSAccessor {
                 ? Type::tRegular
                 : S_ISLNK(st.st_mode) ? Type::tSymlink : Type::tDirectory,
             S_ISREG(st.st_mode) ? (uint64_t)st.st_size : 0,
-            S_ISREG(st.st_mode) && st.st_mode & S_IXUSR};
+            S_ISREG(st.st_mode) && ((st.st_mode & S_IXUSR) != 0u)};
   }
 
   StringSet readDirectory(const Path& path) override {
@@ -92,7 +92,7 @@ std::shared_ptr<std::string> LocalFSStore::getBuildLog(const Path& path_) {
     } catch (InvalidPath&) {
       return nullptr;
     }
-    if (path == "") {
+    if (path.empty()) {
       return nullptr;
     }
   }
@@ -107,8 +107,8 @@ std::shared_ptr<std::string> LocalFSStore::getBuildLog(const Path& path_) {
 
     if (pathExists(logPath)) {
       return std::make_shared<std::string>(readFile(logPath));
-
-    } else if (pathExists(logBz2Path)) {
+    }
+    if (pathExists(logBz2Path)) {
       try {
         return decompress("bzip2", readFile(logBz2Path));
       } catch (Error&) {
diff --git a/third_party/nix/src/libstore/local-store.cc b/third_party/nix/src/libstore/local-store.cc
index 1fa5cb904181..1d162ad6be10 100644
--- a/third_party/nix/src/libstore/local-store.cc
+++ b/third_party/nix/src/libstore/local-store.cc
@@ -86,12 +86,12 @@ LocalStore::LocalStore(const Params& params)
     mode_t perm = 01775;
 
     struct group* gr = getgrnam(settings.buildUsersGroup.get().c_str());
-    if (!gr) {
+    if (gr == nullptr) {
       LOG(ERROR) << "warning: the group '" << settings.buildUsersGroup
                  << "' specified in 'build-users-group' does not exist";
     } else {
       struct stat st;
-      if (stat(realStoreDir.c_str(), &st)) {
+      if (stat(realStoreDir.c_str(), &st) != 0) {
         throw SysError(format("getting attributes of path '%1%'") %
                        realStoreDir);
       }
@@ -115,7 +115,7 @@ LocalStore::LocalStore(const Params& params)
     Path path = realStoreDir;
     struct stat st;
     while (path != "/") {
-      if (lstat(path.c_str(), &st)) {
+      if (lstat(path.c_str(), &st) != 0) {
         throw SysError(format("getting status of '%1%'") % path);
       }
       if (S_ISLNK(st.st_mode)) {
@@ -153,7 +153,7 @@ LocalStore::LocalStore(const Params& params)
   /* Acquire the big fat lock in shared mode to make sure that no
      schema upgrade is in progress. */
   Path globalLockPath = dbDir + "/big-lock";
-  globalLock = openLockFile(globalLockPath.c_str(), true);
+  globalLock = openLockFile(globalLockPath, true);
 
   if (!lockFile(globalLock.get(), ltRead, false)) {
     LOG(INFO) << "waiting for the big Nix store lock...";
@@ -168,8 +168,8 @@ LocalStore::LocalStore(const Params& params)
         format(
             "current Nix store schema is version %1%, but I only support %2%") %
         curSchema % nixSchemaVersion);
-
-  } else if (curSchema == 0) { /* new store */
+  }
+  if (curSchema == 0) { /* new store */
     curSchema = nixSchemaVersion;
     openDB(*state, true);
     writeFile(schemaPath, (format("%1%") % nixSchemaVersion).str());
@@ -311,7 +311,7 @@ int LocalStore::getSchema() {
 }
 
 void LocalStore::openDB(State& state, bool create) {
-  if (access(dbDir.c_str(), R_OK | W_OK)) {
+  if (access(dbDir.c_str(), R_OK | W_OK) != 0) {
     throw SysError(format("Nix database directory '%1%' is not writable") %
                    dbDir);
   }
@@ -399,7 +399,7 @@ void LocalStore::makeStoreWritable() {
     throw SysError("getting info about the Nix store mount point");
   }
 
-  if (stat.f_flag & ST_RDONLY) {
+  if ((stat.f_flag & ST_RDONLY) != 0u) {
     if (unshare(CLONE_NEWNS) == -1) {
       throw SysError("setting up a private mount namespace");
     }
@@ -421,7 +421,8 @@ static void canonicaliseTimestampAndPermissions(const Path& path,
     mode_t mode = st.st_mode & ~S_IFMT;
 
     if (mode != 0444 && mode != 0555) {
-      mode = (st.st_mode & S_IFMT) | 0444 | (st.st_mode & S_IXUSR ? 0111 : 0);
+      mode = (st.st_mode & S_IFMT) | 0444 |
+             ((st.st_mode & S_IXUSR) != 0u ? 0111 : 0);
       if (chmod(path.c_str(), mode) == -1) {
         throw SysError(format("changing mode of '%1%' to %2$o") % path % mode);
       }
@@ -449,7 +450,7 @@ static void canonicaliseTimestampAndPermissions(const Path& path,
 
 void canonicaliseTimestampAndPermissions(const Path& path) {
   struct stat st;
-  if (lstat(path.c_str(), &st)) {
+  if (lstat(path.c_str(), &st) != 0) {
     throw SysError(format("getting attributes of path '%1%'") % path);
   }
   canonicaliseTimestampAndPermissions(path, st);
@@ -470,7 +471,7 @@ static void canonicalisePathMetaData_(const Path& path, uid_t fromUid,
 #endif
 
   struct stat st;
-  if (lstat(path.c_str(), &st)) {
+  if (lstat(path.c_str(), &st) != 0) {
     throw SysError(format("getting attributes of path '%1%'") % path);
   }
 
@@ -564,7 +565,7 @@ void canonicalisePathMetaData(const Path& path, uid_t fromUid,
   /* On platforms that don't have lchown(), the top-level path can't
      be a symlink, since we can't change its ownership. */
   struct stat st;
-  if (lstat(path.c_str(), &st)) {
+  if (lstat(path.c_str(), &st) != 0) {
     throw SysError(format("getting attributes of path '%1%'") % path);
   }
 
@@ -632,7 +633,7 @@ void LocalStore::checkDerivationOutputs(const Path& drvPath,
 
 uint64_t LocalStore::addValidPath(State& state, const ValidPathInfo& info,
                                   bool checkOutputs) {
-  if (info.ca != "" && !info.isContentAddressed(*this)) {
+  if (!info.ca.empty() && !info.isContentAddressed(*this)) {
     throw Error(
         "cannot add path '%s' to the Nix store because it claims to be "
         "content-addressed but isn't",
@@ -642,7 +643,7 @@ uint64_t LocalStore::addValidPath(State& state, const ValidPathInfo& info,
   state.stmtRegisterValidPath
       .use()(info.path)(info.narHash.to_string(Base16))(
           info.registrationTime == 0 ? time(nullptr) : info.registrationTime)(
-          info.deriver, info.deriver != "")(info.narSize, info.narSize != 0)(
+          info.deriver, !info.deriver.empty())(info.narSize, info.narSize != 0)(
           info.ultimate ? 1 : 0, info.ultimate)(
           concatStringsSep(" ", info.sigs), !info.sigs.empty())(
           info.ca, !info.ca.empty())
@@ -709,7 +710,7 @@ void LocalStore::queryPathInfoUncached(
       info->registrationTime = useQueryPathInfo.getInt(2);
 
       auto s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 3);
-      if (s) {
+      if (s != nullptr) {
         info->deriver = s;
       }
 
@@ -719,12 +720,12 @@ void LocalStore::queryPathInfoUncached(
       info->ultimate = useQueryPathInfo.getInt(5) == 1;
 
       s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 6);
-      if (s) {
+      if (s != nullptr) {
         info->sigs = tokenizeString<StringSet>(s, " ");
       }
 
       s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 7);
-      if (s) {
+      if (s != nullptr) {
         info->ca = s;
       }
 
@@ -880,8 +881,10 @@ Path LocalStore::queryPathFromHashPart(const string& hashPart) {
 
     const char* s =
         (const char*)sqlite3_column_text(state->stmtQueryPathFromHashPart, 0);
-    return s && prefix.compare(0, prefix.size(), s, prefix.size()) == 0 ? s
-                                                                        : "";
+    return (s != nullptr) &&
+                   prefix.compare(0, prefix.size(), s, prefix.size()) == 0
+               ? s
+               : "";
   });
 }
 
@@ -908,7 +911,7 @@ PathSet LocalStore::querySubstitutablePaths(const PathSet& paths) {
 
     PathSet remaining2;
     for (auto& path : remaining) {
-      if (valid.count(path)) {
+      if (valid.count(path) != 0u) {
         res.insert(path);
       } else {
         remaining2.insert(path);
@@ -931,7 +934,7 @@ void LocalStore::querySubstitutablePathInfos(const PathSet& paths,
       continue;
     }
     for (auto& path : paths) {
-      if (infos.count(path)) {
+      if (infos.count(path) != 0u) {
         continue;
       }
       DLOG(INFO) << "checking substituter '" << sub->getUri() << "' for path '"
@@ -1049,15 +1052,15 @@ void LocalStore::addToStore(const ValidPathInfo& info, Source& source,
     throw Error("cannot add path '%s' because it lacks a hash", info.path);
   }
 
-  if (requireSigs && checkSigs &&
-      !info.checkSignatures(*this, getPublicKeys())) {
+  if (requireSigs && (checkSigs != 0u) &&
+      (info.checkSignatures(*this, getPublicKeys()) == 0u)) {
     throw Error("cannot add path '%s' because it lacks a valid signature",
                 info.path);
   }
 
   addTempRoot(info.path);
 
-  if (repair || !isValidPath(info.path)) {
+  if ((repair != 0u) || !isValidPath(info.path)) {
     PathLocks outputLock;
 
     Path realPath = realStoreDir + "/" + baseNameOf(info.path);
@@ -1065,11 +1068,11 @@ void LocalStore::addToStore(const ValidPathInfo& info, Source& source,
     /* Lock the output path.  But don't lock if we're being called
        from a build hook (whose parent process already acquired a
        lock on this path). */
-    if (!locksHeld.count(info.path)) {
+    if (locksHeld.count(info.path) == 0u) {
       outputLock.lockPaths({realPath});
     }
 
-    if (repair || !isValidPath(info.path)) {
+    if ((repair != 0u) || !isValidPath(info.path)) {
       deletePath(realPath);
 
       /* While restoring the path from the NAR, compute the hash
@@ -1121,7 +1124,7 @@ Path LocalStore::addToStoreFromDump(const string& dump, const string& name,
 
   addTempRoot(dstPath);
 
-  if (repair || !isValidPath(dstPath)) {
+  if ((repair != 0u) || !isValidPath(dstPath)) {
     /* The first check above is an optimisation to prevent
        unnecessary lock acquisition. */
 
@@ -1129,7 +1132,7 @@ Path LocalStore::addToStoreFromDump(const string& dump, const string& name,
 
     PathLocks outputLock({realPath});
 
-    if (repair || !isValidPath(dstPath)) {
+    if ((repair != 0u) || !isValidPath(dstPath)) {
       deletePath(realPath);
 
       autoGC();
@@ -1196,12 +1199,12 @@ Path LocalStore::addTextToStore(const string& name, const string& s,
 
   addTempRoot(dstPath);
 
-  if (repair || !isValidPath(dstPath)) {
+  if ((repair != 0u) || !isValidPath(dstPath)) {
     Path realPath = realStoreDir + "/" + baseNameOf(dstPath);
 
     PathLocks outputLock({realPath});
 
-    if (repair || !isValidPath(dstPath)) {
+    if ((repair != 0u) || !isValidPath(dstPath)) {
       deletePath(realPath);
 
       autoGC();
@@ -1286,7 +1289,9 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) {
   /* Check whether all valid paths actually exist. */
   LOG(INFO) << "checking path existence...";
 
-  PathSet validPaths2 = queryAllValidPaths(), validPaths, done;
+  PathSet validPaths2 = queryAllValidPaths();
+  PathSet validPaths;
+  PathSet done;
 
   fdGCLock = -1;
 
@@ -1313,7 +1318,7 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) {
           LOG(ERROR) << "path '" << i << "' was modified! expected hash '"
                      << info->narHash.to_string() << "', got '"
                      << current.first.to_string() << "'";
-          if (repair) {
+          if (repair != 0u) {
             repairPath(i);
           } else {
             errors = true;
@@ -1398,7 +1403,7 @@ void LocalStore::verifyPath(const Path& path, const PathSet& store,
     } else {
       LOG(ERROR) << "path '" << path
                  << "' disappeared, but it still has valid referrers!";
-      if (repair) {
+      if (repair != 0u) {
         try {
           repairPath(path);
         } catch (Error& e) {
diff --git a/third_party/nix/src/libstore/local-store.hh b/third_party/nix/src/libstore/local-store.hh
index 47fa74a97be7..1a58df81613b 100644
--- a/third_party/nix/src/libstore/local-store.hh
+++ b/third_party/nix/src/libstore/local-store.hh
@@ -217,7 +217,7 @@ class LocalStore : public LocalFSStore {
 
   void makeStoreWritable();
 
-  uint64_t queryValidPathId(State& state, const Path& path);
+  static uint64_t queryValidPathId(State& state, const Path& path);
 
   uint64_t addValidPath(State& state, const ValidPathInfo& info,
                         bool checkOutputs = true);
@@ -230,7 +230,7 @@ class LocalStore : public LocalFSStore {
   void verifyPath(const Path& path, const PathSet& store, PathSet& done,
                   PathSet& validPaths, RepairFlag repair, bool& errors);
 
-  void updatePathInfo(State& state, const ValidPathInfo& info);
+  static void updatePathInfo(State& state, const ValidPathInfo& info);
 
   void upgradeStore6();
   void upgradeStore7();
@@ -239,7 +239,7 @@ class LocalStore : public LocalFSStore {
 
   struct GCState;
 
-  void deleteGarbage(GCState& state, const Path& path);
+  static void deleteGarbage(GCState& state, const Path& path);
 
   void tryToDelete(GCState& state, const Path& path);
 
@@ -247,8 +247,8 @@ class LocalStore : public LocalFSStore {
 
   void deletePathRecursive(GCState& state, const Path& path);
 
-  bool isActiveTempFile(const GCState& state, const Path& path,
-                        const string& suffix);
+  static bool isActiveTempFile(const GCState& state, const Path& path,
+                               const string& suffix);
 
   AutoCloseFD openGCLock(LockType lockType);
 
@@ -267,18 +267,19 @@ class LocalStore : public LocalFSStore {
   typedef std::unordered_set<ino_t> InodeHash;
 
   InodeHash loadInodeHash();
-  Strings readDirectoryIgnoringInodes(const Path& path,
-                                      const InodeHash& inodeHash);
+  static Strings readDirectoryIgnoringInodes(const Path& path,
+                                             const InodeHash& inodeHash);
   void optimisePath_(OptimiseStats& stats, const Path& path,
                      InodeHash& inodeHash);
 
   // Internal versions that are not wrapped in retry_sqlite.
-  bool isValidPath_(State& state, const Path& path);
-  void queryReferrers(State& state, const Path& path, PathSet& referrers);
+  static bool isValidPath_(State& state, const Path& path);
+  static void queryReferrers(State& state, const Path& path,
+                             PathSet& referrers);
 
   /* Add signatures to a ValidPathInfo using the secret keys
      specified by the ‘secret-key-files’ option. */
-  void signPathInfo(ValidPathInfo& info);
+  static void signPathInfo(ValidPathInfo& info);
 
   Path getRealStoreDir() override { return realStoreDir; }
 
diff --git a/third_party/nix/src/libstore/machines.cc b/third_party/nix/src/libstore/machines.cc
index 480d533e6099..1b8bc4cf75a5 100644
--- a/third_party/nix/src/libstore/machines.cc
+++ b/third_party/nix/src/libstore/machines.cc
@@ -35,8 +35,8 @@ Machine::Machine(decltype(storeUri) storeUri, decltype(systemTypes) systemTypes,
 bool Machine::allSupported(const std::set<string>& features) const {
   return std::all_of(features.begin(), features.end(),
                      [&](const string& feature) {
-                       return supportedFeatures.count(feature) ||
-                              mandatoryFeatures.count(feature);
+                       return (supportedFeatures.count(feature) != 0u) ||
+                              (mandatoryFeatures.count(feature) != 0u);
                      });
 }
 
@@ -74,7 +74,7 @@ void parseMachines(const std::string& s, Machines& machines) {
     }
 
     auto isSet = [&](size_t n) {
-      return tokens.size() > n && tokens[n] != "" && tokens[n] != "-";
+      return tokens.size() > n && !tokens[n].empty() && tokens[n] != "-";
     };
 
     machines.emplace_back(
diff --git a/third_party/nix/src/libstore/misc.cc b/third_party/nix/src/libstore/misc.cc
index 23abaecba050..076c691b004c 100644
--- a/third_party/nix/src/libstore/misc.cc
+++ b/third_party/nix/src/libstore/misc.cc
@@ -30,7 +30,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
       if (state->exc) {
         return;
       }
-      if (state->paths.count(path)) {
+      if (state->paths.count(path) != 0u) {
         return;
       }
       state->paths.insert(path);
@@ -90,7 +90,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
             {
               auto state(state_.lock());
               assert(state->pending);
-              if (!--state->pending) {
+              if (--state->pending == 0u) {
                 done.notify_one();
               }
             }
@@ -101,7 +101,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
               state->exc = std::current_exception();
             }
             assert(state->pending);
-            if (!--state->pending) {
+            if (--state->pending == 0u) {
               done.notify_one();
             }
           };
@@ -114,7 +114,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
 
   {
     auto state(state_.lock());
-    while (state->pending) {
+    while (state->pending != 0u) {
       state.wait(done);
     }
     if (state->exc) {
@@ -192,7 +192,7 @@ void Store::queryMissing(const PathSet& targets, PathSet& willBuild_,
         assert(drvState->left);
         drvState->left--;
         drvState->outPaths.insert(outPath);
-        if (!drvState->left) {
+        if (drvState->left == 0u) {
           for (auto& path : drvState->outPaths) {
             pool.enqueue(std::bind(doPath, path));
           }
@@ -204,7 +204,7 @@ void Store::queryMissing(const PathSet& targets, PathSet& willBuild_,
   doPath = [&](const Path& path) {
     {
       auto state(state_.lock());
-      if (state->done.count(path)) {
+      if (state->done.count(path) != 0u) {
         return;
       }
       state->done.insert(path);
@@ -282,7 +282,8 @@ void Store::queryMissing(const PathSet& targets, PathSet& willBuild_,
 
 Paths Store::topoSortPaths(const PathSet& paths) {
   Paths sorted;
-  PathSet visited, parents;
+  PathSet visited;
+  PathSet parents;
 
   std::function<void(const Path& path, const Path* parent)> dfsVisit;
 
diff --git a/third_party/nix/src/libstore/nar-accessor.cc b/third_party/nix/src/libstore/nar-accessor.cc
index ac286374b8bd..3a8d6b884104 100644
--- a/third_party/nix/src/libstore/nar-accessor.cc
+++ b/third_party/nix/src/libstore/nar-accessor.cc
@@ -132,7 +132,7 @@ struct NarAccessor : public FSAccessor {
   }
 
   NarMember* find(const Path& path) {
-    Path canon = path == "" ? "" : canonPath(path);
+    Path canon = path.empty() ? "" : canonPath(path);
     NarMember* current = &root;
     auto end = path.end();
     for (auto it = path.begin(); it != end;) {
@@ -238,7 +238,7 @@ void listNar(JSONPlaceholder& res, ref<FSAccessor> accessor, const Path& path,
       if (st.isExecutable) {
         obj.attr("executable", true);
       }
-      if (st.narOffset) {
+      if (st.narOffset != 0u) {
         obj.attr("narOffset", st.narOffset);
       }
       break;
diff --git a/third_party/nix/src/libstore/nar-info-disk-cache.cc b/third_party/nix/src/libstore/nar-info-disk-cache.cc
index 7ef178ab4388..19ef2c9d7461 100644
--- a/third_party/nix/src/libstore/nar-info-disk-cache.cc
+++ b/third_party/nix/src/libstore/nar-info-disk-cache.cc
@@ -142,7 +142,7 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
     });
   }
 
-  Cache& getCache(State& state, const std::string& uri) {
+  static Cache& getCache(State& state, const std::string& uri) {
     auto i = state.caches.find(uri);
     if (i == state.caches.end()) {
       abort();
@@ -158,7 +158,8 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
       // FIXME: race
 
       state->insertCache
-          .use()(uri)(time(nullptr))(storeDir)(wantMassQuery)(priority)
+          .use()(uri)(time(nullptr))(storeDir)(
+              static_cast<int64_t>(wantMassQuery))(priority)
           .exec();
       assert(sqlite3_changes(state->db) == 1);
       state->caches[uri] = Cache{(int)sqlite3_last_insert_rowid(state->db),
@@ -209,7 +210,7 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
             return {oUnknown, nullptr};
           }
 
-          if (!queryNAR.getInt(0)) {
+          if (queryNAR.getInt(0) == 0) {
             return {oInvalid, nullptr};
           }
 
@@ -262,10 +263,10 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
                 narInfo && narInfo->fileHash)(
                 narInfo ? narInfo->fileSize : 0,
                 narInfo != nullptr &&
-                    narInfo->fileSize)(info->narHash.to_string())(
+                    (narInfo->fileSize != 0u))(info->narHash.to_string())(
                 info->narSize)(concatStringsSep(" ", info->shortRefs()))(
-                info->deriver != "" ? baseNameOf(info->deriver) : "",
-                info->deriver != "")(concatStringsSep(" ", info->sigs))(
+                !info->deriver.empty() ? baseNameOf(info->deriver) : "",
+                !info->deriver.empty())(concatStringsSep(" ", info->sigs))(
                 info->ca)(time(nullptr))
             .exec();
 
diff --git a/third_party/nix/src/libstore/nar-info.cc b/third_party/nix/src/libstore/nar-info.cc
index fee470fc7df6..6190840ea61c 100644
--- a/third_party/nix/src/libstore/nar-info.cc
+++ b/third_party/nix/src/libstore/nar-info.cc
@@ -90,7 +90,7 @@ NarInfo::NarInfo(const Store& store, const std::string& s,
     pos = eol + 1;
   }
 
-  if (compression == "") {
+  if (compression.empty()) {
     compression = "bzip2";
   }
 
@@ -103,7 +103,7 @@ std::string NarInfo::to_string() const {
   std::string res;
   res += "StorePath: " + path + "\n";
   res += "URL: " + url + "\n";
-  assert(compression != "");
+  assert(!compression.empty());
   res += "Compression: " + compression + "\n";
   assert(fileHash.type == htSHA256);
   res += "FileHash: " + fileHash.to_string(Base32) + "\n";
diff --git a/third_party/nix/src/libstore/optimise-store.cc b/third_party/nix/src/libstore/optimise-store.cc
index 9eaf4cdc3c9e..d7cf2bb74449 100644
--- a/third_party/nix/src/libstore/optimise-store.cc
+++ b/third_party/nix/src/libstore/optimise-store.cc
@@ -18,7 +18,7 @@ namespace nix {
 
 static void makeWritable(const Path& path) {
   struct stat st;
-  if (lstat(path.c_str(), &st)) {
+  if (lstat(path.c_str(), &st) != 0) {
     throw SysError(format("getting attributes of path '%1%'") % path);
   }
   if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) {
@@ -32,7 +32,7 @@ struct MakeReadOnly {
   ~MakeReadOnly() {
     try {
       /* This will make the path read-only. */
-      if (path != "") {
+      if (!path.empty()) {
         canonicaliseTimestampAndPermissions(path);
       }
     } catch (...) {
@@ -78,7 +78,7 @@ Strings LocalStore::readDirectoryIgnoringInodes(const Path& path,
   while (errno = 0, dirent = readdir(dir.get())) { /* sic */
     checkInterrupt();
 
-    if (inodeHash.count(dirent->d_ino)) {
+    if (inodeHash.count(dirent->d_ino) != 0u) {
       DLOG(WARNING) << dirent->d_name << " is already linked";
       continue;
     }
@@ -101,7 +101,7 @@ void LocalStore::optimisePath_(OptimiseStats& stats, const Path& path,
   checkInterrupt();
 
   struct stat st;
-  if (lstat(path.c_str(), &st)) {
+  if (lstat(path.c_str(), &st) != 0) {
     throw SysError(format("getting attributes of path '%1%'") % path);
   }
 
@@ -137,13 +137,13 @@ void LocalStore::optimisePath_(OptimiseStats& stats, const Path& path,
      modified, in particular when running programs as root under
      NixOS (example: $fontconfig/var/cache being modified).  Skip
      those files.  FIXME: check the modification time. */
-  if (S_ISREG(st.st_mode) && (st.st_mode & S_IWUSR)) {
+  if (S_ISREG(st.st_mode) && ((st.st_mode & S_IWUSR) != 0u)) {
     LOG(WARNING) << "skipping suspicious writable file '" << path << "'";
     return;
   }
 
   /* This can still happen on top-level files. */
-  if (st.st_nlink > 1 && inodeHash.count(st.st_ino)) {
+  if (st.st_nlink > 1 && (inodeHash.count(st.st_ino) != 0u)) {
     DLOG(INFO) << path << " is already linked, with " << (st.st_nlink - 2)
                << " other file(s)";
     return;
@@ -196,7 +196,7 @@ retry:
   /* Yes!  We've seen a file with the same contents.  Replace the
      current file with a hard link to that file. */
   struct stat stLink;
-  if (lstat(linkPath.c_str(), &stLink)) {
+  if (lstat(linkPath.c_str(), &stLink) != 0) {
     throw SysError(format("getting attributes of path '%1%'") % linkPath);
   }
 
@@ -234,7 +234,7 @@ retry:
       /* Too many links to the same file (>= 32000 on most file
          systems).  This is likely to happen with empty files.
          Just shrug and ignore. */
-      if (st.st_size) {
+      if (st.st_size != 0) {
         LOG(WARNING) << linkPath << " has maximum number of links";
       }
       return;
diff --git a/third_party/nix/src/libstore/parsed-derivations.cc b/third_party/nix/src/libstore/parsed-derivations.cc
index ec158e0ab1a0..1186203249de 100644
--- a/third_party/nix/src/libstore/parsed-derivations.cc
+++ b/third_party/nix/src/libstore/parsed-derivations.cc
@@ -22,20 +22,19 @@ std::optional<std::string> ParsedDerivation::getStringAttr(
     auto i = structuredAttrs->find(name);
     if (i == structuredAttrs->end()) {
       return {};
-    } else {
-      if (!i->is_string()) {
-        throw Error("attribute '%s' of derivation '%s' must be a string", name,
-                    drvPath);
-      }
-      return i->get<std::string>();
     }
+    if (!i->is_string()) {
+      throw Error("attribute '%s' of derivation '%s' must be a string", name,
+                  drvPath);
+    }
+    return i->get<std::string>();
+
   } else {
     auto i = drv.env.find(name);
     if (i == drv.env.end()) {
       return {};
-    } else {
-      return i->second;
     }
+    return i->second;
   }
 }
 
@@ -44,20 +43,19 @@ bool ParsedDerivation::getBoolAttr(const std::string& name, bool def) const {
     auto i = structuredAttrs->find(name);
     if (i == structuredAttrs->end()) {
       return def;
-    } else {
-      if (!i->is_boolean()) {
-        throw Error("attribute '%s' of derivation '%s' must be a Boolean", name,
-                    drvPath);
-      }
-      return i->get<bool>();
     }
+    if (!i->is_boolean()) {
+      throw Error("attribute '%s' of derivation '%s' must be a Boolean", name,
+                  drvPath);
+    }
+    return i->get<bool>();
+
   } else {
     auto i = drv.env.find(name);
     if (i == drv.env.end()) {
       return def;
-    } else {
-      return i->second == "1";
     }
+    return i->second == "1";
   }
 }
 
@@ -67,30 +65,28 @@ std::optional<Strings> ParsedDerivation::getStringsAttr(
     auto i = structuredAttrs->find(name);
     if (i == structuredAttrs->end()) {
       return {};
-    } else {
-      if (!i->is_array()) {
+    }
+    if (!i->is_array()) {
+      throw Error("attribute '%s' of derivation '%s' must be a list of strings",
+                  name, drvPath);
+    }
+    Strings res;
+    for (const auto& j : *i) {
+      if (!j.is_string()) {
         throw Error(
             "attribute '%s' of derivation '%s' must be a list of strings", name,
             drvPath);
       }
-      Strings res;
-      for (const auto& j : *i) {
-        if (!j.is_string()) {
-          throw Error(
-              "attribute '%s' of derivation '%s' must be a list of strings",
-              name, drvPath);
-        }
-        res.push_back(j.get<std::string>());
-      }
-      return res;
+      res.push_back(j.get<std::string>());
     }
+    return res;
+
   } else {
     auto i = drv.env.find(name);
     if (i == drv.env.end()) {
       return {};
-    } else {
-      return tokenizeString<Strings>(i->second);
     }
+    return tokenizeString<Strings>(i->second);
   }
 }
 
@@ -104,12 +100,13 @@ StringSet ParsedDerivation::getRequiredSystemFeatures() const {
 
 bool ParsedDerivation::canBuildLocally() const {
   if (drv.platform != settings.thisSystem.get() &&
-      !settings.extraPlatforms.get().count(drv.platform) && !drv.isBuiltin()) {
+      (settings.extraPlatforms.get().count(drv.platform) == 0u) &&
+      !drv.isBuiltin()) {
     return false;
   }
 
   for (auto& feature : getRequiredSystemFeatures()) {
-    if (!settings.systemFeatures.get().count(feature)) {
+    if (settings.systemFeatures.get().count(feature) == 0u) {
       return false;
     }
   }
diff --git a/third_party/nix/src/libstore/pathlocks.cc b/third_party/nix/src/libstore/pathlocks.cc
index ac6d260f8414..eeee5ee1e9c9 100644
--- a/third_party/nix/src/libstore/pathlocks.cc
+++ b/third_party/nix/src/libstore/pathlocks.cc
@@ -53,9 +53,8 @@ bool lockFile(int fd, LockType lockType, bool wait) {
       checkInterrupt();
       if (errno != EINTR) {
         throw SysError(format("acquiring/releasing lock"));
-      } else {
-        return false;
       }
+      return false;
     }
   } else {
     while (flock(fd, type | LOCK_NB) != 0) {
@@ -104,7 +103,7 @@ bool PathLocks::lockPaths(const PathSet& paths, const string& waitMsg,
       /* Acquire an exclusive lock. */
       if (!lockFile(fd.get(), ltWrite, false)) {
         if (wait) {
-          if (waitMsg != "") {
+          if (!waitMsg.empty()) {
             LOG(WARNING) << waitMsg;
           }
           lockFile(fd.get(), ltWrite, true);
diff --git a/third_party/nix/src/libstore/profiles.cc b/third_party/nix/src/libstore/profiles.cc
index 3abdfaf1389f..7d16d9f62390 100644
--- a/third_party/nix/src/libstore/profiles.cc
+++ b/third_party/nix/src/libstore/profiles.cc
@@ -31,9 +31,8 @@ static int parseName(const string& profileName, const string& name) {
   int n;
   if (string2Int(string(s, 0, p), n) && n >= 0) {
     return n;
-  } else {
-    return -1;
   }
+  return -1;
 }
 
 Generations findGenerations(Path profile, int& curGen) {
@@ -76,7 +75,7 @@ Path createGeneration(ref<LocalFSStore> store, Path profile, Path outPath) {
   Generations gens = findGenerations(profile, dummy);
 
   unsigned int num;
-  if (gens.size() > 0) {
+  if (!gens.empty()) {
     Generation last = gens.back();
 
     if (readLink(last.path) == outPath) {
@@ -165,7 +164,7 @@ void deleteGenerationsGreaterThan(const Path& profile, int max, bool dryRun) {
       continue;
     }
     if (fromCurGen) {
-      if (max) {
+      if (max != 0) {
         max--;
         continue;
       }
diff --git a/third_party/nix/src/libstore/remote-fs-accessor.cc b/third_party/nix/src/libstore/remote-fs-accessor.cc
index 819f54c161e8..9aceaa9815b5 100644
--- a/third_party/nix/src/libstore/remote-fs-accessor.cc
+++ b/third_party/nix/src/libstore/remote-fs-accessor.cc
@@ -11,14 +11,14 @@ namespace nix {
 
 RemoteFSAccessor::RemoteFSAccessor(ref<Store> store, const Path& cacheDir)
     : store(store), cacheDir(cacheDir) {
-  if (cacheDir != "") {
+  if (!cacheDir.empty()) {
     createDirs(cacheDir);
   }
 }
 
 Path RemoteFSAccessor::makeCacheFile(const Path& storePath,
                                      const std::string& ext) {
-  assert(cacheDir != "");
+  assert(!cacheDir.empty());
   return fmt("%s/%s.%s", cacheDir, storePathToHash(storePath), ext);
 }
 
@@ -26,7 +26,7 @@ void RemoteFSAccessor::addToCache(const Path& storePath, const std::string& nar,
                                   ref<FSAccessor> narAccessor) {
   nars.emplace(storePath, narAccessor);
 
-  if (cacheDir != "") {
+  if (!cacheDir.empty()) {
     try {
       std::ostringstream str;
       JSONPlaceholder jsonRoot(str);
@@ -62,7 +62,7 @@ std::pair<ref<FSAccessor>, Path> RemoteFSAccessor::fetch(const Path& path_) {
   std::string listing;
   Path cacheFile;
 
-  if (cacheDir != "" &&
+  if (!cacheDir.empty() &&
       pathExists(cacheFile = makeCacheFile(storePath, "nar"))) {
     try {
       listing = nix::readFile(makeCacheFile(storePath, "ls"));
diff --git a/third_party/nix/src/libstore/remote-store.cc b/third_party/nix/src/libstore/remote-store.cc
index 564ba444d242..c4215800da8d 100644
--- a/third_party/nix/src/libstore/remote-store.cc
+++ b/third_party/nix/src/libstore/remote-store.cc
@@ -81,9 +81,8 @@ UDSRemoteStore::UDSRemoteStore(std::string socket_path, const Params& params)
 std::string UDSRemoteStore::getUri() {
   if (path) {
     return std::string("unix://") + *path;
-  } else {
-    return "daemon";
   }
+  return "daemon";
 }
 
 ref<RemoteStore::Connection> UDSRemoteStore::openConnection() {
@@ -155,7 +154,7 @@ void RemoteStore::initConnection(Connection& conn) {
     }
 
     if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 11) {
-      conn.to << false;
+      conn.to << 0u;
     }
 
     auto ex = conn.processStderr();
@@ -171,17 +170,18 @@ void RemoteStore::initConnection(Connection& conn) {
 }
 
 void RemoteStore::setOptions(Connection& conn) {
-  conn.to << wopSetOptions << settings.keepFailed
-          << settings.keepGoing
+  conn.to << wopSetOptions << static_cast<uint64_t>(settings.keepFailed)
+          << static_cast<uint64_t>(settings.keepGoing)
           // TODO(tazjin): Remove the verbosity stuff here.
-          << settings.tryFallback << compat::kInfo << settings.maxBuildJobs
-          << settings.maxSilentTime
-          << true
+          << static_cast<uint64_t>(settings.tryFallback) << compat::kInfo
+          << settings.maxBuildJobs << settings.maxSilentTime
+          << 1u
           // TODO(tazjin): what behaviour does this toggle remotely?
           << (settings.verboseBuild ? compat::kError : compat::kVomit)
           << 0  // obsolete log type
           << 0  /* obsolete print build trace */
-          << settings.buildCores << settings.useSubstitutes;
+          << settings.buildCores
+          << static_cast<uint64_t>(settings.useSubstitutes);
 
   if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 12) {
     std::map<std::string, Config::SettingInfo> overrides;
@@ -221,7 +221,7 @@ struct ConnectionHandle {
   ConnectionHandle(ConnectionHandle&& h) : handle(std::move(h.handle)) {}
 
   ~ConnectionHandle() {
-    if (!daemonException && std::uncaught_exceptions()) {
+    if (!daemonException && (std::uncaught_exceptions() != 0)) {
       handle.markBad();
       // TODO(tazjin): are these types of things supposed to be DEBUG?
       DLOG(INFO) << "closing daemon connection because of an exception";
@@ -247,7 +247,7 @@ bool RemoteStore::isValidPathUncached(const Path& path) {
   auto conn(getConnection());
   conn->to << wopIsValidPath << path;
   conn.processStderr();
-  return readInt(conn->from);
+  return readInt(conn->from) != 0u;
 }
 
 PathSet RemoteStore::queryValidPaths(const PathSet& paths,
@@ -261,11 +261,10 @@ PathSet RemoteStore::queryValidPaths(const PathSet& paths,
       }
     }
     return res;
-  } else {
-    conn->to << wopQueryValidPaths << paths;
-    conn.processStderr();
-    return readStorePaths<PathSet>(*this, conn->from);
   }
+  conn->to << wopQueryValidPaths << paths;
+  conn.processStderr();
+  return readStorePaths<PathSet>(*this, conn->from);
 }
 
 PathSet RemoteStore::queryAllValidPaths() {
@@ -282,16 +281,15 @@ PathSet RemoteStore::querySubstitutablePaths(const PathSet& paths) {
     for (auto& i : paths) {
       conn->to << wopHasSubstitutes << i;
       conn.processStderr();
-      if (readInt(conn->from)) {
+      if (readInt(conn->from) != 0u) {
         res.insert(i);
       }
     }
     return res;
-  } else {
-    conn->to << wopQuerySubstitutablePaths << paths;
-    conn.processStderr();
-    return readStorePaths<PathSet>(*this, conn->from);
   }
+  conn->to << wopQuerySubstitutablePaths << paths;
+  conn.processStderr();
+  return readStorePaths<PathSet>(*this, conn->from);
 }
 
 void RemoteStore::querySubstitutablePathInfos(const PathSet& paths,
@@ -312,7 +310,7 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet& paths,
         continue;
       }
       info.deriver = readString(conn->from);
-      if (info.deriver != "") {
+      if (!info.deriver.empty()) {
         assertStorePath(info.deriver);
       }
       info.references = readStorePaths<PathSet>(*this, conn->from);
@@ -329,7 +327,7 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet& paths,
       Path path = readStorePath(*this, conn->from);
       SubstitutablePathInfo& info(infos[path]);
       info.deriver = readString(conn->from);
-      if (info.deriver != "") {
+      if (!info.deriver.empty()) {
         assertStorePath(info.deriver);
       }
       info.references = readStorePaths<PathSet>(*this, conn->from);
@@ -366,7 +364,7 @@ void RemoteStore::queryPathInfoUncached(
       info = std::make_shared<ValidPathInfo>();
       info->path = path;
       info->deriver = readString(conn->from);
-      if (info->deriver != "") {
+      if (!info->deriver.empty()) {
         assertStorePath(info->deriver);
       }
       info->narHash = Hash(readString(conn->from), htSHA256);
@@ -464,7 +462,7 @@ void RemoteStore::addToStore(const ValidPathInfo& info, Source& source,
 Path RemoteStore::addToStore(const string& name, const Path& _srcPath,
                              bool recursive, HashType hashAlgo,
                              PathFilter& filter, RepairFlag repair) {
-  if (repair) {
+  if (repair != 0u) {
     throw Error(
         "repairing is not supported when building through the Nix daemon");
   }
@@ -506,7 +504,7 @@ Path RemoteStore::addToStore(const string& name, const Path& _srcPath,
 
 Path RemoteStore::addTextToStore(const string& name, const string& s,
                                  const PathSet& references, RepairFlag repair) {
-  if (repair) {
+  if (repair != 0u) {
     throw Error(
         "repairing is not supported when building through the Nix daemon");
   }
@@ -593,7 +591,7 @@ Roots RemoteStore::findRoots(bool censor) {
   conn.processStderr();
   auto count = readNum<size_t>(conn->from);
   Roots result;
-  while (count--) {
+  while ((count--) != 0u) {
     Path link = readString(conn->from);
     Path target = readStorePath(*this, conn->from);
     result[target].emplace(link);
@@ -605,7 +603,7 @@ void RemoteStore::collectGarbage(const GCOptions& options, GCResults& results) {
   auto conn(getConnection());
 
   conn->to << wopCollectGarbage << options.action << options.pathsToDelete
-           << options.ignoreLiveness
+           << static_cast<uint64_t>(options.ignoreLiveness)
            << options.maxFreed
            /* removed options */
            << 0 << 0 << 0;
@@ -631,9 +629,9 @@ void RemoteStore::optimiseStore() {
 
 bool RemoteStore::verifyStore(bool checkContents, RepairFlag repair) {
   auto conn(getConnection());
-  conn->to << wopVerifyStore << checkContents << repair;
+  conn->to << wopVerifyStore << static_cast<uint64_t>(checkContents) << repair;
   conn.processStderr();
-  return readInt(conn->from);
+  return readInt(conn->from) != 0u;
 }
 
 void RemoteStore::addSignatures(const Path& storePath, const StringSet& sigs) {
@@ -694,14 +692,14 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink* sink,
 
     if (msg == STDERR_WRITE) {
       string s = readString(from);
-      if (!sink) {
+      if (sink == nullptr) {
         throw Error("no sink");
       }
       (*sink)(s);
     }
 
     else if (msg == STDERR_READ) {
-      if (!source) {
+      if (source == nullptr) {
         throw Error("no source");
       }
       auto len = readNum<size_t>(from);
diff --git a/third_party/nix/src/libstore/remote-store.hh b/third_party/nix/src/libstore/remote-store.hh
index f2692193433e..dc44cd32ac47 100644
--- a/third_party/nix/src/libstore/remote-store.hh
+++ b/third_party/nix/src/libstore/remote-store.hh
@@ -59,7 +59,7 @@ class RemoteStore : public virtual Store {
   void querySubstitutablePathInfos(const PathSet& paths,
                                    SubstitutablePathInfos& infos) override;
 
-  void addToStore(const ValidPathInfo& info, Source& nar, RepairFlag repair,
+  void addToStore(const ValidPathInfo& info, Source& source, RepairFlag repair,
                   CheckSigsFlag checkSigs,
                   std::shared_ptr<FSAccessor> accessor) override;
 
diff --git a/third_party/nix/src/libstore/sqlite.cc b/third_party/nix/src/libstore/sqlite.cc
index 2288277659a3..2dea952d0275 100644
--- a/third_party/nix/src/libstore/sqlite.cc
+++ b/third_party/nix/src/libstore/sqlite.cc
@@ -14,7 +14,7 @@ namespace nix {
   int exterr = sqlite3_extended_errcode(db);
 
   auto path = sqlite3_db_filename(db, nullptr);
-  if (!path) {
+  if (path == nullptr) {
     path = "(in-memory)";
   }
 
@@ -23,9 +23,8 @@ namespace nix {
         err == SQLITE_PROTOCOL
             ? fmt("SQLite database '%s' is busy (SQLITE_PROTOCOL)", path)
             : fmt("SQLite database '%s' is busy", path));
-  } else {
-    throw SQLiteError("%s: %s (in '%s')", fs.s, sqlite3_errstr(exterr), path);
   }
+  throw SQLiteError("%s: %s (in '%s')", fs.s, sqlite3_errstr(exterr), path);
 }
 
 SQLite::SQLite(const Path& path) {
@@ -38,7 +37,7 @@ SQLite::SQLite(const Path& path) {
 
 SQLite::~SQLite() {
   try {
-    if (db && sqlite3_close(db) != SQLITE_OK) {
+    if ((db != nullptr) && sqlite3_close(db) != SQLITE_OK) {
       throwSQLiteError(db, "closing database");
     }
   } catch (...) {
@@ -67,7 +66,7 @@ void SQLiteStmt::create(sqlite3* db, const string& sql) {
 
 SQLiteStmt::~SQLiteStmt() {
   try {
-    if (stmt && sqlite3_finalize(stmt) != SQLITE_OK) {
+    if ((stmt != nullptr) && sqlite3_finalize(stmt) != SQLITE_OK) {
       throwSQLiteError(db, fmt("finalizing statement '%s'", sql));
     }
   } catch (...) {
diff --git a/third_party/nix/src/libstore/ssh.cc b/third_party/nix/src/libstore/ssh.cc
index d549d5c3657b..06aaf285f1b5 100644
--- a/third_party/nix/src/libstore/ssh.cc
+++ b/third_party/nix/src/libstore/ssh.cc
@@ -12,7 +12,7 @@ SSHMaster::SSHMaster(const std::string& host, std::string keyFile,
       useMaster(useMaster && !fakeSSH),
       compress(compress),
       logFD(logFD) {
-  if (host == "" || hasPrefix(host, "-")) {
+  if (host.empty() || hasPrefix(host, "-")) {
     throw Error("invalid SSH host name '%s'", host);
   }
 }
@@ -33,7 +33,8 @@ std::unique_ptr<SSHMaster::Connection> SSHMaster::startCommand(
     const std::string& command) {
   Path socketPath = startMaster();
 
-  Pipe in, out;
+  Pipe in;
+  Pipe out;
   in.create();
   out.create();
 
@@ -63,9 +64,9 @@ std::unique_ptr<SSHMaster::Connection> SSHMaster::startCommand(
         if (fakeSSH) {
           args = {"bash", "-c"};
         } else {
-          args = {"ssh", host.c_str(), "-x", "-a"};
+          args = {"ssh", host, "-x", "-a"};
           addCommonSSHOpts(args);
-          if (socketPath != "") {
+          if (!socketPath.empty()) {
             args.insert(args.end(), {"-S", socketPath});
           }
           // TODO(tazjin): Abseil verbosity flag
@@ -123,7 +124,7 @@ Path SSHMaster::startMaster() {
           throw SysError("duping over stdout");
         }
 
-        Strings args = {"ssh", host.c_str(),
+        Strings args = {"ssh", host,
                         "-M",  "-N",
                         "-S",  state->socketPath,
                         "-o",  "LocalCommand=echo started",
diff --git a/third_party/nix/src/libstore/store-api.cc b/third_party/nix/src/libstore/store-api.cc
index 84b5841a82e6..39cb5ca9f6c8 100644
--- a/third_party/nix/src/libstore/store-api.cc
+++ b/third_party/nix/src/libstore/store-api.cc
@@ -37,9 +37,8 @@ Path Store::toStorePath(const Path& path) const {
   Path::size_type slash = path.find('/', storeDir.size() + 1);
   if (slash == Path::npos) {
     return path;
-  } else {
-    return Path(path, 0, slash);
   }
+  return Path(path, 0, slash);
 }
 
 Path Store::followLinksToStore(const Path& _path) const {
@@ -333,7 +332,7 @@ void Store::queryPathInfo(const Path& storePath,
               res.first == NarInfoDiskCache::oInvalid ? nullptr : res.second);
           if (res.first == NarInfoDiskCache::oInvalid ||
               (res.second->path != storePath &&
-               storePathToName(storePath) != "")) {
+               !storePathToName(storePath).empty())) {
             throw InvalidPath(format("path '%s' is not valid") % storePath);
           }
         }
@@ -362,8 +361,8 @@ void Store::queryPathInfo(const Path& storePath,
             state_->pathInfoCache.upsert(hashPart, info);
           }
 
-          if (!info ||
-              (info->path != storePath && storePathToName(storePath) != "")) {
+          if (!info || (info->path != storePath &&
+                        !storePathToName(storePath).empty())) {
             stats.narInfoMissing++;
             throw InvalidPath("path '%s' is not valid", storePath);
           }
@@ -401,7 +400,7 @@ PathSet Store::queryValidPaths(const PathSet& paths,
             state->exc = std::current_exception();
           }
           assert(state->left);
-          if (!--state->left) {
+          if (--state->left == 0u) {
             wakeup.notify_one();
           }
         }});
@@ -415,7 +414,7 @@ PathSet Store::queryValidPaths(const PathSet& paths,
 
   while (true) {
     auto state(state_.lock());
-    if (!state->left) {
+    if (state->left == 0u) {
       if (state->exc) {
         std::rethrow_exception(state->exc);
       }
@@ -430,7 +429,7 @@ PathSet Store::queryValidPaths(const PathSet& paths,
    responsibility of the caller to provide a closure. */
 string Store::makeValidityRegistration(const PathSet& paths, bool showDerivers,
                                        bool showHash) {
-  string s = "";
+  string s = s;
 
   for (auto& i : paths) {
     s += i + "\n";
@@ -478,7 +477,7 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
         }
       }
 
-      if (info->ca != "") {
+      if (!info->ca.empty()) {
         jsonPath.attr("ca", info->ca);
       }
 
@@ -490,11 +489,11 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
       }
 
       if (includeImpureInfo) {
-        if (info->deriver != "") {
+        if (!info->deriver.empty()) {
           jsonPath.attr("deriver", info->deriver);
         }
 
-        if (info->registrationTime) {
+        if (info->registrationTime != 0) {
           jsonPath.attr("registrationTime", info->registrationTime);
         }
 
@@ -519,7 +518,7 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
           if (narInfo->fileHash) {
             jsonPath.attr("downloadHash", narInfo->fileHash.to_string());
           }
-          if (narInfo->fileSize) {
+          if (narInfo->fileSize != 0u) {
             jsonPath.attr("downloadSize", narInfo->fileSize);
           }
           if (showClosureSize) {
@@ -535,7 +534,8 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
 }
 
 std::pair<uint64_t, uint64_t> Store::getClosureSize(const Path& storePath) {
-  uint64_t totalNarSize = 0, totalDownloadSize = 0;
+  uint64_t totalNarSize = 0;
+  uint64_t totalDownloadSize = 0;
   PathSet closure;
   computeFSClosure(storePath, closure, false, false);
   for (auto& p : closure) {
@@ -596,7 +596,7 @@ void copyStorePath(ref<Store> srcStore, ref<Store> dstStore,
     srcStore->narFromPath({storePath}, sink);
     auto info2 = make_ref<ValidPathInfo>(*info);
     info2->narHash = hashString(htSHA256, *sink.s);
-    if (!info->narSize) {
+    if (info->narSize == 0u) {
       info2->narSize = sink.s->size();
     }
     if (info->ultimate) {
@@ -638,7 +638,7 @@ void copyPaths(ref<Store> srcStore, ref<Store> dstStore,
 
   PathSet missing;
   for (auto& path : storePaths) {
-    if (!valid.count(path)) {
+    if (valid.count(path) == 0u) {
       missing.insert(path);
     }
   }
@@ -724,7 +724,7 @@ ValidPathInfo decodeValidPathInfo(std::istream& str, bool hashGiven) {
   if (!string2Int(s, n)) {
     throw Error("number expected");
   }
-  while (n--) {
+  while ((n--) != 0) {
     getline(str, s);
     info.references.insert(s);
   }
@@ -737,7 +737,7 @@ ValidPathInfo decodeValidPathInfo(std::istream& str, bool hashGiven) {
 string showPaths(const PathSet& paths) {
   string s;
   for (auto& i : paths) {
-    if (s.size() != 0) {
+    if (!s.empty()) {
       s += ", ";
     }
     s += "'" + i + "'";
@@ -769,9 +769,9 @@ bool ValidPathInfo::isContentAddressed(const Store& store) const {
     Hash hash(std::string(ca, 5));
     if (store.makeTextPath(storePathToName(path), hash, references) == path) {
       return true;
-    } else {
-      warn();
     }
+    warn();
+
   }
 
   else if (hasPrefix(ca, "fixed:")) {
@@ -781,9 +781,8 @@ bool ValidPathInfo::isContentAddressed(const Store& store) const {
         store.makeFixedOutputPath(recursive, hash, storePathToName(path)) ==
             path) {
       return true;
-    } else {
-      warn();
     }
+    warn();
   }
 
   return false;
@@ -900,12 +899,14 @@ ref<Store> openStore(const std::string& uri_,
 StoreType getStoreType(const std::string& uri, const std::string& stateDir) {
   if (uri == "daemon") {
     return tDaemon;
-  } else if (uri == "local" || hasPrefix(uri, "/")) {
+  }
+  if (uri == "local" || hasPrefix(uri, "/")) {
     return tLocal;
-  } else if (uri == "" || uri == "auto") {
+  } else if (uri.empty() || uri == "auto") {
     if (access(stateDir.c_str(), R_OK | W_OK) == 0) {
       return tLocal;
-    } else if (pathExists(settings.nixDaemonSocketFile)) {
+    }
+    if (pathExists(settings.nixDaemonSocketFile)) {
       return tDaemon;
     } else {
       return tLocal;
@@ -940,7 +941,7 @@ std::list<ref<Store>> getDefaultSubstituters() {
     StringSet done;
 
     auto addStore = [&](const std::string& uri) {
-      if (done.count(uri)) {
+      if (done.count(uri) != 0u) {
         return;
       }
       done.insert(uri);
diff --git a/third_party/nix/src/libstore/store-api.hh b/third_party/nix/src/libstore/store-api.hh
index e8c78b7a64e7..17299585edaf 100644
--- a/third_party/nix/src/libstore/store-api.hh
+++ b/third_party/nix/src/libstore/store-api.hh
@@ -533,12 +533,12 @@ class Store : public std::enable_shared_from_this<Store>, public Config {
      `storePath' is returned; that is, the closures under the
      `referrers' relation instead of the `references' relation is
      returned. */
-  virtual void computeFSClosure(const PathSet& paths, PathSet& out,
+  virtual void computeFSClosure(const PathSet& paths, PathSet& paths_,
                                 bool flipDirection = false,
                                 bool includeOutputs = false,
                                 bool includeDerivers = false);
 
-  void computeFSClosure(const Path& path, PathSet& out,
+  void computeFSClosure(const Path& path, PathSet& paths_,
                         bool flipDirection = false, bool includeOutputs = false,
                         bool includeDerivers = false);
 
diff --git a/third_party/nix/src/libutil/archive.cc b/third_party/nix/src/libutil/archive.cc
index a316336ec73f..6583dc20b899 100644
--- a/third_party/nix/src/libutil/archive.cc
+++ b/third_party/nix/src/libutil/archive.cc
@@ -40,7 +40,7 @@ const std::string narVersionMagic1 = "nix-archive-1";
 
 static string caseHackSuffix = "~nix~case~hack~";
 
-PathFilter defaultPathFilter = [](const Path&) { return true; };
+PathFilter defaultPathFilter = [](const Path& /*unused*/) { return true; };
 
 static void dumpContents(const Path& path, size_t size, Sink& sink) {
   sink << "contents" << size;
@@ -67,7 +67,7 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) {
   checkInterrupt();
 
   struct stat st;
-  if (lstat(path.c_str(), &st)) {
+  if (lstat(path.c_str(), &st) != 0) {
     throw SysError(format("getting attributes of path '%1%'") % path);
   }
 
@@ -76,7 +76,7 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) {
   if (S_ISREG(st.st_mode)) {
     sink << "type"
          << "regular";
-    if (st.st_mode & S_IXUSR) {
+    if ((st.st_mode & S_IXUSR) != 0u) {
       sink << "executable"
            << "";
     }
@@ -167,7 +167,7 @@ static void parseContents(ParseSink& sink, Source& source, const Path& path) {
   unsigned long long left = size;
   std::vector<unsigned char> buf(65536);
 
-  while (left) {
+  while (left != 0u) {
     checkInterrupt();
     auto n = buf.size();
     if ((unsigned long long)n > left) {
@@ -208,7 +208,7 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
       break;
     }
 
-    else if (s == "type") {
+    if (s == "type") {
       if (type != tpUnknown) {
         throw badArchive("multiple type fields");
       }
@@ -240,14 +240,15 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
 
     else if (s == "executable" && type == tpRegular) {
       auto s = readString(source);
-      if (s != "") {
+      if (!s.empty()) {
         throw badArchive("executable marker has non-empty value");
       }
       sink.isExecutable();
     }
 
     else if (s == "entry" && type == tpDirectory) {
-      string name, prevName;
+      string name;
+      string prevName;
 
       s = readString(source);
       if (s != "(") {
@@ -261,7 +262,8 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
 
         if (s == ")") {
           break;
-        } else if (s == "name") {
+        }
+        if (s == "name") {
           name = readString(source);
           if (name.empty() || name == "." || name == ".." ||
               name.find('/') != string::npos ||
@@ -350,7 +352,7 @@ struct RestoreSink : ParseSink {
 
   void preallocateContents(unsigned long long len) override {
 #if HAVE_POSIX_FALLOCATE
-    if (len) {
+    if (len != 0u) {
       errno = posix_fallocate(fd.get(), 0, len);
       /* Note that EINVAL may indicate that the underlying
          filesystem doesn't support preallocation (e.g. on
diff --git a/third_party/nix/src/libutil/args.cc b/third_party/nix/src/libutil/args.cc
index 92343d88e5a3..2b4407480254 100644
--- a/third_party/nix/src/libutil/args.cc
+++ b/third_party/nix/src/libutil/args.cc
@@ -7,9 +7,9 @@ namespace nix {
 Args::FlagMaker Args::mkFlag() { return FlagMaker(*this); }
 
 Args::FlagMaker::~FlagMaker() {
-  assert(flag->longName != "");
+  assert(!flag->longName.empty());
   args.longFlags[flag->longName] = flag;
-  if (flag->shortName) {
+  if (flag->shortName != 0) {
     args.shortFlags[flag->shortName] = flag;
   }
 }
@@ -26,12 +26,12 @@ void Args::parseCmdline(const Strings& _cmdline) {
     /* Expand compound dash options (i.e., `-qlf' -> `-q -l -f',
        `-j3` -> `-j 3`). */
     if (!dashDash && arg.length() > 2 && arg[0] == '-' && arg[1] != '-' &&
-        isalpha(arg[1])) {
+        (isalpha(arg[1]) != 0)) {
       *pos = (string) "-" + arg[1];
       auto next = pos;
       ++next;
       for (unsigned int j = 2; j < arg.length(); j++) {
-        if (isalpha(arg[j])) {
+        if (isalpha(arg[j]) != 0) {
           cmdline.insert(next, (string) "-" + arg[j]);
         } else {
           cmdline.insert(next, string(arg, j));
@@ -74,11 +74,11 @@ void Args::printHelp(const string& programName, std::ostream& out) {
   std::cout << "\n";
 
   auto s = description();
-  if (s != "") {
+  if (!s.empty()) {
     std::cout << "\nSummary: " << s << ".\n";
   }
 
-  if (longFlags.size()) {
+  if (!longFlags.empty() != 0u) {
     std::cout << "\n";
     std::cout << "Flags:\n";
     printFlags(out);
@@ -88,11 +88,11 @@ void Args::printHelp(const string& programName, std::ostream& out) {
 void Args::printFlags(std::ostream& out) {
   Table2 table;
   for (auto& flag : longFlags) {
-    if (hiddenCategories.count(flag.second->category)) {
+    if (hiddenCategories.count(flag.second->category) != 0u) {
       continue;
     }
     table.push_back(std::make_pair(
-        (flag.second->shortName
+        (flag.second->shortName != 0
              ? std::string("-") + flag.second->shortName + ", "
              : "    ") +
             "--" + flag.first + renderLabels(flag.second->labels),
@@ -188,7 +188,7 @@ Strings argvToStrings(int argc, char** argv) {
   Strings args;
   argc--;
   argv++;
-  while (argc--) {
+  while ((argc--) != 0) {
     args.push_back(*argv++);
   }
   return args;
diff --git a/third_party/nix/src/libutil/compression.cc b/third_party/nix/src/libutil/compression.cc
index 851a7f817994..d7084ab7f15d 100644
--- a/third_party/nix/src/libutil/compression.cc
+++ b/third_party/nix/src/libutil/compression.cc
@@ -21,7 +21,7 @@ struct ChunkedCompressionSink : CompressionSink {
 
   void write(const unsigned char* data, size_t len) override {
     const size_t CHUNK_SIZE = sizeof(outbuf) << 2;
-    while (len) {
+    while (len != 0u) {
       size_t n = std::min(CHUNK_SIZE, len);
       writeInternal(data, n);
       data += n;
@@ -68,10 +68,10 @@ struct XzDecompressionSink : CompressionSink {
     strm.next_in = data;
     strm.avail_in = len;
 
-    while (!finished && (!data || strm.avail_in)) {
+    while (!finished && ((data == nullptr) || (strm.avail_in != 0u))) {
       checkInterrupt();
 
-      lzma_ret ret = lzma_code(&strm, data ? LZMA_RUN : LZMA_FINISH);
+      lzma_ret ret = lzma_code(&strm, data != nullptr ? LZMA_RUN : LZMA_FINISH);
       if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
         throw CompressionError("error %d while decompressing xz file", ret);
       }
@@ -116,7 +116,7 @@ struct BzipDecompressionSink : ChunkedCompressionSink {
     strm.next_in = (char*)data;
     strm.avail_in = len;
 
-    while (strm.avail_in) {
+    while (strm.avail_in != 0u) {
       checkInterrupt();
 
       int ret = BZ2_bzDecompress(&strm);
@@ -142,7 +142,7 @@ struct BrotliDecompressionSink : ChunkedCompressionSink {
 
   explicit BrotliDecompressionSink(Sink& nextSink) : nextSink(nextSink) {
     state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
-    if (!state) {
+    if (state == nullptr) {
       throw CompressionError("unable to initialize brotli decoder");
     }
   }
@@ -160,11 +160,11 @@ struct BrotliDecompressionSink : ChunkedCompressionSink {
     uint8_t* next_out = outbuf;
     size_t avail_out = sizeof(outbuf);
 
-    while (!finished && (!data || avail_in)) {
+    while (!finished && ((data == nullptr) || (avail_in != 0u))) {
       checkInterrupt();
 
-      if (!BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out,
-                                         &next_out, nullptr)) {
+      if (BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out,
+                                        &next_out, nullptr) == 0u) {
         throw CompressionError("error while decompressing brotli file");
       }
 
@@ -174,7 +174,7 @@ struct BrotliDecompressionSink : ChunkedCompressionSink {
         avail_out = sizeof(outbuf);
       }
 
-      finished = BrotliDecoderIsFinished(state);
+      finished = (BrotliDecoderIsFinished(state) != 0);
     }
   }
 };
@@ -189,9 +189,10 @@ ref<std::string> decompress(const std::string& method, const std::string& in) {
 
 ref<CompressionSink> makeDecompressionSink(const std::string& method,
                                            Sink& nextSink) {
-  if (method == "none" || method == "") {
+  if (method == "none" || method.empty()) {
     return make_ref<NoneSink>(nextSink);
-  } else if (method == "xz") {
+  }
+  if (method == "xz") {
     return make_ref<XzDecompressionSink>(nextSink);
   } else if (method == "bzip2") {
     return make_ref<BzipDecompressionSink>(nextSink);
@@ -260,10 +261,10 @@ struct XzCompressionSink : CompressionSink {
     strm.next_in = data;
     strm.avail_in = len;
 
-    while (!finished && (!data || strm.avail_in)) {
+    while (!finished && ((data == nullptr) || (strm.avail_in != 0u))) {
       checkInterrupt();
 
-      lzma_ret ret = lzma_code(&strm, data ? LZMA_RUN : LZMA_FINISH);
+      lzma_ret ret = lzma_code(&strm, data != nullptr ? LZMA_RUN : LZMA_FINISH);
       if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
         throw CompressionError("error %d while compressing xz file", ret);
       }
@@ -308,10 +309,10 @@ struct BzipCompressionSink : ChunkedCompressionSink {
     strm.next_in = (char*)data;
     strm.avail_in = len;
 
-    while (!finished && (!data || strm.avail_in)) {
+    while (!finished && ((data == nullptr) || (strm.avail_in != 0u))) {
       checkInterrupt();
 
-      int ret = BZ2_bzCompress(&strm, data ? BZ_RUN : BZ_FINISH);
+      int ret = BZ2_bzCompress(&strm, data != nullptr ? BZ_RUN : BZ_FINISH);
       if (ret != BZ_RUN_OK && ret != BZ_FINISH_OK && ret != BZ_STREAM_END) {
         throw CompressionError("error %d while compressing bzip2 file", ret);
       }
@@ -335,7 +336,7 @@ struct BrotliCompressionSink : ChunkedCompressionSink {
 
   explicit BrotliCompressionSink(Sink& nextSink) : nextSink(nextSink) {
     state = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
-    if (!state) {
+    if (state == nullptr) {
       throw CompressionError("unable to initialise brotli encoder");
     }
   }
@@ -353,12 +354,14 @@ struct BrotliCompressionSink : ChunkedCompressionSink {
     uint8_t* next_out = outbuf;
     size_t avail_out = sizeof(outbuf);
 
-    while (!finished && (!data || avail_in)) {
+    while (!finished && ((data == nullptr) || (avail_in != 0u))) {
       checkInterrupt();
 
-      if (!BrotliEncoderCompressStream(
-              state, data ? BROTLI_OPERATION_PROCESS : BROTLI_OPERATION_FINISH,
-              &avail_in, &next_in, &avail_out, &next_out, nullptr)) {
+      if (BrotliEncoderCompressStream(state,
+                                      data != nullptr ? BROTLI_OPERATION_PROCESS
+                                                      : BROTLI_OPERATION_FINISH,
+                                      &avail_in, &next_in, &avail_out,
+                                      &next_out, nullptr) == 0) {
         throw CompressionError("error while compressing brotli compression");
       }
 
@@ -368,7 +371,7 @@ struct BrotliCompressionSink : ChunkedCompressionSink {
         avail_out = sizeof(outbuf);
       }
 
-      finished = BrotliEncoderIsFinished(state);
+      finished = (BrotliEncoderIsFinished(state) != 0);
     }
   }
 };
@@ -377,7 +380,8 @@ ref<CompressionSink> makeCompressionSink(const std::string& method,
                                          Sink& nextSink, const bool parallel) {
   if (method == "none") {
     return make_ref<NoneSink>(nextSink);
-  } else if (method == "xz") {
+  }
+  if (method == "xz") {
     return make_ref<XzCompressionSink>(nextSink, parallel);
   } else if (method == "bzip2") {
     return make_ref<BzipCompressionSink>(nextSink);
diff --git a/third_party/nix/src/libutil/config.cc b/third_party/nix/src/libutil/config.cc
index 56f0c8c3e7cd..ef47c167ed49 100644
--- a/third_party/nix/src/libutil/config.cc
+++ b/third_party/nix/src/libutil/config.cc
@@ -303,7 +303,7 @@ template class BaseSetting<Strings>;
 template class BaseSetting<StringSet>;
 
 void PathSetting::set(const std::string& str) {
-  if (str == "") {
+  if (str.empty()) {
     if (allowEmpty) {
       value = "";
     } else {
@@ -356,7 +356,7 @@ GlobalConfig globalConfig;
 GlobalConfig::ConfigRegistrations* GlobalConfig::configRegistrations;
 
 GlobalConfig::Register::Register(Config* config) {
-  if (!configRegistrations) {
+  if (configRegistrations == nullptr) {
     configRegistrations = new ConfigRegistrations;
   }
   configRegistrations->emplace_back(config);
diff --git a/third_party/nix/src/libutil/hash.cc b/third_party/nix/src/libutil/hash.cc
index e33c76cc9093..81d8628e972b 100644
--- a/third_party/nix/src/libutil/hash.cc
+++ b/third_party/nix/src/libutil/hash.cc
@@ -193,7 +193,7 @@ Hash::Hash(const std::string& s, HashType type) : type(type) {
       if (i < hashSize - 1) {
         hash[i + 1] |= digit >> (8 - j);
       } else {
-        if (digit >> (8 - j)) {
+        if ((digit >> (8 - j)) != 0) {
           throw BadHash("invalid base-32 hash '%s'", s);
         }
       }
@@ -280,7 +280,7 @@ Hash hashFile(HashType ht, const Path& path) {
 
   std::vector<unsigned char> buf(8192);
   ssize_t n;
-  while ((n = read(fd.get(), buf.data(), buf.size()))) {
+  while ((n = read(fd.get(), buf.data(), buf.size())) != 0) {
     checkInterrupt();
     if (n == -1) {
       throw SysError(format("reading file '%1%'") % path);
@@ -341,7 +341,8 @@ Hash compressHash(const Hash& hash, unsigned int newSize) {
 HashType parseHashType(const string& s) {
   if (s == "md5") {
     return htMD5;
-  } else if (s == "sha1") {
+  }
+  if (s == "sha1") {
     return htSHA1;
   } else if (s == "sha256") {
     return htSHA256;
@@ -355,7 +356,8 @@ HashType parseHashType(const string& s) {
 string printHashType(HashType ht) {
   if (ht == htMD5) {
     return "md5";
-  } else if (ht == htSHA1) {
+  }
+  if (ht == htSHA1) {
     return "sha1";
   } else if (ht == htSHA256) {
     return "sha256";
diff --git a/third_party/nix/src/libutil/json.cc b/third_party/nix/src/libutil/json.cc
index c5f52ae8ef3f..218fc264ba50 100644
--- a/third_party/nix/src/libutil/json.cc
+++ b/third_party/nix/src/libutil/json.cc
@@ -27,7 +27,7 @@ void toJSON(std::ostream& str, const char* start, const char* end) {
 }
 
 void toJSON(std::ostream& str, const char* s) {
-  if (!s) {
+  if (s == nullptr) {
     str << "null";
   } else {
     toJSON(str, s, s + strlen(s));
@@ -91,7 +91,7 @@ JSONWriter::JSONWriter(std::ostream& str, bool indent)
 JSONWriter::JSONWriter(JSONState* state) : state(state) { state->stack++; }
 
 JSONWriter::~JSONWriter() {
-  if (state) {
+  if (state != nullptr) {
     assertActive();
     state->stack--;
     if (state->stack == 0) {
@@ -150,7 +150,7 @@ void JSONObject::open() {
 }
 
 JSONObject::~JSONObject() {
-  if (state) {
+  if (state != nullptr) {
     state->depth--;
     if (state->indent && !first) {
       indent();
diff --git a/third_party/nix/src/libutil/serialise.cc b/third_party/nix/src/libutil/serialise.cc
index 0d9b069a2887..4b12367196f1 100644
--- a/third_party/nix/src/libutil/serialise.cc
+++ b/third_party/nix/src/libutil/serialise.cc
@@ -16,7 +16,7 @@ void BufferedSink::operator()(const unsigned char* data, size_t len) {
     buffer = decltype(buffer)(new unsigned char[bufSize]);
   }
 
-  while (len) {
+  while (len != 0u) {
     /* Optimisation: bypass the buffer if the data exceeds the
        buffer size. */
     if (bufPos + len >= bufSize) {
@@ -81,7 +81,7 @@ void FdSink::write(const unsigned char* data, size_t len) {
 bool FdSink::good() { return _good; }
 
 void Source::operator()(unsigned char* data, size_t len) {
-  while (len) {
+  while (len != 0u) {
     size_t n = read(data, len);
     data += n;
     len -= n;
@@ -108,7 +108,7 @@ size_t BufferedSource::read(unsigned char* data, size_t len) {
     buffer = decltype(buffer)(new unsigned char[bufSize]);
   }
 
-  if (!bufPosIn) {
+  if (bufPosIn == 0u) {
     bufPosIn = readUnbuffered(buffer.get(), bufSize);
   }
 
@@ -177,7 +177,7 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun,
       if (!coro) {
         coro = coro_t::pull_type([&](coro_t::push_type& yield) {
           LambdaSink sink([&](const unsigned char* data, size_t len) {
-            if (len) {
+            if (len != 0u) {
               yield(std::string((const char*)data, len));
             }
           });
@@ -210,7 +210,7 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun,
 }
 
 void writePadding(size_t len, Sink& sink) {
-  if (len % 8) {
+  if ((len % 8) != 0u) {
     unsigned char zero[8];
     memset(zero, 0, sizeof(zero));
     sink(zero, 8 - (len % 8));
@@ -247,12 +247,12 @@ Sink& operator<<(Sink& sink, const StringSet& s) {
 }
 
 void readPadding(size_t len, Source& source) {
-  if (len % 8) {
+  if ((len % 8) != 0u) {
     unsigned char zero[8];
     size_t n = 8 - (len % 8);
     source(zero, n);
     for (unsigned int i = 0; i < n; i++) {
-      if (zero[i]) {
+      if (zero[i] != 0u) {
         throw SerialisationError("non-zero padding");
       }
     }
diff --git a/third_party/nix/src/libutil/thread-pool.cc b/third_party/nix/src/libutil/thread-pool.cc
index d0042c6df195..879de446c294 100644
--- a/third_party/nix/src/libutil/thread-pool.cc
+++ b/third_party/nix/src/libutil/thread-pool.cc
@@ -8,9 +8,9 @@ namespace nix {
 ThreadPool::ThreadPool(size_t _maxThreads) : maxThreads(_maxThreads) {
   restoreAffinity();  // FIXME
 
-  if (!maxThreads) {
+  if (maxThreads == 0u) {
     maxThreads = std::thread::hardware_concurrency();
-    if (!maxThreads) {
+    if (maxThreads == 0u) {
       maxThreads = 1;
     }
   }
@@ -111,8 +111,8 @@ void ThreadPool::doWork(bool mainThread) {
             try {
               std::rethrow_exception(exc);
             } catch (std::exception& e) {
-              if (!dynamic_cast<Interrupted*>(&e) &&
-                  !dynamic_cast<ThreadPoolShutDown*>(&e)) {
+              if ((dynamic_cast<Interrupted*>(&e) == nullptr) &&
+                  (dynamic_cast<ThreadPoolShutDown*>(&e) == nullptr)) {
                 ignoreException();
               }
             } catch (...) {
@@ -135,7 +135,7 @@ void ThreadPool::doWork(bool mainThread) {
         /* If there are no active or pending items, and the
            main thread is running process(), then no new items
            can be added. So exit. */
-        if (!state->active && state->draining) {
+        if ((state->active == 0u) && state->draining) {
           quit = true;
           work.notify_all();
           return;
diff --git a/third_party/nix/src/libutil/util.cc b/third_party/nix/src/libutil/util.cc
index a4e382f12ebe..21da06b8ab1e 100644
--- a/third_party/nix/src/libutil/util.cc
+++ b/third_party/nix/src/libutil/util.cc
@@ -35,7 +35,7 @@
 #include <sys/prctl.h>
 #endif
 
-extern char** environ __attribute__((weak));
+__attribute__((weak));
 
 namespace nix {
 
@@ -53,15 +53,15 @@ std::string SysError::addErrno(const std::string& s) {
 
 string getEnv(const string& key, const string& def) {
   char* value = getenv(key.c_str());
-  return value ? string(value) : def;
+  return value != nullptr ? string(value) : def;
 }
 
 std::map<std::string, std::string> getEnv() {
   std::map<std::string, std::string> env;
-  for (size_t i = 0; environ[i]; ++i) {
+  for (size_t i = 0; environ[i] != nullptr; ++i) {
     auto s = environ[i];
     auto eq = strchr(s, '=');
-    if (!eq) {
+    if (eq == nullptr) {
       // invalid env, just keep going
       continue;
     }
@@ -85,7 +85,7 @@ void replaceEnv(std::map<std::string, std::string> newEnv) {
 
 Path absPath(Path path, Path dir) {
   if (path[0] != '/') {
-    if (dir == "") {
+    if (dir.empty()) {
 #ifdef __GNU__
       /* GNU (aka. GNU/Hurd) doesn't have any limitation on path
          lengths and doesn't define `PATH_MAX'.  */
@@ -93,7 +93,7 @@ Path absPath(Path path, Path dir) {
       if (buf == NULL)
 #else
       char buf[PATH_MAX];
-      if (!getcwd(buf, sizeof(buf))) {
+      if (getcwd(buf, sizeof(buf)) == nullptr) {
 #endif
         throw SysError("cannot get cwd");
     }
@@ -108,7 +108,7 @@ return canonPath(path);
 }  // namespace nix
 
 Path canonPath(const Path& path, bool resolveSymlinks) {
-  assert(path != "");
+  assert(!path.empty());
 
   string s;
 
@@ -116,12 +116,14 @@ Path canonPath(const Path& path, bool resolveSymlinks) {
     throw Error(format("not an absolute path: '%1%'") % path);
   }
 
-  string::const_iterator i = path.begin(), end = path.end();
+  string::const_iterator i = path.begin();
+  string::const_iterator end = path.end();
   string temp;
 
   /* Count the number of times we follow a symlink and stop at some
      arbitrary (but high) limit to prevent infinite loops. */
-  unsigned int followCount = 0, maxFollow = 1024;
+  unsigned int followCount = 0;
+  unsigned int maxFollow = 1024;
 
   while (true) {
     /* Skip slashes. */
@@ -210,7 +212,7 @@ bool isDirOrInDir(const Path& path, const Path& dir) {
 
 struct stat lstat(const Path& path) {
   struct stat st;
-  if (lstat(path.c_str(), &st)) {
+  if (lstat(path.c_str(), &st) != 0) {
     throw SysError(format("getting status of '%1%'") % path);
   }
   return st;
@@ -220,7 +222,7 @@ bool pathExists(const Path& path) {
   int res;
   struct stat st;
   res = lstat(path.c_str(), &st);
-  if (!res) {
+  if (res == 0) {
     return true;
   }
   if (errno != ENOENT && errno != ENOTDIR) {
@@ -238,9 +240,9 @@ Path readLink(const Path& path) {
     if (rlSize == -1) {
       if (errno == EINVAL) {
         throw Error("'%1%' is not a symlink", path);
-      } else {
-        throw SysError("reading symbolic link '%1%'", path);
       }
+      throw SysError("reading symbolic link '%1%'", path);
+
     } else if (rlSize < bufSize) {
       return string(buf.data(), rlSize);
     }
@@ -436,9 +438,8 @@ static Path tempName(Path tmpRoot, const Path& prefix, bool includePid,
   if (includePid) {
     return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++)
         .str();
-  } else {
-    return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str();
   }
+  return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str();
 }
 
 Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid,
@@ -473,7 +474,7 @@ Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid,
 
 std::string getUserName() {
   auto pw = getpwuid(geteuid());
-  std::string name = pw ? pw->pw_name : getEnv("USER", "");
+  std::string name = pw != nullptr ? pw->pw_name : getEnv("USER", "");
   if (name.empty()) {
     throw Error("cannot figure out user name");
   }
@@ -487,7 +488,7 @@ static Lazy<Path> getHome2([]() {
     struct passwd pwbuf;
     struct passwd* pw;
     if (getpwuid_r(geteuid(), &pwbuf, buf.data(), buf.size(), &pw) != 0 ||
-        !pw || !pw->pw_dir || !pw->pw_dir[0]) {
+        (pw == nullptr) || (pw->pw_dir == nullptr) || (pw->pw_dir[0] == 0)) {
       throw Error("cannot determine user's home directory");
     }
     homeDir = pw->pw_dir;
@@ -557,7 +558,7 @@ Paths createDirs(const Path& path) {
 }
 
 void createSymlink(const Path& target, const Path& link) {
-  if (symlink(target.c_str(), link.c_str())) {
+  if (symlink(target.c_str(), link.c_str()) != 0) {
     throw SysError(format("creating symlink from '%1%' to '%2%'") % link %
                    target);
   }
@@ -585,7 +586,7 @@ void replaceSymlink(const Path& target, const Path& link) {
 }
 
 void readFull(int fd, unsigned char* buf, size_t count) {
-  while (count) {
+  while (count != 0u) {
     checkInterrupt();
     ssize_t res = read(fd, (char*)buf, count);
     if (res == -1) {
@@ -604,7 +605,7 @@ void readFull(int fd, unsigned char* buf, size_t count) {
 
 void writeFull(int fd, const unsigned char* buf, size_t count,
                bool allowInterrupts) {
-  while (count) {
+  while (count != 0u) {
     if (allowInterrupts) {
       checkInterrupt();
     }
@@ -989,11 +990,12 @@ void runProgram2(const RunOptions& options) {
   }
 
   /* Create a pipe. */
-  Pipe out, in;
-  if (options.standardOut) {
+  Pipe out;
+  Pipe in;
+  if (options.standardOut != nullptr) {
     out.create();
   }
-  if (source) {
+  if (source != nullptr) {
     in.create();
   }
 
@@ -1011,7 +1013,7 @@ void runProgram2(const RunOptions& options) {
         if (options.environment) {
           replaceEnv(*options.environment);
         }
-        if (options.standardOut &&
+        if ((options.standardOut != nullptr) &&
             dup2(out.writeSide.get(), STDOUT_FILENO) == -1) {
           throw SysError("dupping stdout");
         }
@@ -1020,7 +1022,8 @@ void runProgram2(const RunOptions& options) {
             throw SysError("cannot dup stdout into stderr");
           }
         }
-        if (source && dup2(in.readSide.get(), STDIN_FILENO) == -1) {
+        if ((source != nullptr) &&
+            dup2(in.readSide.get(), STDIN_FILENO) == -1) {
           throw SysError("dupping stdin");
         }
 
@@ -1065,7 +1068,7 @@ void runProgram2(const RunOptions& options) {
     }
   });
 
-  if (source) {
+  if (source != nullptr) {
     in.readSide = -1;
     writerThread = std::thread([&]() {
       try {
@@ -1087,7 +1090,7 @@ void runProgram2(const RunOptions& options) {
     });
   }
 
-  if (options.standardOut) {
+  if (options.standardOut != nullptr) {
     drainFD(out.readSide.get(), *options.standardOut);
   }
 
@@ -1095,11 +1098,11 @@ void runProgram2(const RunOptions& options) {
   int status = pid.wait();
 
   /* Wait for the writer thread to finish. */
-  if (source) {
+  if (source != nullptr) {
     promise.get_future().get();
   }
 
-  if (status) {
+  if (status != 0) {
     throw ExecError(status, fmt("program '%1%' %2%", options.program,
                                 statusToString(status)));
   }
@@ -1110,7 +1113,7 @@ void closeMostFDs(const set<int>& exceptions) {
   try {
     for (auto& s : readDirectory("/proc/self/fd")) {
       auto fd = std::stoi(s.name);
-      if (!exceptions.count(fd)) {
+      if (exceptions.count(fd) == 0u) {
         DLOG(INFO) << "closing leaked FD " << fd;
         close(fd);
       }
@@ -1123,7 +1126,7 @@ void closeMostFDs(const set<int>& exceptions) {
   int maxFD = 0;
   maxFD = sysconf(_SC_OPEN_MAX);
   for (int fd = 0; fd < maxFD; ++fd) {
-    if (!exceptions.count(fd)) {
+    if (exceptions.count(fd) == 0u) {
       close(fd);
     } /* ignore result */
   }
@@ -1150,7 +1153,7 @@ void _interrupted() {
   /* Block user interrupts while an exception is being handled.
      Throwing an exception while another exception is being handled
      kills the program! */
-  if (!interruptThrown && !std::uncaught_exceptions()) {
+  if (!interruptThrown && (std::uncaught_exceptions() == 0)) {
     interruptThrown = true;
     throw Interrupted("interrupted by the user");
   }
@@ -1182,7 +1185,7 @@ template vector<string> tokenizeString(const string& s,
 string concatStringsSep(const string& sep, const Strings& ss) {
   string s;
   for (auto& i : ss) {
-    if (s.size() != 0) {
+    if (!s.empty()) {
       s += sep;
     }
     s += i;
@@ -1193,7 +1196,7 @@ string concatStringsSep(const string& sep, const Strings& ss) {
 string concatStringsSep(const string& sep, const StringSet& ss) {
   string s;
   for (auto& i : ss) {
-    if (s.size() != 0) {
+    if (!s.empty()) {
       s += sep;
     }
     s += i;
@@ -1233,7 +1236,8 @@ string statusToString(int status) {
   if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
     if (WIFEXITED(status)) {
       return (format("failed with exit code %1%") % WEXITSTATUS(status)).str();
-    } else if (WIFSIGNALED(status)) {
+    }
+    if (WIFSIGNALED(status)) {
       int sig = WTERMSIG(status);
 #if HAVE_STRSIGNAL
       const char* description = strsignal(sig);
@@ -1294,7 +1298,8 @@ void ignoreException() {
 
 std::string filterANSIEscapes(const std::string& s, bool filterAll,
                               unsigned int width) {
-  std::string t, e;
+  std::string t;
+  std::string e;
   size_t w = 0;
   auto i = s.begin();
 
@@ -1333,7 +1338,7 @@ std::string filterANSIEscapes(const std::string& s, bool filterAll,
       i++;
       t += ' ';
       w++;
-      while (w < (size_t)width && w % 8) {
+      while (w < (size_t)width && ((w % 8) != 0u)) {
         t += ' ';
         w++;
       }
@@ -1357,7 +1362,8 @@ static char base64Chars[] =
 
 string base64Encode(const string& s) {
   string res;
-  int data = 0, nbits = 0;
+  int data = 0;
+  int nbits = 0;
 
   for (char c : s) {
     data = data << 8 | (unsigned char)c;
@@ -1368,10 +1374,10 @@ string base64Encode(const string& s) {
     }
   }
 
-  if (nbits) {
+  if (nbits != 0) {
     res.push_back(base64Chars[data << (6 - nbits) & 0x3f]);
   }
-  while (res.size() % 4) {
+  while ((res.size() % 4) != 0u) {
     res.push_back('=');
   }
 
@@ -1391,7 +1397,8 @@ string base64Decode(const string& s) {
   }
 
   string res;
-  unsigned int d = 0, bits = 0;
+  unsigned int d = 0;
+  unsigned int bits = 0;
 
   for (char c : s) {
     if (c == '=') {
@@ -1478,7 +1485,7 @@ static sigset_t savedSignalMask;
 void startSignalHandlerThread() {
   updateWindowSize();
 
-  if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask)) {
+  if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask) != 0) {
     throw SysError("quering signal mask");
   }
 
@@ -1489,7 +1496,7 @@ void startSignalHandlerThread() {
   sigaddset(&set, SIGHUP);
   sigaddset(&set, SIGPIPE);
   sigaddset(&set, SIGWINCH);
-  if (pthread_sigmask(SIG_BLOCK, &set, nullptr)) {
+  if (pthread_sigmask(SIG_BLOCK, &set, nullptr) != 0) {
     throw SysError("blocking signals");
   }
 
@@ -1497,7 +1504,7 @@ void startSignalHandlerThread() {
 }
 
 void restoreSignals() {
-  if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr)) {
+  if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr) != 0) {
     throw SysError("restoring signals");
   }
 }
diff --git a/third_party/nix/src/libutil/util.hh b/third_party/nix/src/libutil/util.hh
index 2439b3da5373..737c4aa77f7a 100644
--- a/third_party/nix/src/libutil/util.hh
+++ b/third_party/nix/src/libutil/util.hh
@@ -188,10 +188,10 @@ class AutoCloseFD {
   AutoCloseFD();
   AutoCloseFD(int fd);
   AutoCloseFD(const AutoCloseFD& fd) = delete;
-  AutoCloseFD(AutoCloseFD&& fd);
+  AutoCloseFD(AutoCloseFD&& that);
   ~AutoCloseFD();
   AutoCloseFD& operator=(const AutoCloseFD& fd) = delete;
-  AutoCloseFD& operator=(AutoCloseFD&& fd);
+  AutoCloseFD& operator=(AutoCloseFD&& that);
   int get() const;
   explicit operator bool() const;
   int release();
diff --git a/third_party/nix/src/nix-build/nix-build.cc b/third_party/nix/src/nix-build/nix-build.cc
index b2cc303ba816..5090cbe51370 100644
--- a/third_party/nix/src/nix-build/nix-build.cc
+++ b/third_party/nix/src/nix-build/nix-build.cc
@@ -23,7 +23,7 @@
 using namespace nix;
 using namespace std::string_literals;
 
-extern char** environ __attribute__((weak));
+__attribute__((weak));
 
 /* Recreate the effect of the perl shellwords function, breaking up a
  * string into arguments like a shell word, including escapes
@@ -75,7 +75,8 @@ static void _main(int argc, char** argv) {
   auto fromArgs = false;
   auto packages = false;
   // Same condition as bash uses for interactive shells
-  auto interactive = isatty(STDIN_FILENO) && isatty(STDERR_FILENO);
+  auto interactive =
+      (isatty(STDIN_FILENO) != 0) && (isatty(STDERR_FILENO) != 0);
   Strings attrPaths;
   Strings left;
   RepairFlag repair = NoRepair;
@@ -344,8 +345,11 @@ static void _main(int argc, char** argv) {
   auto buildPaths = [&](const PathSet& paths) {
     /* Note: we do this even when !printMissing to efficiently
        fetch binary cache data. */
-    unsigned long long downloadSize, narSize;
-    PathSet willBuild, willSubstitute, unknown;
+    unsigned long long downloadSize;
+    unsigned long long narSize;
+    PathSet willBuild;
+    PathSet willSubstitute;
+    PathSet unknown;
     store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize,
                         narSize);
 
@@ -374,7 +378,7 @@ static void _main(int argc, char** argv) {
        <nixpkgs>. */
     auto shell = getEnv("NIX_BUILD_SHELL", "");
 
-    if (shell == "") {
+    if (shell.empty()) {
       try {
         auto expr = state->parseExprFromString(
             "(import <nixpkgs> {}).bashInteractive", absPath("."));
@@ -427,7 +431,7 @@ static void _main(int argc, char** argv) {
     if (pure) {
       decltype(env) newEnv;
       for (auto& i : env) {
-        if (keepVars.count(i.first)) {
+        if (keepVars.count(i.first) != 0u) {
           newEnv.emplace(i);
         }
       }
@@ -447,7 +451,7 @@ static void _main(int argc, char** argv) {
     int fileNr = 0;
 
     for (auto& var : drv.env) {
-      if (passAsFile.count(var.first)) {
+      if (passAsFile.count(var.first) != 0u) {
         keepTmp = true;
         string fn = ".attr-" + std::to_string(fileNr++);
         Path p = (Path)tmpDir + "/" + fn;
@@ -485,8 +489,9 @@ static void _main(int argc, char** argv) {
                 "%7%",
             (Path)tmpDir, (pure ? "" : "p=$PATH; "),
             (pure ? "" : "PATH=$PATH:$p; unset p; "), dirOf(shell), shell,
-            (getenv("TZ") ? (string("export TZ='") + getenv("TZ") + "'; ")
-                          : ""),
+            (getenv("TZ") != nullptr
+                 ? (string("export TZ='") + getenv("TZ") + "'; ")
+                 : ""),
             envCommand));
 
     Strings envStrs;
@@ -510,61 +515,59 @@ static void _main(int argc, char** argv) {
     throw SysError("executing shell '%s'", shell);
   }
 
-  else {
-    PathSet pathsToBuild;
+  PathSet pathsToBuild;
 
-    std::map<Path, Path> drvPrefixes;
-    std::map<Path, Path> resultSymlinks;
-    std::vector<Path> outPaths;
+  std::map<Path, Path> drvPrefixes;
+  std::map<Path, Path> resultSymlinks;
+  std::vector<Path> outPaths;
 
-    for (auto& drvInfo : drvs) {
-      auto drvPath = drvInfo.queryDrvPath();
-      auto outPath = drvInfo.queryOutPath();
+  for (auto& drvInfo : drvs) {
+    auto drvPath = drvInfo.queryDrvPath();
+    auto outPath = drvInfo.queryOutPath();
 
-      auto outputName = drvInfo.queryOutputName();
-      if (outputName == "") {
-        throw Error("derivation '%s' lacks an 'outputName' attribute", drvPath);
-      }
+    auto outputName = drvInfo.queryOutputName();
+    if (outputName.empty()) {
+      throw Error("derivation '%s' lacks an 'outputName' attribute", drvPath);
+    }
 
-      pathsToBuild.insert(drvPath + "!" + outputName);
+    pathsToBuild.insert(drvPath + "!" + outputName);
 
-      std::string drvPrefix;
-      auto i = drvPrefixes.find(drvPath);
-      if (i != drvPrefixes.end()) {
-        drvPrefix = i->second;
-      } else {
-        drvPrefix = outLink;
-        if (drvPrefixes.size()) {
-          drvPrefix += fmt("-%d", drvPrefixes.size() + 1);
-        }
-        drvPrefixes[drvPath] = drvPrefix;
-      }
-
-      std::string symlink = drvPrefix;
-      if (outputName != "out") {
-        symlink += "-" + outputName;
+    std::string drvPrefix;
+    auto i = drvPrefixes.find(drvPath);
+    if (i != drvPrefixes.end()) {
+      drvPrefix = i->second;
+    } else {
+      drvPrefix = outLink;
+      if (!drvPrefixes.empty() != 0u) {
+        drvPrefix += fmt("-%d", drvPrefixes.size() + 1);
       }
+      drvPrefixes[drvPath] = drvPrefix;
+    }
 
-      resultSymlinks[symlink] = outPath;
-      outPaths.push_back(outPath);
+    std::string symlink = drvPrefix;
+    if (outputName != "out") {
+      symlink += "-" + outputName;
     }
 
-    buildPaths(pathsToBuild);
+    resultSymlinks[symlink] = outPath;
+    outPaths.push_back(outPath);
+  }
 
-    if (dryRun) {
-      return;
-    }
+  buildPaths(pathsToBuild);
 
-    for (auto& symlink : resultSymlinks) {
-      if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) {
-        store2->addPermRoot(symlink.second, absPath(symlink.first), true);
-      }
-    }
+  if (dryRun) {
+    return;
+  }
 
-    for (auto& path : outPaths) {
-      std::cout << path << '\n';
+  for (auto& symlink : resultSymlinks) {
+    if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) {
+      store2->addPermRoot(symlink.second, absPath(symlink.first), true);
     }
   }
+
+  for (auto& path : outPaths) {
+    std::cout << path << '\n';
+  }
 }
 
 static RegisterLegacyCommand s1("nix-build", _main);
diff --git a/third_party/nix/src/nix-channel/nix-channel.cc b/third_party/nix/src/nix-channel/nix-channel.cc
index ae5e77e86db5..00305151747a 100644
--- a/third_party/nix/src/nix-channel/nix-channel.cc
+++ b/third_party/nix/src/nix-channel/nix-channel.cc
@@ -86,7 +86,7 @@ static void update(const StringSet& channelNames) {
   for (const auto& channel : channels) {
     auto name = channel.first;
     auto url = channel.second;
-    if (!(channelNames.empty() || channelNames.count(name))) {
+    if (!(channelNames.empty() || (channelNames.count(name) != 0u))) {
       continue;
     }
 
@@ -216,7 +216,7 @@ static int _main(int argc, char** argv) {
       case cNone:
         throw UsageError("no command specified");
       case cAdd:
-        if (args.size() < 1 || args.size() > 2) {
+        if (args.empty() || args.size() > 2) {
           throw UsageError("'--add' requires one or two arguments");
         }
         {
diff --git a/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc b/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc
index dee803ada38f..c3ff068887b5 100644
--- a/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc
+++ b/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc
@@ -42,7 +42,7 @@ void removeOldGenerations(std::string dir) {
       }
       if (link.find("link") != string::npos) {
         LOG(INFO) << "removing old generations of profile " << path;
-        if (deleteOlderThan != "") {
+        if (!deleteOlderThan.empty()) {
           deleteGenerationsOlderThan(path, deleteOlderThan, dryRun);
         } else {
           deleteOldGenerations(path, dryRun);
diff --git a/third_party/nix/src/nix-daemon/nix-daemon.cc b/third_party/nix/src/nix-daemon/nix-daemon.cc
index 14c3eb7ed278..060cc10497b9 100644
--- a/third_party/nix/src/nix-daemon/nix-daemon.cc
+++ b/third_party/nix/src/nix-daemon/nix-daemon.cc
@@ -209,7 +209,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
       store->assertStorePath(path);
       bool result = store->isValidPath(path);
       logger->stopWork();
-      to << result;
+      to << static_cast<uint64_t>(result);
       break;
     }
 
@@ -227,7 +227,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
       logger->startWork();
       PathSet res = store->querySubstitutablePaths({path});
       logger->stopWork();
-      to << (res.find(path) != res.end());
+      to << static_cast<uint64_t>(res.find(path) != res.end());
       break;
     }
 
@@ -299,8 +299,10 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopAddToStore: {
-      bool fixed, recursive;
-      std::string s, baseName;
+      bool fixed;
+      bool recursive;
+      std::string s;
+      std::string baseName;
       from >> baseName >> fixed /* obsolete */ >> recursive >> s;
       /* Compatibility hack. */
       if (!fixed) {
@@ -490,9 +492,9 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopSetOptions: {
-      settings.keepFailed = readInt(from);
-      settings.keepGoing = readInt(from);
-      settings.tryFallback = readInt(from);
+      settings.keepFailed = readInt(from) != 0u;
+      settings.keepGoing = readInt(from) != 0u;
+      settings.tryFallback = readInt(from) != 0u;
       readInt(from);  // obsolete verbosity
       settings.maxBuildJobs.assign(readInt(from));
       settings.maxSilentTime = readInt(from);
@@ -501,7 +503,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
       readInt(from);  // obsolete logType
       readInt(from);  // obsolete printBuildTrace
       settings.buildCores = readInt(from);
-      settings.useSubstitutes = readInt(from);
+      settings.useSubstitutes = readInt(from) != 0u;
 
       StringMap overrides;
       if (GET_PROTOCOL_MINOR(clientVersion) >= 12) {
@@ -530,7 +532,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
           Strings subs;
           auto ss = tokenizeString<Strings>(value);
           for (auto& s : ss) {
-            if (trusted.count(s)) {
+            if (trusted.count(s) != 0u) {
               subs.push_back(s);
             } else {
               LOG(WARNING) << "ignoring untrusted substituter '" << s << "'";
@@ -545,7 +547,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
             ;
           } else if (trusted || name == settings.buildTimeout.name ||
                      name == "connect-timeout" ||
-                     (name == "builders" && value == "")) {
+                     (name == "builders" && value.empty())) {
             settings.set(name, value);
           } else if (setSubstituters(settings.substituters)) {
             ;
@@ -622,7 +624,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
         to << info->deriver << info->narHash.to_string(Base16, false)
            << info->references << info->registrationTime << info->narSize;
         if (GET_PROTOCOL_MINOR(clientVersion) >= 16) {
-          to << info->ultimate << info->sigs << info->ca;
+          to << static_cast<uint64_t>(info->ultimate) << info->sigs << info->ca;
         }
       } else {
         assert(GET_PROTOCOL_MINOR(clientVersion) >= 17);
@@ -639,7 +641,8 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
       break;
 
     case wopVerifyStore: {
-      bool checkContents, repair;
+      bool checkContents;
+      bool repair;
       from >> checkContents >> repair;
       logger->startWork();
       if (repair && !trusted) {
@@ -647,7 +650,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
       }
       bool errors = store->verifyStore(checkContents, (RepairFlag)repair);
       logger->stopWork();
-      to << errors;
+      to << static_cast<uint64_t>(errors);
       break;
     }
 
@@ -673,7 +676,8 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopAddToStoreNar: {
-      bool repair, dontCheckSigs;
+      bool repair;
+      bool dontCheckSigs;
       ValidPathInfo info;
       info.path = readStorePath(*store, from);
       from >> info.deriver;
@@ -716,8 +720,11 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     case wopQueryMissing: {
       auto targets = readStorePaths<PathSet>(*store, from);
       logger->startWork();
-      PathSet willBuild, willSubstitute, unknown;
-      unsigned long long downloadSize, narSize;
+      PathSet willBuild;
+      PathSet willSubstitute;
+      PathSet unknown;
+      unsigned long long downloadSize;
+      unsigned long long narSize;
       store->queryMissing(targets, willBuild, willSubstitute, unknown,
                           downloadSize, narSize);
       logger->stopWork();
@@ -757,7 +764,7 @@ static void processConnection(bool trusted, const std::string& userName,
     DLOG(INFO) << opCount << " operations";
   });
 
-  if (GET_PROTOCOL_MINOR(clientVersion) >= 14 && readInt(from)) {
+  if (GET_PROTOCOL_MINOR(clientVersion) >= 14 && (readInt(from) != 0u)) {
     setAffinityTo(readInt(from));
   }
 
@@ -842,11 +849,12 @@ static void sigChldHandler(int sigNo) {
 }
 
 static void setSigChldAction(bool autoReap) {
-  struct sigaction act, oact;
+  struct sigaction act;
+  struct sigaction oact;
   act.sa_handler = autoReap ? sigChldHandler : SIG_DFL;
   sigfillset(&act.sa_mask);
   act.sa_flags = 0;
-  if (sigaction(SIGCHLD, &act, &oact)) {
+  if (sigaction(SIGCHLD, &act, &oact) != 0) {
     throw SysError("setting SIGCHLD handler");
   }
 }
@@ -866,10 +874,10 @@ bool matchUser(const string& user, const string& group, const Strings& users) {
         return true;
       }
       struct group* gr = getgrnam(i.c_str() + 1);
-      if (!gr) {
+      if (gr == nullptr) {
         continue;
       }
-      for (char** mem = gr->gr_mem; *mem; mem++) {
+      for (char** mem = gr->gr_mem; *mem != nullptr; mem++) {
         if (user == string(*mem)) {
           return true;
         }
@@ -933,7 +941,7 @@ static void daemonLoop(char** argv) {
   AutoCloseFD fdSocket;
 
   /* Handle socket-based activation by systemd. */
-  if (getEnv("LISTEN_FDS") != "") {
+  if (!getEnv("LISTEN_FDS").empty()) {
     if (getEnv("LISTEN_PID") != std::to_string(getpid()) ||
         getEnv("LISTEN_FDS") != "1") {
       throw Error("unexpected systemd environment variables");
@@ -1014,10 +1022,10 @@ static void daemonLoop(char** argv) {
       PeerInfo peer = getPeerInfo(remote.get());
 
       struct passwd* pw = peer.uidKnown ? getpwuid(peer.uid) : nullptr;
-      string user = pw ? pw->pw_name : std::to_string(peer.uid);
+      string user = pw != nullptr ? pw->pw_name : std::to_string(peer.uid);
 
       struct group* gr = peer.gidKnown ? getgrgid(peer.gid) : nullptr;
-      string group = gr ? gr->gr_name : std::to_string(peer.gid);
+      string group = gr != nullptr ? gr->gr_name : std::to_string(peer.gid);
 
       Strings trustedUsers = settings.trustedUsers;
       Strings allowedUsers = settings.allowedUsers;
@@ -1057,7 +1065,7 @@ static void daemonLoop(char** argv) {
             setSigChldAction(false);
 
             /* For debugging, stuff the pid into argv[1]. */
-            if (peer.pidKnown && argv[1]) {
+            if (peer.pidKnown && (argv[1] != nullptr)) {
               string processName = std::to_string(peer.pid);
               strncpy(argv[1], processName.c_str(), strlen(argv[1]));
             }
@@ -1143,7 +1151,8 @@ static int _main(int argc, char** argv) {
                               SPLICE_F_MOVE);
             if (res == -1) {
               throw SysError("splicing data from daemon socket to stdout");
-            } else if (res == 0) {
+            }
+            if (res == 0) {
               throw EndOfFile("unexpected EOF from daemon socket");
             }
           }
@@ -1152,7 +1161,8 @@ static int _main(int argc, char** argv) {
                               SPLICE_F_MOVE);
             if (res == -1) {
               throw SysError("splicing data from stdin to daemon socket");
-            } else if (res == 0) {
+            }
+            if (res == 0) {
               return 0;
             }
           }
diff --git a/third_party/nix/src/nix-env/nix-env.cc b/third_party/nix/src/nix-env/nix-env.cc
index 86340d5c9138..ec2da8f83502 100644
--- a/third_party/nix/src/nix-env/nix-env.cc
+++ b/third_party/nix/src/nix-env/nix-env.cc
@@ -319,7 +319,7 @@ static void queryInstSources(EvalState& state, InstallSourceInfo& instSource,
                              const Strings& args, DrvInfos& elems,
                              bool newestOnly) {
   InstallSourceType type = instSource.type;
-  if (type == srcUnknown && args.size() > 0 && isPath(args.front())) {
+  if (type == srcUnknown && !args.empty() && isPath(args.front())) {
     type = srcStorePaths;
   }
 
@@ -352,7 +352,8 @@ static void queryInstSources(EvalState& state, InstallSourceInfo& instSource,
 
       for (auto& i : args) {
         Expr* eFun = state.parseExprFromString(i, absPath("."));
-        Value vFun, vTmp;
+        Value vFun;
+        Value vTmp;
         state.eval(eFun, vFun);
         mkApp(vTmp, vFun, vArg);
         getDerivations(state, vTmp, "", *instSource.autoArgs, elems, true);
@@ -420,7 +421,7 @@ static void printMissing(EvalState& state, DrvInfos& elems) {
   PathSet targets;
   for (auto& i : elems) {
     Path drvPath = i.queryDrvPath();
-    if (drvPath != "") {
+    if (!drvPath.empty()) {
       targets.insert(drvPath);
     } else {
       targets.insert(i.queryOutPath());
@@ -437,7 +438,8 @@ static void installDerivations(Globals& globals, const Strings& args,
   DLOG(INFO) << "installing derivations";
 
   /* Get the set of user environment elements to be installed. */
-  DrvInfos newElems, newElemsTmp;
+  DrvInfos newElems;
+  DrvInfos newElemsTmp;
   queryInstSources(*globals.state, globals.instSource, args, newElemsTmp, true);
 
   /* If --prebuilt-only is given, filter out source-only packages. */
@@ -453,7 +455,7 @@ static void installDerivations(Globals& globals, const Strings& args,
        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 != "") {
+    if (!globals.forceName.empty()) {
       i.setName(globals.forceName);
     }
     newNames.insert(DrvName(i.queryName()).name);
@@ -644,7 +646,7 @@ static void setMetaFlag(EvalState& state, DrvInfo& drv, const string& name,
 }
 
 static void opSetFlag(Globals& globals, Strings opFlags, Strings opArgs) {
-  if (opFlags.size() > 0) {
+  if (!opFlags.empty()) {
     throw UsageError(format("unknown flag '%1%'") % opFlags.front());
   }
   if (opArgs.size() < 2) {
@@ -708,18 +710,18 @@ static void opSet(Globals& globals, Strings opFlags, Strings opArgs) {
 
   DrvInfo& drv(elems.front());
 
-  if (globals.forceName != "") {
+  if (!globals.forceName.empty()) {
     drv.setName(globals.forceName);
   }
 
-  if (drv.queryDrvPath() != "") {
+  if (!drv.queryDrvPath().empty()) {
     PathSet paths = {drv.queryDrvPath()};
     printMissing(globals.state->store, paths);
     if (globals.dryRun) {
       return;
     }
     globals.state->store->buildPaths(
-        paths, globals.state->repair ? bmRepair : bmNormal);
+        paths, globals.state->repair != 0u ? bmRepair : bmNormal);
   } else {
     printMissing(globals.state->store, {drv.queryOutPath()});
     if (globals.dryRun) {
@@ -774,7 +776,7 @@ static void uninstallDerivations(Globals& globals, Strings& selectors,
 }
 
 static void opUninstall(Globals& globals, Strings opFlags, Strings opArgs) {
-  if (opFlags.size() > 0) {
+  if (!opFlags.empty()) {
     throw UsageError(format("unknown flag '%1%'") % opFlags.front());
   }
   uninstallDerivations(globals, opArgs, globals.profile);
@@ -792,7 +794,7 @@ static bool cmpElemByName(const DrvInfo& a, const DrvInfo& b) {
 using Table = list<Strings>;
 
 void printTable(Table& table) {
-  auto nrColumns = table.size() > 0 ? table.front().size() : 0;
+  auto nrColumns = !table.empty() ? table.front().size() : 0;
 
   vector<size_t> widths;
   widths.resize(nrColumns);
@@ -852,7 +854,7 @@ static VersionDiff compareVersionAgainstSet(const DrvInfo& elem,
         version = name2.version;
       } else if (diff != cvGreater && diff != cvEqual && d > 0) {
         diff = cvLess;
-        if (version == "" || compareVersions(version, name2.version) < 0) {
+        if (version.empty() || compareVersions(version, name2.version) < 0) {
           version = name2.version;
         }
       }
@@ -878,7 +880,7 @@ static void queryJSON(Globals& globals, vector<DrvInfo>& elems) {
     for (auto& j : metaNames) {
       auto placeholder = metaObj.placeholder(j);
       Value* v = i.queryMeta(j);
-      if (!v) {
+      if (v == nullptr) {
         LOG(ERROR) << "derivation '" << i.queryName()
                    << "' has invalid meta attribute '" << j << "'";
         placeholder.write(nullptr);
@@ -946,7 +948,8 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
   }
 
   /* Obtain derivation information from the specified source. */
-  DrvInfos availElems, installedElems;
+  DrvInfos availElems;
+  DrvInfos installedElems;
 
   if (source == sInstalled || compareVersions || printStatus) {
     installedElems = queryInstalled(*globals.state, globals.profile);
@@ -983,7 +986,8 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
   }
 
   /* Query which paths have substitutes. */
-  PathSet validPaths, substitutablePaths;
+  PathSet validPaths;
+  PathSet substitutablePaths;
   if (printStatus || globals.prebuiltOnly) {
     PathSet paths;
     for (auto& i : elems) {
@@ -1005,7 +1009,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
     return;
   }
 
-  bool tty = isatty(STDOUT_FILENO);
+  bool tty = isatty(STDOUT_FILENO) != 0;
   RunPager pager;
 
   Table table;
@@ -1107,7 +1111,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
       }
 
       if (xmlOutput) {
-        if (i.querySystem() != "") {
+        if (!i.querySystem().empty()) {
           attrs["system"] = i.querySystem();
         }
       } else if (printSystem) {
@@ -1117,11 +1121,11 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
       if (printDrvPath) {
         string drvPath = i.queryDrvPath();
         if (xmlOutput) {
-          if (drvPath != "") {
+          if (!drvPath.empty()) {
             attrs["drvPath"] = drvPath;
           }
         } else {
-          columns.push_back(drvPath == "" ? "-" : drvPath);
+          columns.push_back(drvPath.empty() ? "-" : drvPath);
         }
       }
 
@@ -1144,7 +1148,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
       if (printDescription) {
         string descr = i.queryMetaString("description");
         if (xmlOutput) {
-          if (descr != "") {
+          if (!descr.empty()) {
             attrs["description"] = descr;
           }
         } else {
@@ -1170,7 +1174,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
               XMLAttrs attrs2;
               attrs2["name"] = j;
               Value* v = i.queryMeta(j);
-              if (!v) {
+              if (v == nullptr) {
                 LOG(ERROR) << "derivation '" << i.queryName()
                            << "' has invalid meta attribute '" << j << "'";
               } else {
@@ -1244,7 +1248,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
 }
 
 static void opSwitchProfile(Globals& globals, Strings opFlags, Strings opArgs) {
-  if (opFlags.size() > 0) {
+  if (!opFlags.empty()) {
     throw UsageError(format("unknown flag '%1%'") % opFlags.front());
   }
   if (opArgs.size() != 1) {
@@ -1278,9 +1282,8 @@ static void switchGeneration(Globals& globals, int dstGen) {
     if (dstGen == prevGen) {
       throw Error(format("no generation older than the current (%1%) exists") %
                   curGen);
-    } else {
-      throw Error(format("generation %1% does not exist") % dstGen);
     }
+    throw Error(format("generation %1% does not exist") % dstGen);
   }
 
   LOG(INFO) << "switching from generation " << curGen << " to " << dst.number;
@@ -1294,7 +1297,7 @@ static void switchGeneration(Globals& globals, int dstGen) {
 
 static void opSwitchGeneration(Globals& globals, Strings opFlags,
                                Strings opArgs) {
-  if (opFlags.size() > 0) {
+  if (!opFlags.empty()) {
     throw UsageError(format("unknown flag '%1%'") % opFlags.front());
   }
   if (opArgs.size() != 1) {
@@ -1310,10 +1313,10 @@ static void opSwitchGeneration(Globals& globals, Strings opFlags,
 }
 
 static void opRollback(Globals& globals, Strings opFlags, Strings opArgs) {
-  if (opFlags.size() > 0) {
+  if (!opFlags.empty()) {
     throw UsageError(format("unknown flag '%1%'") % opFlags.front());
   }
-  if (opArgs.size() != 0) {
+  if (!opArgs.empty()) {
     throw UsageError(format("no arguments expected"));
   }
 
@@ -1322,10 +1325,10 @@ static void opRollback(Globals& globals, Strings opFlags, Strings opArgs) {
 
 static void opListGenerations(Globals& globals, Strings opFlags,
                               Strings opArgs) {
-  if (opFlags.size() > 0) {
+  if (!opFlags.empty()) {
     throw UsageError(format("unknown flag '%1%'") % opFlags.front());
   }
-  if (opArgs.size() != 0) {
+  if (!opArgs.empty()) {
     throw UsageError(format("no arguments expected"));
   }
 
@@ -1339,7 +1342,7 @@ static void opListGenerations(Globals& globals, Strings opFlags,
 
   for (auto& i : gens) {
     tm t;
-    if (!localtime_r(&i.creationTime, &t)) {
+    if (localtime_r(&i.creationTime, &t) == nullptr) {
       throw Error("cannot convert time");
     }
     cout << format("%|4|   %|4|-%|02|-%|02| %|02|:%|02|:%|02|   %||\n") %
@@ -1351,7 +1354,7 @@ static void opListGenerations(Globals& globals, Strings opFlags,
 
 static void opDeleteGenerations(Globals& globals, Strings opFlags,
                                 Strings opArgs) {
-  if (opFlags.size() > 0) {
+  if (!opFlags.empty()) {
     throw UsageError(format("unknown flag '%1%'") % opFlags.front());
   }
 
@@ -1390,7 +1393,8 @@ static void opVersion(Globals& globals, Strings opFlags, Strings opArgs) {
 
 static int _main(int argc, char** argv) {
   {
-    Strings opFlags, opArgs;
+    Strings opFlags;
+    Strings opArgs;
     Operation op = nullptr;
     RepairFlag repair = NoRepair;
     string file;
@@ -1482,7 +1486,7 @@ static int _main(int argc, char** argv) {
         opArgs.push_back(*arg);
       }
 
-      if (oldOp && oldOp != op) {
+      if ((oldOp != nullptr) && oldOp != op) {
         throw UsageError("only one operation may be specified");
       }
 
@@ -1493,7 +1497,7 @@ static int _main(int argc, char** argv) {
 
     initPlugins();
 
-    if (!op) {
+    if (op == nullptr) {
       throw UsageError("no operation specified");
     }
 
@@ -1503,17 +1507,17 @@ static int _main(int argc, char** argv) {
         std::shared_ptr<EvalState>(new EvalState(myArgs.searchPath, store));
     globals.state->repair = repair;
 
-    if (file != "") {
+    if (!file.empty()) {
       globals.instSource.nixExprPath = lookupFileArg(*globals.state, file);
     }
 
     globals.instSource.autoArgs = myArgs.getAutoArgs(*globals.state);
 
-    if (globals.profile == "") {
+    if (globals.profile.empty()) {
       globals.profile = getEnv("NIX_PROFILE", "");
     }
 
-    if (globals.profile == "") {
+    if (globals.profile.empty()) {
       Path profileLink = getHome() + "/.nix-profile";
       try {
         if (!pathExists(profileLink)) {
diff --git a/third_party/nix/src/nix-env/user-env.cc b/third_party/nix/src/nix-env/user-env.cc
index d013f34b08fa..bf15543c3f95 100644
--- a/third_party/nix/src/nix-env/user-env.cc
+++ b/third_party/nix/src/nix-env/user-env.cc
@@ -31,13 +31,14 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
      exist already. */
   PathSet drvsToBuild;
   for (auto& i : elems) {
-    if (i.queryDrvPath() != "") {
+    if (!i.queryDrvPath().empty()) {
       drvsToBuild.insert(i.queryDrvPath());
     }
   }
 
   DLOG(INFO) << "building user environment dependencies";
-  state.store->buildPaths(drvsToBuild, state.repair ? bmRepair : bmNormal);
+  state.store->buildPaths(drvsToBuild,
+                          state.repair != 0u ? bmRepair : bmNormal);
 
   /* Construct the whole top level derivation. */
   PathSet references;
@@ -61,7 +62,7 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
       mkString(*state.allocAttr(v, state.sSystem), system);
     }
     mkString(*state.allocAttr(v, state.sOutPath), i.queryOutPath());
-    if (drvPath != "") {
+    if (!drvPath.empty()) {
       mkString(*state.allocAttr(v, state.sDrvPath), i.queryDrvPath());
     }
 
@@ -90,7 +91,7 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
     StringSet metaNames = i.queryMetaNames();
     for (auto& j : metaNames) {
       Value* v = i.queryMeta(j);
-      if (!v) {
+      if (v == nullptr) {
         continue;
       }
       vMeta.attrs->push_back(Attr(state.symbols.create(j), v));
@@ -98,7 +99,7 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
     vMeta.attrs->sort();
     v.attrs->sort();
 
-    if (drvPath != "") {
+    if (!drvPath.empty()) {
       references.insert(drvPath);
     }
   }
@@ -115,7 +116,8 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
 
   /* Construct a Nix expression that calls the user environment
      builder with the manifest as argument. */
-  Value args, topLevel;
+  Value args;
+  Value topLevel;
   state.mkAttrs(args, 3);
   mkString(*state.allocAttr(args, state.symbols.create("manifest")),
            manifestFile, {manifestFile});
@@ -128,15 +130,18 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
   state.forceValue(topLevel);
   PathSet context;
   Attr& aDrvPath(*topLevel.attrs->find(state.sDrvPath));
-  Path topLevelDrv = state.coerceToPath(aDrvPath.pos ? *(aDrvPath.pos) : noPos,
-                                        *(aDrvPath.value), context);
+  Path topLevelDrv =
+      state.coerceToPath(aDrvPath.pos != nullptr ? *(aDrvPath.pos) : noPos,
+                         *(aDrvPath.value), context);
   Attr& aOutPath(*topLevel.attrs->find(state.sOutPath));
-  Path topLevelOut = state.coerceToPath(aOutPath.pos ? *(aOutPath.pos) : noPos,
-                                        *(aOutPath.value), context);
+  Path topLevelOut =
+      state.coerceToPath(aOutPath.pos != nullptr ? *(aOutPath.pos) : noPos,
+                         *(aOutPath.value), context);
 
   /* Realise the resulting store expression. */
   DLOG(INFO) << "building user environment";
-  state.store->buildPaths({topLevelDrv}, state.repair ? bmRepair : bmNormal);
+  state.store->buildPaths({topLevelDrv},
+                          state.repair != 0u ? bmRepair : bmNormal);
 
   /* Switch the current user environment to the output path. */
   auto store2 = state.store.dynamic_pointer_cast<LocalFSStore>();
diff --git a/third_party/nix/src/nix-instantiate/nix-instantiate.cc b/third_party/nix/src/nix-instantiate/nix-instantiate.cc
index 05f481906b28..95e5341ade4a 100644
--- a/third_party/nix/src/nix-instantiate/nix-instantiate.cc
+++ b/third_party/nix/src/nix-instantiate/nix-instantiate.cc
@@ -63,13 +63,13 @@ void processExpr(EvalState& state, const Strings& attrPaths, bool parseOnly,
 
         /* What output do we want? */
         string outputName = i.queryOutputName();
-        if (outputName == "") {
+        if (outputName.empty()) {
           throw Error(
               format("derivation '%1%' lacks an 'outputName' attribute ") %
               drvPath);
         }
 
-        if (gcRoot == "") {
+        if (gcRoot.empty()) {
           printGCWarning();
         } else {
           Path rootName = indirectRoot ? absPath(gcRoot) : gcRoot;
@@ -173,7 +173,7 @@ static int _main(int argc, char** argv) {
     if (findFile) {
       for (auto& i : files) {
         Path p = state->findFile(i);
-        if (p == "") {
+        if (p.empty()) {
           throw Error(format("unable to find '%1%'") % i);
         }
         std::cout << p << std::endl;
diff --git a/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc b/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc
index 8c92af19d5f3..5a9b81103d79 100644
--- a/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc
+++ b/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc
@@ -57,7 +57,7 @@ static int _main(int argc, char** argv) {
   {
     HashType ht = htSHA256;
     std::vector<string> args;
-    bool printPath = getEnv("PRINT_PATH") != "";
+    bool printPath = !getEnv("PRINT_PATH").empty();
     bool fromExpr = false;
     string attrPath;
     bool unpack = false;
@@ -163,7 +163,8 @@ static int _main(int argc, char** argv) {
 
     /* If an expected hash is given, the file may already exist in
        the store. */
-    Hash hash, expectedHash(ht);
+    Hash hash;
+    Hash expectedHash(ht);
     Path storePath;
     if (args.size() == 2) {
       expectedHash = Hash(args[1], ht);
diff --git a/third_party/nix/src/nix-store/graphml.cc b/third_party/nix/src/nix-store/graphml.cc
index 07116cda930a..6510b328810d 100644
--- a/third_party/nix/src/nix-store/graphml.cc
+++ b/third_party/nix/src/nix-store/graphml.cc
@@ -58,7 +58,7 @@ void printGraphML(ref<Store> store, const PathSet& roots) {
     workList.erase(path);
 
     ret = doneSet.insert(path);
-    if (ret.second == false) {
+    if (!ret.second) {
       continue;
     }
 
diff --git a/third_party/nix/src/nix-store/nix-store.cc b/third_party/nix/src/nix-store/nix-store.cc
index c6028ea3e7bc..802ebd420792 100644
--- a/third_party/nix/src/nix-store/nix-store.cc
+++ b/third_party/nix/src/nix-store/nix-store.cc
@@ -49,7 +49,7 @@ static Path useDeriver(Path path) {
     return path;
   }
   Path drvPath = store->queryPathInfo(path)->deriver;
-  if (drvPath == "") {
+  if (drvPath.empty()) {
     throw Error(format("deriver of path '%1%' is not known") % path);
   }
   return drvPath;
@@ -85,7 +85,7 @@ static PathSet realisePath(Path path, bool build = true) {
       }
       Path outPath = i->second.path;
       if (store2) {
-        if (gcRoot == "") {
+        if (gcRoot.empty()) {
           printGCWarning();
         } else {
           Path rootName = gcRoot;
@@ -103,27 +103,25 @@ static PathSet realisePath(Path path, bool build = true) {
     return outputs;
   }
 
-  else {
-    if (build) {
-      store->ensurePath(path);
-    } else if (!store->isValidPath(path)) {
-      throw Error(format("path '%1%' does not exist and cannot be created") %
-                  path);
-    }
-    if (store2) {
-      if (gcRoot == "") {
-        printGCWarning();
-      } else {
-        Path rootName = gcRoot;
-        rootNr++;
-        if (rootNr > 1) {
-          rootName += "-" + std::to_string(rootNr);
-        }
-        path = store2->addPermRoot(path, rootName, indirectRoot);
+  if (build) {
+    store->ensurePath(path);
+  } else if (!store->isValidPath(path)) {
+    throw Error(format("path '%1%' does not exist and cannot be created") %
+                path);
+  }
+  if (store2) {
+    if (gcRoot.empty()) {
+      printGCWarning();
+    } else {
+      Path rootName = gcRoot;
+      rootNr++;
+      if (rootNr > 1) {
+        rootName += "-" + std::to_string(rootNr);
       }
+      path = store2->addPermRoot(path, rootName, indirectRoot);
     }
-    return {path};
   }
+  return {path};
 }
 
 /* Realise the given paths. */
@@ -153,8 +151,11 @@ static void opRealise(Strings opFlags, Strings opArgs) {
         store->followLinksToStorePath(p.first), p.second));
   }
 
-  unsigned long long downloadSize, narSize;
-  PathSet willBuild, willSubstitute, unknown;
+  unsigned long long downloadSize;
+  unsigned long long narSize;
+  PathSet willBuild;
+  PathSet willSubstitute;
+  PathSet unknown;
   store->queryMissing(PathSet(paths.begin(), paths.end()), willBuild,
                       willSubstitute, unknown, downloadSize, narSize);
 
@@ -267,9 +268,8 @@ static PathSet maybeUseOutputs(const Path& storePath, bool useOutput,
       outputs.insert(i.second.path);
     }
     return outputs;
-  } else {
-    return {storePath};
   }
+  return {storePath};
 }
 
 /* Some code to print a tree representation of a derivation dependency
@@ -348,7 +348,7 @@ static void opQuery(Strings opFlags, Strings opArgs) {
     } else if (i == "--deriver" || i == "-d") {
       query = qDeriver;
     } else if (i == "--binding" || i == "-b") {
-      if (opArgs.size() == 0) {
+      if (opArgs.empty()) {
         throw UsageError("expected binding name");
       }
       bindingName = opArgs.front();
@@ -437,7 +437,8 @@ static void opQuery(Strings opFlags, Strings opArgs) {
       for (auto& i : opArgs) {
         Path deriver =
             store->queryPathInfo(store->followLinksToStorePath(i))->deriver;
-        cout << format("%1%\n") % (deriver == "" ? "unknown-deriver" : deriver);
+        cout << format("%1%\n") %
+                    (deriver.empty() ? "unknown-deriver" : deriver);
       }
       break;
 
@@ -608,7 +609,7 @@ static void registerValidity(bool reregister, bool hashGiven,
 
   while (true) {
     ValidPathInfo info = decodeValidPathInfo(cin, hashGiven);
-    if (info.path == "") {
+    if (info.path.empty()) {
       break;
     }
     if (!store->isValidPath(info.path) || reregister) {
@@ -947,7 +948,7 @@ static void opServe(Strings opFlags, Strings opArgs) {
     }
     if (GET_PROTOCOL_MINOR(clientVersion) >= 3) {
       settings.buildRepeat = readInt(in);
-      settings.enforceDeterminism = readInt(in);
+      settings.enforceDeterminism = readInt(in) != 0u;
       settings.runDiffHook = true;
     }
     settings.printRepeatedBuilds = false;
@@ -963,8 +964,8 @@ static void opServe(Strings opFlags, Strings opArgs) {
 
     switch (cmd) {
       case cmdQueryValidPaths: {
-        bool lock = readInt(in);
-        bool substitute = readInt(in);
+        bool lock = readInt(in) != 0u;
+        bool substitute = readInt(in) != 0u;
         auto paths = readStorePaths<PathSet>(*store, in);
         if (lock && writeAllowed) {
           for (auto& path : paths) {
@@ -983,8 +984,11 @@ static void opServe(Strings opFlags, Strings opArgs) {
               paths2.insert(path);
             }
           }
-          unsigned long long downloadSize, narSize;
-          PathSet willBuild, willSubstitute, unknown;
+          unsigned long long downloadSize;
+          unsigned long long narSize;
+          PathSet willBuild;
+          PathSet willSubstitute;
+          PathSet unknown;
           store->queryMissing(PathSet(paths2.begin(), paths2.end()), willBuild,
                               willSubstitute, unknown, downloadSize, narSize);
           /* FIXME: should use ensurePath(), but it only
@@ -1080,7 +1084,8 @@ static void opServe(Strings opFlags, Strings opArgs) {
         out << status.status << status.errorMsg;
 
         if (GET_PROTOCOL_MINOR(clientVersion) >= 3) {
-          out << status.timesBuilt << status.isNonDeterministic
+          out << status.timesBuilt
+              << static_cast<uint64_t>(status.isNonDeterministic)
               << status.startTime << status.stopTime;
         }
 
@@ -1088,7 +1093,7 @@ static void opServe(Strings opFlags, Strings opArgs) {
       }
 
       case cmdQueryClosure: {
-        bool includeOutputs = readInt(in);
+        bool includeOutputs = readInt(in) != 0u;
         PathSet closure;
         store->computeFSClosure(readStorePaths<PathSet>(*store, in), closure,
                                 false, includeOutputs);
@@ -1184,7 +1189,8 @@ static void opVersion(Strings opFlags, Strings opArgs) {
    list. */
 static int _main(int argc, char** argv) {
   {
-    Strings opFlags, opArgs;
+    Strings opFlags;
+    Strings opArgs;
     Operation op = nullptr;
 
     parseCmdLine(argc, argv,
@@ -1260,7 +1266,7 @@ static int _main(int argc, char** argv) {
                      opArgs.push_back(*arg);
                    }
 
-                   if (oldOp && oldOp != op) {
+                   if ((oldOp != nullptr) && oldOp != op) {
                      throw UsageError("only one operation may be specified");
                    }
 
@@ -1269,7 +1275,7 @@ static int _main(int argc, char** argv) {
 
     initPlugins();
 
-    if (!op) {
+    if (op == nullptr) {
       throw UsageError("no operation specified");
     }
 
diff --git a/third_party/nix/src/nix/build.cc b/third_party/nix/src/nix/build.cc
index 0738821a8938..9ab2d27e0fc9 100644
--- a/third_party/nix/src/nix/build.cc
+++ b/third_party/nix/src/nix/build.cc
@@ -47,11 +47,11 @@ struct CmdBuild : MixDryRun, InstallablesCommand {
     for (size_t i = 0; i < buildables.size(); ++i) {
       auto& b(buildables[i]);
 
-      if (outLink != "") {
+      if (!outLink.empty()) {
         for (auto& output : b.outputs) {
           if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) {
             std::string symlink = outLink;
-            if (i) {
+            if (i != 0u) {
               symlink += fmt("-%d", i);
             }
             if (output.first != "out") {
diff --git a/third_party/nix/src/nix/command.cc b/third_party/nix/src/nix/command.cc
index b0efcb823dd6..439f22dc3b67 100644
--- a/third_party/nix/src/nix/command.cc
+++ b/third_party/nix/src/nix/command.cc
@@ -80,9 +80,8 @@ bool MultiCommand::processFlag(Strings::iterator& pos, Strings::iterator end) {
 bool MultiCommand::processArgs(const Strings& args, bool finish) {
   if (command) {
     return command->processArgs(args, finish);
-  } else {
-    return Args::processArgs(args, finish);
   }
+  return Args::processArgs(args, finish);
 }
 
 StoreCommand::StoreCommand() = default;
@@ -119,7 +118,7 @@ void StorePathsCommand::run(ref<Store> store) {
   Paths storePaths;
 
   if (all) {
-    if (installables.size()) {
+    if (!installables.empty() != 0u) {
       throw UsageError("'--all' does not expect arguments");
     }
     for (auto& p : store->queryAllValidPaths()) {
diff --git a/third_party/nix/src/nix/doctor.cc b/third_party/nix/src/nix/doctor.cc
index 44ce2d92921d..95bf8a922e26 100644
--- a/third_party/nix/src/nix/doctor.cc
+++ b/third_party/nix/src/nix/doctor.cc
@@ -7,7 +7,7 @@
 using namespace nix;
 
 std::string formatProtocol(unsigned int proto) {
-  if (proto) {
+  if (proto != 0u) {
     auto major = GET_PROTOCOL_MAJOR(proto) >> 8;
     auto minor = GET_PROTOCOL_MINOR(proto);
     return (format("%1%.%2%") % major % minor).str();
@@ -41,7 +41,7 @@ struct CmdDoctor : StoreCommand {
     }
   }
 
-  bool checkNixInPath() {
+  static bool checkNixInPath() {
     PathSet dirs;
 
     for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@@ -64,7 +64,7 @@ struct CmdDoctor : StoreCommand {
     return true;
   }
 
-  bool checkProfileRoots(ref<Store> store) {
+  static bool checkProfileRoots(ref<Store> store) {
     PathSet dirs;
 
     for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@@ -106,7 +106,7 @@ struct CmdDoctor : StoreCommand {
     return true;
   }
 
-  bool checkStoreProtocol(unsigned int storeProto) {
+  static bool checkStoreProtocol(unsigned int storeProto) {
     unsigned int clientProto = GET_PROTOCOL_MAJOR(SERVE_PROTOCOL_VERSION) ==
                                        GET_PROTOCOL_MAJOR(storeProto)
                                    ? SERVE_PROTOCOL_VERSION
diff --git a/third_party/nix/src/nix/installables.cc b/third_party/nix/src/nix/installables.cc
index 06419f1f122d..f6cba6d3b636 100644
--- a/third_party/nix/src/nix/installables.cc
+++ b/third_party/nix/src/nix/installables.cc
@@ -23,7 +23,7 @@ SourceExprCommand::SourceExprCommand() {
 }
 
 Value* SourceExprCommand::getSourceExpr(EvalState& state) {
-  if (vSourceExpr) {
+  if (vSourceExpr != nullptr) {
     return vSourceExpr;
   }
 
@@ -31,7 +31,7 @@ Value* SourceExprCommand::getSourceExpr(EvalState& state) {
 
   vSourceExpr = state.allocValue();
 
-  if (file != "") {
+  if (!file.empty()) {
     state.evalFile(lookupFileArg(state, file), *vSourceExpr);
 
   } else {
@@ -46,7 +46,7 @@ Value* SourceExprCommand::getSourceExpr(EvalState& state) {
     std::unordered_set<std::string> seen;
 
     auto addEntry = [&](const std::string& name) {
-      if (name == "") {
+      if (name.empty()) {
         return;
       }
       if (!seen.insert(name).second) {
@@ -135,7 +135,7 @@ struct InstallableValue : Installable {
       drvPaths.insert(b.drvPath);
 
       auto outputName = drv.queryOutputName();
-      if (outputName == "") {
+      if (outputName.empty()) {
         throw Error("derivation '%s' lacks an 'outputName' attribute",
                     b.drvPath);
       }
@@ -153,9 +153,8 @@ struct InstallableValue : Installable {
         b.outputs.insert(b2.outputs.begin(), b2.outputs.end());
       }
       return {b};
-    } else {
-      return res;
     }
+    return res;
   }
 };
 
@@ -204,7 +203,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
   std::vector<std::shared_ptr<Installable>> result;
 
   if (ss.empty() && useDefaultInstallables) {
-    if (cmd.file == "") {
+    if (cmd.file.empty()) {
       cmd.file = ".";
     }
     ss = {""};
@@ -222,7 +221,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
       }
     }
 
-    else if (s == "" || std::regex_match(s, attrPathRegex)) {
+    else if (s.empty() || std::regex_match(s, attrPathRegex)) {
       result.push_back(std::make_shared<InstallableAttrPath>(cmd, s));
 
     } else {
@@ -254,7 +253,7 @@ Buildables build(ref<Store> store, RealiseMode mode,
 
   for (auto& i : installables) {
     for (auto& b : i->toBuildables()) {
-      if (b.drvPath != "") {
+      if (!b.drvPath.empty()) {
         StringSet outputNames;
         for (auto& output : b.outputs) {
           outputNames.insert(output.first);
diff --git a/third_party/nix/src/nix/log.cc b/third_party/nix/src/nix/log.cc
index 86f133e94a7a..63d3554cc2fb 100644
--- a/third_party/nix/src/nix/log.cc
+++ b/third_party/nix/src/nix/log.cc
@@ -40,7 +40,7 @@ struct CmdLog : InstallableCommand {
 
     RunPager pager;
     for (auto& sub : subs) {
-      auto log = b.drvPath != "" ? sub->getBuildLog(b.drvPath) : nullptr;
+      auto log = !b.drvPath.empty() ? sub->getBuildLog(b.drvPath) : nullptr;
       for (auto& output : b.outputs) {
         if (log) {
           break;
diff --git a/third_party/nix/src/nix/main.cc b/third_party/nix/src/nix/main.cc
index 54285bfa9313..11ba3f8410c4 100644
--- a/third_party/nix/src/nix/main.cc
+++ b/third_party/nix/src/nix/main.cc
@@ -27,14 +27,14 @@ namespace nix {
 static bool haveInternet() {
   struct ifaddrs* addrs;
 
-  if (getifaddrs(&addrs)) {
+  if (getifaddrs(&addrs) != 0) {
     return true;
   }
 
   Finally free([&]() { freeifaddrs(addrs); });
 
-  for (auto i = addrs; i; i = i->ifa_next) {
-    if (!i->ifa_addr) {
+  for (auto i = addrs; i != nullptr; i = i->ifa_next) {
+    if (i->ifa_addr == nullptr) {
       continue;
     }
     if (i->ifa_addr->sa_family == AF_INET) {
diff --git a/third_party/nix/src/nix/path-info.cc b/third_party/nix/src/nix/path-info.cc
index b871c45f1c16..e94dcc962831 100644
--- a/third_party/nix/src/nix/path-info.cc
+++ b/third_party/nix/src/nix/path-info.cc
@@ -113,7 +113,7 @@ struct CmdPathInfo : StorePathsCommand, MixJSON {
           if (info->ultimate) {
             ss.push_back("ultimate");
           }
-          if (info->ca != "") {
+          if (!info->ca.empty()) {
             ss.push_back("ca:" + info->ca);
           }
           for (auto& sig : info->sigs) {
diff --git a/third_party/nix/src/nix/repl.cc b/third_party/nix/src/nix/repl.cc
index 9567ad4315db..81e940dd3aaf 100644
--- a/third_party/nix/src/nix/repl.cc
+++ b/third_party/nix/src/nix/repl.cc
@@ -62,7 +62,7 @@ struct NixRepl {
   ~NixRepl();
   void mainLoop(const std::vector<std::string>& files);
   StringSet completePrefix(string prefix);
-  bool getLine(string& input, const std::string& prompt);
+  static bool getLine(string& input, const std::string& prompt);
   Path getDerivationPath(Value& v);
   bool processLine(string line);
   void loadFile(const Path& path);
@@ -145,11 +145,12 @@ static char* completionCallback(char* s, int* match) {
   if (possible.size() == 1) {
     *match = 1;
     auto* res = strdup(possible.begin()->c_str() + strlen(s));
-    if (!res) {
+    if (res == nullptr) {
       throw Error("allocation failure");
     }
     return res;
-  } else if (possible.size() > 1) {
+  }
+  if (possible.size() > 1) {
     auto checkAllHaveSameAt = [&](size_t pos) {
       auto& first = *possible.begin();
       for (auto& p : possible) {
@@ -167,7 +168,7 @@ static char* completionCallback(char* s, int* match) {
     if (len > 0) {
       *match = 1;
       auto* res = strdup(std::string(*possible.begin(), start, len).c_str());
-      if (!res) {
+      if (res == nullptr) {
         throw Error("allocation failure");
       }
       return res;
@@ -266,10 +267,9 @@ void NixRepl::mainLoop(const std::vector<std::string>& files) {
         // For parse errors on incomplete input, we continue waiting for the
         // next line of input without clearing the input so far.
         continue;
-      } else {
-        LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "")
-                   << e.msg();
       }
+      LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg();
+
     } catch (Error& e) {
       LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg();
     } catch (Interrupted& e) {
@@ -284,29 +284,31 @@ void NixRepl::mainLoop(const std::vector<std::string>& files) {
 }
 
 bool NixRepl::getLine(string& input, const std::string& prompt) {
-  struct sigaction act, old;
-  sigset_t savedSignalMask, set;
+  struct sigaction act;
+  struct sigaction old;
+  sigset_t savedSignalMask;
+  sigset_t set;
 
   auto setupSignals = [&]() {
     act.sa_handler = sigintHandler;
     sigfillset(&act.sa_mask);
     act.sa_flags = 0;
-    if (sigaction(SIGINT, &act, &old)) {
+    if (sigaction(SIGINT, &act, &old) != 0) {
       throw SysError("installing handler for SIGINT");
     }
 
     sigemptyset(&set);
     sigaddset(&set, SIGINT);
-    if (sigprocmask(SIG_UNBLOCK, &set, &savedSignalMask)) {
+    if (sigprocmask(SIG_UNBLOCK, &set, &savedSignalMask) != 0) {
       throw SysError("unblocking SIGINT");
     }
   };
   auto restoreSignals = [&]() {
-    if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr)) {
+    if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr) != 0) {
       throw SysError("restoring signals");
     }
 
-    if (sigaction(SIGINT, &old, nullptr)) {
+    if (sigaction(SIGINT, &old, nullptr) != 0) {
       throw SysError("restoring handler for SIGINT");
     }
   };
@@ -316,13 +318,13 @@ bool NixRepl::getLine(string& input, const std::string& prompt) {
   Finally doFree([&]() { free(s); });
   restoreSignals();
 
-  if (g_signal_received) {
+  if (g_signal_received != 0) {
     g_signal_received = 0;
     input.clear();
     return true;
   }
 
-  if (!s) {
+  if (s == nullptr) {
     return false;
   }
   input += s;
@@ -334,7 +336,8 @@ StringSet NixRepl::completePrefix(string prefix) {
   StringSet completions;
 
   size_t start = prefix.find_last_of(" \n\r\t(){}[]");
-  std::string prev, cur;
+  std::string prev;
+  std::string cur;
   if (start == std::string::npos) {
     prev = "";
     cur = prefix;
@@ -343,13 +346,14 @@ StringSet NixRepl::completePrefix(string prefix) {
     cur = std::string(prefix, start + 1);
   }
 
-  size_t slash, dot;
+  size_t slash;
+  size_t dot;
 
   if ((slash = cur.rfind('/')) != string::npos) {
     try {
       auto dir = std::string(cur, 0, slash);
       auto prefix2 = std::string(cur, slash + 1);
-      for (auto& entry : readDirectory(dir == "" ? "/" : dir)) {
+      for (auto& entry : readDirectory(dir.empty() ? "/" : dir)) {
         if (entry.name[0] != '.' && hasPrefix(entry.name, prefix2)) {
           completions.insert(prev + dir + "/" + entry.name);
         }
@@ -418,7 +422,7 @@ static int runProgram(const string& program, const Strings& args) {
 }
 
 bool isVarName(const string& s) {
-  if (s.size() == 0) {
+  if (s.empty()) {
     return false;
   }
   char c = s[0];
@@ -441,18 +445,19 @@ Path NixRepl::getDerivationPath(Value& v) {
         "expression does not evaluate to a derivation, so I can't build it");
   }
   Path drvPath = drvInfo->queryDrvPath();
-  if (drvPath == "" || !state.store->isValidPath(drvPath)) {
+  if (drvPath.empty() || !state.store->isValidPath(drvPath)) {
     throw Error("expression did not evaluate to a valid derivation");
   }
   return drvPath;
 }
 
 bool NixRepl::processLine(string line) {
-  if (line == "") {
+  if (line.empty()) {
     return true;
   }
 
-  string command, arg;
+  string command;
+  string arg;
 
   if (line[0] == ':') {
     size_t p = line.find_first_of(" \n\r\t");
@@ -505,7 +510,9 @@ bool NixRepl::processLine(string line) {
     std::cout << showType(v) << std::endl;
 
   } else if (command == ":u") {
-    Value v, f, result;
+    Value v;
+    Value f;
+    Value result;
     evalString(arg, v);
     evalString(
         "drv: (import <nixpkgs> {}).runCommand \"shell\" { buildInputs = [ drv "
@@ -553,7 +560,7 @@ bool NixRepl::processLine(string line) {
   else if (command == ":q" || command == ":quit") {
     return false;
 
-  } else if (command != "") {
+  } else if (!command.empty()) {
     throw Error(format("unknown command '%1%'") % command);
 
   } else {
@@ -580,7 +587,8 @@ bool NixRepl::processLine(string line) {
 void NixRepl::loadFile(const Path& path) {
   loadedFiles.remove(path);
   loadedFiles.push_back(path);
-  Value v, v2;
+  Value v;
+  Value v2;
   state.evalFile(lookupFileArg(state, path), v);
   state.autoCallFunction(*autoArgs, v, v2);
   addAttrsToScope(v2);
@@ -652,7 +660,7 @@ std::ostream& NixRepl::printValue(std::ostream& str, Value& v,
 
 std::ostream& printStringValue(std::ostream& str, const char* string) {
   str << "\"";
-  for (const char* i = string; *i; i++) {
+  for (const char* i = string; *i != 0; i++) {
     if (*i == '\"' || *i == '\\') {
       str << "\\" << *i;
     } else if (*i == '\n') {
diff --git a/third_party/nix/src/nix/run.cc b/third_party/nix/src/nix/run.cc
index 5459c38952d4..9827360f0aa9 100644
--- a/third_party/nix/src/nix/run.cc
+++ b/third_party/nix/src/nix/run.cc
@@ -96,7 +96,7 @@ struct CmdRun : InstallablesCommand {
       std::map<std::string, std::string> kept;
       for (auto& var : keep) {
         auto s = getenv(var.c_str());
-        if (s) {
+        if (s != nullptr) {
           kept[var] = s;
         }
       }
@@ -133,9 +133,7 @@ struct CmdRun : InstallablesCommand {
         continue;
       }
 
-      if (true) {
-        unixPath.push_front(path + "/bin");
-      }
+      { unixPath.push_front(path + "/bin"); }
 
       auto propPath = path + "/nix-support/propagated-user-env-packages";
       if (accessor->stat(propPath).type == FSAccessor::tRegular) {
@@ -249,7 +247,7 @@ void chrootHelper(int argc, char** argv) {
     }
 
     char* cwd = getcwd(nullptr, 0);
-    if (!cwd) {
+    if (cwd == nullptr) {
       throw SysError("getting current directory");
     }
     Finally freeCwd([&]() { free(cwd); });
diff --git a/third_party/nix/src/nix/search.cc b/third_party/nix/src/nix/search.cc
index 78a1f21bc1e2..5f6def220291 100644
--- a/third_party/nix/src/nix/search.cc
+++ b/third_party/nix/src/nix/search.cc
@@ -160,11 +160,11 @@ struct CmdSearch : SourceExprCommand, MixJSON {
             }
           }
 
-          if (cache) {
+          if (cache != nullptr) {
             cache->attr("type", "derivation");
             cache->attr("name", drv.queryName());
             cache->attr("system", drv.querySystem());
-            if (description != "") {
+            if (!description.empty()) {
               auto meta(cache->object("meta"));
               meta.attr("description", description);
             }
@@ -190,11 +190,12 @@ struct CmdSearch : SourceExprCommand, MixJSON {
 
           for (auto& i : *v->attrs) {
             auto cache2 =
-                cache ? std::make_unique<JSONObject>(cache->object(i.name))
-                      : nullptr;
+                cache != nullptr
+                    ? std::make_unique<JSONObject>(cache->object(i.name))
+                    : nullptr;
             doExpr(i.value,
-                   attrPath == "" ? (std::string)i.name
-                                  : attrPath + "." + (std::string)i.name,
+                   attrPath.empty() ? (std::string)i.name
+                                    : attrPath + "." + (std::string)i.name,
                    toplevel2 || fromCache, cache2 ? cache2.get() : nullptr);
           }
         }
@@ -256,7 +257,7 @@ struct CmdSearch : SourceExprCommand, MixJSON {
       }
     }
 
-    if (results.size() == 0) {
+    if (results.empty()) {
       throw Error("no results for the given search term(s)!");
     }
 
diff --git a/third_party/nix/src/nix/show-derivation.cc b/third_party/nix/src/nix/show-derivation.cc
index 4a604c2c224c..b821a9ee1205 100644
--- a/third_party/nix/src/nix/show-derivation.cc
+++ b/third_party/nix/src/nix/show-derivation.cc
@@ -63,7 +63,7 @@ struct CmdShowDerivation : InstallablesCommand {
           for (auto& output : drv.outputs) {
             auto outputObj(outputsObj.object(output.first));
             outputObj.attr("path", output.second.path);
-            if (output.second.hash != "") {
+            if (!output.second.hash.empty()) {
               outputObj.attr("hashAlgo", output.second.hashAlgo);
               outputObj.attr("hash", output.second.hash);
             }
diff --git a/third_party/nix/src/nix/sigs.cc b/third_party/nix/src/nix/sigs.cc
index eb99fc8ee581..420296a8023f 100644
--- a/third_party/nix/src/nix/sigs.cc
+++ b/third_party/nix/src/nix/sigs.cc
@@ -71,7 +71,7 @@ struct CmdCopySigs : StorePathsCommand {
           }
 
           for (auto& sig : info2->sigs) {
-            if (!info->sigs.count(sig)) {
+            if (info->sigs.count(sig) == 0u) {
               newSigs.insert(sig);
             }
           }
@@ -132,7 +132,7 @@ struct CmdSignPaths : StorePathsCommand {
       info2.sign(secretKey);
       assert(!info2.sigs.empty());
 
-      if (!info->sigs.count(*info2.sigs.begin())) {
+      if (info->sigs.count(*info2.sigs.begin()) == 0u) {
         store->addSignatures(storePath, info2.sigs);
         added++;
       }
diff --git a/third_party/nix/src/nix/upgrade-nix.cc b/third_party/nix/src/nix/upgrade-nix.cc
index dd11da0087c7..b225aac2d725 100644
--- a/third_party/nix/src/nix/upgrade-nix.cc
+++ b/third_party/nix/src/nix/upgrade-nix.cc
@@ -52,7 +52,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
   void run(ref<Store> store) override {
     evalSettings.pureEval = true;
 
-    if (profileDir == "") {
+    if (profileDir.empty()) {
       profileDir = getProfileDir(store);
     }
 
@@ -97,7 +97,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
   }
 
   /* Return the profile in which Nix is installed. */
-  Path getProfileDir(ref<Store> store) {
+  static Path getProfileDir(ref<Store> store) {
     Path where;
 
     for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@@ -107,7 +107,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
       }
     }
 
-    if (where == "") {
+    if (where.empty()) {
       throw Error(
           "couldn't figure out how Nix is installed, so I can't upgrade it");
     }
diff --git a/third_party/nix/src/nix/verify.cc b/third_party/nix/src/nix/verify.cc
index 6b74761ba75a..63dd181e074c 100644
--- a/third_party/nix/src/nix/verify.cc
+++ b/third_party/nix/src/nix/verify.cc
@@ -94,7 +94,7 @@ struct CmdVerify : StorePathsCommand {
         if (!noTrust) {
           bool good = false;
 
-          if (info->ultimate && !sigsNeeded) {
+          if (info->ultimate && (sigsNeeded == 0u)) {
             good = true;
 
           } else {
@@ -104,7 +104,7 @@ struct CmdVerify : StorePathsCommand {
 
             auto doSigs = [&](StringSet sigs) {
               for (auto sig : sigs) {
-                if (sigsSeen.count(sig)) {
+                if (sigsSeen.count(sig) != 0u) {
                   continue;
                 }
                 sigsSeen.insert(sig);
@@ -162,7 +162,8 @@ struct CmdVerify : StorePathsCommand {
 
     pool.process();
 
-    throw Exit((corrupted ? 1 : 0) | (untrusted ? 2 : 0) | (failed ? 4 : 0));
+    throw Exit((corrupted != 0u ? 1 : 0) | (untrusted != 0u ? 2 : 0) |
+               (failed != 0u ? 4 : 0));
   }
 };
 
diff --git a/third_party/nix/src/nix/why-depends.cc b/third_party/nix/src/nix/why-depends.cc
index baf27a69514a..bbbfd1fe0182 100644
--- a/third_party/nix/src/nix/why-depends.cc
+++ b/third_party/nix/src/nix/why-depends.cc
@@ -18,7 +18,7 @@ static std::string hilite(const std::string& s, size_t pos, size_t len,
 static std::string filterPrintable(const std::string& s) {
   std::string res;
   for (char c : s) {
-    res += isprint(c) ? c : '.';
+    res += isprint(c) != 0 ? c : '.';
   }
   return res;
 }
@@ -70,7 +70,7 @@ struct CmdWhyDepends : SourceExprCommand {
     PathSet closure;
     store->computeFSClosure({packagePath}, closure, false, false);
 
-    if (!closure.count(dependencyPath)) {
+    if (closure.count(dependencyPath) == 0u) {
       LOG(WARNING) << "'" << package->what() << "' does not depend on '"
                    << dependency->what() << "'";
       return;
@@ -146,7 +146,7 @@ struct CmdWhyDepends : SourceExprCommand {
       assert(node.dist != inf);
       std::cout << fmt("%s%s%s%s" ANSI_NORMAL "\n", firstPad,
                        node.visited ? "\e[38;5;244m" : "",
-                       firstPad != "" ? "=> " : "", node.path);
+                       !firstPad.empty() ? "=> " : "", node.path);
 
       if (node.path == dependencyPath && !all &&
           packagePath != dependencyPath) {