1 package loader
2 3 // Synthetic String() methods for structs and named func types.
4 //
5 // fmt takes ...Stringer, so a type with no declared String() has no printable
6 // form: stage4 used to print '?' and legacy refused the package. The compiler
7 // declares one for every such type (a declared String always wins), and the
8 // body calls runtime.RenderValue, which walks the type descriptor. The method
9 // is injected as ordinary source and parsed, so the type checker and the code
10 // generator see a normal method.
11 //
12 // This file is the legacy side of the same rule; _mxc_stage4/ir_typecheck.mx
13 // injectBuiltinString is the stage4 side. Wood law: both or neither.
14 15 import (
16 "bytes"
17 "fmt"
18 "go/ast"
19 "os"
20 "path/filepath"
21 "go/parser"
22 "go/token"
23 "go/types"
24 "strconv"
25 "strings"
26 )
27 28 // renderSkipPkg reports whether the package is inside runtime's own import
29 // closure: the synthesized method imports runtime, and runtime already imports
30 // these, so the import would be a cycle. The list is runtime's measured
31 // transitive import closure (11 packages) and must be recomputed if runtime's
32 // imports change.
33 func renderSkipPkg(pkgPath string) bool {
34 switch pkgPath {
35 case "array", "errors", "moxielang.dev/pkg/mxregexp",
36 "moxielang.dev/pkg/mxutil", "internal/binary", "internal/task", "io",
37 "math/bits", "moxie", "runtime", "runtime/interrupt", "unsafe":
38 return true
39 }
40 return false
41 }
42 43 // renderUserPkg reports whether the package belongs to the program being built
44 // rather than to the toolchain's own stdlib. Synthesizing String() for every
45 // stdlib struct was measured to be unshippable: the method lands in each type's
46 // export data and in the Stringer dispatch table, and a ~250-package fixture
47 // grew past the compiler's type-check arena before it linked. User code is
48 // where the request came from and its type set is small; a stdlib type that is
49 // printed needs a declared String() until the builtin method is served from
50 // the dispatch default instead of a per-type declaration.
51 func renderUserPkg(dir, goroot string) bool {
52 if dir == "" || goroot == "" {
53 return false
54 }
55 if dir == goroot || strings.HasPrefix(dir, goroot+string(filepath.Separator)) {
56 return false
57 }
58 return true
59 }
60 61 // recvBaseName returns the base type name of a method receiver expression.
62 func recvBaseName(e ast.Expr) string {
63 switch r := e.(type) {
64 case *ast.Ident:
65 return r.Name
66 case *ast.StarExpr:
67 return recvBaseName(r.X)
68 case *ast.ParenExpr:
69 return recvBaseName(r.X)
70 case *ast.IndexExpr:
71 return recvBaseName(r.X)
72 }
73 return ""
74 }
75 76 // injectBuiltinStrings appends one synthetic file declaring String() for every
77 // struct and named func type in the package that does not already declare one,
78 // and returns the extended file list.
79 func (p *Package) injectBuiltinStrings(files []*ast.File) ([]*ast.File, error) {
80 if renderSkipPkg(p.ImportPath) || !renderUserPkg(p.Dir, p.program.goroot) {
81 return files, nil
82 }
83 declared := make(map[string]bool)
84 var specs []*ast.TypeSpec
85 for _, f := range files {
86 for _, d := range f.Decls {
87 switch d := d.(type) {
88 case *ast.FuncDecl:
89 if d.Recv != nil && d.Name != nil && d.Name.Name == "String" && len(d.Recv.List) == 1 {
90 if n := recvBaseName(d.Recv.List[0].Type); n != "" {
91 declared[n] = true
92 }
93 }
94 case *ast.GenDecl:
95 if d.Tok != token.TYPE {
96 continue
97 }
98 for _, s := range d.Specs {
99 ts, ok := s.(*ast.TypeSpec)
100 if !ok {
101 continue
102 }
103 specs = append(specs, ts)
104 }
105 }
106 }
107 }
108 109 // Package source, for the used test: the type declaration itself is one
110 // mention, and a second mention is a use by this package. An unexported
111 // type that is never mentioned twice cannot reach a Stringer slot anywhere
112 // (unexported names are package-local), so it gets no method. Exported
113 // types are always kept: another package can place them in a slot, which
114 // this package cannot see.
115 var pkgSource []byte
116 for _, f := range p.GoFiles {
117 data, rerr := os.ReadFile(filepath.Join(p.Dir, f))
118 if rerr != nil {
119 continue
120 }
121 pkgSource = append(pkgSource, data...)
122 pkgSource = append(pkgSource, '\n')
123 }
124 125 var b strings.Builder
126 needRuntime := false
127 for _, ts := range specs {
128 if ts.Name == nil || ts.Assign.IsValid() || ts.TypeParams != nil || declared[ts.Name.Name] {
129 continue
130 }
131 if !isExportedName(ts.Name.Name) && !mentionCountAtLeast(pkgSource, ts.Name.Name, 2) {
132 continue
133 }
134 switch t := ts.Type.(type) {
135 case *ast.StructType:
136 // A struct with an embedded field may already promote a String();
137 // synthesizing one would replace that promotion.
138 embedded := false
139 if t.Fields != nil {
140 for _, f := range t.Fields.List {
141 if len(f.Names) == 0 {
142 embedded = true
143 }
144 }
145 }
146 if embedded {
147 continue
148 }
149 needRuntime = true
150 fmt.Fprintf(&b, "func (p *%s) String() (s string) {\n", ts.Name.Name)
151 b.WriteString("\treturn runtime.RenderValue((*runtime.RawType)(unsafe.TypeOf(*p)), unsafe.Pointer(p))\n}\n\n")
152 case *ast.FuncType:
153 fmt.Fprintf(&b, "func (p *%s) String() (s string) { return %s }\n\n",
154 ts.Name.Name, strconv.Quote(types.ExprString(t)))
155 }
156 }
157 if b.Len() == 0 {
158 return files, nil
159 }
160 var src strings.Builder
161 fmt.Fprintf(&src, "package %s\n\nimport (\n", p.Name)
162 if needRuntime {
163 src.WriteString("\t\"runtime\"\n\t\"unsafe\"\n")
164 }
165 src.WriteString(")\n\n")
166 src.WriteString(b.String())
167 f, err := parser.ParseFile(p.program.fset, "<moxie:stringers>", src.String(), 0)
168 if err != nil {
169 return nil, fmt.Errorf("synthetic String methods for %s: %w", p.ImportPath, err)
170 }
171 if !needRuntime {
172 // The file only declares constant-returning methods; the empty import
173 // block above is still valid, but keep the file only if it parsed.
174 return append(files, f), nil
175 }
176 return append(files, f), nil
177 }
178 179 // isExportedName reports whether name starts with an upper-case letter, the
180 // same rule the language uses.
181 func isExportedName(name string) bool {
182 if name == "" {
183 return false
184 }
185 return name[0] >= 'A' && name[0] <= 'Z'
186 }
187 188 func isIdentByte(b byte) bool {
189 return b == '_' || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9')
190 }
191 192 // mentionCountAtLeast reports whether src names ident at least n times as a
193 // whole identifier. Comments and strings count, which can only keep a method
194 // that was not strictly needed, never drop one that was.
195 func mentionCountAtLeast(src []byte, ident string, n int) bool {
196 if ident == "" {
197 return false
198 }
199 seen := 0
200 for i := 0; i+len(ident) <= len(src); i++ {
201 if src[i] != ident[0] {
202 continue
203 }
204 if i > 0 && isIdentByte(src[i-1]) {
205 continue
206 }
207 if !bytes.Equal(src[i:i+len(ident)], []byte(ident)) {
208 continue
209 }
210 if i+len(ident) < len(src) && isIdentByte(src[i+len(ident)]) {
211 continue
212 }
213 seen++
214 if seen >= n {
215 return true
216 }
217 }
218 return false
219 }
220