本文整理匯總了Golang中golang.org/x/tools/go/loader.Config.Import方法的典型用法代碼示例。如果您正苦於以下問題:Golang Config.Import方法的具體用法?Golang Config.Import怎麽用?Golang Config.Import使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類golang.org/x/tools/go/loader.Config
的用法示例。
在下文中一共展示了Config.Import方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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
})
}
}
}
示例2: 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)
}
}
}
}
示例3: 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)
}
示例4: 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]
}
示例5: 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)
}
}
}
示例6: TestLoad_BadDependency_AllowErrors
func TestLoad_BadDependency_AllowErrors(t *testing.T) {
for _, test := range []struct {
descr string
pkgs map[string]string
wantPkgs string
}{
{
descr: "missing dependency",
pkgs: map[string]string{
"a": `package a; import _ "b"`,
"b": `package b; import _ "c"`,
},
wantPkgs: "a b",
},
{
descr: "bad package decl in dependency",
pkgs: map[string]string{
"a": `package a; import _ "b"`,
"b": `package b; import _ "c"`,
"c": `package`,
},
wantPkgs: "a b",
},
{
descr: "parse error in dependency",
pkgs: map[string]string{
"a": `package a; import _ "b"`,
"b": `package b; import _ "c"`,
"c": `package c; var x = `,
},
wantPkgs: "a b c",
},
} {
conf := loader.Config{
AllowErrors: true,
SourceImports: true,
Build: fakeContext(test.pkgs),
}
conf.Import("a")
prog, err := conf.Load()
if err != nil {
t.Errorf("%s: Load failed unexpectedly: %v", test.descr, err)
}
if prog == nil {
t.Fatalf("%s: Load returned a nil Program", test.descr)
}
if got, want := imported(prog), "a"; got != want {
t.Errorf("%s: Imported = %s, want %s", test.descr, got, want)
}
if got := all(prog); strings.Join(got, " ") != test.wantPkgs {
t.Errorf("%s: AllPackages = %s, want %s", test.descr, got, test.wantPkgs)
}
}
}
示例7: invalidProgram
func invalidProgram(name string) *loader.Program {
var ldr loader.Config
ldr.ParserMode = goparser.ParseComments
ldr.Import("../fixtures/goparsing/" + name)
prog, err := ldr.Load()
if err != nil {
log.Fatal(err)
}
return prog
}
示例8: TestErrorReporting
// Test that both syntax (scan/parse) and type errors are both recorded
// (in PackageInfo.Errors) and reported (via Config.TypeChecker.Error).
func TestErrorReporting(t *testing.T) {
pkgs := map[string]string{
"a": `package a; import _ "b"; var x int = false`,
"b": `package b; 'syntax error!`,
}
conf := loader.Config{
AllowErrors: true,
SourceImports: true,
Build: fakeContext(pkgs),
}
var allErrors []error
conf.TypeChecker.Error = func(err error) {
allErrors = append(allErrors, err)
}
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")
}
hasError := func(errors []error, substr string) bool {
for _, err := range errors {
if strings.Contains(err.Error(), substr) {
return true
}
}
return false
}
// TODO(adonovan): test keys of ImportMap.
// Check errors recorded in each PackageInfo.
for pkg, info := range prog.AllPackages {
switch pkg.Path() {
case "a":
if !hasError(info.Errors, "cannot convert false") {
t.Errorf("a.Errors = %v, want bool conversion (type) error", info.Errors)
}
case "b":
if !hasError(info.Errors, "rune literal not terminated") {
t.Errorf("b.Errors = %v, want unterminated literal (syntax) error", info.Errors)
}
}
}
// Check errors reported via error handler.
if !hasError(allErrors, "cannot convert false") ||
!hasError(allErrors, "rune literal not terminated") {
t.Errorf("allErrors = %v, want both syntax and type errors", allErrors)
}
}
示例9: loadProgram
func loadProgram(ctx *build.Context, pkgs []string) (*loader.Program, error) {
conf := loader.Config{
Build: ctx,
ParserMode: parser.ParseComments,
AllowErrors: false,
}
for _, pkg := range pkgs {
conf.Import(pkg)
}
return conf.Load()
}
示例10: TestErrorReporting
// Test that syntax (scan/parse), type, and loader errors are recorded
// (in PackageInfo.Errors) and reported (via Config.TypeChecker.Error).
func TestErrorReporting(t *testing.T) {
pkgs := map[string]string{
"a": `package a; import (_ "b"; _ "c"); var x int = false`,
"b": `package b; 'syntax error!`,
}
conf := loader.Config{
AllowErrors: true,
Build: fakeContext(pkgs),
}
var mu sync.Mutex
var allErrors []error
conf.TypeChecker.Error = func(err error) {
mu.Lock()
allErrors = append(allErrors, err)
mu.Unlock()
}
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")
}
// TODO(adonovan): test keys of ImportMap.
// Check errors recorded in each PackageInfo.
for pkg, info := range prog.AllPackages {
switch pkg.Path() {
case "a":
if !hasError(info.Errors, "cannot convert false") {
t.Errorf("a.Errors = %v, want bool conversion (type) error", info.Errors)
}
if !hasError(info.Errors, "could not import c") {
t.Errorf("a.Errors = %v, want import (loader) error", info.Errors)
}
case "b":
if !hasError(info.Errors, "rune literal not terminated") {
t.Errorf("b.Errors = %v, want unterminated literal (syntax) error", info.Errors)
}
}
}
// Check errors reported via error handler.
if !hasError(allErrors, "cannot convert false") ||
!hasError(allErrors, "rune literal not terminated") ||
!hasError(allErrors, "could not import c") {
t.Errorf("allErrors = %v, want syntax, type and loader errors", allErrors)
}
}
示例11: InlineDotImports
// InlineDotImports displays Go package source code with dot imports inlined.
func InlineDotImports(w io.Writer, importPath string) {
/*imp2 := importer.New()
imp2.Config.UseGcFallback = true
cfg := types.Config{Import: imp2.Import}
_ = cfg*/
conf := loader.Config{
//TypeChecker: cfg,
}
conf.Import(importPath)
prog, err := conf.Load()
if err != nil {
panic(err)
}
/*pi, err := imp.ImportPackage(importPath)
if err != nil {
panic(err)
}
_ = pi*/
pi := prog.Imported[importPath]
findDotImports(prog, pi)
files := make(map[string]*ast.File)
{
// This package
for _, file := range pi.Files {
filename := prog.Fset.File(file.Package).Name()
files[filename] = file
}
// All dot imports
for _, pi := range dotImports {
for _, file := range pi.Files {
filename := prog.Fset.File(file.Package).Name()
files[filename] = file
}
}
}
apkg := &ast.Package{Name: pi.Pkg.Name(), Files: files}
merged := ast.MergePackageFiles(apkg, astMergeMode)
WriteMergedPackage(w, prog.Fset, merged)
}
示例12: TestLoad_MissingInitialPackage
func TestLoad_MissingInitialPackage(t *testing.T) {
var conf loader.Config
conf.Import("nosuchpkg")
conf.Import("errors")
const wantErr = "couldn't load packages due to errors: nosuchpkg"
prog, err := conf.Load()
if err == nil {
t.Errorf("Load succeeded unexpectedly, want %q", wantErr)
} else if err.Error() != wantErr {
t.Errorf("Load failed with wrong error %q, want %q", err, wantErr)
}
if prog != nil {
t.Errorf("Load unexpectedly returned a Program")
}
}
示例13: main
func main() {
if len(os.Args) != 3 {
log.Fatal("Usage: doc <package> <object>")
}
//!+part1
pkgpath, name := os.Args[1], os.Args[2]
// The loader loads a complete Go program from source code.
conf := loader.Config{ParserMode: parser.ParseComments}
conf.Import(pkgpath)
lprog, err := conf.Load()
if err != nil {
log.Fatal(err) // load error
}
// Find the package and package-level object.
pkg := lprog.Package(pkgpath).Pkg
obj := pkg.Scope().Lookup(name)
if obj == nil {
log.Fatalf("%s.%s not found", pkg.Path(), name)
}
//!-part1
//!+part2
// Print the object and its methods (incl. location of definition).
fmt.Println(obj)
for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
fmt.Printf("%s: %s\n", lprog.Fset.Position(sel.Obj().Pos()), sel)
}
// Find the path from the root of the AST to the object's position.
// Walk up to the enclosing ast.Decl for the doc comment.
_, path, _ := lprog.PathEnclosingInterval(obj.Pos(), obj.Pos())
for _, n := range path {
switch n := n.(type) {
case *ast.GenDecl:
fmt.Println("\n", n.Doc.Text())
return
case *ast.FuncDecl:
fmt.Println("\n", n.Doc.Text())
return
}
}
//!-part2
}
示例14: importQueryPackage
// importQueryPackage finds the package P containing the
// query position and tells conf to import it.
// It returns the package's path.
func importQueryPackage(pos string, conf *loader.Config) (string, error) {
fqpos, err := fastQueryPos(pos)
if err != nil {
return "", err // bad query
}
filename := fqpos.fset.File(fqpos.start).Name()
// This will not work for ad-hoc packages
// such as $GOROOT/src/net/http/triv.go.
// TODO(adonovan): ensure we report a clear error.
_, importPath, err := guessImportPath(filename, conf.Build)
if err != nil {
return "", err // can't find GOPATH dir
}
if importPath == "" {
return "", fmt.Errorf("can't guess import path from %s", filename)
}
// Check that it's possible to load the queried package.
// (e.g. oracle tests contain different 'package' decls in same dir.)
// Keep consistent with logic in loader/util.go!
cfg2 := *conf.Build
cfg2.CgoEnabled = false
bp, err := cfg2.Import(importPath, "", 0)
if err != nil {
return "", err // no files for package
}
switch pkgContainsFile(bp, filename) {
case 'T':
conf.ImportWithTests(importPath)
case 'X':
conf.ImportWithTests(importPath)
importPath += "_test" // for TypeCheckFuncBodies
case 'G':
conf.Import(importPath)
default:
return "", fmt.Errorf("package %q doesn't contain file %s",
importPath, filename)
}
conf.TypeCheckFuncBodies = func(p string) bool { return p == importPath }
return importPath, nil
}
示例15: ExampleLoadProgram
// This program shows how to load a main package (cmd/cover) and all its
// dependencies from source, using the loader, and then build SSA code
// for the entire program. This is what you'd typically use for a
// whole-program analysis.
//
func ExampleLoadProgram() {
// Load cmd/cover and its dependencies.
var conf loader.Config
conf.Import("cmd/cover")
lprog, err := conf.Load()
if err != nil {
fmt.Print(err) // type error in some package
return
}
// Create SSA-form program representation.
prog := ssautil.CreateProgram(lprog, ssa.SanityCheckFunctions)
// Build SSA code for the entire cmd/cover program.
prog.Build()
// Output:
}