当前位置: 首页>>代码示例>>Golang>>正文


Golang types.Config类代码示例

本文整理汇总了Golang中golang.org/x/tools/go/types.Config的典型用法代码示例。如果您正苦于以下问题:Golang Config类的具体用法?Golang Config怎么用?Golang Config使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Config类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ParseAST

// Parse parses the ast for this file and returns a ParsedFile
func (w *Weave) ParseAST(fname string) *ast.File {
	var err error

	fset := token.NewFileSet()
	af, err := parser.ParseFile(fset, fname, nil, 0)
	if err != nil {
		w.flog.Println(err)
	}

	loadcfg := loader.Config{}
	loadcfg.CreateFromFilenames(fname)

	info := types.Info{
		Types: make(map[ast.Expr]types.TypeAndValue),
		Defs:  make(map[*ast.Ident]types.Object),
	}

	var conf types.Config
	_, err = conf.Check(af.Name.Name, fset, []*ast.File{af}, &info)
	if err != nil {
		if w.warnAST {
			w.flog.Println(err)
		}
	}

	return af
}
开发者ID:skyportsystems,项目名称:goweave,代码行数:28,代码来源:weave.go

示例2: ObjectOf

func ObjectOf(filename string, cursor int) (types.Object, *types.Selection, error) {
	text, off, err := readSourceOffset(filename, cursor, nil)
	if err != nil {
		return nil, nil, err
	}
	if err := checkSelection(text, off); err != nil {
		return nil, nil, err
	}
	af, fset, err := parseFile(filename, text)
	if err != nil {
		return nil, nil, err
	}
	node, err := nodeAtOffset(af, fset, cursor)
	if err != nil {
		return nil, nil, err
	}
	ctx := newContext(filename, af, fset, &build.Default)
	info := &types.Info{
		Defs: make(map[*ast.Ident]types.Object),
		Uses: make(map[*ast.Ident]types.Object),
	}
	if _, ok := node.(*ast.SelectorExpr); ok {
		info.Selections = make(map[*ast.SelectorExpr]*types.Selection)
	}
	conf := types.Config{}
	if _, err := conf.Check(ctx.dirname, ctx.fset, ctx.files, info); err != nil {
		// Return error only if missing type info.
		if len(info.Defs) == 0 && len(info.Uses) == 0 {
			return nil, nil, err
		}
	}
	return lookupType(node, info)
}
开发者ID:charlievieth,项目名称:define,代码行数:33,代码来源:api.go

示例3: 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.spans = make(map[types.Object]Span)
	pkg.types = make(map[ast.Expr]types.TypeAndValue)
	config := types.Config{
		// We provide the same packages map for all imports to ensure
		// that everybody sees identical packages for the given paths.
		Packages: imports,
		// 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{
		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
}
开发者ID:Lane391,项目名称:golangdemo,代码行数:29,代码来源:types.go

示例4: checkPkgFiles

func checkPkgFiles(files []*ast.File) {
	type bailout struct{}
	conf := types.Config{
		FakeImportC: true,
		Error: func(err error) {
			if !*allErrors && errorCount >= 10 {
				panic(bailout{})
			}
			report(err)
		},
		Sizes: sizes,
	}
	if *gccgo {
		var inst gccgoimporter.GccgoInstallation
		inst.InitFromDriver("gccgo")
		conf.Import = inst.GetImporter(nil, nil)
	}

	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)
}
开发者ID:CyCoreSystems,项目名称:coreos-kubernetes,代码行数:31,代码来源:gotype14.go

示例5: Object

func (c *Config) Object(filename string, cursor int, src interface{}) (*Object, []byte, error) {
	// TODO: Refactor this mess!
	text, err := readSource(filename, src)
	if err != nil {
		return nil, nil, err
	}
	if err := checkSelection(text, cursor); err != nil {
		return nil, nil, err
	}
	af, fset, err := parseFile(filename, text)
	if err != nil {
		return nil, nil, err
	}
	node, err := nodeAtOffset(af, fset, cursor)
	if err != nil {
		return nil, nil, err
	}
	ctx := newContext(filename, af, fset, &c.Context)
	info := &types.Info{
		Defs: make(map[*ast.Ident]types.Object),
		Uses: make(map[*ast.Ident]types.Object),
	}
	if _, ok := node.(*ast.SelectorExpr); ok {
		info.Selections = make(map[*ast.SelectorExpr]*types.Selection)
	}
	conf := types.Config{}
	if _, err := conf.Check(ctx.dirname, ctx.fset, ctx.files, info); err != nil {
		// Return error only if missing type info.
		if len(info.Defs) == 0 && len(info.Uses) == 0 {
			return nil, nil, err
		}
	}
	obj, sel, err := lookupType(node, info)
	if err != nil {
		return nil, nil, err
	}
	o, err := newObject(obj, sel)
	if err != nil {
		return nil, nil, err
	}
	f, err := o.Finder()
	if err != nil {
		return nil, nil, err
	}
	tp, objSrc, err := ctx.objectPosition(o.PkgPath, f)
	if err != nil {
		if o.pos.IsValid() {
			if p := positionFor(o.pos, fset); p != nil {
				o.Position = Position(*p)
				return o, objSrc, nil
			}
		}
		return nil, nil, err
	}
	if tp != nil {
		o.Position = Position(*tp)
	}
	return o, objSrc, nil
}
开发者ID:charlievieth,项目名称:define,代码行数:59,代码来源:api.go

示例6: main

func main() {
	flag.Parse()
	exitStatus := 0
	importPaths := gotool.ImportPaths(flag.Args())
	if len(importPaths) == 0 {
		importPaths = []string{"."}
	}
	for _, pkgPath := range importPaths {
		visitor := &visitor{
			info: types.Info{
				Types:      make(map[ast.Expr]types.TypeAndValue),
				Defs:       make(map[*ast.Ident]types.Object),
				Selections: make(map[*ast.SelectorExpr]*types.Selection),
			},

			m:    make(map[types.Type]map[string]int),
			skip: make(map[types.Type]struct{}),
		}
		fset, astFiles := check.ASTFilesForPackage(pkgPath, *loadTestFiles)
		imp := importer.New()
		// Preliminary cgo support.
		imp.Config = importer.Config{UseGcFallback: true}
		config := types.Config{Import: imp.Import}
		var err error
		visitor.pkg, err = config.Check(pkgPath, fset, astFiles, &visitor.info)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s: %v\n", pkgPath, err)
			continue
		}
		for _, f := range astFiles {
			ast.Walk(visitor, f)
		}
		for t := range visitor.m {
			if _, skip := visitor.skip[t]; skip {
				continue
			}
			for fieldName, v := range visitor.m[t] {
				if !*reportExported && ast.IsExported(fieldName) {
					continue
				}
				if v == 0 {
					field, _, _ := types.LookupFieldOrMethod(t, false, visitor.pkg, fieldName)
					if fieldName == "XMLName" {
						if named, ok := field.Type().(*types.Named); ok && named.Obj().Pkg().Path() == "encoding/xml" {
							continue
						}
					}
					pos := fset.Position(field.Pos())
					fmt.Printf("%s: %s:%d:%d: %s.%s\n",
						pkgPath, pos.Filename, pos.Line, pos.Column,
						types.TypeString(t, nil), fieldName,
					)
					exitStatus = 1
				}
			}
		}
	}
	os.Exit(exitStatus)
}
开发者ID:aganno2,项目名称:check,代码行数:59,代码来源:structcheck.go

示例7: grind

func (ctxt *Context) grind(pkg *Package) {
Loop:
	for loop := 0; ; loop++ {
		println(loop)
		pkg.FileSet = token.NewFileSet()

		pkg.Files = nil
		for _, name := range pkg.Filenames {
			f, err := parser.ParseFile(pkg.FileSet, name, pkg.Src(name), 0)
			if err != nil {
				if loop > 0 {
					ctxt.Errorf("%s: error parsing rewritten file: %v", pkg.ImportPath, err)
					return
				}
				ctxt.Errorf("%s: %v", pkg.ImportPath, err)
				return
			}
			pkg.Files = append(pkg.Files, f)
		}

		conf := new(types.Config)
		// conf.DisableUnusedImportCheck = true
		pkg.Info = types.Info{}
		pkg.Info.Types = make(map[ast.Expr]types.TypeAndValue)
		pkg.Info.Scopes = make(map[ast.Node]*types.Scope)
		pkg.Info.Defs = make(map[*ast.Ident]types.Object)
		pkg.Info.Uses = make(map[*ast.Ident]types.Object)
		typesPkg, err := conf.Check(pkg.ImportPath, pkg.FileSet, pkg.Files, &pkg.Info)
		if err != nil && typesPkg == nil {
			if loop > 0 {
				ctxt.Errorf("%s: error type checking rewritten package: %v", pkg.ImportPath, err)
				for _, name := range pkg.Filenames {
					if pkg.Modified(name) {
						ctxt.Errorf("%s <<<\n%s\n>>>", name, pkg.Src(name))
					}
				}
				return
			}
			ctxt.Errorf("%s: %v", pkg.ImportPath, err)
			return
		}
		pkg.Types = typesPkg
		pkg.TypesError = err

		for _, g := range ctxt.Grinders {
			pkg.clean = true
			g(ctxt, pkg)
			if !pkg.clean {
				continue Loop
			}
		}
		break
	}
}
开发者ID:niltonkummer,项目名称:grind,代码行数:54,代码来源:grind.go

示例8: check

// check type-checks the package. The package must be OK to proceed.
func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) {
	pkg.defs = make(map[*ast.Ident]types.Object)
	config := types.Config{FakeImportC: true}
	info := &types.Info{
		Defs: pkg.defs,
	}
	typesPkg, err := config.Check(pkg.dir, fs, astFiles, info)
	if err != nil {
		log.Fatalf("checking package: %s", err)
	}
	pkg.typesPkg = typesPkg
}
开发者ID:TriangleGo,项目名称:golang.org,代码行数:13,代码来源:stringer.go

示例9: ExampleMap

func ExampleMap() {
	const source = `package P

var X []string
var Y []string

const p, q = 1.0, 2.0

func f(offset int32) (value byte, ok bool)
func g(rune) (uint8, bool)
`

	// Parse and type-check the package.
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "P.go", source, 0)
	if err != nil {
		panic(err)
	}
	pkg, err := new(types.Config).Check("P", fset, []*ast.File{f}, nil)
	if err != nil {
		panic(err)
	}

	scope := pkg.Scope()

	// Group names of package-level objects by their type.
	var namesByType typeutil.Map // value is []string
	for _, name := range scope.Names() {
		T := scope.Lookup(name).Type()

		names, _ := namesByType.At(T).([]string)
		names = append(names, name)
		namesByType.Set(T, names)
	}

	// Format, sort, and print the map entries.
	var lines []string
	namesByType.Iterate(func(T types.Type, names interface{}) {
		lines = append(lines, fmt.Sprintf("%s   %s", names, T))
	})
	sort.Strings(lines)
	for _, line := range lines {
		fmt.Println(line)
	}

	// Output:
	// [X Y]   []string
	// [f g]   func(offset int32) (value byte, ok bool)
	// [p q]   untyped float
}
开发者ID:jappre,项目名称:mutation,代码行数:50,代码来源:example_test.go

示例10: parseSourceFiles

func (p *Processor) parseSourceFiles(filenames []string) (*types.Package, error) {
	var files []*ast.File
	fs := token.NewFileSet()
	for _, filename := range filenames {
		file, err := parser.ParseFile(fs, filename, nil, 0)
		if err != nil {
			return nil, fmt.Errorf("parsing package: %s: %s", filename, err)
		}

		files = append(files, file)
	}

	config := types.Config{FakeImportC: true, Error: func(error) {}}
	info := &types.Info{}

	return config.Check(p.Path, fs, files, info)
}
开发者ID:vsouza,项目名称:storable,代码行数:17,代码来源:processor.go

示例11: typeCheck

func typeCheck(t *testing.T, filename 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)
	}
	pkg, err := conf.Check(pkgName, fset, []*ast.File{f}, nil)
	if err != nil {
		t.Fatal(err)
	}
	return pkg
}
开发者ID:handong890,项目名称:mobile,代码行数:20,代码来源:bind_test.go

示例12: ParsePackage

// ParsePackage parses the package in the given directory and returns it.
func ParsePackage(directory, skipPrefix, skipSuffix string) (*Package, error) {
	pkgDir, err := build.Default.ImportDir(directory, 0)
	if err != nil {
		return nil, fmt.Errorf("cannot process directory %s: %s", directory, err)
	}

	var files []*ast.File
	fs := token.NewFileSet()
	for _, name := range pkgDir.GoFiles {
		if !strings.HasSuffix(name, ".go") ||
			(skipSuffix != "" && strings.HasPrefix(name, skipPrefix) &&
				strings.HasSuffix(name, skipSuffix)) {
			continue
		}
		if directory != "." {
			name = filepath.Join(directory, name)
		}
		f, err := parser.ParseFile(fs, name, nil, 0)
		if err != nil {
			return nil, fmt.Errorf("parsing file %v: %v", name, err)
		}
		files = append(files, f)
	}
	if len(files) == 0 {
		return nil, fmt.Errorf("%s: no buildable Go files", directory)
	}

	// type-check the package
	defs := make(map[*ast.Ident]types.Object)
	config := types.Config{FakeImportC: true}
	info := &types.Info{Defs: defs}
	if _, err := config.Check(directory, fs, files, info); err != nil {
		return nil, fmt.Errorf("type-checking package: %v", err)
	}

	return &Package{
		Name:  files[0].Name.Name,
		files: files,
		defs:  defs,
	}, nil
}
开发者ID:wiless,项目名称:jsonenums,代码行数:42,代码来源:parser.go

示例13: parsePackage

func (p *Parser) parsePackage(directory string, fileNames []string) (*PackageInfo, error) {
	var files FileInfos
	pkg := &PackageInfo{}
	fs := token.NewFileSet()
	for _, fileName := range fileNames {
		if !strings.HasSuffix(fileName, ".go") {
			continue
		}
		parsedFile, err := parser.ParseFile(fs, fileName, nil, parser.ParseComments)
		if err != nil {
			return nil, fmt.Errorf("parsing package: %s: %s", fileName, err)
		}
		files = append(files, (*FileInfo)(parsedFile))
	}
	if len(files) == 0 {
		return nil, fmt.Errorf("%s: no buildable Go files", directory)
	}
	pkg.Files = files
	pkg.Dir = directory

	// resolve types
	config := types.Config{
		FakeImportC:              true,
		IgnoreFuncBodies:         true,
		DisableUnusedImportCheck: true,
	}
	info := &types.Info{
		Defs: make(map[*ast.Ident]types.Object),
	}
	typesPkg, err := config.Check(pkg.Dir, fs, files.AstFiles(), info)
	if p.SkipSemanticsCheck && err != nil {
		return pkg, nil
	} else if err != nil {
		return nil, err
	}
	pkg.Types = typesPkg

	return pkg, nil
}
开发者ID:mackee,项目名称:genbase,代码行数:39,代码来源:parsing.go

示例14: importPkg

func importPkg(pkgname string) (*types.Package, *ast.Package, error) {
	pkg, err := build.Import(pkgname, "", 0)
	if err != nil {
		return nil, nil, err
	}

	fset := token.NewFileSet()
	pkgmap, err := parser.ParseDir(fset, pkg.Dir, nil, parser.ParseComments)
	if err != nil {
		return nil, nil, err
	}

	var filelist []*ast.File
	for _, f := range pkgmap[pkg.Name].Files {
		filelist = append(filelist, f)
	}

	config := types.Config{}
	typpkg, err := config.Check(pkg.Dir, fset, filelist, nil)

	return typpkg, pkgmap[pkg.Name], err
}
开发者ID:johan--,项目名称:kube-annotator,代码行数:22,代码来源:main.go

示例15: TestDependencies

func TestDependencies(t *testing.T) {
	packages := make(map[string]*types.Package)
	conf := types.Config{
		Packages: packages,
		Import: func(_ map[string]*types.Package, path string) (*types.Package, error) {
			return packages[path], nil
		},
	}
	fset := token.NewFileSet()

	// All edges go to the right.
	//  /--D--B--A
	// F    \_C_/
	//  \__E_/
	for i, content := range []string{
		`package a`,
		`package c; import (_ "a")`,
		`package b; import (_ "a")`,
		`package e; import (_ "c")`,
		`package d; import (_ "b"; _ "c")`,
		`package f; import (_ "d"; _ "e")`,
	} {
		f, err := parser.ParseFile(fset, fmt.Sprintf("%d.go", i), content, 0)
		if err != nil {
			t.Fatal(err)
		}
		pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
		if err != nil {
			t.Fatal(err)
		}
		packages[pkg.Path()] = pkg
	}

	for _, test := range []struct {
		roots, want string
	}{
		{"a", "a"},
		{"b", "ab"},
		{"c", "ac"},
		{"d", "abcd"},
		{"e", "ace"},
		{"f", "abcdef"},

		{"be", "abce"},
		{"eb", "aceb"},
		{"de", "abcde"},
		{"ed", "acebd"},
		{"ef", "acebdf"},
	} {
		var pkgs []*types.Package
		for _, r := range test.roots {
			pkgs = append(pkgs, packages[string(r)])
		}
		var got string
		for _, p := range typeutil.Dependencies(pkgs...) {
			got += p.Path()
		}
		if got != test.want {
			t.Errorf("Dependencies(%q) = %q, want %q", test.roots, got, test.want)
		}
	}
}
开发者ID:dylanpoe,项目名称:golang.org,代码行数:62,代码来源:imports14_test.go


注:本文中的golang.org/x/tools/go/types.Config类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。