本文整理汇总了Golang中go/ast.NewIdent函数的典型用法代码示例。如果您正苦于以下问题:Golang NewIdent函数的具体用法?Golang NewIdent怎么用?Golang NewIdent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewIdent函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ParseTry
func ParseTry(fset *token.FileSet, f *ast.File) {
blocks := FilterAst(f, func(n ast.Node) bool {
return GetBlock(n) != nil
})
for tree := range blocks {
parent := ParentFunc(tree)
b := GetBlock(tree.Node)
var block []ast.Stmt
madeTry := false
for _, v := range *b {
if try := GetTryCall(v); try != nil {
madeTry = true
block = AppendTryBlock(block, v, BuildTryBlock(parent, try))
} else {
block = append(block, v)
}
}
if madeTry {
varErr := &ast.ValueSpec{nil, []*ast.Ident{ast.NewIdent("err")}, ast.NewIdent("error"), nil, nil}
defineErr := &ast.GenDecl{nil, 0, token.VAR, 0, []ast.Spec{varErr, nil}, 0}
stmt := []ast.Stmt{&ast.DeclStmt{defineErr}}
block = append(stmt, block...)
}
*b = block
}
EnsureNoTry(f)
}
示例2: insertIntVar
func insertIntVar(file *ast.File, name string, value int) {
var before, after []ast.Decl
if len(file.Decls) > 0 {
hasImport := false
if genDecl, ok := file.Decls[0].(*ast.GenDecl); ok {
hasImport = genDecl.Tok == token.IMPORT
}
if hasImport {
before, after = []ast.Decl{file.Decls[0]}, file.Decls[1:]
} else {
after = file.Decls
}
}
file.Decls = append(before,
&ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{
&ast.ValueSpec{
Names: []*ast.Ident{ast.NewIdent(name)},
Type: ast.NewIdent("int"),
Values: []ast.Expr{
&ast.BasicLit{
Kind: token.INT,
Value: fmt.Sprintf("%d", value),
},
},
},
},
},
)
file.Decls = append(file.Decls, after...)
}
示例3: AppendTryBlock
func AppendTryBlock(block []ast.Stmt, node ast.Node, errBlock []ast.Stmt) []ast.Stmt {
var try, call *ast.CallExpr
var assign *ast.AssignStmt
_err, _nil := ast.NewIdent("err"), ast.NewIdent("nil")
// err != nil
errNil := &ast.BinaryExpr{_err, 0, token.NEQ, _nil}
// if errNil { stmt }
ifBlock := &ast.IfStmt{0, nil, errNil, &ast.BlockStmt{0, errBlock, 0}, nil}
switch n := node.(type) {
case *ast.AssignStmt:
assign = n
try = n.Rhs[0].(*ast.CallExpr)
case *ast.ExprStmt:
try = n.X.(*ast.CallExpr)
default:
log.Fatalf("unhandled try() node type: %T\n", node)
}
if assign == nil {
assign = &ast.AssignStmt{nil, 0, token.ASSIGN, nil}
}
call = StripTry(try)
assign.Rhs = []ast.Expr{call}
assign.Lhs = append(assign.Lhs, _err)
block = append(block, assign)
block = append(block, ifBlock)
return block
}
示例4: replaceStructLiteralWithIdentifier
func replaceStructLiteralWithIdentifier(statement ast.Node, n *ast.CompositeLit, name string) {
ast.Inspect(statement, func(parentNode ast.Node) bool {
switch parentNode := parentNode.(type) {
case *ast.KeyValueExpr:
if parentNode.Value == n {
parentNode.Value = ast.NewIdent(name)
}
case *ast.CallExpr:
for i, expr := range parentNode.Args {
if expr == n {
parentNode.Args[i] = ast.NewIdent(name)
}
}
case *ast.AssignStmt:
if parentNode.Rhs[0] == n {
parentNode.Rhs[0] = ast.NewIdent(name)
}
case *ast.ReturnStmt:
for i, expr := range parentNode.Results {
if expr == n {
parentNode.Results[i] = ast.NewIdent(name)
}
}
case *ast.CompositeLit:
for i, expr := range parentNode.Elts {
if expr == n {
parentNode.Elts[i] = ast.NewIdent(name)
}
}
}
return true
})
}
示例5: resolveMutexType
func (t *GeneratorModel) resolveMutexType() *ast.SelectorExpr {
alias := t.AddImport("sync", "sync")
return &ast.SelectorExpr{
X: ast.NewIdent(alias),
Sel: ast.NewIdent("RWMutex"),
}
}
示例6: insertHello
func insertHello(file *ast.File) {
ast.Inspect(file, func(node ast.Node) bool {
if ifStmt, ok := node.(*ast.IfStmt); ok {
ifStmt.Body.List = append(
[]ast.Stmt{
&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent("fmt"),
Sel: ast.NewIdent("Printf"),
},
Args: []ast.Expr{
&ast.BasicLit{
Kind: token.STRING,
Value: "\"hello\"",
},
},
},
},
},
ifStmt.Body.List...,
)
}
return true
})
}
示例7: Build
func (m *FileBuilder) Build() *ast.File {
file := &ast.File{
Name: ast.NewIdent(m.filePackageName),
}
if len(m.aliasToImport) > 0 {
importDeclaration := &ast.GenDecl{
Tok: token.IMPORT,
Lparen: token.Pos(1),
Specs: []ast.Spec{},
}
for alias, location := range m.aliasToImport {
importDeclaration.Specs = append(importDeclaration.Specs, &ast.ImportSpec{
Name: ast.NewIdent(alias),
Path: &ast.BasicLit{
Kind: token.STRING,
Value: fmt.Sprintf("\"%s\"", location),
},
})
}
file.Decls = append(file.Decls, importDeclaration)
}
for _, builder := range m.generalDeclarationBuilders {
file.Decls = append(file.Decls, builder.Build())
}
return file
}
示例8: playExampleFile
// playExampleFile takes a whole file example and synthesizes a new *ast.File
// such that the example is function main in package main.
func playExampleFile(file *ast.File) *ast.File {
// Strip copyright comment if present.
comments := file.Comments
if len(comments) > 0 && strings.HasPrefix(comments[0].Text(), "Copyright") {
comments = comments[1:]
}
// Copy declaration slice, rewriting the ExampleX function to main.
var decls []ast.Decl
for _, d := range file.Decls {
if f, ok := d.(*ast.FuncDecl); ok && isTest(f.Name.Name, "Example") {
// Copy the FuncDecl, as it may be used elsewhere.
newF := *f
newF.Name = ast.NewIdent("main")
newF.Body, comments = stripOutputComment(f.Body, comments)
d = &newF
}
decls = append(decls, d)
}
// Copy the File, as it may be used elsewhere.
f := *file
f.Name = ast.NewIdent("main")
f.Decls = decls
f.Comments = comments
return &f
}
示例9: Build
func (m *MethodBuilder) Build() ast.Decl {
statements := make([]ast.Stmt, len(m.statementBuilders))
for i, builder := range m.statementBuilders {
statements[i] = builder.Build()
}
return &ast.FuncDecl{
Recv: &ast.FieldList{
List: []*ast.Field{
{
Names: []*ast.Ident{
ast.NewIdent(m.receiverName),
},
Type: &ast.StarExpr{
X: ast.NewIdent(m.receiverType),
},
},
},
},
Name: ast.NewIdent(m.name),
Type: m.funcType,
Body: &ast.BlockStmt{
List: statements,
},
}
}
示例10: methodCallCountGetter
func (gen CodeGenerator) methodCallCountGetter(method *ast.Field) *ast.FuncDecl {
return &ast.FuncDecl{
Name: ast.NewIdent(callCountMethodName(method)),
Type: &ast.FuncType{
Results: &ast.FieldList{List: []*ast.Field{
&ast.Field{
Type: ast.NewIdent("int"),
},
}},
},
Recv: gen.receiverFieldList(),
Body: &ast.BlockStmt{List: []ast.Stmt{
callMutex(method, "RLock"),
deferMutex(method, "RUnlock"),
&ast.ReturnStmt{
Results: []ast.Expr{
&ast.CallExpr{
Fun: ast.NewIdent("len"),
Args: []ast.Expr{
&ast.SelectorExpr{
X: receiverIdent(),
Sel: ast.NewIdent(callArgsFieldName(method)),
},
},
},
},
},
}},
}
}
示例11: hmacnew
func hmacnew(f *ast.File) (fixed bool) {
if !imports(f, "crypto/hmac") {
return
}
walk(f, func(n interface{}) {
ce, ok := n.(*ast.CallExpr)
if !ok {
return
}
var pkg string
switch {
case isPkgDot(ce.Fun, "hmac", "NewMD5"):
pkg = "md5"
case isPkgDot(ce.Fun, "hmac", "NewSHA1"):
pkg = "sha1"
case isPkgDot(ce.Fun, "hmac", "NewSHA256"):
pkg = "sha256"
default:
return
}
addImport(f, "crypto/"+pkg)
ce.Fun = ast.NewIdent("hmac.New")
ce.Args = append([]ast.Expr{ast.NewIdent(pkg + ".New")}, ce.Args...)
fixed = true
})
return
}
示例12: makeLoop
func makeLoop(node *parser.CallNode) *ast.CallExpr {
returnIdent := generateIdent()
loopIdent := generateIdent()
fnBody := h.EmptyS()
bindingsVector := node.Args[0].(*parser.VectorNode)
addRecurLabelAndBindings(parser.NewIdentNode(loopIdent.String()), bindingsVector.Copy().(*parser.VectorNode), node.Args[1:])
bindings := makeBindings(bindingsVector, token.DEFINE)
returnIdentValueSpec := makeValueSpec(h.I(returnIdent), nil, anyType)
returnIdentDecl := makeDeclStmt(makeGeneralDecl(token.VAR, []ast.Spec{returnIdentValueSpec}))
fnBody = append(fnBody, bindings...)
fnBody = append(fnBody, returnIdentDecl)
init := makeAssignStmt(h.E(loopIdent), h.E(ast.NewIdent("true")), token.DEFINE)
forBody := h.EmptyS()
forBody = append(forBody, makeAssignStmt(h.E(loopIdent), h.E(ast.NewIdent("false")), token.ASSIGN))
forBody = append(forBody, wrapExprsWithStmt(EvalExprs(node.Args[1:len(node.Args)-1]))...)
forBody = append(forBody, makeAssignStmt(h.E(returnIdent), h.E(EvalExpr(node.Args[len(node.Args)-1])), token.ASSIGN))
forStmt := makeForStmt(init, nil, loopIdent, makeBlockStmt(forBody))
fnBody = append(fnBody, forStmt)
fnBody = append(fnBody, makeReturnStmt(h.E(returnIdent)))
results := makeFieldList([]*ast.Field{makeField(nil, anyType)})
fnType := makeFuncType(results, nil)
fn := makeFuncLit(fnType, makeBlockStmt(fnBody))
return makeFuncCall(fn, h.EmptyE())
}
示例13: Build
func (b *CountMethodBuilder) Build() ast.Decl {
mutexLockBuilder := NewMutexActionBuilder()
mutexLockBuilder.SetMutexFieldSelector(b.mutexFieldSelector)
mutexLockBuilder.SetAction("RLock")
mutexUnlockBuilder := NewMutexActionBuilder()
mutexUnlockBuilder.SetMutexFieldSelector(b.mutexFieldSelector)
mutexUnlockBuilder.SetAction("RUnlock")
mutexUnlockBuilder.SetDeferred(true)
b.methodBuilder.SetType(&ast.FuncType{
Params: &ast.FieldList{},
Results: &ast.FieldList{
List: []*ast.Field{
{
Type: ast.NewIdent("int"),
},
},
},
})
b.methodBuilder.AddStatementBuilder(mutexLockBuilder)
b.methodBuilder.AddStatementBuilder(mutexUnlockBuilder)
b.methodBuilder.AddStatementBuilder(StatementToBuilder(&ast.ReturnStmt{
Results: []ast.Expr{
&ast.CallExpr{
Fun: ast.NewIdent("len"),
Args: []ast.Expr{
b.argsFieldSelector,
},
},
},
}))
return b.methodBuilder.Build()
}
示例14: makeNAryCallableExpr
// We handle comparisons as a call to some go code, since you can only
// compare ints, floats, cmplx, and such, you know...
// We handle arithmetic operations as function calls, since all args are evaluated
func makeNAryCallableExpr(node *parser.CallNode) *ast.CallExpr {
op := node.Callee.(*parser.IdentNode).Ident
args := EvalExprs(node.Args)
var selector string
// TODO: abstract this away into a map!!!
switch op {
case ">":
selector = "GT"
case ">=":
selector = "GTEQ"
case "<":
selector = "LT"
case "<=":
selector = "LTEQ"
case "=":
selector = "EQ"
case "+":
selector = "ADD"
case "-":
selector = "SUB"
case "*":
selector = "MUL"
case "/":
selector = "DIV"
case "mod":
if len(node.Args) > 2 {
panic("can't calculate modulo with more than 2 arguments!")
}
selector = "MOD"
}
return makeFuncCall(makeSelectorExpr(ast.NewIdent("core"), ast.NewIdent(selector)), args)
}
示例15: TestBadAst
func TestBadAst(t *testing.T) {
// typeOfExpr should gracefully handle broken AST structures. Let's
// construct some.
// Array with bad length descriptor.
// [Bad]int32
badArr := ast.ArrayType{
Len: ast.NewIdent("Bad"),
Elt: ast.NewIdent("int32"),
}
typ, err := typeOfExpr(&badArr)
assert.Equal(t, typ, nil)
assert.Equal(t, err.Error(), "invalid array size expression")
// Array with bad length descriptor.
// ["How about that!"]int32
badArr = ast.ArrayType{
Len: &ast.BasicLit{Kind: token.STRING, Value: `"How about that!"`},
Elt: ast.NewIdent("int32"),
}
typ, err = typeOfExpr(&badArr)
assert.Equal(t, typ, nil)
assert.Equal(t, err.Error(), "invalid array size type")
// Array with bad length descriptor.
// [10ii0]int32
badArr = ast.ArrayType{
Len: &ast.BasicLit{Kind: token.INT, Value: "10ii0"},
Elt: ast.NewIdent("int32"),
}
typ, err = typeOfExpr(&badArr)
assert.Equal(t, typ, nil)
assert.Equal(t, err.Error(), "strconv.ParseInt: parsing \"10ii0\": invalid syntax")
}