-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathbetteralign_unit_test.go
More file actions
2180 lines (1997 loc) · 80.2 KB
/
Copy pathbetteralign_unit_test.go
File metadata and controls
2180 lines (1997 loc) · 80.2 KB
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
// Copyright (c) 2026 Dinko Korunic <dinko.korunic@gmail.com>
//
// SPDX-FileCopyrightText: Copyright (c) 2026 Dinko Korunic <dinko.korunic@gmail.com>
// SPDX-License-Identifier: BSD-3-Clause
package betteralign
// Unit tests for unexported helpers. BUG-xx cases pin specific historical mutants.
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"math"
"os"
"path/filepath"
"strings"
"testing"
"time"
dst "github.com/dkorunic/betteralign/internal/dstmin"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/ast/inspector"
)
// testSizes64 is the 64-bit gcSizes used by every size/alignment expectation here.
var testSizes64 = &gcSizes{WordSize: 8, MaxAlign: 8}
// ─── Layer 1: align() (BUG-01) ────────────────────────────────────────────────
// TestAlign verifies the round-up-to-alignment helper.
// BUG-01: using x+a instead of x+a-1 causes already-aligned values to
// overshoot to the next boundary (e.g. align(8,8)==16 instead of 8).
func TestAlign(t *testing.T) {
tests := []struct {
name string
x, a, want int64
}{
// Already-aligned inputs must not move (BUG-01 would overshoot).
{"already aligned 8/8", 8, 8, 8},
{"already aligned 4/4", 4, 4, 4},
{"already aligned 0/8", 0, 8, 0},
{"already aligned 16/8", 16, 8, 16},
// Normal round-up cases.
{"round up 7 to 8", 7, 8, 8},
{"round up 1 to 4", 1, 4, 4},
{"round up 9 to 16", 9, 8, 16},
// Alignment-1 is always already aligned.
{"align-1 identity", 5, 1, 5},
{"align-1 zero", 0, 1, 0},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := align(tc.x, tc.a)
if got != tc.want {
t.Errorf("align(%d, %d) = %d, want %d", tc.x, tc.a, got, tc.want)
}
})
}
}
// ─── Layer 2: gcSizes.Alignof (BUG-02, BUG-03) ────────────────────────────────
// TestGcSizesAlignofArray verifies that an array's alignment equals its
// element's alignment, not 1.
// BUG-02: returning 1 unconditionally for arrays.
func TestGcSizesAlignofArray(t *testing.T) {
// [4]uint64 must have alignment 8 (element alignment), not 1.
arrU64 := types.NewArray(types.Typ[types.Uint64], 4)
if got := testSizes64.Alignof(arrU64); got != 8 {
t.Errorf("Alignof([4]uint64) = %d, want 8 (BUG-02 would return 1)", got)
}
// [100]bool must have alignment 1 (element alignment).
arrBool := types.NewArray(types.Typ[types.Bool], 100)
if got := testSizes64.Alignof(arrBool); got != 1 {
t.Errorf("Alignof([100]bool) = %d, want 1", got)
}
// Cases where element-size ≠ element-alignment, to distinguish Alignof from Sizeof.
arrInt8 := types.NewArray(types.Typ[types.Int8], 8)
if got := testSizes64.Alignof(arrInt8); got != 1 {
t.Errorf("Alignof([8]int8) = %d, want 1 (Sizeof-mutation would return 8)", got)
}
inner := types.NewArray(types.Typ[types.Int8], 8)
outer := types.NewArray(inner, 4)
if got := testSizes64.Alignof(outer); got != 1 {
t.Errorf("Alignof([4][8]int8) = %d, want 1", got)
}
}
// TestGcSizesAlignofStruct verifies that a struct's alignment is the maximum
// field alignment, not the minimum.
// BUG-03: using < instead of > in the running-max comparison.
func TestGcSizesAlignofStruct(t *testing.T) {
// struct{bool;uint64}: max(1,8) = 8 (BUG-03 would yield min = 1).
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "x", types.Typ[types.Bool]),
types.NewVar(token.NoPos, nil, "y", types.Typ[types.Uint64]),
}
mixedStruct := types.NewStruct(fields, nil)
if got := testSizes64.Alignof(mixedStruct); got != 8 {
t.Errorf("Alignof(struct{bool;uint64}) = %d, want 8 (BUG-03 would return 1)", got)
}
// Empty struct must have alignment >= 1 (spec).
emptyStruct := types.NewStruct(nil, nil)
if got := testSizes64.Alignof(emptyStruct); got < 1 {
t.Errorf("Alignof(struct{}) = %d, want >= 1", got)
}
}
// ─── Layer 3: gcSizes.Sizeof (BUG-04 … BUG-08) ────────────────────────────────
// TestGcSizesSizeofString verifies that string is measured as two words.
// BUG-04: returning WordSize (one word) instead of WordSize*2.
func TestGcSizesSizeofString(t *testing.T) {
got := testSizes64.Sizeof(types.Typ[types.String])
if got != 16 {
t.Errorf("Sizeof(string) = %d, want 16 (BUG-04 would return 8)", got)
}
}
// TestGcSizesSizeofSlice verifies that a slice header is three words.
// BUG-05: returning WordSize*2 (two words) instead of WordSize*3.
func TestGcSizesSizeofSlice(t *testing.T) {
sliceInt := types.NewSlice(types.Typ[types.Int])
got := testSizes64.Sizeof(sliceInt)
if got != 24 {
t.Errorf("Sizeof([]int) = %d, want 24 (BUG-05 would return 16)", got)
}
}
// TestGcSizesSizeofArray verifies that array size is element-count × element-size.
// BUG-06: returning element count alone (forgetting to multiply by element size).
func TestGcSizesSizeofArray(t *testing.T) {
// [8]uint64 = 8 × 8 = 64 bytes; BUG-06 would return 8.
arr := types.NewArray(types.Typ[types.Uint64], 8)
if got := testSizes64.Sizeof(arr); got != 64 {
t.Errorf("Sizeof([8]uint64) = %d, want 64 (BUG-06 would return 8)", got)
}
// [3]uint32 = 3 × 4 = 12 bytes.
arr2 := types.NewArray(types.Typ[types.Uint32], 3)
if got := testSizes64.Sizeof(arr2); got != 12 {
t.Errorf("Sizeof([3]uint32) = %d, want 12", got)
}
}
// TestGcSizesSizeofEmptyStruct verifies that struct{} has size 0.
// BUG-07: removing the o != 0 guard causes struct{} to be assigned size 1.
func TestGcSizesSizeofEmptyStruct(t *testing.T) {
emptyStruct := types.NewStruct(nil, nil)
if got := testSizes64.Sizeof(emptyStruct); got != 0 {
t.Errorf("Sizeof(struct{}) = %d, want 0 (BUG-07 would return 1)", got)
}
}
// TestGcSizesSizeofTrailingPadding verifies that struct size is rounded up to
// the struct's maximum field alignment (trailing padding is added).
// BUG-08: returning the raw byte offset without the final align() call.
func TestGcSizesSizeofTrailingPadding(t *testing.T) {
// struct{uint64;bool} = 16 with trailing padding (BUG-08 would return 9).
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "x", types.Typ[types.Uint64]),
types.NewVar(token.NoPos, nil, "y", types.Typ[types.Bool]),
}
strType := types.NewStruct(fields, nil)
if got := testSizes64.Sizeof(strType); got != 16 {
t.Errorf("Sizeof(struct{uint64;bool}) = %d, want 16 (BUG-08 would return 9)", got)
}
// struct { uint32; bool } = 4 + 1 + 3 padding = 8.
fields2 := []*types.Var{
types.NewVar(token.NoPos, nil, "x", types.Typ[types.Uint32]),
types.NewVar(token.NoPos, nil, "y", types.Typ[types.Bool]),
}
strType2 := types.NewStruct(fields2, nil)
if got := testSizes64.Sizeof(strType2); got != 8 {
t.Errorf("Sizeof(struct{uint32;bool}) = %d, want 8", got)
}
}
// ─── Layer 4: gcSizes.ptrdata (BUG-09 … BUG-12) ──────────────────────────────
// TestGcSizesPtrdataString verifies that string contributes one pointer word.
// BUG-09: treating string as non-pointer-bearing (returning 0).
func TestGcSizesPtrdataString(t *testing.T) {
got := testSizes64.ptrdata(types.Typ[types.String])
if got != 8 {
t.Errorf("ptrdata(string) = %d, want 8 (BUG-09 would return 0)", got)
}
}
// TestGcSizesPtrdataInterface verifies that an interface contributes two pointer words.
// BUG-10: returning WordSize (one word) instead of 2×WordSize.
func TestGcSizesPtrdataInterface(t *testing.T) {
iface := types.NewInterfaceType(nil, nil)
got := testSizes64.ptrdata(iface)
if got != 16 {
t.Errorf("ptrdata(interface{}) = %d, want 16 (BUG-10 would return 8)", got)
}
}
// TestGcSizesPtrdataArray verifies the array ptrdata formula: (n-1)*stride + elem_ptrdata.
// BUG-11: using n instead of n-1, overestimating by one element's stride.
func TestGcSizesPtrdataArray(t *testing.T) {
// [3]*int = (3-1)*8 + 8 = 24 (BUG-11 uses n instead of n-1 → 32).
ptrInt := types.NewPointer(types.Typ[types.Int])
arr := types.NewArray(ptrInt, 3)
if got := testSizes64.ptrdata(arr); got != 24 {
t.Errorf("ptrdata([3]*int) = %d, want 24 (BUG-11 would return 32)", got)
}
// [1]*int: (1-1)*8 + 8 = 8.
arr1 := types.NewArray(ptrInt, 1)
if got := testSizes64.ptrdata(arr1); got != 8 {
t.Errorf("ptrdata([1]*int) = %d, want 8", got)
}
// [4]int (no pointers): ptrdata = 0.
arrInt := types.NewArray(types.Typ[types.Int], 4)
if got := testSizes64.ptrdata(arrInt); got != 0 {
t.Errorf("ptrdata([4]int) = %d, want 0", got)
}
}
// TestGcSizesPtrdataStructOffset verifies that struct ptrdata records the pointer
// extent using the field's offset before advancing, not after.
// BUG-12: advancing o += sz before recording p = o + fp, shifting all pointer
// extents by one field's size.
func TestGcSizesPtrdataStructOffset(t *testing.T) {
// struct{*int;int}: ptrdata = 8 (BUG-12 would report 16 by advancing o before recording p).
ptrInt := types.NewPointer(types.Typ[types.Int])
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "ptr", ptrInt),
types.NewVar(token.NoPos, nil, "val", types.Typ[types.Int]),
}
strType := types.NewStruct(fields, nil)
if got := testSizes64.ptrdata(strType); got != 8 {
t.Errorf("ptrdata(struct{*int;int}) = %d, want 8 (BUG-12 would return 16)", got)
}
}
// ─── Layer 4.5: gcSizes cycle safety (BUG-29) ────────────────────────────────
// TestGcSizesCycleSafety pins the sentinel-pre-population in Alignof / Sizeof
// / ptrdata. The trigger is a self-embedding struct whose composite-literal
// use forces go/types to materialise the struct type instead of replacing
// it with Invalid. Without the literal, the type-checker's cycle detector
// rewrites e to *types.Basic[Invalid] and the bug stays dormant.
//
// BUG-29: cache filled only after recursion returns, so the in-progress call
// re-enters itself, recurses without bound, and exhausts the goroutine
// stack. Found by FuzzOptimalOrder; trigger pinned as fuzz seed
// testdata/fuzz/FuzzOptimalOrder/bug29_recursive_struct.
//
// The watchdog guards against a regression hanging the whole test binary:
// the goroutine running optimalOrder still leaks until the process exits,
// but the test result is deterministic.
func TestGcSizesCycleSafety(t *testing.T) {
const src = `package p
type e struct {
e
}
var _ = e{}
`
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "in.go", src, 0)
if err != nil {
t.Fatalf("parse: %v", err)
}
conf := types.Config{Error: func(error) {}, Importer: nil}
pkg, _ := conf.Check("p", fset, []*ast.File{file}, nil)
if pkg == nil {
t.Fatal("nil package from type-check")
}
tn, ok := pkg.Scope().Lookup("e").(*types.TypeName)
if !ok {
t.Fatal("type e missing from scope")
}
named, ok := tn.Type().(*types.Named)
if !ok {
t.Fatalf("e.Type() = %T, want *types.Named", tn.Type())
}
st, ok := named.Origin().Underlying().(*types.Struct)
if !ok {
t.Skipf("type-checker no longer admits self-embedding here (Underlying = %T); BUG-29 trigger neutralised upstream", named.Underlying())
}
if st.NumFields() == 0 || st.Field(0).Type() != named {
t.Skip("type-checker no longer makes field[0] self-referential; BUG-29 trigger neutralised upstream")
}
sizes := newGCSizes(8, 8)
type result struct {
indexes []int
optSize, optPtrdata int64
}
resCh := make(chan result, 1)
go func() {
indexes, optSize, optPtrdata := optimalOrder(st, sizes)
resCh <- result{indexes, optSize, optPtrdata}
}()
var res result
select {
case res = <-resCh:
case <-time.After(5 * time.Second):
t.Fatal("BUG-29: optimalOrder did not terminate within 5s on a self-embedding struct (cache sentinel missing)")
}
if len(res.indexes) != st.NumFields() {
t.Errorf("len(indexes) = %d, want %d", len(res.indexes), st.NumFields())
}
seen := make([]bool, st.NumFields())
for _, i := range res.indexes {
if i < 0 || i >= st.NumFields() {
t.Errorf("index %d out of range [0,%d)", i, st.NumFields())
continue
}
if seen[i] {
t.Errorf("index %d appears twice", i)
}
seen[i] = true
}
if origSize := sizes.Sizeof(st); res.optSize > origSize {
t.Errorf("optSize=%d > origSize=%d", res.optSize, origSize)
}
if origPtrdata := sizes.ptrdata(st); res.optPtrdata > origPtrdata {
t.Errorf("optPtrdata=%d > origPtrdata=%d", res.optPtrdata, origPtrdata)
}
}
// ─── Layer 4.6: gcSizes overflow safety (BUG-30) ─────────────────────────────
// TestGcSizesArrayOverflowSaturates pins saturation in Sizeof / ptrdata array paths.
// BUG-30: raw int64 multiply on huge arrays wrapped Sizeof to MinInt64.
// Fuzz seed testdata/fuzz/FuzzGCSizes/d713d410fe8c6747 is the corpus-level regression.
func TestGcSizesArrayOverflowSaturates(t *testing.T) {
sizes := newGCSizes(8, 8)
huge := types.NewArray(types.Typ[types.Uint64], 1<<60)
if got := sizes.Sizeof(huge); got < 0 {
t.Errorf("Sizeof saturating: got %d (negative), want MaxInt64", got)
}
hugePtrs := types.NewArray(types.NewPointer(types.Typ[types.Int]), 1<<60)
sz := sizes.Sizeof(hugePtrs)
pd := sizes.ptrdata(hugePtrs)
if pd < 0 || sz < 0 {
t.Errorf("array of pointers overflow: Sizeof=%d ptrdata=%d, want both non-negative", sz, pd)
}
if pd > sz {
t.Errorf("invariant violation: ptrdata=%d > Sizeof=%d", pd, sz)
}
}
// TestAlignSaturationBoundary pins the `(a-1)` off-by-one in align()'s overflow guard.
func TestAlignSaturationBoundary(t *testing.T) {
cases := []struct {
name string
x, a int64
want int64
}{
// MaxInt64-3 with a=4: result is MaxInt64-3 (no saturation); off-by-one mutation saturates.
{"boundary x=MaxInt64-3 a=4", math.MaxInt64 - 3, 4, math.MaxInt64 - 3},
{"saturates x=MaxInt64-2 a=4", math.MaxInt64 - 2, 4, math.MaxInt64},
{"already aligned MaxInt64-7 a=8", math.MaxInt64 - 7, 8, math.MaxInt64 - 7},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := align(tc.x, tc.a); got != tc.want {
t.Errorf("align(%d, %d) = %d, want %d", tc.x, tc.a, got, tc.want)
}
})
}
}
// TestAddSizeArgOrder pins the operand pairing in addSize's `a > MaxInt64-b` guard.
// An asymmetric (a, b) distinguishes the baseline from the `MaxInt64-a` typo.
func TestAddSizeArgOrder(t *testing.T) {
const a int64 = math.MaxInt64 - 20
const b int64 = 10
const want = math.MaxInt64 - 10
if got := addSize(a, b); got != want {
t.Errorf("addSize(%d, %d) = %d, want %d (typo `a > MaxInt64-a` would saturate)", a, b, got, want)
}
}
// TestMulSizeSaturates pins the saturating-multiply helper directly.
func TestMulSizeSaturates(t *testing.T) {
cases := []struct {
name string
n, size int64
want int64
}{
{"normal", 10, 8, 80},
{"zero size", 100, 0, 0},
{"zero n", 0, 100, 0},
{"negative n", -1, 100, 0},
{"overflow saturates", 1 << 60, 1 << 10, math.MaxInt64},
{"exact MaxInt64", math.MaxInt64, 1, math.MaxInt64},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := mulSize(tc.n, tc.size); got != tc.want {
t.Errorf("mulSize(%d, %d) = %d, want %d", tc.n, tc.size, got, tc.want)
}
})
}
}
// TestAddSizeSaturates pins the saturating-add helper directly.
func TestAddSizeSaturates(t *testing.T) {
cases := []struct {
name string
a, b int64
want int64
}{
{"normal", 10, 20, 30},
{"overflow saturates", math.MaxInt64 - 5, 10, math.MaxInt64},
{"max + zero", math.MaxInt64, 0, math.MaxInt64},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := addSize(tc.a, tc.b); got != tc.want {
t.Errorf("addSize(%d, %d) = %d, want %d", tc.a, tc.b, got, tc.want)
}
})
}
}
// ─── Layer 5: optimalOrder sort comparator (BUG-13 … BUG-17) ─────────────────
// TestOptimalOrderZeroSizedFirst verifies that zero-sized fields sort before
// non-zero-sized fields.
// BUG-13: returning zeroj instead of zeroi places zero-sized fields last.
func TestOptimalOrderZeroSizedFirst(t *testing.T) {
// struct { int32; struct{} }: struct{} (zero-sized) must sort first.
emptyStruct := types.NewStruct(nil, nil)
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "x", types.Typ[types.Int32]),
types.NewVar(token.NoPos, nil, "z", emptyStruct),
}
strType := types.NewStruct(fields, nil)
indexes, _, _ := optimalOrder(strType, testSizes64)
if len(indexes) != 2 {
t.Fatalf("expected 2 indexes, got %d", len(indexes))
}
// indexes[0] == 1 means struct{} (original index 1) is placed first.
if indexes[0] != 1 {
t.Errorf("zero-sized field should be first: indexes[0] = %d, want 1 (BUG-13 places it last)", indexes[0])
}
}
// TestOptimalOrderHighAlignmentFirst verifies that higher-alignment fields sort
// before lower-alignment fields.
// BUG-14: using < instead of > in the alignment comparison.
func TestOptimalOrderHighAlignmentFirst(t *testing.T) {
// struct { bool; uint64 }: uint64 (align=8) must precede bool (align=1).
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "b", types.Typ[types.Bool]),
types.NewVar(token.NoPos, nil, "u", types.Typ[types.Uint64]),
}
strType := types.NewStruct(fields, nil)
indexes, _, _ := optimalOrder(strType, testSizes64)
if len(indexes) != 2 {
t.Fatalf("expected 2 indexes, got %d", len(indexes))
}
// indexes[0] == 1 means uint64 (original index 1) is placed first.
if indexes[0] != 1 {
t.Errorf("uint64 (align=8) should be first: indexes[0] = %d, want 1 (BUG-14 inverts order)", indexes[0])
}
}
// TestOptimalOrderPointerBearingFirst verifies that pointer-bearing fields sort
// before pointer-free fields of the same alignment.
// BUG-15: returning noptrsi instead of noptrsj swaps the placement.
func TestOptimalOrderPointerBearingFirst(t *testing.T) {
// Same alignment 8; *int (pointer-bearing) must precede uint64.
ptrInt := types.NewPointer(types.Typ[types.Int])
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "u", types.Typ[types.Uint64]),
types.NewVar(token.NoPos, nil, "p", ptrInt),
}
strType := types.NewStruct(fields, nil)
indexes, _, _ := optimalOrder(strType, testSizes64)
if len(indexes) != 2 {
t.Fatalf("expected 2 indexes, got %d", len(indexes))
}
// indexes[0] == 1 means *int (original index 1) is placed first.
if indexes[0] != 1 {
t.Errorf("*int (pointer-bearing) should be first: indexes[0] = %d, want 1 (BUG-15 inverts)", indexes[0])
}
}
// TestOptimalOrderFewerTrailingFirst verifies that among pointer-bearing fields,
// the one with fewer trailing non-pointer bytes sorts first.
// BUG-16: using > instead of < inverts the trailing-bytes comparison.
func TestOptimalOrderFewerTrailingFirst(t *testing.T) {
// *int (trailing=0) must precede string (trailing=8) under the fewer-trailing rule.
ptrInt := types.NewPointer(types.Typ[types.Int])
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "s", types.Typ[types.String]),
types.NewVar(token.NoPos, nil, "p", ptrInt),
}
strType := types.NewStruct(fields, nil)
indexes, _, _ := optimalOrder(strType, testSizes64)
if len(indexes) != 2 {
t.Fatalf("expected 2 indexes, got %d", len(indexes))
}
// indexes[0] == 1 means *int (original index 1) is placed first.
if indexes[0] != 1 {
t.Errorf("*int (trailing=0) should be first: indexes[0] = %d, want 1 (BUG-16 inverts)", indexes[0])
}
}
// TestOptimalOrderLargerSizeFirst verifies that, as a final tiebreaker, larger
// fields sort before smaller fields when all other criteria are equal.
// BUG-17: using < instead of > places smaller fields first.
func TestOptimalOrderLargerSizeFirst(t *testing.T) {
// Same align/ptrdata; [2]uint32 (larger) must precede uint32 as final tiebreak.
arr2u32 := types.NewArray(types.Typ[types.Uint32], 2)
fields := []*types.Var{
types.NewVar(token.NoPos, nil, "u", types.Typ[types.Uint32]),
types.NewVar(token.NoPos, nil, "a", arr2u32),
}
strType := types.NewStruct(fields, nil)
indexes, _, _ := optimalOrder(strType, testSizes64)
if len(indexes) != 2 {
t.Fatalf("expected 2 indexes, got %d", len(indexes))
}
// indexes[0] == 1 means [2]uint32 (original index 1) is placed first.
if indexes[0] != 1 {
t.Errorf("[2]uint32 (larger) should be first: indexes[0] = %d, want 1 (BUG-17 inverts)", indexes[0])
}
}
// ─── Layer 6: hasSuffix ──────────────────────────────────────────────────────
// TestHasSuffix verifies the suffix matcher used to skip test or generated
// files by filename. The previous cached variant (hasSuffixes) was retired in
// favour of a single per-file call from the visitor.
func TestHasSuffix(t *testing.T) {
suffixes := []string{"_test.go", "_generated.go", ".pb.go"}
tests := []struct {
name string
fn string
want bool
}{
{"matches _test.go", "foo_test.go", true},
{"matches .pb.go", "rpc.pb.go", true},
{"matches _generated.go", "schema_generated.go", true},
{"no match plain .go", "foo.go", false},
{"no match different suffix", "foo_tests.go", false},
{"empty filename", "", false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := hasSuffix(tc.fn, suffixes); got != tc.want {
t.Errorf("hasSuffix(%q) = %v, want %v", tc.fn, got, tc.want)
}
})
}
}
// ─── Layer 7: hasGeneratedComment (BUG-23) ───────────────────────────────────
// parseTestFile is a helper that parses src as Go source and returns the *ast.File.
func parseTestFile(t *testing.T, src string) *ast.File {
t.Helper()
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "test.go", src, parser.ParseComments)
if err != nil {
t.Fatalf("parse error: %v", err)
}
return f
}
// TestHasGeneratedComment verifies that the generated-file marker is detected
// only when it appears before the package keyword.
// BUG-23: using < instead of > causes the function to stop at comments that
// precede the package keyword, never inspecting them.
func TestHasGeneratedComment(t *testing.T) {
t.Run("generated comment before package is detected", func(t *testing.T) {
// Canonical "DO NOT EDIT" header (BUG-23 would short-circuit the guard).
f := parseTestFile(t, "// Code generated by foo. DO NOT EDIT.\npackage foo\n")
if !hasGeneratedComment(f) {
t.Error("generated comment before package keyword not detected (BUG-23)")
}
})
t.Run("no generated comment returns false", func(t *testing.T) {
f := parseTestFile(t, "// Regular comment.\npackage foo\n")
if hasGeneratedComment(f) {
t.Error("non-generated comment should not be detected")
}
})
t.Run("generated comment after package keyword is not detected", func(t *testing.T) {
// Post-package comments are not headers and must be ignored.
f := parseTestFile(t, "package foo\n// Code generated by foo. DO NOT EDIT.\n")
if hasGeneratedComment(f) {
t.Error("generated comment after package keyword should not be detected")
}
})
}
// ─── Layer 8: hasIgnoreComment (BUG-24, BUG-25) ──────────────────────────────
// TestHasIgnoreCommentOpening verifies that the betteralign:ignore directive is
// read from the Opening decoration of the field list, not from other positions.
// BUG-24: checking End (closing-brace area) instead of Opening means the
// annotation is never found.
func TestHasIgnoreCommentOpening(t *testing.T) {
t.Run("ignore comment in Opening is detected", func(t *testing.T) {
fl := &dst.FieldList{}
fl.Decs.Opening = dst.Decorations{"// betteralign:ignore"}
if !hasIgnoreComment(fl) {
t.Error("betteralign:ignore in Opening not detected (BUG-24)")
}
})
t.Run("ignore comment in End (node tail) is NOT detected", func(t *testing.T) {
// BUG-24 would also fire on End-decorations; this asserts it doesn't.
fl := &dst.FieldList{}
fl.Decs.End = dst.Decorations{"// betteralign:ignore"}
if hasIgnoreComment(fl) {
t.Error("betteralign:ignore in End should not trigger ignore (BUG-24 would wrongly trigger)")
}
})
t.Run("ignore comment in Start (node head) is NOT detected", func(t *testing.T) {
fl := &dst.FieldList{}
fl.Decs.Start = dst.Decorations{"// betteralign:ignore"}
if hasIgnoreComment(fl) {
t.Error("betteralign:ignore in Start should not trigger ignore")
}
})
t.Run("no decorations returns false", func(t *testing.T) {
fl := &dst.FieldList{}
if hasIgnoreComment(fl) {
t.Error("empty field list should return false")
}
})
t.Run("unrelated comment in Opening does not trigger", func(t *testing.T) {
fl := &dst.FieldList{}
fl.Decs.Opening = dst.Decorations{"// some other comment"}
if hasIgnoreComment(fl) {
t.Error("unrelated Opening comment should not trigger ignore")
}
})
}
// TestHasIgnoreCommentPrefixGuard verifies that only line comments (// prefix)
// can carry the betteralign:ignore directive, not block comments or bare strings.
// BUG-25: removing the HasPrefix("//") guard allows block comments and other
// strings that merely contain the directive substring to trigger ignore.
func TestHasIgnoreCommentPrefixGuard(t *testing.T) {
t.Run("line comment triggers ignore", func(t *testing.T) {
fl := &dst.FieldList{}
fl.Decs.Opening = dst.Decorations{"// betteralign:ignore"}
if !hasIgnoreComment(fl) {
t.Error("line comment with // prefix should trigger ignore")
}
})
t.Run("block comment does NOT trigger ignore", func(t *testing.T) {
// BUG-25 removes HasPrefix("//") so block comments would also match.
fl := &dst.FieldList{}
fl.Decs.Opening = dst.Decorations{"/* betteralign:ignore */"}
if hasIgnoreComment(fl) {
t.Error("block comment should NOT trigger ignore (BUG-25 would wrongly trigger)")
}
})
t.Run("bare string containing directive does NOT trigger ignore", func(t *testing.T) {
// Without the // prefix guard a bare substring match would fire (BUG-25).
fl := &dst.FieldList{}
fl.Decs.Opening = dst.Decorations{"betteralign:ignore"}
if hasIgnoreComment(fl) {
t.Error("bare string without // prefix should NOT trigger ignore (BUG-25 would wrongly trigger)")
}
})
t.Run("partial match without directive does NOT trigger", func(t *testing.T) {
fl := &dst.FieldList{}
fl.Decs.Opening = dst.Decorations{"// betteralign:checked"}
if hasIgnoreComment(fl) {
t.Error("partial directive match should not trigger ignore")
}
})
}
// ─── Layer 8b: hasIgnoreCommentAST (DST-independent ignore) ──────────────────
// firstStructType parses src (with comments) and returns its fileset, file,
// and the first *ast.StructType in preorder.
func firstStructType(t *testing.T, src string) (*token.FileSet, *ast.File, *ast.StructType) {
t.Helper()
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "test.go", src, parser.ParseComments)
if err != nil {
t.Fatalf("parse: %v", err)
}
var st *ast.StructType
ast.Inspect(f, func(n ast.Node) bool {
if s, ok := n.(*ast.StructType); ok && st == nil {
st = s
return false
}
return true
})
if st == nil {
t.Fatal("no struct type in fixture")
}
return fset, f, st
}
// TestHasIgnoreCommentAST pins the DST-independent ignore check: it honors the
// directive only on the opening-brace line (matching hasIgnoreComment's
// Opening routing), so it agrees with the DST path on decoratable structs
// while still working for shapes dstmin cannot decorate.
func TestHasIgnoreCommentAST(t *testing.T) {
cases := []struct {
name string
src string
want bool
}{
{"brace-line directive", "package p\ntype S struct { // betteralign:ignore\n\ta byte\n\tb int64\n}\n", true},
{"directive on first-field line (lead-doc, not Opening)", "package p\ntype S struct {\n\t// betteralign:ignore\n\ta byte\n\tb int64\n}\n", false},
{"unrelated brace-line comment", "package p\ntype S struct { // hello\n\ta byte\n\tb int64\n}\n", false},
{"no comment", "package p\ntype S struct {\n\ta byte\n\tb int64\n}\n", false},
{"block comment does not trigger", "package p\ntype S struct { /* betteralign:ignore */\n\ta byte\n\tb int64\n}\n", false},
// Trailing comment is after the brace, outside the body: not honored.
{"single-line trailing directive not honored", "package p\ntype S struct { a byte; b int64 } // betteralign:ignore\n", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
fset, f, st := firstStructType(t, tc.src)
if got := hasIgnoreCommentAST(fset, f, st); got != tc.want {
t.Errorf("hasIgnoreCommentAST = %v, want %v", got, tc.want)
}
})
}
}
// ─── Layer 9: optimalOrder direct size/ptrdata (P5) ──────────────────────────
// TestOptimalOrderSizeAndPtrdata verifies that the size and ptrdata returned
// directly by optimalOrder match gcSizes.Sizeof / gcSizes.ptrdata computed on
// the same fields re-built in optimal order. The direct computation must
// produce identical numbers to the indirect path for every input.
func TestOptimalOrderSizeAndPtrdata(t *testing.T) {
ptrInt := types.NewPointer(types.Typ[types.Int])
arr2u32 := types.NewArray(types.Typ[types.Uint32], 2)
emptyStruct := types.NewStruct(nil, nil)
cases := []struct {
name string
fields []*types.Var
}{
{"bool_then_uint64", []*types.Var{
types.NewVar(token.NoPos, nil, "b", types.Typ[types.Bool]),
types.NewVar(token.NoPos, nil, "u", types.Typ[types.Uint64]),
}},
{"three_mixed", []*types.Var{
types.NewVar(token.NoPos, nil, "x", types.Typ[types.Bool]),
types.NewVar(token.NoPos, nil, "y", types.Typ[types.Int32]),
types.NewVar(token.NoPos, nil, "z", types.Typ[types.Uint64]),
}},
{"string_then_pointer", []*types.Var{
types.NewVar(token.NoPos, nil, "s", types.Typ[types.String]),
types.NewVar(token.NoPos, nil, "p", ptrInt),
}},
{"zero_sized_field_present", []*types.Var{
types.NewVar(token.NoPos, nil, "x", types.Typ[types.Int32]),
types.NewVar(token.NoPos, nil, "z", emptyStruct),
}},
{"equal_align_size_tiebreak", []*types.Var{
types.NewVar(token.NoPos, nil, "u", types.Typ[types.Uint32]),
types.NewVar(token.NoPos, nil, "a", arr2u32),
}},
{"single_field", []*types.Var{
types.NewVar(token.NoPos, nil, "u", types.Typ[types.Uint64]),
}},
{"empty_struct", nil},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
str := types.NewStruct(tc.fields, nil)
indexes, optSize, optPtrdata := optimalOrder(str, testSizes64)
if len(indexes) != len(tc.fields) {
t.Fatalf("indexes len = %d, want %d", len(indexes), len(tc.fields))
}
ordered := make([]*types.Var, len(indexes))
for i, idx := range indexes {
ordered[i] = str.Field(idx)
}
optStruct := types.NewStruct(ordered, nil)
if got := testSizes64.Sizeof(optStruct); got != optSize {
t.Errorf("size mismatch: optimalOrder=%d, Sizeof(optimalStruct)=%d", optSize, got)
}
if got := testSizes64.ptrdata(optStruct); got != optPtrdata {
t.Errorf("ptrdata mismatch: optimalOrder=%d, ptrdata(optimalStruct)=%d", optPtrdata, got)
}
})
}
}
// ─── Layer 10: applyToFile (BUG-28) ──────────────────────────────────────────
// TestApplyToFileSuccess writes content to a pre-existing file and verifies
// the file contents and mode are preserved as expected. The error paths are
// covered by TestApplyToFileSentinelsAreWrapped below.
func TestApplyToFileSuccess(t *testing.T) {
dir := t.TempDir()
fn := filepath.Join(dir, "target.go")
const initialContent = "package x\nvar X = 1\n"
const newContent = "package x\nvar X = 2\n"
// Use a non-default mode so we can verify it survives the write.
const wantMode os.FileMode = 0o640
if err := os.WriteFile(fn, []byte(initialContent), wantMode); err != nil {
t.Fatalf("seed file: %v", err)
}
if err := applyToFile(fn, []byte(newContent)); err != nil {
t.Fatalf("applyToFile: %v", err)
}
got, err := os.ReadFile(fn)
if err != nil {
t.Fatalf("read back: %v", err)
}
if string(got) != newContent {
t.Errorf("file content mismatch:\n got=%q\nwant=%q", got, newContent)
}
info, err := os.Stat(fn)
if err != nil {
t.Fatalf("stat: %v", err)
}
if info.Mode().Perm() != wantMode.Perm() {
t.Errorf("file mode after write = %o, want %o", info.Mode().Perm(), wantMode.Perm())
}
}
// TestApplyToFileSentinelsAreWrapped verifies that errors returned by
// applyToFile chain to their sentinel via errors.Is.
// BUG-28: formatting sentinels with %v instead of %w makes errors.Is checks
// silently return false, breaking the public error API.
func TestApplyToFileSentinelsAreWrapped(t *testing.T) {
t.Run("non-existent file wraps ErrStatFile", func(t *testing.T) {
err := applyToFile(filepath.Join(t.TempDir(), "does-not-exist.go"), []byte("package x\n"))
if err == nil {
t.Fatal("expected error for missing file, got nil")
}
if !errors.Is(err, ErrStatFile) {
t.Errorf("errors.Is(err, ErrStatFile) = false; err = %v (BUG-28)", err)
}
})
t.Run("directory wraps ErrNotRegularFile", func(t *testing.T) {
dir := t.TempDir()
err := applyToFile(dir, []byte("package x\n"))
if err == nil {
t.Fatal("expected error for directory path, got nil")
}
if !errors.Is(err, ErrNotRegularFile) {
t.Errorf("errors.Is(err, ErrNotRegularFile) = false; err = %v (BUG-28)", err)
}
})
t.Run("symlink to regular file wraps ErrNotRegularFile", func(t *testing.T) {
// Lstat must observe the symlink, not its target.
dir := t.TempDir()
target := filepath.Join(dir, "target.go")
if err := os.WriteFile(target, []byte("package x\n"), 0o644); err != nil {
t.Fatalf("seed target: %v", err)
}
link := filepath.Join(dir, "link.go")
if err := os.Symlink(target, link); err != nil {
t.Skipf("symlink unsupported: %v", err)
}
err := applyToFile(link, []byte("package y\n"))
if err == nil {
t.Fatal("expected error for symlink path, got nil")
}
if !errors.Is(err, ErrNotRegularFile) {
t.Errorf("errors.Is(err, ErrNotRegularFile) = false; err = %v", err)
}
got, err := os.ReadFile(target)
if err != nil {
t.Fatalf("read target after refused write: %v", err)
}
if string(got) != "package x\n" {
t.Errorf("symlink target was modified: got %q, want %q", got, "package x\n")
}
})
}
// ─── Layer 11: StringArrayFlag.Set (BUG-26) ──────────────────────────────────
// TestStringArrayFlagSetEmptyValues verifies that StringArrayFlag.Set never
// appends empty strings.
// BUG-26: strings.Split(value, ",") yields a single empty entry for "" and
// adjacent empty entries for "a,", ",a", and "a,,b". An empty entry in
// excludeDirs makes filepath.Rel(".", dir) succeed for every file, silently
// excluding the entire tree from analysis.
func TestStringArrayFlagSetEmptyValues(t *testing.T) {
tests := []struct {
name string
input string
want []string
}{
{"empty string yields no entries", "", nil},
{"single non-empty value", "a", []string{"a"}},
{"trailing comma drops empty tail", "a,", []string{"a"}},
{"leading comma drops empty head", ",a", []string{"a"}},
{"adjacent commas drop empty middle", "a,,b", []string{"a", "b"}},
{"only commas yields no entries", ",,", nil},
{"surrounding whitespace trimmed", " a , b ", []string{"a", "b"}},
{"tab whitespace trimmed", "\ta\t,\tb\t", []string{"a", "b"}},
{"whitespace-only entries dropped", " , a , ", []string{"a"}},
{"internal whitespace preserved", "my path,other path", []string{"my path", "other path"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var f StringArrayFlag
if err := f.Set(tc.input); err != nil {
t.Fatalf("Set(%q) returned error: %v", tc.input, err)
}
if len(f) != len(tc.want) {
t.Fatalf("Set(%q): got %d entries %v, want %d entries %v",
tc.input, len(f), []string(f), len(tc.want), tc.want)
}
for i := range f {
if f[i] != tc.want[i] {
t.Errorf("Set(%q)[%d] = %q, want %q", tc.input, i, f[i], tc.want[i])
}
}
})
}
}
// ─── Layer 12: commentGroupHasOptIn / isExcluded / commentHasDirective ───────
// makeCommentGroup builds an *ast.CommentGroup from comment text strings.
// Each string must include its // or /* */ markers.
func makeCommentGroup(texts ...string) *ast.CommentGroup {
cg := &ast.CommentGroup{}
for _, t := range texts {
cg.List = append(cg.List, &ast.Comment{Text: t})
}
return cg
}
// TestCommentGroupHasOptInPrefix verifies that only line comments with the
// betteralign:check directive as a separate token (word boundary) trigger
// opt-in. Block comments, substring matches, and missing // prefix must not.
// BUG-27: substring matching (strings.Contains) without a // prefix guard and
// without a word-boundary check accepts block comments and partial directives,
// inconsistent with hasIgnoreComment.
func TestCommentGroupHasOptInPrefix(t *testing.T) {
tests := []struct {
name string
text string
want bool
}{
{"nil group", "", false},
{"line comment with directive", "// betteralign:check", true},
{"line comment with directive and trailing text", "// betteralign:check explanation", true},
{"line comment with directive and tab separator", "// betteralign:check\texplanation", true},
{"line comment with extra spaces before directive", "// betteralign:check", true},
{"block comment is rejected", "/* betteralign:check */", false},
{"bare string without // prefix is rejected", "betteralign:check", false},
{"substring suffix is rejected (checked)", "// betteralign:checked", false},
{"substring prefix is rejected", "// xbetteralign:check", false},
{"unrelated comment", "// some other comment", false},
{"empty line comment", "//", false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var cg *ast.CommentGroup
if tc.text != "" || tc.name == "empty line comment" {
cg = makeCommentGroup(tc.text)
}
got := commentGroupHasOptIn(cg)
if got != tc.want {