當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Config.CreateFromFiles方法代碼示例

本文整理匯總了Golang中golang.org/x/tools/go/loader.Config.CreateFromFiles方法的典型用法代碼示例。如果您正苦於以下問題:Golang Config.CreateFromFiles方法的具體用法?Golang Config.CreateFromFiles怎麽用?Golang Config.CreateFromFiles使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在golang.org/x/tools/go/loader.Config的用法示例。


在下文中一共展示了Config.CreateFromFiles方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: main

func main() {
	// Loader is a tool for opening Go files, it loads from a Config type
	conf := loader.Config{
		Build: &build.Default,
	}

	path, _ := filepath.Abs("looper")
	file, err := conf.ParseFile(path+"/"+"looper.go", nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Creation of a single file main pacakge
	conf.CreateFromFiles("looper", file)
	conf.Import("runtime")

	p, err := conf.Load()
	if err != nil {
		fmt.Println(err)
		return
	}

	// Finally, create SSA representation from the package we've loaded
	program := ssautil.CreateProgram(p, ssa.SanityCheckFunctions)
	looperPkg := program.Package(p.Created[0].Pkg)

	fmt.Println("RIGHT IN THE SINGLE STATIC ASSIGNMENT FORM:")
	looperPkg.WriteTo(os.Stdout)

	fmt.Println("LOOK AT THIS HERE LOOPER FUNC:")
	looperFunc := looperPkg.Func("Looper")
	looperFunc.WriteTo(os.Stdout)
}
開發者ID:vandosant,項目名稱:ssa-play,代碼行數:34,代碼來源:ssa.go

示例2: Parse

func (p *Parser) Parse(path string) error {
	dir := filepath.Dir(path)

	files, err := ioutil.ReadDir(dir)
	if err != nil {
		fmt.Printf("// [ERROR] Parse(%s) -> ioutil.ReadDir(%#v) -> err=<%#v>\n", path, dir, err)
		return err
	}

	var astFiles []*ast.File
	var conf loader.Config

	conf.TypeCheckFuncBodies = func(_ string) bool { return false }
	conf.TypeChecker.DisableUnusedImportCheck = true
	conf.TypeChecker.Importer = importer.Default()

	for _, fi := range files {
		if filepath.Ext(fi.Name()) != ".go" {
			continue
		}

		fpath := filepath.Join(dir, fi.Name())
		f, err := conf.ParseFile(fpath, nil)
		if err != nil {
			fmt.Printf("// [ERROR] Parse(%s) -> conf.ParseFile(%#v) -> err=<%#v>\n", path, fpath, err)
			return err
		}

		if fi.Name() == filepath.Base(path) {
			p.file = f
		}

		astFiles = append(astFiles, f)
	}

	abs, err := filepath.Abs(path)
	if err != nil {
		fmt.Printf("// [ERROR] Parse(%s) -> filepath.Abs(%#v) -> err=<%#v>\n", path, path, err)
		return err
	}

	// Type-check a package consisting of this file.
	// Type information for the imported packages
	// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
	conf.CreateFromFiles(abs, astFiles...)

	prog, err := conf.Load()
	if err != nil {
		fmt.Printf("// [ERROR] Parse(%s) -> conf.Load() -> err=<%#v>\n", path, err)
		return err
	} else if len(prog.Created) != 1 {
		panic("expected only one Created package")
	}

	p.path = abs
	p.pkg = prog.Created[0].Pkg

	return nil
}
開發者ID:tetrafolium,項目名稱:mockery,代碼行數:59,代碼來源:parse.go

示例3: Build

// Build constructs the SSA IR using given config, and sets up pointer analysis.
func (conf *Config) Build() (*SSAInfo, error) {
	var lconf = loader.Config{Build: &build.Default}
	buildLog := log.New(conf.BuildLog, "ssabuild: ", conf.LogFlags)

	if conf.BuildMode == FromFiles {
		args, err := lconf.FromArgs(conf.Files, false /* No tests */)
		if err != nil {
			return nil, err
		}
		if len(args) > 0 {
			return nil, fmt.Errorf("surplus arguments: %q", args)
		}
	} else if conf.BuildMode == FromString {
		f, err := lconf.ParseFile("", conf.Source)
		if err != nil {
			return nil, err
		}
		lconf.CreateFromFiles("", f)
	} else {
		buildLog.Fatal("Unknown build mode")

	}

	// Load, parse and type-check program
	lprog, err := lconf.Load()
	if err != nil {
		return nil, err
	}
	buildLog.Print("Program loaded and type checked")

	prog := ssautil.CreateProgram(lprog, ssa.GlobalDebug|ssa.BareInits)

	// Prepare Config for whole-program pointer analysis.
	ptaConf, err := setupPTA(prog, lprog, conf.PtaLog)

	ignoredPkgs := []string{}
	if len(conf.BadPkgs) == 0 {
		prog.Build()
	} else {
		for _, info := range lprog.AllPackages {
			if reason, badPkg := conf.BadPkgs[info.Pkg.Name()]; badPkg {
				buildLog.Printf("Skip package: %s (%s)", info.Pkg.Name(), reason)
				ignoredPkgs = append(ignoredPkgs, info.Pkg.Name())
			} else {
				prog.Package(info.Pkg).Build()
			}
		}
	}

	return &SSAInfo{
		BuildConf:   conf,
		IgnoredPkgs: ignoredPkgs,
		FSet:        lprog.Fset,
		Prog:        prog,
		PtaConf:     ptaConf,
		Logger:      buildLog,
	}, nil
}
開發者ID:nickng,項目名稱:dingo-hunter,代碼行數:59,代碼來源:ssabuild.go

示例4: TestSwitches

func TestSwitches(t *testing.T) {
	conf := loader.Config{ParserMode: parser.ParseComments}
	f, err := conf.ParseFile("testdata/switches.go", nil)
	if err != nil {
		t.Error(err)
		return
	}

	conf.CreateFromFiles("main", f)
	iprog, err := conf.Load()
	if err != nil {
		t.Error(err)
		return
	}

	prog := ssautil.CreateProgram(iprog, 0)
	mainPkg := prog.Package(iprog.Created[0].Pkg)
	mainPkg.Build()

	for _, mem := range mainPkg.Members {
		if fn, ok := mem.(*ssa.Function); ok {
			if fn.Synthetic != "" {
				continue // e.g. init()
			}
			// Each (multi-line) "switch" comment within
			// this function must match the printed form
			// of a ConstSwitch.
			var wantSwitches []string
			for _, c := range f.Comments {
				if fn.Syntax().Pos() <= c.Pos() && c.Pos() < fn.Syntax().End() {
					text := strings.TrimSpace(c.Text())
					if strings.HasPrefix(text, "switch ") {
						wantSwitches = append(wantSwitches, text)
					}
				}
			}

			switches := ssautil.Switches(fn)
			if len(switches) != len(wantSwitches) {
				t.Errorf("in %s, found %d switches, want %d", fn, len(switches), len(wantSwitches))
			}
			for i, sw := range switches {
				got := sw.String()
				if i >= len(wantSwitches) {
					continue
				}
				want := wantSwitches[i]
				if got != want {
					t.Errorf("in %s, found switch %d: got <<%s>>, want <<%s>>", fn, i, got, want)
				}
			}
		}
	}
}
開發者ID:2722,項目名稱:lantern,代碼行數:54,代碼來源:switch_test.go

示例5: genPkg

func genPkg(pkg *build.Package) {
	if len(pkg.CgoFiles) > 0 {
		errorf("gobind: cannot use cgo-dependent package as service definition: %s", pkg.CgoFiles[0])
		return
	}

	files := parseFiles(pkg.Dir, pkg.GoFiles)
	if len(files) == 0 {
		return // some error has been reported
	}

	conf := loader.Config{
		Fset: fset,
	}
	conf.TypeChecker.Error = func(err error) {
		errorf("%v", err)
	}
	conf.CreateFromFiles(pkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		errorf("%v", err)
		return
	}
	p := program.Created[0].Pkg

	fname := defaultFileName(*lang, p)
	switch *lang {
	case "java":
		w, closer := writer(fname, p)
		processErr(bind.GenJava(w, fset, p))
		closer()
	case "go":
		w, closer := writer(fname, p)
		processErr(bind.GenGo(w, fset, p))
		closer()
	case "objc":
		if fname == "" {
			processErr(bind.GenObjc(os.Stdout, fset, p, true))
			processErr(bind.GenObjc(os.Stdout, fset, p, false))
		} else {
			hname := fname[:len(fname)-2] + ".h"
			w, closer := writer(hname, p)
			processErr(bind.GenObjc(w, fset, p, true))
			closer()
			w, closer = writer(fname, p)
			processErr(bind.GenObjc(w, fset, p, false))
			closer()
		}
	default:
		errorf("unknown target language: %q", *lang)
	}
}
開發者ID:handong890,項目名稱:mobile,代碼行數:52,代碼來源:gen.go

示例6: newBinder

func newBinder(bindPkg *build.Package) (*binder, error) {
	if bindPkg.Name == "main" {
		return nil, fmt.Errorf("package %q: can only bind a library package", bindPkg.Name)
	}

	if len(bindPkg.CgoFiles) > 0 {
		return nil, fmt.Errorf("cannot use cgo-dependent package as service definition: %s", bindPkg.CgoFiles[0])
	}

	fset := token.NewFileSet()

	hasErr := false
	var files []*ast.File
	for _, filename := range bindPkg.GoFiles {
		p := filepath.Join(bindPkg.Dir, filename)
		file, err := parser.ParseFile(fset, p, nil, parser.AllErrors)
		if err != nil {
			hasErr = true
			if list, _ := err.(scanner.ErrorList); len(list) > 0 {
				for _, err := range list {
					fmt.Fprintln(os.Stderr, err)
				}
			} else {
				fmt.Fprintln(os.Stderr, err)
			}
		}
		files = append(files, file)
	}

	if hasErr {
		return nil, errors.New("package parsing failed.")
	}

	conf := loader.Config{
		Fset: fset,
	}
	conf.TypeChecker.Error = func(err error) {
		fmt.Fprintln(os.Stderr, err)
	}

	conf.CreateFromFiles(bindPkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		return nil, err
	}
	b := &binder{
		files: files,
		fset:  fset,
		pkg:   program.Created[0].Pkg,
	}
	return b, nil
}
開發者ID:Miaque,項目名稱:mojo,代碼行數:52,代碼來源:bind.go

示例7: create

func create(t *testing.T, content string) []*ssa.Package {
	var conf loader.Config
	f, err := conf.ParseFile("foo_test.go", content)
	if err != nil {
		t.Fatal(err)
	}
	conf.CreateFromFiles("foo", f)

	iprog, err := conf.Load()
	if err != nil {
		t.Fatal(err)
	}

	// We needn't call Build.
	return ssa.Create(iprog, ssa.SanityCheckFunctions).AllPackages()
}
開發者ID:himanshugpt,項目名稱:evergreen,代碼行數:16,代碼來源:testmain_test.go

示例8: TestRTA

// TestRTA runs RTA on each file in inputs, prints the results, and
// compares it with the golden results embedded in the WANT comment at
// the end of the file.
//
// The results string consists of two parts: the set of dynamic call
// edges, "f --> g", one per line, and the set of reachable functions,
// one per line.  Each set is sorted.
//
func TestRTA(t *testing.T) {
	for _, filename := range inputs {
		content, err := ioutil.ReadFile(filename)
		if err != nil {
			t.Errorf("couldn't read file '%s': %s", filename, err)
			continue
		}

		conf := loader.Config{
			SourceImports: true,
			ParserMode:    parser.ParseComments,
		}
		f, err := conf.ParseFile(filename, content)
		if err != nil {
			t.Error(err)
			continue
		}

		want, pos := expectation(f)
		if pos == token.NoPos {
			t.Errorf("No WANT: comment in %s", filename)
			continue
		}

		conf.CreateFromFiles("main", f)
		iprog, err := conf.Load()
		if err != nil {
			t.Error(err)
			continue
		}

		prog := ssa.Create(iprog, 0)
		mainPkg := prog.Package(iprog.Created[0].Pkg)
		prog.BuildAll()

		res := rta.Analyze([]*ssa.Function{
			mainPkg.Func("main"),
			mainPkg.Func("init"),
		}, true)

		if got := printResult(res, mainPkg.Object); got != want {
			t.Errorf("%s: got:\n%s\nwant:\n%s",
				prog.Fset.Position(pos), got, want)
		}
	}
}
開發者ID:himanshugpt,項目名稱:evergreen,代碼行數:54,代碼來源:rta_test.go

示例9: create

func create(t *testing.T, content string) *ssa.Package {
	var conf loader.Config
	f, err := conf.ParseFile("foo_test.go", content)
	if err != nil {
		t.Fatal(err)
	}
	conf.CreateFromFiles("foo", f)

	lprog, err := conf.Load()
	if err != nil {
		t.Fatal(err)
	}

	// We needn't call Build.
	foo := lprog.Package("foo").Pkg
	return ssautil.CreateProgram(lprog, ssa.SanityCheckFunctions).Package(foo)
}
開發者ID:syreclabs,項目名稱:go-tools,代碼行數:17,代碼來源:testmain_test.go

示例10: genPkg

func genPkg(pkg *build.Package) {
	if len(pkg.CgoFiles) > 0 {
		errorf("gobind: cannot use cgo-dependent package as service definition: %s", pkg.CgoFiles[0])
		return
	}

	files := parseFiles(pkg.Dir, pkg.GoFiles)
	if len(files) == 0 {
		return // some error has been reported
	}

	conf := loader.Config{
		SourceImports: true,
		Fset:          fset,
	}
	conf.TypeChecker.Error = func(err error) {
		errorf("%v", err)
	}
	conf.CreateFromFiles(pkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		errorf("%v", err)
		return
	}
	p := program.Created[0].Pkg

	switch *lang {
	case "java":
		err = bind.GenJava(os.Stdout, fset, p)
	case "go":
		err = bind.GenGo(os.Stdout, fset, p)
	default:
		errorf("unknown target language: %q", *lang)
	}

	if err != nil {
		if list, _ := err.(bind.ErrorList); len(list) > 0 {
			for _, err := range list {
				errorf("%v", err)
			}
		} else {
			errorf("%v", err)
		}
	}
}
開發者ID:TriangleGo,項目名稱:golang.org,代碼行數:45,代碼來源:gen.go

示例11: TestCHA

// TestCHA runs CHA on each file in inputs, prints the dynamic edges of
// the call graph, and compares it with the golden results embedded in
// the WANT comment at the end of the file.
//
func TestCHA(t *testing.T) {
	for _, filename := range inputs {
		content, err := ioutil.ReadFile(filename)
		if err != nil {
			t.Errorf("couldn't read file '%s': %s", filename, err)
			continue
		}

		conf := loader.Config{
			ParserMode: parser.ParseComments,
		}
		f, err := conf.ParseFile(filename, content)
		if err != nil {
			t.Error(err)
			continue
		}

		want, pos := expectation(f)
		if pos == token.NoPos {
			t.Errorf("No WANT: comment in %s", filename)
			continue
		}

		conf.CreateFromFiles("main", f)
		iprog, err := conf.Load()
		if err != nil {
			t.Error(err)
			continue
		}

		prog := ssautil.CreateProgram(iprog, 0)
		mainPkg := prog.Package(iprog.Created[0].Pkg)
		prog.Build()

		cg := cha.CallGraph(prog)

		if got := printGraph(cg, mainPkg.Pkg); got != want {
			t.Errorf("%s: got:\n%s\nwant:\n%s",
				prog.Fset.Position(pos), got, want)
		}
	}
}
開發者ID:binaryedge,項目名稱:40fy-client,代碼行數:46,代碼來源:cha_test.go

示例12: newPackage

func newPackage(files []*ast.File, conf *loader.Config, pkg *build.Package) (*bind.Package, error) {

	conf.CreateFromFiles(pkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		return nil, err
	}
	p := program.Created[0].Pkg

	var pkgast *ast.Package
	pkgs, err := parser.ParseDir(fset, pkg.Dir, nil, parser.ParseComments)
	if err != nil {
		return nil, err
	}
	pkgast = pkgs[p.Name()]

	pkgdoc := doc.New(pkgast, pkg.ImportPath, 0)

	return bind.NewPackage(p, pkgdoc), err
}
開發者ID:justinfx,項目名稱:gopy,代碼行數:20,代碼來源:gen.go

示例13: ExampleConfig_CreateFromFiles

// This example creates and type-checks a package from a list of
// already-parsed files, and loads all its dependencies.
func ExampleConfig_CreateFromFiles() {
	var conf loader.Config
	f, err := conf.ParseFile("hello.go", hello)
	if err != nil {
		log.Fatal(err)
	}
	conf.CreateFromFiles("hello", f)
	prog, err := conf.Load()
	if err != nil {
		log.Fatal(err)
	}

	printProgram(prog)
	printFilenames(prog.Fset, prog.Package("strconv"))
	// Output:
	// created: [hello]
	// imported: []
	// initial: [hello]
	// all: [errors fmt hello io math os reflect runtime strconv sync sync/atomic syscall time unicode/utf8]
	// strconv.Files: [atob.go atof.go atoi.go decimal.go doc.go extfloat.go ftoa.go isprint.go itoa.go quote.go]
}
開發者ID:dionb,項目名稱:tools,代碼行數:23,代碼來源:example_test.go

示例14: TestStatic

func TestStatic(t *testing.T) {
	conf := loader.Config{ParserMode: parser.ParseComments}
	f, err := conf.ParseFile("P.go", input)
	if err != nil {
		t.Fatal(err)
	}

	conf.CreateFromFiles("P", f)
	iprog, err := conf.Load()
	if err != nil {
		t.Fatal(err)
	}

	P := iprog.Created[0].Pkg

	prog := ssautil.CreateProgram(iprog, 0)
	prog.BuildAll()

	cg := static.CallGraph(prog)

	var edges []string
	callgraph.GraphVisitEdges(cg, func(e *callgraph.Edge) error {
		edges = append(edges, fmt.Sprintf("%s -> %s",
			e.Caller.Func.RelString(P),
			e.Callee.Func.RelString(P)))
		return nil
	})
	sort.Strings(edges)

	want := []string{
		"(*C).f -> (C).f",
		"f -> (C).f",
		"f -> f$1",
		"f -> g",
	}
	if !reflect.DeepEqual(edges, want) {
		t.Errorf("Got edges %v, want %v", edges, want)
	}
}
開發者ID:2722,項目名稱:lantern,代碼行數:39,代碼來源:static_test.go

示例15: parseProgram

func parseProgram(myPkg string, fs []*ast.File, target *ast.Ident) types.Object {
	cfg := loader.Config{
		Fset:       fset,
		ParserMode: parser.AllErrors,
		TypeChecker: types.Config{
			Error: func(error) {},
			DisableUnusedImportCheck: true,
		},
		TypeCheckFuncBodies: func(path string) bool {
			return path == myPkg
		},
		AllowErrors: true,
	}
	os.Setenv("CGO_ENABLED", "0")

	cfg.CreateFromFiles(myPkg, fs...)
	prog, err := cfg.Load()
	if err != nil {
		lg("load program err=%v", err)
	}

	return findIdentObj(prog, target)
}
開發者ID:zncoder,項目名稱:gosym,代碼行數:23,代碼來源:main.go


注:本文中的golang.org/x/tools/go/loader.Config.CreateFromFiles方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。