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< Field > | Fields |
typedef std::function< void(std::string_view data)> | lambda_t |
using | string_view = OsStringView |
typedef std::optional< Type > | DirEntry |
typedef std::map< std::string, DirEntry > | DirEntries |
using | Inner = T |
typedef std::map< Symbol, AttrDef > | AttrDefs |
typedef std::vector< DynamicAttrDef > | DynamicAttrDefs |
typedef std::vector< Formal > | Formals_ |
typedef std::vector< std::pair< Symbol, Displacement > > | Vars |
typedef uint32_t | size_t |
typedef Attr * | iterator |
typedef const Attr * | const_iterator |
using | value_type = Attr |
typedef std::variant< std::monostate, Stdin, String, SourcePath > | Origin |
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_t > | PrimOpCalls |
typedef std::map< ExprLambda *, size_t > | FunctionCalls |
typedef std::map< PosIdx, size_t > | AttrSelects |
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 | ||
BackedStringView & | operator= (const BackedStringView &)=delete | |
BackedStringView (BackedStringView &&other)=default | ||
BackedStringView & | operator= (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 | |
Suggestions & | operator+= (const Suggestions &other) | |
operator bool () const noexcept | ||
OrSuggestions (T t) | ||
OrSuggestions () | ||
const Suggestions & | getSuggestions () | |
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... Args > | HintFmt (const std::string &format, const Args &... args) | |
HintFmt (const HintFmt &hf) | ||
HintFmt (boost::format &&fmt, const Args &... args) | ||
HintFmt & | operator% (const T &value) | |
HintFmt & | operator% (const Uncolored< T > &value) | |
HintFmt & | operator= (HintFmt const &rhs)=default | |
const std::string & | calcWhat () const | |
BaseError (const BaseError &)=default | ||
BaseError & | operator= (const BaseError &)=default | |
BaseError & | operator= (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 char * | what () const noexcept override | |
const ErrorInfo & | info () 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 char * | c_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< SymbolStr > | resolve (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 char * | rel_c_str () const | |
std::optional< CanonPath > | parent () const | |
void | pop () | |
std::optional< std::string_view > | dirOf () const | |
std::optional< std::string_view > | baseName () 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< char > | ask (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 | ||
c | erase (i) | |
if (c.empty()) return | ||
c | 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 | ||
AutoCloseFD & | operator= (const AutoCloseFD &fd)=delete | |
AutoCloseFD & | operator= (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 | ||
FdSink & | operator= (FdSink &&s) | |
FdSource () | ||
FdSource (Descriptor fd) | ||
FdSource (FdSource &&)=default | ||
FdSource & | operator= (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_view & | native () 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< Stat > | maybeLstat (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::path > | getPhysicalPath (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::path > | getPhysicalPath () 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 | |
ExternalValueBase * | external () const | |
const PrimOp * | primOp () 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 Value * | maybeThunk (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 StaticEnv > | bindInheritSources (EvalState &es, const std::shared_ptr< const StaticEnv > &env) | |
Env * | buildInheritFromEnv (EvalState &state, Env &up) | |
void | showBindings (const SymbolTable &symbols, std::ostream &str) const | |
ExprList () | ||
bool | has (Symbol arg) const | |
std::vector< Formal > | lexicographicOrder (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 Attr * | get (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) | |
Value & | alloc (Symbol name, PosIdx pos=noPos) | |
Value & | alloc (std::string_view name, PosIdx pos=noPos) | |
Bindings * | alreadySorted () | |
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< LinesOfCode > | getCodeLines () 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< SourcePath > | getSourcePath () const | |
SyncBase () | ||
SyncBase (const T &data) | ||
SyncBase (T &&data) noexcept | ||
WriteLock | lock () | |
ReadLock | readLock () const | |
const Origin * | resolve (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_view > | suffixIfPotentialMatch (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 StaticEnv > | getStaticEnv (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) | |
Expr * | parseExprFromFile (const SourcePath &path) | |
Expr * | parseExprFromFile (const SourcePath &path, std::shared_ptr< StaticEnv > &staticEnv) | |
Expr * | parseExprFromString (std::string s, const SourcePath &basePath, std::shared_ptr< StaticEnv > &staticEnv) | |
Expr * | parseExprFromString (std::string s, const SourcePath &basePath) | |
Expr * | parseStdin () | |
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< SourcePath > | resolveLookupPathPath (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_view > | coerceToSingleDerivedPathUnchecked (const PosIdx pos, Value &v, std::string_view errorCtx) | |
SingleDerivedPath | coerceToSingleDerivedPath (const PosIdx pos, Value &v, std::string_view errorCtx) | |
void | createBaseEnv () | |
Value * | addConstant (const std::string &name, Value &v, Constant info) | |
void | addConstant (const std::string &name, Value *v, Constant info) | |
Value * | addPrimOp (PrimOp &&primOp) | |
Value & | getBuiltin (const std::string &name) | |
Value & | getBuiltins () | |
std::optional< Doc > | getDoc (Value &v) | |
Value * | lookupVar (Env *env, const ExprVar &var, bool noEval) | |
Expr * | parse (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) | |
Value * | allocValue () | |
Env & | allocEnv (size_t size) | |
Bindings * | allocBindings (size_t capacity) | |
BindingsBuilder | buildBindings (size_t capacity) | |
ListBuilder | buildList (size_t size) | |
Value * | getBool (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) | |
Formals * | validateFormals (Formals *formals, PosIdx pos=noPos, Symbol arg={}) | |
Expr * | stripIndentation (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 | t |
std::variant< std::string, std::string_view > | data |
int | distance |
The smaller the better. | |
std::string | suggestion |
std::set< Suggestion > | suggestions |
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 Pos & | errPos |
const std::string const Pos const LinesOfCode & | loc |
Default | |
Always | |
std::shared_ptr< Pos > | pos = 0 |
HintFmt | hint |
TracePrint | print = TracePrint::Default |
Verbosity | level |
HintFmt | msg |
std::list< Trace > | traces |
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_view & | name |
std::ostream & | str |
std::ostream const ExperimentalFeature & | feature |
ExperimentalFeature | missingFeature |
StringMap | unknownSettings |
Settings | _settings |
const std::string | description |
const std::set< std::string > | aliases |
int | created = 123 |
bool | overridden = false |
std::optional< ExperimentalFeature > | experimentalFeature |
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 |
Logger & | logger |
const ActivityId | prevAct |
const Activity & | act |
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 |
T | 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 Sink & | sink |
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"} |
Sink & | sink1 |
Sink & | sink2 |
Source & | orig |
size_t | remain |
uint64_t | length = 0 |
Source & | next |
uint64_t | total = 0 |
lambda_t | lambda |
Source & | source1 |
Source & | source2 |
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< char > | pending |
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 |
Ctx * | ctx |
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< SourceAccessor > | accessor |
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 |
EvalState & | state |
T | error |
PosIdx | begin |
PosIdx | end |
Symbol | symbol |
Expr * | expr |
ExprWith * | fromWith |
Displacement | displ = 0 |
Expr * | e |
Expr * | def |
AttrPath | attrPath |
AttrDefs | attrs |
std::unique_ptr< std::vector< Expr * > > | inheritFromExprs |
DynamicAttrDefs | dynamicAttrs |
std::vector< Expr * > | elems |
Formals_ | formals |
bool | ellipsis |
Symbol | arg |
Expr * | body |
DocComment | docComment |
std::vector< Expr * > | args |
std::optional< PosIdx > | cursedOrEndPos |
size_t | prevWith |
ExprWith * | parentWith |
Expr * | cond |
Expr * | then |
Expr * | else_ |
bool | forceString |
std::vector< std::pair< PosIdx, Expr * > > * | es |
ExprWith * | isWith |
const StaticEnv * | up |
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_ |
Bindings * | bindings |
uint32_t | line = 0 |
uint32_t | column = 0 |
Origin | origin = std::monostate() |
M | mutex |
std::map< uint32_t, Origin > | origins |
Sync< std::map< uint32_t, Lines > > | lines |
std::list< LookupPath::Elem > | elements |
QuitAll | |
Continue | |
size_t & | count |
size_t | arity = 0 |
const char * | doc = nullptr |
bool | addTrace = true |
bool | internal = false |
ValueType | type = nThunk |
bool | impureOnly = false |
Value * | values [0] |
const Env & | env = (Env *) allocBytes(sizeof(Env) + size * sizeof(Value *)) |
bool | isError |
const fetchers::Settings & | fetchSettings |
const EvalSettings & | settings |
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< SourceAccessor > | rootFS |
const ref< MemorySourceAccessor > | corepkgsFS |
const ref< MemorySourceAccessor > | internalFS |
const SourcePath | derivationInternal |
const SourcePath | callFlakeInternal |
const ref< Store > | buildStore |
RootValue | vImportedDrvToDerivation = nullptr |
ReplExitStatus(* | debugRepl )(ref< EvalState > es, const ValMap &extraEnv) |
bool | debugStop |
bool | inDebugger = false |
int | trylevel |
std::list< DebugTrace > | debugTraces |
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< RegexCache > | regexCache |
Env & | baseEnv |
std::shared_ptr< StaticEnv > | staticBaseEnv |
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 |
EvalState & | evalState |
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 int > | maxCallDepth |
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 LexerState & | lexerState |
Expr * | result |
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 |
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.
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.
will generate comparison operators semantically equivalent to:
prefix | This is for something before each declaration like template<classname Foo> . |
my_type | the 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.
v
.withArticle | Whether to begin with an english article, e.g. "an
integer" vs "integer". If path refers to a directory, then append "/default.nix". |
addDefaultNix | Whether 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.
#define COMMON_METHODS |
#define debug | ( | args... | ) |
#define FORCE_DEFAULT_CONSTRUCTORS | ( | CLASS_NAME | ) |
#define GENERATE_CMP_EXT | ( | prefix, | |
ret, | |||
my_type, | |||
args... ) |
#define GENERATE_EQUAL | ( | prefix, | |
qualification, | |||
my_type, | |||
args... ) |
#define GENERATE_ONE_CMP | ( | PRE, | |
RET, | |||
QUAL, | |||
COMPARATOR, | |||
MY_TYPE, | |||
... ) |
#define GENERATE_SPACESHIP | ( | prefix, | |
ret, | |||
qualification, | |||
my_type, | |||
args... ) |
#define logError | ( | errorInfo... | ) |
#define logErrorInfo | ( | level, | |
errorInfo... ) |
#define logWarning | ( | errorInfo... | ) |
#define MAKE_WRAPPER_CONSTRUCTOR | ( | CLASS_NAME | ) |
#define MakeError | ( | newClass, | |
superClass ) |
#define notice | ( | args... | ) |
#define POP_STATE | ( | ) |
#define printError | ( | args... | ) |
#define printInfo | ( | args... | ) |
#define printMsg | ( | level, | |
args... ) |
#define printMsgUsing | ( | loggerParam, | |
level, | |||
args... ) |
#define printTalkative | ( | args... | ) |
#define PUSH_STATE | ( | state | ) |
#define S_ISLNK | ( | m | ) |
#define unreachable | ( | ) |
#define vomit | ( | args... | ) |
#define warnOnce | ( | haveWarned, | |
args... ) |
using Built = SingleDerivedPath::Built |
Derivation output.
Encoded in the form !<output>!<drvPath>
.
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.
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.
using Inner = T |
Numeric value enforcing checked arithmetic. Performing mathematical operations on such values will return a Result type which needs to be checked.
Convert a function into a sink.
Convert a function into a source.
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.
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.
using Opaque = SingleDerivedPath::Opaque |
Plain opaque path to some store object.
Encoded as just the path: <path>
.
typedef std::variant< Opaque, DrvDeep, Built > Raw = std::variant<T, Suggestions> |
Either a value of type T
, or some suggestions
typedef uint32_t size_t |
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::path
s.
Stop gap until std::filesystem::path_view
from P1030R6 exists in a future C++ standard.
enum Type |
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.
Check that the call depth is within limits, and increment it, until the returned object is destroyed.
auto & addChunk | ( | ) |
Keep this out of the add hot path
|
inline |
Allocation primitives.
Allow access to a store path and return it as a string.
void allowClosure | ( | const StorePath & | storePath | ) |
Allow access to the closure of a store path.
void allowPath | ( | const Path & | path | ) |
Allow access to a path.
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.
|
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.
append | Whether to append or overwrite. |
void applyConfig | ( | const std::string & | contents, |
const std::string & | path = "<unknown>" ) |
Parses the configuration in contents
and applies it
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)
Automatically call a function for which each argument has a default value or has a binding in the args
map.
|
default |
We only want move operations defined since the sole purpose of this type is to avoid copies.
|
nodiscard |
Returns the length of a base-16 representation of this hash.
|
nodiscard |
Returns the length of a base-32 representation of this hash.
|
nodiscard |
Returns the length of a base-64 representation of this hash.
const std::string & calcWhat | ( | ) | const |
Format err.msg
and set what_
to the resulting value.
bool canDebug | ( | ) |
Whether a debug repl can be started. If false
, runDebugRepl(error)
will return without starting a repl.
CanonPath | ( | const std::vector< std::string > & | elems | ) |
Construct a canon path from a vector of elements.
CanonPath | ( | std::string_view | raw | ) |
Construct a canon path from a non-canonical path. Any '.', '..' or empty components are removed.
CanonPath | ( | std::string_view | raw, |
const CanonPath & | root ) |
If raw
starts with a slash, return CanonPath(raw)
. Otherwise return a CanonPath
representing root + "/" + raw
.
void check | ( | ) |
Validity check to be performed by functions that introduce primops, such as RegisterPrimOp() and Value::mkPrimOp().
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.
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.
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.
StorePath coerceToStorePath | ( | const PosIdx | pos, |
Value & | v, | ||
NixStringContext & | context, | ||
std::string_view | errorCtx ) |
Like coerceToPath, but the result must be a store path.
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.
|
overridepure virtual |
Converts settings to Args
to be used on the command line interface
Symbol create | ( | std::string_view | s | ) |
converts a string into a symbol.
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
.
void debugThrow | ( | ) |
Delete the EvalErrorBuilder
and throw the underlying exception.
size_t drainAll | ( | ) |
Consume the original source until no remain data is left to consume.
void dumpPath | ( | Sink & | sink, |
PathFilter & | filter = defaultPathFilter ) const |
Dump this SourcePath
to sink
as a NAR archive.
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.
Evaluate an expression to normal form
[out] | v | The resulting is stored here. |
Evaluation the expression, then verify that it has the expected type.
Evaluate the a.b.c
part of a.b.c.d
. This exists mostly for the purpose of :doc in the repl.
[out] | attrs | The attribute set that should contain the last attribute name (if it exists). |
attrPath
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).
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 | ( | PosIdx | pos, |
Displacement | displ ) |
void extend | ( | const CanonPath & | x | ) |
Append another path to this one.
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.
SourcePath findFile | ( | const std::string_view | path | ) |
Look up a file in the search path.
|
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.
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.
void forceFunction | ( | Value & | v, |
const PosIdx | pos, | ||
std::string_view | errorCtx ) |
v | either lambda or primop |
NixInt forceInt | ( | Value & | v, |
const PosIdx | pos, | ||
std::string_view | errorCtx ) |
Force v
, and then verify that it has the expected type.
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.
void forceValueDeep | ( | Value & | v | ) |
Force a value, then recursively force list elements and attributes.
formatHelper | ( | f % | x, |
args... | ) |
A helper for writing boost::format
expressions.
These are equivalent:
With a single argument, formatHelper(s)
is a no-op.
void fsync | ( | ) | const |
Perform a blocking fsync operation.
bool fullGC | ( | ) |
Perform a full memory garbage collection - not incremental.
Value & getBuiltin | ( | const std::string & | name | ) |
Retrieve a specific builtin, equivalent to evaluating builtins.${name}
.
name | The attribute name of the builtin to retrieve. |
EvalError | if the builtin does not exist. |
Value & getBuiltins | ( | ) |
Retrieve the builtins
attrset, equivalent to evaluating the reference builtins
. Always returns an attribute set value.
const std::string & getCurrentSystem | ( | ) | const |
Implements the eval-system
vs system
defaulting logic described for eval-system
.
Retrieve the documentation for a value. This will evaluate the value if it is a thunk, and it will partially apply __functor if applicable.
v | The value to get the documentation for. |
|
virtual |
Return the maximum last-modified time of the files in this tree, if available.
std::optional< std::filesystem::path > getPhysicalPath | ( | ) | const |
Return the location of this path in the "real" filesystem, if it has a physical location.
|
virtual |
Return a corresponding path in the root filesystem, if possible. This is only possible for filesystems that are materialized in the root filesystem.
|
overridepure virtual |
Adds the currently known settings to the given result map res
.
res
std::optional< std::string > getSource | ( | ) | const |
Return the contents of the source file.
std::optional< SourcePath > getSourcePath | ( | ) | const |
Get the SourcePath, if the source was loaded from a file.
bool hasData | ( | ) |
Return true if the buffer is not empty.
Return true if the buffer is not empty after a non-blocking read.
|
explicit |
Create a zero-filled hash object.
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 | ( | c. | empty() | ) |
Remove and return the first item from a container.
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()
.
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.)
|
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.
bool isDerivation | ( | Value & | v | ) |
v
denotes a derivation (i.e. a set with attribute type = "derivation"
). bool isEnabled | ( | const ExperimentalFeature & | ) | const |
Check whether the given experimental feature is enabled.
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.
bool isTrivial | ( | ) | const |
Check whether forcing this value requires a trivial amount of computation. In particular, function applications are non-trivial.
bool isWithin | ( | const CanonPath & | parent | ) | const |
Return true if this
is equal to parent
or a child of parent
.
std::vector< const Attr * > lexicographicOrder | ( | const SymbolTable & | symbols | ) | const |
Returns the attributes in lexicographically sorted order.
WriteLock lock | ( | ) |
Acquire write (exclusive) access to the inner value.
SourceAccessor::Stat lstat | ( | ) | const |
Return stats about this SourcePath
, or throw an exception if it doesn't exist.
Magenta | ( | const T & | s | ) |
std::string makeRelative | ( | const CanonPath & | path | ) | const |
Return a representation x
of path
relative to this
, i.e. CanonPath(this.makeRelative(x), this) == path
.
std::optional< SourceAccessor::Stat > maybeLstat | ( | ) | const |
Return stats about this SourcePath
, or std::nullopt if it doesn't exist.
void maybePrintStats | ( | ) |
Print statistics, if enabled.
Performs a full memory GC before printing the statistics, so that the GC statistics are more accurate.
std::string message | ( | ) |
The error message without "error: " prefixed to it.
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.
value | Value we are settings |
b | the drv whose output we are making a string for, and the output |
optStaticOutputPath | Optional 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 ). |
xpSettings | Stop-gap to avoid globals during unit tests. |
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.
void mkSingleDerivedPathString | ( | const SingleDerivedPath & | p, |
Value & | v ) |
Create a string representing a SingleDerivedPath
.
A combination of mkStorePathString
and mkOutputString
.
std::string mkSingleDerivedPathStringRaw | ( | const SingleDerivedPath & | p | ) |
Like mkSingleDerivedPathStringRaw
but just creates a raw string Value, which would also have a string context.
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 | ( | T... | ) |
A variadic template that does nothing.
Useful to call a function with each argument in a parameter pack.
OnStartup | ( | T && | t | ) |
Paths are just strings. Helper class to run code at startup.
|
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
.
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.
|
overridepure virtual |
Just throws away data.
SourcePath operator/ | ( | const CanonPath & | x | ) | const |
Concatenate two paths.
Append a CanonPath
to this path.
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
.
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.
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.
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!'.
|
noexcept |
Compare how two hashes are ordered.
|
noexcept |
Check whether two hashes are equal.
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.
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.
SourcePath parent | ( | ) | const |
Construct the parent of this SourcePath
. Aborts if this
denotes the root.
|
overridevirtual |
Parse the string into a T
.
Used by set()
.
Expr * parseExprFromFile | ( | const SourcePath & | path | ) |
Parse a Nix expression from the specified file.
Expr * parseExprFromString | ( | std::string | s, |
const SourcePath & | basePath, | ||
std::shared_ptr< StaticEnv > & | staticEnv ) |
Parse a Nix expression from the specified string.
bool pathExists | ( | ) | const |
Return whether this SourcePath
denotes a file (of any type) that exists
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.
c pop | ( | ) |
Remove the last component. Panics if this path is the root.
return printLiteralString | ( | o | , |
std::string_view(s) | ) |
Print a string as a Nix string literal.
Quotes and fairly minimal escaping are added.
o | The output stream to print to |
s | The logical string |
void printStatistics | ( | ) |
Print statistics, unconditionally, cheaply, without performing a GC first.
void push | ( | std::string_view | c | ) |
Add a path component to this one. It must not contain any slashes.
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.
SourceAccessor::DirEntries readDirectory | ( | ) | const |
If this SourcePath
denotes a directory (not a symlink), return its directory entries; otherwise throw an error.
|
pure virtual |
readFile
, this method should not follow symlinks. std::string readFile | ( | ) | const |
If this SourcePath
denotes a regular file (not a symlink), return its contents; otherwise throw an error.
|
virtual |
Return the contents of a file as a string.
|
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.
readFile
, this method should not follow symlinks.SourceAccessor
need to implement at least one of the readFile()
variants. std::string readLink | ( | ) | const |
If this SourcePath
denotes a symlink, return its target; otherwise throw an error.
ReadLock readLock | ( | ) | const |
Acquire read access to the inner value. When using std::shared_mutex
, this will use a shared lock.
Underlying read call, to be overridden.
|
nodiscard |
Realise the given context
[in] | context | the context to realise |
[out] | maybePaths | if not nullptr, all built or referenced store paths will be added to this set |
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.
[in] | str | the string to realise |
[out] | paths | all referenced store paths will be added to this set |
EvalError | if the value is not a string, path or derivation (see coerceToString ) |
void reapplyUnknownSettings | ( | ) |
Re-applies all previously attempted changes to unknown settings
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.
void require | ( | const ExperimentalFeature & | ) | const |
Require an experimental feature be enabled, throwing an error if it is not.
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.
|
overridepure virtual |
Resets the overridden
flag of all Settings
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
.
CanonPath resolveSymlinks | ( | const CanonPath & | path, |
SymlinkResolution | mode = SymlinkResolution::Full ) |
Resolve any symlinks in path
according to the given resolution mode.
mode | might only be a temporary solution for this. See the discussion in https://github.com/NixOS/nix/pull/9985. |
SourcePath resolveSymlinks | ( | SymlinkResolution | mode = SymlinkResolution::Full | ) | const |
Convenience wrapper around SourceAccessor::resolveSymlinks()
.
SourcePath rootPath | ( | CanonPath | path | ) |
Return a SourcePath
that refers to path
in the root filesystem.
SourcePath rootPath | ( | PathView | path | ) |
Variant which accepts relative paths too.
void runDebugRepl | ( | const Error * | error | ) |
Use front of debugTraces
; see runDebugRepl(error,env,expr)
Run a debug repl with the given error, environment and expression.
error | The error to debug, may be nullptr. |
env | The environment to debug, matching the expression. |
expr | The expression to debug, matching the environment. |
|
overridepure virtual |
Sets the value referenced by name
to value
. Returns true if the setting is known, false otherwise.
|
finaloverridepure virtual |
Require any experimental feature the setting depends on
Uses parse()
to get the value from str
, and appendOrSet()
to set it.
|
inline |
True if pretty-printing is enabled.
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.
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.
Construct using the ambient errno
.
Be sure to not perform another errno
-modifying operation before calling this constructor!
Construct using the explicitly-provided error number. strerror
will be used to try to add additional information to the message.
|
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:").
|
overridepure virtual |
Outputs all settings to JSON
|
overridepure virtual |
Outputs all settings in a key-value pair format suitable to be used as nix.conf
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.
void warnUnknownSettings | ( | ) |
Logs a warning for each unregistered setting
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.
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.
int yylex | ( | YYSTYPE * | yylval_param, |
YYLTYPE * | yylloc_param, | ||
yyscan_t | yyscanner ) |
[^/*] reject /*
|
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.
|
virtual |
Abstract source of binary data.
std::filesystem::path _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.
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.
concatStringsSep
. 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.
const Activity & act |
source | A noun phrase describing the source of the message, e.g. "the builder". |
source | A noun phrase describing the source of the message, e.g. "the builder". |
source | A noun phrase describing the source of the message, e.g. "the builder". |
bool addTrace = true |
Add a trace item, while calling the <name>
builtin.
This is used to remove the redundant item for builtins.addErrorContext
.
Setting<Strings> allowedUris |
Always |
Always printed. Produced by builtins.addErrorContext
.
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 = 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.
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.
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 |
Lowercase hexadecimal encoding.
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.
Env& baseEnv |
The base environment, containing the builtin functions and values.
const_iterator begin |
A documentation comment, in the sense of RFC 145
Note that this does not implement the following:
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 |
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.
Descriptor Sink bool block |
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.
Setting<bool> builtinsAbortOnWarn |
Setting<bool> builtinsDebuggerOnWarn |
Setting<bool> builtinsTraceDebugger |
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.
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 |
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.
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 |
The user exited with :continue
. The program should continue running.
const ref<MemorySourceAccessor> corepkgsFS |
The in-memory filesystem for <nix/...> paths.
size_t& count |
Increments a count on construction and decrements on destruction.
T& counter |
A RAII helper that increments a counter on construction and decrements it on destruction.
Setting<std::string> currentSystem |
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.
ReplExitStatus(* debugRepl) (ref< EvalState > es, const ValMap &extraEnv) | ( | ref< EvalState > | es, |
const ValMap & | extraEnv ) |
Debugger
Default |
When a stack frame is printed. The default behavior; always printed when --show-trace
is set.
bool derivationPaths = false |
If true and force
is set, print derivations as «derivation /nix/store/...»
instead of as attribute sets.
std::optional< PathView > dir = {} |
Polyfill for MinGW
Windows does in fact support symlinks, but the C runtime interfaces predate this.
stat
when we want lstat
too. Return whether the path denotes an absolute path.
In the process of being deprecated for std::filesystem::absolute
.
int distance |
The smaller the better.
A potential suggestion for the cli interface.
const char * doc = nullptr |
Optional free-form documentation about the primop.
Optional free-form documentation about the constant.
int doc_comment_first_column |
Latest doc comment position, or 0.
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.
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 |
Setting<bool> enableImportFromDerivation |
Setting<bool> enableNativeCode |
const_iterator end |
Position right after the final asterisk and /
that terminate the comment.
bool eof |
|
mutable |
BaseError should generally not be caught, as it has Interrupted as a subclass. Catch Error instead.
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.
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. How to handle errors encountered while printing values.
std::map<const Hash, ref<eval_cache::EvalCache> > evalCaches |
A cache for evaluation caches, so as to reuse the same root value if possible
std::optional< ExperimentalFeature > experimentalFeature |
Optional experimental for this to be gated on.
Setting<std::set<ExperimentalFeature> > experimentalFeatures |
Descriptor 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.
fd | The file descriptor to read from |
eofOk | If true, return an unterminated line if EOF is reached. (e.g. the empty string) |
\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.
std::optional<std::string> fingerprint |
A string that uniquely represents the contents of this accessor. This is used for caching lookups (see fetchToStore()
).
bool force = false |
If true, force values.
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 |
Resolve symlinks fully, realpath(3)-style.
No component of the result will be a symlink.
std::function< PrimOpFun > fun |
std::hash<T> hasher |
hash_combine()
from Boost. Hash several hashable values together into a single hash.
auto i = map.find(key) |
s
starts with prefix
. 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.
Setting<bool> ignoreExceptionsDuringTry |
bool impureOnly = false |
Whether the constant is impure, and not available in pure mode.
bool includePid = true |
Create a temporary directory.
int |
Operating System capability
bool internal = false |
If true, this primop is not exposed to the user.
const ref<MemorySourceAccessor> internalFS |
In-memory filesystem for internal, non-user-callable Nix expressions like call-flake.nix.
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.
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.
std::shared_ptr<std::basic_istream<char> > istream |
An adapter that converts a std::basic_istream into a source.
ExprAttrs::AttrDefs::iterator j = attrs->attrs.find(symbol) |
Precondition: attrPath is used for error messages and should already contain symbol as its last element.
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.
ParserLocation lastDocCommentLoc |
The location of the last doc comment.
(stashing fields are not used)
uint64_t length = 0 |
A sink that that just counts the number of bytes given to it
uint32_t line = 0 |
A position and an origin for that position (like a source file).
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.
maxDepth = std::numeric_limits<size_t>::max() |
Maximum depth to evaluate to.
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 = std::numeric_limits<size_t>::max() |
Maximum string length to print.
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.
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.
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.
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.
Source& next |
A wrapper source that counts the number of bytes read from it.
Nix32 |
Nix-specific base-32 encoding.
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).
Source & orig |
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.
char *
and size_t
allows us to avoid having to define the special members that using string_view here would implicitly delete. Path path |
A canonical representation of a path. It ensures the following:
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.
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.Create a single directory. Set the access and modification times of the given path, not following symlinks.
accessedTime | Specified in seconds. |
modificationTime | Specified in seconds. |
isSymlink | Whether 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.
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.
size_t prettyIndent = 0 |
Indentation width for pretty-printing.
If set to 0 (the default), values are not pretty-printed.
lvlVomit std::optional<std::string> prevLineOfCode |
The lines of code surrounding an error.
How errors should be handled when printing values. Print the first line of the error in brackets: «error: oh no!»
Setting<bool> pureEval |
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 |
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;
std::shared_ptr<RegexCache> regexCache |
Cache used by prim_match().
RepairFlag repair |
If set, force copying files to the Nix store even if they already exist there.
return res |
Add quotes around a collection of strings.
Setting<bool> restrictEval |
const ref< SourceAccessor > rootFS |
The accessor for the root filesystem.
const Expr::AstSymbols & s |
A helper for writing a boost::format
expression to a string.
These are (roughly) equivalent:
However, when called with a single argument, the string is returned unchanged.
If you write code like this:
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.
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
LookupPath::Prefix
? The location of a search path item, as a path or URL.
std::variant<SourcePath, URL>
. Setting<bool> showTrace |
Sink& sink1 |
A sink that writes all incoming data to two other sinks.
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().
Source& source1 |
Chain two sources together so after the first is exhausted, the second is used
std::shared_ptr<StaticEnv> staticBaseEnv |
The same, but used during parsing to resolve variables.
return STDERR_FILENO |
Get Standard Error
return STDIN_FILENO |
Get Standard Input
return STDOUT_FILENO |
Get Standard Output
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 |
An attribute path is a sequence of attribute names.
SymbolTable & symbols |
Symbol table used by the parser and evaluator to represent and look up identifiers and attributes efficiently.
Convenience alias for when we use a errno
-based error handling function on Unix, and GetLastError()
-based error handling on on Windows.
T t |
Wrap bools to prevent string literals (i.e. 'char *') from being cast to a bool in Attr.
Throw |
Throw the error to the code that attempted to print the value, instead of suppressing it it.
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 = decltype(std::begin(std::declval<T>())) |
A Rust/Python-like enumerate() iterator adapter.
Borrowed from http://reedbeta.com/blog/python-like-enumerate-in-cpp17.
BufferedSink & 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.
Setting<bool> traceFunctionCalls |
Setting<bool> traceVerbose |
bool trackRepeated = true |
If true, track which values have been printed and skip them on subsequent encounters. Useful for self-referential values.
const auto trimExpr |
ValueType type = nThunk |
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.
Setting<bool> useEvalCache |
Value & value |
A setting of type T.
Value vEmptyList |
Empty list constant.
Value vFalse |
true
constant.
This is not a singleton. Pointer equality is not sufficient.
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.
Value vNull |
null
constant.
This is not a singleton. Pointer equality is not sufficient.
Value vStringDirectory |
"directory"
Value vStringRegular |
"regular"
Value vStringSymlink |
"symlink"
Value vStringUnknown |
"unknown"
Value vTrue |
true
constant.
This is not a singleton. Pointer equality is not sufficient.
|
mutable |
Cached formatted contents of err.msg
.
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.