| 1 |
// Copyright 2026 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package dfa_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"testing" |
| 9 |
|
| 10 |
"honnef.co/go/tools/analysis/dfa" |
| 11 |
) |
| 12 |
|
| 13 |
type nodeSet uint64 |
| 14 |
|
| 15 |
type nodeSetUnion struct{} |
| 16 |
|
| 17 |
func (nodeSetUnion) Ident() nodeSet { return 0 } |
| 18 |
func (nodeSetUnion) Equals(a, b nodeSet) bool { return a == b } |
| 19 |
func (nodeSetUnion) Merge(a, b nodeSet) nodeSet { return a | b } |
| 20 |
|
| 21 |
var _ dfa.Semilattice[nodeSet] = nodeSetUnion{} |
| 22 |
|
| 23 |
func set(nodes ...int) nodeSet { |
| 24 |
var out nodeSet |
| 25 |
for _, node := range nodes { |
| 26 |
if node < 0 || node >= 64 { |
| 27 |
panic("NodeID out of range") |
| 28 |
} |
| 29 |
out |= 1 << node |
| 30 |
} |
| 31 |
return out |
| 32 |
} |
| 33 |
|
| 34 |
func TestMapLattice_Trivial(t *testing.T) { |
| 35 |
l := dfa.MapLattice[int, nodeSet, nodeSetUnion]{} |
| 36 |
|
| 37 |
// Case 1: a is empty, b is not |
| 38 |
a := map[int]nodeSet{} |
| 39 |
b := map[int]nodeSet{1: set(1)} |
| 40 |
|
| 41 |
got := l.Merge(a, b) |
| 42 |
if !l.Equals(got, b) { |
| 43 |
t.Errorf("Merge(empty, b) = %v, want %v", got, b) |
| 44 |
} |
| 45 |
|
| 46 |
// Case 2: b is empty, a is not |
| 47 |
got = l.Merge(b, a) |
| 48 |
if !l.Equals(got, b) { |
| 49 |
t.Errorf("Merge(b, empty) = %v, want %v", got, b) |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
func TestMapLattice_Merge(t *testing.T) { |
| 54 |
l := dfa.MapLattice[int, nodeSet, nodeSetUnion]{} |
| 55 |
|
| 56 |
a := map[int]nodeSet{ |
| 57 |
1: set(1), // Only in a |
| 58 |
2: set(2), // In both |
| 59 |
} |
| 60 |
b := map[int]nodeSet{ |
| 61 |
2: set(3), // In both |
| 62 |
3: set(4), // Only in b |
| 63 |
} |
| 64 |
|
| 65 |
want := map[int]nodeSet{ |
| 66 |
1: set(1), |
| 67 |
2: set(2, 3), |
| 68 |
3: set(4), |
| 69 |
} |
| 70 |
|
| 71 |
got := l.Merge(a, b) |
| 72 |
if !l.Equals(got, want) { |
| 73 |
t.Errorf("Merge(a, b) = %v, want %v", got, want) |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
func TestDenseMapLattice_Equal(t *testing.T) { |
| 78 |
l := dfa.DenseMapLattice[nodeSet, nodeSetUnion]{} |
| 79 |
|
| 80 |
a := []nodeSet{ |
| 81 |
0: set(), |
| 82 |
1: set(1), |
| 83 |
} |
| 84 |
b := []nodeSet{ |
| 85 |
0: set(), |
| 86 |
1: set(1), |
| 87 |
2: set(), |
| 88 |
} |
| 89 |
|
| 90 |
if !l.Equals(a, b) { |
| 91 |
t.Errorf("Equal(a, b) = false, want true") |
| 92 |
} |
| 93 |
} |