aboutsummaryrefslogtreecommitdiff
path: root/src/libexpr/value.cc
blob: 7e172f989d5365c1380f7635d9066b9e660a18c6 (plain)
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
#include "value.hh"

#include <ostream>

#include "eval.hh"
#include "print.hh"


namespace nix
{

static void copyContextToValue(Value & v, const NixStringContext & context)
{
    if (!context.empty()) {
        size_t n = 0;
        v.string.context = gcAllocType<char const *>(context.size() + 1);
        for (auto & i : context)
            v.string.context[n++] = gcCopyStringIfNeeded(i.to_string());
        v.string.context[n] = 0;
    }
}

Value::Value(primop_t, PrimOp & primop)
    : internalType(tPrimOp)
    , primOp(&primop)
    , _primop_pad(0)
{
    primop.check();
}


void Value::print(EvalState & state, std::ostream & str, PrintOptions options)
{
    printValue(state, str, *this, options);
}

PosIdx Value::determinePos(const PosIdx pos) const
{
    // Allow selecting a subset of enum values
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wswitch-enum"
    switch (internalType) {
        case tAttrs: return attrs->pos;
        case tLambda: return lambda.fun->pos;
        case tApp: return app.left->determinePos(pos);
        default: return pos;
    }
    #pragma GCC diagnostic pop
}

bool Value::isTrivial() const
{
    return
        internalType != tApp
        && internalType != tPrimOpApp
        && (internalType != tThunk
            || (dynamic_cast<ExprAttrs *>(thunk.expr)
                && static_cast<ExprAttrs *>(thunk.expr)->dynamicAttrs.empty())
            || dynamic_cast<ExprLambda *>(thunk.expr)
            || dynamic_cast<ExprList *>(thunk.expr));
}

PrimOp * Value::primOpAppPrimOp() const
{
    Value * left = primOpApp.left;
    while (left && !left->isPrimOp()) {
        left = left->primOpApp.left;
    }

    if (!left)
        return nullptr;
    return left->primOp;
}

void Value::mkPrimOp(PrimOp * p)
{
    p->check();
    clearValue();
    internalType = tPrimOp;
    primOp = p;
}

void Value::mkString(std::string_view s)
{
    mkString(gcCopyStringIfNeeded(s));
}

void Value::mkString(std::string_view s, const NixStringContext & context)
{
    mkString(s);
    copyContextToValue(*this, context);
}

void Value::mkStringMove(const char * s, const NixStringContext & context)
{
    mkString(s);
    copyContextToValue(*this, context);
}


void Value::mkPath(const SourcePath & path)
{
    mkPath(gcCopyStringIfNeeded(path.path.abs()));
}

}