本文整理匯總了Golang中golang.org/x/tools/go/loader.Config.Load方法的典型用法代碼示例。如果您正苦於以下問題:Golang Config.Load方法的具體用法?Golang Config.Load怎麽用?Golang Config.Load使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類golang.org/x/tools/go/loader.Config
的用法示例。
在下文中一共展示了Config.Load方法的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)
}
示例2: loadProgram
func loadProgram(args []string, tests bool) (*ssa.Program, error) {
conf := loader.Config{}
if len(args) == 0 {
fmt.Fprintln(os.Stderr, Usage)
os.Exit(1)
}
// Use the initial packages from the command line.
args, err := conf.FromArgs(args, tests)
if err != nil {
return nil, err
}
// Load, parse and type-check the whole program.
iprog, err := conf.Load()
if err != nil {
return nil, err
}
// Create and build SSA-form program representation.
prog := ssautil.CreateProgram(iprog, 0)
prog.BuildAll()
return prog, nil
}
示例3: myloader
// Return count of unused vars
func myloader(args []string) (count int) {
var conf loader.Config
conf.FromArgs(args, false)
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
for _, pi := range prog.Created {
fmt.Println(pi)
}
info := prog.Package(args[0]).Info
fset := prog.Fset
ssaprog := ssautil.CreateProgram(prog, ssa.GlobalDebug)
ssaprog.Build()
for expr, object := range info.Defs {
unused := checkObj(expr, object, prog, ssaprog, fset)
if unused {
fmt.Fprintf(os.Stderr, "Unused assignment for '%v' %v\n", expr, fset.Position(expr.Pos()))
count++
}
}
for expr, object := range info.Uses {
unused := checkObj(expr, object, prog, ssaprog, fset)
if unused {
fmt.Fprintf(os.Stderr, "Unused assignment for '%v' %v\n", expr, fset.Position(expr.Pos()))
count++
}
}
return count
}
示例4: TestLoad_FromImports_Success
func TestLoad_FromImports_Success(t *testing.T) {
var conf loader.Config
conf.ImportWithTests("fmt")
conf.ImportWithTests("errors")
prog, err := conf.Load()
if err != nil {
t.Errorf("Load failed unexpectedly: %v", err)
}
if prog == nil {
t.Fatalf("Load returned a nil Program")
}
if got, want := created(prog), "errors_test fmt_test"; got != want {
t.Errorf("Created = %q, want %s", got, want)
}
if got, want := imported(prog), "errors fmt"; got != want {
t.Errorf("Imported = %s, want %s", got, want)
}
// Check set of transitive packages.
// There are >30 and the set may grow over time, so only check a few.
want := map[string]bool{
"strings": true,
"time": true,
"runtime": true,
"testing": true,
"unicode": true,
}
for _, path := range all(prog) {
delete(want, path)
}
if len(want) > 0 {
t.Errorf("AllPackages is missing these keys: %q", keys(want))
}
}
示例5: TestLoad_ParseError_AllowErrors
func TestLoad_ParseError_AllowErrors(t *testing.T) {
var conf loader.Config
conf.AllowErrors = true
conf.CreateFromFilenames("badpkg", "testdata/badpkgdecl.go")
prog, err := conf.Load()
if err != nil {
t.Errorf("Load failed unexpectedly: %v", err)
}
if prog == nil {
t.Fatalf("Load returned a nil Program")
}
if got, want := created(prog), "badpkg"; got != want {
t.Errorf("Created = %s, want %s", got, want)
}
badpkg := prog.Created[0]
if len(badpkg.Files) != 1 {
t.Errorf("badpkg has %d files, want 1", len(badpkg.Files))
}
wantErr := filepath.Join("testdata", "badpkgdecl.go") + ":1:34: expected 'package', found 'EOF'"
if !hasError(badpkg.Errors, wantErr) {
t.Errorf("badpkg.Errors = %v, want %s", badpkg.Errors, wantErr)
}
}
示例6: loadWithSoftErrors
// loadWithSoftErrors calls lconf.Load, suppressing "soft" errors. (See Go issue 16530.)
// TODO(adonovan): Once the loader has an option to allow soft errors,
// replace calls to loadWithSoftErrors with loader calls with that parameter.
func loadWithSoftErrors(lconf *loader.Config) (*loader.Program, error) {
lconf.AllowErrors = true
// Ideally we would just return conf.Load() here, but go/types
// reports certain "soft" errors that gc does not (Go issue 14596).
// As a workaround, we set AllowErrors=true and then duplicate
// the loader's error checking but allow soft errors.
// It would be nice if the loader API permitted "AllowErrors: soft".
prog, err := lconf.Load()
if err != nil {
return nil, err
}
var errpkgs []string
// Report hard errors in indirectly imported packages.
for _, info := range prog.AllPackages {
if containsHardErrors(info.Errors) {
errpkgs = append(errpkgs, info.Pkg.Path())
} else {
// Enable SSA construction for packages containing only soft errors.
info.TransitivelyErrorFree = true
}
}
if errpkgs != nil {
var more string
if len(errpkgs) > 3 {
more = fmt.Sprintf(" and %d more", len(errpkgs)-3)
errpkgs = errpkgs[:3]
}
return nil, fmt.Errorf("couldn't load packages due to errors: %s%s",
strings.Join(errpkgs, ", "), more)
}
return prog, err
}
示例7: TestCwd
func TestCwd(t *testing.T) {
ctxt := fakeContext(map[string]string{"one/two/three": `package three`})
for _, test := range []struct {
cwd, arg, want string
}{
{cwd: "/go/src/one", arg: "./two/three", want: "one/two/three"},
{cwd: "/go/src/one", arg: "../one/two/three", want: "one/two/three"},
{cwd: "/go/src/one", arg: "one/two/three", want: "one/two/three"},
{cwd: "/go/src/one/two/three", arg: ".", want: "one/two/three"},
{cwd: "/go/src/one", arg: "two/three", want: ""},
} {
conf := loader.Config{
Cwd: test.cwd,
Build: ctxt,
}
conf.Import(test.arg)
var got string
prog, err := conf.Load()
if prog != nil {
got = imported(prog)
}
if got != test.want {
t.Errorf("Load(%s) from %s: Imported = %s, want %s",
test.arg, test.cwd, got, test.want)
if err != nil {
t.Errorf("Load failed: %v", err)
}
}
}
}
示例8: TestStdlib
func TestStdlib(t *testing.T) {
defer func(saved func(format string, args ...interface{})) {
logf = saved
}(logf)
logf = t.Errorf
ctxt := build.Default // copy
// Enumerate $GOROOT packages.
saved := ctxt.GOPATH
ctxt.GOPATH = "" // disable GOPATH during AllPackages
pkgs := buildutil.AllPackages(&ctxt)
ctxt.GOPATH = saved
// Throw in a number of go.tools packages too.
pkgs = append(pkgs,
"golang.org/x/tools/cmd/godoc",
"golang.org/x/tools/refactor/lexical")
// Load, parse and type-check the program.
conf := loader.Config{Build: &ctxt}
for _, path := range pkgs {
conf.ImportWithTests(path)
}
iprog, err := conf.Load()
if err != nil {
t.Fatalf("Load failed: %v", err)
}
// This test ensures that Structure doesn't panic and that
// its internal sanity-checks against go/types don't fail.
for pkg, info := range iprog.AllPackages {
_ = Structure(iprog.Fset, pkg, &info.Info, info.Files)
}
}
示例9: ExampleConfig_Import
// This example imports three packages, including the tests for one of
// them, and loads all their dependencies.
func ExampleConfig_Import() {
// ImportWithTest("strconv") causes strconv to include
// internal_test.go, and creates an external test package,
// strconv_test.
// (Compare with the example of CreateFromFiles.)
var conf loader.Config
conf.Import("unicode/utf8")
conf.Import("errors")
conf.ImportWithTests("strconv")
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
printProgram(prog)
printFilenames(prog.Fset, prog.Package("strconv"))
printFilenames(prog.Fset, prog.Package("strconv_test"))
// Output:
// created: [strconv_test]
// imported: [errors strconv unicode/utf8]
// initial: [errors strconv strconv_test unicode/utf8]
// all: [bufio bytes errors flag fmt io log math math/rand os reflect runtime runtime/pprof runtime/trace sort strconv strconv_test strings sync sync/atomic syscall testing text/tabwriter time unicode unicode/utf8]
// strconv.Files: [atob.go atof.go atoi.go decimal.go doc.go extfloat.go ftoa.go isprint.go itoa.go quote.go internal_test.go]
// strconv_test.Files: [atob_test.go atof_test.go atoi_test.go decimal_test.go example_test.go fp_test.go ftoa_test.go itoa_test.go quote_test.go strconv_test.go]
}
示例10: loadProgram
// loadProgram loads the specified set of packages (plus their tests)
// and all their dependencies, from source, through the specified build
// context. Only packages in pkgs will have their functions bodies typechecked.
func loadProgram(ctxt *build.Context, pkgs map[string]bool) (*loader.Program, error) {
conf := loader.Config{
Build: ctxt,
SourceImports: true,
ParserMode: parser.ParseComments,
// TODO(adonovan): enable this. Requires making a lot of code more robust!
AllowErrors: false,
}
// Optimization: don't type-check the bodies of functions in our
// dependencies, since we only need exported package members.
conf.TypeCheckFuncBodies = func(p string) bool {
return pkgs[p] || pkgs[strings.TrimSuffix(p, "_test")]
}
if Verbose {
var list []string
for pkg := range pkgs {
list = append(list, pkg)
}
sort.Strings(list)
for _, pkg := range list {
fmt.Fprintf(os.Stderr, "Loading package: %s\n", pkg)
}
}
for pkg := range pkgs {
if err := conf.ImportWithTests(pkg); err != nil {
return nil, err
}
}
return conf.Load()
}
示例11: main
func main() {
flag.Parse()
importPaths := gotool.ImportPaths(flag.Args())
if len(importPaths) == 0 {
return
}
var conf loader.Config
conf.Fset = fset
for _, importPath := range importPaths {
conf.Import(importPath)
}
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
for _, pkg := range prog.InitialPackages() {
for _, file := range pkg.Files {
ast.Inspect(file, func(node ast.Node) bool {
if s, ok := node.(*ast.StructType); ok {
malign(node.Pos(), pkg.Types[s].Type.(*types.Struct))
}
return true
})
}
}
}
示例12: NewUnexporter
// Create unexporter
func NewUnexporter(o *Config) (*unexporter, error) {
var conf loader.Config
for _, package_name := range buildutil.AllPackages(&build.Default) {
conf.ImportWithTests(package_name)
}
program, err := conf.Load()
if err != nil {
return nil, err
}
if program.Package(o.Pkg) == nil {
return nil, errors.New(fmt.Sprintf("'%s' is not a valid package", o.Pkg))
}
if o.Debug {
pkg := program.Package(o.Pkg).Pkg
fmt.Printf("finding unused identifiers for %s (%s)\n", pkg.Name(), pkg.Path())
}
unexporter := &unexporter{
Program: program,
MainPackage: program.Package(o.Pkg),
Verbose: o.Debug,
}
unexporter.run()
return unexporter, nil
}
示例13: TestTransitivelyErrorFreeFlag
func TestTransitivelyErrorFreeFlag(t *testing.T) {
// Create an minimal custom build.Context
// that fakes the following packages:
//
// a --> b --> c! c has an error
// \ d and e are transitively error-free.
// e --> d
//
// Each package [a-e] consists of one file, x.go.
pkgs := map[string]string{
"a": `package a; import (_ "b"; _ "e")`,
"b": `package b; import _ "c"`,
"c": `package c; func f() { _ = int(false) }`, // type error within function body
"d": `package d;`,
"e": `package e; import _ "d"`,
}
conf := loader.Config{
AllowErrors: true,
SourceImports: true,
Build: fakeContext(pkgs),
}
conf.Import("a")
prog, err := conf.Load()
if err != nil {
t.Errorf("Load failed: %s", err)
}
if prog == nil {
t.Fatalf("Load returned nil *Program")
}
for pkg, info := range prog.AllPackages {
var wantErr, wantTEF bool
switch pkg.Path() {
case "a", "b":
case "c":
wantErr = true
case "d", "e":
wantTEF = true
default:
t.Errorf("unexpected package: %q", pkg.Path())
continue
}
if (info.Errors != nil) != wantErr {
if wantErr {
t.Errorf("Package %q.Error = nil, want error", pkg.Path())
} else {
t.Errorf("Package %q has unexpected Errors: %v",
pkg.Path(), info.Errors)
}
}
if info.TransitivelyErrorFree != wantTEF {
t.Errorf("Package %q.TransitivelyErrorFree=%t, want %t",
pkg.Path(), info.TransitivelyErrorFree, wantTEF)
}
}
}
示例14: 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
}
示例15: createProgram
// createProgram returns a program containing packages specified.
func createProgram(packages ...string) (*loader.Program, error) {
var conf loader.Config
for _, name := range packages {
conf.CreateFromFilenames(name, getFileNames(name)...)
}
return conf.Load()
}