On Monday, 12 December 2016 12:22:51 UTC-5, Jan Mercl wrote:
>
> On Mon, Dec 12, 2016 at 6:20 PM <[email protected] <javascript:>> wrote:
>
> > I realize that obviously the Go compiler does it, I was wondering if
> there is a good API for that I can use, like the ast package?
>
> See https://golang.org/pkg/go/types/
>
You can use go/types directly if you just want to type-check a single file,
but all but the most trivial Go programs import other packages. You have
three choices for how to handle import declarations:
(1) ignore them
(2) load type information for exported packages from .a files produced by
the compiler
(3) load the entire program from source.
The vet command takes approach #1, which of course means that it has
incomplete information. To use approach #2, you need to use the
go/importer package, and furthermore rely on all the relevant .a files
being up to date (which they rarely are). For approach #3, you need to use
the golang.org/x/tools/go/loader package, which loads, parses, and
type-checks all the source code for a multi-package program laid out
according to 'go build' conventions. Look at any of several tools in that
repository for an example of how to put the pieces together. For example,
with no flags, ssadump simply type-checks the specified packages:
$ go get golang.org/x/tools/cmd/ssadump
$ cat a.go
package main
var x int = "string"
$ ssadump a.go
a.go:2:13: cannot convert "string" (untyped string constant) to int
There's an in-depth tutorial for the go/types package here:
https://github.com/golang/example/tree/master/gotypes
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.