1
2
3
4
5
6 package importer
7
8 import (
9 "go/build"
10 "go/internal/gccgoimporter"
11 "go/internal/gcimporter"
12 "go/internal/srcimporter"
13 "go/token"
14 "go/types"
15 "io"
16 "runtime"
17 )
18
19
20
21 type Lookup func(path string) (io.ReadCloser, error)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 func ForCompiler(fset *token.FileSet, compiler string, lookup Lookup) types.Importer {
41 switch compiler {
42 case "gc":
43 return &gcimports{
44 fset: fset,
45 packages: make(map[string]*types.Package),
46 lookup: lookup,
47 }
48
49 case "gccgo":
50 var inst gccgoimporter.GccgoInstallation
51 if err := inst.InitFromDriver("gccgo"); err != nil {
52 return nil
53 }
54 return &gccgoimports{
55 packages: make(map[string]*types.Package),
56 importer: inst.GetImporter(nil, nil),
57 lookup: lookup,
58 }
59
60 case "source":
61 if lookup != nil {
62 panic("source importer for custom import path lookup not supported (issue #13847).")
63 }
64
65 return srcimporter.New(&build.Default, fset, make(map[string]*types.Package))
66 }
67
68
69 return nil
70 }
71
72
73
74
75
76 func For(compiler string, lookup Lookup) types.Importer {
77 return ForCompiler(token.NewFileSet(), compiler, lookup)
78 }
79
80
81
82 func Default() types.Importer {
83 return For(runtime.Compiler, nil)
84 }
85
86
87
88 type gcimports struct {
89 fset *token.FileSet
90 packages map[string]*types.Package
91 lookup Lookup
92 }
93
94 func (m *gcimports) Import(path string) (*types.Package, error) {
95 return m.ImportFrom(path, "" , 0)
96 }
97
98 func (m *gcimports) ImportFrom(path, srcDir string, mode types.ImportMode) (*types.Package, error) {
99 if mode != 0 {
100 panic("mode must be 0")
101 }
102 return gcimporter.Import(m.fset, m.packages, path, srcDir, m.lookup)
103 }
104
105
106
107 type gccgoimports struct {
108 packages map[string]*types.Package
109 importer gccgoimporter.Importer
110 lookup Lookup
111 }
112
113 func (m *gccgoimports) Import(path string) (*types.Package, error) {
114 return m.ImportFrom(path, "" , 0)
115 }
116
117 func (m *gccgoimports) ImportFrom(path, srcDir string, mode types.ImportMode) (*types.Package, error) {
118 if mode != 0 {
119 panic("mode must be 0")
120 }
121 return m.importer(m.packages, path, srcDir, m.lookup)
122 }
123
View as plain text