-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathvalue.hh
More file actions
1622 lines (1375 loc) · 45.8 KB
/
Copy pathvalue.hh
File metadata and controls
1622 lines (1375 loc) · 45.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
///@file
#include <bit>
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <memory_resource>
#include <exception>
#include <span>
#include <string_view>
#include <type_traits>
#include <concepts>
#include "nix/expr/eval-gc.hh"
#include "nix/expr/value/context.hh"
#include "nix/util/source-path.hh"
#include "nix/expr/print-options.hh"
#include "nix/util/checked-arithmetic.hh"
#include <boost/unordered/unordered_flat_map_fwd.hpp>
#include <nlohmann/json_fwd.hpp>
#if defined(__x86_64__) && defined(__SSE2__)
# include <emmintrin.h>
#endif
namespace nix {
struct Value;
class BindingsBuilder;
/**
* Internal type discriminator, which is more detailed than `ValueType`, as
* it specifies the exact representation used (for types that have multiple
* possible representations).
*
* @warning The ordering is very significant. See ValueStorage::getInternalType() for details
* about how this is mapped into the alignment bits to save significant memory.
* This also restricts the number of internal types represented with distinct memory layouts.
*/
enum InternalType {
tUninitialized = 0,
/* layout: Single/zero field payload */
tInt = 1,
tBool,
tNull,
tFloat,
tFailed,
tExternal,
tPrimOp,
tAttrs,
/* layout: Pair of pointers payload */
tFirstPairOfPointers,
tListSmall = tFirstPairOfPointers,
tPrimOpApp,
tApp,
tThunk,
tLambda,
tLastPairOfPointers = tLambda,
/* layout: Single untaggable field */
tFirstSingleUntaggable,
tListN = tFirstSingleUntaggable,
tString,
tPath,
tNumberOfInternalTypes, // Must be last
};
/**
* This type abstracts over all actual value types in the language,
* grouping together implementation details like tList*, different function
* types, and types in non-normal form (so thunks and co.)
*/
typedef enum {
nThunk,
nFailed,
nInt,
nFloat,
nBool,
nString,
nPath,
nNull,
nAttrs,
nList,
nFunction,
nExternal,
} ValueType;
class Bindings;
struct Env;
struct Expr;
struct ExprLambda;
struct ExprBlackHole;
struct PrimOp;
class Symbol;
class SymbolStr;
class PosIdx;
struct Pos;
class StorePath;
class EvalState;
class EvalMemory;
class XMLWriter;
class Printer;
using NixInt = checked::Checked<int64_t>;
using NixFloat = double;
/**
* External values must descend from ExternalValueBase, so that
* type-agnostic nix functions (e.g. showType) can be implemented
*/
class ExternalValueBase
{
friend std::ostream & operator<<(std::ostream & str, const ExternalValueBase & v);
friend class Printer;
protected:
/**
* Print out the value
*/
virtual std::ostream & print(std::ostream & str) const = 0;
public:
/**
* Return a simple string describing the type
*/
virtual std::string showType() const = 0;
/**
* Return a string to be used in builtins.typeOf
*/
virtual std::string typeOf() const = 0;
/**
* Coerce the value to a string. Defaults to uncoercable, i.e. throws an
* error.
*/
virtual std::string coerceToString(
EvalState & state, const PosIdx & pos, NixStringContext & context, bool copyMore, bool copyToStore) const;
/**
* Compare to another value of the same type. Defaults to uncomparable,
* i.e. always false.
*/
virtual bool operator==(const ExternalValueBase & b) const noexcept;
/**
* Print the value as JSON. Defaults to unconvertible, i.e. throws an error
*/
virtual nlohmann::json
printValueAsJSON(EvalState & state, bool strict, NixStringContext & context, bool copyToStore = true) const;
/**
* Print the value as XML. Defaults to unevaluated
*/
virtual void printValueAsXML(
EvalState & state,
bool strict,
bool location,
XMLWriter & doc,
NixStringContext & context,
StringSet & drvsSeen,
const PosIdx pos) const;
virtual ~ExternalValueBase() {};
};
std::ostream & operator<<(std::ostream & str, const ExternalValueBase & v);
class ListBuilder
{
const size_t size;
Value * inlineElems[2] = {nullptr, nullptr};
public:
Value ** elems;
ListBuilder(EvalMemory & mem, size_t size);
ListBuilder(ListBuilder && x) noexcept
: size(x.size)
, inlineElems{x.inlineElems[0], x.inlineElems[1]}
, elems(size <= 2 ? inlineElems : x.elems)
{
}
ListBuilder(const ListBuilder &) = delete;
ListBuilder & operator=(ListBuilder &&) = delete;
ListBuilder & operator=(const ListBuilder &) = delete;
~ListBuilder() = default;
Value *& operator[](size_t n)
{
return elems[n];
}
typedef Value ** iterator;
iterator begin()
{
return &elems[0];
}
iterator end()
{
return &elems[size];
}
friend struct Value;
};
class StringData
{
public:
using size_type = std::size_t;
size_type size_;
char data_[];
/*
* This in particular ensures that we cannot have a `StringData`
* that we use by value, which is just what we want!
*
* Dynamically sized types aren't a thing in C++ and even flexible array
* members are a language extension and beyond the realm of standard C++.
* Technically, sizeof data_ member is 0 and the intended way to use flexible
* array members is to allocate sizeof(StrindData) + count * sizeof(char) bytes
* and the compiler will consider alignment restrictions for the FAM.
*
*/
StringData(StringData &&) = delete;
StringData & operator=(StringData &&) = delete;
StringData(const StringData &) = delete;
StringData & operator=(const StringData &) = delete;
~StringData() = default;
private:
StringData() = delete;
explicit StringData(size_type size)
: size_(size)
{
}
public:
/**
* Allocate StringData on the (possibly) GC-managed heap and copy
* the contents of s to it.
*/
static const StringData & make(EvalMemory & mem, std::string_view s);
/**
* Allocate StringData on the (possibly) GC-managed heap.
* @param size Length of the string (without the NUL terminator).
*/
static StringData & alloc(EvalMemory & mem, size_t size);
size_t size() const
{
return size_;
}
char * data() noexcept
{
return data_;
}
const char * data() const noexcept
{
return data_;
}
const char * c_str() const noexcept
{
return data_;
}
constexpr std::string_view view() const noexcept
{
return std::string_view(data_, size_);
}
template<size_t N>
struct Static;
static StringData & make(std::pmr::memory_resource & resource, std::string_view s)
{
auto & res =
*new (resource.allocate(sizeof(StringData) + s.size() + 1, alignof(StringData))) StringData(s.size());
std::memcpy(res.data_, s.data(), s.size());
res.data_[s.size()] = '\0';
return res;
}
};
namespace detail {
/**
* Implementation mixin class for defining the public types
* In can be inherited from by the actual ValueStorage implementations
* for free due to Empty Base Class Optimization (EBCO).
*/
struct ValueBase
{
/**
* Strings in the evaluator carry a so-called `context` which
* is a list of strings representing store paths. This is to
* allow users to write things like
*
* "--with-freetype2-library=" + freetype + "/lib"
*
* where `freetype` is a derivation (or a source to be copied
* to the store). If we just concatenated the strings without
* keeping track of the referenced store paths, then if the
* string is used as a derivation attribute, the derivation
* will not have the correct dependencies in its inputDrvs and
* inputSrcs.
* The semantics of the context is as follows: when a string
* with context C is used as a derivation attribute, then the
* derivations in C will be added to the inputDrvs of the
* derivation, and the other store paths in C will be added to
* the inputSrcs of the derivations.
* For canonicity, the store paths should be in sorted order.
*/
struct StringWithContext
{
const StringData * str;
/**
* The type of the context itself.
*
* Currently, it is length-prefixed array of pointers to
* null-terminated strings. The strings are specially formatted
* to represent a flattening of the recursive sum type that is a
* context element.
*
* @See NixStringContext for an more easily understood type,
* that of the "builder" for this data structure.
*/
struct Context
{
using value_type = const StringData *;
using size_type = std::size_t;
using iterator = const value_type *;
Context(size_type size)
: size_(size)
{
}
private:
/**
* Number of items in the array
*/
size_type size_;
/**
* @pre must be in sorted order
*/
value_type elems[];
public:
iterator begin() const
{
return elems;
}
iterator end() const
{
return elems + size();
}
size_type size() const
{
return size_;
}
/**
* @return null pointer when context.empty()
*/
static Context * fromBuilder(const NixStringContext & context, EvalMemory & mem);
};
/**
* May be null for a string without context.
*/
const Context * context;
};
struct Path
{
SourceAccessor * accessor;
const StringData * path;
};
struct Null
{};
struct ClosureThunk
{
Env * env;
Expr * expr;
};
struct FunctionApplicationThunk
{
Value *left, *right;
};
/**
* Like FunctionApplicationThunk, but must be a distinct type in order to
* resolve overloads to `tPrimOpApp` instead of `tApp`.
* This type helps with the efficient implementation of arity>=2 primop calls.
*/
struct PrimOpApplicationThunk
{
Value *left, *right;
};
struct Lambda
{
Env * env;
ExprLambda * fun;
};
using SmallList = std::array<Value *, 2>;
struct List
{
size_t size;
Value * const * elems;
};
/**
* Wrapper that stores a std::exception_ptr on the GC heap with a finaliser
* that runs the exception_ptr destructor (which is refcounted internally).
* This is not a part of the Failed structure to avoid cycles with finalisers,
* which Boehm warns about.
*/
struct ExceptionRef : gc_cleanup
{
ExceptionRef(std::exception_ptr ex)
: ex(std::move(ex))
{
assert(this->ex);
}
ExceptionRef(ExceptionRef &&) = delete;
ExceptionRef(const ExceptionRef &) = delete;
ExceptionRef & operator=(ExceptionRef &&) = delete;
ExceptionRef & operator=(const ExceptionRef &) = delete;
/* To appease -Wweak-vtables. */
virtual ~ExceptionRef();
std::exception_ptr ex;
};
struct Failed : gc
{
ExceptionRef * exRef;
/**
* Optional value for recovering `RecoverableEvalError`
* Must be set iff `ex` is an instance of `RecoverableEvalError`.
*/
Value * recoveryValue;
Failed(std::exception_ptr ex, Value * recoveryValue)
: exRef(new /* ExceptionRef : gc_cleanup */ ExceptionRef(ex))
, recoveryValue(recoveryValue)
{
}
[[noreturn]] void rethrow() const
{
try {
std::rethrow_exception(exRef->ex);
} catch (BaseError & e) {
/* Rethrow the copy of the exception - not the original one.
Stack tracing mechanisms rely on being able to modify the exceptions
they catch by reference. */
e.throwClone();
} catch (...) {
throw;
}
unreachable();
}
};
};
template<typename T>
struct PayloadTypeToInternalType
{};
/**
* All stored types must be distinct (not type aliases) for the purposes of
* overload resolution in setStorage. This ensures there's a bijection from
* InternalType <-> C++ type.
*/
#define NIX_VALUE_STORAGE_FOR_EACH_FIELD(MACRO) \
MACRO(NixInt, integer, tInt) \
MACRO(bool, boolean, tBool) \
MACRO(ValueBase::StringWithContext, string, tString) \
MACRO(ValueBase::Path, path, tPath) \
MACRO(ValueBase::Null, null_, tNull) \
MACRO(const Bindings *, attrs, tAttrs) \
MACRO(ValueBase::List, bigList, tListN) \
MACRO(ValueBase::SmallList, smallList, tListSmall) \
MACRO(ValueBase::ClosureThunk, thunk, tThunk) \
MACRO(ValueBase::FunctionApplicationThunk, app, tApp) \
MACRO(ValueBase::Lambda, lambda, tLambda) \
MACRO(PrimOp *, primOp, tPrimOp) \
MACRO(ValueBase::PrimOpApplicationThunk, primOpApp, tPrimOpApp) \
MACRO(ExternalValueBase *, external, tExternal) \
MACRO(ValueBase::Failed *, failed, tFailed) \
MACRO(NixFloat, fpoint, tFloat)
#define NIX_VALUE_PAYLOAD_TYPE(T, FIELD_NAME, DISCRIMINATOR) \
template<> \
struct PayloadTypeToInternalType<T> \
{ \
static constexpr InternalType value = DISCRIMINATOR; \
};
NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_PAYLOAD_TYPE)
#undef NIX_VALUE_PAYLOAD_TYPE
template<typename T>
inline constexpr InternalType payloadTypeToInternalType = PayloadTypeToInternalType<T>::value;
} // namespace detail
/**
* Discriminated union of types stored in the value.
* The union discriminator is @ref InternalType enumeration.
*
* This class can be specialized with a non-type template parameter
* of pointer size for more optimized data layouts on when pointer alignment
* bits can be used for storing the discriminator.
*
* All specializations of this type need to implement getStorage, setStorage and
* getInternalType methods.
*/
template<std::size_t ptrSize, typename Enable = void>
class ValueStorage : public detail::ValueBase
{
protected:
using Payload = union
{
#define NIX_VALUE_STORAGE_DEFINE_FIELD(T, FIELD_NAME, DISCRIMINATOR) T FIELD_NAME;
NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_STORAGE_DEFINE_FIELD)
#undef NIX_VALUE_STORAGE_DEFINE_FIELD
};
private:
InternalType internalType = tUninitialized;
Payload payload;
protected:
#define NIX_VALUE_STORAGE_GET_IMPL(K, FIELD_NAME, DISCRIMINATOR) \
void getStorage(K & val) const noexcept \
{ \
assert(internalType == DISCRIMINATOR); \
val = payload.FIELD_NAME; \
}
#define NIX_VALUE_STORAGE_SET_IMPL(K, FIELD_NAME, DISCRIMINATOR) \
void setStorage(K val) noexcept \
{ \
payload.FIELD_NAME = val; \
internalType = DISCRIMINATOR; \
}
NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_STORAGE_GET_IMPL)
NIX_VALUE_STORAGE_FOR_EACH_FIELD(NIX_VALUE_STORAGE_SET_IMPL)
#undef NIX_VALUE_STORAGE_SET_IMPL
#undef NIX_VALUE_STORAGE_GET_IMPL
#undef NIX_VALUE_STORAGE_FOR_EACH_FIELD
/** Get internal type currently occupying the storage. */
InternalType getInternalType() const noexcept
{
return internalType;
}
static bool isAtomic()
{
return false;
}
};
namespace detail {
/* Whether to use a specialization of ValueStorage that does bitpacking into
alignment niches. */
template<std::size_t ptrSize>
inline constexpr bool useBitPackedValueStorage = (ptrSize == 8) && (__STDCPP_DEFAULT_NEW_ALIGNMENT__ >= 16);
} // namespace detail
/**
* Value storage that is optimized for 64 bit systems.
* Packs discriminator bits into the pointer alignment niches.
*/
template<std::size_t ptrSize>
class alignas(16)
ValueStorage<ptrSize, std::enable_if_t<detail::useBitPackedValueStorage<ptrSize>>> : public detail::ValueBase
{
/* Needs a dependent type name in order for member functions (and
* potentially ill-formed bit casts) to be SFINAE'd out.
*
* Otherwise some member functions could possibly be instantiated for 32 bit
* systems and fail due to an unsatisfied constraint.
*/
template<std::size_t size>
struct PackedPointerTypeStruct
{
using type = std::uint64_t;
};
using PackedPointer = typename PackedPointerTypeStruct<ptrSize>::type;
using Payload = std::array<PackedPointer, 2>;
#if defined(__x86_64__) && defined(__SSE2__)
__m128i payloadWords;
#else
Payload payloadWords = {};
#endif
static constexpr int discriminatorBits = 3;
static constexpr PackedPointer discriminatorMask = (PackedPointer(1) << discriminatorBits) - 1;
/**
* The value is stored as a pair of 8-byte double words. All pointers are assumed
* to be 8-byte aligned. This gives us at most 6 bits of discriminator bits
* of free storage. In some cases when one double word can't be tagged the whole
* discriminator is stored in the first double word.
*
* The layout of discriminator bits is determined by the 3 bits of PrimaryDiscriminator,
* which are always stored in the lower 3 bits of the first dword of the payload.
* The memory layout has 3 types depending on the PrimaryDiscriminator value.
*
* PrimaryDiscriminator::pdSingleDWord - Only the second dword carries the data.
* That leaves the first 8 bytes free for storing the InternalType in the upper
* bits.
*
* PrimaryDiscriminator::pdListN - pdPath - Only has 3 available padding bits
* because:
* - tListN needs a size, whose lower bits we can't borrow.
* - tString and tPath have C-string fields, which don't necessarily need to
* be aligned.
*
* In this case we reserve their discriminators directly in the PrimaryDiscriminator
* bits stored in payload[0].
*
* PrimaryDiscriminator::pdPairOfPointers - Payloads that consist of a pair of pointers.
* In this case the 3 lower bits of payload[1] can be tagged.
*
* The primary discriminator with value 0 is reserved for uninitialized Values,
* which are useful for diagnostics in C bindings.
*/
enum PrimaryDiscriminator : int {
pdUninitialized = 0,
pdSingleDWord, //< layout: Single/zero field payload
/* The order of these enumerations must be the same as in InternalType. */
pdListN, //< layout: Single untaggable field.
pdString,
pdPath,
pdPairOfPointers, //< layout: Pair of pointers payload
};
#if defined(__x86_64__) && defined(__SSE2__)
/* Why do we even bother with hand-rolling these arch-specific intrinsics
* and don't use libatomic directly for 16 byte atomics? Here's why:
* - https://gcc.gnu.org/legacy-ml/gcc/2018-02/msg00224.html
* - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84563
*
* Basically, we don't really ever want to go through libatomic. As is
* so happens on x86_64 with AVX, MOVDQA/MOVAPS instructions (16-byte aligned
* 128-bit loads and stores) are atomic [^]. Note that
* these instructions are not part of AVX but rather SSE2, which is x86_64-v1.
* They are just not guaranteed to be atomic without AVX.
*
* For more details see:
* - [^] Intel® 64 and IA-32 Architectures Software Developer’s Manual (10.1.1 Guaranteed Atomic Operations).
* - https://patchwork.sourceware.org/project/gcc/patch/YhxkfzGEEQ9KHbBC@tucnak/
* - https://ibraheem.ca/posts/128-bit-atomics/
* - https://rigtorp.se/isatomic/
*/
[[gnu::always_inline]]
void updatePayload(Payload payload) noexcept
{
/* This intrinsic corresponds to MOVAPS. Note that Value (and thus the first member
payloadWords) is 16 bytes aligned. */
_mm_store_si128(&payloadWords, std::bit_cast<__m128i>(payload));
}
[[gnu::always_inline]]
Payload loadPayload() const noexcept
{
/* This intrinsic corresponds to MOVDQA. Note that Value (and thus the first member
payloadWords) is 16 bytes aligned. */
__m128i res = _mm_load_si128(&payloadWords);
return std::bit_cast<Payload>(res);
}
#else
[[gnu::always_inline]]
void updatePayload(Payload payload) noexcept
{
payloadWords = payload;
}
[[gnu::always_inline]]
Payload loadPayload() const noexcept
{
return payloadWords;
}
#endif
template<typename T>
requires std::is_pointer_v<T>
static T untagPointer(PackedPointer val) noexcept
{
return std::bit_cast<T>(val & ~discriminatorMask);
}
PrimaryDiscriminator getPrimaryDiscriminator(PackedPointer firstDWord) const noexcept
{
return static_cast<PrimaryDiscriminator>(firstDWord & discriminatorMask);
}
static void assertAligned(PackedPointer val) noexcept
{
assert((val & discriminatorMask) == 0 && "Pointer is not 8 bytes aligned");
}
template<InternalType type>
void setSingleDWordPayload(PackedPointer untaggedVal) noexcept
{
Payload payload;
/* There's plenty of free upper bits in the first dword, which is
used only for the discriminator. */
payload[0] = static_cast<int>(pdSingleDWord) | (static_cast<int>(type) << discriminatorBits);
payload[1] = untaggedVal;
updatePayload(payload);
}
template<PrimaryDiscriminator discriminator, typename T, typename U>
void setUntaggablePayload(T * firstPtrField, U untaggableField) noexcept
{
Payload payload;
static_assert(discriminator >= pdListN && discriminator <= pdPath);
auto firstFieldPayload = std::bit_cast<PackedPointer>(firstPtrField);
assertAligned(firstFieldPayload);
payload[0] = static_cast<int>(discriminator) | firstFieldPayload;
payload[1] = std::bit_cast<PackedPointer>(untaggableField);
updatePayload(payload);
}
template<InternalType type, typename T, typename U>
void setPairOfPointersPayload(T * firstPtrField, U * secondPtrField) noexcept
{
Payload payload;
static_assert(type >= tFirstPairOfPointers && type <= tLastPairOfPointers);
{
auto firstFieldPayload = std::bit_cast<PackedPointer>(firstPtrField);
assertAligned(firstFieldPayload);
payload[0] = static_cast<int>(pdPairOfPointers) | firstFieldPayload;
}
{
auto secondFieldPayload = std::bit_cast<PackedPointer>(secondPtrField);
assertAligned(secondFieldPayload);
payload[1] = (type - tFirstPairOfPointers) | secondFieldPayload;
}
updatePayload(payload);
}
template<typename T, typename U>
requires std::is_pointer_v<T> && std::is_pointer_v<U>
void getPairOfPointersPayload(T & firstPtrField, U & secondPtrField) const noexcept
{
Payload payload = loadPayload();
firstPtrField = untagPointer<T>(payload[0]);
secondPtrField = untagPointer<U>(payload[1]);
}
public:
ValueStorage()
{
updatePayload({});
}
ValueStorage(const ValueStorage & other)
{
updatePayload(other.loadPayload());
}
ValueStorage & operator=(const ValueStorage & other)
{
updatePayload(other.loadPayload());
return *this;
}
ValueStorage(ValueStorage && other) noexcept
{
updatePayload(other.loadPayload());
other.updatePayload({}); // Zero out rhs
}
ValueStorage & operator=(ValueStorage && other) noexcept
{
updatePayload(other.loadPayload());
other.updatePayload({}); // Zero out rhs
return *this;
}
~ValueStorage() noexcept {}
protected:
static bool isAtomic();
/** Get internal type currently occupying the storage. */
InternalType getInternalType() const noexcept
{
Payload payload = loadPayload();
switch (auto pd = getPrimaryDiscriminator(payload[0])) {
case pdUninitialized:
/* Discriminator value of zero is used to distinguish uninitialized values. */
return tUninitialized;
case pdSingleDWord:
/* Payloads that only use up a single double word store the InternalType
in the upper bits of the first double word. */
return InternalType(payload[0] >> discriminatorBits);
/* The order must match that of the enumerations defined in InternalType. */
case pdListN:
case pdString:
case pdPath:
return static_cast<InternalType>(tFirstSingleUntaggable + (pd - pdListN));
case pdPairOfPointers:
return static_cast<InternalType>(tFirstPairOfPointers + (payload[1] & discriminatorMask));
[[unlikely]] default:
nixUnreachableWhenHardened();
}
}
#define NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(TYPE, MEMBER_A, MEMBER_B) \
\
void getStorage(TYPE & val) const noexcept \
{ \
getPairOfPointersPayload(val MEMBER_A, val MEMBER_B); \
} \
\
void setStorage(TYPE val) noexcept \
{ \
setPairOfPointersPayload<detail::payloadTypeToInternalType<TYPE>>(val MEMBER_A, val MEMBER_B); \
}
NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(SmallList, [0], [1])
NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(PrimOpApplicationThunk, .left, .right)
NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(FunctionApplicationThunk, .left, .right)
NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(ClosureThunk, .env, .expr)
NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS(Lambda, .env, .fun)
#undef NIX_VALUE_STORAGE_DEF_PAIR_OF_PTRS
void getStorage(NixInt & integer) const noexcept
{
Payload payload = loadPayload();
/* PackedPointerType -> int64_t here is well-formed, since the standard requires
this conversion to follow 2's complement rules. This is just a no-op. */
integer = NixInt(payload[1]);
}
void getStorage(bool & boolean) const noexcept
{
Payload payload = loadPayload();
boolean = payload[1];
}
void getStorage(Null & null) const noexcept {}
void getStorage(NixFloat & fpoint) const noexcept
{
Payload payload = loadPayload();
fpoint = std::bit_cast<NixFloat>(payload[1]);
}
void getStorage(ExternalValueBase *& external) const noexcept
{
Payload payload = loadPayload();
external = std::bit_cast<ExternalValueBase *>(payload[1]);
}
void getStorage(PrimOp *& primOp) const noexcept
{
Payload payload = loadPayload();
primOp = std::bit_cast<PrimOp *>(payload[1]);
}
void getStorage(const Bindings *& attrs) const noexcept
{
Payload payload = loadPayload();
attrs = std::bit_cast<Bindings *>(payload[1]);
}
void getStorage(List & list) const noexcept
{
Payload payload = loadPayload();
list.elems = untagPointer<decltype(list.elems)>(payload[0]);
list.size = payload[1];
}
void getStorage(StringWithContext & string) const noexcept
{
Payload payload = loadPayload();
string.context = untagPointer<decltype(string.context)>(payload[0]);
string.str = std::bit_cast<const StringData *>(payload[1]);
}
void getStorage(Path & path) const noexcept
{
Payload payload = loadPayload();
path.accessor = untagPointer<decltype(path.accessor)>(payload[0]);
path.path = std::bit_cast<const StringData *>(payload[1]);
}
void getStorage(Failed *& failed) const noexcept
{
Payload payload = loadPayload();
failed = std::bit_cast<Failed *>(payload[1]);
}
void setStorage(NixInt integer) noexcept
{
setSingleDWordPayload<tInt>(integer.value);
}
void setStorage(bool boolean) noexcept
{
setSingleDWordPayload<tBool>(boolean);
}
void setStorage(Null path) noexcept
{
setSingleDWordPayload<tNull>(0);
}
void setStorage(NixFloat fpoint) noexcept
{
setSingleDWordPayload<tFloat>(std::bit_cast<PackedPointer>(fpoint));
}
void setStorage(ExternalValueBase * external) noexcept
{
setSingleDWordPayload<tExternal>(std::bit_cast<PackedPointer>(external));
}
void setStorage(PrimOp * primOp) noexcept
{
setSingleDWordPayload<tPrimOp>(std::bit_cast<PackedPointer>(primOp));
}
void setStorage(const Bindings * bindings) noexcept
{
setSingleDWordPayload<tAttrs>(std::bit_cast<PackedPointer>(bindings));
}
void setStorage(List list) noexcept
{
setUntaggablePayload<pdListN>(list.elems, list.size);
}
void setStorage(StringWithContext string) noexcept
{
setUntaggablePayload<pdString>(string.context, string.str);
}
void setStorage(Path path) noexcept
{
setUntaggablePayload<pdPath>(path.accessor, path.path);
}
void setStorage(Failed * failed) noexcept
{
setSingleDWordPayload<tFailed>(std::bit_cast<PackedPointer>(failed));
}
};
/**
* View into a list of Value * that is itself immutable.
*
* Since not all representations of ValueStorage can provide
* a pointer to a const array of Value * this proxy class either
* stores the small list inline or points to the big list.
*/