|
1 | 1 | package bindings
|
2 | 2 |
|
3 |
| -import ( |
4 |
| - "fmt" |
5 |
| - "reflect" |
6 |
| -) |
7 |
| - |
8 | 3 | // DeclarationType is any type that can exist at the top level of a AST.
|
9 | 4 | // Meaning it can be serialized into valid Typescript.
|
10 | 5 | type DeclarationType interface {
|
@@ -69,23 +64,41 @@ func (p *TypeParameter) isNode() {}
|
69 | 64 |
|
70 | 65 | // Simplify removes duplicate type parameters
|
71 | 66 | func Simplify(p []*TypeParameter) ([]*TypeParameter, error) {
|
72 |
| - params := make([]*TypeParameter, 0, len(p)) |
73 |
| - exists := make(map[string]*TypeParameter) |
| 67 | + params := []*TypeParameter{} |
| 68 | + set := make(map[string]bool) |
74 | 69 | for _, tp := range p {
|
75 |
| - if found, ok := exists[tp.Name.Ref()]; ok { |
76 |
| - // Compare types, make sure they are the same |
77 |
| - equal := reflect.DeepEqual(found, tp) |
78 |
| - if !equal { |
79 |
| - return nil, fmt.Errorf("type parameter %q already exists with different type", tp.Name) |
| 70 | + ref := tp.Name.Ref() |
| 71 | + if _, ok := set[ref]; !ok { |
| 72 | + params = append(params, tp) |
| 73 | + set[ref] = true |
| 74 | + |
| 75 | + if union, ok := tp.Type.(*UnionType); ok { |
| 76 | + simplifyUnionLiterals(union) |
80 | 77 | }
|
81 |
| - continue |
82 | 78 | }
|
83 |
| - params = append(params, tp) |
84 |
| - exists[tp.Name.Ref()] = tp |
85 | 79 | }
|
86 | 80 | return params, nil
|
87 | 81 | }
|
88 | 82 |
|
| 83 | +func simplifyUnionLiterals(union *UnionType) *UnionType { |
| 84 | + types := []ExpressionType{} |
| 85 | + literalSet := map[string]bool{} |
| 86 | + for _, arg := range union.Types { |
| 87 | + switch v := arg.(type) { |
| 88 | + case *LiteralKeyword: |
| 89 | + key := v.String() |
| 90 | + if _, ok := literalSet[key]; !ok { |
| 91 | + literalSet[key] = true |
| 92 | + types = append(types, arg) |
| 93 | + } |
| 94 | + default: |
| 95 | + types = append(types, arg) |
| 96 | + } |
| 97 | + } |
| 98 | + union.Types = types |
| 99 | + return union |
| 100 | +} |
| 101 | + |
89 | 102 | // VariableStatement is a top level declaration of a variable
|
90 | 103 | // var foo: string = "bar"
|
91 | 104 | // const foo: string = "bar"
|
|
0 commit comments