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
#pragma once
///@file

#include "lix/libexpr/print.hh"
#include "lix/libexpr/eval.hh"
#include "lix/libexpr/eval-error.hh"
#include "lix/libexpr/gc-alloc.hh"
#include "value.hh"

namespace nix {

inline Value::Value(app_t, EvalMemory & mem, Value & lhs, Value & rhs)
{
    auto app = static_cast<Value::App *>(mem.allocBytes(sizeof(Value::App) + sizeof(Value *)));
    app->_left = lhs;
    app->_n = 1;
    app->_args[0] = rhs;
    raw = tag(tApp, app);
}

inline Value::Value(app_t, EvalMemory & mem, Value & lhs, std::span<Value> args)
    : Value(app_t{}, mem, lhs, args, {})
{
}

inline Value::Value(
    app_t, EvalMemory & mem, const Value & lhs, std::span<Value> baseArgs, std::span<Value> moreArgs
)
{
    auto app = static_cast<Value::App *>(
        mem.allocBytes(sizeof(Value::App) + baseArgs.size_bytes() + moreArgs.size_bytes())
    );
    app->_left = lhs;
    app->_n = baseArgs.size() + moreArgs.size();
    std::copy(baseArgs.begin(), baseArgs.end(), app->_args);
    std::copy(moreArgs.begin(), moreArgs.end(), app->_args + baseArgs.size());
    raw = tag(tApp, app);
}

inline Value::Value(thunk_t, EvalMemory & mem, Env & env, Expr & expr)
{
    auto thunk = mem.allocType<Thunk>();
    *thunk = {._env = &env, .expr = &expr};
    raw = tag(tThunk, thunk);
}

inline Value::Value(lambda_t, EvalMemory & mem, Env & env, ExprLambda & lambda)
{
    auto lp = mem.allocType<Lambda>();
    new (lp) Lambda{env, lambda};
    raw = tag(tAuxiliary, lp);
}

[[gnu::always_inline]]
void * EvalMemory::allocBytes(size_t size)
{
#if HAVE_BOEHMGC
    /* We use the boehm batch allocator to speed up allocations of Values (of which there are many).
       GC_malloc_many returns a linked list of objects of the given size, where the first word
       of each object is also the pointer to the next object in the list. This also means that we
       have to explicitly clear the first word of every object we take. */
    // NOTE: we purposely do not allocate 0 byte blocks on caches; we never allocate
    // zero bytes anyway, and it makes cache index calculation a little bit simpler.
    const auto cacheIdx = (size - 1) / CACHE_INCREMENT;
    if (cacheIdx < CACHES) {
        const auto roundedSize = (cacheIdx + 1) * CACHE_INCREMENT;
        auto & cache = gcCache[cacheIdx];
        if (!cache) {
            cache = GC_malloc_many(roundedSize);
            if (!cache) {
                throw std::bad_alloc();
            }
        }

        /* GC_NEXT is a convenience macro for accessing the first word of an object.
           Take the first list item, advance the list to the next item, and clear the next pointer.
         */
        void * p = cache;
        cache = GC_NEXT(p);
        GC_NEXT(p) = nullptr;
        return p;
    }
#endif

    return gcAllocBytes(size);
}

/// `gcAllocType`, but using allocation caches to amortize allocation overhead.
template<typename T>
[[gnu::always_inline]]
T * EvalMemory::allocType(size_t n)
{
    // NOLINTNEXTLINE(bugprone-sizeof-expression)
    return static_cast<T *>(allocBytes(checkedArrayAllocSize(sizeof(T), n)));
}

[[gnu::always_inline]]
Env & EvalMemory::allocEnv(size_t size)
{
    static_assert(CACHES * CACHE_INCREMENT >= sizeof(Env) + sizeof(Value *));

    stats.nrEnvs++;
    stats.nrValuesInEnvs += size;

    Env * env = static_cast<Env *>(allocBytes(sizeof(Env) + size * sizeof(Value *)));

    /* We assume that env->values has been cleared by the allocator; maybeThunk() and lookupVar fromWith expect this. */

    return *env;
}

/* The overloaded versions of `checkType` exist because of non-unified error handling
 * The variant which takes an Expression is required because of debug frames (`withFrames`).
 * Ideally, at some point in the future, we'd implement debug frames that are not tied to the expression and
 * env and then unify both `checkType` functions into one. Then the argument forwarding overloading hack done
 * for the other functions below will be removable again.
 */
[[gnu::always_inline]]
void EvalState::checkType(Value & v, ValueType vType, Env & env, Expr & e)
{
    if (v.type() != vType) {
        ctx.errors
            .make<TypeError>(
                "expected %1% but found %2%: %3%",
                Uncolored(vType),
                showType(v),
                ValuePrinter(*this, v, errorPrintOptions)
            )
            .atPos(e.getPos())
            .withFrame(env, e)
            .debugThrow();
    }
}

[[gnu::always_inline]]
void EvalState::checkType(Value & v, ValueType vType)
{
    if (v.type() != vType) {
        ctx.errors
            .make<TypeError>(
                "expected %1% but found %2%: %3%",
                Uncolored(vType),
                showType(v),
                ValuePrinter(*this, v, errorPrintOptions)
            )
            .debugThrow();
    }
}

template<typename... Args>
[[gnu::always_inline]]
bool EvalState::checkBool(Value & v, Args &&... errorArgs)
{
    checkType(v, nBool, std::forward<Args>(errorArgs)...);
    return v.boolean();
}

template<typename... Args>
[[gnu::always_inline]]
NixInt EvalState::checkInt(Value & v, Args &&... errorArgs)
{
    checkType(v, nInt, std::forward<Args>(errorArgs)...);
    return v.integer();
}

template<typename... Args>
[[gnu::always_inline]]
NixFloat EvalState::checkFloat(Value & v, Args &&... errorArgs)
{
    if (v.type() == nInt) {
        return v.integer().value;
    }
    checkType(v, nFloat, std::forward<Args>(errorArgs)...);
    return v.fpoint();
}

template<typename... Args>
[[gnu::always_inline]]
void EvalState::checkList(Value & v, Args &&... errorArgs)
{
    checkType(v, nList, std::forward<Args>(errorArgs)...);
}

template<typename... Args>
[[gnu::always_inline]]
Bindings * EvalState::checkAttrs(Value & v, Args &&... errorArgs)
{
    checkType(v, nAttrs, std::forward<Args>(errorArgs)...);
    return v.attrs();
}

[[gnu::always_inline]]
void EvalState::forceValue(Value & v, const PosIdx pos)
{
    if (v.isThunk()) {
        auto & thunk = v.thunk();
        if (thunk.resolved()) {
            v = thunk.result();
        } else {
            const auto backup = thunk;
            Env * env = thunk.env();
            Expr & expr = *thunk.expr;
            thunk = Value::blackHole;
            try {
                v = expr.eval(*this, *env);
                thunk.resolve(v);
            } catch (...) {
                thunk = backup;
                tryFixupBlackHolePos(v, pos);
                throw;
            }
        }
    } else if (v.isApp()) {
        auto & app = v.app();
        if (app.resolved()) {
            v = app.result();
        } else {
            auto target = app.target();
            if (!target.isPrimOp() || target.primOp()->arity <= app.totalArgs()) {
                auto tmp = v.app().left();
                v = callFunction(tmp, v.app().args(), pos);
                app.resolve(v);
            }
        }
    }
}

[[gnu::always_inline]]
inline Bindings * EvalState::forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx)
{
    try {
        forceValue(v, pos);
        return checkAttrs(v);
    } catch (Error & e) {
        e.addTrace(ctx.positions[pos], errorCtx);
        throw;
    }
}


[[gnu::always_inline]]
inline void EvalState::forceList(Value & v, const PosIdx pos, std::string_view errorCtx)
{
    try {
        forceValue(v, pos);
        checkList(v);
    } catch (Error & e) {
        e.addTrace(ctx.positions[pos], errorCtx);
        throw;
    }
}

inline Value * EvalState::lookupVar(Env * env, const ExprVar & var, bool noEval)
{
    for (auto l = var.level; l; --l, env = env->up)
        ;

    if (!var.fromWith) {
        return &env->values[var.displ];
    }

    // This early exit defeats the `maybeThunk` optimization for variables from `with`,
    // The added complexity of handling this appears to be similarly in cost, or
    // the cases where applicable were insignificant in the first place.
    if (noEval) {
        return nullptr;
    }

    auto * fromWith = var.fromWith;
    while (1) {
        forceAttrs(
            env->values[0], fromWith->pos, "while evaluating the first subexpression of a with expression"
        );
        auto j = env->values[0].attrs()->get(var.name);
        if (j) {
            if (ctx.stats.countCalls) {
                ctx.stats.attrSelects[j->pos]++;
            }
            return &j->value;
        }
        if (!fromWith->parentWith) {
            ctx.errors.make<UndefinedVarError>("undefined variable '%1%'", ctx.symbols[var.name])
                .atPos(var.pos)
                .withFrame(*env, var)
                .debugThrow();
        }
        for (size_t l = fromWith->prevWith; l; --l, env = env->up)
            ;
        fromWith = fromWith->parentWith;
    }
}
}