/
array.go
55 lines (44 loc) · 1.5 KB
/
array.go
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
package prefixer
import (
"errors"
"fmt"
"go/ast"
)
// Slice represents the token for a go slice prefix.
const Slice = "[]"
// arrayPrefixer implements Prefixer for ArrayType.
type arrayPrefixer struct {
*ast.ArrayType
LenPrefixer Prefixer
EltPrefixer Prefixer
}
var _ Prefixer = &arrayPrefixer{} // ensure interface is implemented
// Valid validates the prefixer and its subprefixers.
//
// An example would be a composition of a StarExpr with an ArrayType of an Ident.
// In that case, all three prefixers computed from those ast.Expr will be validated with Valid.
func (a *arrayPrefixer) Valid() error {
var errs []error
if a.Len != nil {
// retrieve prefixer associated to ellipsis [X]
a.LenPrefixer = NewPrefixer(a.Len)
errs = append(errs, a.LenPrefixer.Valid())
}
// retrieve prefixer associated to slice/array element
a.EltPrefixer = NewPrefixer(a.Elt)
errs = append(errs, a.EltPrefixer.Valid())
return errors.Join(errs...)
}
// ToString transforms a Prefixer (ast.Expr) into its string representation.
// It also returns a boolean indicating whether the type is exported.
func (a *arrayPrefixer) ToString(sourcePackage string, typeParams []string, prefixes ...string) (_ string, _ bool) {
prefix := func() string {
if a.LenPrefixer == nil {
return Slice
}
ellipsis, _ := a.LenPrefixer.ToString("", nil)
return fmt.Sprintf("[%s]", ellipsis)
}()
// retrieve prefixer associated to slice/array element
return a.EltPrefixer.ToString(sourcePackage, typeParams, append(prefixes, prefix)...)
}