本文整理汇总了Golang中go/types.Config.Check方法的典型用法代码示例。如果您正苦于以下问题:Golang Config.Check方法的具体用法?Golang Config.Check怎么用?Golang Config.Check使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类go/types.Config
的用法示例。
在下文中一共展示了Config.Check方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: check
func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) error {
pkg.defs = make(map[*ast.Ident]types.Object)
pkg.uses = make(map[*ast.Ident]types.Object)
pkg.selectors = make(map[*ast.SelectorExpr]*types.Selection)
pkg.spans = make(map[types.Object]Span)
pkg.types = make(map[ast.Expr]types.TypeAndValue)
config := types.Config{
// We use the same importer for all imports to ensure that
// everybody sees identical packages for the given paths.
Importer: stdImporter,
// By providing a Config with our own error function, it will continue
// past the first error. There is no need for that function to do anything.
Error: func(error) {},
}
info := &types.Info{
Selections: pkg.selectors,
Types: pkg.types,
Defs: pkg.defs,
Uses: pkg.uses,
}
typesPkg, err := config.Check(pkg.path, fs, astFiles, info)
pkg.typesPkg = typesPkg
// update spans
for id, obj := range pkg.defs {
pkg.growSpan(id, obj)
}
for id, obj := range pkg.uses {
pkg.growSpan(id, obj)
}
return err
}
示例2: TestIssue16902
func TestIssue16902(t *testing.T) {
const src = `
package a
import "unsafe"
const _ = unsafe.Offsetof(struct{ x int64 }{}.x)
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "x.go", src, 0)
if err != nil {
t.Fatal(err)
}
info := types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
conf := types.Config{
Importer: importer.Default(),
Sizes: &types.StdSizes{WordSize: 8, MaxAlign: 8},
}
_, err = conf.Check("x", fset, []*ast.File{f}, &info)
if err != nil {
t.Fatal(err)
}
for _, tv := range info.Types {
_ = conf.Sizes.Sizeof(tv.Type)
_ = conf.Sizes.Alignof(tv.Type)
}
}
示例3: parseFiles
func parseFiles(path string) (*token.FileSet, *types.Package, types.Info, *ast.File) {
fset := token.NewFileSet()
files := []*ast.File{}
for _, name := range []string{"server.go", "client.go"} {
f, err := parser.ParseFile(fset, filepath.Join(path, name), nil, 0)
if err != nil {
log.Fatal(err)
}
files = append(files, f)
}
info := types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
var conf types.Config
conf.Importer = importer.Default()
pkg, err := conf.Check(path, fset, files, &info)
if err != nil {
log.Fatal(err)
}
return fset, pkg, info, files[1]
}
示例4: TestVeryLongFile
// TestVeryLongFile tests the position of an import object declared in
// a very long input file. Line numbers greater than maxlines are
// reported as line 1, not garbage or token.NoPos.
func TestVeryLongFile(t *testing.T) {
// parse and typecheck
longFile := "package foo" + strings.Repeat("\n", 123456) + "var X int"
fset1 := token.NewFileSet()
f, err := parser.ParseFile(fset1, "foo.go", longFile, 0)
if err != nil {
t.Fatal(err)
}
var conf types.Config
pkg, err := conf.Check("foo", fset1, []*ast.File{f}, nil)
if err != nil {
t.Fatal(err)
}
// export
exportdata := gcimporter.BExportData(fset1, pkg)
// import
imports := make(map[string]*types.Package)
fset2 := token.NewFileSet()
_, pkg2, err := gcimporter.BImportData(fset2, imports, exportdata, pkg.Path())
if err != nil {
t.Fatalf("BImportData(%s): %v", pkg.Path(), err)
}
// compare
posn1 := fset1.Position(pkg.Scope().Lookup("X").Pos())
posn2 := fset2.Position(pkg2.Scope().Lookup("X").Pos())
if want := "foo.go:1:1"; posn2.String() != want {
t.Errorf("X position = %s, want %s (orig was %s)",
posn2, want, posn1)
}
}
示例5: main
func main() {
f, err := parser.ParseFile(fset, "hello.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil {
log.Fatal(err) // type error
}
//!+inspect
// f is a parsed, type-checked *ast.File.
ast.Inspect(f, func(n ast.Node) bool {
if expr, ok := n.(ast.Expr); ok {
if tv, ok := info.Types[expr]; ok {
fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv))
fmt.Printf("\t\t\t\ttype: %v\n", tv.Type)
if tv.Value != nil {
fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value)
}
}
}
return true
})
//!-inspect
}
示例6: main
func main() {
name := "testdata/import.go"
var files []*ast.File
fs := token.NewFileSet()
file, err := parser.ParseFile(fs, name, nil, 0)
if err != nil {
log.Fatal(err)
}
files = append(files, file)
config := types.Config{
Importer: importer.Default(),
Error: func(error) {},
}
info := &types.Info{
Selections: make(map[*ast.SelectorExpr]*types.Selection),
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
pkg, err := config.Check("testdata", fs, files, info)
if err != nil {
log.Fatal(err)
}
fmt.Println(pkg)
}
示例7: GetCurrentAppSettings
func GetCurrentAppSettings(settings_path string)(settings map[string]string,err error){
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, default_settings_path, nil, 0)
if err != nil {
f, err = parser.ParseFile(fset, default_relative_settings_path, nil, 0)
if err!=nil{
return nil,err
}
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("wapour/settings", fset, []*ast.File{f}, nil)
if err != nil {
return nil,err
}
settings=make(map[string]string,0)
for word_id := range initial {
word:=initial[word_id]
existing_set:=pkg.Scope().Lookup(word).(*types.Const).Val().String()
settings[word]=existing_set
}
return settings,err
}
示例8: checkPkgFiles
func checkPkgFiles(files []*ast.File) {
compiler := "gc"
if *gccgo {
compiler = "gccgo"
}
type bailout struct{}
conf := types.Config{
FakeImportC: true,
Error: func(err error) {
if !*allErrors && errorCount >= 10 {
panic(bailout{})
}
report(err)
},
Importer: importer.For(compiler, nil),
Sizes: sizes,
}
defer func() {
switch p := recover().(type) {
case nil, bailout:
// normal return or early exit
default:
// re-panic
panic(p)
}
}()
const path = "pkg" // any non-empty string will do for now
conf.Check(path, fset, files, nil)
}
示例9: typeCheck
func typeCheck(t *testing.T, filename string, gopath string) *types.Package {
f, err := parser.ParseFile(fset, filename, nil, parser.AllErrors)
if err != nil {
t.Fatalf("%s: %v", filename, err)
}
pkgName := filepath.Base(filename)
pkgName = strings.TrimSuffix(pkgName, ".go")
// typecheck and collect typechecker errors
var conf types.Config
conf.Error = func(err error) {
t.Error(err)
}
if gopath != "" {
conf.Importer = importer.Default()
oldDefault := build.Default
defer func() { build.Default = oldDefault }()
build.Default.GOPATH = gopath
}
pkg, err := conf.Check(pkgName, fset, []*ast.File{f}, nil)
if err != nil {
t.Fatal(err)
}
return pkg
}
示例10: main
func main() {
fset := token.NewFileSet()
// Parse the input string, []byte, or io.Reader,
// recording position information in fset.
// ParseFile returns an *ast.File, a syntax tree.
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
// A Config controls various options of the type checker.
// The defaults work fine except for one setting:
// we must specify how to deal with imports.
conf := types.Config{Importer: importer.Default()}
// Type-check the package containing only file f.
// Check returns a *types.Package.
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
fmt.Printf("Package %q\n", pkg.Path())
fmt.Printf("Name: %s\n", pkg.Name())
fmt.Printf("Imports: %s\n", pkg.Imports())
fmt.Printf("Scope: %s\n", pkg.Scope())
}
示例11: getPackage
func getPackage(fset *token.FileSet, a *ast.Package, conf *Config) (*Package, *TypeCheckError) {
// pull map into a slice
var files []*ast.File
for _, f := range a.Files {
files = append(files, f)
}
config := types.Config{
DisableUnusedImportCheck: true,
IgnoreFuncBodies: true,
}
if conf.IgnoreTypeCheckErrors {
// no-op allows type checking to proceed in presence of errors
// https://godoc.org/golang.org/x/tools/go/types#Config
config.Error = func(err error) {}
}
typesPkg, err := config.Check(a.Name, fset, files, nil)
p := &Package{typesPkg, fset, []Type{}}
if err != nil {
return p, &TypeCheckError{err, conf.IgnoreTypeCheckErrors}
}
return p, nil
}
示例12: Collect
//Collect going through package and collect info
//using conf.Check method. It's using this implementation
//of importer for check all inner packages and go/types/importer.Default()
//to check all built in packages (without sources)
func (_importer *CollectInfoImporter) Collect() (*types.Package, *token.FileSet, error) {
var conf types.Config
conf.Importer = _importer
conf.Error = _importer.errorHandler
if _importer.packages == nil {
_importer.packages = make(map[string]*types.Package)
}
var pkg *types.Package
var err error
var files []string
if files, err = fs.SourceFiles(_importer.Pkg, false); err != nil {
return nil, nil, err
}
if _importer.fset, _importer.astFiles, err = doParseFiles(files, _importer.fset); err != nil {
return nil, nil, err
}
//XXX: return positive result if check() returns error.
pkg, _ = conf.Check(_importer.Pkg, _importer.fset, _importer.astFiles, _importer.Info)
// if pkg, err = conf.Check(_importer.Pkg, _importer.fset, _importer.astFiles, _importer.Info); err != nil {
// return pkg, _importer.fset, err
// }
_importer.packages[_importer.Pkg] = pkg
util.Debug("package [%s] successfully parsed\n", pkg.Name())
return pkg, _importer.fset, nil
}
示例13: main
//!+main
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
// Each comment contains a name.
// Look up that name in the innermost scope enclosing the comment.
for _, comment := range f.Comments {
pos := comment.Pos()
name := strings.TrimSpace(comment.Text())
fmt.Printf("At %s,\t%q = ", fset.Position(pos), name)
inner := pkg.Scope().Innermost(pos)
if _, obj := inner.LookupParent(name, pos); obj != nil {
fmt.Println(obj)
} else {
fmt.Println("not found")
}
}
}
示例14: process
func (gas *Analyzer) process(filename string, source interface{}) error {
mode := parser.ParseComments
root, err := parser.ParseFile(gas.context.FileSet, filename, source, mode)
if err == nil {
gas.context.Comments = ast.NewCommentMap(gas.context.FileSet, root, root.Comments)
gas.context.Root = root
// here we get type info
gas.context.Info = &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Selections: make(map[*ast.SelectorExpr]*types.Selection),
Scopes: make(map[ast.Node]*types.Scope),
Implicits: make(map[ast.Node]types.Object),
}
conf := types.Config{Importer: importer.Default()}
gas.context.Pkg, _ = conf.Check("pkg", gas.context.FileSet, []*ast.File{root}, gas.context.Info)
if err != nil {
gas.logger.Println("failed to check imports")
return err
}
ast.Walk(gas, root)
gas.Stats.NumFiles++
}
return err
}
示例15: typeCheckPackage
// typeCheckPackage will attempt to return the package even if there are some
// errors, so you may check whether the package is nil or not even if you get
// an error.
func (b *Builder) typeCheckPackage(id string) (*tc.Package, error) {
if pkg, ok := b.pkgs[id]; ok {
if pkg != nil {
return pkg, nil
}
// We store a nil right before starting work on a package. So
// if we get here and it's present and nil, that means there's
// another invocation of this function on the call stack
// already processing this package.
return nil, fmt.Errorf("circular dependency for %q", id)
}
parsedFiles, ok := b.parsed[id]
if !ok {
return nil, fmt.Errorf("No files for pkg %q: %#v", id, b.parsed)
}
files := make([]*ast.File, len(parsedFiles))
for i := range parsedFiles {
files[i] = parsedFiles[i].file
}
b.pkgs[id] = nil
c := tc.Config{
IgnoreFuncBodies: true,
// Note that importAdater can call b.import which calls this
// method. So there can't be cycles in the import graph.
Importer: importAdapter{b},
Error: func(err error) {
glog.V(2).Infof("type checker error: %v\n", err)
},
}
pkg, err := c.Check(id, b.fset, files, nil)
b.pkgs[id] = pkg // record the result whether or not there was an error
return pkg, err
}