1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // gotype.go is a copy of the original source maintained
6 // in $GOROOT/src/go/types/gotype.go, but with the call
7 // to types.SizesFor factored out so we can provide a local
8 // implementation when compiling against Go 1.8 and earlier.
10 // This code is here for the sole purpose of satisfying historic
11 // references to this location, and for making gotype accessible
14 // Do NOT make changes to this version as they will not be maintained
15 // (and possibly overwritten). Any changes should be made to the original
16 // and then ported to here.
19 The gotype command, like the front-end of a Go compiler, parses and
20 type-checks a single Go package. Errors are reported if the analysis
21 fails; otherwise gotype is quiet (unless -v is set).
23 Without a list of paths, gotype reads from standard input, which
24 must provide a single Go source file defining a complete package.
26 With a single directory argument, gotype checks the Go files in
27 that directory, comprising a single package. Use -t to include the
28 (in-package) _test.go files. Use -x to type check only external
31 Otherwise, each path must be the filename of a Go file belonging
34 Imports are processed by importing directly from the source of
35 imported packages (default), or by importing from compiled and
36 installed packages (by setting -c to the respective compiler).
38 The -c flag must be set to a compiler ("gc", "gccgo") when type-
39 checking packages containing imports with relative import paths
40 (import "./mypkg") because the source importer cannot know which
41 files to include for such packages.
44 gotype [flags] [path...]
48 include local test files in a directory (ignored if -x is provided)
50 consider only external test files in a directory
52 report all errors (not just the first 10)
56 compiler used for installed packages (gc, gccgo, or source); default: source
58 Flags controlling additional output:
60 print AST (forces -seq)
62 print parse trace (forces -seq)
64 parse comments (ignored unless -ast or -trace is provided)
68 To check the files a.go, b.go, and c.go:
72 To check an entire package including (in-package) tests in the directory dir and print the processed files:
76 To check the external test package (if any) in the current directory, based on installed packages compiled with
81 To verify the output of a pipe:
83 echo "package foo" | gotype
106 // main operation modes
107 testFiles = flag.Bool("t", false, "include in-package test files in a directory")
108 xtestFiles = flag.Bool("x", false, "consider only external test files in a directory")
109 allErrors = flag.Bool("e", false, "report all errors, not just the first 10")
110 verbose = flag.Bool("v", false, "verbose mode")
111 compiler = flag.String("c", defaultCompiler, "compiler used for installed packages (gc, gccgo, or source)")
113 // additional output control
114 printAST = flag.Bool("ast", false, "print AST (forces -seq)")
115 printTrace = flag.Bool("trace", false, "print parse trace (forces -seq)")
116 parseComments = flag.Bool("comments", false, "parse comments (ignored unless -ast or -trace is provided)")
120 fset = token.NewFileSet()
123 parserMode parser.Mode
126 func initParserMode() {
128 parserMode |= parser.AllErrors
134 parserMode |= parser.Trace
137 if *parseComments && (*printAST || *printTrace) {
138 parserMode |= parser.ParseComments
142 const usageString = `usage: gotype [flags] [path ...]
144 The gotype command, like the front-end of a Go compiler, parses and
145 type-checks a single Go package. Errors are reported if the analysis
146 fails; otherwise gotype is quiet (unless -v is set).
148 Without a list of paths, gotype reads from standard input, which
149 must provide a single Go source file defining a complete package.
151 With a single directory argument, gotype checks the Go files in
152 that directory, comprising a single package. Use -t to include the
153 (in-package) _test.go files. Use -x to type check only external
156 Otherwise, each path must be the filename of a Go file belonging
159 Imports are processed by importing directly from the source of
160 imported packages (default), or by importing from compiled and
161 installed packages (by setting -c to the respective compiler).
163 The -c flag must be set to a compiler ("gc", "gccgo") when type-
164 checking packages containing imports with relative import paths
165 (import "./mypkg") because the source importer cannot know which
166 files to include for such packages.
170 fmt.Fprintln(os.Stderr, usageString)
175 func report(err error) {
176 scanner.PrintError(os.Stderr, err)
177 if list, ok := err.(scanner.ErrorList); ok {
178 errorCount += len(list)
184 // parse may be called concurrently
185 func parse(filename string, src interface{}) (*ast.File, error) {
187 fmt.Println(filename)
189 file, err := parser.ParseFile(fset, filename, src, parserMode) // ok to access fset concurrently
191 ast.Print(fset, file)
196 func parseStdin() (*ast.File, error) {
197 src, err := ioutil.ReadAll(os.Stdin)
201 return parse("<standard input>", src)
204 func parseFiles(dir string, filenames []string) ([]*ast.File, error) {
205 files := make([]*ast.File, len(filenames))
206 errors := make([]error, len(filenames))
208 var wg sync.WaitGroup
209 for i, filename := range filenames {
211 go func(i int, filepath string) {
213 files[i], errors[i] = parse(filepath, nil)
214 }(i, filepath.Join(dir, filename))
221 // if there are errors, return the first one for deterministic results
222 for _, err := range errors {
231 func parseDir(dir string) ([]*ast.File, error) {
232 ctxt := build.Default
233 pkginfo, err := ctxt.ImportDir(dir, 0)
234 if _, nogo := err.(*build.NoGoError); err != nil && !nogo {
239 return parseFiles(dir, pkginfo.XTestGoFiles)
242 filenames := append(pkginfo.GoFiles, pkginfo.CgoFiles...)
244 filenames = append(filenames, pkginfo.TestGoFiles...)
246 return parseFiles(dir, filenames)
249 func getPkgFiles(args []string) ([]*ast.File, error) {
252 file, err := parseStdin()
256 return []*ast.File{file}, nil
260 // possibly a directory
262 info, err := os.Stat(path)
267 return parseDir(path)
272 return parseFiles("", args)
275 func checkPkgFiles(files []*ast.File) {
276 type bailout struct{}
278 // if checkPkgFiles is called multiple times, set up conf only once
279 conf := types.Config{
281 Error: func(err error) {
282 if !*allErrors && errorCount >= 10 {
287 Importer: importer.ForCompiler(fset, *compiler, nil),
288 Sizes: SizesFor(build.Default.Compiler, build.Default.GOARCH),
292 switch p := recover().(type) {
294 // normal return or early exit
301 const path = "pkg" // any non-empty string will do for now
302 conf.Check(path, fset, files, nil)
305 func printStats(d time.Duration) {
308 fset.Iterate(func(f *token.File) bool {
310 lineCount += f.LineCount()
315 "%s (%d files, %d lines, %d lines/s)\n",
316 d, fileCount, lineCount, int64(float64(lineCount)/d.Seconds()),
327 files, err := getPkgFiles(flag.Args())
339 printStats(time.Since(start))