当前位置: 首页>>代码示例>>Golang>>正文


Golang ast.Inspect函数代码示例

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


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


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