1
2
3
4
5
6
7 package srcimporter
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/build"
13 "go/parser"
14 "go/token"
15 "go/types"
16 exec "internal/execabs"
17 "io"
18 "os"
19 "path/filepath"
20 "strings"
21 "sync"
22 _ "unsafe"
23 )
24
25
26 type Importer struct {
27 ctxt *build.Context
28 fset *token.FileSet
29 sizes types.Sizes
30 packages map[string]*types.Package
31 }
32
33
34
35
36
37
38
39 func New(ctxt *build.Context, fset *token.FileSet, packages map[string]*types.Package) *Importer {
40 return &Importer{
41 ctxt: ctxt,
42 fset: fset,
43 sizes: types.SizesFor(ctxt.Compiler, ctxt.GOARCH),
44 packages: packages,
45 }
46 }
47
48
49
50 var importing types.Package
51
52
53 func (p *Importer) Import(path string) (*types.Package, error) {
54 return p.ImportFrom(path, ".", 0)
55 }
56
57
58
59
60
61
62
63 func (p *Importer) ImportFrom(path, srcDir string, mode types.ImportMode) (*types.Package, error) {
64 if mode != 0 {
65 panic("non-zero import mode")
66 }
67
68 if abs, err := p.absPath(srcDir); err == nil {
69 srcDir = abs
70 }
71 bp, err := p.ctxt.Import(path, srcDir, 0)
72 if err != nil {
73 return nil, err
74 }
75
76
77 if bp.ImportPath == "unsafe" {
78 return types.Unsafe, nil
79 }
80
81
82 pkg := p.packages[bp.ImportPath]
83 if pkg != nil {
84 if pkg == &importing {
85 return nil, fmt.Errorf("import cycle through package %q", bp.ImportPath)
86 }
87 if !pkg.Complete() {
88
89
90
91
92 return pkg, fmt.Errorf("reimported partially imported package %q", bp.ImportPath)
93 }
94 return pkg, nil
95 }
96
97 p.packages[bp.ImportPath] = &importing
98 defer func() {
99
100
101
102
103 if p.packages[bp.ImportPath] == &importing {
104 p.packages[bp.ImportPath] = nil
105 }
106 }()
107
108 var filenames []string
109 filenames = append(filenames, bp.GoFiles...)
110 filenames = append(filenames, bp.CgoFiles...)
111
112 files, err := p.parseFiles(bp.Dir, filenames)
113 if err != nil {
114 return nil, err
115 }
116
117
118 var firstHardErr error
119 conf := types.Config{
120 IgnoreFuncBodies: true,
121
122 Error: func(err error) {
123 if firstHardErr == nil && !err.(types.Error).Soft {
124 firstHardErr = err
125 }
126 },
127 Importer: p,
128 Sizes: p.sizes,
129 }
130 if len(bp.CgoFiles) > 0 {
131 if p.ctxt.OpenFile != nil {
132
133
134 conf.FakeImportC = true
135 } else {
136 setUsesCgo(&conf)
137 file, err := p.cgo(bp)
138 if err != nil {
139 return nil, err
140 }
141 files = append(files, file)
142 }
143 }
144
145 pkg, err = conf.Check(bp.ImportPath, p.fset, files, nil)
146 if err != nil {
147
148
149
150 if firstHardErr != nil {
151 pkg = nil
152 err = firstHardErr
153 }
154 return pkg, fmt.Errorf("type-checking package %q failed (%v)", bp.ImportPath, err)
155 }
156 if firstHardErr != nil {
157
158 panic("package is not safe yet no error was returned")
159 }
160
161 p.packages[bp.ImportPath] = pkg
162 return pkg, nil
163 }
164
165 func (p *Importer) parseFiles(dir string, filenames []string) ([]*ast.File, error) {
166
167 open := p.ctxt.OpenFile
168 if open == nil {
169 open = func(name string) (io.ReadCloser, error) { return os.Open(name) }
170 }
171
172 files := make([]*ast.File, len(filenames))
173 errors := make([]error, len(filenames))
174
175 var wg sync.WaitGroup
176 wg.Add(len(filenames))
177 for i, filename := range filenames {
178 go func(i int, filepath string) {
179 defer wg.Done()
180 src, err := open(filepath)
181 if err != nil {
182 errors[i] = err
183 return
184 }
185 files[i], errors[i] = parser.ParseFile(p.fset, filepath, src, 0)
186 src.Close()
187 }(i, p.joinPath(dir, filename))
188 }
189 wg.Wait()
190
191
192 for _, err := range errors {
193 if err != nil {
194 return nil, err
195 }
196 }
197
198 return files, nil
199 }
200
201 func (p *Importer) cgo(bp *build.Package) (*ast.File, error) {
202 tmpdir, err := os.MkdirTemp("", "srcimporter")
203 if err != nil {
204 return nil, err
205 }
206 defer os.RemoveAll(tmpdir)
207
208 args := []string{"go", "tool", "cgo", "-objdir", tmpdir}
209 if bp.Goroot {
210 switch bp.ImportPath {
211 case "runtime/cgo":
212 args = append(args, "-import_runtime_cgo=false", "-import_syscall=false")
213 case "runtime/race":
214 args = append(args, "-import_syscall=false")
215 }
216 }
217 args = append(args, "--")
218 args = append(args, strings.Fields(os.Getenv("CGO_CPPFLAGS"))...)
219 args = append(args, bp.CgoCPPFLAGS...)
220 if len(bp.CgoPkgConfig) > 0 {
221 cmd := exec.Command("pkg-config", append([]string{"--cflags"}, bp.CgoPkgConfig...)...)
222 out, err := cmd.CombinedOutput()
223 if err != nil {
224 return nil, err
225 }
226 args = append(args, strings.Fields(string(out))...)
227 }
228 args = append(args, "-I", tmpdir)
229 args = append(args, strings.Fields(os.Getenv("CGO_CFLAGS"))...)
230 args = append(args, bp.CgoCFLAGS...)
231 args = append(args, bp.CgoFiles...)
232
233 cmd := exec.Command(args[0], args[1:]...)
234 cmd.Dir = bp.Dir
235 if err := cmd.Run(); err != nil {
236 return nil, err
237 }
238
239 return parser.ParseFile(p.fset, filepath.Join(tmpdir, "_cgo_gotypes.go"), nil, 0)
240 }
241
242
243
244 func (p *Importer) absPath(path string) (string, error) {
245
246
247 return filepath.Abs(path)
248 }
249
250 func (p *Importer) isAbsPath(path string) bool {
251 if f := p.ctxt.IsAbsPath; f != nil {
252 return f(path)
253 }
254 return filepath.IsAbs(path)
255 }
256
257 func (p *Importer) joinPath(elem ...string) string {
258 if f := p.ctxt.JoinPath; f != nil {
259 return f(elem...)
260 }
261 return filepath.Join(elem...)
262 }
263
264
265 func setUsesCgo(conf *types.Config)
266
View as plain text