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

Golang ast.Inspect函数代码示例

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

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



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

示例1: findRouteTableAST

func findRouteTableAST(file *ast.File) (routeTableAST *ast.CompositeLit) {
	defer func() {
		if err := recover(); err != nil && err != ErrRouteTableASTIsFound {
			panic(err)
		}
	}()
	ast.Inspect(file, func(node ast.Node) bool {
		switch aType := node.(type) {
		case *ast.GenDecl:
			if aType.Tok != token.VAR {
				return false
			}
			ast.Inspect(aType, func(n ast.Node) bool {
				switch typ := n.(type) {
				case *ast.CompositeLit:
					switch t := typ.Type.(type) {
					case *ast.Ident:
						if t.Name == routeTableTypeName {
							routeTableAST = typ
							panic(ErrRouteTableASTIsFound)
						}
					}
				}
				return true
			})
		}
		return true
	})
	return routeTableAST
}
开发者ID:jmcarbo,项目名称:kocha,代码行数:30,代码来源:controller.go


示例2: rewriteConflictingNames

func rewriteConflictingNames(fn *ast.FuncDecl) {
	for _, fieldList := range []*ast.FieldList{fn.Recv, fn.Type.Params, fn.Type.Results} {
		if fieldList == nil {
			continue
		}
		for _, f := range fieldList.List {
			for _, name := range f.Names {
				if name.Name == fn.Name.Name {
					oldName := name.Name
					newName := createConflictFreeNameCheckIdents(name.Name, fn)
					rewriteFn := func(node ast.Node) bool {
						if ident, ok := node.(*ast.Ident); ok && ident.Name == oldName {
							ident.Name = newName
						}
						return true
					}
					// Instead of walking all of fn, walk fn.Recv, fn.Type, and fn.Body.
					// If we walked all of fn we would rewrite the name of the function itself
					// in addition to the parameter we are rewriting.
					if fn.Recv != nil && fn.Recv.List != nil {
						ast.Inspect(fn.Recv, rewriteFn)
					}
					if fn.Type != nil {
						ast.Inspect(fn.Type, rewriteFn)
					}
					if fn.Body != nil {
						ast.Inspect(fn.Body, rewriteFn)
					}
					return // at most one parameter can share a name with the function
				}
			}
		}
	}
}
开发者ID:ricardo-rossi,项目名称:godebug,代码行数:34,代码来源:gen.go


示例3: GetPublicFunctions

// GetPublicFunctions lists all public functions (not methods) from a golang source file.
func GetPublicFunctions(filePath string) ([]string, error) {
	var functionNames []string

	// Create the AST by parsing src.
	fset := token.NewFileSet() // positions are relative to fset
	f, err := parser.ParseFile(fset, filePath, nil, 0)
	if err != nil {
		return nil, fmt.Errorf("failed parse file to list functions: %v", err)
	}

	// Inspect the AST and print all identifiers and literals.
	ast.Inspect(f, func(n ast.Node) bool {
		var s string
		switch x := n.(type) {
		case *ast.FuncDecl:
			s = x.Name.Name
			// It's a function (not method), and is public, record it.
			if x.Recv == nil && isPublic(s) {
				functionNames = append(functionNames, s)
			}
		}
		return true
	})

	return functionNames, nil
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:27,代码来源:codeinspector.go


示例4: Build

// Build constructs a control flow graph,
// filtered to include only interesting nodes.
func Build(fset *token.FileSet, body *ast.BlockStmt, interesting func(ast.Node) bool) *Graph {
	start := &ast.Ident{Name: "_cfg_start_"}
	end := &ast.Ident{Name: "_cfg_end_"}
	b := &builder{
		interesting:  interesting,
		followCache:  make(map[ast.Node][]ast.Node),
		end:          end,
		need:         make(map[ast.Node]bool),
		trimmed:      make(map[ast.Node]bool),
		followed:     make(map[ast.Node]bool),
		brkLabel:     make(map[string][]ast.Node),
		contLabel:    make(map[string][]ast.Node),
		gotoLabel:    make(map[string]ast.Node),
		isGotoTarget: make(map[string]bool),
		stmtLabel:    make(map[ast.Stmt]string),
	}

	ast.Inspect(body, b.scanGoto)
	b.followCache[start] = b.trimList(b.follow(body, []ast.Node{end}))
	return &Graph{
		FileSet: fset,
		Start:   start,
		End:     end,
		Follow:  b.followCache,
	}
}
开发者ID:niltonkummer,项目名称:grind,代码行数:28,代码来源:cfg.go


示例5: getValidationKeys

// Scan app source code for calls to X.Y(), where X is of type *Validation.
//
// Recognize these scenarios:
// - "Y" = "Validation" and is a member of the receiver.
//   (The common case for inline validation)
// - "X" is passed in to the func as a parameter.
//   (For structs implementing Validated)
//
// The line number to which a validation call is attributed is that of the
// surrounding ExprStmt.  This is so that it matches what runtime.Callers()
// reports.
//
// The end result is that we can set the default validation key for each call to
// be the same as the local variable.
func getValidationKeys(fset *token.FileSet, funcDecl *ast.FuncDecl, imports map[string]string) map[int]string {
	var (
		lineKeys = make(map[int]string)

		// Check the func parameters and the receiver's members for the *revel.Validation type.
		validationParam = getValidationParameter(funcDecl, imports)
	)

	ast.Inspect(funcDecl.Body, func(node ast.Node) bool {
		// e.g. c.Validation.Required(arg) or v.Required(arg)
		callExpr, ok := node.(*ast.CallExpr)
		if !ok {
			return true
		}

		// e.g. c.Validation.Required or v.Required
		funcSelector, ok := callExpr.Fun.(*ast.SelectorExpr)
		if !ok {
			return true
		}

		switch x := funcSelector.X.(type) {
		case *ast.SelectorExpr: // e.g. c.Validation
			if x.Sel.Name != "Validation" {
				return true
			}

		case *ast.Ident: // e.g. v
			if validationParam == nil || x.Obj != validationParam {
				return true
			}

		default:
			return true
		}

		if len(callExpr.Args) == 0 {
			return true
		}

		// If the argument is a binary expression, take the first expression.
		// (e.g. c.Validation.Required(myName != ""))
		arg := callExpr.Args[0]
		if binExpr, ok := arg.(*ast.BinaryExpr); ok {
			arg = binExpr.X
		}

		// If it's a literal, skip it.
		if _, ok = arg.(*ast.BasicLit); ok {
			return true
		}

		if typeExpr := NewTypeExpr("", arg); typeExpr.Valid {
			lineKeys[fset.Position(callExpr.End()).Line] = typeExpr.TypeName("")
		}
		return true
	})

	return lineKeys
}
开发者ID:elvin-du,项目名称:revel,代码行数:74,代码来源:reflect.go


示例6: init

func init() {
	act(Action{
		Path: "/imports",
		Doc:  "",
		Func: func(r Request) (data, error) {
			res := ImportsResult{}

			a := ImportsArgs{
				Toggle:    []ImportDeclArg{},
				TabWidth:  8,
				TabIndent: true,
			}

			if err := r.Decode(&a); err != nil {
				return res, err
			}

			fset, af, err := parseAstFile(a.Fn, a.Src, parser.ImportsOnly|parser.ParseComments)
			if err == nil {
				ast.Inspect(af, func(n ast.Node) bool {
					if n != nil {
						tp := fset.Position(n.End())
						if tp.Line > res.LineRef {
							res.LineRef = tp.Line
						}
					}
					return true
				})
				af = imp(fset, af, a.Toggle)
				res.Src, err = printSrc(fset, af, a.TabIndent, a.TabWidth)
			}
			return res, err
		},
	})
}
开发者ID:pyoner,项目名称:GoSublime,代码行数:35,代码来源:ac_imports.go


示例7: StructFuncs

func StructFuncs(f *ast.File) map[string]funcs {

	structFuncs := map[string]funcs{}

	ast.Inspect(f, func(n ast.Node) bool {

		f, ok := n.(*ast.FuncDecl)

		if !ok {
			return true
		}

		recv, ok := findRecv(f.Recv)
		if !ok {
			return true
		}

		fn := funcType{
			Recv:     recv,
			Name:     f.Name.Name,
			Comments: findComments(f.Doc),
		}

		structFuncs[recv] = append(structFuncs[recv], fn)
		return false
	})

	return structFuncs
}
开发者ID:skatsuta,项目名称:argen,代码行数:29,代码来源:parser.go


示例8: extractString

func (sms *ShowMissingStrings) extractString(f *ast.File, fset *token.FileSet, filename string) error {
	ast.Inspect(f, func(n ast.Node) bool {
		switch x := n.(type) {
		case *ast.CallExpr:
			switch x.Fun.(type) {
			case *ast.Ident:
				funName := x.Fun.(*ast.Ident).Name

				if funName == "T" || funName == "t" {
					if stringArg, ok := x.Args[0].(*ast.BasicLit); ok {
						translatedString, err := strconv.Unquote(stringArg.Value)
						if err != nil {
							panic(err.Error())
						}

						sms.Println("Adding to translated strings:", translatedString)
						sms.TranslatedStrings = append(sms.TranslatedStrings, filename+": "+translatedString)
					}
				}
			default:
				//Skip!
			}
		}
		return true
	})

	return nil
}
开发者ID:huuzkee-foundation,项目名称:i18n4go,代码行数:28,代码来源:show_missing_strings.go


示例9: checkRangeLoop

// checkRangeLoop walks the body of the provided range statement, checking if
// its index or value variables are used unsafely inside goroutines or deferred
// function literals.
func checkRangeLoop(f *File, node ast.Node) {
	n := node.(*ast.RangeStmt)
	key, _ := n.Key.(*ast.Ident)
	val, _ := n.Value.(*ast.Ident)
	if key == nil && val == nil {
		return
	}
	sl := n.Body.List
	if len(sl) == 0 {
		return
	}
	var last *ast.CallExpr
	switch s := sl[len(sl)-1].(type) {
	case *ast.GoStmt:
		last = s.Call
	case *ast.DeferStmt:
		last = s.Call
	default:
		return
	}
	lit, ok := last.Fun.(*ast.FuncLit)
	if !ok {
		return
	}
	ast.Inspect(lit.Body, func(n ast.Node) bool {
		id, ok := n.(*ast.Ident)
		if !ok || id.Obj == nil {
			return true
		}
		if key != nil && id.Obj == key.Obj || val != nil && id.Obj == val.Obj {
			f.Bad(id.Pos(), "range variable", id.Name, "captured by func literal")
		}
		return true
	})
}
开发者ID:danny8002,项目名称:go,代码行数:38,代码来源:rangeloop.go


示例10: lintCheckFlagParse

func lintCheckFlagParse(fset *token.FileSet, af *ast.File, res []AcLintReport) []AcLintReport {
	reps := []AcLintReport{}
	foundParse := false
	ast.Inspect(af, func(node ast.Node) bool {
		switch c := node.(type) {
		case *ast.CallExpr:
			if sel, ok := c.Fun.(*ast.SelectorExpr); ok {
				if id, ok := sel.X.(*ast.Ident); ok && id.Name == "flag" {
					if sel.Sel.String() == "Parse" {
						foundParse = true
					} else if !foundParse && c != nil {
						tp := fset.Position(c.Pos())
						if tp.IsValid() {
							reps = append(reps, AcLintReport{
								Row: tp.Line - 1,
								Col: tp.Column - 1,
								Msg: "Cannot find corresponding call to flag.Parse()",
							})
						}
					}
				}
			}
		}
		return !foundParse
	})

	if !foundParse {
		res = append(res, reps...)
	}

	return res
}
开发者ID:hardPass,项目名称:MarGo,代码行数:32,代码来源:ac_lint.go


示例11: checkFileContent

func (f *file) checkFileContent() {
	if f.isTest() {
		return
	}

	if f.config.PackageName {
		f.checkPkgName(f.ast.Name)
	}

	for _, v := range f.ast.Decls {
		switch decl := v.(type) {
		case *ast.FuncDecl:
			f.checkFunctionDeclare(decl)
			if decl.Body == nil {
				break
			}
			ast.Inspect(decl.Body, func(node ast.Node) bool {
				switch decl2 := node.(type) {
				case *ast.GenDecl:
					f.checkGenDecl(decl2, false)
				case *ast.FuncDecl:
					f.checkFunctionDeclare(decl2)
				case *ast.AssignStmt:
					f.checkAssign(decl2)
				case *ast.StructType:
					f.checkStruct(decl2)
				}
				return true
			})
		case *ast.GenDecl:
			f.checkGenDecl(decl, true)
		}
	}
}
开发者ID:qiniu,项目名称:checkstyle,代码行数:34,代码来源:checkstyle.go


示例12: checkValueName

func (f *file) checkValueName(decl *ast.GenDecl, kind string, top bool) {
	for _, spec := range decl.Specs {
		if vSpec, ok := spec.(*ast.ValueSpec); ok {
			for _, name := range vSpec.Names {
				f.checkName(name, kind, !top)
			}
		} else if tSpec, ok := spec.(*ast.TypeSpec); ok {
			f.checkName(tSpec.Name, kind, false)
			ast.Inspect(tSpec.Type, func(node ast.Node) bool {
				switch decl2 := node.(type) {
				case *ast.GenDecl:
					f.checkGenDecl(decl2, false)
				case *ast.FuncDecl:
					f.checkFunctionDeclare(decl2)
				case *ast.StructType:
					f.checkStruct(decl2)
				case *ast.InterfaceType:
					f.checkInterface(decl2)
				}
				return true
			})
		} else if iSpec, ok := spec.(*ast.ImportSpec); ok && iSpec.Name != nil {
			f.checkName(iSpec.Name, "import", true)
		}
	}
}
开发者ID:qiniu,项目名称:checkstyle,代码行数:26,代码来源:checkstyle.go


示例13: enumerateAstNodesInPackage

func enumerateAstNodesInPackage(iterator func(filename string, node ast.Node) bool) error {
	packageRoot, err := getPackageFolderPath()
	if err != nil {
		return err
	}

	files, err := ioutil.ReadDir(packageRoot)
	if err != nil {
		return fmt.Errorf("Error listing package root: %v", err)
	}

	fileSet := token.NewFileSet()

	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".go") {
			contents, err := ioutil.ReadFile(filepath.Join(packageRoot, f.Name()))
			if err != nil {
				return fmt.Errorf("Error reading contents of go file in package: %v", err)
			}

			parsed, err := parser.ParseFile(fileSet, f.Name(), contents, 0)
			if err != nil {
				return fmt.Errorf("Error parsing source file %s: %v", f.Name(), err)
			}

			ast.Inspect(parsed, func(n ast.Node) bool {
				return iterator(f.Name(), n)
			})
		}
	}

	return nil
}
开发者ID:cs2dsb,项目名称:udp-sd,代码行数:33,代码来源:wire_format_test.go


示例14: printNode

func printNode(n ast.Node) {
	ast.Inspect(n, func(n ast.Node) bool {
		fmt.Printf("%T: %v\n", n, n)

		return true
	})
}
开发者ID:Logiraptor,项目名称:nap,代码行数:7,代码来源:method.go


示例15: inspectFile

func (fix *Fixup) inspectFile(file string) (translatedStrings []string, err error) {
	fset := token.NewFileSet()
	astFile, err := parser.ParseFile(fset, file, nil, parser.AllErrors)
	if err != nil {
		fix.Println(err)
		return
	}

	ast.Inspect(astFile, func(n ast.Node) bool {
		switch x := n.(type) {
		case *ast.CallExpr:
			switch x.Fun.(type) {
			case *ast.Ident:
				funName := x.Fun.(*ast.Ident).Name

				if funName == "T" || funName == "t" {
					if stringArg, ok := x.Args[0].(*ast.BasicLit); ok {
						translatedString, err := strconv.Unquote(stringArg.Value)
						if err != nil {
							panic(err.Error())
						}
						translatedStrings = append(translatedStrings, translatedString)
					}
				}
			default:
				//Skip!
			}
		}
		return true
	})

	return
}
开发者ID:krishicks,项目名称:i18n4go,代码行数:33,代码来源:fixup.go


示例16: main

func main() {
	fset := token.NewFileSet()

	f, err := parser.ParseFile(fset, "example_test.go", nil, 0)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, s := range f.Imports {
		fmt.Println(s.Path.Value)
	}

	for _, decl := range f.Decls {
		ast.Inspect(decl, func(node ast.Node) bool {
			fn, ok := node.(*ast.FuncDecl)
			if !ok {
				return false
			}
			fnName := fn.Name.Name
			for _, param := range fn.Type.Params.List {
				typeName := param.Type.(*ast.Ident).Name
				for _, name := range param.Names {
					println(fnName, name.Name, typeName)
				}
			}
			return false
		})
	}
}
开发者ID:qtkmz,项目名称:dojo,代码行数:30,代码来源:sample_parser.go


示例17: hasAllRequiredTests

// This function checks that all the functions using the tests
// defined in indextest, namely:
// TestIndex_, TestPathOfSignerTarget_, TestFiles_
// do exist in the provided test file.
func hasAllRequiredTests(name string, t *testing.T) error {
	tests := make(map[string]bool)
	for _, v := range requiredTests {
		tests[v] = false
	}

	if !strings.HasSuffix(name, "_test.go") || skipFromList(name) {
		return nil
	}
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, name, nil, 0)
	if err != nil {
		t.Fatalf("%v: %v", name, err)
	}
	ast.Inspect(f, func(n ast.Node) bool {
		switch x := n.(type) {
		case *ast.FuncDecl:
			name := x.Name.Name
			for k, _ := range tests {
				if strings.HasPrefix(name, k) {
					tests[k] = true
				}
			}
		}
		return true
	})

	for k, v := range tests {
		if !v {
			return fmt.Errorf("%v not implemented in %v", k, name)
		}
	}
	return nil
}
开发者ID:rfistman,项目名称:camlistore,代码行数:38,代码来源:index_test.go


示例18: getTaggedComments

// getTaggedComments walks the AST and returns types which have directive comment
// returns a map of TypeSpec to directive
func getTaggedComments(pkg *ast.Package, directive string) map[*ast.TypeSpec]*ast.Comment {
	specs := make(map[*ast.TypeSpec]*ast.Comment)

	ast.Inspect(pkg, func(n ast.Node) bool {
		g, ok := n.(*ast.GenDecl)

		// is it a type?
		// http://golang.org/pkg/go/ast/#GenDecl
		if !ok || g.Tok != token.TYPE {
			// never mind, move on
			return true
		}

		if g.Lparen == 0 {
			// not parenthesized, copy GenDecl.Doc into TypeSpec.Doc
			g.Specs[0].(*ast.TypeSpec).Doc = g.Doc
		}

		for _, s := range g.Specs {
			t := s.(*ast.TypeSpec)

			if c := findAnnotation(t.Doc, directive); c != nil {
				specs[t] = c
			}
		}

		// no need to keep walking, we don't care about TypeSpec's children
		return false
	})

	return specs
}
开发者ID:rickb777,项目名称:typewriter,代码行数:34,代码来源:parse.go


示例19: processFile

func processFile(filename string) []Function {
	var res []Function
	fset := token.NewFileSet() // positions are relative to fset
	f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	cmap := ast.NewCommentMap(fset, f, f.Comments)
	ast.Inspect(f, func(n ast.Node) bool {
		switch x := n.(type) {
		case *ast.FuncDecl:
			fun := Function{Begin: fset.Position(x.Pos()).Line,
				Package:  f.Name.String(),
				Name:     x.Name.String(),
				End:      fset.Position(x.End()).Line,
				Filepath: fset.Position(x.Pos()).Filename}

			fun.getTSpec(cmap[n])
			res = append(res, fun)
		}
		return true
	})
	return res
}
开发者ID:srenatus,项目名称:threatspec-playground,代码行数:25,代码来源:tojson.go


示例20: TestIncompleteSelection

// TestIncompleteSelection ensures that an incomplete selector
// expression is parsed as a (blank) *ast.SelectorExpr, not a
// *ast.BadExpr.
func TestIncompleteSelection(t *testing.T) {
	for _, src := range []string{
		"package p; var _ = fmt.",             // at EOF
		"package p; var _ = fmt.\ntype X int", // not at EOF
	} {
		fset := token.NewFileSet()
		f, err := ParseFile(fset, "", src, 0)
		if err == nil {
			t.Errorf("ParseFile(%s) succeeded unexpectedly", src)
			continue
		}

		const wantErr = "expected selector or type assertion"
		if !strings.Contains(err.Error(), wantErr) {
			t.Errorf("ParseFile returned wrong error %q, want %q", err, wantErr)
		}

		var sel *ast.SelectorExpr
		ast.Inspect(f, func(n ast.Node) bool {
			if n, ok := n.(*ast.SelectorExpr); ok {
				sel = n
			}
			return true
		})
		if sel == nil {
			t.Error("found no *ast.SelectorExpr")
			continue
		}
		const wantSel = "&{fmt _}"
		if fmt.Sprint(sel) != wantSel {
			t.Errorf("found selector %s, want %s", sel, wantSel)
			continue
		}
	}
}
开发者ID:ProjectSerenity,项目名称:myth,代码行数:38,代码来源:parser_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang ast.IsExported函数代码示例发布时间:2022-05-28
下一篇:
Golang ast.Fprint函数代码示例发布时间: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