Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
eval-inline.hh
Go to the documentation of this file.
1#pragma once
3
4#include "nix/expr/print.hh"
5#include "nix/expr/eval.hh"
6#include "nix/expr/eval-error.hh"
8#include <exception>
9
10namespace nix {
11
15[[gnu::always_inline]]
16inline void * EvalMemory::allocBytes(size_t n)
17{
18 void * p;
19#if NIX_USE_BOEHMGC
20 p = GC_MALLOC(n);
21#else
22 p = calloc(n, 1);
23#endif
24 if (!p)
25 throw std::bad_alloc();
26 return p;
27}
28
29namespace detail {
30
35template<typename T, std::size_t N>
36[[gnu::always_inline]]
37inline size_t checkedAllocSize(size_t count)
38{
39 size_t res = 0;
40
41 if (__builtin_mul_overflow(count, sizeof(T), &res)) [[unlikely]]
42 throw std::bad_alloc();
43
44 if (__builtin_add_overflow(res, N, &res)) [[unlikely]]
45 throw std::bad_alloc();
46
47 return res;
48}
49
50} // namespace detail
51
52template<typename T, std::size_t N>
53[[gnu::always_inline]]
54inline void * EvalMemory::allocBytes(size_t count)
55{
57}
58
59[[gnu::always_inline]]
60inline void * EvalMemory::allocBytesAtomic(size_t n)
61{
62 void * p = GC_MALLOC_ATOMIC(n);
63 if (!p)
64 throw std::bad_alloc();
65 return p;
66}
67
68template<typename T, std::size_t N>
69[[gnu::always_inline]]
70inline void * EvalMemory::allocBytesAtomic(size_t count)
71{
73}
74
75[[gnu::always_inline]]
76Value * EvalMemory::allocValue()
77{
78#if NIX_USE_BOEHMGC
79 /* Allocation cache for GC'd Value objects. Boehm GC is already a global resource, so thread_local is
80 a natural solution. Multiple EvalState instances on the same thread will reuse the same cache. */
81 static thread_local std::shared_ptr<void *> valueAllocCache{
82 std::allocate_shared<void *>(traceable_allocator<void *>(), nullptr)};
83
84 /* We use the boehm batch allocator to speed up allocations of Values (of which there are many).
85 GC_malloc_many returns a linked list of objects of the given size, where the first word
86 of each object is also the pointer to the next object in the list. This also means that we
87 have to explicitly clear the first word of every object we take. */
88 if (!*valueAllocCache) {
89 *valueAllocCache = GC_malloc_many(sizeof(Value));
90 if (!*valueAllocCache)
91 throw std::bad_alloc();
92 }
93
94 /* GC_NEXT is a convenience macro for accessing the first word of an object.
95 Take the first list item, advance the list to the next item, and clear the next pointer. */
96 void * p = *valueAllocCache;
97 *valueAllocCache = GC_NEXT(p);
98 GC_NEXT(p) = nullptr;
99#else
100 void * p = allocBytes(sizeof(Value));
101#endif
102
103 stats.nrValues++;
104 return (Value *) p;
105}
106
107[[gnu::always_inline]]
108Env & EvalMemory::allocEnv(size_t size)
109{
110 stats.nrEnvs++;
111 stats.nrValuesInEnvs += size;
112
113 Env * env;
114
115#if NIX_USE_BOEHMGC
116 if (size == 1) {
117 /* Allocation cache for size-1 Env objects. Boehm GC is already a global resource, so thread_local is
118 a natural solution. Multiple EvalState instances on the same thread will reuse the same cache. */
119 static thread_local std::shared_ptr<void *> env1AllocCache{
120 std::allocate_shared<void *>(traceable_allocator<void *>(), nullptr)};
121 /* see allocValue for explanations. */
122 if (!*env1AllocCache) {
123 *env1AllocCache = GC_malloc_many(sizeof(Env) + sizeof(Value *));
124 if (!*env1AllocCache)
125 throw std::bad_alloc();
126 }
127
128 void * p = *env1AllocCache;
129 *env1AllocCache = GC_NEXT(p);
130 GC_NEXT(p) = nullptr;
131 env = (Env *) p;
132 } else
133#endif
134 env = (Env *) allocBytes<Value *, sizeof(Env)>(size);
135
136 /* We assume that env->values has been cleared by the allocator; maybeThunk() and lookupVar fromWith expect this. */
137
138 return *env;
139}
140
141[[gnu::always_inline]]
142void EvalState::forceValue(Value & v, const PosIdx pos)
143{
144 if (v.isThunk()) {
145 Env * env = v.thunk().env;
146 assert(env || v.isBlackhole());
147 Expr * expr = v.thunk().expr;
148 try {
149 v.mkBlackhole();
150 if (env) [[likely]]
151 expr->eval(*this, *env, v);
152 else
153 ExprBlackHole::throwInfiniteRecursionError(*this, v);
154 } catch (...) {
155 handleEvalExceptionForThunk(env, expr, v, pos);
156 throw;
157 }
158 } else if (v.isApp()) {
159 Value savedApp = v;
160 try {
161 callFunction(*v.app().left, *v.app().right, v, pos);
162 } catch (...) {
163 handleEvalExceptionForApp(v, savedApp);
164 throw;
165 }
166 } else if (v.isFailed()) {
167 handleEvalFailed(v, pos);
168 }
169}
170
171[[gnu::always_inline]]
172inline void EvalState::forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx)
173{
174 forceAttrs(v, [&]() { return pos; }, errorCtx);
175}
176
177template<typename Callable>
178[[gnu::always_inline]]
179inline void EvalState::forceAttrs(Value & v, Callable getPos, std::string_view errorCtx)
180{
181 PosIdx pos = getPos();
182 forceValue(v, pos);
183 if (v.type() != nAttrs) {
184 error<TypeError>("expected a set but found %1%: %2%", showType(v), ValuePrinter(*this, v, errorPrintOptions))
185 .withTrace(pos, errorCtx)
186 .debugThrow();
187 }
188}
189
190[[gnu::always_inline]]
191inline void EvalState::forceList(Value & v, const PosIdx pos, std::string_view errorCtx)
192{
193 forceValue(v, pos);
194 if (!v.isList()) {
195 error<TypeError>("expected a list but found %1%: %2%", showType(v), ValuePrinter(*this, v, errorPrintOptions))
196 .withTrace(pos, errorCtx)
197 .debugThrow();
198 }
199}
200
201[[gnu::always_inline]]
203{
204 if (callDepth > settings.maxCallDepth)
205 error<StackOverflowError>().atPos(pos).debugThrow();
206
207 return CallDepth(callDepth);
208};
209
210template<typename Cb>
211std::invoke_result_t<Cb, Value *, bool>
212EvalState::peelToStringOutPath(const PosIdx pos, Value & v, bool checkToStringReturn, Cb && cb)
213{
214 using R = std::invoke_result_t<Cb, Value *, bool>;
215 bool cameThroughToString = false;
216
217 auto peel = [&, &state = *this](this const auto & peel, const PosIdx pos, Value & v) -> R {
218 state.forceValue(v, pos);
219 auto vType = v.type();
220 if (vType != nAttrs) {
221 /* Trivially string-coercible types (i.e. coerceMore = false compatible)
222 get to return happily.
223 String and path terminate happily. External needs to be handled
224 by caller. E.g. `printValueAsJSON` routes to `ExternalValueBase::printValueAsJSON`,
225 `coerceToString` to `ExternalValueBase::coerceToString`).
226 Everything else violates the "`__toString` returns a
227 string" contract.
228 */
229 if (checkToStringReturn && cameThroughToString && vType != nString && vType != nPath && vType != nExternal)
230 state
231 .error<TypeError>(
232 "`__toString` should return a string, but got %1%: %2%",
233 showType(v),
234 ValuePrinter(state, v, errorPrintOptions))
235 .atPos(pos)
236 .debugThrow();
237 return std::forward<Cb>(cb)(&v, cameThroughToString);
238 }
239 if (auto i = v.attrs()->get(state.s.toString)) {
240 Value & v1 = *state.allocValue();
241 try {
242 state.callFunction(*i->value, v, v1, i->pos);
243 } catch (Error & e) {
244 e.addTrace(state.positions[i->pos], "while calling the `__toString` attribute");
245 throw;
246 }
247 cameThroughToString = true;
248 try {
249 auto _level = state.addCallDepth(pos);
250 return peel(i->pos, v1);
251 } catch (Error & e) {
252 e.addTrace(
253 state.positions[i->pos], "while %s the result of the `__toString` attribute", WhileTryingToUse{v1});
254 throw;
255 }
256 }
257 if (auto i = v.attrs()->get(state.s.outPath)) {
258 try {
259 state.forceValue(*i->value, i->pos);
260 auto _level = state.addCallDepth(pos);
261 return peel(i->pos, *i->value);
262 } catch (Error & e) {
263 e.addTrace(state.positions[i->pos], "while %s the `outPath` attribute", WhileTryingToUse{*i->value});
264 throw;
265 }
266 }
267 /* Can't peel more. (no `__toString`, no `outPath`).
268 If we came through a `__toString` call at any depth, this violates
269 the string-return contract. (usually not enforced) */
270 if (checkToStringReturn && cameThroughToString)
271 state
272 .error<TypeError>(
273 "`__toString` must return a string, but got %1%: %2%",
274 showType(v),
275 ValuePrinter(state, v, errorPrintOptions))
276 .atPos(pos)
277 .debugThrow();
278 return std::forward<Cb>(cb)(&v, cameThroughToString);
279 };
280 return peel(pos, v);
281}
282
283} // namespace nix
void addTrace(std::shared_ptr< const Pos > &&pos, std::string_view fs, Args &&... args)
Definition error.hh:238
const Attr * get(Symbol name) const noexcept
Definition attr-set.hh:357
Definition eval.hh:64
Definition error.hh:310
void * allocBytes(size_t n)
Definition eval-inline.hh:16
void * allocBytesAtomic(size_t n)
Definition eval-inline.hh:60
void forceValue(Value &v, const PosIdx pos)
Definition eval-inline.hh:142
auto peelToStringOutPath(const PosIdx pos, Value &v, bool checkToStringReturn, Cb &&cb) -> std::invoke_result_t< Cb, Value *, bool >
Definition eval-inline.hh:212
CallDepth addCallDepth(const PosIdx pos)
Definition eval-inline.hh:202
Definition pos-idx.hh:10
Definition print.hh:80
size_t checkedAllocSize(size_t count)
Definition eval-inline.hh:37
Common printing functions for the Nix language.
Definition eval.hh:197
Definition nixexpr.hh:100
virtual void eval(EvalState &state, Env &env, Value &v)
Definition eval.cc:1258
Definition value.hh:1166
ValueType type() const
Definition value.hh:1285
Definition eval.hh:225