本文整理汇总了Golang中go/ast.Print函数的典型用法代码示例。如果您正苦于以下问题:Golang Print函数的具体用法?Golang Print怎么用?Golang Print使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Print函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: printIncReturnsVerbose
func printIncReturnsVerbose(fset *token.FileSet, v map[*ast.ReturnStmt]*ast.FuncType) {
for ret, ftyp := range v {
fmt.Print("FUNC TYPE: ")
ast.Print(fset, ftyp)
fmt.Print(" RETURN: ")
ast.Print(fset, ret)
fmt.Println()
}
}
开发者ID:DuoSoftware,项目名称:v6engine-deps,代码行数:9,代码来源:fix.go
示例2: main
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "parsing.go", nil, 0)
if err != nil {
log.Fatalf("failed parsing file: %s", err)
}
ast.Print(fset, f)
expr, err := parser.ParseExpr(`foo.Bar(1, "argument", something())`)
if err != nil {
log.Fatal("failed parsing expression: %s", err)
}
ast.Print(nil, expr)
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:14,代码来源:parsing.go
示例3: Visit
func (v *GoAstVisitor) Visit(node ast.Node) (w ast.Visitor) {
if node != nil {
fmt.Println(reflect.TypeOf(node))
if typeSpec, ok := node.(*ast.TypeSpec); ok {
ast.Print(fset, typeSpec)
v.TypeName = typeSpec.Name.Name
}
if funcSpec, ok := node.(*ast.FuncDecl); ok {
ast.Print(fset, funcSpec.Recv)
ast.Print(fset, funcSpec.Type)
v.Funcs = append(v.Funcs, funcSpec)
// funcSpec.Type.Params.List[0].Names[0].Name
}
}
return v
}
开发者ID:xinhuang327,项目名称:gobridge,代码行数:16,代码来源:gobridge.go
示例4: main
func main() {
fileSet := token.NewFileSet()
astFile, err := parser.ParseFile(fileSet, "minimal.go", nil, parser.ParseComments)
if err != nil {
panic(err)
}
ast.Print(fileSet, astFile)
return
astFile.Decls = append(astFile.Decls[:0], append([]ast.Decl{&ast.FuncDecl{
Name: ast.NewIdent("MyNewFunc"),
Type: &ast.FuncType{
Func: 15,
Params: &ast.FieldList{
Opening: 29,
Closing: 30,
},
},
}}, astFile.Decls[0:]...)...)
offset := astFile.Decls[0].End() - astFile.Decls[0].Pos()
intoffset := int(offset)
fmt.Println("offset", offset)
astFile.Comments[0].List[0].Slash += offset
// astFile.Comments[0].List[0].Slash = 18
astFile.Decls[1].(*ast.GenDecl).TokPos += offset
astFile.Decls[1].(*ast.GenDecl).Lparen += offset
astFile.Decls[1].(*ast.GenDecl).Rparen += offset
fileSetFile := fileSet.File(1)
newFileSet := token.NewFileSet()
newFileSetFile := newFileSet.AddFile("whatever", 1, fileSetFile.Size()+int(offset))
newFileSetFile.SetLines([]int{
0,
13,
14,
15,
15 + intoffset,
20 + intoffset,
21 + intoffset,
32 + intoffset,
33 + intoffset,
}) // hardcoded for now
fmt.Println("astFile:")
spew.Dump(astFile)
fmt.Println()
fmt.Println()
fmt.Println("fileSet:")
spew.Dump(fileSet)
buf := new(bytes.Buffer)
err = printer.Fprint(buf, newFileSet, astFile)
if err != nil {
panic(err)
}
fmt.Println(buf)
}
开发者ID:petergtz,项目名称:goextract,代码行数:60,代码来源:exploring.go
示例5: NewTypeExpr
func NewTypeExpr(pkgName, importPath string, imports map[string]string, expr ast.Expr) (string, TypeExpr) {
switch t := expr.(type) {
case *ast.Ident:
if IsBultinType(t.Name) {
pkgName = ""
importPath = ""
}
return importPath, TypeExpr{t.Name, pkgName, 0, true}
case *ast.SelectorExpr:
_, e := NewTypeExpr(pkgName, importPath, imports, t.X)
return imports[e.Expr], TypeExpr{t.Sel.Name, e.Expr, e.PkgIdx, e.Valid}
case *ast.StarExpr:
i, e := NewTypeExpr(pkgName, importPath, imports, t.X)
return i, TypeExpr{"*" + e.Expr, e.PkgName, e.PkgIdx + 1, e.Valid}
case *ast.ArrayType:
i, e := NewTypeExpr(pkgName, importPath, imports, t.Elt)
return i, TypeExpr{"[]" + e.Expr, e.PkgName, e.PkgIdx + 2, e.Valid}
case *ast.Ellipsis:
i, e := NewTypeExpr(pkgName, importPath, imports, t.Elt)
return i, TypeExpr{"[]" + e.Expr, e.PkgName, e.PkgIdx + 3, e.Valid}
default:
log.Println("Failed to generate name for field.")
ast.Print(nil, expr)
}
return "", TypeExpr{Valid: false}
}
开发者ID:Joinhack,项目名称:peony,代码行数:26,代码来源:gowalker.go
示例6: TestCheck
func TestCheck(t *testing.T) {
// src is the input for which we want to print the AST.
src := `
package main
// T comment
type T struct {
// S1 comment
S1 string
// S2 comment
S2 string
// S3 comment
S3 string
}
// E is a type E
type E int
const (
E1 E = 1
E2 E = 2
)
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "", src, parser.ParseComments)
if err != nil {
panic(err)
}
ast.Print(fset, f)
}
开发者ID:h12w,项目名称:xsd,代码行数:34,代码来源:xsd_test.go
示例7: NewTypeExpr
// This returns the syntactic expression for referencing this type in Go.
func NewTypeExpr(pkgName string, expr ast.Expr) TypeExpr {
switch t := expr.(type) {
case *ast.Ident:
if IsBuiltinType(t.Name) {
pkgName = ""
}
return TypeExpr{t.Name, pkgName, 0}
case *ast.SelectorExpr:
e := NewTypeExpr(pkgName, t.X)
return TypeExpr{t.Sel.Name, e.Expr, 0}
case *ast.StarExpr:
e := NewTypeExpr(pkgName, t.X)
return TypeExpr{"*" + e.Expr, e.PkgName, e.pkgIndex + 1}
case *ast.ArrayType:
e := NewTypeExpr(pkgName, t.Elt)
return TypeExpr{"[]" + e.Expr, e.PkgName, e.pkgIndex + 2}
case *ast.Ellipsis:
e := NewTypeExpr(pkgName, t.Elt)
return TypeExpr{"[]" + e.Expr, e.PkgName, e.pkgIndex + 2}
default:
log.Println("Failed to generate name for field.")
ast.Print(nil, expr)
}
return TypeExpr{}
}
开发者ID:hardPass,项目名称:revel,代码行数:26,代码来源:reflect.go
示例8: main
func main() {
var err error
var p *ast.Object
var pp []*ast.Object = make([]*ast.Object, 0)
for _, s := range packages {
p, err = types.GcImport(imports, s)
if err != nil {
panic(err)
}
pp = append(pp, p)
}
fset := token.NewFileSet()
for i, pkg := range pp {
Printf("\n")
Printf("%s: \n", packages[i])
Printf("\n")
Printf("pkg=%#v\n", pkg)
Printf("\n")
Printf("pkg.Data=%#v\n", pkg.Data)
Printf("\n")
ast.Print(fset, pkg)
Printf("\n")
Printf("\n")
}
}
开发者ID:strickyak,项目名称:goterp,代码行数:28,代码来源:demo-types-1.go
示例9: Transform
func Transform(src *ast.File) *ast.File {
// find the golex import...
var toplevel ToplevelVisitor
for _, spec := range src.Imports {
ast.Print(nil, spec)
if conv, err := strconv.Unquote(spec.Path.Value); err != nil || conv != "golex" {
continue
}
if spec.Name != nil {
toplevel.golexPackage = spec.Name.Name
} else {
toplevel.golexPackage = "golex"
}
break
}
if toplevel.golexPackage == "" {
log.Print("Not a lex input")
return src
}
ast.Walk(&toplevel, src)
// Now, find switch statemnts...
return src
}
开发者ID:glenker,项目名称:go-lex,代码行数:26,代码来源:lex.go
示例10: dumpAst
func dumpAst(files ...string) {
for _, arg := range files {
// Ensure file exists and not a directory
st, e := os.Stat(arg)
if e != nil {
fmt.Fprintf(os.Stderr, "Skipping: %s - %s\n", arg, e)
continue
}
if st.IsDir() {
fmt.Fprintf(os.Stderr, "Skipping: %s - directory\n", arg)
continue
}
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, arg, nil, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to parse file %s\n", err)
continue
}
// Print the AST.
ast.Print(fset, f)
}
}
开发者ID:vmware,项目名称:vic,代码行数:25,代码来源:tools.go
示例11: main
func main() {
flag.Parse()
if len(flag.Args()) != 1 {
log.Fatal("Usage: go run goprint.go path")
}
bpkg, err := build.Default.Import(flag.Args()[0], ".", 0)
if err != nil {
log.Fatal(err)
}
fset := token.NewFileSet()
files := make(map[string]*ast.File)
for _, fname := range bpkg.GoFiles {
p, err := ioutil.ReadFile(filepath.Join(bpkg.SrcRoot, bpkg.ImportPath, fname))
if err != nil {
log.Fatal(err)
}
file, err := parser.ParseFile(fset, fname, p, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
files[fname] = file
}
c := spew.NewDefaultConfig()
c.DisableMethods = true
apkg, _ := ast.NewPackage(fset, files, importer, nil)
c.Dump(apkg)
ast.Print(fset, apkg)
dpkg := doc.New(apkg, bpkg.ImportPath, 0)
c.Dump(dpkg)
}
开发者ID:maddyonline,项目名称:gddo,代码行数:30,代码来源:goprint.go
示例12: main
func main() {
// src is the input for which we want to print the AST.
src := `
package main
func anon(a int, b int) {
}
func named(a: int, b: int) {
}
func main() {
named(a: 3 + 2, b: 5)
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "", src, 0)
if err != nil {
panic(err)
}
// Print the AST.
ast.Print(fset, f)
fmt.Printf("%s\n", parser.RenderFile(f, fset))
}
开发者ID:elliotchance,项目名称:go-named-params,代码行数:28,代码来源:main.go
示例13: main
func main() {
if len(os.Args) > 1 {
args(os.Args[1])
return
}
r := bufio.NewReader(os.Stdin)
for {
fmt.Print(">> ")
line, _, _ := r.ReadLine()
p := parser.ParseFromString("<REPL>", string(line)+"\n")
fmt.Println(p)
// a := generator.GenerateAST(p)
a := generator.EvalExprs(p)
fset := token.NewFileSet()
ast.Print(fset, a)
var buf bytes.Buffer
printer.Fprint(&buf, fset, a)
fmt.Printf("%s\n", buf.String())
}
}
开发者ID:8l,项目名称:gsp,代码行数:25,代码来源:gsp.go
示例14: ProcessFunc
func ProcessFunc(cur *Cursor, node *ast.FuncDecl) Candidates {
ast.Print(cur.FSet, GetOutNode(cur.Node, cur.Offset))
if cur.LeftWords != nil && len(cur.LeftWords) > 0 {
cands := Candidates{}
lastw := strings.ToLower(cur.GetLastWord())
pkg := cur.Asist.GetPackage(cur.PackagePath)
if lastw == "func" && cur.LastLetter == ' ' { //begin of func
file := pkg.GetFile(cur.File.GetPath())
if file == nil {
return nil
}
for _, t := range file.Types {
fmt.Println(t.Name, t.Type)
tmp := "(" + strings.ToLower(string(t.Name[0])) + " " + t.Name + ")"
cand := Candidate{Name: tmp}
if t.Type == "struct" {
cand.Perc = 50
}
cands = append(cands, cand)
}
return cands
}
}
return nil
}
开发者ID:YouROK,项目名称:GoProjectManager,代码行数:27,代码来源:process.go
示例15: Compile
// compiles source consisting of a number of statements. E.g.:
// src = "a = 1; b = sin(x)"
// code, err := world.Compile(src)
// code.Eval()
func (w *World) Compile(src string) (code *BlockStmt, e error) {
// parse
exprSrc := "func(){\n" + src + "\n}" // wrap in func to turn into expression
tree, err := parser.ParseExpr(exprSrc)
if err != nil {
return nil, fmt.Errorf("script line %v: ", err)
}
// catch compile errors and decode line number
if !Debug {
defer func() {
err := recover()
if err == nil {
return
}
if compErr, ok := err.(*compileErr); ok {
code = nil
e = fmt.Errorf("script %v: %v", pos2line(compErr.pos, exprSrc), compErr.msg)
} else {
panic(err)
}
}()
}
// compile
stmts := tree.(*ast.FuncLit).Body.List // strip func again
if Debug {
ast.Print(nil, stmts)
}
block := new(BlockStmt)
for _, s := range stmts {
block.append(w.compile(s), s)
}
return block, nil
}
开发者ID:callistoaz,项目名称:3,代码行数:39,代码来源:compile.go
示例16: CompileExpr
// Compiles an expression, which can then be evaluated. E.g.:
// expr, err := world.CompileExpr("1+1")
// expr.Eval() // returns 2
func (w *World) CompileExpr(src string) (code Expr, e error) {
// parse
tree, err := parser.ParseExpr(src)
if err != nil {
return nil, fmt.Errorf(`parse "%s": %v`, src, err)
}
if Debug {
ast.Print(nil, tree)
}
// catch compile errors
if !Debug {
defer func() {
err := recover()
if err == nil {
return
}
if er, ok := err.(*compileErr); ok {
code = nil
e = fmt.Errorf(`parse "%s": %v`, src, er)
} else {
panic(err)
}
}()
}
return w.compile(tree), nil
}
开发者ID:callistoaz,项目名称:3,代码行数:30,代码来源:compile.go
示例17: main
func main() {
// src is the input for which we want to print the AST.
src := `
package main
func hello(a, b Any, rest ...Any) Any {
return a
}
func main() {
f := 10
f.(func(int)Any)
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "", src, 0)
if err != nil {
panic(err)
}
// (f.Decls[0].(*ast.GenDecl)).Specs[0].Name.Obj = nil
// ((f.Decls[0].(*ast.GenDecl)).Specs[0].(*ast.TypeSpec).Name.Obj) = nil
// f.Imports = nil
ast.Print(fset, f)
// Print the AST.
var buf bytes.Buffer
printer.Fprint(&buf, fset, f)
fmt.Println(buf.String())
}
开发者ID:Immortalin,项目名称:gisp,代码行数:33,代码来源:ast_print.go
示例18: AstCommand
// AstCommand implements the debugger command: ast
//
// ast
//
// Prints AST for current function.
func AstCommand(args []string) {
var syntax ast.Node
var err error
fr := gub.CurFrame()
fn := fr.Fn()
if len(args) > 1 {
name := args[1]
fn, err = gub.FuncLookup(name)
if err != nil {
gub.Errmsg(err.Error())
return
} else if fn == nil {
gub.Errmsg("function '%s' not found", name)
return
} else {
syntax = fn.Syntax()
}
} else {
syntax = fn.Syntax()
switch s := (*gub.Instr).(type) {
case *ssa2.Trace:
syntax = s.Syntax()
}
}
if syntax != nil {
ast.Print(fn.Prog.Fset, syntax)
fmt.Println("")
} else {
gub.Msg("Sorry, we don't have an AST for this")
}
}
开发者ID:rocky,项目名称:ssa-interp,代码行数:36,代码来源:ast.go
示例19: ScanControllers
// Parse the app directory and return a list of the controller types found.
// Returns a CompileError if the parsing fails.
func ScanControllers(path string) (specs []*ControllerSpec, compileError *rev.Error) {
// Parse files within the path.
var pkgs map[string]*ast.Package
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, path, func(f os.FileInfo) bool {
return !f.IsDir() && !strings.HasPrefix(f.Name(), ".")
}, 0)
if err != nil {
if errList, ok := err.(scanner.ErrorList); ok {
var pos token.Position = errList[0].Pos
return nil, &rev.Error{
SourceType: ".go source",
Title: "Go Compilation Error",
Path: pos.Filename,
Description: errList[0].Msg,
Line: pos.Line,
Column: pos.Column,
SourceLines: rev.MustReadLines(pos.Filename),
}
}
ast.Print(nil, err)
log.Fatalf("Failed to parse dir: %s", err)
}
// For each package... (often only "controllers")
for _, pkg := range pkgs {
var structSpecs []*ControllerSpec
methodSpecs := make(methodMap)
// For each source file in the package...
for _, file := range pkg.Files {
// Imports maps the package key to the full import path.
// e.g. import "sample/app/models" => "models": "sample/app/models"
imports := map[string]string{}
// For each declaration in the source file...
for _, decl := range file.Decls {
// Match and add both structs and methods
addImports(imports, decl)
structSpecs = appendStruct(structSpecs, pkg, decl)
appendMethod(fset, methodSpecs, decl, pkg.Name, imports)
}
}
// Filter the struct specs to just the ones that embed rev.Controller.
structSpecs = filterControllers(structSpecs)
// Add the method specs to them.
for _, spec := range structSpecs {
spec.MethodSpecs = methodSpecs[spec.StructName]
}
// Add the prepared ControllerSpecs to the list.
specs = append(specs, structSpecs...)
}
return
}
开发者ID:aresLove,项目名称:revel,代码行数:61,代码来源:reflect.go
示例20: main
func main() {
fileSet := token.NewFileSet()
astFile, err := parser.ParseFile(fileSet, os.Args[1], nil, 0)
if err != nil {
panic(err)
}
ast.Print(fileSet, astFile)
}
开发者ID:petergtz,项目名称:goextract,代码行数:8,代码来源:print_ast.go
注:本文中的go/ast.Print函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论