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

#include <map>
#include <memory>
#include <vector>

#include "lix/libexpr/value.hh"
#include "lix/libexpr/symbol-table.hh"
#include "lix/libutil/json.hh"
#include "lix/libexpr/eval-error.hh"
#include "lix/libexpr/pos-idx.hh"
#include "lix/libutil/strings.hh"
#include "lix/libutil/linear-map.hh"

namespace nix {

struct Env;
struct Value;
class Evaluator;
struct ExprWith;
struct StaticEnv;


/**
 * An attribute path is a sequence of attribute names.
 */
struct AttrName
{
    PosIdx pos;
    Symbol symbol;
    std::unique_ptr<Expr> expr;
    AttrName(PosIdx pos, Symbol s);
    AttrName(PosIdx pos, std::unique_ptr<Expr> e);

    inline bool isDynamic()
    {
        return !symbol;
    }
};

typedef std::vector<AttrName> AttrPath;

std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath);
JSON printAttrPathToJson(const SymbolTable & symbols, const AttrPath & attrPath);


/* Abstract syntax of Nix expressions. */

struct ExprDebugFrame;
struct ExprLiteral;
struct ExprString;
struct ExprPath;
struct ExprVar;
struct ExprInheritFrom;
struct ExprSelect;
struct ExprOpHasAttr;
struct ExprSet;
struct ExprList;
struct ExprLambda;
struct ExprCall;
struct ExprLet;
struct ExprWith;
struct ExprIf;
struct ExprAssert;
struct ExprOpNot;
struct ExprOpEq;
struct ExprOpNEq;
struct ExprOpAnd;
struct ExprOpOr;
struct ExprOpImpl;
struct ExprOpUpdate;
struct ExprOpConcatLists;
struct ExprConcatStrings;
struct ExprPos;
struct ExprBlackHole;

struct ExprVisitor
{
    virtual void visit(ExprDebugFrame & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprLiteral & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprVar & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprInheritFrom & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprSelect & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpHasAttr & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprSet & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprList & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprLambda & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprCall & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprLet & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprWith & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprIf & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprAssert & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpNot & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpEq & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpNEq & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpAnd & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpOr & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpImpl & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpUpdate & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprOpConcatLists & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprConcatStrings & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprPos & e, std::unique_ptr<Expr> & ptr) = 0;
    virtual void visit(ExprBlackHole & e, std::unique_ptr<Expr> & ptr) = 0;

    void visit(std::unique_ptr<Expr> & ptr);
};

struct Expr
{
protected:
    Expr(Expr &&) = default;
    Expr & operator=(Expr &&) = default;
    Expr(const PosIdx pos) : pos(pos) {};

public:

    PosIdx pos;

    Expr() = default;
    Expr(const Expr &) = delete;
    Expr & operator=(const Expr &) = delete;
    virtual ~Expr() { };

    static std::unique_ptr<Expr> finalize(
        std::unique_ptr<Expr> parsed, Evaluator & es, const std::shared_ptr<const StaticEnv> & env
    );

    virtual JSON toJSON(const SymbolTable & symbols) const;
    virtual void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) = 0;
    virtual Value eval(EvalState & state, Env & env);
    Value makeThunk(Evaluator & ctx, Env & env);
    virtual Value maybeThunk(EvalState & state, Env & env);
    /* Lambdas have a name associated with them, when they are declared in a binding:
     * `identity = x: x` will print the resulting value as `«lambda identity @ «string»:1:14»`.
     * This is set in the parser. After parsing, all expressions are immutable.
     */
    virtual void setName(Symbol name);
    PosIdx getPos() const { return pos; }

    template<typename E>
    E & cast()
    {
        return dynamic_cast<E &>(*this);
    }

    template<typename E>
    E * try_cast()
    {
        return dynamic_cast<E *>(this);
    }
};

inline void ExprVisitor::visit(std::unique_ptr<Expr> & ptr)
{
    ptr->accept(*this, ptr);
}

struct ExprDebugFrame : Expr
{
    std::unique_ptr<Expr> inner;
    std::string message;

    ExprDebugFrame(PosIdx pos, std::unique_ptr<Expr> inner, std::string message)
        : Expr(pos)
        , inner(std::move(inner))
        , message(std::move(message))
    {
    }

    JSON toJSON(const SymbolTable & symbols) const override
    {
        return inner->toJSON(symbols);
    }
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprLiteral : Expr
{
protected:
    Value v;
    ExprLiteral(const PosIdx pos, Value v) : Expr(pos), v(v) {};
public:
    /// Read-only access to the literal value (used by codec encoder).
    const Value & literalValue() const
    {
        return v;
    }
    Value maybeThunk(EvalState & state, Env & env) override;
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprInt : private std::tuple<Value::Int>, ExprLiteral
{
    ExprInt(const PosIdx pos, NixInt n)
        : tuple({{Value::Acb::tInt}, n})
        , ExprLiteral(
              pos,
              Value::isTaggableInteger(n) ? Value{NewValueAs::integer, n} : Value(std::get<Value::Int>(*this))
          )
    {
    }
    ExprInt(const PosIdx pos, NixInt::Inner n) : ExprInt(pos, NixInt(n)) {}
};

struct ExprFloat : private std::tuple<Value::Float>, ExprLiteral
{
    ExprFloat(const PosIdx pos, NewValueAs::floating_t, double f)
        : tuple({{Value::Acb::tFloat}, f})
        , ExprLiteral(pos, Value(std::get<Value::Float>(*this)))
    {
    }
};

struct ExprStringBase
{
    std::unique_ptr<Value::Str, Value::Str::Deleter> contents;
    Value::String strcb;
protected:
    ExprStringBase(std::string_view s, const char ** context = nullptr)
        : contents(Value::Str::copy(s))
        , strcb{.content = contents.get(), .context = context}
    {
    }
};

struct ExprString : private ExprStringBase, ExprLiteral
{
    ExprString(const PosIdx pos, std::string s)
        : ExprStringBase(s)
        , ExprLiteral(pos, Value{NewValueAs::string, &strcb})
    {
    }

    std::string_view str() const
    {
        return contents->str();
    }
};

struct ExprPath : private ExprStringBase, ExprLiteral
{
    // True if this path was written as a relative literal (./foo, ../foo, ~/foo)
    // in the source. False for absolute literals (/foo).
    // Used by the codec to let the Go evaluator distinguish the two cases for
    // path-to-string coercion (RealPath mapping).
    bool relative = false;

    ExprPath(const PosIdx pos, std::string s)
        : ExprStringBase(s, Value::String::path)
        , ExprLiteral(pos, Value{NewValueAs::path, &strcb})
    {
        v = Value{NewValueAs::path, &strcb};
    }

    std::string_view str() const
    {
        return contents->str();
    }
};

typedef uint32_t Level;
typedef uint32_t Displacement;

struct ExprVar : Expr
{
    Symbol name;

    /* Whether the variable comes from an environment (e.g. a rec, let
       or function argument) or from a "with".

       `nullptr`: Not from a `with`.
       Valid pointer: the nearest, innermost `with` expression to query first. */
    ExprWith * fromWith;

    /* In the former case, the value is obtained by going `level`
       levels up from the current environment and getting the
       `displ`th value in that environment.  In the latter case, the
       value is obtained by getting the attribute named `name` from
       the set stored in the environment that is `level` levels up
       from the current one.*/
    Level level;
    Displacement displ;

    /* Variables like `__sub` as generated from expressions like `5 - 3` shouldn't be overridden.
     * This is implemented by having a blessed "root" env that contains the definitions (usually `builtins`)
     * and checking that this var only binds against that env.
     */
    bool needsRoot;

    ExprVar(Symbol name) : name(name), needsRoot(false) { };
    ExprVar(const PosIdx & pos, Symbol name, bool needsRoot = false) : Expr(pos), name(name), needsRoot(needsRoot) { };
    Value maybeThunk(EvalState & state, Env & env) override;
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

/**
 * A pseudo-expression for the purpose of evaluating the `from` expression in `inherit (from)` syntax.
 * Unlike normal variable references, the displacement is set during parsing, and always refers to
 * `ExprAttrs::inheritFromExprs` (by itself or in `ExprLet`), whose values are put into their own `Env`.
 */
struct ExprInheritFrom : Expr
{
    Expr & fromExpr;
    Displacement displ;

    ExprInheritFrom(PosIdx pos, Displacement displ, Expr & fromExpr)
          : Expr(pos), fromExpr(fromExpr), displ(displ)
    {
    }

    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct Attr;

struct ExprSelect : Expr
{
    /** The expression attributes are being selected on. e.g. `foo` in `foo.bar.baz`. */
    std::unique_ptr<Expr> e;

    /** A default value specified with `or`, if the selected attr doesn't exist.
     * e.g. `bix` in `foo.bar.baz or bix`
     */
    std::unique_ptr<Expr> def;

    /** The path of attributes being selected. e.g. `bar.baz` in `foo.bar.baz.` */
    AttrPath attrPath;

    ExprSelect(const PosIdx & pos, std::unique_ptr<Expr> e, AttrPath attrPath, std::unique_ptr<Expr> def) : Expr(pos), e(std::move(e)), def(std::move(def)), attrPath(std::move(attrPath)) { };
    ExprSelect(const PosIdx & pos, std::unique_ptr<Expr> e, const PosIdx namePos, Symbol name) : Expr(pos), e(std::move(e)) { attrPath.push_back(AttrName(namePos, name)); };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }

private:
    Attr const * selectSingleAttr(EvalState & state, Env & env, AttrName const & attrName, Value & vCurrent);
};

struct ExprOpHasAttr : Expr
{
    std::unique_ptr<Expr> e;
    AttrPath attrPath;
    ExprOpHasAttr(const PosIdx & pos, std::unique_ptr<Expr> e, AttrPath attrPath) : Expr(pos), e(std::move(e)), attrPath(std::move(attrPath)) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

/* Helper struct to contain the data shared across lets and sets */
struct ExprAttrs
{
    ExprAttrs() = default;
    ExprAttrs(const ExprAttrs &) = delete;
    ExprAttrs & operator=(const ExprAttrs &) = delete;
    ExprAttrs(ExprAttrs &&) = default;
    ExprAttrs & operator=(ExprAttrs &&) = default;
    virtual ~ExprAttrs() = default;

    struct AttrDef {
        enum class Kind {
            /** `attr = expr;` */
            Plain,
            /** `inherit attr1 attrn;` */
            Inherited,
            /** `inherit (expr) attr1 attrn;` */
            InheritedFrom,
        };

        Kind kind;
        std::unique_ptr<Expr> e;
        PosIdx pos;
        Displacement displ; // displacement
        AttrDef(std::unique_ptr<Expr> e, const PosIdx & pos, Kind kind = Kind::Plain)
            : kind(kind), e(std::move(e)), pos(pos) { };
        AttrDef() { };

        template<typename T>
        T chooseByKind(const T & plain, const T & inherited, const T & inheritedFrom) const
        {
            switch (kind) {
            case Kind::Plain:
                return plain;
            case Kind::Inherited:
                return inherited;
            default:
            case Kind::InheritedFrom:
                return inheritedFrom;
            }
        }
    };
    typedef std::map<Symbol, AttrDef> AttrDefs;
    AttrDefs attrs;
    std::unique_ptr<std::list<std::unique_ptr<Expr>>> inheritFromExprs;
    struct DynamicAttrDef {
        std::unique_ptr<Expr> nameExpr, valueExpr;
        PosIdx pos;
        DynamicAttrDef(std::unique_ptr<Expr> nameExpr, std::unique_ptr<Expr> valueExpr, const PosIdx & pos)
            : nameExpr(std::move(nameExpr)), valueExpr(std::move(valueExpr)), pos(pos) { };
    };
    typedef std::vector<DynamicAttrDef> DynamicAttrDefs;
    DynamicAttrDefs dynamicAttrs;

    std::shared_ptr<const StaticEnv> buildRecursiveEnv(const std::shared_ptr<const StaticEnv> & env);
    std::shared_ptr<const StaticEnv> bindInheritSources(ExprVisitor & e, const StaticEnv & env);
    Env * buildInheritFromEnv(EvalState & state, Env & up);
    void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const;
};

struct ExprSet : Expr, ExprAttrs {
    bool recursive = false;

    ExprSet(const PosIdx &pos, bool recursive = false) : Expr(pos), recursive(recursive) { };
    ExprSet() { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprReplBindings {
    std::map<Symbol, std::unique_ptr<Expr>> symbols;

    void finalize(Evaluator & es, const std::shared_ptr<const StaticEnv> & env) {
        for (auto & [_, e] : symbols)
            e = Expr::finalize(std::move(e), es, env);
    }
};

struct ExprList : Expr
{
    std::vector<std::unique_ptr<Expr>> elems;
    ExprList(PosIdx pos) : Expr(pos) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
    Value maybeThunk(EvalState & state, Env & env) override;
};

struct Pattern {
    /** The argument name of this particular lambda. Is a falsey symbol if there
     * is no such argument. */
    Symbol name;

    Pattern() = default;
    explicit Pattern(Symbol name) : name(name) { }
    virtual ~Pattern() = default;

    virtual std::shared_ptr<const StaticEnv> buildEnv(const StaticEnv * up) = 0;
    virtual void accept(ExprVisitor & ev) = 0;
    virtual Env &
    match(ExprLambda & lambda, EvalState & state, Env & up, Value & arg, const PosIdx pos) = 0;

    virtual void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const = 0;
};

/** A plain old lambda */
struct SimplePattern : Pattern
{
    SimplePattern() = default;
    SimplePattern(Symbol name) : Pattern(name) {
        assert(name);
    }

    virtual std::shared_ptr<const StaticEnv> buildEnv(const StaticEnv * up) override;
    virtual void accept(ExprVisitor & ev) override;
    virtual Env &
    match(ExprLambda & lambda, EvalState & state, Env & up, Value & arg, const PosIdx pos) override;

    virtual void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const override;
};

/** Attribute set destructuring in arguments of a lambda, if present */
struct AttrsPattern : Pattern
{
    struct Formal
    {
        PosIdx pos;
        Symbol name;
        std::unique_ptr<Expr> def;
    };

    typedef std::vector<Formal> Formals_;
    Formals_ formals;
    bool ellipsis;

    virtual std::shared_ptr<const StaticEnv> buildEnv(const StaticEnv * up) override;
    virtual void accept(ExprVisitor & ev) override;
    virtual Env &
    match(ExprLambda & lambda, EvalState & state, Env & up, Value & arg, const PosIdx pos) override;

    virtual void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const override;

    bool has(Symbol arg) const
    {
        auto it = std::lower_bound(formals.begin(), formals.end(), arg,
            [] (const Formal & f, const Symbol & sym) { return f.name < sym; });
        return it != formals.end() && it->name == arg;
    }

    std::vector<std::reference_wrapper<const Formal>> lexicographicOrder(const SymbolTable & symbols) const
    {
        std::vector<std::reference_wrapper<const Formal>> result(formals.begin(), formals.end());
        std::sort(result.begin(), result.end(),
            [&] (const Formal & a, const Formal & b) {
                std::string_view sa = symbols[a.name], sb = symbols[b.name];
                return sa < sb;
            });
        return result;
    }
};

struct ExprLambda : Expr
{
    /** Name of the lambda. This is set if the lambda is defined in a
     * let-expression or an attribute set, such that there is a name.
     * Lambdas may have a falsey symbol as the name if they are anonymous */
    Symbol name;
    std::unique_ptr<Pattern> pattern;
    std::unique_ptr<Expr> body;
    ExprLambda(PosIdx pos, std::unique_ptr<Pattern> pattern, std::unique_ptr<Expr> body)
        : Expr(pos), pattern(std::move(pattern)), body(std::move(body))
    {
    }
    void setName(Symbol name) override;
    std::string showNamePos(const EvalState & state) const;

    /** Returns the name of the lambda,
     * or "anonymous lambda" if it doesn't have one.
     */
    inline std::string_view getName(SymbolTable const & symbols) const
    {
        if (this->name) {
            return symbols[this->name];
        }

        return "anonymous lambda";
    }

    /** Returns the name of the lambda in single quotes,
     * or "anonymous lambda" if it doesn't have one.
     */
    inline std::string getQuotedName(SymbolTable const & symbols) const
    {
        if (this->name) {
            return concatStrings("'", symbols[this->name], "'");
        }

        return "anonymous lambda";
    }

    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprCall : Expr
{
    std::unique_ptr<Expr> fun;
    std::vector<std::unique_ptr<Expr>> args;
    ExprCall(const PosIdx & pos, std::unique_ptr<Expr> fun, std::vector<std::unique_ptr<Expr>> && args)
        : Expr(pos), fun(std::move(fun)), args(std::move(args))
    { }
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprLet : Expr, ExprAttrs
{
    std::unique_ptr<Expr> body;
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprWith : Expr
{
    std::unique_ptr<Expr> attrs, body;
    size_t prevWith;
    ExprWith * parentWith;
    ExprWith(const PosIdx & pos, std::unique_ptr<Expr> attrs, std::unique_ptr<Expr> body) : Expr(pos), attrs(std::move(attrs)), body(std::move(body)) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprIf : Expr
{
    std::unique_ptr<Expr> cond, then, else_;
    ExprIf(const PosIdx & pos, std::unique_ptr<Expr> cond, std::unique_ptr<Expr> then, std::unique_ptr<Expr> else_) : Expr(pos), cond(std::move(cond)), then(std::move(then)), else_(std::move(else_)) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprAssert : Expr
{
    std::unique_ptr<Expr> cond, body;
    ExprAssert(const PosIdx & pos, std::unique_ptr<Expr> cond, std::unique_ptr<Expr> body) : Expr(pos), cond(std::move(cond)), body(std::move(body)) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprOpNot : Expr
{
    std::unique_ptr<Expr> e;
    ExprOpNot(const PosIdx & pos, std::unique_ptr<Expr> e) : Expr(pos), e(std::move(e)) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

#define MakeBinOp(name, s)                                                                                  \
    struct name : Expr                                                                                      \
    {                                                                                                       \
        std::unique_ptr<Expr> e1, e2;                                                                       \
        name(std::unique_ptr<Expr> e1, std::unique_ptr<Expr> e2) : e1(std::move(e1)), e2(std::move(e2)) {}; \
        name(const PosIdx & pos, std::unique_ptr<Expr> e1, std::unique_ptr<Expr> e2)                        \
            : Expr(pos)                                                                                     \
            , e1(std::move(e1))                                                                             \
            , e2(std::move(e2)) {};                                                                         \
        JSON toJSON(const SymbolTable & symbols) const override                                             \
        {                                                                                                   \
            return {{"_type", #name}, {"e1", e1->toJSON(symbols)}, {"e2", e2->toJSON(symbols)}};            \
        }                                                                                                   \
        void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override                                 \
        {                                                                                                   \
            ev.visit(*this, ptr);                                                                           \
        }                                                                                                   \
        Value eval(EvalState & state, Env & env) override;                                                  \
    };

MakeBinOp(ExprOpEq, "==")
MakeBinOp(ExprOpNEq, "!=")
MakeBinOp(ExprOpAnd, "&&")
MakeBinOp(ExprOpOr, "||")
MakeBinOp(ExprOpImpl, "->")
MakeBinOp(ExprOpUpdate, "//")
MakeBinOp(ExprOpConcatLists, "++")

struct ExprConcatStrings : Expr
{
    bool isInterpolation;
    std::vector<std::pair<PosIdx, std::unique_ptr<Expr>>> es;
    ExprConcatStrings(const PosIdx & pos, bool isInterpolation, std::vector<std::pair<PosIdx, std::unique_ptr<Expr>>> es)
        : Expr(pos), isInterpolation(isInterpolation), es(std::move(es)) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

struct ExprPos : Expr
{
    ExprPos(const PosIdx & pos) : Expr(pos) { };
    JSON toJSON(const SymbolTable & symbols) const override;
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

/* only used to mark thunks as black holes. */
struct ExprBlackHole : Expr
{
    Value eval(EvalState & state, Env & env) override;
    void accept(ExprVisitor & ev, std::unique_ptr<Expr> & ptr) override { ev.visit(*this, ptr); }
};

extern ExprBlackHole eBlackHole;


/* Static environments are used to map variable names onto (level,
   displacement) pairs used to obtain the value of the variable at
   runtime. */
struct StaticEnv
{
    ExprWith * isWith;
    const StaticEnv * up;

    LinearMap<Symbol, Displacement> vars;

    /* See ExprVar::needsRoot */
    bool isRoot = false;

    StaticEnv(ExprWith * isWith, const StaticEnv * up, size_t expectedSize = 0) : isWith(isWith), up(up) {
        vars.reserve(expectedSize);
    };
};


}