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
|
package eval
import (
"testing"
"unsafe"
)
// TestLiteralNodesAreBoxed pins the invariant the literal constructors exist
// to establish: every literal AST node that reaches the evaluator carries its
// Value already boxed.
//
// This needs a test rather than an eval-time check because the failure is
// silent. eval() returns e.val unconditionally, so an unboxed node yields a
// nil Value, and a nil Value does not panic — it propagates until some type
// assertion fails to match, which surfaces far from the cause and looks like a
// wrong derivation hash rather than a bug. The alternative, a `if e.val == nil`
// guard at each of the eight consume sites, would put a branch on the hot path
// (maybeThunk runs ~11M times per system evaluation) to defend against a
// condition this test rules out statically.
//
// Deleting the `val:` field from any constructor in expr.go makes this fail.
func TestLiteralNodesAreBoxed(t *testing.T) {
// Every literal-producing syntactic form: plain and indented strings,
// interpolation (which splits literals into ConcatParts), escapes, paths
// both absolute and relative, ints and floats.
const src = `
let
s = "plain";
empty = "";
interp = "before ${"inner"} after";
ind = ''
indented ${"x"} line
'';
esc = "tab\tnewline\n";
pAbs = /absolute/path;
pRel = ./relative/path;
n = 42;
big = 1099511627776;
f = 3.14;
in [ s empty interp ind esc pAbs pRel n big f ]
`
symbols := NewSymbolTable()
for _, name := range DefaultBuiltinNames {
symbols.Create(name)
}
ast, err := NativeParseExpr([]byte(src), "/", "/test.nix", symbols, DefaultBuiltinNames)
if err != nil {
t.Fatalf("parse: %v", err)
}
var ints, floats, strs, paths int
walkExpr(ast, func(e Expr) {
switch x := e.(type) {
case *ExprInt:
ints++
if x.val == nil {
t.Errorf("ExprInt %d has nil val", x.V)
} else if v, ok := x.val.(VInt); !ok || v.V != x.V {
t.Errorf("ExprInt %d boxed as %#v", x.V, x.val)
}
case *ExprFloat:
floats++
if x.val == nil {
t.Errorf("ExprFloat %v has nil val", x.V)
} else if v, ok := x.val.(VFloat); !ok || v.V != x.V {
t.Errorf("ExprFloat %v boxed as %#v", x.V, x.val)
}
case *ExprString:
strs++
if x.val == nil {
t.Errorf("ExprString %q has nil val", x.V)
} else if v, ok := x.val.(VString); !ok || v.V != x.V {
t.Errorf("ExprString %q boxed as %#v", x.V, x.val)
}
case *ExprPath:
paths++
if x.val == nil {
t.Errorf("ExprPath %q has nil val", x.V)
} else if v, ok := x.val.(VPath); !ok || v.V != x.V || v.Relative != x.Relative {
t.Errorf("ExprPath %q boxed as %#v", x.V, x.val)
}
}
})
// Guard against the walk silently visiting nothing, which would make every
// assertion above vacuous.
if ints == 0 || floats == 0 || strs == 0 || paths == 0 {
t.Fatalf("walk found int=%d float=%d string=%d path=%d; expected all non-zero",
ints, floats, strs, paths)
}
}
// TestPreboxedLiteralIsShared documents that evaluating the same literal twice
// yields the identical box, which is the entire point of the change: the
// allocation happens once per AST node, not once per evaluation.
//
// It is safe to share because a value stored in an interface is not
// addressable, so no Nix operation can reach through it and mutate the
// string's context.
//
// Identity is checked through the interface's data word rather than with ==,
// because VString holds a map and comparing two of them panics at runtime —
// the same reason callFunction compares type tags instead of values.
func TestPreboxedLiteralIsShared(t *testing.T) {
dataWord := func(v Value) unsafe.Pointer {
return (*struct {
typ unsafe.Pointer
data unsafe.Pointer
})(unsafe.Pointer(&v)).data
}
e := NewExprString(NoPosIdx, "shared")
a, err := e.eval(nil, nil)
if err != nil {
t.Fatal(err)
}
b, err := e.eval(nil, nil)
if err != nil {
t.Fatal(err)
}
if dataWord(a) != dataWord(b) {
t.Fatal("two evaluations of one literal produced two different boxes")
}
// And the box really is the literal's value, not merely a stable one.
if s, ok := a.(VString); !ok || s.V != "shared" {
t.Fatalf("unexpected boxed value %#v", a)
}
}
// TestEmptyListMaybeThunkIsShared pins maybeThunk's third avoidance case: an
// empty list literal yields the EmptyList singleton rather than a thunk, as
// C++ ExprList::maybeThunk does (eval-expr.cc:47).
//
// Like the literal case above, this cannot be caught by any evaluation test,
// and that is the reason it needs pinning: thunking `[]` produces the *right*
// answer by a slower route, since forcing that thunk lands on the same
// singleton ExprList.eval returns. The divergence was found by comparing
// nrThunks against Lix, was worth 517471 objects per system evaluation, and
// survived a doc comment that claimed the case was implemented.
//
// Two distinct properties are asserted, because only checking the second would
// pass if the fix allocated a fresh empty VList per call — which OPTIMIZATION.md
// warns about specifically, as it removes the thunk while keeping the
// allocation it was there to avoid.
func TestEmptyListMaybeThunkIsShared(t *testing.T) {
s := &EvalState{}
// 1. No thunk, and the *same* object every time — not merely an equal one.
a := s.maybeThunk(slotOf(&ExprList{}), nil)
b := s.maybeThunk(slotOf(&ExprList{}), nil)
if _, isThunk := a.(*VThunk); isThunk {
t.Fatal("maybeThunk thunked an empty list literal")
}
if a != b {
t.Fatal("two maybeThunks of an empty list produced two different objects")
}
if a != EmptyList {
t.Fatalf("empty list did not yield the EmptyList singleton, got %#v", a)
}
// The same singleton the eval path returns, which is what makes the
// missing thunk unobservable to identity-keyed consumers.
viaEval, err := (&ExprList{}).eval(s, nil)
if err != nil {
t.Fatal(err)
}
if viaEval != a {
t.Fatal("eval and maybeThunk disagree on the empty list's identity")
}
// 2. A non-empty list still thunks: the case is narrow on purpose, since
// its elements must stay lazy.
nonEmpty := s.maybeThunk(slotOf(&ExprList{Elems: []Expr{NewExprInt(NoPosIdx, 1)}}), nil)
if _, isThunk := nonEmpty.(*VThunk); !isThunk {
t.Fatalf("maybeThunk stopped thunking a non-empty list, got %#v", nonEmpty)
}
// 3. Neither counter moved for the empty lists. C++ returns before
// reaching makeThunk and does not touch nrAvoided either
// (eval-expr.cc:47 vs the three sites at :16,:35,:43), so counting it
// would put a 6.3% gap into nrAvoided where there is currently 0.02%.
if s.Stats.NrAvoided != 0 {
t.Errorf("empty list bumped NrAvoided (%d); C++ does not", s.Stats.NrAvoided)
}
if s.Stats.NrThunks != 1 {
t.Errorf("NrThunks = %d, want 1 (the non-empty list only)", s.Stats.NrThunks)
}
}
// walkExpr calls fn on e and every Expr reachable from it.
//
// Deliberately exhaustive over the node types that can *contain* literals
// rather than delegating to a generic visitor, because the point of the test
// is to reach literals in every syntactic position: attrset values, list
// elements, interpolation parts, lambda defaults, operator operands.
func walkExpr(e Expr, fn func(Expr)) {
if e == nil {
return
}
fn(e)
switch x := e.(type) {
case *ExprSet:
for _, a := range x.Attrs {
walkExpr(a.Expr, fn)
}
for _, d := range x.DynamicAttrs {
walkExpr(d.NameExpr, fn)
walkExpr(d.ValueExpr, fn)
}
for _, i := range x.InheritFrom {
walkExpr(i, fn)
}
case *ExprList:
for _, el := range x.Elems {
walkExpr(el, fn)
}
case *ExprLet:
for _, a := range x.Attrs {
walkExpr(a.Expr, fn)
}
for _, i := range x.InheritFrom {
walkExpr(i, fn)
}
walkExpr(x.Body, fn)
case *ExprConcatStrings:
for _, p := range x.Parts {
walkExpr(p.Expr, fn)
}
case *ExprCall:
walkExpr(x.Fun, fn)
for _, a := range x.Args {
walkExpr(a, fn)
}
case *ExprSelect:
walkExpr(x.E, fn)
walkExpr(x.Def, fn)
for _, an := range x.AttrPath {
walkExpr(an.Expr, fn)
}
case *ExprLambda:
if ap, ok := x.Pattern.(AttrsPattern); ok {
for _, f := range ap.Formals {
walkExpr(f.Default, fn)
}
}
walkExpr(x.Body, fn)
case *ExprIf:
walkExpr(x.Cond, fn)
walkExpr(x.Then, fn)
walkExpr(x.Else, fn)
case *ExprWith:
walkExpr(x.Attrs, fn)
walkExpr(x.Body, fn)
case *ExprAssert:
walkExpr(x.Cond, fn)
walkExpr(x.Body, fn)
case *ExprOpNot:
walkExpr(x.E, fn)
case *ExprOpUpdate:
walkExpr(x.E1, fn)
walkExpr(x.E2, fn)
case *ExprOpConcatLists:
walkExpr(x.E1, fn)
walkExpr(x.E2, fn)
case *ExprOpEq:
walkExpr(x.E1, fn)
walkExpr(x.E2, fn)
case *ExprOpNEq:
walkExpr(x.E1, fn)
walkExpr(x.E2, fn)
case *ExprOpAnd:
walkExpr(x.E1, fn)
walkExpr(x.E2, fn)
case *ExprOpOr:
walkExpr(x.E1, fn)
walkExpr(x.E2, fn)
case *ExprOpImpl:
walkExpr(x.E1, fn)
walkExpr(x.E2, fn)
case *ExprOpHasAttr:
walkExpr(x.E, fn)
case *ExprDebugFrame:
walkExpr(x.Inner, fn)
}
}
|