Nix 2.26.3
Nix, the purely functional package manager; unstable internal interfaces
 
Loading...
Searching...
No Matches
lexer.l File Reference

This file defines two main structs/classes used in nix error handling. More...

#include "parser-tab.hh"
#include "parser-state.hh"
#include "nixexpr.hh"
#include "lexer-helpers.hh"

Classes

class  Ptr
 
struct  DrvDeep
 
struct  unchecked_t
 
struct  Iterator
 
struct  SettingInfo
 
struct  SettingData
 
struct  Field
 
struct  iterable_wrapper
 
struct  Stat
 
class  Result
 
struct  AstSymbols
 
struct  AttrDef
 
struct  DynamicAttrDef
 
struct  ExprOpEq
 
struct  ExprOpNEq
 
struct  ExprOpAnd
 
struct  ExprOpOr
 
struct  ExprOpImpl
 
struct  ExprOpUpdate
 
struct  ExprOpConcatLists
 
struct  Stdin
 
struct  String
 
struct  LinesIterator
 
class  Lock< L >
 
struct  WriteLock
 
struct  ReadLock
 
class  Origin
 
struct  Doc
 

Macros

#define GC_MALLOC_ATOMIC   std::malloc
 
#define ANSI_NORMAL   "\e[0m"
 
#define ANSI_BOLD   "\e[1m"
 
#define ANSI_FAINT   "\e[2m"
 
#define ANSI_ITALIC   "\e[3m"
 
#define ANSI_RED   "\e[31;1m"
 
#define ANSI_GREEN   "\e[32;1m"
 
#define ANSI_WARNING   "\e[35;1m"
 
#define ANSI_BLUE   "\e[34;1m"
 
#define ANSI_MAGENTA   "\e[35;1m"
 
#define ANSI_CYAN   "\e[36;1m"
 
#define MakeError(newClass, superClass)
 
#define unreachable()
 
#define GENERATE_ONE_CMP(PRE, RET, QUAL, COMPARATOR, MY_TYPE, ...)
 
#define GENERATE_EQUAL(prefix, qualification, my_type, args...)
 
#define GENERATE_SPACESHIP(prefix, ret, qualification, my_type, args...)
 
#define GENERATE_CMP(args...)
 
#define GENERATE_CMP_EXT(prefix, ret, my_type, args...)
 
#define FORCE_DEFAULT_CONSTRUCTORS(CLASS_NAME)
 
#define MAKE_WRAPPER_CONSTRUCTOR(CLASS_NAME)
 
#define logErrorInfo(level, errorInfo...)
 
#define logError(errorInfo...)
 
#define logWarning(errorInfo...)
 
#define printMsgUsing(loggerParam, level, args...)
 
#define printMsg(level, args...)
 
#define printError(args...)
 
#define notice(args...)
 
#define printInfo(args...)
 
#define printTalkative(args...)
 
#define debug(args...)
 
#define vomit(args...)
 
#define warnOnce(haveWarned, args...)
 
#define OS_STR(s)
 
#define S_ISLNK(m)
 
#define COMMON_METHODS
 
#define MakeBinOp(name, s)
 
#define CUR_POS   state->at(*yylloc)
 
#define YY_USER_INIT   initLoc(yylloc)
 
#define YY_USER_ACTION   adjustLoc(yyscanner, yylloc, yytext, yyleng);
 
#define PUSH_STATE(state)
 
#define POP_STATE()
 

Typedefs

using Raw = std::variant<T, Suggestions>
 
using Opaque = SingleDerivedPath::Opaque
 
using Built = SingleDerivedPath::Built
 
using Settings = std::map<std::string, SettingData>
 
typedef std::vector< FieldFields
 
typedef std::function< void(std::string_view data)> lambda_t
 
using string_view = OsStringView
 
typedef std::optional< TypeDirEntry
 
typedef std::map< std::string, DirEntry > DirEntries
 
using Inner = T
 
typedef std::map< Symbol, AttrDefAttrDefs
 
typedef std::vector< DynamicAttrDefDynamicAttrDefs
 
typedef std::vector< FormalFormals_
 
typedef std::vector< std::pair< Symbol, Displacement > > Vars
 
typedef uint32_t size_t
 
typedef Attriterator
 
typedef const Attrconst_iterator
 
using value_type = Attr
 
typedef std::variant< std::monostate, Stdin, String, SourcePathOrigin
 
using Lines = std::vector<uint32_t>
 
typedef std::unordered_map< SourcePath, Expr *, std::hash< SourcePath >, std::equal_to< SourcePath >, traceable_allocator< std::pair< const SourcePath, Expr * > > > FileParseCache
 
typedef std::unordered_map< SourcePath, Value, std::hash< SourcePath >, std::equal_to< SourcePath >, traceable_allocator< std::pair< const SourcePath, Value > > > FileEvalCache
 
typedef std::map< std::string, size_tPrimOpCalls
 
typedef std::map< ExprLambda *, size_tFunctionCalls
 
typedef std::map< PosIdx, size_tAttrSelects
 
using LookupPathHook = std::optional<SourcePath>(EvalState & state, std::string_view)
 
using LookupPathHooks = std::map<std::string, std::function<LookupPathHook>>
 

Enumerations

enum  Type {
  tRegular , tSymlink , tDirectory , tChar ,
  tBlock , tSocket , tFifo , tUnknown
}
 
enum  OverflowKind { NoOverflow , Overflow , DivByZero }
 

Functions

 OnStartup (T &&t)
 
bool operator== (const Explicit< T > &other) const =default
 
bool operator< (const Explicit< T > &other) const
 
 BackedStringView (std::string &&s)
 
 BackedStringView (std::string_view sv)
 
 BackedStringView (const char(&lit)[N])
 
 BackedStringView (const BackedStringView &)=delete
 
BackedStringViewoperator= (const BackedStringView &)=delete
 
 BackedStringView (BackedStringView &&other)=default
 
BackedStringViewoperator= (BackedStringView &&other)=default
 
bool isOwned () const
 
std::string toOwned () &&
 
std::string_view operator* () const
 
Ptr operator-> () const
 
std::string to_string () const
 
bool operator== (const Suggestion &) const =default
 
auto operator<=> (const Suggestion &) const =default
 
Suggestions trim (int limit=5, int maxDistance=2) const
 
Suggestionsoperator+= (const Suggestions &other)
 
 operator bool () const noexcept
 
 OrSuggestions (T t)
 
 OrSuggestions ()
 
const SuggestionsgetSuggestions ()
 
 formatHelper (f % x, args...)
 
fmt exceptions (boost::io::all_error_bits ^ boost::io::too_many_args_bit ^ boost::io::too_few_args_bit)
 
boost::format f (fs)
 
 setExceptions (f)
 
 formatHelper (f, args...)
 
 Magenta (const T &s)
 
return out<< ANSI_WARNING<< y.value<< ANSI_NORMAL;Uncolored(const T &s) :value(s) {} const T &value;return out<< ANSI_NORMAL<< y.value;boost::format fmt;HintFmt(const std::string &literal) :HintFmt("%s", Uncolored(literal)) { } static HintFmt fromFormatString(const std::string &format) { return HintFmt(boost::format(format));} template< typename... ArgsHintFmt (const std::string &format, const Args &... args)
 
 HintFmt (const HintFmt &hf)
 
 HintFmt (boost::format &&fmt, const Args &... args)
 
HintFmtoperator% (const T &value)
 
HintFmtoperator% (const Uncolored< T > &value)
 
HintFmtoperator= (HintFmt const &rhs)=default
 
const std::string & calcWhat () const
 
 BaseError (const BaseError &)=default
 
BaseErroroperator= (const BaseError &)=default
 
BaseErroroperator= (BaseError &&)=default
 
 BaseError (unsigned int status, const Args &... args)
 
 BaseError (const std::string &fs, const Args &... args)
 
 BaseError (const Suggestions &sug, const Args &... args)
 
 BaseError (HintFmt hint)
 
 BaseError (ErrorInfo &&e)
 
 BaseError (const ErrorInfo &e)
 
std::string message ()
 
const charwhat () const noexcept override
 
const ErrorInfoinfo () const
 
void withExitStatus (unsigned int status)
 
void atPos (std::shared_ptr< Pos > pos)
 
void pushTrace (Trace trace)
 
void addTrace (std::shared_ptr< Pos > &&e, std::string_view fs, const Args &... args)
 
void addTrace (std::shared_ptr< Pos > &&e, HintFmt hint, TracePrint print=TracePrint::Default)
 
bool hasTrace () const
 
 SysError (int errNo, const Args &... args)
 
 SysError (const Args &... args)
 
auto & addChunk ()
 
 ChunkedVector (uint32_t reserve)
 
uint32_t size () const
 
std::pair< T &, uint32_t > add (T value)
 
const T & operator[] (uint32_t idx) const
 
void forEach (Fn fn) const
 
 SymbolStr (const std::string &symbol)
 
bool operator== (std::string_view s2) const
 
const charc_str () const
 
std::ostream & operator<< (std::ostream &os, const SymbolStr &symbol)
 
bool empty () const
 
 Symbol (uint32_t id)
 
 Symbol ()
 
auto operator<=> (const Symbol other) const
 
bool operator== (const Symbol other) const
 
Symbol create (std::string_view s)
 
std::vector< SymbolStrresolve (const std::vector< Symbol > &symbols) const
 
SymbolStr operator[] (Symbol s) const
 
size_t totalSize () const
 
void dump (T callback) const
 
std::size_t operator() (const nix::Symbol &s) const noexcept
 
 BadNixStringContextElem (std::string_view raw_, const Args &... args)
 
 GENERATE_CMP (NixStringContextElem, me->raw)
 
 MAKE_WRAPPER_CONSTRUCTOR (NixStringContextElem)
 
 ref (const std::shared_ptr< T > &p)
 
 ref (T *p)
 
std::shared_ptr< T > get_ptr () const
 
ref< T2 > cast () const
 
std::shared_ptr< T2 > dynamic_pointer_cast () const
 
 operator ref< T2 > () const
 
bool operator== (const ref< T > &other) const
 
bool operator!= (const ref< T > &other) const
 
auto operator<=> (const ref< T > &other) const
 
ref< T2 > make_ref (Args &&... args)
 
return ref< T > (p)
 
 CanonPath (std::string_view raw)
 
 CanonPath (const char *raw)
 
 CanonPath (unchecked_t _, std::string path)
 
 CanonPath (const std::vector< std::string > &elems)
 
 CanonPath (std::string_view raw, const CanonPath &root)
 
bool isRoot () const
 
const std::string & abs () const
 
const std::string & absOrEmpty () const
 
std::string_view rel () const
 
const charrel_c_str () const
 
std::optional< CanonPathparent () const
 
void pop ()
 
std::optional< std::string_viewdirOf () const
 
std::optional< std::string_viewbaseName () const
 
bool operator== (const CanonPath &x) const
 
bool operator!= (const CanonPath &x) const
 
auto operator<=> (const CanonPath &x) const
 
bool isWithin (const CanonPath &parent) const
 
CanonPath removePrefix (const CanonPath &prefix) const
 
void extend (const CanonPath &x)
 
CanonPath operator/ (const CanonPath &x) const
 
void push (std::string_view c)
 
CanonPath operator/ (std::string_view c) const
 
bool isAllowed (const std::set< CanonPath > &allowed) const
 
std::string makeRelative (const CanonPath &path) const
 
std::size_t operator() (const nix::CanonPath &s) const noexcept
 
 MissingExperimentalFeature (ExperimentalFeature missingFeature)
 
 AbstractConfig (StringMap initials={})
 
virtual bool set (const std::string &name, const std::string &value)=0
 
virtual void getSettings (std::map< std::string, SettingInfo > &res, bool overriddenOnly=false)=0
 
void applyConfig (const std::string &contents, const std::string &path="<unknown>")
 
virtual void resetOverridden ()=0
 
virtual nlohmann::json toJSON ()=0
 
virtual std::string toKeyValue ()=0
 
virtual void convertToArgs (Args &args, const std::string &category)=0
 
void warnUnknownSettings ()
 
void reapplyUnknownSettings ()
 
 Config (StringMap initials={})
 
void addSetting (AbstractSetting *setting)
 
 AbstractSetting (const std::string &name, const std::string &description, const std::set< std::string > &aliases, std::optional< ExperimentalFeature > experimentalFeature=std::nullopt)
 
virtual void set (const std::string &value, bool append=false)=0
 
virtual bool isAppendable ()=0
 
virtual std::map< std::string, nlohmann::json > toJSONObject () const
 
virtual void convertToArg (Args &args, const std::string &category)
 
bool isOverridden () const
 
virtual T parse (const std::string &str) const
 
virtual void appendOrSet (T newValue, bool append)
 
 BaseSetting (const T &def, const bool documentDefault, const std::string &name, const std::string &description, const std::set< std::string > &aliases={}, std::optional< ExperimentalFeature > experimentalFeature=std::nullopt)
 
 operator const T & () const
 
 operator T& ()
 
const T & get () const
 
bool operator== (const U &v2) const
 
bool operator!= (const U &v2) const
 
void operator= (const U &v)
 
virtual void assign (const T &v)
 
void setDefault (const U &v)
 
virtual void override (const T &v)
 
return str<< static_cast< const T & > (opt)
 
 Setting (Config *options, const T &def, const std::string &name, const std::string &description, const std::set< std::string > &aliases={}, const bool documentDefault=true, std::optional< ExperimentalFeature > experimentalFeature=std::nullopt)
 
void operator= (const T &v)
 
 PathSetting (Config *options, const Path &def, const std::string &name, const std::string &description, const std::set< std::string > &aliases={})
 
Path operator+ (const char *p) const
 
void operator= (const Path &v)
 
 OptionalPathSetting (Config *options, const std::optional< Path > &def, const std::string &name, const std::string &description, const std::set< std::string > &aliases={})
 
void operator= (const std::optional< Path > &v)
 
bool isEnabled (const ExperimentalFeature &) const
 
void require (const ExperimentalFeature &) const
 
bool isEnabled (const std::optional< ExperimentalFeature > &) const
 
void require (const std::optional< ExperimentalFeature > &) const
 
virtual void stop ()
 
virtual void pause ()
 
virtual void resume ()
 
virtual bool isVerbose ()
 
virtual void log (Verbosity lvl, std::string_view s)=0
 
void log (std::string_view s)
 
virtual void logEI (const ErrorInfo &ei)=0
 
void logEI (Verbosity lvl, ErrorInfo ei)
 
virtual void warn (const std::string &msg)
 
virtual void startActivity (ActivityId act, Verbosity lvl, ActivityType type, const std::string &s, const Fields &fields, ActivityId parent)
 
virtual void stopActivity (ActivityId act)
 
virtual void result (ActivityId act, ResultType type, const Fields &fields)
 
virtual void writeToStdout (std::string_view s)
 
void cout (const Args &... args)
 
virtual std::optional< charask (std::string_view s)
 
virtual void setPrintBuildLogs (bool printBuildLogs)
 
 nop (T...)
 
 Activity (Logger &logger, Verbosity lvl, ActivityType type, const std::string &s="", const Logger::Fields &fields={}, ActivityId parent=getCurActivity())
 
 Activity (Logger &logger, ActivityType type, const Logger::Fields &fields={}, ActivityId parent=getCurActivity())
 
 Activity (const Activity &act)=delete
 
void progress (uint64_t done=0, uint64_t expected=0, uint64_t running=0, uint64_t failed=0) const
 
void setExpected (ActivityType type2, uint64_t expected) const
 
void result (ResultType type, const Args &... args) const
 
void result (ResultType type, const Logger::Fields &fields) const
 
 PushActivity (ActivityId act)
 
logger warn (f.str())
 
return concatStringsSep ({}, views)
 
 for (auto &s :c) res.push_back("'"+s+"'")
 
 if (!s.empty())
 
 if (auto n=string2Int< N >(s)) return *n *multiplier
 
throw UsageError ("'%s' is not an integer", s)
 
 for (size_t i=0;i< sizeof(x);++i,++p)
 
 if (i==map.end()) return nullptr
 
erase (i)
 
 if (c.empty()) return
 
insert (c.end(), l.begin(), l.end())
 
 MaintainCount (T &counter, long delta=1)
 
s reserve (s1.size()+s2.size())
 
s append (s1)
 
s append (s2)
 
s reserve (s1.size()+s2Size)
 
s append (s2, s2Size)
 
 AutoCloseFD ()
 
 AutoCloseFD (Descriptor fd)
 
 AutoCloseFD (const AutoCloseFD &fd)=delete
 
 AutoCloseFD (AutoCloseFD &&fd) noexcept
 
AutoCloseFDoperator= (const AutoCloseFD &fd)=delete
 
AutoCloseFDoperator= (AutoCloseFD &&fd)
 
Descriptor release ()
 
void close ()
 
void fsync () const
 
void startFsync () const
 
void create ()
 
virtual ~Sink ()
 
virtual void operator() (std::string_view data)=0
 
virtual bool good ()
 
virtual void finish ()=0
 
 BufferedSink (size_t bufSize=32 *1024)
 
void flush ()
 
virtual void writeUnbuffered (std::string_view data)=0
 
virtual ~Source ()
 
void operator() (char *data, size_t len)
 
virtual size_t read (char *data, size_t len)=0
 
void drainInto (Sink &sink)
 
std::string drain ()
 
 BufferedSource (size_t bufSize=32 *1024)
 
bool hasData ()
 
virtual size_t readUnbuffered (char *data, size_t len)=0
 
 FdSink ()
 
 FdSink (Descriptor fd)
 
 FdSink (FdSink &&)=default
 
FdSinkoperator= (FdSink &&s)
 
 FdSource ()
 
 FdSource (Descriptor fd)
 
 FdSource (FdSource &&)=default
 
FdSourceoperator= (FdSource &&s)=default
 
 StringSink ()
 
 StringSink (const size_t reservedSize)
 
 StringSink (std::string &&s)
 
 StringSource (std::string &&)=delete
 
 StringSource (std::string_view s)
 
 StringSource (const std::string &str)
 
 TeeSink (Sink &sink1, Sink &sink2)
 
 TeeSource (Source &orig, Sink &sink)
 
 SizedSource (Source &orig, size_t size)
 
size_t drainAll ()
 
 LengthSource (Source &next)
 
 LambdaSink (const lambda_t &lambda)
 
 LambdaSource (const lambda_t &lambda)
 
 ChainSource (Source &s1, Source &s2)
 
 sink ({(char *) buf, sizeof(buf)})
 
 source ((char *) buf, sizeof(buf))
 
 if (n >(uint64_t) std::numeric_limits< T >::max()) throw SerialisationError("serialised integer %d is too large for type '%s'"
 
 typeid (T).name())
 
 return (T) n
 
return readNum< unsigned int > (source)
 
return readNum< uint64_t > (source)
 
 StreamToSourceAdapter (std::shared_ptr< std::basic_istream< char > > istream)
 
 FramedSource (Source &from)
 
 FramedSink (BufferedSink &to, std::function< void()> &&checkError)
 
 PathViewNG (const std::filesystem::path &path)
 
 PathViewNG (const OsString &path)
 
const string_viewnative () const
 
return writeFile (path.string(), s, mode, sync)
 
return writeFile (path.string(), source, mode, sync)
 
return createDirs (Path(path))
 
return replaceSymlink (std::filesystem::path{target}, std::filesystem::path{link})
 
 AutoDelete ()
 
 AutoDelete (const std::filesystem::path &p, bool recursive=true)
 
void cancel ()
 
void reset (const std::filesystem::path &p, bool recursive=true)
 
PathViewNG view () const
 
 operator PathViewNG () const
 
void operator() (DIR *dir) const
 
 Hash (HashAlgorithm algo)
 
 Hash (std::string_view s, HashAlgorithm algo, bool isSRI)
 
bool operator== (const Hash &h2) const noexcept
 
std::strong_ordering operator<=> (const Hash &h2) const noexcept
 
size_t base16Len () const
 
size_t base32Len () const
 
size_t base64Len () const
 
std::string to_string (HashFormat hashFormat, bool includeAlgo) const
 
std::string gitRev () const
 
std::string gitShortRev () const
 
 HashSink (HashAlgorithm ha)
 
 HashSink (const HashSink &h)
 
HashResult currentHash ()
 
 SourceAccessor ()
 
virtual std::string readFile (const CanonPath &path)
 
virtual void readFile (const CanonPath &path, Sink &sink, std::function< void(uint64_t)> sizeCallback=[](uint64_t size){})
 
virtual bool pathExists (const CanonPath &path)
 
Stat lstat (const CanonPath &path)
 
virtual std::optional< StatmaybeLstat (const CanonPath &path)=0
 
virtual DirEntries readDirectory (const CanonPath &path)=0
 
virtual std::string readLink (const CanonPath &path)=0
 
virtual void dumpPath (const CanonPath &path, Sink &sink, PathFilter &filter=defaultPathFilter)
 
Hash hashPath (const CanonPath &path, PathFilter &filter=defaultPathFilter, HashAlgorithm ha=HashAlgorithm::SHA256)
 
virtual std::optional< std::filesystem::pathgetPhysicalPath (const CanonPath &path)
 
bool operator== (const SourceAccessor &x) const
 
auto operator<=> (const SourceAccessor &x) const
 
void setPathDisplay (std::string displayPrefix, std::string displaySuffix="")
 
virtual std::string showPath (const CanonPath &path)
 
CanonPath resolveSymlinks (const CanonPath &path, SymlinkResolution mode=SymlinkResolution::Full)
 
virtual std::optional< time_t > getLastModified ()
 
 hash_combine (seed, rest...)
 
 SourcePath (ref< SourceAccessor > accessor, CanonPath path=CanonPath::root)
 
std::string readFile () const
 
void readFile (Sink &sink, std::function< void(uint64_t)> sizeCallback=[](uint64_t size){}) const
 
bool pathExists () const
 
SourceAccessor::Stat lstat () const
 
std::optional< SourceAccessor::Stat > maybeLstat () const
 
SourceAccessor::DirEntries readDirectory () const
 
std::string readLink () const
 
void dumpPath (Sink &sink, PathFilter &filter=defaultPathFilter) const
 
std::optional< std::filesystem::pathgetPhysicalPath () const
 
bool operator== (const SourcePath &x) const noexcept
 
std::strong_ordering operator<=> (const SourcePath &x) const noexcept
 
SourcePath resolveSymlinks (SymlinkResolution mode=SymlinkResolution::Full) const
 
std::size_t operator() (const nix::SourcePath &s) const noexcept
 
bool shouldPrettyPrint ()
 
 Checked ()=default
 
 Checked (T const value)
 
 Checked (Checked< T > const &other)=default
 
 Checked (Checked< T > &&other)=default
 
Checked< T > & operator= (Checked< T > const &other)=default
 
std::strong_ordering operator<=> (Checked< T > const &other) const =default
 
std::strong_ordering operator<=> (T const &other) const
 
 operator T () const
 
Result operator+ (Checked< T > const other) const
 
Result operator+ (T const other) const
 
Result operator- (Checked< T > const other) const
 
Result operator- (T const other) const
 
Result operator* (Checked< T > const other) const
 
Result operator* (T const other) const
 
Result operator/ (Checked< T > const other) const
 
Result operator/ (T const other) const
 
ios<< v.value;return ios;tUninitialized=0, tInt=1, tBool, tString, tPath, tNull, tAttrs, tList1, tList2, tListN, tThunk, tApp, tLambda, tPrimOp, tPrimOpApp, tExternal, tFloat nThunk, nInt, nFloat, nBool, nString, nPath, nNull, nAttrs, nList, nFunction, nExternal friend std::ostream &operator<<(std::ostream &str, const ExternalValueBase &v);friend class Printer;protected:virtual std::ostream &print(std::ostream &str) const =0;public:virtual std::string showType() const =0;virtual std::string typeOf() const =0;virtual std::string coerceToString(EvalState &state, const PosIdx &pos, NixStringContext &context, bool copyMore, bool copyToStore) const ;virtual bool operator==(const ExternalValueBase &b) const noexcept;virtual nlohmann::json printValueAsJSON(EvalState &state, bool strict, NixStringContext &context, bool copyToStore=true) const ;virtual void printValueAsXML(EvalState &state, bool strict, bool location, XMLWriter &doc, NixStringContext &context, PathSet &drvsSeen, const PosIdx pos) const ;virtual ~ExternalValueBase() { };const size_t size;Value *inlineElems[2]={nullptr, nullptr};Value **elems;ListBuilder(EvalState &state, size_t size);ListBuilder(ListBuilder &&x) noexcept :size(x.size), inlineElems{x.inlineElems[0], x.inlineElems[1]}, elems(size<=2 ? inlineElems :x.elems) { } Value *&operator[](size_t n) { return elems[n];} typedef Value **iterator;iterator begin() { return &elems[0];} iterator end() { return &elems[size];} friend struct Value;InternalType internalType=tUninitialized;friend std::string showType(const Value &v);void print(EvalState &state, std::ostream &str, PrintOptions options=PrintOptions {});inline bool isThunk() const { return internalType==tThunk;};inline bool isApp() const { return internalType==tApp;};inline bool isBlackhole() const ;inline bool isLambda() const { return internalType==tLambda;};inline bool isPrimOp() const { return internalType==tPrimOp;};inline bool isPrimOpApp() const { return internalType==tPrimOpApp;};struct StringWithContext { const char *c_str;const char **context;};struct Path { SourceAccessor *accessor;const char *path;};struct ClosureThunk { Env *env;Expr *expr;};struct FunctionApplicationThunk { Value *left, *right;};struct Lambda { Env *env;ExprLambda *fun;};using Payload=union { NixInt integer;bool boolean;StringWithContext string;Path path;Bindings *attrs;struct { size_t size;Value *const *elems;} bigList;Value *smallList[2];ClosureThunk thunk;FunctionApplicationThunk app;Lambda lambda;PrimOp *primOp;FunctionApplicationThunk primOpApp;ExternalValueBase *external;NixFloat fpoint;};Payload payload;inline ValueType type(bool invalidIsThunk=false) const { switch(internalType) { case tUninitialized:break;case tInt:return nInt;case tBool:return nBool;case tString:return nString;case tPath:return nPath;case tNull:return nNull;case tAttrs:return nAttrs;case tList1:case tList2:case tListN:return nList;case tLambda:case tPrimOp:case tPrimOpApp:return nFunction;case tExternal:return nExternal;case tFloat:return nFloat;case tThunk:case tApp:return nThunk;} if(invalidIsThunk) return nThunk;else unreachable();} inline void finishValue(InternalType newType, Payload newPayload) { payload=newPayload;internalType=newType;} inline bool isValid() const { return internalType !=tUninitialized;} inline void mkInt(NixInt::Inner n) { mkInt(NixInt{n});} inline void mkInt(NixInt n) { finishValue(tInt, { .integer=n });} inline void mkBool(bool b) { finishValue(tBool, { .boolean=b });} inline void mkString(const char *s, const char **context=0) { finishValue(tString, { .string={ .c_str=s,.context=context } });} void mkString(std::string_view s);void mkString(std::string_view s, const NixStringContext &context);void mkStringMove(const char *s, const NixStringContext &context);inline void mkString(const SymbolStr &s) { mkString(s.c_str());} void mkPath(const SourcePath &path);void mkPath(std::string_view path);inline void mkPath(SourceAccessor *accessor, const char *path) { finishValue(tPath, { .path={ .accessor=accessor,.path=path } });} inline void mkNull() { finishValue(tNull, {});} inline void mkAttrs(Bindings *a) { finishValue(tAttrs, { .attrs=a });} Value &mkAttrs(BindingsBuilder &bindings);void mkList(const ListBuilder &builder) { if(builder.size==1) finishValue(tList1, { .smallList={ builder.inlineElems[0] } });else if(builder.size==2) finishValue(tList2, { .smallList={ builder.inlineElems[0], builder.inlineElems[1] } });else finishValue(tListN, { .bigList={ .size=builder.size,.elems=builder.elems } });} inline void mkThunk(Env *e, Expr *ex) { finishValue(tThunk, { .thunk={ .env=e,.expr=ex } });} inline void mkApp(Value *l, Value *r) { finishValue(tApp, { .app={ .left=l,.right=r } });} inline void mkLambda(Env *e, ExprLambda *f) { finishValue(tLambda, { .lambda={ .env=e,.fun=f } });} inline void mkBlackhole();void mkPrimOp(PrimOp *p);inline void mkPrimOpApp(Value *l, Value *r) { finishValue(tPrimOpApp, { .primOpApp={ .left=l,.right=r } });} const PrimOp *primOpAppPrimOp() const ;inline void mkExternal(ExternalValueBase *e) { finishValue(tExternal, { .external=e });} inline void mkFloat(NixFloat n) { finishValue(tFloat, { .fpoint=n });} bool isList() const { return internalType==tList1||internalType==tList2||internalType==tListN;} Value *const *listElems() { return internalType==tList1||internalType==tList2 ? payload.smallList :payload.bigList.elems;} std::span< Value *const > listItems () const
 
Value *const * listElems () const
 
size_t listSize () const
 
PosIdx determinePos (const PosIdx pos) const
 
bool isTrivial () const
 
const char ** context () const
 
ExternalValueBaseexternal () const
 
const PrimOpprimOp () const
 
bool boolean () const
 
NixInt integer () const
 
NixFloat fpoint () const
 
 mkThunk (nullptr,(Expr *) &eBlackHole)
 
 PosIdx (uint32_t id)
 
 PosIdx ()
 
auto operator<=> (const PosIdx other) const
 
bool operator== (const PosIdx other) const
 
std::size_t operator() (nix::PosIdx pos) const noexcept
 
 EvalBaseError (EvalState &state, ErrorInfo &&errorInfo)
 
 EvalBaseError (EvalState &state, const std::string &formatString, const Args &... formatArgs)
 
 InvalidPathError (EvalState &state, const Path &path)
 
 EvalErrorBuilder (EvalState &state, const Args &... args)
 
EvalErrorBuilder< T > & atPos (PosIdx pos)
 
EvalErrorBuilder< T > & atPos (Value &value, PosIdx fallback=noPos)
 
EvalErrorBuilder< T > & withTrace (PosIdx pos, const std::string_view text)
 
EvalErrorBuilder< T > & withFrameTrace (PosIdx pos, const std::string_view text)
 
EvalErrorBuilder< T > & withSuggestions (Suggestions &s)
 
EvalErrorBuilder< T > & withFrame (const Env &e, const Expr &ex)
 
EvalErrorBuilder< T > & addTrace (PosIdx pos, HintFmt hint)
 
EvalErrorBuilder< T > & setIsFromExpr ()
 
EvalErrorBuilder< T > & addTrace (PosIdx pos, std::string_view formatString, const Args &... formatArgs)
 
void debugThrow ()
 
void panic ()
 
std::string getInnerText (const PosTable &positions) const
 
 AttrName (Symbol s)
 
 AttrName (Expr *e)
 
 Expr ()
 
virtual void show (const SymbolTable &symbols, std::ostream &str) const
 
virtual void bindVars (EvalState &es, const std::shared_ptr< const StaticEnv > &env)
 
virtual void eval (EvalState &state, Env &env, Value &v)
 
virtual ValuemaybeThunk (EvalState &state, Env &env)
 
virtual void setName (Symbol name)
 
virtual void setDocComment (DocComment docComment)
 
virtual PosIdx getPos () const
 
virtual void resetCursedOr ()
 
virtual void warnIfCursedOr (const SymbolTable &symbols, const PosTable &positions)
 
 ExprInt (NixInt n)
 
 ExprInt (NixInt::Inner n)
 
 ExprFloat (NixFloat nf)
 
 ExprString (std::string &&s)
 
 ExprPath (ref< SourceAccessor > accessor, std::string s)
 
 ExprVar (Symbol name)
 
 ExprVar (const PosIdx &pos, Symbol name)
 
 ExprInheritFrom (PosIdx pos, Displacement displ)
 
 ExprSelect (const PosIdx &pos, Expr *e, AttrPath attrPath, Expr *def)
 
 ExprSelect (const PosIdx &pos, Expr *e, Symbol name)
 
Symbol evalExceptFinalSelect (EvalState &state, Env &env, Value &attrs)
 
 ExprOpHasAttr (Expr *e, AttrPath attrPath)
 
 ExprAttrs (const PosIdx &pos)
 
std::shared_ptr< const StaticEnvbindInheritSources (EvalState &es, const std::shared_ptr< const StaticEnv > &env)
 
EnvbuildInheritFromEnv (EvalState &state, Env &up)
 
void showBindings (const SymbolTable &symbols, std::ostream &str) const
 
 ExprList ()
 
bool has (Symbol arg) const
 
std::vector< FormallexicographicOrder (const SymbolTable &symbols) const
 
 ExprLambda (PosIdx pos, Symbol arg, Formals *formals, Expr *body)
 
 ExprLambda (PosIdx pos, Formals *formals, Expr *body)
 
std::string showNamePos (const EvalState &state) const
 
bool hasFormals () const
 
 ExprCall (const PosIdx &pos, Expr *fun, std::vector< Expr * > &&args)
 
 ExprCall (const PosIdx &pos, Expr *fun, std::vector< Expr * > &&args, PosIdx &&cursedOrEndPos)
 
 ExprLet (ExprAttrs *attrs, Expr *body)
 
 ExprWith (const PosIdx &pos, Expr *attrs, Expr *body)
 
 ExprIf (const PosIdx &pos, Expr *cond, Expr *then, Expr *else_)
 
 ExprAssert (const PosIdx &pos, Expr *cond, Expr *body)
 
 ExprOpNot (Expr *e)
 
 ExprConcatStrings (const PosIdx &pos, bool forceString, std::vector< std::pair< PosIdx, Expr * > > *es)
 
 ExprPos (const PosIdx &pos)
 
 StaticEnv (ExprWith *isWith, const StaticEnv *up, size_t expectedSize=0)
 
void sort ()
 
void deduplicate ()
 
Vars::const_iterator find (Symbol name) const
 
 Attr (Symbol name, Value *value, PosIdx pos=noPos)
 
 Attr ()
 
auto operator<=> (const Attr &a) const
 
 Bindings (size_t capacity)
 
 Bindings (const Bindings &bindings)=delete
 
void push_back (const Attr &attr)
 
const Attrget (Symbol name) const
 
size_t capacity () const
 
 BindingsBuilder (EvalState &state, Bindings *bindings)
 
void insert (Symbol name, Value *value, PosIdx pos=noPos)
 
void insert (const Attr &attr)
 
Valuealloc (Symbol name, PosIdx pos=noPos)
 
Valuealloc (std::string_view name, PosIdx pos=noPos)
 
BindingsalreadySorted ()
 
void grow (Bindings *newBindings)
 
 Pos ()
 
 Pos (uint32_t line, uint32_t column, Origin origin)
 
 Pos (Pos &other)=default
 
 Pos (const Pos &other)=default
 
 Pos (Pos &&other)=default
 
 Pos (const Pos *other)
 
std::optional< std::string > getSource () const
 
void print (std::ostream &out, bool showOrigin) const
 
std::optional< LinesOfCodegetCodeLines () const
 
bool operator== (const Pos &rhs) const =default
 
auto operator<=> (const Pos &rhs) const =default
 
std::optional< std::string > getSnippetUpTo (const Pos &end) const
 
std::optional< SourcePathgetSourcePath () const
 
 SyncBase ()
 
 SyncBase (const T &data)
 
 SyncBase (T &&data) noexcept
 
WriteLock lock ()
 
ReadLock readLock () const
 
const Originresolve (PosIdx p) const
 
Origin addOrigin (Pos::Origin origin, size_t size)
 
PosIdx add (const Origin &origin, size_t offset)
 
Pos operator[] (PosIdx p) const
 
Pos::Origin originOf (PosIdx p) const
 
 GENERATE_CMP (LookupPath::Prefix, me->s)
 
std::optional< std::string_viewsuffixIfPotentialMatch (std::string_view path) const
 
 GENERATE_CMP (LookupPath::Path, me->s)
 
 GENERATE_CMP (LookupPath::Elem, me->prefix, me->path)
 
 CallDepth (size_t &count)
 
void check ()
 
const std::shared_ptr< const StaticEnvgetStaticEnv (const Expr &expr) const
 
bool canDebug ()
 
void runDebugRepl (const Error *error)
 
void runDebugRepl (const Error *error, const Env &env, const Expr &expr)
 
EvalErrorBuilder< T > & error (const Args &... args)
 
 EvalState (const LookupPath &_lookupPath, ref< Store > store, const fetchers::Settings &fetchSettings, const EvalSettings &settings, std::shared_ptr< Store > buildStore=nullptr)
 
LookupPath getLookupPath ()
 
SourcePath rootPath (CanonPath path)
 
SourcePath rootPath (PathView path)
 
void allowPath (const Path &path)
 
void allowPath (const StorePath &storePath)
 
void allowClosure (const StorePath &storePath)
 
void allowAndSetStorePathString (const StorePath &storePath, Value &v)
 
void checkURI (const std::string &uri)
 
Path toRealPath (const Path &path, const NixStringContext &context)
 
ExprparseExprFromFile (const SourcePath &path)
 
ExprparseExprFromFile (const SourcePath &path, std::shared_ptr< StaticEnv > &staticEnv)
 
ExprparseExprFromString (std::string s, const SourcePath &basePath, std::shared_ptr< StaticEnv > &staticEnv)
 
ExprparseExprFromString (std::string s, const SourcePath &basePath)
 
ExprparseStdin ()
 
void evalFile (const SourcePath &path, Value &v, bool mustBeTrivial=false)
 
void resetFileCache ()
 
SourcePath findFile (const std::string_view path)
 
SourcePath findFile (const LookupPath &lookupPath, const std::string_view path, const PosIdx pos=noPos)
 
std::optional< SourcePathresolveLookupPathPath (const LookupPath::Path &elem, bool initAccessControl=false)
 
void eval (Expr *e, Value &v)
 
bool evalBool (Env &env, Expr *e)
 
bool evalBool (Env &env, Expr *e, const PosIdx pos, std::string_view errorCtx)
 
void evalAttrs (Env &env, Expr *e, Value &v, const PosIdx pos, std::string_view errorCtx)
 
void forceValue (Value &v, const PosIdx pos)
 
void tryFixupBlackHolePos (Value &v, PosIdx pos)
 
void forceValueDeep (Value &v)
 
NixInt forceInt (Value &v, const PosIdx pos, std::string_view errorCtx)
 
NixFloat forceFloat (Value &v, const PosIdx pos, std::string_view errorCtx)
 
bool forceBool (Value &v, const PosIdx pos, std::string_view errorCtx)
 
void forceAttrs (Value &v, const PosIdx pos, std::string_view errorCtx)
 
void forceAttrs (Value &v, Callable getPos, std::string_view errorCtx)
 
void forceList (Value &v, const PosIdx pos, std::string_view errorCtx)
 
void forceFunction (Value &v, const PosIdx pos, std::string_view errorCtx)
 
std::string_view forceString (Value &v, const PosIdx pos, std::string_view errorCtx)
 
std::string_view forceString (Value &v, NixStringContext &context, const PosIdx pos, std::string_view errorCtx)
 
std::string_view forceStringNoCtx (Value &v, const PosIdx pos, std::string_view errorCtx)
 
void addErrorTrace (Error &e, const Args &... formatArgs) const
 
void addErrorTrace (Error &e, const PosIdx pos, const Args &... formatArgs) const
 
bool isDerivation (Value &v)
 
std::optional< std::string > tryAttrsToString (const PosIdx pos, Value &v, NixStringContext &context, bool coerceMore=false, bool copyToStore=true)
 
BackedStringView coerceToString (const PosIdx pos, Value &v, NixStringContext &context, std::string_view errorCtx, bool coerceMore=false, bool copyToStore=true, bool canonicalizePath=true)
 
StorePath copyPathToStore (NixStringContext &context, const SourcePath &path)
 
SourcePath coerceToPath (const PosIdx pos, Value &v, NixStringContext &context, std::string_view errorCtx)
 
StorePath coerceToStorePath (const PosIdx pos, Value &v, NixStringContext &context, std::string_view errorCtx)
 
std::pair< SingleDerivedPath, std::string_viewcoerceToSingleDerivedPathUnchecked (const PosIdx pos, Value &v, std::string_view errorCtx)
 
SingleDerivedPath coerceToSingleDerivedPath (const PosIdx pos, Value &v, std::string_view errorCtx)
 
void createBaseEnv ()
 
ValueaddConstant (const std::string &name, Value &v, Constant info)
 
void addConstant (const std::string &name, Value *v, Constant info)
 
ValueaddPrimOp (PrimOp &&primOp)
 
ValuegetBuiltin (const std::string &name)
 
ValuegetBuiltins ()
 
std::optional< DocgetDoc (Value &v)
 
ValuelookupVar (Env *env, const ExprVar &var, bool noEval)
 
Exprparse (char *text, size_t length, Pos::Origin origin, const SourcePath &basePath, std::shared_ptr< StaticEnv > &staticEnv)
 
CallDepth addCallDepth (const PosIdx pos)
 
bool eqValues (Value &v1, Value &v2, const PosIdx pos, std::string_view errorCtx)
 
void assertEqValues (Value &v1, Value &v2, const PosIdx pos, std::string_view errorCtx)
 
bool isFunctor (Value &fun)
 
void callFunction (Value &fun, std::span< Value * > args, Value &vRes, const PosIdx pos)
 
void callFunction (Value &fun, Value &arg, Value &vRes, const PosIdx pos)
 
void autoCallFunction (const Bindings &args, Value &fun, Value &res)
 
ValueallocValue ()
 
EnvallocEnv (size_t size)
 
BindingsallocBindings (size_t capacity)
 
BindingsBuilder buildBindings (size_t capacity)
 
ListBuilder buildList (size_t size)
 
ValuegetBool (bool b)
 
void mkThunk_ (Value &v, Expr *expr)
 
void mkPos (Value &v, PosIdx pos)
 
void mkStorePathString (const StorePath &storePath, Value &v)
 
void mkOutputString (Value &value, const SingleDerivedPath::Built &b, std::optional< StorePath > optStaticOutputPath, const ExperimentalFeatureSettings &xpSettings=experimentalFeatureSettings)
 
void mkSingleDerivedPathString (const SingleDerivedPath &p, Value &v)
 
void concatLists (Value &v, size_t nrLists, Value *const *lists, const PosIdx pos, std::string_view errorCtx)
 
void maybePrintStats ()
 
void printStatistics ()
 
bool fullGC ()
 
StringMap realiseContext (const NixStringContext &context, StorePathSet *maybePaths=nullptr, bool isIFD=true)
 
std::string realiseString (Value &str, StorePathSet *storePathsOutMaybe, bool isIFD=true, const PosIdx pos=noPos)
 
bool callPathFilter (Value *filterFun, const SourcePath &path, PosIdx pos)
 
DocComment getDocCommentForPos (PosIdx pos)
 
std::string mkOutputStringRaw (const SingleDerivedPath::Built &b, std::optional< StorePath > optStaticOutputPath, const ExperimentalFeatureSettings &xpSettings=experimentalFeatureSettings)
 
std::string mkSingleDerivedPathStringRaw (const SingleDerivedPath &p)
 
void incrFunctionCall (ExprLambda *fun)
 
void prim_getAttr (EvalState &state, const PosIdx pos, Value **args, Value &v)
 
void prim_match (EvalState &state, const PosIdx pos, Value **args, Value &v)
 
void prim_split (EvalState &state, const PosIdx pos, Value **args, Value &v)
 
 DebugTraceStacker (EvalState &evalState, DebugTrace t)
 
return printLiteralString (o, std::string_view(s))
 
std::ostream & operator<< (std::ostream &output, const ValuePrinter &printer)
 
 ValuePrinter (EvalState &state, Value &value, PrintOptions options=PrintOptions {})
 
 EvalSettings (bool &readOnlyMode, LookupPathHooks lookupPathHooks={})
 
const std::string & getCurrentSystem () const
 
 return (Value *) p
 
 if (v.isThunk())
 
 forceAttrs (v, [&]() { return pos;}, errorCtx)
 
 forceValue (v, pos)
 
 if (v.type() !=nAttrs)
 
 if (!v.isList())
 
 if (callDepth > settings.maxCallDepth) error< EvalError >("stack overflow
 
max call depth exceeded atPos (pos).debugThrow()
 
return CallDepth (callDepth)
 
void stash ()
 
void unstash ()
 
PosIdx at (const ParserLocation &loc)
 
void dupAttr (const AttrPath &attrPath, const PosIdx pos, const PosIdx prevPos)
 
void dupAttr (Symbol attr, const PosIdx pos, const PosIdx prevPos)
 
void addAttr (ExprAttrs *attrs, AttrPath &&attrPath, const ParserLocation &loc, Expr *e, const ParserLocation &exprLoc)
 
void addAttr (ExprAttrs *attrs, AttrPath &attrPath, const Symbol &symbol, ExprAttrs::AttrDef &&def)
 
FormalsvalidateFormals (Formals *formals, PosIdx pos=noPos, Symbol arg={})
 
ExprstripIndentation (const PosIdx pos, std::vector< std::pair< PosIdx, std::variant< Expr *, StringToken > > > &&es)
 
throw ParseError ({ .msg=HintFmt("attribute '%1%' already defined at %2%", showAttrPath(symbols, attrPath), positions[prevPos]),.pos=positions[pos] })
 
throw ParseError ({ .msg=HintFmt("attribute '%1%' already defined at %2%", symbols[attr], positions[prevPos]),.pos=positions[pos] })
 
 assert (!attrPath.empty())
 
 if (i->symbol)
 
 if (it !=lexerState.positionToDocComment.end())
 
 if (j !=attrs->attrs.end())
 
def e setName (symbol)
 
 for (size_t i=0;i+1< formals->formals.size();i++)
 
 if (duplicate) throw ParseError(
 
 if (arg &&formals->has(arg)) throw ParseError(
 
std::vector< std::pair< PosIdx, std::variant< Expr *, StringToken > > > &&es if (es.empty()) return new ExprString("")
 
 for (auto &[i_pos, i] :es)
 
 for (;i !=es.end();++i, --n)
 
 if (es2->size()==0)
 
return new ExprConcatStrings (pos, true, es2)
 
return positions add (origin, loc.beginOffset)
 
int yylex (YYSTYPE *yylval_param, YYLTYPE *yylloc_param, yyscan_t yyscanner)
 

Variables

t
 
std::variant< std::string, std::string_viewdata
 
int distance
 The smaller the better.
 
std::string suggestion
 
std::set< Suggestionsuggestions
 
Raw raw
 
return s
 
const T & value
 
 lvlError = 0
 
 lvlWarn
 
 lvlNotice
 
 lvlInfo
 
 lvlTalkative
 
 lvlChatty
 
 lvlDebug
 
lvlVomit std::optional< std::string > prevLineOfCode
 
std::optional< std::string > errLineOfCode
 
std::optional< std::string > nextLineOfCode
 
const std::string & prefix
 
const std::string const PoserrPos
 
const std::string const Pos const LinesOfCodeloc
 
 Default
 
 Always
 
std::shared_ptr< Pospos = 0
 
HintFmt hint
 
TracePrint print = TracePrint::Default
 
Verbosity level
 
HintFmt msg
 
std::list< Tracetraces
 
bool isFromExpr = false
 
unsigned int status = 1
 
ErrorInfo err
 
std::optional< std::string > what_
 
int errNo
 
 SysError
 
uint32_t size_ = 0
 
std::vector< std::vector< T > > chunks
 
uint32_t id
 
std::unordered_map< std::string_view, std::pair< const std::string *, uint32_t > > symbols
 
ChunkedVector< std::string, 8192 > store {16}
 
std::shared_ptr< T > p = std::make_shared<T>(std::forward<Args>(args)...)
 
std::string path
 
 CaDerivations
 
 ImpureDerivations
 
 Flakes
 
 FetchTree
 
 NixCommand
 
 GitHashing
 
 RecursiveNix
 
 NoUrlLiterals
 
 FetchClosure
 
 AutoAllocateUids
 
 Cgroups
 
 DaemonTrustOverride
 
 DynamicDerivations
 
 ParseTomlTimestamps
 
 ReadOnlyLocalStore
 
 LocalOverlayStore
 
 ConfigurableImpureEnv
 
 MountedSSHStore
 
 VerifiedFetches
 
 PipeOperators
 
const std::string_viewname
 
std::ostream & str
 
std::ostream const ExperimentalFeaturefeature
 
ExperimentalFeature missingFeature
 
StringMap unknownSettings
 
Settings _settings
 
const std::string description
 
const std::set< std::string > aliases
 
int created = 123
 
bool overridden = false
 
std::optional< ExperimentalFeatureexperimentalFeature
 
const T defaultValue
 
const bool documentDefault
 
Setting< std::set< ExperimentalFeature > > experimentalFeatures
 
 actUnknown = 0
 
 actCopyPath = 100
 
 actFileTransfer = 101
 
 actRealise = 102
 
 actCopyPaths = 103
 
 actBuilds = 104
 
 actBuild = 105
 
 actOptimiseStore = 106
 
 actVerifyPaths = 107
 
 actSubstitute = 108
 
 actQueryPathInfo = 109
 
 actPostBuildHook = 110
 
 actBuildWaiting = 111
 
 actFetchTree = 112
 
 resFileLinked = 100
 
 resBuildLogLine = 101
 
 resUntrustedPath = 102
 
 resCorruptedPath = 103
 
 resSetPhase = 104
 
 resProgress = 105
 
 resSetExpected = 106
 
 resPostBuildLogLine = 107
 
 resFetchStatus = 108
 
Setting< bool > showTrace
 
Loggerlogger
 
const ActivityId prevAct
 
const Activityact
 
const Activity std::map< ActivityId, Activity > & activities
 
const Activity std::map< ActivityId, Activity > std::string_view source
 
const Activity std::map< ActivityId, Activity > std::string_view bool trusted
 
Consider removing the empty string dropping behavior If acceptable
 
Consider removing the empty string dropping behavior If use concatStringsSep instead std::string std::enable_if_t<(... &&std::is_convertible_v< Parts, std::string_view >), std::string > std::string_view views [sizeof...(parts)] = {parts...}
 
Strings res
 
std::string std::string_view from
 
std::string std::string_view std::string_view to
 
uint64_t multiplier = 1
 
x = 0
 
auto i = map.find(key)
 
return &i second
 
const T::key_type & key
 
auto v = std::move(*i)
 
T & counter
 
long delta
 
 TIter = decltype(std::begin(std::declval<T>()))
 
return iterable_wrapper { std::forward<T>(iterable) }
 
auto s2Size = strlen(s2)
 
 int
 
return fd
 
Descriptor Sinksink
 
Descriptor Sink bool block
 
return STDIN_FILENO
 
return STDOUT_FILENO
 
return STDERR_FILENO
 
AutoCloseFD readSide
 
AutoCloseFD writeSide
 
size_t bufSize
 
size_t bufPos
 
std::unique_ptr< char[]> buffer
 
size_t bufPosIn
 
size_t bufPosOut
 
size_t written = 0
 
bool _good = true
 
size_t read = 0
 
BackedStringView endOfFileError {"unexpected end-of-file"}
 
Sinksink1
 
Sinksink2
 
Sourceorig
 
size_t remain
 
uint64_t length = 0
 
Sourcenext
 
uint64_t total = 0
 
lambda_t lambda
 
Sourcesource1
 
Sourcesource2
 
bool useSecond = false
 
std::function< void(Sink &)> fun
 
std::function< void(Sink &)> std::function< void()> eof
 
unsigned char buf [8] = n & 0xff
 
auto n = readLittleEndian<uint64_t>(buf)
 
return in
 
 b = readNum<uint64_t>(in)
 
std::shared_ptr< std::basic_istream< char > > istream
 
std::vector< charpending
 
std::function< void()> checkError
 
 char
 
std::optional< PathView > dir = {}
 
std::optional< PathView > bool resolveSymlinks = false)
 
const std::filesystem::path time_t accessedTime
 
const std::filesystem::path time_t time_t modificationTime
 
const std::filesystem::path time_t time_t std::optional< bool > isSymlink = std::nullopt)
 
std::filesystem::path _path
 
bool del
 
bool recursive
 
bool includePid = true
 
bool bool useGlobalCounter = true
 
bool bool mode_t mode = 0755)
 
 Base64
 Enumeration representing the hash formats.
 
 Nix32
 Nix-specific base-32 encoding.
 
 Base16
 Lowercase hexadecimal encoding.
 
size_t hashSize = 0
 
uint8_t hash [maxHashSize] = {}
 
HashAlgorithm algo
 
HashAlgorithm ha
 
Ctxctx
 
uint64_t bytes
 
 Ancestors
 
 Full
 
const size_t number
 
std::string displayPrefix
 
std::string displaySuffix
 
std::optional< std::string > fingerprint
 
std::hash< T > hasher
 
 seed = hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2)
 
ref< SourceAccessoraccessor
 
 Print
 
 Throw
 
 ThrowTopLevel
 
bool ansiColors = false
 
bool force = false
 
bool derivationPaths = false
 
bool trackRepeated = true
 
size_t maxDepth = std::numeric_limits<size_t>::max()
 
size_t maxAttrs = std::numeric_limits<size_t>::max()
 
size_t maxListItems = std::numeric_limits<size_t>::max()
 
size_t maxStringLength = std::numeric_limits<size_t>::max()
 
size_t prettyIndent = 0
 
ErrorPrintBehavior errors = ErrorPrintBehavior::Print
 
return internalType == tThunk && payload.thunk.expr == (Expr*) &eBlackHole
 
EvalStatestate
 
error
 
PosIdx begin
 
PosIdx end
 
Symbol symbol
 
Exprexpr
 
ExprWithfromWith
 
Displacement displ = 0
 
Expre
 
Exprdef
 
AttrPath attrPath
 
AttrDefs attrs
 
std::unique_ptr< std::vector< Expr * > > inheritFromExprs
 
DynamicAttrDefs dynamicAttrs
 
std::vector< Expr * > elems
 
Formals_ formals
 
bool ellipsis
 
Symbol arg
 
Exprbody
 
DocComment docComment
 
std::vector< Expr * > args
 
std::optional< PosIdxcursedOrEndPos
 
size_t prevWith
 
ExprWithparentWith
 
Exprcond
 
Exprthen
 
Exprelse_
 
bool forceString
 
std::vector< std::pair< PosIdx, Expr * > > * es
 
ExprWithisWith
 
const StaticEnvup
 
Vars vars
 
performance of the evaluator is highly sensitive to the size of Attr avoid introducing any padding into Attr if at all possible
 
performance of the evaluator is highly sensitive to the size of Attr avoid introducing any padding into Attr if at all and do not introduce new fields that need not be present for almost every instance
 
size_t capacity_
 
Bindingsbindings
 
uint32_t line = 0
 
uint32_t column = 0
 
Origin origin = std::monostate()
 
mutex
 
std::map< uint32_t, Originorigins
 
Sync< std::map< uint32_t, Lines > > lines
 
std::list< LookupPath::Elemelements
 
 QuitAll
 
 Continue
 
size_tcount
 
size_t arity = 0
 
const chardoc = nullptr
 
bool addTrace = true
 
bool internal = false
 
ValueType type = nThunk
 
bool impureOnly = false
 
Valuevalues [0]
 
const Envenv = (Env *) allocBytes(sizeof(Env) + size * sizeof(Value *))
 
bool isError
 
const fetchers::SettingsfetchSettings
 
const EvalSettingssettings
 
PosTable positions
 
const Symbol sWith
 
const Symbol sOutPath
 
const Symbol sDrvPath
 
const Symbol sType
 
const Symbol sMeta
 
const Symbol sName
 
const Symbol sValue
 
const Symbol sSystem
 
const Symbol sOverrides
 
const Symbol sOutputs
 
const Symbol sOutputName
 
const Symbol sIgnoreNulls
 
const Symbol sFile
 
const Symbol sLine
 
const Symbol sColumn
 
const Symbol sFunctor
 
const Symbol sToString
 
const Symbol sRight
 
const Symbol sWrong
 
const Symbol sStructuredAttrs
 
const Symbol sAllowedReferences
 
const Symbol sAllowedRequisites
 
const Symbol sDisallowedReferences
 
const Symbol sDisallowedRequisites
 
const Symbol sMaxSize
 
const Symbol sMaxClosureSize
 
const Symbol sBuilder
 
const Symbol sArgs
 
const Symbol sContentAddressed
 
const Symbol sImpure
 
const Symbol sOutputHash
 
const Symbol sOutputHashAlgo
 
const Symbol sOutputHashMode
 
const Symbol sRecurseForDerivations
 
const Symbol sDescription
 
const Symbol sSelf
 
const Symbol sEpsilon
 
const Symbol sStartSet
 
const Symbol sOperator
 
const Symbol sKey
 
const Symbol sPath
 
const Symbol sPrefix
 
const Symbol sOutputSpecified
 
const Expr::AstSymbols exprSymbols
 
RepairFlag repair
 
Bindings emptyBindings
 
Value vEmptyList
 
Value vNull
 
Value vTrue
 
Value vFalse
 
Value vStringRegular
 
Value vStringDirectory
 
Value vStringSymlink
 
Value vStringUnknown
 
const ref< SourceAccessorrootFS
 
const ref< MemorySourceAccessorcorepkgsFS
 
const ref< MemorySourceAccessorinternalFS
 
const SourcePath derivationInternal
 
const SourcePath callFlakeInternal
 
const ref< StorebuildStore
 
RootValue vImportedDrvToDerivation = nullptr
 
ReplExitStatus(* debugRepl )(ref< EvalState > es, const ValMap &extraEnv)
 
bool debugStop
 
bool inDebugger = false
 
int trylevel
 
std::list< DebugTracedebugTraces
 
std::map< const Expr *, const std::shared_ptr< const StaticEnv > > exprEnvs
 
std::map< const Hash, ref< eval_cache::EvalCache > > evalCaches
 
Sync< std::unordered_map< SourcePath, StorePath > > srcToStore
 
FileParseCache fileParseCache
 
FileEvalCache fileEvalCache
 
std::unordered_map< SourcePath, DocCommentMap > positionToDocComment
 Maps some positions to a DocComment, where the comment is relevant to the location.
 
LookupPath lookupPath
 
std::map< std::string, std::optional< SourcePath > > lookupPathResolved
 
std::shared_ptr< RegexCacheregexCache
 
EnvbaseEnv
 
std::shared_ptr< StaticEnvstaticBaseEnv
 
std::unordered_map< std::string, Value *, std::hash< std::string >, std::equal_to< std::string >, traceable_allocator< std::pair< const std::string, Value * > > > internalPrimOps
 
std::vector< std::pair< std::string, Constant > > constantInfos
 
unsigned int baseEnvDispl = 0
 
size_t callDepth = 0
 
unsigned long nrEnvs = 0
 
unsigned long nrValuesInEnvs = 0
 
unsigned long nrValues = 0
 
unsigned long nrListElems = 0
 
unsigned long nrLookups = 0
 
unsigned long nrAttrsets = 0
 
unsigned long nrAttrsInAttrsets = 0
 
unsigned long nrAvoided = 0
 
unsigned long nrOpUpdates = 0
 
unsigned long nrOpUpdateValuesCopied = 0
 
unsigned long nrListConcats = 0
 
unsigned long nrPrimOpCalls = 0
 
unsigned long nrFunctionCalls = 0
 
bool countCalls
 
PrimOpCalls primOpCalls
 
FunctionCalls functionCalls
 
AttrSelects attrSelects
 
EvalStateevalState
 
DebugTrace trace
 
PrintOptions options
 
bool & readOnlyMode
 
LookupPathHooks lookupPathHooks
 
Setting< bool > enableNativeCode
 
Setting< Strings > nixPath
 
Setting< std::string > currentSystem
 
Setting< bool > restrictEval
 
Setting< bool > pureEval
 
Setting< bool > enableImportFromDerivation
 
Setting< Strings > allowedUris
 
Setting< bool > traceFunctionCalls
 
Setting< bool > useEvalCache
 
Setting< bool > ignoreExceptionsDuringTry
 
Setting< bool > traceVerbose
 
Setting< unsigned intmaxCallDepth
 
Setting< bool > builtinsTraceDebugger
 
Setting< bool > builtinsDebuggerOnWarn
 
Setting< bool > builtinsAbortOnWarn
 
else *v payload app right
 
size_t l
 
bool hasIndentation
 
int beginOffset
 
int endOffset
 
int stashedBeginOffset
 
int stashedEndOffset
 
int doc_comment_first_column
 
int doc_comment_last_column
 
int docCommentDistance = std::numeric_limits<int>::max()
 
ParserLocation lastDocCommentLoc
 
const LexerStatelexerState
 
Exprresult
 
SourcePath basePath
 
 else
 
auto it = lexerState.positionToDocComment.find(pos)
 
ExprAttrs::AttrDefs::iterator j = attrs->attrs.find(symbol)
 
std::optional< std::pair< Symbol, PosIdx > > duplicate
 
bool atStartOfLine = true
 
size_t minIndent = 1000000
 
size_t curIndent = 0
 
auto * es2 = new std::vector<std::pair<PosIdx, Expr *>>
 
size_t curDropped = 0
 
const auto trimExpr
 
const auto trimString
 

Detailed Description

This file defines two main structs/classes used in nix error handling.

Common printing functions for the Nix language.

Pos and AbstractPos.

Options for printing Nix values.

SourcePath.

Some ANSI escape sequences.

Initialise the Boehm GC, if applicable. Make sure initGC has already been called.

ErrorInfo provides a standard payload of error information, with conversion to string happening in the logger rather than at the call site.

BaseError is the ancestor of nix specific exceptions (and Interrupted), and contains an ErrorInfo.

ErrorInfo structs are sent to the logger as part of an exception, or directly with the logError or logWarning macros. See libutil/tests/logging.cc for usage examples.

Awful hacky generation of the comparison operators by doing a lexicographic comparison between the choosen fields.

G

will generate comparison operators semantically equivalent to:

auto operator<=>(const ClassName& other) const noexcept {
if (auto cmp = field1 <=> other.field1; cmp != 0)
return cmp;
if (auto cmp = field2 <=> other.field2; cmp != 0)
return cmp;
...
return 0;
}
Parameters
prefixThis is for something before each declaration like template<classname Foo>.
my_typethe type are defining operators for.

Utiltities for working with the file sytem and file paths.

Return a source accessor that contains only an empty root directory. Exception thrown when accessing a filtered path (see FilteringSourceAccessor). Return an accessor for the root filesystem. Construct an accessor for the filesystem rooted at root. Note that it is not possible to escape root by appending .. path elements, and that absolute symlinks are resolved relative to root.

Hashing utilities for use with std::unordered_map, etc. (i.e. low level implementation logic, not domain logic like Nix hashing).

Checked arithmetic with classes that make it hard to accidentally make something an unchecked operation.

Returns
A string representing the type of the value v.
Parameters
withArticleWhether to begin with an english article, e.g. "an integer" vs "integer". If path refers to a directory, then append "/default.nix".
addDefaultNixWhether to append "/default.nix" after resolving symlinks. Whether a URI is allowed, assuming restrictEval is enabled

While most types come with their own methods for printing, they share some functions that are placed here.

ValuePrinter does its own ANSI formatting, so we don't color it magenta.

Macro Definition Documentation

◆ COMMON_METHODS

#define COMMON_METHODS
Value:
void show(const SymbolTable & symbols, std::ostream & str) const override; \
void eval(EvalState & state, Env & env, Value & v) override; \
void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override;
Definition eval.hh:182
Definition symbol-table.hh:82
std::ostream & str
Definition lexer.l:1728
std::unordered_map< std::string_view, std::pair< const std::string *, uint32_t > > symbols
Definition lexer.l:1010
Definition eval.hh:152
Definition value.hh:167

◆ debug

#define debug ( args...)
Value:
printMsg(lvlDebug, args)
std::vector< Expr * > args
Definition lexer.l:6126

◆ FORCE_DEFAULT_CONSTRUCTORS

#define FORCE_DEFAULT_CONSTRUCTORS ( CLASS_NAME)
Value:
CLASS_NAME(const CLASS_NAME &) = default; \
CLASS_NAME(CLASS_NAME &) = default; \
CLASS_NAME(CLASS_NAME &&) = default; \
\
CLASS_NAME & operator =(const CLASS_NAME &) = default; \
CLASS_NAME & operator =(CLASS_NAME &) = default;

◆ GENERATE_CMP

#define GENERATE_CMP ( args...)
Value:
GENERATE_EQUAL(,,args) \
GENERATE_SPACESHIP(,auto,,args)

◆ GENERATE_CMP_EXT

#define GENERATE_CMP_EXT ( prefix,
ret,
my_type,
args... )
Value:
GENERATE_EQUAL(prefix, my_type ::, my_type, args) \
GENERATE_SPACESHIP(prefix, ret, my_type ::, my_type, args)

◆ GENERATE_EQUAL

#define GENERATE_EQUAL ( prefix,
qualification,
my_type,
args... )
Value:
GENERATE_ONE_CMP(prefix, bool, qualification, ==, my_type, args)

◆ GENERATE_ONE_CMP

#define GENERATE_ONE_CMP ( PRE,
RET,
QUAL,
COMPARATOR,
MY_TYPE,
... )
Value:
PRE RET QUAL operator COMPARATOR(const MY_TYPE & other) const noexcept { \
__VA_OPT__(const MY_TYPE * me = this;) \
auto fields1 = std::tie( __VA_ARGS__ ); \
__VA_OPT__(me = &other;) \
auto fields2 = std::tie( __VA_ARGS__ ); \
return fields1 COMPARATOR fields2; \
}

◆ GENERATE_SPACESHIP

#define GENERATE_SPACESHIP ( prefix,
ret,
qualification,
my_type,
args... )
Value:
GENERATE_ONE_CMP(prefix, ret, qualification, <=>, my_type, args)

◆ logError

#define logError ( errorInfo...)
Value:
logErrorInfo(lvlError, errorInfo)

◆ logErrorInfo

#define logErrorInfo ( level,
errorInfo... )
Value:
do { \
if ((level) <= nix::verbosity) { \
logger->logEI((level), errorInfo); \
} \
} while (0)

◆ logWarning

#define logWarning ( errorInfo...)
Value:
logErrorInfo(lvlWarn, errorInfo)

◆ MAKE_WRAPPER_CONSTRUCTOR

#define MAKE_WRAPPER_CONSTRUCTOR ( CLASS_NAME)
Value:
FORCE_DEFAULT_CONSTRUCTORS(CLASS_NAME) \
\
CLASS_NAME(auto &&... arg) \
: raw(std::forward<decltype(arg)>(arg)...) \
{ }
Raw raw
Definition lexer.l:316

◆ MakeBinOp

#define MakeBinOp ( name,
s )
Value:
struct name : Expr \
{ \
PosIdx pos; \
Expr * e1, * e2; \
name(Expr * e1, Expr * e2) : e1(e1), e2(e2) { }; \
name(const PosIdx & pos, Expr * e1, Expr * e2) : pos(pos), e1(e1), e2(e2) { }; \
void show(const SymbolTable & symbols, std::ostream & str) const override \
{ \
str << "("; e1->show(symbols, str); str << " " s " "; e2->show(symbols, str); str << ")"; \
} \
void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override \
{ \
e1->bindVars(es, env); e2->bindVars(es, env); \
} \
void eval(EvalState & state, Env & env, Value & v) override; \
PosIdx getPos() const override { return pos; } \
};
Definition pos-idx.hh:9
friend class EvalState
Definition lexer.l:5728
friend class SymbolTable
Definition lexer.l:947
return s
Definition lexer.l:459
const std::string_view & name
Definition lexer.l:1709
Definition nixexpr.hh:81

◆ MakeError

#define MakeError ( newClass,
superClass )
Value:
class newClass : public superClass \
{ \
public: \
using superClass::superClass; \
}

◆ notice

#define notice ( args...)
Value:
printMsg(lvlNotice, args)

◆ OS_STR

#define OS_STR ( s)
Value:

◆ POP_STATE

#define POP_STATE ( )
Value:
yy_pop_state(yyscanner)

◆ printError

#define printError ( args...)
Value:
printMsg(lvlError, args)

◆ printInfo

#define printInfo ( args...)
Value:
printMsg(lvlInfo, args)

◆ printMsg

#define printMsg ( level,
args... )
Value:
printMsgUsing(logger, level, args)

◆ printMsgUsing

#define printMsgUsing ( loggerParam,
level,
args... )
Value:
do { \
auto __lvl = level; \
if (__lvl <= nix::verbosity) { \
loggerParam->log(__lvl, fmt(args)); \
} \
} while (0)
std::string fmt(const std::string &s)
Definition fmt.hh:67

◆ printTalkative

#define printTalkative ( args...)
Value:
printMsg(lvlTalkative, args)

◆ PUSH_STATE

#define PUSH_STATE ( state)
Value:
yy_push_state(state, yyscanner)

◆ S_ISLNK

#define S_ISLNK ( m)
Value:
false

◆ unreachable

#define unreachable ( )
Value:
(::nix::panic(__FILE__, __LINE__, __func__))

◆ vomit

#define vomit ( args...)
Value:
printMsg(lvlVomit, args)

◆ warnOnce

#define warnOnce ( haveWarned,
args... )
Value:
if (!haveWarned) { \
haveWarned = true; \
warn(args); \
}

Typedef Documentation

◆ Built

Derivation output.

Encoded in the form !<output>!<drvPath>.

◆ FileEvalCache

typedef std::unordered_map<SourcePath, Value, std::hash<SourcePath>, std::equal_to<SourcePath>, traceable_allocator<std::pair<const SourcePath, Value> > > FileEvalCache

A cache from path names to values.

◆ FileParseCache

typedef std::unordered_map<SourcePath, Expr *, std::hash<SourcePath>, std::equal_to<SourcePath>, traceable_allocator<std::pair<const SourcePath, Expr *> > > FileParseCache

A cache from path names to parse trees.

◆ Inner

using Inner = T

Numeric value enforcing checked arithmetic. Performing mathematical operations on such values will return a Result type which needs to be checked.

◆ lambda_t

typedef std::function< size_t(char *, size_t)> lambda_t

Convert a function into a sink.

Convert a function into a source.

◆ LookupPathHook

using LookupPathHook = std::optional<SourcePath>(EvalState & state, std::string_view)

Function used to interpet look path entries of a given scheme.

The argument is the non-scheme part of the lookup path entry (see LookupPathHooks below).

The return value is (a) whether the entry was valid, and, if so, what does it map to.

◆ LookupPathHooks

using LookupPathHooks = std::map<std::string, std::function<LookupPathHook>>

Map from "scheme" to a LookupPathHook.

Given a lookup path value (i.e. either the whole thing, or after the <key>=) in the form of:

<

if <scheme> is a key in this map, then <arbitrary string> is passed to the hook that is the value in this map.

◆ Opaque

Plain opaque path to some store object.

Encoded as just the path: <path>.

◆ Raw

typedef std::variant< Opaque, DrvDeep, Built > Raw = std::variant<T, Suggestions>

Either a value of type T, or some suggestions

◆ size_t

typedef uint32_t size_t

Bindings contains all the attributes of an attribute set. It is defined by its size and its capacity, the capacity being the number of Attr elements allocated after this structure, while the size corresponds to the number of elements already inserted in this structure.

◆ string_view

std::string_view string_view = OsStringView

Named because it is similar to the Rust type, except it is in the native encoding not WTF-8.

Same as std::filesystem::path::string_type, but manually defined for the same reason as OsChar. std::string_view counterpart for OsString. Create string literals with the native character width of paths Paths are just std::filesystem::paths.

Todo
drop NG suffix and replace the ones in types.hh.

Stop gap until std::filesystem::path_view from P1030R6 exists in a future C++ standard.

Todo
drop NG suffix and replace the one in types.hh.

Enumeration Type Documentation

◆ Type

enum Type
Enumerator
tChar 

Any other node types that may be encountered on the file system, such as device nodes, sockets, named pipe, and possibly even more exotic things.

Responsible for "unknown" from builtins.readFileType "/dev/null".

Unlike DT_UNKNOWN, this must not be used for deferring the lookup of types.

Function Documentation

◆ absOrEmpty()

const std::string & absOrEmpty ( ) const

Like abs(), but return an empty string if this path is '/'. Thus the returned string never ends in a slash.

◆ addCallDepth()

CallDepth addCallDepth ( const PosIdx pos)
inline

Check that the call depth is within limits, and increment it, until the returned object is destroyed.

◆ addChunk()

auto & addChunk ( )

Keep this out of the add hot path

◆ allocValue()

Value * allocValue ( )
inline

Allocation primitives.

◆ allowAndSetStorePathString()

void allowAndSetStorePathString ( const StorePath & storePath,
Value & v )

Allow access to a store path and return it as a string.

◆ allowClosure()

void allowClosure ( const StorePath & storePath)

Allow access to the closure of a store path.

◆ allowPath() [1/2]

void allowPath ( const Path & path)

Allow access to a path.

◆ allowPath() [2/2]

void allowPath ( const StorePath & storePath)

Allow access to a store path. Note that this gets remapped to the real store path if store is a chroot store.

◆ appendOrSet()

virtual void appendOrSet ( T newValue,
bool append )
virtual

Append or overwrite value with newValue.

Some types to do not support appending in which case append should never be passed. The default handles this case.

Parameters
appendWhether to append or overwrite.

◆ applyConfig()

void applyConfig ( const std::string & contents,
const std::string & path = "<unknown>" )

Parses the configuration in contents and applies it

  • contents: configuration contents to be parsed and applied
  • path: location of the configuration file

◆ assertEqValues()

void assertEqValues ( Value & v1,
Value & v2,
const PosIdx pos,
std::string_view errorCtx )

Like eqValues, but throws an AssertionError if not equal.

WARNING: Callers should call eqValues first and report if assertEqValues behaves incorrectly. (e.g. if it doesn't throw if eqValues returns false or vice versa)

◆ autoCallFunction()

void autoCallFunction ( const Bindings & args,
Value & fun,
Value & res )

Automatically call a function for which each argument has a default value or has a binding in the args map.

◆ BackedStringView()

BackedStringView ( BackedStringView && other)
default

We only want move operations defined since the sole purpose of this type is to avoid copies.

◆ base16Len()

size_t base16Len ( ) const
nodiscard

Returns the length of a base-16 representation of this hash.

◆ base32Len()

size_t base32Len ( ) const
nodiscard

Returns the length of a base-32 representation of this hash.

◆ base64Len()

size_t base64Len ( ) const
nodiscard

Returns the length of a base-64 representation of this hash.

◆ calcWhat()

const std::string & calcWhat ( ) const

Format err.msg and set what_ to the resulting value.

◆ canDebug()

bool canDebug ( )

Whether a debug repl can be started. If false, runDebugRepl(error) will return without starting a repl.

◆ CanonPath() [1/3]

CanonPath ( const std::vector< std::string > & elems)

Construct a canon path from a vector of elements.

◆ CanonPath() [2/3]

Construct a canon path from a non-canonical path. Any '.', '..' or empty components are removed.

◆ CanonPath() [3/3]

CanonPath ( std::string_view raw,
const CanonPath & root )

If raw starts with a slash, return CanonPath(raw). Otherwise return a CanonPath representing root + "/" + raw.

◆ check()

void check ( )

Validity check to be performed by functions that introduce primops, such as RegisterPrimOp() and Value::mkPrimOp().

◆ coerceToPath()

SourcePath coerceToPath ( const PosIdx pos,
Value & v,
NixStringContext & context,
std::string_view errorCtx )

Path coercion.

Converts strings, paths and derivations to a path. The result is guaranteed to be a canonicalised, absolute path. Nothing is copied to the store.

◆ coerceToSingleDerivedPath()

SingleDerivedPath coerceToSingleDerivedPath ( const PosIdx pos,
Value & v,
std::string_view errorCtx )

Coerce to SingleDerivedPath.

Must be a string which is either a literal store path or a "placeholder (see DownstreamPlaceholder).

Even more importantly, the string context must be exactly one element, which is either a NixStringContextElem::Opaque or NixStringContextElem::Built. (NixStringContextEleme::DrvDeep is not permitted).

The string is parsed based on the context — the context is the source of truth, and ultimately tells us what we want, and then we ensure the string corresponds to it.

◆ coerceToSingleDerivedPathUnchecked()

std::pair< SingleDerivedPath, std::string_view > coerceToSingleDerivedPathUnchecked ( const PosIdx pos,
Value & v,
std::string_view errorCtx )

Part of coerceToSingleDerivedPath() without any store IO which is exposed for unit testing only.

◆ coerceToStorePath()

StorePath coerceToStorePath ( const PosIdx pos,
Value & v,
NixStringContext & context,
std::string_view errorCtx )

Like coerceToPath, but the result must be a store path.

◆ coerceToString()

BackedStringView coerceToString ( const PosIdx pos,
Value & v,
NixStringContext & context,
std::string_view errorCtx,
bool coerceMore = false,
bool copyToStore = true,
bool canonicalizePath = true )

String coercion.

Converts strings, paths and derivations to a string. If coerceMore is set, also converts nulls, integers, booleans and lists to a string. If copyToStore is set, referenced paths are copied to the Nix store as a side effect.

◆ convertToArgs()

void convertToArgs ( Args & args,
const std::string & category )
overridepure virtual

Converts settings to Args to be used on the command line interface

  • args: args to write to
  • category: category of the settings

◆ create()

Symbol create ( std::string_view s)

converts a string into a symbol.

◆ createDirs()

return createDirs ( Path(path) )

Flush a path's parent directory to disk. Flush a file or entire directory tree to disk. Delete a path; i.e., in the case of a directory, it is deleted recursively. It's not an error if the path does not exist. The second variant returns the number of bytes and blocks freed. Create a directory and all its parents, if necessary.

In the process of being deprecated for std::filesystem::create_directories.

◆ debugThrow()

void debugThrow ( )

Delete the EvalErrorBuilder and throw the underlying exception.

◆ drainAll()

size_t drainAll ( )

Consume the original source until no remain data is left to consume.

◆ dumpPath()

void dumpPath ( Sink & sink,
PathFilter & filter = defaultPathFilter ) const

Dump this SourcePath to sink as a NAR archive.

◆ eqValues()

bool eqValues ( Value & v1,
Value & v2,
const PosIdx pos,
std::string_view errorCtx )

Do a deep equality test between two values. That is, list elements and attributes are compared recursively.

◆ eval()

void eval ( Expr * e,
Value & v )

Evaluate an expression to normal form

Parameters
[out]vThe resulting is stored here.

◆ evalBool()

bool evalBool ( Env & env,
Expr * e )
inline

Evaluation the expression, then verify that it has the expected type.

◆ evalExceptFinalSelect()

Symbol evalExceptFinalSelect ( EvalState & state,
Env & env,
Value & attrs )

Evaluate the a.b.c part of a.b.c.d. This exists mostly for the purpose of :doc in the repl.

Parameters
[out]attrsThe attribute set that should contain the last attribute name (if it exists).
Returns
The last attribute name in attrPath
Note
This does not evaluate the final attribute, and does not fail if that's the only attribute that does not exist.

◆ evalFile()

void evalFile ( const SourcePath & path,
Value & v,
bool mustBeTrivial = false )

Evaluate an expression read from the given file to normal form. Optionally enforce that the top-level expression is trivial (i.e. doesn't require arbitrary computation).

◆ exceptions()

fmt exceptions ( boost::io::all_error_bits ^ boost::io::too_many_args_bit ^ boost::io::too_few_args_bit )

Set the correct exceptions for fmt.

◆ ExprInheritFrom()

ExprInheritFrom ( PosIdx pos,
Displacement displ )

A pseudo-expression for the purpose of evaluating the from expression in inherit (from) syntax. Unlike normal variable references, the displacement is set during parsing, and always refers to ExprAttrs::inheritFromExprs (by itself or in ExprLet), whose values are put into their own Env.

◆ extend()

void extend ( const CanonPath & x)

Append another path to this one.

◆ f()

boost::format f ( fs )

suppress msgs > this Print a message with the standard ErrorInfo format. In general, use these 'log' macros for reporting problems that may require user intervention or that need more explanation. Use the 'print' macros for more lightweight status messages. Print a string message if the current log level is at least the specified level. Note that this has to be implemented as a macro to ensure that the arguments are evaluated lazily. if verbosity >= lvlWarn, print a message with a yellow 'warning:' prefix.

◆ findFile()

SourcePath findFile ( const std::string_view path)

Look up a file in the search path.

◆ finish()

Bindings * finish ( )
overridepure virtual

Helper that defaults empty hashes to the 0 hash. Print a hash in base-16 if it's MD5, or base-32 otherwise. Compute the hash of the given string. Compute the hash of the given file, hashing its contents directly.

(Metadata, such as the executable permission bit, is ignored.) The final hash and the number of bytes digested.

Todo
Convert to proper struct

Compress a hash to the specified number of bytes by cyclically XORing bytes together. Parse a string representing a hash format. std::optional version of parseHashFormat that doesn't throw error. The reverse of parseHashFormat. Parse a string representing a hash algorithm. Will return nothing on parse error And the reverse.

◆ forceFunction()

void forceFunction ( Value & v,
const PosIdx pos,
std::string_view errorCtx )
Parameters
veither lambda or primop

◆ forceInt()

NixInt forceInt ( Value & v,
const PosIdx pos,
std::string_view errorCtx )

Force v, and then verify that it has the expected type.

◆ forceValue()

void forceValue ( Value & v,
const PosIdx pos )
inline

If v is a thunk, enter it and overwrite v with the result of the evaluation of the thunk. If v is a delayed function application, call the function and overwrite v with the result. Otherwise, this is a no-op.

◆ forceValueDeep()

void forceValueDeep ( Value & v)

Force a value, then recursively force list elements and attributes.

◆ formatHelper()

formatHelper ( f % x,
args...  )

A helper for writing boost::format expressions.

These are equivalent:

formatHelper(formatter, a_0, ..., a_n)
f

With a single argument, formatHelper(s) is a no-op.

◆ fsync()

void fsync ( ) const

Perform a blocking fsync operation.

◆ fullGC()

bool fullGC ( )

Perform a full memory garbage collection - not incremental.

Returns
true if Nix was built with GC and a GC was performed, false if not. The return value is currently not thread safe - just the return value.

◆ getBool()

Value * getBool ( bool b)

Return a boolean Value * without allocating.

◆ getBuiltin()

Value & getBuiltin ( const std::string & name)

Retrieve a specific builtin, equivalent to evaluating builtins.${name}.

Parameters
nameThe attribute name of the builtin to retrieve.
Exceptions
EvalErrorif the builtin does not exist.

◆ getBuiltins()

Value & getBuiltins ( )

Retrieve the builtins attrset, equivalent to evaluating the reference builtins. Always returns an attribute set value.

◆ getCurrentSystem()

const std::string & getCurrentSystem ( ) const

Implements the eval-system vs system defaulting logic described for eval-system.

◆ getDoc()

std::optional< Doc > getDoc ( Value & v)

Retrieve the documentation for a value. This will evaluate the value if it is a thunk, and it will partially apply __functor if applicable.

Parameters
vThe value to get the documentation for.

◆ getLastModified()

virtual std::optional< time_t > getLastModified ( )
virtual

Return the maximum last-modified time of the files in this tree, if available.

◆ getPhysicalPath() [1/2]

std::optional< std::filesystem::path > getPhysicalPath ( ) const

Return the location of this path in the "real" filesystem, if it has a physical location.

◆ getPhysicalPath() [2/2]

virtual std::optional< std::filesystem::path > getPhysicalPath ( const CanonPath & path)
virtual

Return a corresponding path in the root filesystem, if possible. This is only possible for filesystems that are materialized in the root filesystem.

◆ getSettings()

void getSettings ( std::map< std::string, SettingInfo > & res,
bool overriddenOnly = false )
overridepure virtual

Adds the currently known settings to the given result map res.

  • res: map to store settings in
  • overriddenOnly: when set to true only overridden settings will be added to res

◆ getSource()

std::optional< std::string > getSource ( ) const

Return the contents of the source file.

◆ getSourcePath()

std::optional< SourcePath > getSourcePath ( ) const

Get the SourcePath, if the source was loaded from a file.

◆ hasData()

bool hasData ( )

Return true if the buffer is not empty.

Return true if the buffer is not empty after a non-blocking read.

◆ Hash() [1/2]

Hash ( HashAlgorithm algo)
explicit

Create a zero-filled hash object.

◆ Hash() [2/2]

Hash ( std::string_view s,
HashAlgorithm algo,
bool isSRI )

The type must be provided, the string view must not include <type> prefix. isSRI helps disambigate the various base-* encodings.

◆ if()

if ( c. empty())

Remove and return the first item from a container.

◆ insert()

c insert ( c. end(),
l. begin(),
l. end() )

Append items to a container. TODO: remove this once we can use C++23's append_range().

◆ isAllowed()

bool isAllowed ( const std::set< CanonPath > & allowed) const

Check whether access to this path is allowed, which is the case if 1) this is within any of the allowed paths; or 2) any of the allowed paths are within this. (The latter condition ensures access to the parents of allowed paths.)

◆ isAppendable()

bool isAppendable ( )
finaloverridepure virtual

Whether the type is appendable; i.e. whether the append parameter to set() is allowed to be true.

Always defined based on the C++ magic with trait above.

◆ isDerivation()

bool isDerivation ( Value & v)
Returns
true iff the value v denotes a derivation (i.e. a set with attribute type = "derivation").

◆ isEnabled() [1/2]

bool isEnabled ( const ExperimentalFeature & ) const

Check whether the given experimental feature is enabled.

◆ isEnabled() [2/2]

bool isEnabled ( const std::optional< ExperimentalFeature > & ) const

std::nullopt pointer means no feature, which means there is nothing that could be disabled, and so the function returns true in that case.

◆ isTrivial()

bool isTrivial ( ) const

Check whether forcing this value requires a trivial amount of computation. In particular, function applications are non-trivial.

◆ isWithin()

bool isWithin ( const CanonPath & parent) const

Return true if this is equal to parent or a child of parent.

◆ lexicographicOrder()

std::vector< const Attr * > lexicographicOrder ( const SymbolTable & symbols) const

Returns the attributes in lexicographically sorted order.

◆ lock()

WriteLock lock ( )

Acquire write (exclusive) access to the inner value.

◆ lstat()

SourceAccessor::Stat lstat ( ) const

Return stats about this SourcePath, or throw an exception if it doesn't exist.

◆ Magenta()

Magenta ( const T & s)

Values wrapped in this struct are printed in magenta.

By default, arguments to HintFmt are printed in magenta. To avoid this, either wrap the argument in Uncolored or add a specialization of HintFmt::operator%.

◆ makeRelative()

std::string makeRelative ( const CanonPath & path) const

Return a representation x of path relative to this, i.e. CanonPath(this.makeRelative(x), this) == path.

◆ maybeLstat()

std::optional< SourceAccessor::Stat > maybeLstat ( ) const

Return stats about this SourcePath, or std::nullopt if it doesn't exist.

◆ maybePrintStats()

void maybePrintStats ( )

Print statistics, if enabled.

Performs a full memory GC before printing the statistics, so that the GC statistics are more accurate.

◆ message()

std::string message ( )

The error message without "error: " prefixed to it.

◆ mkOutputString()

void mkOutputString ( Value & value,
const SingleDerivedPath::Built & b,
std::optional< StorePath > optStaticOutputPath,
const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings )

Create a string representing a SingleDerivedPath::Built.

The string is the printed store path with a context containing a single NixStringContextElem::Built element of the drv path and output name.

Parameters
valueValue we are settings
bthe drv whose output we are making a string for, and the output
optStaticOutputPathOptional output path for that string. Must be passed if and only if output store object is input-addressed or fixed output. Will be printed to form string if passed, otherwise a placeholder will be used (see DownstreamPlaceholder).
xpSettingsStop-gap to avoid globals during unit tests.

◆ mkOutputStringRaw()

std::string mkOutputStringRaw ( const SingleDerivedPath::Built & b,
std::optional< StorePath > optStaticOutputPath,
const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings )

Like mkOutputString but just creates a raw string, not an string Value, which would also have a string context.

◆ mkSingleDerivedPathString()

void mkSingleDerivedPathString ( const SingleDerivedPath & p,
Value & v )

Create a string representing a SingleDerivedPath.

A combination of mkStorePathString and mkOutputString.

◆ mkSingleDerivedPathStringRaw()

std::string mkSingleDerivedPathStringRaw ( const SingleDerivedPath & p)

Like mkSingleDerivedPathStringRaw but just creates a raw string Value, which would also have a string context.

◆ mkStorePathString()

void mkStorePathString ( const StorePath & storePath,
Value & v )

Create a string representing a store path.

The string is the printed store path with a context containing a single NixStringContextElem::Opaque element of that store path.

◆ nop()

nop ( T... )

A variadic template that does nothing.

Useful to call a function with each argument in a parameter pack.

◆ OnStartup()

OnStartup ( T && t)

Paths are just strings. Helper class to run code at startup.

◆ operator bool()

operator bool ( ) const
explicitnoexcept

Whether the comment is set.

A DocComment is small enough that it makes sense to pass by value, and therefore baking optionality into it is also useful, to avoiding the memory overhead of std::optional.

◆ operator()() [1/2]

void operator() ( char * data,
size_t len )

Store exactly ‘len’ bytes in the buffer pointed to by ‘data’. It blocks until all the requested data is available, or throws an error if it is not going to be available.

◆ operator()() [2/2]

void operator() ( std::string_view data)
overridepure virtual

Just throws away data.

◆ operator/() [1/3]

SourcePath operator/ ( const CanonPath & x) const

Concatenate two paths.

Append a CanonPath to this path.

◆ operator/() [2/3]

SourcePath operator/ ( std::string_view c) const

Append a single component c to this path. c must not contain a slash. A slash is implicitly added between this path and c.

◆ operator/() [3/3]

Result operator/ ( T const other) const

Performs a checked division.

If the right hand side is zero, the result is marked as a DivByZero and valueWrapping will throw.

◆ operator<<()

friend std::ostream & operator<< ( std::ostream & output,
const ValuePrinter & printer )

Print true or false. Print a string as an attribute name in the Nix expression language syntax.

Prints a quoted string if necessary. Returns ‘true’ is a string is a reserved keyword which requires quotation when printing attribute set field names. Print a string as an identifier in the Nix expression language syntax.

FIXME: "identifier" is ambiguous. Identifiers do not have a single textual representation. They can be used in variable references, let bindings, left-hand sides or attribute names in a select expression, or something else entirely, like JSON. Use one of the print* functions instead. A partially-applied form of printValue which can be formatted using << without allocating an intermediate string.

◆ operator<=>() [1/2]

auto operator<=> ( const CanonPath & x) const

Compare paths lexicographically except that path separators are sorted before any other character. That is, in the sorted order a directory is always followed directly by its children. For instance, 'foo' < 'foo/bar' < 'foo!'.

◆ operator<=>() [2/2]

std::strong_ordering operator<=> ( const Hash & h2) const
noexcept

Compare how two hashes are ordered.

◆ operator==()

bool operator== ( const Hash & h2) const
noexcept

Check whether two hashes are equal.

◆ OptionalPathSetting()

OptionalPathSetting ( Config * options,
const std::optional< Path > & def,
const std::string & name,
const std::string & description,
const std::set< std::string > & aliases = {} )

Like PathSetting, but the absence of a path is also allowed.

std::optional is used instead of the empty string for clarity.

◆ panic()

void panic ( )

A programming error or fatal condition occurred. Abort the process for core dump and debugging. This does not print a proper backtrace, because unwinding the stack is destructive.

◆ parent()

SourcePath parent ( ) const

Construct the parent of this SourcePath. Aborts if this denotes the root.

◆ parse()

std::optional< Path > parse ( const std::string & str) const
overridevirtual

Parse the string into a T.

Used by set().

◆ parseExprFromFile()

Expr * parseExprFromFile ( const SourcePath & path)

Parse a Nix expression from the specified file.

◆ parseExprFromString()

Expr * parseExprFromString ( std::string s,
const SourcePath & basePath,
std::shared_ptr< StaticEnv > & staticEnv )

Parse a Nix expression from the specified string.

◆ pathExists()

bool pathExists ( ) const

Return whether this SourcePath denotes a file (of any type) that exists

◆ PathSetting()

PathSetting ( Config * options,
const Path & def,
const std::string & name,
const std::string & description,
const std::set< std::string > & aliases = {} )

A special setting for Paths. These are automatically canonicalised (e.g. "/foo//bar/" becomes "/foo/bar").

It is mandatory to specify a path; i.e. the empty string is not permitted.

◆ pop()

c pop ( )

Remove the last component. Panics if this path is the root.

◆ printLiteralString()

return printLiteralString ( o ,
std::string_view(s)  )

Print a string as a Nix string literal.

Quotes and fairly minimal escaping are added.

Parameters
oThe output stream to print to
sThe logical string

◆ printStatistics()

void printStatistics ( )

Print statistics, unconditionally, cheaply, without performing a GC first.

◆ push()

void push ( std::string_view c)

Add a path component to this one. It must not contain any slashes.

◆ read()

virtual size_t read ( char * data,
size_t len )
pure virtual

Store up to ‘len’ in the buffer pointed to by ‘data’, and return the number of bytes stored. It blocks until at least one byte is available.

◆ readDirectory() [1/2]

SourceAccessor::DirEntries readDirectory ( ) const

If this SourcePath denotes a directory (not a symlink), return its directory entries; otherwise throw an error.

◆ readDirectory() [2/2]

virtual DirEntries readDirectory ( const CanonPath & path)
pure virtual
Note
Like readFile, this method should not follow symlinks.

◆ readFile() [1/3]

std::string readFile ( ) const

If this SourcePath denotes a regular file (not a symlink), return its contents; otherwise throw an error.

◆ readFile() [2/3]

virtual std::string readFile ( const CanonPath & path)
virtual

Return the contents of a file as a string.

Note
Unlike Unix, this method should not follow symlinks. Nix by default wants to manipulate symlinks explicitly, and not implictly follow them, as they are frequently untrusted user data and thus may point to arbitrary locations. Acting on the targets targets of symlinks should only occasionally be done, and only with care.

◆ readFile() [3/3]

virtual void readFile ( const CanonPath & path,
Sink & sink,
std::function< void(uint64_t)> sizeCallback = [](uint64_t size){} )
virtual

Write the contents of a file as a sink. sizeCallback must be called with the size of the file before any data is written to the sink.

Note
Like the other readFile, this method should not follow symlinks.
subclasses of SourceAccessor need to implement at least one of the readFile() variants.

◆ readLink()

std::string readLink ( ) const

If this SourcePath denotes a symlink, return its target; otherwise throw an error.

◆ readLock()

ReadLock readLock ( ) const

Acquire read access to the inner value. When using std::shared_mutex, this will use a shared lock.

◆ readUnbuffered()

size_t readUnbuffered ( char * data,
size_t len )
overridepure virtual

Underlying read call, to be overridden.

◆ realiseContext()

StringMap realiseContext ( const NixStringContext & context,
StorePathSet * maybePaths = nullptr,
bool isIFD = true )
nodiscard

Realise the given context

Parameters
[in]contextthe context to realise
[out]maybePathsif not nullptr, all built or referenced store paths will be added to this set
Returns
a mapping from the placeholders used to construct the associated value to their final store path.

◆ realiseString()

std::string realiseString ( Value & str,
StorePathSet * storePathsOutMaybe,
bool isIFD = true,
const PosIdx pos = noPos )

Realise the given string with context, and return the string with outputs instead of downstream output placeholders.

Parameters
[in]strthe string to realise
[out]pathsall referenced store paths will be added to this set
Returns
the realised string
Exceptions
EvalErrorif the value is not a string, path or derivation (see coerceToString)

◆ reapplyUnknownSettings()

void reapplyUnknownSettings ( )

Re-applies all previously attempted changes to unknown settings

◆ replaceSymlink()

return replaceSymlink ( std::filesystem::path{target} ,
std::filesystem::path{link}  )

Convenience wrapper that takes all arguments from the struct stat. Create a symlink. Atomically create or replace a symlink.

◆ require() [1/2]

void require ( const ExperimentalFeature & ) const

Require an experimental feature be enabled, throwing an error if it is not.

◆ require() [2/2]

void require ( const std::optional< ExperimentalFeature > & ) const

std::nullopt pointer means no feature, which means there is nothing that could be disabled, and so the function does nothing in that case.

◆ resetOverridden()

void resetOverridden ( )
overridepure virtual

Resets the overridden flag of all Settings

◆ resolveLookupPathPath()

std::optional< SourcePath > resolveLookupPathPath ( const LookupPath::Path & elem,
bool initAccessControl = false )

Try to resolve a search path value (not the optional key part).

If the specified search path element is a URI, download it.

If it is not found, return std::nullopt.

◆ resolveSymlinks() [1/2]

CanonPath resolveSymlinks ( const CanonPath & path,
SymlinkResolution mode = SymlinkResolution::Full )

Resolve any symlinks in path according to the given resolution mode.

Parameters
modemight only be a temporary solution for this. See the discussion in https://github.com/NixOS/nix/pull/9985.

◆ resolveSymlinks() [2/2]

SourcePath resolveSymlinks ( SymlinkResolution mode = SymlinkResolution::Full) const

Convenience wrapper around SourceAccessor::resolveSymlinks().

◆ rootPath() [1/2]

SourcePath rootPath ( CanonPath path)

Return a SourcePath that refers to path in the root filesystem.

◆ rootPath() [2/2]

SourcePath rootPath ( PathView path)

Variant which accepts relative paths too.

◆ runDebugRepl() [1/2]

void runDebugRepl ( const Error * error)

Use front of debugTraces; see runDebugRepl(error,env,expr)

◆ runDebugRepl() [2/2]

void runDebugRepl ( const Error * error,
const Env & env,
const Expr & expr )

Run a debug repl with the given error, environment and expression.

Parameters
errorThe error to debug, may be nullptr.
envThe environment to debug, matching the expression.
exprThe expression to debug, matching the environment.

◆ set() [1/2]

bool set ( const std::string & name,
const std::string & value )
overridepure virtual

Sets the value referenced by name to value. Returns true if the setting is known, false otherwise.

◆ set() [2/2]

void set ( const std::string & str,
bool append = false )
finaloverridepure virtual

Require any experimental feature the setting depends on

Uses parse() to get the value from str, and appendOrSet() to set it.

◆ shouldPrettyPrint()

bool shouldPrettyPrint ( )
inline

True if pretty-printing is enabled.

◆ startFsync()

void startFsync ( ) const

Asynchronously flush to disk without blocking, if available on the platform. This is just a performance optimization, and fsync must be run later even if this is called.

◆ suffixIfPotentialMatch()

std::optional< std::string_view > suffixIfPotentialMatch ( std::string_view path) const

If the path possibly matches this search path element, return the suffix that we should look for inside the resolved value of the element Note the double optionality in the name. While we might have a matching prefix, the suffix may not exist.

◆ SysError() [1/2]

SysError ( const Args &... args)

Construct using the ambient errno.

Be sure to not perform another errno-modifying operation before calling this constructor!

◆ SysError() [2/2]

SysError ( int errNo,
const Args &... args )

Construct using the explicitly-provided error number. strerror will be used to try to add additional information to the message.

◆ to_string()

std::string to_string ( HashFormat hashFormat,
bool includeAlgo ) const
nodiscard

Return a string representation of the hash, in base-16, base-32 or base-64. By default, this is prefixed by the hash algo (e.g. "sha256:").

◆ toJSON()

nlohmann::json toJSON ( )
overridepure virtual

Outputs all settings to JSON

  • out: JSONObject to write the configuration to

◆ toKeyValue()

std::string toKeyValue ( )
overridepure virtual

Outputs all settings in a key-value pair format suitable to be used as nix.conf

◆ toRealPath()

Path toRealPath ( const Path & path,
const NixStringContext & context )

When using a diverted store and 'path' is in the Nix store, map 'path' to the diverted location (e.g. /nix/store/foo is mapped to /home/alice/my-nix/nix/store/foo). However, this is only done if the context is not empty, since otherwise we're probably trying to read from the actual /nix/store. This is intended to distinguish between import-from-derivation and sources stored in the actual /nix/store.

◆ warnUnknownSettings()

void warnUnknownSettings ( )

Logs a warning for each unregistered setting

◆ writeFile()

return writeFile ( path. string(),
s ,
mode ,
sync  )

Canonicalize a path except for the last component.

This is useful for getting the canonical location of a symlink.

Consider the case where foo/l is a symlink. canonical("foo/l") will resolve the symlink l to its target. makeParentCanonical("foo/l") will not resolve the symlink l to its target, but does ensure that the returned parent part of the path, foo is resolved to canonical("foo"), and can therefore be retrieved without traversing any symlinks.

If a relative path is passed, it will be made absolute, so that the parent can always be canonicalized. A version of pathExists that returns false on a permission error. Useful for inferring default paths across directories that might not be readable.

Returns
true iff the given path can be accessed and exists Read the contents (target) of a symbolic link. The result is not in any way canonicalised.

In the process of being deprecated for std::filesystem::read_symlink. Open a Descriptor with read-only access to the given directory. Read the contents of a file into a string. Write a string to a file.

◆ yylex()

int yylex ( YYSTYPE * yylval_param,
YYLTYPE * yylloc_param,
yyscan_t yyscanner )

[^/*] reject /*

◆ ~Sink()

virtual ~Sink ( )
virtual

Close all file descriptors except stdio fds (ie 0, 1, 2). Good practice in child processes. Set the close-on-exec flag for the given file descriptor. Abstract destination of binary data.

◆ ~Source()

virtual ~Source ( )
virtual

Abstract source of binary data.

Variable Documentation

◆ _path

Similar to 'renameFile', but fallback to a copy+remove if src and dst are on a different filesystem.

Beware that this might not be atomic because of the copy that happens behind the scenes Recursively copy the content of oldPath to newPath. If andDelete is true, then also remove oldPath (making this equivalent to moveFile, but with the guaranty that the destination will be “fresh”, with no stale inode or file descriptor pointing to it). Automatic cleanup of resources.

◆ acceptable

Consider removing the empty string dropping behavior If acceptable

String tokenizer.

See also basicSplitString(), which preserves empty strings between separators, as well as at the start and end. Like basicTokenizeString but specialized to the default char Split a string, preserving empty strings between separators, as well as at the start and end.

Returns a non-empty collection of strings. Concatenate the given strings with a separator between the elements. Ignore any empty strings at the start of the list, and then concatenate the given strings with a separator between the elements.

Deprecated
This function exists for historical reasons. You probably just want to use concatStringsSep.

◆ accessor

ref< SourceAccessor > accessor

An abstraction for accessing source files during evaluation. Currently, it's just a wrapper around CanonPath that accesses files in the regular filesystem, but in the future it will support fetching files in other ways.

◆ act

const Activity & act
Parameters
sourceA noun phrase describing the source of the message, e.g. "the builder".
sourceA noun phrase describing the source of the message, e.g. "the builder".
sourceA noun phrase describing the source of the message, e.g. "the builder".

◆ addTrace

bool addTrace = true

Add a trace item, while calling the <name> builtin.

This is used to remove the redundant item for builtins.addErrorContext.

◆ allowedUris

Setting<Strings> allowedUris
Initial value:
{this, {}, "allowed-uris",
R"(
A list of URI prefixes to which access is allowed in restricted
evaluation mode. For example, when set to
`https://github.com/NixOS`, builtin functions such as `fetchGit` are
allowed to access `https://github.com/NixOS/patchelf.git`.
Access is granted when
- the URI is equal to the prefix,
- or the URI is a subpath of the prefix,
- or the prefix is a URI scheme ended by a colon `:` and the URI has the same scheme.
)"}

◆ Always

Always

Always printed. Produced by builtins.addErrorContext.

◆ Ancestors

Ancestors

Note there is a decent chance this type soon goes away because the problem is solved another way. See the discussion in https://github.com/NixOS/nix/pull/9985. Resolve symlinks in the ancestors only.

Only the last component of the result is possibly a symlink.

◆ ansiColors

ansiColors = false

Options for printing Nix values. If true, output ANSI color sequences.

PrintOptions for unknown and therefore potentially large values in error messages, to avoid printing "too much" output.

◆ args

std::vector< std::string > args

Names of the parameters of a primop, for primops that take a fixed number of arguments to be substituted for these parameters.

◆ arity

size_t arity = 0

Aritiy of the primop.

If args is not empty, this field will be computed from that field instead, so it doesn't need to be manually set.

◆ Base16

Base16

Lowercase hexadecimal encoding.

See also
base16Chars

◆ Base64

Base64

Enumeration representing the hash formats.

Create a temporary file, returning a file handle and its path. Return TMPDIR, or the default temporary directory if unset or empty. Interpret exe as a location in the ambient file system and return whether it resolves to a file that is executable. Used in various places.

Base 64 encoding.

See also
IETF RFC 4648, section 4.

◆ baseEnv

Env& baseEnv

The base environment, containing the builtin functions and values.

◆ begin

A documentation comment, in the sense of RFC 145

Note that this does not implement the following:

  • argument attribute names ("formals"): TBD
  • argument names: these are internal to the function and their names may not be optimal for documentation
  • function arity (degree of currying or number of ':'s):
    • Functions returning partially applied functions have a higher arity than can be determined locally and without evaluation. We do not want to present false data.
    • Some functions should be thought of as transformations of other functions. For instance overlay -> overlay -> overlay is the simplest way to understand composeExtensions, but its implementation looks like f: g: final: prev: <...>. The parameters final and prev are part of the overlay concept, while distracting from the function's purpose. Start of the comment, including the opening, ie / and **.

◆ bindings

Bindings* bindings

A wrapper around Bindings that ensures that its always in sorted order at the end. The only way to consume a BindingsBuilder is to call finish(), which sorts the bindings.

◆ block

Descriptor Sink bool block
Initial value:
= true
)

◆ bufSize

size_t bufSize

A buffered abstract sink. Warning: a BufferedSink should not be used from multiple threads concurrently.

A buffered abstract source. Warning: a BufferedSource should not be used from multiple threads concurrently.

◆ buildStore

const ref<Store> buildStore

Store used to build stuff.

◆ builtinsAbortOnWarn

Setting<bool> builtinsAbortOnWarn
Initial value:
{this, false, "abort-on-warn",
R"(
If set to true, [`builtins.warn`](@docroot@/language/builtins.md#builtins-warn) will throw an error when logging a warning.
This will give you a stack trace that leads to the location of the warning.
This is useful for finding information about warnings in third-party Nix code when you can not start the interactive debugger, such as when Nix is called from a non-interactive script. See [`debugger-on-warn`](#conf-debugger-on-warn).
Currently, a stack trace can only be produced when the debugger is enabled, or when evaluation is aborted.
This option can be enabled by setting `NIX_ABORT_ON_WARN=1` in the environment.
)"}

◆ builtinsDebuggerOnWarn

Setting<bool> builtinsDebuggerOnWarn
Initial value:
{this, false, "debugger-on-warn",
R"(
If set to true and the `--debugger` flag is given, [`builtins.warn`](@docroot@/language/builtins.md#builtins-warn)
will enter the debugger like [`builtins.break`](@docroot@/language/builtins.md#builtins-break).
This is useful for debugging warnings in third-party Nix code.
Use [`debugger-on-trace`](#conf-debugger-on-trace) to also enter the debugger on legacy warnings that are logged with [`builtins.trace`](@docroot@/language/builtins.md#builtins-trace).
)"}

◆ builtinsTraceDebugger

Setting<bool> builtinsTraceDebugger
Initial value:
{this, false, "debugger-on-trace",
R"(
If set to true and the `--debugger` flag is given, the following functions
will enter the debugger like [`builtins.break`](@docroot@/language/builtins.md#builtins-break).
* [`builtins.trace`](@docroot@/language/builtins.md#builtins-trace)
* [`builtins.traceVerbose`](@docroot@/language/builtins.md#builtins-traceVerbose)
if [`trace-verbose`](#conf-trace-verbose) is set to true.
* [`builtins.warn`](@docroot@/language/builtins.md#builtins-warn)
This is useful for debugging warnings in third-party Nix code.
)"}

◆ CaDerivations

CaDerivations

The list of available experimental features.

If you update this, don’t forget to also change the map defining their string representation and documentation in the corresponding .cc file as well.

◆ callDepth

size_t callDepth = 0

Current Nix call stack depth, used with max-call-depth setting to throw stack overflow hopefully before we run out of system stack.

◆ char

char

Named because it is similar to the Rust type, except it is in the native encoding not WTF-8.

Same as std::filesystem::path::value_type, but manually defined to avoid including a much more complex header.

◆ constantInfos

std::vector<std::pair<std::string, Constant> > constantInfos

Name and documentation about every constant.

Constants from primops are hard to crawl, and their docs will go here too.

◆ Continue

Continue

The user exited with :continue. The program should continue running.

◆ corepkgsFS

const ref<MemorySourceAccessor> corepkgsFS

The in-memory filesystem for <nix/...> paths.

◆ count

size_t& count

Increments a count on construction and decrements on destruction.

◆ counter

T& counter

A RAII helper that increments a counter on construction and decrements it on destruction.

◆ currentSystem

Setting<std::string> currentSystem
Initial value:
{
this, "", "eval-system",
R"(
This option defines
[`builtins.currentSystem`](@docroot@/language/builtins.md#builtins-currentSystem)
in the Nix language if it is set as a non-empty string.
Otherwise, if it is defined as the empty string (the default), the value of the
[`system` ](#conf-system)
configuration setting is used instead.
Unlike `system`, this setting does not change what kind of derivations can be built locally.
This is useful for evaluating Nix code on one system to produce derivations to be built on another type of system.
)"}

◆ data

T data

This wants to be a little bit like rust's Cow type. Some parts of the evaluator benefit greatly from being able to reuse existing allocations for strings, but have to be able to also use newly allocated storage for values.

We do not define implicit conversions, even with ref qualifiers, since those can easily become ambiguous to the reader and can degrade into copying behaviour we want to avoid.

◆ debugRepl

ReplExitStatus(* debugRepl) (ref< EvalState > es, const ValMap &extraEnv) ( ref< EvalState > es,
const ValMap & extraEnv )

Debugger

◆ Default

Default

When a stack frame is printed. The default behavior; always printed when --show-trace is set.

◆ derivationPaths

bool derivationPaths = false

If true and force is set, print derivations as «derivation /nix/store/...» instead of as attribute sets.

◆ dir

std::optional< PathView > dir = {}

Polyfill for MinGW

Windows does in fact support symlinks, but the C runtime interfaces predate this.

Todo
get rid of this, and stop using stat when we want lstat too.

Return whether the path denotes an absolute path.

Returns
An absolutized path, resolving paths relative to the specified directory, or the current directory otherwise. The path is also canonicalised.

In the process of being deprecated for std::filesystem::absolute.

◆ distance

int distance

The smaller the better.

A potential suggestion for the cli interface.

◆ doc

const char * doc = nullptr

Optional free-form documentation about the primop.

Optional free-form documentation about the constant.

◆ doc_comment_first_column

int doc_comment_first_column

Latest doc comment position, or 0.

◆ docCommentDistance

int docCommentDistance = std::numeric_limits<int>::max()

Tracks the distance to the last doc comment, in terms of lexer tokens.

The lexer sets this to 0 when reading a doc comment, and increments it for every matched rule; see lexer-helpers.cc. Whitespace and comment rules decrement the distance, so that they result in a net 0 change in distance.

◆ elements

std::list<LookupPath::Elem> elements

The list of search path elements. Each one is checked for a path when looking up. (The actual lookup entry point is in EvalState not in this class.)

◆ else

else
Initial value:
{
attrs->dynamicAttrs.push_back(ExprAttrs::DynamicAttrDef(i->expr, e, pos))
auto i
Definition lexer.l:2745

◆ enableImportFromDerivation

Setting<bool> enableImportFromDerivation
Initial value:
{
this, true, "allow-import-from-derivation",
R"(
By default, Nix allows [Import from Derivation](@docroot@/language/import-from-derivation.md).
With this option set to `false`, Nix will throw an error when evaluating an expression that uses this feature,
even when the required store object is readily available.
This ensures that evaluation will not require any builds to take place,
regardless of the state of the store.
)"}

◆ enableNativeCode

Setting<bool> enableNativeCode
Initial value:
{this, false, "allow-unsafe-native-code-during-evaluation", R"(
Enable built-in functions that allow executing native code.
In particular, this adds:
- `builtins.importNative` *path* *symbol*
Opens dynamic shared object (DSO) at *path*, loads the function with the symbol name *symbol* from it and runs it.
The loaded function must have the following signature:
```cpp
extern "C" typedef void (*ValueInitialiser) (EvalState & state, Value & v);
```
The [Nix C++ API documentation](@docroot@/development/documentation.md#api-documentation) has more details on evaluator internals.
- `builtins.exec` *arguments*
Execute a program, where *arguments* are specified as a list of strings, and parse its output as a Nix expression.
)"}

◆ end

Position right after the final asterisk and / that terminate the comment.

◆ eof

bool eof
Initial value:
= []() {
throw EndOfFile("coroutine has finished");
})

◆ err

ErrorInfo err
mutable

BaseError should generally not be caught, as it has Interrupted as a subclass. Catch Error instead.

◆ errNo

int errNo

To use in catch-blocks. POSIX system error, created using errno, strerror friends.

Throw this, but prefer not to catch this, and catch SystemError instead. This allows implementations to freely switch between this and windows::WinError without breaking catch blocks.

However, it is permissible to catch this and rethrow so long as certain conditions are not met (e.g. to catch only if errNo = EFooBar). In that case, try to also catch the equivalent windows::WinError code.

Todo
Rename this to PosixError or similar. At this point Windows support is too WIP to justify the code churn, but if it is finished then a better identifier becomes moe worth it.

◆ errors

How to handle errors encountered while printing values.

◆ evalCaches

std::map<const Hash, ref<eval_cache::EvalCache> > evalCaches

A cache for evaluation caches, so as to reuse the same root value if possible

◆ experimentalFeature

std::optional< ExperimentalFeature > experimentalFeature

Optional experimental for this to be gated on.

◆ experimentalFeatures

Setting<std::set<ExperimentalFeature> > experimentalFeatures
Initial value:
{
this, {}, "experimental-features",
R"(
Experimental features that are enabled.
Example:
```
experimental-features = nix-command flakes
```
The following experimental features are available:
{{#include experimental-features-shortlist.md}}
Experimental features are [further documented in the manual](@docroot@/development/experimental-features.md).
)"}

◆ fd

Convert a native Descriptor to a POSIX file descriptor

This is a no-op except on Windows.

Convert a POSIX file descriptor to a native Descriptor in read-only mode.

This is a no-op except on Windows.

Read the contents of a resource into a string. Wrappers arount read()/write() that read/write exactly the requested number of bytes. Read a line from a file descriptor.

Parameters
fdThe file descriptor to read from
eofOkIf true, return an unterminated line if EOF is reached. (e.g. the empty string)
Returns
A line of text ending in \n, or a string without \n if eofOk is true and EOF is reached. Write a line to a file descriptor. Read a file descriptor until EOF occurs. The Windows version is always blocking.

Automatic cleanup of resources.

A sink that writes data to a file descriptor.

A source that reads data from a file descriptor.

◆ fingerprint

std::optional<std::string> fingerprint

A string that uniquely represents the contents of this accessor. This is used for caching lookups (see fetchToStore()).

◆ force

bool force = false

If true, force values.

◆ from

Source & from

A source that reads a distinct format of concatenated chunks back into its logical form, in order to guarantee a known state to the original stream, even in the event of errors.

Use with FramedSink, which also allows the logical stream to be terminated in the event of an exception.

◆ Full

Full

Resolve symlinks fully, realpath(3)-style.

No component of the result will be a symlink.

◆ fun

std::function< PrimOpFun > fun

Convert a function that feeds data into a Sink into a Source. The Source executes the function as a coroutine.

Implementation of the primop.

◆ hasher

std::hash<T> hasher

hash_combine() from Boost. Hash several hashable values together into a single hash.

◆ i

auto i = map.find(key)
Returns
true iff s starts with prefix.
true iff s ends in suffix. Convert a string to lower case. Escape a string as a shell word. Exception handling in destructors: print an error message, then ignore the exception.

If you're not in a destructor, you usually want to use ignoreExceptionExceptInterrupt().

This function might also be used in callbacks whose caller may not handle exceptions, but ideally we propagate the exception using an exception_ptr in such cases. See e.g. PackBuilderContext Not destructor-safe. Print an error message, then ignore the exception. If the exception is an Interrupted exception, rethrow it.

This may be used in a few places where Interrupt can't happen, but that's ok. Tree formatting. Encode arbitrary bytes as Base64. Decode arbitrary bytes to Base64. Remove common leading whitespace from the lines in the string 's'. For example, if every line is indented by at least 3 spaces, then we remove 3 spaces from the start of every line. Get the prefix of 's' up to and excluding the next line break (LF optionally preceded by CR), and the remainder following the line break. Get a value for the specified key from an associate container.

Remove and return the first item from a container.

◆ ignoreExceptionsDuringTry

Setting<bool> ignoreExceptionsDuringTry
Initial value:
{this, false, "ignore-try",
R"(
If set to true, ignore exceptions inside 'tryEval' calls when evaluating nix expressions in
debug mode (using the --debugger flag). By default the debugger will pause on all exceptions.
)"}

◆ impureOnly

bool impureOnly = false

Whether the constant is impure, and not available in pure mode.

◆ includePid

bool includePid = true

Create a temporary directory.

◆ int

int

Operating System capability

◆ internal

bool internal = false

If true, this primop is not exposed to the user.

◆ internalFS

const ref<MemorySourceAccessor> internalFS

In-memory filesystem for internal, non-user-callable Nix expressions like call-flake.nix.

◆ internalPrimOps

std::unordered_map<std::string, Value *, std::hash<std::string>, std::equal_to<std::string>, traceable_allocator<std::pair<const std::string, Value *> > > internalPrimOps

Internal primops not exposed to the user.

◆ isFromExpr

bool isFromExpr = false

Some messages are generated directly by expressions; notably builtins.warn, abort, throw. These may be rendered differently, so that users can distinguish them.

◆ istream

std::shared_ptr<std::basic_istream<char> > istream

An adapter that converts a std::basic_istream into a source.

◆ j

ExprAttrs::AttrDefs::iterator j = attrs->attrs.find(symbol)

Precondition: attrPath is used for error messages and should already contain symbol as its last element.

◆ key

const T::key_type& key

Get a value for the specified key from an associate container, or a default value if the key isn't present.

◆ lastDocCommentLoc

ParserLocation lastDocCommentLoc

The location of the last doc comment.

(stashing fields are not used)

◆ length

uint64_t length = 0

A sink that that just counts the number of bytes given to it

◆ line

uint32_t line = 0

A position and an origin for that position (like a source file).

◆ maxAttrs

maxAttrs = std::numeric_limits<size_t>::max()

Maximum number of attributes in attribute sets to print.

Note that this is a limit for the entire print invocation, not for each attribute set encountered.

◆ maxCallDepth

Setting<unsigned int> maxCallDepth
Initial value:
{this, 10000, "max-call-depth",
"The maximum function call depth to allow before erroring."}

◆ maxDepth

maxDepth = std::numeric_limits<size_t>::max()

Maximum depth to evaluate to.

◆ maxListItems

maxListItems = std::numeric_limits<size_t>::max()

Maximum number of list items to print.

Note that this is a limit for the entire print invocation, not for each list encountered.

◆ maxStringLength

maxStringLength = std::numeric_limits<size_t>::max()

Maximum string length to print.

◆ missingFeature

ExperimentalFeature missingFeature

Parse a set of strings to the corresponding set of experimental features, ignoring (but warning for) any unknown feature. An experimental feature was required for some (experimental) operation, but was not enabled. The experimental feature that was required but not enabled.

◆ multiplier

uint64_t multiplier = 1

Parse a string into an integer. Like string2Int(), but support an optional suffix 'K', 'M', 'G' or 'T' denoting a binary unit prefix.

◆ mutex

M mutex

This template class ensures synchronized access to a value of type T. It is used as follows:

struct Data { int x; ... };

Sync<Data> data;

{ auto data_(data.lock()); data_->x = 123; }

Here, "data" is automatically unlocked when "data_" goes out of scope.

◆ name

std::string name

Just because writing ExperimentalFeature::CaDerivations is way too long Parse an experimental feature (enum value) from its name. Experimental feature flag names are hyphenated and do not contain spaces.

Map one attribute name to its value.

Function that implements a primop. Info about a primitive operation, and its implementation Name of the primop. __ prefix is treated specially.

◆ next

Source& next

A wrapper source that counts the number of bytes read from it.

◆ Nix32

Nix32

Nix-specific base-32 encoding.

See also
nix32Chars

◆ number

const size_t number

A read-only filesystem abstraction. This is used by the Nix evaluator and elsewhere for accessing sources in various filesystem-like entities (such as the real filesystem, tarballs or Git repositories).

◆ orig

Source & orig

Adapter class of a Source that saves all data read to a sink.

A reader that consumes the original Source until 'size'.

◆ p

const char * p = std::make_shared<T>(std::forward<Args>(args)...)

A simple non-nullable reference-counted pointer. Actually a wrapper around std::shared_ptr that prevents null constructions.

Conventionally part of the default nix path in impure mode. Note: Various places expect the allocated memory to be zeroed.

Note
Storing a C-style char * and size_t allows us to avoid having to define the special members that using string_view here would implicitly delete.

◆ path

Path path

A canonical representation of a path. It ensures the following:

  • It always starts with a slash.
  • It never ends with a slash, except if the path is "/".
  • A slash is never followed by a slash (i.e. no empty components).
  • There are no components equal to '.' or '..'.

CanonPath are "virtual" Nix paths for abstract file system objects; they are always Unix-style paths, regardless of what OS Nix is running on. The / root doesn't denote the ambient host file system root, but some virtual FS root.

Note
It might be useful to compare openat(some_fd, "foo/bar") on Unix. "foo/bar" is a relative path because an absolute path would "override" the some_fd directory file descriptor and escape to the "system root". Conversely, Nix's abstract file operations never escape the designated virtual file system (i.e. SourceAccessor or ParseSink), so CanonPath does not need an absolute/relative distinction.
The path does not need to correspond to an actually existing path, and the path may or may not have unresolved symlinks.

Create a single directory. Set the access and modification times of the given path, not following symlinks.

Parameters
accessedTimeSpecified in seconds.
modificationTimeSpecified in seconds.
isSymlinkWhether the file in question is a symlink. Used for fallback code where we don't have lutimes or similar. if std::optional is passed, the information will be recomputed if it is needed. Race conditions are possible so be careful!

EvalError is the base class for almost all errors that occur during evaluation.

All instances of EvalError should show a degree of purity that allows them to be cached in pure mode. This means that they should not depend on the configuration or the overall environment.

◆ positionToDocComment

std::unordered_map< PosIdx, DocComment > & positionToDocComment

Maps some positions to a DocComment, where the comment is relevant to the location.

Associate source positions of certain AST nodes with their preceding doc comment, if they have one. Grouped by file.

◆ prettyIndent

size_t prettyIndent = 0

Indentation width for pretty-printing.

If set to 0 (the default), values are not pretty-printed.

◆ prevLineOfCode

lvlVomit std::optional<std::string> prevLineOfCode

The lines of code surrounding an error.

◆ Print

Print

How errors should be handled when printing values. Print the first line of the error in brackets: «error: oh no!»

◆ pureEval

Setting<bool> pureEval
Initial value:
{this, false, "pure-eval",
R"(
Pure evaluation mode ensures that the result of Nix expressions is fully determined by explicitly declared inputs, and not influenced by external state:
- Restrict file system and network access to files specified by cryptographic hash
- Disable impure constants:
- [`builtins.currentSystem`](@docroot@/language/builtins.md#builtins-currentSystem)
- [`builtins.currentTime`](@docroot@/language/builtins.md#builtins-currentTime)
- [`builtins.nixPath`](@docroot@/language/builtins.md#builtins-nixPath)
- [`builtins.storePath`](@docroot@/language/builtins.md#builtins-storePath)
)"
}

◆ QuitAll

QuitAll

Exit status returned from the REPL. The user exited with :quit. The program (e.g., if the REPL was acting as the debugger) should exit.

◆ raw

Raw raw

Force the default versions of all constructors (copy, move, copy assignment). Make a wrapper constructor. All args are forwarded to the construction of the "raw" field. (Which we assume is the only one.)

The moral equivalent of using Raw::Raw;

◆ regexCache

std::shared_ptr<RegexCache> regexCache

Cache used by prim_match().

◆ repair

RepairFlag repair

If set, force copying files to the Nix store even if they already exist there.

◆ res

return res

Add quotes around a collection of strings.

◆ restrictEval

Setting<bool> restrictEval
Initial value:
{
this, false, "restrict-eval",
R"(
If set to `true`, the Nix evaluator will not allow access to any
files outside of
[`builtins.nixPath`](@docroot@/language/builtins.md#builtins-nixPath),
or to URIs outside of
[`allowed-uris`](@docroot@/command-ref/conf-file.md#conf-allowed-uris).
)"}

◆ rootFS

const ref< SourceAccessor > rootFS

The accessor for the root filesystem.

◆ s

const Expr::AstSymbols & s

A helper for writing a boost::format expression to a string.

These are (roughly) equivalent:

fmt(formatString, a_0, ..., a_n)
(

However, when called with a single argument, the string is returned unchanged.

If you write code like this:

s

And stringFromUserInput contains formatting placeholders like s, then the code will crash at runtime. fmt helps you avoid this pitfall.

Remove trailing whitespace from a string.

Todo
return std::string_view.

Remove whitespace from the start and end of a string. Replace all occurrences of a string inside another string.

C++17 std::visit boilerplate Provide an addition operator between strings and string_views inexplicably omitted from the standard library.

A sink that writes data to a string.

A source that reads data from a string.

Underlying string

Todo
Should we normalize this when constructing a LookupPath::Prefix?

The location of a search path item, as a path or URL.

Todo
Maybe change this to std::variant<SourcePath, URL>.

◆ showTrace

Setting<bool> showTrace
Initial value:
{
this, false, "show-trace",
R"(
Whether Nix should print out a stack trace in case of Nix
expression evaluation errors.
)"}

◆ sink1

Sink& sink1

A sink that writes all incoming data to two other sinks.

◆ size_

size_t size_ = 0

Throw an exception for the purpose of checking that exception handling works; see 'initLibUtil()'. Print a message and abort(). Print a basic error message with source position and abort(). Use the unreachable() macro to call this. Print a basic error message with source position and abort().

Note
: This assumes that the logger is operational Provides an indexable container like vector<> with memory overhead guarantees like list<> by allocating storage in chunks of ChunkSize elements instead of using a contiguous memory allocation like vector<> does. Not using a single vector that is resized reduces memory overhead on large data sets by on average (growth factor)/2, mostly eliminates copies within the vector during resizing, and provides stable references to its elements.

◆ source1

Source& source1

Chain two sources together so after the first is exhausted, the second is used

◆ staticBaseEnv

std::shared_ptr<StaticEnv> staticBaseEnv

The same, but used during parsing to resolve variables.

◆ status

unsigned int status = 1

Exit status.

◆ STDERR_FILENO

return STDERR_FILENO

◆ STDIN_FILENO

return STDIN_FILENO

◆ STDOUT_FILENO

return STDOUT_FILENO

◆ store

const ref< Store > store {16}

Store used to materialise .drv files.

◆ str

std::string str

Show the name of an experimental feature. This is the opposite of parseExperimentalFeature(). Compute the documentation of all experimental features.

See doc/manual for how this information is used. Shorthand for str << showExperimentalFeature(feature).

◆ symbol

Symbol symbol

An attribute path is a sequence of attribute names.

◆ symbols

SymbolTable & symbols

Symbol table used by the parser and evaluator to represent and look up identifiers and attributes efficiently.

◆ SysError

Convenience alias for when we use a errno-based error handling function on Unix, and GetLastError()-based error handling on on Windows.

◆ t

T t

Wrap bools to prevent string literals (i.e. 'char *') from being cast to a bool in Attr.

◆ Throw

Throw

Throw the error to the code that attempted to print the value, instead of suppressing it it.

◆ ThrowTopLevel

ThrowTopLevel

Only throw the error if encountered at the top level of the expression.

This will cause expressions like builtins.throw "uh oh!" to throw errors, but will print attribute sets and other nested structures containing values that error (like nixpkgs) normally.

◆ TIter

TIter = decltype(std::begin(std::declval<T>()))

A Rust/Python-like enumerate() iterator adapter.

Borrowed from http://reedbeta.com/blog/python-like-enumerate-in-cpp17.

◆ to

Write as chunks in the format expected by FramedSource.

The checkError function can be used to terminate the stream when you detect that an error has occurred. It does so by throwing an exception.

◆ traceFunctionCalls

Setting<bool> traceFunctionCalls
Initial value:
{this, false, "trace-function-calls",
R"(
If set to `true`, the Nix evaluator will trace every function call.
Nix will print a log message at the "vomit" level for every function
entrance and function exit.
function-trace entered undefined position at 1565795816999559622
function-trace exited undefined position at 1565795816999581277
function-trace entered /nix/store/.../example.nix:226:41 at 1565795253249935150
function-trace exited /nix/store/.../example.nix:226:41 at 1565795253249941684
The `undefined position` means the function call is a builtin.
Use the `contrib/stack-collapse.py` script distributed with the Nix
source code to convert the trace logs in to a format suitable for
`flamegraph.pl`.
)"}

◆ traceVerbose

Setting<bool> traceVerbose
Initial value:
{this, false, "trace-verbose",
"Whether `builtins.traceVerbose` should trace its first argument when evaluated."}

◆ trackRepeated

bool trackRepeated = true

If true, track which values have been printed and skip them on subsequent encounters. Useful for self-referential values.

◆ trimExpr

const auto trimExpr
Initial value:
= [&] (Expr * e) {
atStartOfLine = false;
curDropped = 0;
es2->emplace_back(i->first, e);
}

◆ type

ValueType type = nThunk

Info about a constant Optional type of the constant (known since it is a fixed value).

Todo
we should use an enum for this.

◆ unknownSettings

StringMap unknownSettings

Semi-magic conversion to and from json. See the nlohmann/json readme for more details. The Config class provides Nix runtime configurations.

What is a Configuration? A collection of uniquely named Settings.

What is a Setting? Each property that you can set in a configuration corresponds to a Setting. A setting records value and description of a property with a default and optional aliases.

A valid configuration consists of settings that are registered to a Config object instance:

Config config; Setting<std::string> systemSetting{&config, "x86_64-linux", "system", "the current system"};

The above creates a Config object and registers a setting called "system" via the variable systemSetting with it. The setting defaults to the string "x86_64-linux", it's description is "the current system". All of the registered settings can then be accessed as shown below:

std::map<std::string, Config::SettingInfo> settings; config.getSettings(settings); settings["system"].description == "the current system" settings["system"].value == "x86_64-linux"

The above retrieves all currently known settings from the Config object and adds them to the settings map.

◆ useEvalCache

Setting<bool> useEvalCache
Initial value:
{this, true, "eval-cache",
R"(
Whether to use the flake evaluation cache.
Certain commands won't have to evaluate when invoked for the second time with a particular version of a flake.
Intermediate results are not cached.
)"}

◆ value

Value & value

A setting of type T.

◆ vEmptyList

Value vEmptyList

Empty list constant.

◆ vFalse

Value vFalse

true constant.

This is not a singleton. Pointer equality is not sufficient.

◆ views

Consider removing the empty string dropping behavior If use concatStringsSep instead std::string std::enable_if_t<(... && std::is_convertible_v<Parts, std::string_view>), std::string> std::string_view views[sizeof...(parts)] = {parts...}

Shell split string: split a string into shell arguments, respecting quotes and backslashes.

Used for NIX_SSHOPTS handling, which previously used tokenizeString and was broken by Arguments that need to be passed to ssh with spaces in them. Convert a list of strings to a null-terminated vector of char *s. The result must not be accessed beyond the lifetime of the list of strings.

◆ vNull

Value vNull

null constant.

This is not a singleton. Pointer equality is not sufficient.

◆ vStringDirectory

Value vStringDirectory

"directory"

◆ vStringRegular

Value vStringRegular

"regular"

◆ vStringSymlink

Value vStringSymlink

"symlink"

◆ vStringUnknown

Value vStringUnknown

"unknown"

◆ vTrue

Value vTrue

true constant.

This is not a singleton. Pointer equality is not sufficient.

◆ what_

std::optional<std::string> what_
mutable

Cached formatted contents of err.msg.

◆ x

return x = 0

Pretty-print a byte value, e.g. 12433615056 is rendered as 11.6 GiB. If align is set, the number will be right-justified by padding with spaces on the left. Parse a string into a float. Convert a little-endian integer to host order.