• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ast.Walk函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中go/ast.Walk函数的典型用法代码示例。如果您正苦于以下问题:Golang Walk函数的具体用法?Golang Walk怎么用?Golang Walk使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Walk函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Visit

func (v *visitor) Visit(node ast.Node) ast.Visitor {
	switch node := node.(type) {
	case *ast.Ident:
		v.use(v.pkg.Info.Uses[node])

	case *ast.ValueSpec:
		if !v.insideFunc {
			for _, ident := range node.Names {
				if !isReserved(ident.Name) {
					v.decl(v.pkg.Info.Defs[ident])
				}
			}
		}
		for _, val := range node.Values {
			ast.Walk(v, val)
		}
		return nil

	case *ast.FuncDecl:
		if node.Body != nil {
			v.insideFunc = true
			ast.Walk(v, node.Body)
			v.insideFunc = false
		}

		return nil
	}

	return v
}
开发者ID:sha1sum,项目名称:check,代码行数:30,代码来源:varcheck.go


示例2: Check

func (this *astEquals) Check(params []interface{}, names []string) (bool, string) {
	var obtainedNodes, expectedNodes chan *NodeWithBreadcrumbs
	var obtainedNode, expectedNode *NodeWithBreadcrumbs

	obtainedNodes = make(chan *NodeWithBreadcrumbs)
	expectedNodes = make(chan *NodeWithBreadcrumbs)

	go ast.Walk(&AstChannelWalker{Out: obtainedNodes}, params[0].(ast.Node))
	go ast.Walk(&AstChannelWalker{Out: expectedNodes}, params[1].(ast.Node))

	for {
		obtainedNode = <-obtainedNodes
		expectedNode = <-expectedNodes

		if obtainedNode == nil && expectedNode == nil {
			break
		}

		if obtainedNode == nil || expectedNode == nil {
			return false, fmt.Sprintf("\n%+v\ndid not match\n%+v", obtainedNode, expectedNode)
		}

		if !this.nodeEquals(obtainedNode.Node, expectedNode.Node) {
			return false, fmt.Sprintf("\n%+v\ndid not match\n%+v", obtainedNode, expectedNode)
		}
	}

	return true, ""
}
开发者ID:pjvds,项目名称:json2go,代码行数:29,代码来源:json2ast_test.go


示例3: visitSpec

func (x *Indexer) visitSpec(kind SpotKind, spec ast.Spec) {
	switch n := spec.(type) {
	case *ast.ImportSpec:
		x.visitIdent(ImportDecl, n.Name)
		if n.Path != nil {
			if imp, err := strconv.Unquote(n.Path.Value); err == nil {
				x.importCount[x.intern(imp)]++
			}
		}

	case *ast.AliasSpec:
		x.visitIdent(kind, n.Name)
		ast.Walk(x, n.Orig)

	case *ast.ValueSpec:
		for _, n := range n.Names {
			x.visitIdent(kind, n)
		}
		ast.Walk(x, n.Type)
		for _, v := range n.Values {
			ast.Walk(x, v)
		}

	case *ast.TypeSpec:
		x.visitIdent(TypeDecl, n.Name)
		ast.Walk(x, n.Type)
	}
}
开发者ID:syreclabs,项目名称:go-tools,代码行数:28,代码来源:index18.go


示例4: Visit

// Visits files for used nodes.
func (p *Package) Visit(node ast.Node) ast.Visitor {
	u := usedWalker(*p) // hopefully p fields are references.
	switch n := node.(type) {
	// don't walk whole file, but only:
	case *ast.ValueSpec:
		// - variable initializers
		for _, value := range n.Values {
			ast.Walk(&u, value)
		}
		// variable types.
		if n.Type != nil {
			ast.Walk(&u, n.Type)
		}
	case *ast.BlockStmt:
		// - function bodies
		for _, stmt := range n.List {
			ast.Walk(&u, stmt)
		}
	case *ast.FuncDecl:
		// - function signatures
		ast.Walk(&u, n.Type)
	case *ast.TypeSpec:
		// - type declarations
		ast.Walk(&u, n.Type)
	}
	return p
}
开发者ID:reillywatson,项目名称:go-misc,代码行数:28,代码来源:deadcode.go


示例5: rewriteOptionalMethods

// rewriteOptionalMethods makes specific mutations to marshaller methods that belong to types identified
// as being "optional" (they may be nil on the wire). This allows protobuf to serialize a map or slice and
// properly discriminate between empty and nil (which is not possible in protobuf).
// TODO: move into upstream gogo-protobuf once https://github.com/gogo/protobuf/issues/181
//   has agreement
func rewriteOptionalMethods(decl ast.Decl, isOptional OptionalFunc) {
	switch t := decl.(type) {
	case *ast.FuncDecl:
		ident, ptr, ok := receiver(t)
		if !ok {
			return
		}

		// correct initialization of the form `m.Field = &OptionalType{}` to
		// `m.Field = OptionalType{}`
		if t.Name.Name == "Unmarshal" {
			ast.Walk(optionalAssignmentVisitor{fn: isOptional}, t.Body)
		}

		if !isOptional(ident.Name) {
			return
		}

		switch t.Name.Name {
		case "Unmarshal":
			ast.Walk(&optionalItemsVisitor{}, t.Body)
		case "MarshalTo", "Size", "String":
			ast.Walk(&optionalItemsVisitor{}, t.Body)
			fallthrough
		case "Marshal":
			// if the method has a pointer receiver, set it back to a normal receiver
			if ptr {
				t.Recv.List[0].Type = ident
			}
		}
	}
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:37,代码来源:parser.go


示例6: visitSpec

func (x *Indexer) visitSpec(spec ast.Spec, isVarDecl bool) {
	switch n := spec.(type) {
	case *ast.ImportSpec:
		x.visitComment(n.Doc)
		x.visitIdent(ImportDecl, n.Name)
		ast.Walk(x, n.Path)
		x.visitComment(n.Comment)

	case *ast.ValueSpec:
		x.visitComment(n.Doc)
		kind := ConstDecl
		if isVarDecl {
			kind = VarDecl
		}
		for _, n := range n.Names {
			x.visitIdent(kind, n)
		}
		ast.Walk(x, n.Type)
		for _, v := range n.Values {
			ast.Walk(x, v)
		}
		x.visitComment(n.Comment)

	case *ast.TypeSpec:
		x.visitComment(n.Doc)
		x.visitIdent(TypeDecl, n.Name)
		ast.Walk(x, n.Type)
		x.visitComment(n.Comment)
	}
}
开发者ID:go-nosql,项目名称:golang,代码行数:30,代码来源:index.go


示例7: Visit

// Visits files for used nodes.
func (p *Package) Visit(node ast.Node) ast.Visitor {
	u := usedWalker(*p) // hopefully p fields are references.
	switch n := node.(type) {
	// don't walk whole file, but only:
	case *ast.ValueSpec:
		// - variable initializers
		for _, value := range n.Values {
			ast.Walk(&u, value)
		}
		// variable types.
		if n.Type != nil {
			ast.Walk(&u, n.Type)
		}
	case *ast.BlockStmt:
		// - function bodies
		for _, stmt := range n.List {
			ast.Walk(&u, stmt)
		}
	case *ast.FuncDecl:
		// - function signatures
		if *includeTests {
			// Test* functions are always used
			if strings.HasPrefix(n.Name.String(), "Test") {
				u.used[n.Name.String()] = true
			}
		}
		ast.Walk(&u, n.Type)
	case *ast.TypeSpec:
		// - type declarations
		ast.Walk(&u, n.Type)
	}
	return p
}
开发者ID:robmurtha,项目名称:go-misc,代码行数:34,代码来源:deadcode.go


示例8: instrument

func instrument(pkg, shortName, fullName string, fset *token.FileSet, parsedFile *ast.File, info *types.Info, out io.Writer, lits map[Literal]struct{}, blocks *[]CoverBlock, sonar *[]CoverBlock) {
	file := &File{
		fset:      fset,
		pkg:       pkg,
		shortName: shortName,
		fullName:  fullName,
		astFile:   parsedFile,
		blocks:    blocks,
		info:      info,
	}
	file.addImport("github.com/dvyukov/go-fuzz/go-fuzz-dep", fuzzdepPkg, "Main")

	if lits != nil {
		ast.Walk(&LiteralCollector{lits}, file.astFile)
	}

	ast.Walk(file, file.astFile)

	if sonar != nil {
		s := &Sonar{
			fset:      fset,
			shortName: shortName,
			fullName:  fullName,
			pkg:       pkg,
			blocks:    sonar,
			info:      info,
		}
		ast.Walk(s, file.astFile)
	}

	file.print(out)
}
开发者ID:h8liu,项目名称:go-fuzz,代码行数:32,代码来源:cover.go


示例9: restoreIdentMapping

func restoreIdentMapping(oldFile, newFile *ast.File, identMap st.IdentifierMap) {
	comm := make(chan *ast.Ident)
	source := &restoreIMSourceVisitor{comm}
	dest := &restoreIMDestVisitor{identMap, comm}
	go ast.Walk(source, oldFile)
	ast.Walk(dest, newFile)
}
开发者ID:vpavkin,项目名称:GoRefactor,代码行数:7,代码来源:reparseFile.go


示例10: main

func main() {
	goopt.Parse(func() []string { return nil })
	if len(goopt.Args) > 0 {
		x, err := parser.ParseFiles(myfiles, goopt.Args, 0)
		die(err)
		fmt.Fprintln(os.Stderr, "Parsed: ", *x["main"])
		die(typechecker.CheckPackage(myfiles, x["main"], nil))
		fmt.Fprintln(os.Stderr, "Checked: ", *x["main"])
		//for _,a := range x["main"].Files {
		//	die(printer.Fprint(os.Stdout, a))
		//}

		aaa := x86.StartData
		var bbb *Stack
		var cv = CompileVisitor{&aaa, make(map[string]string), bbb.New("global")}
		ast.Walk(StringVisitor(cv), x["main"])

		cv.Append(x86.StartText...)
		ast.Walk(&cv, x["main"])

		// Here we just add a crude debug library
		cv.Append(x86.Debugging...)
		ass := x86.Assembly(*cv.assembly)
		//fmt.Println(ass)
		die(elf.AssembleAndLink(goopt.Args[0][:len(goopt.Args[0])-3], []byte(ass)))
	}
}
开发者ID:droundy,项目名称:go-compiler,代码行数:27,代码来源:go.go


示例11: trans

func trans(pks map[string]*ast.Package) {
	ts := Trans{}
	for _, pk := range pks {
		ast.Walk(normalizer{}, pk)
		ast.Walk(ts, pk)
	}
	fmt.Println("main();")
}
开发者ID:drhodes,项目名称:gotojs,代码行数:8,代码来源:main.go


示例12: Trim

// Trim trims the AST rooted at node based on the coverage profile,
// removing irrelevant and unreached parts of the program.
// If the node is an *ast.File, comments are updated as well using
// an ast.CommentMap.
func (p *Profile) Trim(node ast.Node) {
	if f, ok := node.(*ast.File); ok {
		cmap := ast.NewCommentMap(p.Fset, f, f.Comments)
		ast.Walk(&trimVisitor{p}, f)
		f.Comments = cmap.Filter(f).Comments()
	} else {
		ast.Walk(&trimVisitor{p}, node)
	}
}
开发者ID:roger2000hk,项目名称:discover,代码行数:13,代码来源:trim.go


示例13: Visit

func (vis *pointerCandidatesVisitor) Visit(node ast.Node) ast.Visitor {
	switch t := node.(type) {
	case *ast.AssignStmt:
		for _, expr := range t.Rhs {
			ast.Walk(vis, expr)
		}
		if t.Tok == token.DEFINE {
			return nil
		}
		for _, ee := range t.Lhs {
			depth := 1
			stop := false
			for !stop {
				fmt.Printf("%T\n", ee)
				switch e := ee.(type) {
				case *ast.Ident:
					s := vis.identMap.GetSymbol(e)
					if vis.params.Contains(s) && depth > 0 {
						if i, ok := vis.result[s]; !ok || i < depth {
							vis.result[s] = depth
						}
					}
					stop = true
				case *ast.StarExpr:
					depth--
					ee = e.X
				case *ast.UnaryExpr:
					if e.Op == token.AND {
						depth++
					}
					ee = e.X
				case *ast.ParenExpr:
					ee = e.X
				case *ast.IndexExpr:
					ast.Walk(vis, e.Index)
					stop = true
				case *ast.SelectorExpr:
					ast.Walk(vis, e.X)
					stop = true
				default:
					stop = true
				}
			}
		}
		return nil
	case *ast.UnaryExpr:
		if t.Op != token.AND {
			return vis
		}
		vis.checkAddrOperators(t)
		return nil
	case *ast.StarExpr:
		vis.checkAddrOperators(t)
		return nil
	}
	return vis
}
开发者ID:vpavkin,项目名称:GoRefactor,代码行数:57,代码来源:extractMethod.go


示例14: compareTwoTrees

func compareTwoTrees(src string) {
	v1 := &channelPusher{}
	v1.fileSet = token.NewFileSet()
	v1.queue = make(chan *ast.Node)

	v2 := &channelPusher{}
	v2.fileSet = token.NewFileSet()
	v2.queue = make(chan *ast.Node)

	tree1, err := parser.ParseExpr(src)
	if err != nil {
		panic(err)
	}

	src2 := "x + 2*y"
	tree2, err := parser.ParseExpr(src2)
	if err != nil {
		panic(err)
	}
	done := make(chan struct{})
	defer close(done)

	go func() {
		ast.Walk(v1, tree1)
		close(v1.queue)
		done <- struct{}{}
	}()
	go func() {
		ast.Walk(v2, tree2)
		close(v2.queue)
		done <- struct{}{}
	}()

	var n1, n2 *ast.Node
	quit := false
	for !quit {
		select {
		case n1 = <-v1.queue:
		case n2 = <-v2.queue:
		case <-done:
			quit = true
		}
		if n1 != nil && n2 != nil {
			if !equalNodes(n1, n2) {
				println("!equalNodes")
				break
			}
			println("equalNodes")
			n1 = nil
			n2 = nil
		}
	}
}
开发者ID:rtfb,项目名称:sketchbook,代码行数:53,代码来源:parz.go


示例15: Visit

func (v *idVisitor) Visit(n ast.Node) (w ast.Visitor) {
	switch node := n.(type) {
	case *ast.Ident, *ast.SelectorExpr:
		id, err := str(node.(ast.Expr))
		if err == nil {
			v.rIDs[id] = n
		}
	case *ast.StarExpr:
		ast.Walk(v, node.X)
		return nil
	case *ast.CallExpr:
		stmt, ok := node.Fun.(*ast.SelectorExpr)
		if ok {
			ast.Walk(v, stmt.X)
		}

		if node.Args == nil {
			return nil
		}

		for _, arg := range node.Args {
			ast.Walk(v, arg)
		}
		return nil
	case *ast.AssignStmt:
		for _, e := range node.Lhs {
			id, err := str(e)
			if err != nil {
				return
			}
			v.wIDs[id] = n
		}

		for _, e := range node.Rhs {
			ast.Walk(v, e)
		}
		return nil
	case *ast.GenDecl:
		for _, s := range node.Specs {
			val, ok := s.(*ast.ValueSpec)
			if !ok {
				continue
			}

			for _, n := range val.Names {
				id, _ := str(n)
				v.wIDs[id] = node
			}
		}
	}
	w = v
	return
}
开发者ID:jyzhe,项目名称:beehive,代码行数:53,代码来源:ast.go


示例16: Visit

func (x *Indexer) Visit(node ast.Node) ast.Visitor {
	switch n := node.(type) {
	case nil:
		// nothing to do

	case *ast.Ident:
		x.visitIdent(Use, n)

	case *ast.FieldList:
		x.visitFieldList(VarDecl, n)

	case *ast.InterfaceType:
		x.visitFieldList(MethodDecl, n.Methods)

	case *ast.DeclStmt:
		// local declarations should only be *ast.GenDecls;
		// ignore incorrect ASTs
		if decl, ok := n.Decl.(*ast.GenDecl); ok {
			x.decl = nil // no snippets for local declarations
			x.visitGenDecl(decl)
		}

	case *ast.GenDecl:
		x.decl = n
		x.visitGenDecl(n)

	case *ast.FuncDecl:
		kind := FuncDecl
		if n.Recv != nil {
			kind = MethodDecl
			ast.Walk(x, n.Recv)
		}
		x.decl = n
		x.visitIdent(kind, n.Name)
		ast.Walk(x, n.Type)
		if n.Body != nil {
			ast.Walk(x, n.Body)
		}

	case *ast.File:
		x.decl = nil
		x.visitIdent(PackageClause, n.Name)
		for _, d := range n.Decls {
			ast.Walk(x, d)
		}

	default:
		return x
	}

	return nil
}
开发者ID:gnanderson,项目名称:go,代码行数:52,代码来源:index.go


示例17: main

func main() {
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "simple.go", nil, 0)
	if err != nil {
		// Whoops!
	}
	ast.Walk(new(FuncVisitor), file)
	printer.Fprint(os.Stdout, fset, file)
	fmt.Println("-------------------------------------")
	ast.Walk(new(ImportVisitor), file)
	printer.Fprint(os.Stdout, fset, file)

	f, _ := os.Create("/tmp/new_simple.go")
	printer.Fprint(f, fset, file)
}
开发者ID:AnuchitPrasertsang,项目名称:golang-ast-example,代码行数:15,代码来源:transformation.go


示例18: scanDir

func (v visitor) scanDir(dirPath string) {
	dir, err := os.Open(dirPath)
	if err != nil {
		logFatal(err)
	}
	defer dir.Close()

	names, err := dir.Readdirnames(-1)
	if err != nil {
		logFatal(err)
	}

	for _, name := range names {
		fullPath := path.Join(dirPath, name)

		fi, err := os.Stat(fullPath)
		if err != nil {
			logFatal(err)
		}

		if fi.IsDir() {
			v.scanDir(fullPath)
		} else if !fi.IsDir() && strings.HasSuffix(fullPath, ".go") {
			astFile, err := parser.ParseFile(v.fileSet, fullPath, nil, 0)
			if err != nil {
				logFatal(err)
			}

			ast.Walk(v, astFile)
		}
	}
}
开发者ID:2105666566,项目名称:polyglot,代码行数:32,代码来源:main.go


示例19: process

// process parses and rewrites a file by generating the appropriate exported
// types for raw types.
func process(path string) error {
	b, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	// Remove code between begin/end pragma comments.
	b = regexp.MustCompile(`(?is)//raw:codegen:begin.+?//raw:codegen:end`).ReplaceAll(b, []byte{})
	b = []byte(strings.TrimRight(string(b), " \n\r"))

	// Re-parse the file without the pragmas.
	f, err := parser.ParseFile(token.NewFileSet(), path, b, 0)
	if err != nil {
		return err
	}

	// Iterate over all the nodes and add exported types where appropriate.
	var g generator
	g.w.Write(b)
	g.w.WriteString("\n\n")

	ast.Walk(&g, f)
	if g.err != nil {
		return g.err
	}

	// Rewrite original file.
	ioutil.WriteFile(path, g.w.Bytes(), 0600)

	log.Println("OK", path)

	return nil
}
开发者ID:jmptrader,项目名称:raw,代码行数:35,代码来源:main.go


示例20: 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



注:本文中的go/ast.Walk函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ast.AssignStmt类代码示例发布时间:2022-05-28
下一篇:
Golang ast.SortImports函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap