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


Golang importer.Default函数代码示例

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


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

示例1: 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())
}
开发者ID:kavehmz,项目名称:garbage,代码行数:28,代码来源:tmp34.go

示例2: 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
}
开发者ID:f5tracker,项目名称:example,代码行数:28,代码来源:main.go

示例3: main

func main() {
	flag.Parse()

	if *lang != "java" && *javaPkg != "" {
		log.Fatalf("Invalid option -javapkg for gobind -lang=%s", *lang)
	} else if *lang != "objc" && *prefix != "" {
		log.Fatalf("Invalid option -prefix for gobind -lang=%s", *lang)
	}

	// Make sure the export data for the packages being compiled is up to
	// date. Also use the go tool to provide good error messages for any
	// type checking errors in the provided packages.
	cmd := exec.Command("go", "install")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Args = append(cmd.Args, flag.Args()...)
	if err := cmd.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "%s failed: %v", strings.Join(cmd.Args, " "), err)
		os.Exit(1)
	}

	for _, arg := range flag.Args() {
		pkg, err := importer.Default().Import(arg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "could not import package %s: %v", arg, err)
			os.Exit(1)
		}
		genPkg(pkg)
	}
	os.Exit(exitStatus)
}
开发者ID:2722,项目名称:lantern,代码行数:31,代码来源:main.go

示例4: TestImportBug

func TestImportBug(t *testing.T) {
	buildPkg, err := build.Import("github.com/netbrain/importbug/foo", "", build.ImportComment)
	if err != nil {
		t.Fatal(err)
	}

	fset := token.NewFileSet()
	packages, err := parser.ParseDir(fset, buildPkg.Dir, nil, 0)
	if err != nil {
		t.Fatal(err)
	}

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

	for pName, p := range packages {
		files := make([]*ast.File, 0, len(p.Files))
		for _, f := range p.Files {
			files = append(files, f)
		}

		conf := &types.Config{
			FakeImportC: true,
			Importer:    importer.Default(),
		}
		_, err := conf.Check(pName, fset, files, info)
		if err != nil {
			log.Fatal(err)
		}
	}
}
开发者ID:netbrain,项目名称:importbug,代码行数:32,代码来源:importbug_test.go

示例5: 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,
		Importer:                 importer.Default(),
	}

	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
}
开发者ID:rickb777,项目名称:typewriter,代码行数:29,代码来源:package.go

示例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)
}
开发者ID:kr,项目名称:gotypesrepro,代码行数:27,代码来源:try.go

示例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
}
开发者ID:gtfour,项目名称:actuator,代码行数:25,代码来源:run.go

示例8: ImportFrom

// ImportFrom implements the go/types.ImporterFrom interface
func (i imp) ImportFrom(pkgpath, srcDir string, mode types.ImportMode) (*types.Package, error) {
	pkg, has := i.cache[pkgpath]
	if has {
		return pkg, nil
	}

	if pkgpath == "runtime" {
		pkg, err := importer.Default().(types.ImporterFrom).ImportFrom(pkgpath, srcDir, mode)
		i.cache[pkgpath] = pkg // cache even if pkg == nil and err != nil to prevent never ending loops
		return pkg, err
	}

	buildPkg, err := build.Import(pkgpath, srcDir, build.AllowBinary)
	if err != nil {
		return nil, err
	}

	var (
		fset     = token.NewFileSet()
		astFiles []*ast.File
	)

	astFiles, err = ParseAstFiles(fset, buildPkg.Dir, append(buildPkg.GoFiles, buildPkg.CgoFiles...))
	if err != nil {
		return nil, err
	}

	pkg, err = i.checkfn(buildPkg.ImportPath, fset, astFiles)
	i.cache[pkgpath] = pkg // cache even if pkg == nil and err != nil to prevent never ending loops
	return pkg, err
}
开发者ID:go-stay,项目名称:stay,代码行数:32,代码来源:importer.go

示例9: 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")
		}
	}
}
开发者ID:CoderLinDaCheng,项目名称:example,代码行数:28,代码来源:lookup.go

示例10: TestHilbert

func TestHilbert(t *testing.T) {
	t.Skip("skipping for gccgo--no importer")

	// generate source
	src := program(*H, *out)
	if *out != "" {
		ioutil.WriteFile(*out, src, 0666)
		return
	}

	// parse source
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "hilbert.go", src, 0)
	if err != nil {
		t.Fatal(err)
	}

	// type-check file
	DefPredeclaredTestFuncs() // define assert built-in
	conf := Config{Importer: importer.Default()}
	_, err = conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
	if err != nil {
		t.Fatal(err)
	}
}
开发者ID:kraj,项目名称:gcc,代码行数:25,代码来源:hilbert_test.go

示例11: newPackageInfo

func (imp *importer) newPackageInfo(path string) *PackageInfo {
	pkg := types.NewPackage(path, "")
	info := &PackageInfo{
		Pkg: pkg,
		Info: types.Info{
			Types:      make(map[ast.Expr]types.TypeAndValue),
			Defs:       make(map[*ast.Ident]types.Object),
			Uses:       make(map[*ast.Ident]types.Object),
			Implicits:  make(map[ast.Node]types.Object),
			Scopes:     make(map[ast.Node]*types.Scope),
			Selections: make(map[*ast.SelectorExpr]*types.Selection),
		},
		errorFunc: imp.conf.TypeChecker.Error,
	}

	// Copy the types.Config so we can vary it across PackageInfos.
	tc := imp.conf.TypeChecker
	tc.IgnoreFuncBodies = false
	if f := imp.conf.TypeCheckFuncBodies; f != nil {
		tc.IgnoreFuncBodies = !f(path)
	}
	tc.Importer = goimporter.Default()
	tc.Error = info.appendError // appendError wraps the user's Error function

	info.checker = types.NewChecker(&tc, imp.conf.fset(), pkg, &info.Info)
	imp.progMu.Lock()
	imp.prog.AllPackages[pkg] = info
	imp.progMu.Unlock()
	return info
}
开发者ID:arnold8,项目名称:mobile,代码行数:30,代码来源:loader.go

示例12: DefaultWithTestFiles

// DefaultWithTestFiles same as Default but it parses test files too
func DefaultWithTestFiles() types.Importer {
	return &customImporter{
		imported:      make(map[string]*types.Package),
		base:          importer.Default(),
		skipTestFiles: false,
	}
}
开发者ID:ernesto-jimenez,项目名称:gogen,代码行数:8,代码来源:importer.go

示例13: 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]
}
开发者ID:DuoSoftware,项目名称:v6engine-deps,代码行数:27,代码来源:typecheckrpc.go

示例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
}
开发者ID:vmware,项目名称:vic,代码行数:29,代码来源:analyzer.go

示例15: 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)
	}
}
开发者ID:achanda,项目名称:go,代码行数:27,代码来源:sizes_test.go


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