Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
value.hh
Go to the documentation of this file.
1#pragma once
3
4#include <bit>
5#include <cassert>
6#include <cstddef>
7#include <cstring>
8#include <memory>
9#include <memory_resource>
10#include <exception>
11#include <span>
12#include <string_view>
13#include <type_traits>
14#include <concepts>
15
16#include "nix/expr/eval-gc.hh"
21#include "nix/util/pos-idx.hh"
22
23#include <boost/unordered/unordered_flat_map_fwd.hpp>
24#include <nlohmann/json_fwd.hpp>
25
26#if defined(__x86_64__) && defined(__SSE2__)
27# include <emmintrin.h>
28#endif
29
30namespace nix {
31
32struct Value;
33class BindingsBuilder;
34
45 tUninitialized = 0,
46 /* layout: Single/zero field payload */
47 tInt = 1,
48 tBool,
49 tNull,
50 tFloat,
51 tFailed,
52 tExternal,
53 tPrimOp,
54 tAttrs,
55 /* layout: Pair of pointers payload */
56 tFirstPairOfPointers,
57 tListSmall = tFirstPairOfPointers,
58 tString,
59 tPath,
60 tPrimOpApp,
61 tApp,
62 tThunk,
63 tLambda,
64 tLastPairOfPointers = tLambda,
65 /* layout: Single untaggable field */
66 tFirstSingleUntaggable,
67 tListN = tFirstSingleUntaggable,
68 tSymbol,
69 tNumberOfInternalTypes, // Must be last
70};
71
77typedef enum {
78 nThunk,
79 nFailed,
80 nInt,
81 nFloat,
82 nBool,
83 nString,
84 nPath,
85 nNull,
86 nAttrs,
87 nList,
88 nFunction,
89 nExternal,
90} ValueType;
91
92class Bindings;
93struct Env;
94struct Expr;
95struct ExprLambda;
96struct ExprBlackHole;
97struct PrimOp;
98class Symbol;
99class SymbolStr;
100struct Pos;
101class PosTable;
102class StorePath;
103class EvalState;
104class EvalMemory;
105class XMLWriter;
106class Printer;
107
108using NixInt = checked::Checked<int64_t>;
109using NixFloat = double;
110
116{
117 friend std::ostream & operator<<(std::ostream & str, const ExternalValueBase & v);
118 friend class Printer;
119protected:
123 virtual std::ostream & print(std::ostream & str) const = 0;
124
125public:
129 virtual std::string showType() const = 0;
130
134 virtual std::string typeOf() const = 0;
135
140 virtual std::string coerceToString(
141 EvalState & state, const PosIdx & pos, NixStringContext & context, bool copyMore, bool copyToStore) const;
142
147 virtual bool operator==(const ExternalValueBase & b) const noexcept;
148
152 virtual nlohmann::json
153 printValueAsJSON(EvalState & state, bool strict, NixStringContext & context, bool copyToStore = true) const;
154
158 virtual void printValueAsXML(
159 EvalState & state,
160 bool strict,
161 bool location,
162 XMLWriter & doc,
163 NixStringContext & context,
164 StringSet & drvsSeen,
165 const PosIdx pos) const;
166
167 virtual ~ExternalValueBase() {};
168};
169
170std::ostream & operator<<(std::ostream & str, const ExternalValueBase & v);
171
172class ListBuilder
173{
174 const size_t size;
175 Value * inlineElems[2] = {nullptr, nullptr};
176public:
177 Value ** elems;
178 ListBuilder(EvalMemory & mem, size_t size);
179
180 ListBuilder(ListBuilder && x) noexcept
181 : size(x.size)
182 , inlineElems{x.inlineElems[0], x.inlineElems[1]}
183 , elems(size <= 2 ? inlineElems : x.elems)
184 {
185 }
186
187 ListBuilder(const ListBuilder &) = delete;
188 ListBuilder & operator=(ListBuilder &&) = delete;
189 ListBuilder & operator=(const ListBuilder &) = delete;
190 ~ListBuilder() = default;
191
192 Value *& operator[](size_t n)
193 {
194 return elems[n];
195 }
196
197 typedef Value ** iterator;
198
199 iterator begin()
200 {
201 return &elems[0];
202 }
203
204 iterator end()
205 {
206 return &elems[size];
207 }
208
209 friend struct Value;
210};
211
212class StringData
213{
214public:
215 using size_type = std::size_t;
216
217 size_type size_;
218 char data_[];
219
220 /*
221 * This in particular ensures that we cannot have a `StringData`
222 * that we use by value, which is just what we want!
223 *
224 * Dynamically sized types aren't a thing in C++ and even flexible array
225 * members are a language extension and beyond the realm of standard C++.
226 * Technically, sizeof data_ member is 0 and the intended way to use flexible
227 * array members is to allocate sizeof(StrindData) + count * sizeof(char) bytes
228 * and the compiler will consider alignment restrictions for the FAM.
229 *
230 */
231
232 StringData(StringData &&) = delete;
233 StringData & operator=(StringData &&) = delete;
234 StringData(const StringData &) = delete;
235 StringData & operator=(const StringData &) = delete;
236 ~StringData() = default;
237
238private:
239 StringData() = delete;
240
241 explicit StringData(size_type size)
242 : size_(size)
243 {
244 }
245
246public:
251 static const StringData & make(EvalMemory & mem, std::string_view s);
252
257 static StringData & alloc(EvalMemory & mem, size_t size);
258
259 size_t size() const
260 {
261 return size_;
262 }
263
264 char * data() noexcept
265 {
266 return data_;
267 }
268
269 const char * data() const noexcept
270 {
271 return data_;
272 }
273
274 const char * c_str() const noexcept
275 {
276 return data_;
277 }
278
279 constexpr std::string_view view() const noexcept
280 {
281 return std::string_view(data_, size_);
282 }
283
284 template<size_t N>
285 struct Static;
286
287 static StringData & make(std::pmr::memory_resource & resource, std::string_view s)
288 {
289 auto & res =
290 *new (resource.allocate(sizeof(StringData) + s.size() + 1, alignof(StringData))) StringData(s.size());
291 std::memcpy(res.data_, s.data(), s.size());
292 res.data_[s.size()] = '\0';
293 return res;
294 }
295};
296
297namespace detail {
298
305{
306 struct Symbol
307 {
308 size_t symbol;
309 const StringData * str;
310 };
311
335 {
336 const StringData * str;
337
349 struct Context
350 {
351 using value_type = const StringData *;
352 using size_type = std::size_t;
353 using iterator = const value_type *;
354
355 Context(size_type size)
356 : size_(size)
357 {
358 }
359
360 private:
364 size_type size_;
365
369 value_type elems[];
370
371 public:
372 iterator begin() const
373 {
374 return elems;
375 }
376
377 iterator end() const
378 {
379 return elems + size();
380 }
381
382 size_type size() const
383 {
384 return size_;
385 }
386
390 static Context * fromBuilder(const NixStringContext & context, EvalMemory & mem);
391 };
392
397 };
398
399 struct Path
400 {
401 SourceAccessor * accessor;
402 const StringData * path;
403 };
404
405 struct Null
406 {};
407
409 {
410 Env * env;
411 Expr * expr;
412 };
413
415 {
416 Value *left, *right;
417 };
418
425 {
426 Value *left, *right;
427 };
428
429 struct Lambda
430 {
431 Env * env;
432 ExprLambda * fun;
433 };
434
435 using SmallList = std::array<Value *, 2>;
436
437 struct List
438 {
439 size_t size;
440 Value * const * elems;
441 };
442
449 struct ExceptionRef : gc_cleanup
450 {
451 ExceptionRef(std::exception_ptr ex)
452 : ex(std::move(ex))
453 {
454 assert(this->ex);
455 }
456
457 ExceptionRef(ExceptionRef &&) = delete;
458 ExceptionRef(const ExceptionRef &) = delete;
459 ExceptionRef & operator=(ExceptionRef &&) = delete;
460 ExceptionRef & operator=(const ExceptionRef &) = delete;
461
462 /* To appease -Wweak-vtables. */
463 virtual ~ExceptionRef();
464
465 std::exception_ptr ex;
466 };
467
468 struct Failed : gc
469 {
470 ExceptionRef * exRef;
471
477
478 Failed(std::exception_ptr ex, Value * recoveryValue)
479 : exRef(new /* ExceptionRef : gc_cleanup */ ExceptionRef(ex))
481 {
482 }
483
484 [[noreturn]] void rethrow() const
485 {
486 /* Rethrow the copy of the exception - not the original one.
487 Stack tracing mechanisms rely on being able to modify the exceptions
488 they catch by reference. */
489 rethrowExceptionCopy(exRef->ex);
490 }
491 };
492};
493
494template<typename T>
497
503#define NIX_VALUE_STORAGE_FOR_EACH_FIELD(MACRO) \
504 MACRO(NixInt, integer, tInt) \
505 MACRO(bool, boolean, tBool) \
506 MACRO(ValueBase::StringWithContext, string, tString) \
507 MACRO(ValueBase::Path, path, tPath) \
508 MACRO(ValueBase::Null, null_, tNull) \
509 MACRO(const Bindings *, attrs, tAttrs) \
510 MACRO(ValueBase::List, bigList, tListN) \
511 MACRO(ValueBase::Symbol, symbol, tSymbol) \
512 MACRO(ValueBase::SmallList, smallList, tListSmall) \
513 MACRO(ValueBase::ClosureThunk, thunk, tThunk) \
514 MACRO(ValueBase::FunctionApplicationThunk, app, tApp) \
515 MACRO(ValueBase::Lambda, lambda, tLambda) \
516 MACRO(PrimOp *, primOp, tPrimOp) \
517 MACRO(ValueBase::PrimOpApplicationThunk, primOpApp, tPrimOpApp) \
518 MACRO(ExternalValueBase *, external, tExternal) \
519 MACRO(ValueBase::Failed *, failed, tFailed) \
520 MACRO(NixFloat, fpoint, tFloat)
521
522#define NIX_VALUE_PAYLOAD_TYPE(T, FIELD_NAME, DISCRIMINATOR) \
523 template<> \
524 struct PayloadTypeToInternalType<T> \
525 { \
526 static constexpr InternalType value = DISCRIMINATOR; \
527 };
528
529NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_PAYLOAD_TYPE)
530
531#undef NIX_VALUE_PAYLOAD_TYPE
532
533template<typename T>
534inline constexpr InternalType payloadTypeToInternalType = PayloadTypeToInternalType<T>::value;
535
536} // namespace detail
537
549template<std::size_t ptrSize, typename Enable = void>
551{
552protected:
553 using Payload = union
554 {
555#define NIX_VALUE_STORAGE_DEFINE_FIELD(T, FIELD_NAME, DISCRIMINATOR) T FIELD_NAME;
556 NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_STORAGE_DEFINE_FIELD)
557#undef NIX_VALUE_STORAGE_DEFINE_FIELD
558 };
559
560private:
561 InternalType internalType = tUninitialized;
562 Payload payload;
563
564protected:
565#define NIX_VALUE_STORAGE_GET_IMPL(K, FIELD_NAME, DISCRIMINATOR) \
566 void getStorage(K & val) const noexcept \
567 { \
568 assert(internalType == DISCRIMINATOR); \
569 val = payload.FIELD_NAME; \
570 }
571
572#define NIX_VALUE_STORAGE_SET_IMPL(K, FIELD_NAME, DISCRIMINATOR) \
573 void setStorage(K val) noexcept \
574 { \
575 payload.FIELD_NAME = val; \
576 internalType = DISCRIMINATOR; \
577 }
578
579 NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_STORAGE_GET_IMPL)
580 NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_STORAGE_SET_IMPL)
581
582#undef NIX_VALUE_STORAGE_SET_IMPL
583#undef NIX_VALUE_STORAGE_GET_IMPL
584#undef NIX_VALUE_STORAGE_FOR_EACH_FIELD
585
588 {
589 return internalType;
590 }
591
592 static bool isAtomic()
593 {
594 return false;
595 }
596};
597
598namespace detail {
599
600/* Whether to use a specialization of ValueStorage that does bitpacking into
601 alignment niches. */
602template<std::size_t ptrSize>
603inline constexpr bool useBitPackedValueStorage = (ptrSize == 8) && (__STDCPP_DEFAULT_NEW_ALIGNMENT__ >= 16);
604
605} // namespace detail
606
611template<std::size_t ptrSize>
612class alignas(16)
613 ValueStorage<ptrSize, std::enable_if_t<detail::useBitPackedValueStorage<ptrSize>>> : public detail::ValueBase
614{
615 /* Needs a dependent type name in order for member functions (and
616 * potentially ill-formed bit casts) to be SFINAE'd out.
617 *
618 * Otherwise some member functions could possibly be instantiated for 32 bit
619 * systems and fail due to an unsatisfied constraint.
620 */
621 template<std::size_t size>
622 struct PackedPointerTypeStruct
623 {
624 using type = std::uint64_t;
625 };
626
627 using PackedPointer = typename PackedPointerTypeStruct<ptrSize>::type;
628 using Payload = std::array<PackedPointer, 2>;
629#if defined(__x86_64__) && defined(__SSE2__)
630 __m128i payloadWords;
631#else
632 Payload payloadWords = {};
633#endif
634
635 static constexpr int discriminatorBits = 3;
636 static constexpr PackedPointer discriminatorMask = (PackedPointer(1) << discriminatorBits) - 1;
637
666 enum PrimaryDiscriminator : int {
667 pdUninitialized = 0,
668 pdSingleDWord, //< layout: Single/zero field payload
669 /* The order of these enumerations must be the same as in InternalType. */
670 pdListN, //< layout: Single untaggable field.
671 pdSymbol,
672 pdPairOfPointers, //< layout: Pair of pointers payload
673 };
674
675#if defined(__x86_64__) && defined(__SSE2__)
676 /* Why do we even bother with hand-rolling these arch-specific intrinsics
677 * and don't use libatomic directly for 16 byte atomics? Here's why:
678 * - https://gcc.gnu.org/legacy-ml/gcc/2018-02/msg00224.html
679 * - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84563
680 *
681 * Basically, we don't really ever want to go through libatomic. As is
682 * so happens on x86_64 with AVX, MOVDQA/MOVAPS instructions (16-byte aligned
683 * 128-bit loads and stores) are atomic [^]. Note that
684 * these instructions are not part of AVX but rather SSE2, which is x86_64-v1.
685 * They are just not guaranteed to be atomic without AVX.
686 *
687 * For more details see:
688 * - [^] Intel® 64 and IA-32 Architectures Software Developer’s Manual (10.1.1 Guaranteed Atomic Operations).
689 * - https://patchwork.sourceware.org/project/gcc/patch/YhxkfzGEEQ9KHbBC@tucnak/
690 * - https://ibraheem.ca/posts/128-bit-atomics/
691 * - https://rigtorp.se/isatomic/
692 */
693 [[gnu::always_inline]]
694 void updatePayload(Payload payload) noexcept
695 {
696 /* This intrinsic corresponds to MOVAPS. Note that Value (and thus the first member
697 payloadWords) is 16 bytes aligned. */
698 _mm_store_si128(&payloadWords, std::bit_cast<__m128i>(payload));
699 }
700
701 [[gnu::always_inline]]
702 Payload loadPayload() const noexcept
703 {
704 /* This intrinsic corresponds to MOVDQA. Note that Value (and thus the first member
705 payloadWords) is 16 bytes aligned. */
706 __m128i res = _mm_load_si128(&payloadWords);
707 return std::bit_cast<Payload>(res);
708 }
709#else
710 [[gnu::always_inline]]
711 void updatePayload(Payload payload) noexcept
712 {
713 payloadWords = payload;
714 }
715
716 [[gnu::always_inline]]
717 Payload loadPayload() const noexcept
718 {
719 return payloadWords;
720 }
721#endif
722
723 template<typename T>
724 requires std::is_pointer_v<T>
725 static T untagPointer(PackedPointer val) noexcept
726 {
727 return std::bit_cast<T>(val & ~discriminatorMask);
728 }
729
730 PrimaryDiscriminator getPrimaryDiscriminator(PackedPointer firstDWord) const noexcept
731 {
732 return static_cast<PrimaryDiscriminator>(firstDWord & discriminatorMask);
733 }
734
735 static void assertAligned(PackedPointer val) noexcept
736 {
737 assert((val & discriminatorMask) == 0 && "Pointer is not 8 bytes aligned");
738 }
739
740 template<InternalType type>
741 void setSingleDWordPayload(PackedPointer untaggedVal) noexcept
742 {
743 Payload payload;
744 /* There's plenty of free upper bits in the first dword, which is
745 used only for the discriminator. */
746 payload[0] = static_cast<int>(pdSingleDWord) | (static_cast<int>(type) << discriminatorBits);
747 payload[1] = untaggedVal;
748 updatePayload(payload);
749 }
750
751 template<PrimaryDiscriminator discriminator, typename T, typename U>
752 void setUntaggablePayload(T * firstPtrField, U untaggableField) noexcept
753 {
754 Payload payload;
755 static_assert(discriminator >= pdListN && discriminator <= pdSymbol);
756 auto firstFieldPayload = std::bit_cast<PackedPointer>(firstPtrField);
757 assertAligned(firstFieldPayload);
758 payload[0] = static_cast<int>(discriminator) | firstFieldPayload;
759 payload[1] = std::bit_cast<PackedPointer>(untaggableField);
760 updatePayload(payload);
761 }
762
763 template<InternalType type, typename T, typename U>
764 void setPairOfPointersPayload(T * firstPtrField, U * secondPtrField) noexcept
765 {
766 Payload payload;
767 static_assert(type >= tFirstPairOfPointers && type <= tLastPairOfPointers);
768 {
769 auto firstFieldPayload = std::bit_cast<PackedPointer>(firstPtrField);
770 assertAligned(firstFieldPayload);
771 payload[0] = static_cast<int>(pdPairOfPointers) | firstFieldPayload;
772 }
773 static_assert(tLastPairOfPointers - tFirstPairOfPointers < (1 << discriminatorBits));
774 {
775 auto secondFieldPayload = std::bit_cast<PackedPointer>(secondPtrField);
776 assertAligned(secondFieldPayload);
777 payload[1] = (type - tFirstPairOfPointers) | secondFieldPayload;
778 }
779 updatePayload(payload);
780 }
781
782 template<typename T, typename U>
783 requires std::is_pointer_v<T> && std::is_pointer_v<U>
784 void getPairOfPointersPayload(T & firstPtrField, U & secondPtrField) const noexcept
785 {
786 Payload payload = loadPayload();
787 firstPtrField = untagPointer<T>(payload[0]);
788 secondPtrField = untagPointer<U>(payload[1]);
789 }
790
791public:
792 ValueStorage()
793 {
794 updatePayload({});
795 }
796
797 ValueStorage(const ValueStorage & other)
798 {
799 updatePayload(other.loadPayload());
800 }
801
802 ValueStorage & operator=(const ValueStorage & other)
803 {
804 updatePayload(other.loadPayload());
805 return *this;
806 }
807
808 ValueStorage(ValueStorage && other) noexcept
809 {
810 updatePayload(other.loadPayload());
811 other.updatePayload({}); // Zero out rhs
812 }
813
814 ValueStorage & operator=(ValueStorage && other) noexcept
815 {
816 updatePayload(other.loadPayload());
817 other.updatePayload({}); // Zero out rhs
818 return *this;
819 }
820
821 ~ValueStorage() noexcept {}
822
823protected:
824 static bool isAtomic();
825
828 {
829 Payload payload = loadPayload();
830 switch (auto pd = getPrimaryDiscriminator(payload[0])) {
831 case pdUninitialized:
832 /* Discriminator value of zero is used to distinguish uninitialized values. */
833 return tUninitialized;
834 case pdSingleDWord:
835 /* Payloads that only use up a single double word store the InternalType
836 in the upper bits of the first double word. */
837 return InternalType(payload[0] >> discriminatorBits);
838 /* The order must match that of the enumerations defined in InternalType. */
839 case pdListN:
840 case pdSymbol:
841 return static_cast<InternalType>(tFirstSingleUntaggable + (pd - pdListN));
842 case pdPairOfPointers:
843 return static_cast<InternalType>(tFirstPairOfPointers + (payload[1] & discriminatorMask));
844 [[unlikely]] default:
845 nixUnreachableWhenHardened();
846 }
847 }
848
849#define NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(TYPE, MEMBER_A, MEMBER_B) \
850 \
851 void getStorage(TYPE & val) const noexcept \
852 { \
853 getPairOfPointersPayload(val MEMBER_A, val MEMBER_B); \
854 } \
855 \
856 void setStorage(TYPE val) noexcept \
857 { \
858 setPairOfPointersPayload<detail::payloadTypeToInternalType<TYPE>>(val MEMBER_A, val MEMBER_B); \
859 }
860
861 NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(SmallList, [0], [1])
862 NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(StringWithContext, .str, .context)
863 NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(Path, .accessor, .path)
864 NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(PrimOpApplicationThunk, .left, .right)
865 NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(FunctionApplicationThunk, .left, .right)
866 NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(ClosureThunk, .env, .expr)
867 NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(Lambda, .env, .fun)
868
869#undef NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS
870
871 void getStorage(NixInt & integer) const noexcept
872 {
873 Payload payload = loadPayload();
874 /* PackedPointerType -> int64_t here is well-formed, since the standard requires
875 this conversion to follow 2's complement rules. This is just a no-op. */
876 integer = NixInt(payload[1]);
877 }
878
879 void getStorage(bool & boolean) const noexcept
880 {
881 Payload payload = loadPayload();
882 boolean = payload[1];
883 }
884
885 void getStorage(Null & null) const noexcept {}
886
887 void getStorage(NixFloat & fpoint) const noexcept
888 {
889 Payload payload = loadPayload();
890 fpoint = std::bit_cast<NixFloat>(payload[1]);
891 }
892
893 void getStorage(ExternalValueBase *& external) const noexcept
894 {
895 Payload payload = loadPayload();
896 external = std::bit_cast<ExternalValueBase *>(payload[1]);
897 }
898
899 void getStorage(PrimOp *& primOp) const noexcept
900 {
901 Payload payload = loadPayload();
902 primOp = std::bit_cast<PrimOp *>(payload[1]);
903 }
904
905 void getStorage(const Bindings *& attrs) const noexcept
906 {
907 Payload payload = loadPayload();
908 attrs = std::bit_cast<Bindings *>(payload[1]);
909 }
910
911 void getStorage(List & list) const noexcept
912 {
913 Payload payload = loadPayload();
914 list.elems = untagPointer<decltype(list.elems)>(payload[0]);
915 list.size = payload[1];
916 }
917
918 void getStorage(Symbol & symbol) const noexcept
919 {
920 Payload payload = loadPayload();
921 symbol.str = untagPointer<decltype(symbol.str)>(payload[0]);
922 symbol.symbol = payload[1];
923 }
924
925 void getStorage(Failed *& failed) const noexcept
926 {
927 Payload payload = loadPayload();
928 failed = std::bit_cast<Failed *>(payload[1]);
929 }
930
931 void setStorage(NixInt integer) noexcept
932 {
933 setSingleDWordPayload<tInt>(integer.value);
934 }
935
936 void setStorage(bool boolean) noexcept
937 {
938 setSingleDWordPayload<tBool>(boolean);
939 }
940
941 void setStorage(Null path) noexcept
942 {
943 setSingleDWordPayload<tNull>(0);
944 }
945
946 void setStorage(NixFloat fpoint) noexcept
947 {
948 setSingleDWordPayload<tFloat>(std::bit_cast<PackedPointer>(fpoint));
949 }
950
951 void setStorage(ExternalValueBase * external) noexcept
952 {
953 setSingleDWordPayload<tExternal>(std::bit_cast<PackedPointer>(external));
954 }
955
956 void setStorage(PrimOp * primOp) noexcept
957 {
958 setSingleDWordPayload<tPrimOp>(std::bit_cast<PackedPointer>(primOp));
959 }
960
961 void setStorage(const Bindings * bindings) noexcept
962 {
963 setSingleDWordPayload<tAttrs>(std::bit_cast<PackedPointer>(bindings));
964 }
965
966 void setStorage(List list) noexcept
967 {
968 setUntaggablePayload<pdListN>(list.elems, list.size);
969 }
970
971 void setStorage(Symbol symbol) noexcept
972 {
973 setUntaggablePayload<pdSymbol>(symbol.str, symbol.symbol);
974 }
975
976 void setStorage(Failed * failed) noexcept
977 {
978 setSingleDWordPayload<tFailed>(std::bit_cast<PackedPointer>(failed));
979 }
980};
981
989class ListView
990{
991 using SpanType = std::span<Value * const>;
992 using SmallList = detail::ValueBase::SmallList;
993 using List = detail::ValueBase::List;
994
995 std::variant<SmallList, List> raw;
996
997public:
998 ListView(SmallList list)
999 : raw(list)
1000 {
1001 }
1002
1003 ListView(List list)
1004 : raw(list)
1005 {
1006 }
1007
1008 Value * const * data() const & noexcept
1009 {
1010 return std::visit(
1011 overloaded{
1012 [](const SmallList & list) { return list.data(); }, [](const List & list) { return list.elems; }},
1013 raw);
1014 }
1015
1016 std::size_t size() const noexcept
1017 {
1018 return std::visit(
1019 overloaded{
1020 [](const SmallList & list) -> std::size_t { return list.back() == nullptr ? 1 : 2; },
1021 [](const List & list) -> std::size_t { return list.size; }},
1022 raw);
1023 }
1024
1025 Value * operator[](std::size_t i) const noexcept
1026 {
1027 return data()[i];
1028 }
1029
1030 SpanType span() const &
1031 {
1032 return SpanType(data(), size());
1033 }
1034
1035 /* Ensure that no dangling views can be created accidentally, as that
1036 would lead to hard to diagnose bugs that only affect small lists. */
1037 SpanType span() && = delete;
1038 Value * const * data() && noexcept = delete;
1039
1047 class iterator
1048 {
1049 public:
1050 using value_type = Value *;
1051 using pointer = const value_type *;
1052 using reference = const value_type &;
1053 using difference_type = std::ptrdiff_t;
1054 using iterator_category = std::random_access_iterator_tag;
1055
1056 private:
1057 pointer ptr = nullptr;
1058
1059 friend class ListView;
1060
1061 iterator(pointer ptr)
1062 : ptr(ptr)
1063 {
1064 }
1065
1066 public:
1067 iterator() = default;
1068
1069 reference operator*() const
1070 {
1071 return *ptr;
1072 }
1073
1074 const value_type * operator->() const
1075 {
1076 return ptr;
1077 }
1078
1079 reference operator[](difference_type diff) const
1080 {
1081 return ptr[diff];
1082 }
1083
1084 iterator & operator++()
1085 {
1086 ++ptr;
1087 return *this;
1088 }
1089
1090 iterator operator++(int)
1091 {
1092 pointer tmp = ptr;
1093 ++*this;
1094 return iterator(tmp);
1095 }
1096
1097 iterator & operator--()
1098 {
1099 --ptr;
1100 return *this;
1101 }
1102
1103 iterator operator--(int)
1104 {
1105 pointer tmp = ptr;
1106 --*this;
1107 return iterator(tmp);
1108 }
1109
1110 iterator & operator+=(difference_type diff)
1111 {
1112 ptr += diff;
1113 return *this;
1114 }
1115
1116 iterator operator+(difference_type diff) const
1117 {
1118 return iterator(ptr + diff);
1119 }
1120
1121 friend iterator operator+(difference_type diff, const iterator & rhs)
1122 {
1123 return iterator(diff + rhs.ptr);
1124 }
1125
1126 iterator & operator-=(difference_type diff)
1127 {
1128 ptr -= diff;
1129 return *this;
1130 }
1131
1132 iterator operator-(difference_type diff) const
1133 {
1134 return iterator(ptr - diff);
1135 }
1136
1137 difference_type operator-(const iterator & rhs) const
1138 {
1139 return ptr - rhs.ptr;
1140 }
1141
1142 std::strong_ordering operator<=>(const iterator & rhs) const = default;
1143 };
1144
1145 using const_iterator = iterator;
1146
1147 iterator begin() const &
1148 {
1149 return data();
1150 }
1151
1152 iterator end() const &
1153 {
1154 return data() + size();
1155 }
1156
1157 /* Ensure that no dangling iterators can be created accidentally, as that
1158 would lead to hard to diagnose bugs that only affect small lists. */
1159 iterator begin() && = delete;
1160 iterator end() && = delete;
1161};
1162
1163static_assert(std::random_access_iterator<ListView::iterator>);
1164
1165struct Value : public ValueStorage<sizeof(void *)>
1166{
1167 friend std::string showType(const Value & v);
1168 /* Only the symbol table creates `tSymbol` values. */
1169 friend class SymbolStr;
1170
1177
1183 static Value vNull;
1184
1190 static Value vTrue;
1191
1198
1199private:
1200 template<InternalType... discriminator>
1201 bool isa() const noexcept
1202 {
1203 return ((getInternalType() == discriminator) || ...);
1204 }
1205
1206 template<typename T>
1207 T getStorage() const noexcept
1208 {
1209 if (getInternalType() != detail::payloadTypeToInternalType<T>) [[unlikely]]
1210 nixUnreachableWhenHardened();
1211 T out;
1212 ValueStorage::getStorage(out);
1213 return out;
1214 }
1215
1220 StringWithContext getStringStorage() const noexcept
1221 {
1222 if (isa<tSymbol>()) {
1223 ValueBase::Symbol symbol;
1224 ValueStorage::getStorage(symbol);
1225 return {.str = symbol.str, .context = nullptr};
1226 }
1227 return getStorage<StringWithContext>();
1228 }
1229
1230public:
1231
1235 static Value * toPtr(SymbolStr str) noexcept;
1236
1237 void print(EvalState & state, std::ostream & str, PrintOptions options = PrintOptions{});
1238
1239 // Functions needed to distinguish the type
1240 // These should be removed eventually, by putting the functionality that's
1241 // needed by callers into methods of this type
1242
1243 // type() == nThunk
1244 inline bool isThunk() const
1245 {
1246 return isa<tThunk>();
1247 }
1248
1249 inline bool isApp() const
1250 {
1251 return isa<tApp>();
1252 }
1253
1254 inline bool isBlackhole() const;
1255
1256 // type() == nFunction
1257 inline bool isLambda() const
1258 {
1259 return isa<tLambda>();
1260 }
1261
1262 inline bool isPrimOp() const
1263 {
1264 return isa<tPrimOp>();
1265 }
1266
1267 inline bool isPrimOpApp() const
1268 {
1269 return isa<tPrimOpApp>();
1270 }
1271
1272 inline bool isFailed() const
1273 {
1274 return isa<tFailed>();
1275 }
1276
1284 template<bool invalidIsThunk = false>
1285 inline ValueType type() const
1286 {
1287 /* Explicit lookup table. switch() might compile down (and it does at least with GCC 14)
1288 to a jump table. Let's help the compiler a bit here. */
1289 static constexpr auto table = [] {
1290 std::array<ValueType, tNumberOfInternalTypes> t{};
1291 t[tUninitialized] = nThunk;
1292 t[tInt] = nInt;
1293 t[tBool] = nBool;
1294 t[tNull] = nNull;
1295 t[tFloat] = nFloat;
1296 t[tFailed] = nFailed;
1297 t[tExternal] = nExternal;
1298 t[tAttrs] = nAttrs;
1299 t[tPrimOp] = nFunction;
1300 t[tLambda] = nFunction;
1301 t[tPrimOpApp] = nFunction;
1302 t[tApp] = nThunk;
1303 t[tThunk] = nThunk;
1304 t[tListSmall] = nList;
1305 t[tString] = nString;
1306 t[tPath] = nPath;
1307 t[tListN] = nList;
1308 t[tSymbol] = nString;
1309 return t;
1310 }();
1311
1312 auto it = getInternalType();
1313 if (it == tUninitialized || it >= tNumberOfInternalTypes) [[unlikely]] {
1314 if constexpr (invalidIsThunk)
1315 return nThunk;
1316 else
1317 nixUnreachableWhenHardened();
1318 }
1319
1320 return table[it];
1321 }
1322
1328 inline bool isValid() const noexcept
1329 {
1330 return !isa<tUninitialized>();
1331 }
1332
1338 inline bool isWHNF() const noexcept
1339 {
1340 switch (getInternalType()) {
1341 case tUninitialized:
1342 panic("attempt to use uninitialized Value");
1343 case tFailed:
1344 case tApp:
1345 case tThunk:
1346 return false;
1347 case tInt:
1348 case tBool:
1349 case tNull:
1350 case tFloat:
1351 case tExternal:
1352 case tPrimOp:
1353 case tAttrs:
1354 case tListSmall:
1355 case tString:
1356 case tPath:
1357 case tPrimOpApp: // primop-app is known to be a function, which is WHNF
1358 case tLambda:
1359 case tListN:
1360 case tSymbol:
1361 return true;
1362 case tNumberOfInternalTypes:
1363 unreachable();
1364 }
1365 unreachable();
1366 }
1367
1368 inline void mkInt(NixInt::Inner n) noexcept
1369 {
1370 mkInt(NixInt{n});
1371 }
1372
1373 inline void mkInt(NixInt n) noexcept
1374 {
1375 setStorage(NixInt{n});
1376 }
1377
1378 inline void mkBool(bool b) noexcept
1379 {
1380 setStorage(b);
1381 }
1382
1383 void mkStringNoCopy(const StringData & s, const Value::StringWithContext::Context * context = nullptr) noexcept
1384 {
1385 setStorage(StringWithContext{.str = &s, .context = context});
1386 }
1387
1388 void mkString(std::string_view s, EvalMemory & mem);
1389
1390 void mkString(std::string_view s, const NixStringContext & context, EvalMemory & mem);
1391
1392 void mkStringMove(const StringData & s, const NixStringContext & context, EvalMemory & mem);
1393
1394 void mkPath(const SourcePath & path, EvalMemory & mem);
1395
1396 inline void mkPath(SourceAccessor * accessor, const StringData & path) noexcept
1397 {
1398 setStorage(Path{.accessor = accessor, .path = &path});
1399 }
1400
1401 inline void mkNull() noexcept
1402 {
1403 setStorage(Null{});
1404 }
1405
1406 inline void mkAttrs(const Bindings * a) noexcept
1407 {
1408 setStorage(a);
1409 }
1410
1411 Value & mkAttrs(BindingsBuilder & bindings);
1412
1413 void mkList(const ListBuilder & builder) noexcept
1414 {
1415 switch (builder.size) {
1416 case 0:
1417 setStorage(List{.size = 0, .elems = nullptr});
1418 break;
1419 case 1:
1420 setStorage(std::array<Value *, 2>{builder.inlineElems[0], nullptr});
1421 break;
1422 case 2:
1423 setStorage(std::array<Value *, 2>{builder.inlineElems[0], builder.inlineElems[1]});
1424 break;
1425 default:
1426 setStorage(List{.size = builder.size, .elems = builder.elems});
1427 break;
1428 }
1429 }
1430
1431 inline void mkThunk(Env * e, Expr * ex) noexcept
1432 {
1433 setStorage(ClosureThunk{.env = e, .expr = ex});
1434 }
1435
1436 inline void mkApp(Value * l, Value * r) noexcept
1437 {
1438 setStorage(FunctionApplicationThunk{.left = l, .right = r});
1439 }
1440
1441 inline void mkLambda(Env * e, ExprLambda * f) noexcept
1442 {
1443 setStorage(Lambda{.env = e, .fun = f});
1444 }
1445
1446 inline void mkBlackhole();
1447
1448 void mkPrimOp(PrimOp * p);
1449
1450 inline void mkPrimOpApp(Value * l, Value * r) noexcept
1451 {
1452 setStorage(PrimOpApplicationThunk{.left = l, .right = r});
1453 }
1454
1458 const PrimOp * primOpAppPrimOp() const;
1459
1460 inline void mkExternal(ExternalValueBase * e) noexcept
1461 {
1462 setStorage(e);
1463 }
1464
1465 inline void mkFloat(NixFloat n) noexcept
1466 {
1467 setStorage(n);
1468 }
1469
1470 inline void mkFailed(std::exception_ptr e, Value * recovery) noexcept
1471 {
1472 setStorage(new Value::Failed(e, recovery));
1473 }
1474
1475 bool isList() const noexcept
1476 {
1477 return isa<tListSmall, tListN>();
1478 }
1479
1480 ListView listView() const noexcept
1481 {
1482 return isa<tListSmall>() ? ListView(getStorage<SmallList>()) : ListView(getStorage<List>());
1483 }
1484
1485 size_t listSize() const noexcept
1486 {
1487 return isa<tListSmall>() ? (getStorage<SmallList>()[1] == nullptr ? 1 : 2) : getStorage<List>().size;
1488 }
1489
1490 PosIdx determinePos(const PosIdx pos) const;
1491
1497 bool isTrivial() const;
1498
1499 SourcePath path() const
1500 {
1501 return SourcePath(
1502 ref(pathAccessor()->shared_from_this()), CanonPath(CanonPath::unchecked_t(), std::string(pathStrView())));
1503 }
1504
1505 const StringData & string_data() const noexcept
1506 {
1507 return *getStringStorage().str;
1508 }
1509
1510 const char * c_str() const noexcept
1511 {
1512 return getStringStorage().str->data();
1513 }
1514
1515 std::string_view string_view() const noexcept
1516 {
1517 return string_data().view();
1518 }
1519
1526 nix::Symbol symbol() const noexcept;
1527
1528 const Value::StringWithContext::Context * context() const noexcept
1529 {
1530 return getStringStorage().context;
1531 }
1532
1533 ExternalValueBase * external() const noexcept
1534 {
1535 return getStorage<ExternalValueBase *>();
1536 }
1537
1538 const Bindings * attrs() const noexcept
1539 {
1540 return getStorage<const Bindings *>();
1541 }
1542
1543 const PrimOp * primOp() const noexcept
1544 {
1545 return getStorage<PrimOp *>();
1546 }
1547
1548 bool boolean() const noexcept
1549 {
1550 return getStorage<bool>();
1551 }
1552
1553 NixInt integer() const noexcept
1554 {
1555 return getStorage<NixInt>();
1556 }
1557
1558 NixFloat fpoint() const noexcept
1559 {
1560 return getStorage<NixFloat>();
1561 }
1562
1563 Lambda lambda() const noexcept
1564 {
1565 return getStorage<Lambda>();
1566 }
1567
1568 ClosureThunk thunk() const noexcept
1569 {
1570 return getStorage<ClosureThunk>();
1571 }
1572
1573 PrimOpApplicationThunk primOpApp() const noexcept
1574 {
1575 return getStorage<PrimOpApplicationThunk>();
1576 }
1577
1578 FunctionApplicationThunk app() const noexcept
1579 {
1580 return getStorage<FunctionApplicationThunk>();
1581 }
1582
1583 const char * pathStr() const noexcept
1584 {
1585 return getStorage<Path>().path->c_str();
1586 }
1587
1588 std::string_view pathStrView() const noexcept
1589 {
1590 return getStorage<Path>().path->view();
1591 }
1592
1593 SourceAccessor * pathAccessor() const noexcept
1594 {
1595 return getStorage<Path>().accessor;
1596 }
1597
1598 Failed & failed() const noexcept
1599 {
1600 auto p = getStorage<Failed *>();
1601 assert(p);
1602 return *p;
1603 }
1604};
1605
1606extern ExprBlackHole eBlackHole;
1607
1608bool Value::isBlackhole() const
1609{
1610 return isThunk() && thunk().expr == (Expr *) &eBlackHole;
1611}
1612
1613void Value::mkBlackhole()
1614{
1615 mkThunk(nullptr, (Expr *) &eBlackHole);
1616}
1617
1618typedef std::vector<Value *, traceable_allocator<Value *>> ValueVector;
1619typedef boost::unordered_flat_map<
1620 Symbol,
1621 Value *,
1622 std::hash<Symbol>,
1623 std::equal_to<Symbol>,
1624 traceable_allocator<std::pair<const Symbol, Value *>>>
1625 ValueMap;
1626typedef std::map<Symbol, ValueVector, std::less<Symbol>, traceable_allocator<std::pair<const Symbol, ValueVector>>>
1627 ValueVectorMap;
1628
1632typedef std::shared_ptr<Value *> RootValue;
1633
1634RootValue allocRootValue(Value * v);
1635
1640[[noreturn, gnu::cold, gnu::noinline]] void
1641throwNullByteError(std::string_view s, const PosTable * positions = nullptr, PosIdx pos = noPos);
1642
1648inline void forceNoNullByte(std::string_view s, const PosTable * positions = nullptr, PosIdx pos = noPos)
1649{
1650 if (s.find('\0') != s.npos) [[unlikely]]
1651 throwNullByteError(s, positions, pos);
1652}
1653} // namespace nix
Definition attr-set.hh:448
CanonPath(std::string_view raw)
Definition canon-path.cc:38
Definition eval.hh:347
Definition eval.hh:420
Definition value.hh:116
virtual void printValueAsXML(EvalState &state, bool strict, bool location, XMLWriter &doc, NixStringContext &context, StringSet &drvsSeen, const PosIdx pos) const
Definition value-to-xml.cc:191
virtual nlohmann::json printValueAsJSON(EvalState &state, bool strict, NixStringContext &context, bool copyToStore=true) const
Definition value-to-json.cc:131
virtual std::string showType() const =0
virtual bool operator==(const ExternalValueBase &b) const noexcept
Definition eval.cc:3490
virtual std::string typeOf() const =0
virtual std::ostream & print(std::ostream &str) const =0
virtual std::string coerceToString(EvalState &state, const PosIdx &pos, NixStringContext &context, bool copyMore, bool copyToStore) const
Definition eval.cc:3484
Definition value.hh:1048
Definition pos-idx.hh:10
Definition pos-table.hh:15
Definition value.hh:213
static StringData & alloc(EvalMemory &mem, size_t size)
Definition eval.cc:90
static const StringData & make(EvalMemory &mem, std::string_view s)
Definition eval.cc:98
Definition symbol-table.hh:24
Definition value.hh:551
InternalType getInternalType() const noexcept
Definition value.hh:587
Definition xml-writer.hh:14
Definition fun.hh:19
std::set< NixStringContextElem > NixStringContext
Definition context.hh:103
Options for printing Nix values.
SourcePath.
Definition eval-gc.hh:69
Definition eval-gc.hh:66
Definition eval.hh:197
Definition nixexpr.hh:823
Definition nixexpr.hh:522
Definition nixexpr.hh:100
Definition source-accessor.hh:50
Definition static-string-data.hh:10
Definition value.hh:1166
static Value * toPtr(SymbolStr str) noexcept
Definition eval.cc:134
bool isValid() const noexcept
Definition value.hh:1328
nix::Symbol symbol() const noexcept
Definition symbol-table.hh:69
const PrimOp * primOpAppPrimOp() const
Definition eval.cc:533
static Value vEmptyList
Definition value.hh:1176
static Value vTrue
Definition value.hh:1190
bool isTrivial() const
Definition eval.cc:214
static Value vNull
Definition value.hh:1183
bool isWHNF() const noexcept
Definition value.hh:1338
static Value vFalse
Definition value.hh:1197
ValueType type() const
Definition value.hh:1285
Definition value.hh:469
Value * recoveryValue
Definition value.hh:476
Definition value.hh:430
Definition value.hh:438
Definition value.hh:406
Definition value.hh:400
static Context * fromBuilder(const NixStringContext &context, EvalMemory &mem)
const Context * context
Definition value.hh:396
Definition value.hh:307
Definition value.hh:305
Definition util.hh:444
std::set< std::string, std::less<> > StringSet
Definition types.hh:45
void forceNoNullByte(std::string_view s, const PosTable *positions=nullptr, PosIdx pos=noPos)
Definition value.hh:1648
InternalType
Definition value.hh:44
#define NIX_VALUE_STORAGE_FOR_EACH_FIELD(MACRO)
Definition value.hh:503
ValueType
Definition value.hh:77
std::shared_ptr< Value * > RootValue
Definition value.hh:1632