-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoperators.go
283 lines (210 loc) · 5.29 KB
/
operators.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package main
import (
"fmt"
"github.com/jessevdk/go-flags"
"github.com/jessevdk/go-operators/types"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/token"
"os"
"path"
"strings"
)
type TypeCheck struct {
Path string
ImportPath string
Package *types.Package
FileSet *token.FileSet
ParseFiles []string
ProcessFiles []string
FilesToAst map[string]*ast.File
Ast []*ast.File
}
var typechecks = make(map[string]*TypeCheck)
func packageLocations(args []string) []string {
if len(args) == 0 {
dirname, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to obtain current working directory\n")
os.Exit(1)
}
return []string{dirname}
}
return args
}
func buildFiles(packageDir string) (parse []string, process []string, pkgname string) {
ctx := build.Default
ctx.BuildTags = []string{"operators"}
p, err := ctx.ImportDir(packageDir, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "Error while importing build: %s\n", err)
os.Exit(1)
}
for _, f := range p.GoFiles {
parse = append(parse, path.Join(packageDir, f))
if strings.HasSuffix(f, ".op.go") {
process = append(process, f)
}
}
return parse, process, p.Name
}
func parseAST(files []string) (fs *token.FileSet, afs []*ast.File, afsmap map[string]*ast.File) {
fs = token.NewFileSet()
afs = make([]*ast.File, 0, len(files))
afsmap = make(map[string]*ast.File)
for _, f := range files {
af, err := parser.ParseFile(fs, f, nil, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "Error while parsing AST: %s\n", err)
os.Exit(1)
}
afsmap[f] = af
afs = append(afs, af)
}
return fs, afs, afsmap
}
func checkTypes(pkgpath string, importpath string) *TypeCheck {
if ret, ok := typechecks[importpath]; ok {
return ret
}
parse, process, pkgname := buildFiles(pkgpath)
fs, afs, afsmap := parseAST(parse)
var conf types.Config
conf.Import = importSources
pp, err := conf.Check(pkgname, fs, afs, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Error while type checking: %s\n", err)
os.Exit(1)
}
ret := &TypeCheck{
Path: pkgpath,
Package: pp,
ImportPath: importpath,
ParseFiles: parse,
ProcessFiles: process,
FileSet: fs,
Ast: afs,
FilesToAst: afsmap,
}
typechecks[importpath] = ret
return ret
}
func resolvePackage(importpath string, tryLocal bool) *TypeCheck {
if ret, ok := typechecks[importpath]; ok {
return ret
}
// Try local first
if tryLocal {
if _, err := os.Stat(importpath); err == nil {
return checkTypes(importpath, importpath)
}
}
paths := strings.Split(os.Getenv("GOPATH"), ":")
for _, p := range paths {
src := path.Join(p, "src", importpath)
if _, err := os.Stat(src); err != nil {
continue
}
return checkTypes(src, importpath)
}
fmt.Fprintf(os.Stderr, "Could not find package %s.\n", importpath)
os.Exit(1)
return nil
}
func importSource(imports map[string]*types.Package, path string) (pkg *types.Package, err error) {
if pkg, ok := imports[path]; ok {
return pkg, nil
}
// Try from source
ct := resolvePackage(path, false)
if ct == nil {
return nil, fmt.Errorf("Could not locate import path %s", path)
}
imports[ct.ImportPath] = ct.Package
return ct.Package, nil
}
func importSources(imports map[string]*types.Package, path string) (pkg *types.Package, err error) {
if operatorPackages[path] {
return importSource(imports, path)
}
pkg, err = types.GcImport(imports, path)
if err != nil {
if path == "C" {
return nil, fmt.Errorf("go-operators does not have support for packages that use cgo at the moment")
}
return importSource(imports, path)
}
return pkg, err
}
func replacer(overloads map[ast.Expr]types.OverloadInfo, node ast.Node) ast.Node {
expr, ok := node.(ast.Expr)
if !ok {
return node
}
info, ok := overloads[expr]
if !ok {
return node
}
sel := &ast.SelectorExpr{
X: info.Recv,
Sel: ast.NewIdent(info.Func.Name()),
}
args := []ast.Expr{}
if info.Oper != nil {
args = append(args, info.Oper)
}
// Create function call expression
call := &ast.CallExpr{
Fun: sel,
Args: args,
}
return call
}
func replaceOperators(ct *TypeCheck) {
overloads := ct.Package.Overloads()
for _, f := range ct.ProcessFiles {
af := ct.FilesToAst[path.Join(ct.Path, f)]
af = replace(func(node ast.Node) ast.Node {
return replacer(overloads, node)
}, af).(*ast.File)
suffix := ".op.go"
outname := f[:len(f)-len(suffix)] + ".go"
fn := path.Join(ct.Path, outname)
of, err := os.Create(fn)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create output file: %s\n", err)
os.Exit(1)
}
defer of.Close()
if opts.Verbose {
fmt.Println(fn)
}
// Write build constraint
fmt.Fprintln(of, "// +build !operators\n")
if err := format.Node(of, ct.FileSet, af); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write code: %s\n", err)
os.Exit(1)
}
}
}
var opts struct {
Verbose bool `short:"v" long:"verbose" description:"Enable verbose mode"`
}
var operatorPackages = make(map[string]bool)
func main() {
fp := flags.NewParser(&opts, flags.Default)
args, err := fp.Parse()
if err != nil {
os.Exit(1)
}
packageDirs := packageLocations(args)
for _, p := range packageDirs {
operatorPackages[p] = true
}
for _, p := range packageDirs {
ct := resolvePackage(p, true)
replaceOperators(ct)
}
}