本文整理匯總了Golang中golang.org/x/tools/go/loader.Config.FromArgs方法的典型用法代碼示例。如果您正苦於以下問題:Golang Config.FromArgs方法的具體用法?Golang Config.FromArgs怎麽用?Golang Config.FromArgs使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類golang.org/x/tools/go/loader.Config
的用法示例。
在下文中一共展示了Config.FromArgs方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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
}
示例2: 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
}
示例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
}
示例4: Query
// Query runs a single oracle query.
//
// args specify the main package in (*loader.Config).FromArgs syntax.
// mode is the query mode ("callers", etc).
// ptalog is the (optional) pointer-analysis log file.
// buildContext is the go/build configuration for locating packages.
// reflection determines whether to model reflection soundly (currently slow).
//
// Clients that intend to perform multiple queries against the same
// analysis scope should use this pattern instead:
//
// conf := loader.Config{Build: buildContext, SourceImports: true}
// ... populate config, e.g. conf.FromArgs(args) ...
// iprog, err := conf.Load()
// if err != nil { ... }
// o, err := oracle.New(iprog, nil, false)
// if err != nil { ... }
// for ... {
// qpos, err := oracle.ParseQueryPos(imp, pos, needExact)
// if err != nil { ... }
//
// res, err := o.Query(mode, qpos)
// if err != nil { ... }
//
// // use res
// }
//
// TODO(adonovan): the ideal 'needsExact' parameter for ParseQueryPos
// depends on the query mode; how should we expose this?
//
func Query(args []string, mode, pos string, ptalog io.Writer, buildContext *build.Context, reflection bool) (*Result, error) {
if mode == "what" {
// Bypass package loading, type checking, SSA construction.
return what(pos, buildContext)
}
minfo := findMode(mode)
if minfo == nil {
return nil, fmt.Errorf("invalid mode type: %q", mode)
}
conf := loader.Config{Build: buildContext, SourceImports: true}
// Determine initial packages.
args, err := conf.FromArgs(args, true)
if err != nil {
return nil, err
}
if len(args) > 0 {
return nil, fmt.Errorf("surplus arguments: %q", args)
}
// For queries needing only a single typed package,
// reduce the analysis scope to that package.
if minfo.needs&(needSSA|needRetainTypeInfo) == 0 {
reduceScope(pos, &conf)
}
// TODO(adonovan): report type errors to the user via Serial
// types, not stderr?
// conf.TypeChecker.Error = func(err error) {
// E := err.(types.Error)
// fmt.Fprintf(os.Stderr, "%s: %s\n", E.Fset.Position(E.Pos), E.Msg)
// }
// Load/parse/type-check the program.
iprog, err := conf.Load()
if err != nil {
return nil, err
}
o, err := newOracle(iprog, ptalog, minfo.needs, reflection)
if err != nil {
return nil, err
}
qpos, err := ParseQueryPos(iprog, pos, minfo.needs&needExactPos != 0)
if err != nil && minfo.needs&(needPos|needExactPos) != 0 {
return nil, err
}
// SSA is built and we have the QueryPos.
// Release the other ASTs and type info to the GC.
iprog = nil
return o.query(minfo, qpos)
}
示例5: addCode
// addCode searches for main func in data, and updates AST code
// adding tracing functions.
func addCode(path string) ([]byte, error) {
var conf loader.Config
if _, err := conf.FromArgs([]string{path}, false); err != nil {
return nil, err
}
prog, err := conf.Load()
if err != nil {
return nil, err
}
// check if runtime/trace already imported
for i, _ := range prog.Imported {
if i == "runtime/trace" {
return nil, ErrImported
}
}
pkg := prog.Created[0]
// TODO: find file with main func inside
astFile := pkg.Files[0]
// add imports
astutil.AddImport(prog.Fset, astFile, "os")
astutil.AddImport(prog.Fset, astFile, "runtime/trace")
astutil.AddImport(prog.Fset, astFile, "time")
// add start/stop code
ast.Inspect(astFile, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
// find 'main' function
if x.Name.Name == "main" && x.Recv == nil {
stmts := createTraceStmts()
stmts = append(stmts, x.Body.List...)
x.Body.List = stmts
return true
}
}
return true
})
var buf bytes.Buffer
err = printer.Fprint(&buf, prog.Fset, astFile)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
示例6: setPTAScope
func setPTAScope(lconf *loader.Config, scope []string) error {
if len(scope) == 0 {
return fmt.Errorf("no packages specified for pointer analysis scope")
}
// Determine initial packages for PTA.
args, err := lconf.FromArgs(scope, true)
if err != nil {
return err
}
if len(args) > 0 {
return fmt.Errorf("surplus arguments: %q", args)
}
return nil
}
示例7: loadProgram
func loadProgram(args []string) (*loader.Program, error) {
var conf loader.Config
rest, err := conf.FromArgs(args, true)
if err != nil {
return nil, fmt.Errorf("could not parse arguments: %s", err)
}
if len(rest) > 0 {
return nil, fmt.Errorf("unhandled extra arguments: %v", rest)
}
prog, err := conf.Load()
if err != nil {
return nil, fmt.Errorf("could not load: %s", err)
}
return prog, nil
}
示例8: Main
// Main is like calling the 'gog' program.
func Main(config *loader.Config, args []string) (*Output, error) {
var importUnsafe bool
for _, a := range args {
if a == "unsafe" {
importUnsafe = true
break
}
}
extraArgs, err := config.FromArgs(args, true)
if err != nil {
log.Fatal(err)
}
if len(extraArgs) > 0 {
return nil, fmt.Errorf("extra args after pkgs list")
}
if importUnsafe {
// Special-case "unsafe" because go/loader does not let you load it
// directly.
if config.ImportPkgs == nil {
config.ImportPkgs = make(map[string]bool)
}
config.ImportPkgs["unsafe"] = true
}
prog, err := config.Load()
if err != nil {
return nil, err
}
g := New(prog)
var pkgs []*loader.PackageInfo
pkgs = append(pkgs, prog.Created...)
for _, pkg := range prog.Imported {
pkgs = append(pkgs, pkg)
}
for _, pkg := range pkgs {
if err := g.Graph(pkg); err != nil {
return nil, err
}
}
return &g.Output, nil
}
示例9: load
func (c *Checker) load(paths ...string) (*loader.Program, error) {
ctx := build.Default
for _, tag := range c.Tags {
ctx.BuildTags = append(ctx.BuildTags, tag)
}
loadcfg := loader.Config{
Build: &ctx,
}
rest, err := loadcfg.FromArgs(paths, !c.WithoutTests)
if err != nil {
return nil, fmt.Errorf("could not parse arguments: %s", err)
}
if len(rest) > 0 {
return nil, fmt.Errorf("unhandled extra arguments: %v", rest)
}
return loadcfg.Load()
}
示例10: main
func main() {
flag.Parse()
// The loader loads a complete Go program from source code.
var conf loader.Config
_, err := conf.FromArgs(flag.Args(), false)
if err != nil {
log.Fatal(err) // command syntax error
}
lprog, err := conf.Load()
if err != nil {
log.Fatal(err) // load error
}
for _, info := range lprog.InitialPackages() {
PrintHugeParams(lprog.Fset, &info.Info, info.Files)
}
}
示例11: ExampleConfig_FromArgs
// This example loads a set of packages and all of their dependencies
// from a typical command-line. FromArgs parses a command line and
// makes calls to the other methods of Config shown in the examples that
// follow.
func ExampleConfig_FromArgs() {
args := []string{"mytool", "unicode/utf8", "errors", "runtime", "--", "foo", "bar"}
const wantTests = false
var conf loader.Config
rest, err := conf.FromArgs(args[1:], wantTests)
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
fmt.Printf("rest: %s\n", rest)
printProgram(prog)
// Output:
// rest: [foo bar]
// created: []
// imported: [errors runtime unicode/utf8]
// initial: [errors runtime unicode/utf8]
// all: [errors runtime unicode/utf8]
}
示例12: run
func run(t *testing.T, dir, input string, success successPredicate) bool {
fmt.Printf("Input: %s\n", input)
start := time.Now()
var inputs []string
for _, i := range strings.Split(input, " ") {
if strings.HasSuffix(i, ".go") {
i = dir + i
}
inputs = append(inputs, i)
}
var conf loader.Config
if _, err := conf.FromArgs(inputs, true); err != nil {
t.Errorf("FromArgs(%s) failed: %s", inputs, err)
return false
}
conf.Import("runtime")
// Print a helpful hint if we don't make it to the end.
var hint string
defer func() {
if hint != "" {
fmt.Println("FAIL")
fmt.Println(hint)
} else {
fmt.Println("PASS")
}
interp.CapturedOutput = nil
}()
hint = fmt.Sprintf("To dump SSA representation, run:\n%% go build golang.org/x/tools/cmd/ssadump && ./ssadump -build=CFP %s\n", input)
iprog, err := conf.Load()
if err != nil {
t.Errorf("conf.Load(%s) failed: %s", inputs, err)
return false
}
prog := ssautil.CreateProgram(iprog, ssa.SanityCheckFunctions)
prog.BuildAll()
var mainPkg *ssa.Package
var initialPkgs []*ssa.Package
for _, info := range iprog.InitialPackages() {
if info.Pkg.Path() == "runtime" {
continue // not an initial package
}
p := prog.Package(info.Pkg)
initialPkgs = append(initialPkgs, p)
if mainPkg == nil && p.Func("main") != nil {
mainPkg = p
}
}
if mainPkg == nil {
testmainPkg := prog.CreateTestMainPackage(initialPkgs...)
if testmainPkg == nil {
t.Errorf("CreateTestMainPackage(%s) returned nil", mainPkg)
return false
}
if testmainPkg.Func("main") == nil {
t.Errorf("synthetic testmain package has no main")
return false
}
mainPkg = testmainPkg
}
var out bytes.Buffer
interp.CapturedOutput = &out
hint = fmt.Sprintf("To trace execution, run:\n%% go build golang.org/x/tools/cmd/ssadump && ./ssadump -build=C -run --interp=T %s\n", input)
exitCode := interp.Interpret(mainPkg, 0, &types.StdSizes{8, 8}, inputs[0], []string{})
// The definition of success varies with each file.
if err := success(exitCode, out.String()); err != nil {
t.Errorf("interp.Interpret(%s) failed: %s", inputs, err)
return false
}
hint = "" // call off the hounds
if false {
fmt.Println(input, time.Since(start)) // test profiling
}
return true
}
示例13: Run
// Run runs program analysis and computes the resulting markup,
// populating *result in a thread-safe manner, first with type
// information then later with pointer analysis information if
// enabled by the pta flag.
//
func Run(pta bool, result *Result) {
conf := loader.Config{
AllowErrors: true,
}
// Silence the default error handler.
// Don't print all errors; we'll report just
// one per errant package later.
conf.TypeChecker.Error = func(e error) {}
var roots, args []string // roots[i] ends with os.PathSeparator
// Enumerate packages in $GOROOT.
root := filepath.Join(runtime.GOROOT(), "src") + string(os.PathSeparator)
roots = append(roots, root)
args = allPackages(root)
log.Printf("GOROOT=%s: %s\n", root, args)
// Enumerate packages in $GOPATH.
for i, dir := range filepath.SplitList(build.Default.GOPATH) {
root := filepath.Join(dir, "src") + string(os.PathSeparator)
roots = append(roots, root)
pkgs := allPackages(root)
log.Printf("GOPATH[%d]=%s: %s\n", i, root, pkgs)
args = append(args, pkgs...)
}
// Uncomment to make startup quicker during debugging.
//args = []string{"golang.org/x/tools/cmd/godoc"}
//args = []string{"fmt"}
if _, err := conf.FromArgs(args, true); err != nil {
// TODO(adonovan): degrade gracefully, not fail totally.
// (The crippling case is a parse error in an external test file.)
result.setStatusf("Analysis failed: %s.", err) // import error
return
}
result.setStatusf("Loading and type-checking packages...")
iprog, err := conf.Load()
if iprog != nil {
// Report only the first error of each package.
for _, info := range iprog.AllPackages {
for _, err := range info.Errors {
fmt.Fprintln(os.Stderr, err)
break
}
}
log.Printf("Loaded %d packages.", len(iprog.AllPackages))
}
if err != nil {
result.setStatusf("Loading failed: %s.\n", err)
return
}
// Create SSA-form program representation.
// Only the transitively error-free packages are used.
prog := ssautil.CreateProgram(iprog, ssa.GlobalDebug)
// Compute the set of main packages, including testmain.
allPackages := prog.AllPackages()
var mainPkgs []*ssa.Package
if testmain := prog.CreateTestMainPackage(allPackages...); testmain != nil {
mainPkgs = append(mainPkgs, testmain)
if p := testmain.Const("packages"); p != nil {
log.Printf("Tested packages: %v", exact.StringVal(p.Value.Value))
}
}
for _, pkg := range allPackages {
if pkg.Pkg.Name() == "main" && pkg.Func("main") != nil {
mainPkgs = append(mainPkgs, pkg)
}
}
log.Print("Transitively error-free main packages: ", mainPkgs)
// Build SSA code for bodies of all functions in the whole program.
result.setStatusf("Constructing SSA form...")
prog.Build()
log.Print("SSA construction complete")
a := analysis{
result: result,
prog: prog,
pcgs: make(map[*ssa.Package]*packageCallGraph),
}
// Build a mapping from openable filenames to godoc file URLs,
// i.e. "/src/" plus path relative to GOROOT/src or GOPATH[i]/src.
a.path2url = make(map[string]string)
for _, info := range iprog.AllPackages {
nextfile:
for _, f := range info.Files {
if f.Pos() == 0 {
continue // e.g. files generated by cgo
}
//.........這裏部分代碼省略.........
示例14: TestFromArgs
// TestFromArgs checks that conf.FromArgs populates conf correctly.
// It does no I/O.
func TestFromArgs(t *testing.T) {
type result struct {
Err string
Rest []string
ImportPkgs map[string]bool
CreatePkgs []loader.PkgSpec
}
for _, test := range []struct {
args []string
tests bool
want result
}{
// Mix of existing and non-existent packages.
{
args: []string{"nosuchpkg", "errors"},
want: result{
ImportPkgs: map[string]bool{"errors": false, "nosuchpkg": false},
},
},
// Same, with -test flag.
{
args: []string{"nosuchpkg", "errors"},
tests: true,
want: result{
ImportPkgs: map[string]bool{"errors": true, "nosuchpkg": true},
},
},
// Surplus arguments.
{
args: []string{"fmt", "errors", "--", "surplus"},
want: result{
Rest: []string{"surplus"},
ImportPkgs: map[string]bool{"errors": false, "fmt": false},
},
},
// Ad hoc package specified as *.go files.
{
args: []string{"foo.go", "bar.go"},
want: result{CreatePkgs: []loader.PkgSpec{{
Filenames: []string{"foo.go", "bar.go"},
}}},
},
// Mixture of *.go and import paths.
{
args: []string{"foo.go", "fmt"},
want: result{
Err: "named files must be .go files: fmt",
},
},
} {
var conf loader.Config
rest, err := conf.FromArgs(test.args, test.tests)
got := result{
Rest: rest,
ImportPkgs: conf.ImportPkgs,
CreatePkgs: conf.CreatePkgs,
}
if err != nil {
got.Err = err.Error()
}
if !reflect.DeepEqual(got, test.want) {
t.Errorf("FromArgs(%q) = %+v, want %+v", test.args, got, test.want)
}
}
}
示例15: doTestable
//.........這裏部分代碼省略.........
// Profiling support.
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
return err
}
err = pprof.StartCPUProfile(f)
if err != nil {
return err
}
defer pprof.StopCPUProfile()
}
// TODO Eventually this might be better as an environment variable
//if !(*runFlag) {
if *tgoroot == "" {
if conf.Build.GOPATH == "" {
return fmt.Errorf("GOPATH must be set")
}
conf.Build.GOROOT = strings.Split(conf.Build.GOPATH, ":")[0] + "/src/github.com/tardisgo/tardisgo/goroot/haxe/go1.4"
} else {
conf.Build.GOROOT = *tgoroot
}
//}
//fmt.Println("DEBUG GOPATH", conf.Build.GOPATH)
//fmt.Println("DEBUG GOROOT", conf.Build.GOROOT)
if *testFlag {
conf.ImportWithTests(args[0]) // assumes you give the full cannonical name of the package to test
args = args[1:]
}
// Use the initial packages from the command line.
_, err := conf.FromArgs(args, *testFlag)
if err != nil {
return err
}
// The interpreter needs the runtime package.
//if *runFlag {
conf.Import("runtime")
//} else {
// TARDIS GO additional line to add the language specific go runtime code
conf.Import(pogo.LanguageList[pogo.TargetLang].Goruntime) // TODO add code to set pogo.TargetLang when more than one of them
//}
// Load, parse and type-check the whole program, including the type definitions.
iprog, err := conf.Load()
if err != nil {
return err
}
// Create and build SSA-form program representation.
*modeFlag |= mode | ssa.SanityCheckFunctions
prog := ssautil.CreateProgram(iprog, *modeFlag)
prog.BuildAll()
// Run the interpreter.
if *runFlag {
var main *ssa.Package
pkgs := prog.AllPackages()
if *testFlag {
// If -test, run all packages' tests.
if len(pkgs) > 0 {
main = prog.CreateTestMainPackage(pkgs...)