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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
|
package eval
// astcmp.go — Compare Go Expr AST against nix-instantiate --parse JSON output.
//
// The comparison uses a generic tree representation (Node) that both the
// nix-instantiate JSON and the Go Expr tree are converted into. The
// comparison then walks both trees and reports structural differences.
//
// Usage:
//
// nixNode, err := ParseNixJSON(jsonBytes)
// goNode := ExprToNode(expr, symbols)
// diffs := CompareAST(nixNode, goNode)
import (
"bytes"
"encoding/json"
"fmt"
"math"
"sort"
"strings"
)
// ---------------------------------------------------------------------------
// Generic AST node representation
// ---------------------------------------------------------------------------
// Node is the generic AST representation used for comparison.
// It mirrors the JSON output of `nix-instantiate --parse`.
type Node struct {
Type string // e.g. "ExprLiteral", "ExprVar", "ExprLambda", ...
// Payload fields — only the relevant ones are set per type.
// Literal:
LitValue interface{} // int64, float64, string, bool, nil
LitValueType string // "Int", "Float", "String", "Path", "Bool", "Null"
// Var:
VarName string
// Lambda:
LambdaArg string // "" if absent (formals-only)
LambdaFormals map[string]*Node // formal name → default expr (nil if no default)
LambdaFormalsOrder []string // formals in definition order
LambdaEllipsis bool
LambdaBody *Node
// Call:
CallFun *Node
CallArgs []*Node
// Set:
SetRecursive bool
SetAttrs map[string]*Node // attr name → value expr
SetInherit map[string]*Node // inherit name → var expr
SetInheritFrom []InheritFromGroup
SetDynamicAttrs []DynAttrNode
// Let:
LetAttrs map[string]*Node
LetInherit map[string]*Node
LetInheritFrom []InheritFromGroup
LetBody *Node
// With:
WithAttrs *Node
WithBody *Node
// If:
IfCond *Node
IfThen *Node
IfElse *Node
// Assert:
AssertCond *Node
AssertBody *Node
// List:
ListElems []*Node
// Select:
SelectExpr *Node
SelectPath []AttrPathElem // each elem is either a static string or a dynamic Node
SelectDefault *Node // nil if no `or` clause
// OpHasAttr:
HasAttrExpr *Node
HasAttrPath []AttrPathElem
// ConcatStrings:
ConcatParts []*Node
ConcatForceString bool // nix-instantiate calls it "forceString"; Go calls it "IsInterpolation"
// Unary op:
UnaryExpr *Node
// Binary ops (Eq, NEq, And, Or, Impl, Update, ConcatLists):
BinLeft *Node
BinRight *Node
}
// InheritFromGroup represents `inherit (from) attr1 attr2;`
type InheritFromGroup struct {
From *Node
Attrs []string // sorted
}
// DynAttrNode represents `${nameExpr} = valueExpr;`
type DynAttrNode struct {
Name *Node
Value *Node
}
// AttrPathElem is one step in a select/hasAttr path: either a static name or
// a dynamic expression.
type AttrPathElem struct {
Static string // set if static
Dynamic *Node // set if dynamic
}
// ---------------------------------------------------------------------------
// Parse nix-instantiate --parse JSON → Node
// ---------------------------------------------------------------------------
// ParseNixJSON parses the JSON output of `nix-instantiate --parse` into a Node tree.
func ParseNixJSON(data []byte) (*Node, error) {
// Use UseNumber() so that large integers are not rounded via float64.
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
var raw interface{}
if err := dec.Decode(&raw); err != nil {
return nil, fmt.Errorf("parseNixJSON: %w", err)
}
return convertJSON(raw)
}
func convertJSON(v interface{}) (*Node, error) {
obj, ok := v.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("expected JSON object, got %T", v)
}
typ, _ := obj["_type"].(string)
if typ == "" {
return nil, fmt.Errorf("missing _type in JSON object")
}
n := &Node{Type: typ}
switch typ {
case "ExprLiteral":
n.LitValueType, _ = obj["valueType"].(string)
switch n.LitValueType {
case "Int":
// With UseNumber(), large integers arrive as json.Number, not float64.
switch v := obj["value"].(type) {
case json.Number:
n.LitValue, _ = v.Int64()
case float64:
n.LitValue = int64(v) // fallback (shouldn't happen with UseNumber)
}
case "Float":
switch v := obj["value"].(type) {
case json.Number:
n.LitValue, _ = v.Float64()
case float64:
n.LitValue = v
}
case "String", "Path":
n.LitValue, _ = obj["value"].(string)
}
case "ExprVar":
n.VarName, _ = obj["value"].(string)
case "ExprLambda":
if arg, ok := obj["arg"].(string); ok {
n.LambdaArg = arg
}
if formals, ok := obj["formals"].(map[string]interface{}); ok {
n.LambdaFormals = make(map[string]*Node, len(formals))
// Collect keys and sort for stable ordering
keys := make([]string, 0, len(formals))
for k := range formals {
keys = append(keys, k)
}
sort.Strings(keys)
n.LambdaFormalsOrder = keys
for _, k := range keys {
v := formals[k]
if v == nil {
n.LambdaFormals[k] = nil
} else {
child, err := convertJSON(v)
if err != nil {
return nil, fmt.Errorf("lambda formal %q default: %w", k, err)
}
n.LambdaFormals[k] = child
}
}
}
if ell, ok := obj["formalsEllipsis"].(bool); ok {
n.LambdaEllipsis = ell
}
if body, ok := obj["body"]; ok {
child, err := convertJSON(body)
if err != nil {
return nil, fmt.Errorf("lambda body: %w", err)
}
n.LambdaBody = child
}
case "ExprCall":
if fun, ok := obj["fun"]; ok {
child, err := convertJSON(fun)
if err != nil {
return nil, fmt.Errorf("call fun: %w", err)
}
n.CallFun = child
}
if args, ok := obj["args"].([]interface{}); ok {
n.CallArgs = make([]*Node, len(args))
for i, a := range args {
child, err := convertJSON(a)
if err != nil {
return nil, fmt.Errorf("call arg[%d]: %w", i, err)
}
n.CallArgs[i] = child
}
}
case "ExprSet":
if rec, ok := obj["recursive"].(bool); ok {
n.SetRecursive = rec
}
if err := parseAttrsField(obj, "attrs", &n.SetAttrs); err != nil {
return nil, fmt.Errorf("set attrs: %w", err)
}
if err := parseAttrsField(obj, "inherit", &n.SetInherit); err != nil {
return nil, fmt.Errorf("set inherit: %w", err)
}
if err := parseInheritFrom(obj, &n.SetInheritFrom); err != nil {
return nil, fmt.Errorf("set inheritFrom: %w", err)
}
if err := parseDynamicAttrs(obj, &n.SetDynamicAttrs); err != nil {
return nil, fmt.Errorf("set dynamicAttrs: %w", err)
}
case "ExprLet":
if err := parseAttrsField(obj, "attrs", &n.LetAttrs); err != nil {
return nil, fmt.Errorf("let attrs: %w", err)
}
if err := parseAttrsField(obj, "inherit", &n.LetInherit); err != nil {
return nil, fmt.Errorf("let inherit: %w", err)
}
if err := parseInheritFrom(obj, &n.LetInheritFrom); err != nil {
return nil, fmt.Errorf("let inheritFrom: %w", err)
}
if body, ok := obj["body"]; ok {
child, err := convertJSON(body)
if err != nil {
return nil, fmt.Errorf("let body: %w", err)
}
n.LetBody = child
}
case "ExprWith":
if attrs, ok := obj["attrs"]; ok {
child, err := convertJSON(attrs)
if err != nil {
return nil, fmt.Errorf("with attrs: %w", err)
}
n.WithAttrs = child
}
if body, ok := obj["body"]; ok {
child, err := convertJSON(body)
if err != nil {
return nil, fmt.Errorf("with body: %w", err)
}
n.WithBody = child
}
case "ExprIf":
for _, pair := range []struct {
key string
dest **Node
}{
{"cond", &n.IfCond}, {"then", &n.IfThen}, {"else", &n.IfElse},
} {
if v, ok := obj[pair.key]; ok {
child, err := convertJSON(v)
if err != nil {
return nil, fmt.Errorf("if %s: %w", pair.key, err)
}
*pair.dest = child
}
}
case "ExprAssert":
if v, ok := obj["cond"]; ok {
child, err := convertJSON(v)
if err != nil {
return nil, fmt.Errorf("assert cond: %w", err)
}
n.AssertCond = child
}
if v, ok := obj["body"]; ok {
child, err := convertJSON(v)
if err != nil {
return nil, fmt.Errorf("assert body: %w", err)
}
n.AssertBody = child
}
case "ExprList":
if elems, ok := obj["elems"].([]interface{}); ok {
n.ListElems = make([]*Node, len(elems))
for i, e := range elems {
child, err := convertJSON(e)
if err != nil {
return nil, fmt.Errorf("list[%d]: %w", i, err)
}
n.ListElems[i] = child
}
}
case "ExprSelect":
if e, ok := obj["e"]; ok {
child, err := convertJSON(e)
if err != nil {
return nil, fmt.Errorf("select e: %w", err)
}
n.SelectExpr = child
}
if err := parseAttrPath(obj, "attrs", &n.SelectPath); err != nil {
return nil, fmt.Errorf("select attrs: %w", err)
}
if def, ok := obj["default"]; ok {
child, err := convertJSON(def)
if err != nil {
return nil, fmt.Errorf("select default: %w", err)
}
n.SelectDefault = child
}
case "ExprOpHasAttr":
if e, ok := obj["e"]; ok {
child, err := convertJSON(e)
if err != nil {
return nil, fmt.Errorf("hasattr e: %w", err)
}
n.HasAttrExpr = child
}
if err := parseAttrPath(obj, "attrs", &n.HasAttrPath); err != nil {
return nil, fmt.Errorf("hasattr attrs: %w", err)
}
case "ExprConcatStrings":
if fs, ok := obj["forceString"].(bool); ok {
n.ConcatForceString = fs
}
if es, ok := obj["es"].([]interface{}); ok {
n.ConcatParts = make([]*Node, len(es))
for i, e := range es {
child, err := convertJSON(e)
if err != nil {
return nil, fmt.Errorf("concat[%d]: %w", i, err)
}
n.ConcatParts[i] = child
}
}
case "ExprOpNot":
if e, ok := obj["e"]; ok {
child, err := convertJSON(e)
if err != nil {
return nil, fmt.Errorf("not e: %w", err)
}
n.UnaryExpr = child
}
case "ExprOpEq", "ExprOpNEq", "ExprOpAnd", "ExprOpOr",
"ExprOpImpl", "ExprOpUpdate", "ExprOpConcatLists":
if e1, ok := obj["e1"]; ok {
child, err := convertJSON(e1)
if err != nil {
return nil, fmt.Errorf("%s e1: %w", typ, err)
}
n.BinLeft = child
}
if e2, ok := obj["e2"]; ok {
child, err := convertJSON(e2)
if err != nil {
return nil, fmt.Errorf("%s e2: %w", typ, err)
}
n.BinRight = child
}
case "ExprPos":
// No fields
default:
return nil, fmt.Errorf("unknown _type %q", typ)
}
return n, nil
}
// parseAttrsField extracts a JSON object field as a map of name → Node.
func parseAttrsField(obj map[string]interface{}, field string, dest *map[string]*Node) error {
raw, ok := obj[field]
if !ok {
return nil
}
m, ok := raw.(map[string]interface{})
if !ok {
return nil
}
*dest = make(map[string]*Node, len(m))
for k, v := range m {
child, err := convertJSON(v)
if err != nil {
return fmt.Errorf("attr %q: %w", k, err)
}
(*dest)[k] = child
}
return nil
}
// parseInheritFrom extracts the "inheritFrom" array field.
func parseInheritFrom(obj map[string]interface{}, dest *[]InheritFromGroup) error {
raw, ok := obj["inheritFrom"]
if !ok {
return nil
}
arr, ok := raw.([]interface{})
if !ok {
return nil
}
for _, item := range arr {
group, ok := item.(map[string]interface{})
if !ok {
continue
}
var g InheritFromGroup
if from, ok := group["from"]; ok {
child, err := convertJSON(from)
if err != nil {
return fmt.Errorf("inheritFrom.from: %w", err)
}
g.From = child
}
if attrs, ok := group["attrs"].([]interface{}); ok {
for _, a := range attrs {
if s, ok := a.(string); ok {
g.Attrs = append(g.Attrs, s)
}
}
}
*dest = append(*dest, g)
}
return nil
}
// parseDynamicAttrs extracts the "dynamicAttrs" array field.
func parseDynamicAttrs(obj map[string]interface{}, dest *[]DynAttrNode) error {
raw, ok := obj["dynamicAttrs"]
if !ok {
return nil
}
arr, ok := raw.([]interface{})
if !ok {
return nil
}
for i, item := range arr {
da, ok := item.(map[string]interface{})
if !ok {
continue
}
var d DynAttrNode
if name, ok := da["name"]; ok {
child, err := convertJSON(name)
if err != nil {
return fmt.Errorf("dynamicAttrs[%d].name: %w", i, err)
}
d.Name = child
}
if value, ok := da["value"]; ok {
child, err := convertJSON(value)
if err != nil {
return fmt.Errorf("dynamicAttrs[%d].value: %w", i, err)
}
d.Value = child
}
*dest = append(*dest, d)
}
return nil
}
// parseAttrPath extracts an attr path (array of strings or expr nodes).
func parseAttrPath(obj map[string]interface{}, field string, dest *[]AttrPathElem) error {
raw, ok := obj[field]
if !ok {
return nil
}
arr, ok := raw.([]interface{})
if !ok {
return nil
}
for _, item := range arr {
switch v := item.(type) {
case string:
*dest = append(*dest, AttrPathElem{Static: v})
case map[string]interface{}:
child, err := convertJSON(v)
if err != nil {
return fmt.Errorf("attrpath elem: %w", err)
}
*dest = append(*dest, AttrPathElem{Dynamic: child})
}
}
return nil
}
// ---------------------------------------------------------------------------
// Convert Go Expr → Node
// ---------------------------------------------------------------------------
// ExprToNode converts a Go Expr AST into the generic Node representation,
// matching the structure that nix-instantiate --parse produces.
func ExprToNode(e Expr, symbols *SymbolTable) *Node {
if e == nil {
return nil
}
switch x := e.(type) {
case *ExprInt:
return &Node{Type: "ExprLiteral", LitValue: x.V, LitValueType: "Int"}
case *ExprFloat:
return &Node{Type: "ExprLiteral", LitValue: x.V, LitValueType: "Float"}
case *ExprString:
return &Node{Type: "ExprLiteral", LitValue: x.V, LitValueType: "String"}
case *ExprPath:
return &Node{Type: "ExprLiteral", LitValue: x.V, LitValueType: "Path"}
case *ExprVar:
return &Node{Type: "ExprVar", VarName: symbols.Str(x.Name)}
case *ExprLambda:
n := &Node{Type: "ExprLambda"}
switch p := x.Pattern.(type) {
case SimplePattern:
n.LambdaArg = symbols.Str(p.Name)
case AttrsPattern:
if p.Name != 0 {
n.LambdaArg = symbols.Str(p.Name)
}
n.LambdaFormals = make(map[string]*Node, len(p.Formals))
n.LambdaFormalsOrder = make([]string, 0, len(p.Formals))
// Collect formal names and sort them (nix-instantiate outputs sorted JSON object keys)
formalNames := make([]string, len(p.Formals))
for i, f := range p.Formals {
formalNames[i] = symbols.Str(f.Name)
}
sort.Strings(formalNames)
n.LambdaFormalsOrder = formalNames
// Build the map
for _, f := range p.Formals {
name := symbols.Str(f.Name)
if f.HasDefault {
n.LambdaFormals[name] = ExprToNode(f.Default, symbols)
} else {
n.LambdaFormals[name] = nil
}
}
n.LambdaEllipsis = p.Ellipsis
}
n.LambdaBody = ExprToNode(x.Body, symbols)
return n
case *ExprCall:
n := &Node{Type: "ExprCall"}
n.CallFun = ExprToNode(x.Fun, symbols)
n.CallArgs = make([]*Node, len(x.Args))
for i, a := range x.Args {
n.CallArgs[i] = ExprToNode(a, symbols)
}
return n
case *ExprSet:
n := &Node{Type: "ExprSet", SetRecursive: x.Recursive}
n.SetAttrs = make(map[string]*Node)
n.SetInherit = make(map[string]*Node)
// Group inheritFrom entries by their source expression displacement.
// In our Go AST, inherit (from) x y; is stored as:
// InheritFrom[displ] = ExprInheritFrom{Displ: displ}
// AttrDef{Kind: InheritedFrom, Expr: ExprSelect{E: ExprInheritFrom{Displ}, AttrPath: [x]}}
// We need to reconstruct the grouped representation.
inheritFromMap := make(map[uint32]*InheritFromGroup) // displ → group
var inheritFromOrder []uint32
for _, attr := range x.Attrs {
name := symbols.Str(attr.Name)
switch attr.Kind {
case AttrDefPlain:
n.SetAttrs[name] = ExprToNode(attr.Expr, symbols)
case AttrDefInherited:
n.SetInherit[name] = ExprToNode(attr.Expr, symbols)
case AttrDefInheritedFrom:
// Extract the InheritFrom displacement from the ExprSelect
displ := inheritFromDispl(attr.Expr)
g, ok := inheritFromMap[displ]
if !ok {
g = &InheritFromGroup{}
inheritFromMap[displ] = g
inheritFromOrder = append(inheritFromOrder, displ)
}
g.Attrs = append(g.Attrs, name)
}
}
// Build InheritFrom groups with the source expression from ExprSet.InheritFrom
for _, displ := range inheritFromOrder {
g := inheritFromMap[displ]
sort.Strings(g.Attrs)
var from *Node
if int(displ) < len(x.InheritFrom) {
from = ExprToNode(x.InheritFrom[displ], symbols)
}
n.SetInheritFrom = append(n.SetInheritFrom, InheritFromGroup{
From: from,
Attrs: g.Attrs,
})
}
// Dynamic attrs
for _, da := range x.DynamicAttrs {
n.SetDynamicAttrs = append(n.SetDynamicAttrs, DynAttrNode{
Name: ExprToNode(da.NameExpr, symbols),
Value: ExprToNode(da.ValueExpr, symbols),
})
}
// Clean up empty maps
if len(n.SetAttrs) == 0 {
n.SetAttrs = nil
}
if len(n.SetInherit) == 0 {
n.SetInherit = nil
}
return n
case *ExprLet:
n := &Node{Type: "ExprLet"}
n.LetAttrs = make(map[string]*Node)
n.LetInherit = make(map[string]*Node)
inheritFromMap := make(map[uint32]*InheritFromGroup)
var inheritFromOrder []uint32
for _, attr := range x.Attrs {
name := symbols.Str(attr.Name)
switch attr.Kind {
case AttrDefPlain:
n.LetAttrs[name] = ExprToNode(attr.Expr, symbols)
case AttrDefInherited:
n.LetInherit[name] = ExprToNode(attr.Expr, symbols)
case AttrDefInheritedFrom:
displ := inheritFromDispl(attr.Expr)
g, ok := inheritFromMap[displ]
if !ok {
g = &InheritFromGroup{}
inheritFromMap[displ] = g
inheritFromOrder = append(inheritFromOrder, displ)
}
g.Attrs = append(g.Attrs, name)
}
}
for _, displ := range inheritFromOrder {
g := inheritFromMap[displ]
sort.Strings(g.Attrs)
var from *Node
if int(displ) < len(x.InheritFrom) {
from = ExprToNode(x.InheritFrom[displ], symbols)
}
n.LetInheritFrom = append(n.LetInheritFrom, InheritFromGroup{
From: from,
Attrs: g.Attrs,
})
}
if len(n.LetAttrs) == 0 {
n.LetAttrs = nil
}
if len(n.LetInherit) == 0 {
n.LetInherit = nil
}
n.LetBody = ExprToNode(x.Body, symbols)
return n
case *ExprWith:
return &Node{
Type: "ExprWith",
WithAttrs: ExprToNode(x.Attrs, symbols),
WithBody: ExprToNode(x.Body, symbols),
}
case *ExprIf:
return &Node{
Type: "ExprIf",
IfCond: ExprToNode(x.Cond, symbols),
IfThen: ExprToNode(x.Then, symbols),
IfElse: ExprToNode(x.Else, symbols),
}
case *ExprAssert:
return &Node{
Type: "ExprAssert",
AssertCond: ExprToNode(x.Cond, symbols),
AssertBody: ExprToNode(x.Body, symbols),
}
case *ExprList:
n := &Node{Type: "ExprList"}
n.ListElems = make([]*Node, len(x.Elems))
for i, e := range x.Elems {
n.ListElems[i] = ExprToNode(e, symbols)
}
return n
case *ExprSelect:
n := &Node{Type: "ExprSelect"}
n.SelectExpr = ExprToNode(x.E, symbols)
n.SelectPath = attrPathToElems(x.AttrPath, symbols)
if x.Def != nil {
n.SelectDefault = ExprToNode(x.Def, symbols)
}
return n
case *ExprOpHasAttr:
n := &Node{Type: "ExprOpHasAttr"}
n.HasAttrExpr = ExprToNode(x.E, symbols)
n.HasAttrPath = attrPathToElems(x.AttrPath, symbols)
return n
case *ExprConcatStrings:
n := &Node{Type: "ExprConcatStrings"}
n.ConcatForceString = x.IsInterpolation
n.ConcatParts = make([]*Node, len(x.Parts))
for i, p := range x.Parts {
n.ConcatParts[i] = ExprToNode(p.Expr, symbols)
}
return n
case *ExprOpNot:
return &Node{Type: "ExprOpNot", UnaryExpr: ExprToNode(x.E, symbols)}
case *ExprOpEq:
return &Node{Type: "ExprOpEq", BinLeft: ExprToNode(x.E1, symbols), BinRight: ExprToNode(x.E2, symbols)}
case *ExprOpNEq:
return &Node{Type: "ExprOpNEq", BinLeft: ExprToNode(x.E1, symbols), BinRight: ExprToNode(x.E2, symbols)}
case *ExprOpAnd:
return &Node{Type: "ExprOpAnd", BinLeft: ExprToNode(x.E1, symbols), BinRight: ExprToNode(x.E2, symbols)}
case *ExprOpOr:
return &Node{Type: "ExprOpOr", BinLeft: ExprToNode(x.E1, symbols), BinRight: ExprToNode(x.E2, symbols)}
case *ExprOpImpl:
return &Node{Type: "ExprOpImpl", BinLeft: ExprToNode(x.E1, symbols), BinRight: ExprToNode(x.E2, symbols)}
case *ExprOpUpdate:
return &Node{Type: "ExprOpUpdate", BinLeft: ExprToNode(x.E1, symbols), BinRight: ExprToNode(x.E2, symbols)}
case *ExprOpConcatLists:
return &Node{Type: "ExprOpConcatLists", BinLeft: ExprToNode(x.E1, symbols), BinRight: ExprToNode(x.E2, symbols)}
case *ExprPos:
return &Node{Type: "ExprPos"}
case *ExprInheritFrom:
// Should not appear at top level; it's an internal node used inside
// ExprSelect for inherit (from). If we encounter it, just mark it.
return &Node{Type: "ExprInheritFrom"}
default:
return &Node{Type: fmt.Sprintf("UNKNOWN(%T)", e)}
}
}
// inheritFromDispl extracts the displacement from an inherit-from AttrDef's Expr.
// The Expr is ExprSelect{E: ExprInheritFrom{Displ: N}, AttrPath: [name]}.
func inheritFromDispl(e Expr) uint32 {
sel, ok := e.(*ExprSelect)
if !ok {
return 0
}
inhFrom, ok := sel.E.(*ExprInheritFrom)
if !ok {
return 0
}
return inhFrom.Displ
}
// attrPathToElems converts a Go AttrPath to the generic comparison format.
func attrPathToElems(path []AttrName, symbols *SymbolTable) []AttrPathElem {
out := make([]AttrPathElem, len(path))
for i, an := range path {
if an.Symbol != 0 {
out[i] = AttrPathElem{Static: symbols.Str(an.Symbol)}
} else if an.Expr != nil {
out[i] = AttrPathElem{Dynamic: ExprToNode(an.Expr, symbols)}
}
}
return out
}
// ---------------------------------------------------------------------------
// Compare two Node trees
// ---------------------------------------------------------------------------
// Diff describes one difference between two AST trees.
type Diff struct {
Path string // dot-separated path to the differing node
Msg string // human-readable description
}
func (d Diff) String() string {
if d.Path == "" {
return d.Msg
}
return d.Path + ": " + d.Msg
}
// CompareAST compares two Node trees and returns all differences found.
// An empty slice means the trees are structurally identical.
func CompareAST(nix, go_ *Node) []Diff {
return compareNodes(nix, go_, "")
}
func compareNodes(a, b *Node, path string) []Diff {
if a == nil && b == nil {
return nil
}
if a == nil {
return []Diff{{Path: path, Msg: "nix=nil, go=" + b.Type}}
}
if b == nil {
return []Diff{{Path: path, Msg: "nix=" + a.Type + ", go=nil"}}
}
if a.Type != b.Type {
return []Diff{{Path: path, Msg: fmt.Sprintf("type: nix=%s, go=%s", a.Type, b.Type)}}
}
var diffs []Diff
d := func(subpath, msg string) {
full := path
if subpath != "" {
if full != "" {
full += "." + subpath
} else {
full = subpath
}
}
diffs = append(diffs, Diff{Path: full, Msg: msg})
}
switch a.Type {
case "ExprLiteral":
if a.LitValueType != b.LitValueType {
d("", fmt.Sprintf("valueType: nix=%s, go=%s", a.LitValueType, b.LitValueType))
} else if !litValEqual(a.LitValue, b.LitValue) {
d("", fmt.Sprintf("value: nix=%v, go=%v", a.LitValue, b.LitValue))
}
case "ExprVar":
if a.VarName != b.VarName {
d("", fmt.Sprintf("name: nix=%q, go=%q", a.VarName, b.VarName))
}
case "ExprLambda":
if a.LambdaArg != b.LambdaArg {
d("arg", fmt.Sprintf("nix=%q, go=%q", a.LambdaArg, b.LambdaArg))
}
diffs = append(diffs, compareFormalsMap(a.LambdaFormals, b.LambdaFormals, sub(path, "formals"))...)
if a.LambdaEllipsis != b.LambdaEllipsis {
d("ellipsis", fmt.Sprintf("nix=%v, go=%v", a.LambdaEllipsis, b.LambdaEllipsis))
}
diffs = append(diffs, compareNodes(a.LambdaBody, b.LambdaBody, sub(path, "body"))...)
case "ExprCall":
diffs = append(diffs, compareNodes(a.CallFun, b.CallFun, sub(path, "fun"))...)
diffs = append(diffs, compareNodeSlice(a.CallArgs, b.CallArgs, sub(path, "args"))...)
case "ExprSet":
if a.SetRecursive != b.SetRecursive {
d("recursive", fmt.Sprintf("nix=%v, go=%v", a.SetRecursive, b.SetRecursive))
}
diffs = append(diffs, compareNodeMap(a.SetAttrs, b.SetAttrs, sub(path, "attrs"))...)
diffs = append(diffs, compareNodeMap(a.SetInherit, b.SetInherit, sub(path, "inherit"))...)
diffs = append(diffs, compareInheritFrom(a.SetInheritFrom, b.SetInheritFrom, sub(path, "inheritFrom"))...)
diffs = append(diffs, compareDynAttrs(a.SetDynamicAttrs, b.SetDynamicAttrs, sub(path, "dynamicAttrs"))...)
case "ExprLet":
diffs = append(diffs, compareNodeMap(a.LetAttrs, b.LetAttrs, sub(path, "attrs"))...)
diffs = append(diffs, compareNodeMap(a.LetInherit, b.LetInherit, sub(path, "inherit"))...)
diffs = append(diffs, compareInheritFrom(a.LetInheritFrom, b.LetInheritFrom, sub(path, "inheritFrom"))...)
diffs = append(diffs, compareNodes(a.LetBody, b.LetBody, sub(path, "body"))...)
case "ExprWith":
diffs = append(diffs, compareNodes(a.WithAttrs, b.WithAttrs, sub(path, "attrs"))...)
diffs = append(diffs, compareNodes(a.WithBody, b.WithBody, sub(path, "body"))...)
case "ExprIf":
diffs = append(diffs, compareNodes(a.IfCond, b.IfCond, sub(path, "cond"))...)
diffs = append(diffs, compareNodes(a.IfThen, b.IfThen, sub(path, "then"))...)
diffs = append(diffs, compareNodes(a.IfElse, b.IfElse, sub(path, "else"))...)
case "ExprAssert":
diffs = append(diffs, compareNodes(a.AssertCond, b.AssertCond, sub(path, "cond"))...)
diffs = append(diffs, compareNodes(a.AssertBody, b.AssertBody, sub(path, "body"))...)
case "ExprList":
diffs = append(diffs, compareNodeSlice(a.ListElems, b.ListElems, sub(path, "elems"))...)
case "ExprSelect":
diffs = append(diffs, compareNodes(a.SelectExpr, b.SelectExpr, sub(path, "e"))...)
diffs = append(diffs, compareAttrPath(a.SelectPath, b.SelectPath, sub(path, "attrs"))...)
diffs = append(diffs, compareNodes(a.SelectDefault, b.SelectDefault, sub(path, "default"))...)
case "ExprOpHasAttr":
diffs = append(diffs, compareNodes(a.HasAttrExpr, b.HasAttrExpr, sub(path, "e"))...)
diffs = append(diffs, compareAttrPath(a.HasAttrPath, b.HasAttrPath, sub(path, "attrs"))...)
case "ExprConcatStrings":
if a.ConcatForceString != b.ConcatForceString {
d("forceString", fmt.Sprintf("nix=%v, go=%v", a.ConcatForceString, b.ConcatForceString))
}
diffs = append(diffs, compareNodeSlice(a.ConcatParts, b.ConcatParts, sub(path, "es"))...)
case "ExprOpNot":
diffs = append(diffs, compareNodes(a.UnaryExpr, b.UnaryExpr, sub(path, "e"))...)
case "ExprOpEq", "ExprOpNEq", "ExprOpAnd", "ExprOpOr",
"ExprOpImpl", "ExprOpUpdate", "ExprOpConcatLists":
diffs = append(diffs, compareNodes(a.BinLeft, b.BinLeft, sub(path, "e1"))...)
diffs = append(diffs, compareNodes(a.BinRight, b.BinRight, sub(path, "e2"))...)
case "ExprPos":
// No fields to compare
default:
d("", fmt.Sprintf("unhandled type %q", a.Type))
}
return diffs
}
func litValEqual(a, b interface{}) bool {
switch av := a.(type) {
case int64:
bv, ok := b.(int64)
return ok && av == bv
case float64:
bv, ok := b.(float64)
return ok && (av == bv || (math.IsNaN(av) && math.IsNaN(bv)))
case string:
bv, ok := b.(string)
return ok && av == bv
case nil:
return b == nil
}
return false
}
func sub(path, child string) string {
if path == "" {
return child
}
return path + "." + child
}
func compareNodeSlice(a, b []*Node, path string) []Diff {
var diffs []Diff
if len(a) != len(b) {
diffs = append(diffs, Diff{Path: path, Msg: fmt.Sprintf("length: nix=%d, go=%d", len(a), len(b))})
}
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
diffs = append(diffs, compareNodes(a[i], b[i], fmt.Sprintf("%s[%d]", path, i))...)
}
return diffs
}
func compareNodeMap(a, b map[string]*Node, path string) []Diff {
var diffs []Diff
allKeys := make(map[string]bool)
for k := range a {
allKeys[k] = true
}
for k := range b {
allKeys[k] = true
}
keys := make([]string, 0, len(allKeys))
for k := range allKeys {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
av, aok := a[k]
bv, bok := b[k]
kpath := sub(path, k)
if aok && !bok {
diffs = append(diffs, Diff{Path: kpath, Msg: "only in nix"})
} else if !aok && bok {
diffs = append(diffs, Diff{Path: kpath, Msg: "only in go"})
} else {
diffs = append(diffs, compareNodes(av, bv, kpath)...)
}
}
return diffs
}
func compareFormalsMap(a, b map[string]*Node, path string) []Diff {
// Both nil/empty means no formals
if len(a) == 0 && len(b) == 0 {
return nil
}
if (len(a) == 0) != (len(b) == 0) {
return []Diff{{Path: path, Msg: fmt.Sprintf("nix has %d formals, go has %d", len(a), len(b))}}
}
var diffs []Diff
allKeys := make(map[string]bool)
for k := range a {
allKeys[k] = true
}
for k := range b {
allKeys[k] = true
}
keys := make([]string, 0, len(allKeys))
for k := range allKeys {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
av, aok := a[k]
bv, bok := b[k]
kpath := sub(path, k)
if aok && !bok {
diffs = append(diffs, Diff{Path: kpath, Msg: "only in nix"})
} else if !aok && bok {
diffs = append(diffs, Diff{Path: kpath, Msg: "only in go"})
} else {
// Both present. nil means no default.
diffs = append(diffs, compareNodes(av, bv, kpath)...)
}
}
return diffs
}
func compareInheritFrom(a, b []InheritFromGroup, path string) []Diff {
var diffs []Diff
if len(a) != len(b) {
diffs = append(diffs, Diff{Path: path, Msg: fmt.Sprintf("length: nix=%d, go=%d", len(a), len(b))})
}
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
ipath := fmt.Sprintf("%s[%d]", path, i)
diffs = append(diffs, compareNodes(a[i].From, b[i].From, sub(ipath, "from"))...)
if !stringSliceEqual(a[i].Attrs, b[i].Attrs) {
diffs = append(diffs, Diff{
Path: sub(ipath, "attrs"),
Msg: fmt.Sprintf("nix=%v, go=%v", a[i].Attrs, b[i].Attrs),
})
}
}
return diffs
}
func compareDynAttrs(a, b []DynAttrNode, path string) []Diff {
var diffs []Diff
if len(a) != len(b) {
diffs = append(diffs, Diff{Path: path, Msg: fmt.Sprintf("length: nix=%d, go=%d", len(a), len(b))})
}
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
ipath := fmt.Sprintf("%s[%d]", path, i)
diffs = append(diffs, compareNodes(a[i].Name, b[i].Name, sub(ipath, "name"))...)
diffs = append(diffs, compareNodes(a[i].Value, b[i].Value, sub(ipath, "value"))...)
}
return diffs
}
func compareAttrPath(a, b []AttrPathElem, path string) []Diff {
var diffs []Diff
if len(a) != len(b) {
diffs = append(diffs, Diff{Path: path, Msg: fmt.Sprintf("length: nix=%d, go=%d", len(a), len(b))})
}
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
ipath := fmt.Sprintf("%s[%d]", path, i)
if a[i].Static != "" || b[i].Static != "" {
if a[i].Static != b[i].Static {
diffs = append(diffs, Diff{Path: ipath, Msg: fmt.Sprintf("nix=%q, go=%q", a[i].Static, b[i].Static)})
}
} else {
diffs = append(diffs, compareNodes(a[i].Dynamic, b[i].Dynamic, ipath)...)
}
}
return diffs
}
func stringSliceEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// FormatDiffs formats a slice of Diff values as a human-readable multi-line string.
func FormatDiffs(diffs []Diff) string {
if len(diffs) == 0 {
return ""
}
var sb strings.Builder
for i, d := range diffs {
if i > 0 {
sb.WriteByte('\n')
}
sb.WriteString(d.String())
}
return sb.String()
}
|