How to use pos method of ast Package

Best Syzkaller code snippet using ast.pos

inspect.go

Source:inspect.go Github

copy

Full Screen

...25func (h HappyAst) Position(tp token.Pos) token.Position {26 return h.FileSet.PositionFor(tp, true)27}28//29//func (h HappyAst) FindNodeByPos(pos token.Pos) (ret *ast.Node) {30// if pos == token.NoPos {31// return nil32// }33// ast.Inspect(h.Ast, func(node ast.Node) bool {34// switch node.(type) {35// case ast.Node:36// if !node.Pos().IsValid() {37// return true38// }39// if node.Pos() == pos {40// ret = &node41// return false42// }43// }44// return true45// })46// return ret47//}48// find function by name,49// return token.Pos50func (h HappyAst) FindIdent(ident string) (pos []token.Pos) {51 ast.Inspect(h.Ast, func(node ast.Node) bool {52 switch x := node.(type) {53 case *ast.Ident:54 if x.Name == ident {55 pos = append(pos, x.Pos())56 return true57 }58 }59 return true60 })61 return pos62}63// find value spec node by name,64// return token.Pos65func (h HappyAst) FindValueSpec(ident string) (pos []token.Pos) {66 ast.Inspect(h.Ast, func(node ast.Node) bool {67 switch x := node.(type) {68 case *ast.ValueSpec:69 for _, v := range x.Names {70 if v.Name == ident {71 pos = append(pos, x.Pos())72 return true73 }74 }75 }76 return true77 })78 return pos79}80// find value spec node by name,81// return token.Pos82func (h HappyAst) FindValueSpecFromNode(n ast.Node, ident string) (pos []token.Pos) {83 ast.Inspect(n, func(node ast.Node) bool {84 switch x := node.(type) {85 case *ast.ValueSpec:86 for _, v := range x.Names {87 if v.Name == ident {88 pos = append(pos, x.Pos())89 return true90 }91 }92 }93 return true94 })95 return pos96}97// find function by name,98// return token.Pos99func (h HappyAst) FindFuncDeclNode(wantName string) (pos token.Pos) {100 ast.Inspect(h.Ast, func(node ast.Node) bool {101 switch x := node.(type) {102 case *ast.FuncDecl:103 if x.Name.Name == wantName {104 pos = x.Pos()105 return false106 }107 }108 return true109 })110 return111}112// find Struct Decl by name,113// return token.Pos114func (h HappyAst) FindStructDeclNode(wantName string) (pos token.Pos) {115 ast.Inspect(h.Ast, func(node ast.Node) bool {116 switch g := node.(type) {117 case *ast.GenDecl:118 if g.Tok == token.TYPE {119 for _, v := range g.Specs {120 switch x := v.(type) {121 case *ast.TypeSpec:122 switch x.Type.(type) {123 case *ast.StructType:124 if x.Name.Name == wantName {125 pos = x.Pos()126 return false127 }128 }129 }130 }131 }132 }133 return true134 })135 return136}137// find Struct Field by name from given Node,138// return token.Pos139func (h HappyAst) FindStructFieldFromNode(n ast.Node, wantName string) (pos token.Pos) {140 ast.Inspect(n, func(node ast.Node) bool {141 switch g := node.(type) {142 case *ast.StructType:143 for _, v := range g.Fields.List {144 for _, val := range v.Names {145 if val.Name == wantName {146 pos = val.Pos()147 return false148 }149 }150 }151 }152 return true153 })154 return155}156// find function call from given Node,157// return token.Pos158func (h HappyAst) FindCallExprFromNode(n ast.Node, funcName string) (pos token.Pos) {159 ast.Inspect(n, func(node ast.Node) bool {160 switch x := node.(type) {161 case *ast.CallExpr:162 switch i := x.Fun.(type) {163 case *ast.Ident:164 if i.Name == funcName {165 pos = x.Pos()166 return false167 }168 }169 }170 return true171 })172 return173}174// print HappyAst into string175func (h HappyAst) Output(printConfig *printer.Config) string {176 var buf bytes.Buffer177 if printConfig == nil {178 printConfig = &printer.Config{Mode: printer.TabIndent, Tabwidth: 4}179 }180 err := printConfig.Fprint(&buf, h.FileSet, h.Ast)181 if err != nil {182 panic(err)183 }184 out := buf.Bytes()185 out, err = format.Source(out)186 if err != nil {187 panic(err)188 }189 return string(out)190}191// print HappyAst into string192// 以下节点不支持打印:193// ast.CommentGroup194// ast.Comment195func (h HappyAst) OutputNode(node interface{}) string {196 var buf bytes.Buffer197 printConfig := &printer.Config{Mode: printer.TabIndent, Tabwidth: 4}198 err := printConfig.Fprint(&buf, h.FileSet, node)199 if err != nil {200 panic(err)201 }202 out := buf.Bytes()203 out, err = format.Source(out)204 if err != nil {205 panic(err)206 }207 return string(out)208}209//print210func (h HappyAst) Print() {211 ast.Fprint(os.Stdout, h.FileSet, h.Ast, nil)212}213//visitor214func (h HappyAst) Visit() {215 //visitor216 ast.Walk(HappyVisitor(printNode), h.Ast)217}218// node Visitor219type HappyVisitor func(ast.Node) string220func (v HappyVisitor) Visit(node ast.Node) ast.Visitor {221 view := v(node)222 //_=view223 fmt.Print(view)224 return v225}226// print node227func printNode(node ast.Node) string {228 if node == nil {229 return ""230 }231 //save232 ptr := node.Pos()233 if line, exists := p.ptrmap[ptr]; exists {234 _ = line235 //printf("(obj @ %d)", line)236 return ""237 } else {238 p.ptrmap[node.Pos()] = node.Pos()239 }240 switch n := node.(type) {241 case *ast.Comment:242 return ""243 //code = n.Text244 //return printLine(code)245 case *ast.CommentGroup:246 return ""247 //for _,c := range n.List{248 // code += printNode(c)249 //}250 //return printLine(code)251 case *ast.Field:252 return ""253 //for _,v := range n.Names{254 // code+=printNode(v)255 //}256 //return code + string(tab)257 case *ast.FieldList:258 return ""259 //for _,v := range n.List{260 // code += printNode(v)261 //}262 //return code + string(tab)263 case *ast.BadExpr:264 case *ast.Ident:265 inner := ""266 if n.Obj != nil {267 inner += n.Obj.Kind.String()268 }269 inner += n.Name270 //return ""271 return inner + string(blank)272 case *ast.BasicLit:273 inner := ""274 inner += n.Kind.String()275 inner += n.Value276 return inner277 //return n.Value+ string(blank)278 case *ast.Ellipsis:279 return ""280 //return printNode(n)+ string(blank)281 case *ast.FuncLit:282 return ""283 //return printNode(n.Body)+ string(newline)284 case *ast.CompositeLit:285 return ""286 //return printNode(n.Type)+ string(blank)287 case *ast.ParenExpr:288 return ""289 //return printNode(n)+ string(blank)290 case *ast.SelectorExpr:291 inner := ""292 //inner += printNode(n.X)293 inner += "."294 //inner += printNode(n.Sel)295 return inner296 case *ast.IndexExpr:297 inner := "*"298 inner += printNode(n.X)299 return inner300 case *ast.SliceExpr:301 inner := "*"302 inner += printNode(n.X)303 return inner304 case *ast.TypeAssertExpr:305 inner := "*"306 //inner += printNode(n.Type)307 //inner += printNode(n.X)308 return inner309 case *ast.CallExpr:310 case *ast.StarExpr:311 inner := "*"312 inner += printNode(n.X)313 return inner314 case *ast.UnaryExpr:315 inner := ""316 inner += printNode(n.X)317 return inner318 case *ast.BinaryExpr:319 inner := ""320 inner += printNode(n.X)321 inner += printNode(n.Y)322 return inner323 case *ast.KeyValueExpr:324 case *ast.ArrayType:325 case *ast.StructType:326 case *ast.FuncType:327 case *ast.InterfaceType:328 case *ast.MapType:329 case *ast.ChanType:330 case *ast.BadStmt:331 case *ast.DeclStmt:332 case *ast.EmptyStmt:333 case *ast.LabeledStmt:334 case *ast.ExprStmt:335 case *ast.SendStmt:336 case *ast.IncDecStmt:337 case *ast.AssignStmt:338 case *ast.GoStmt:339 case *ast.DeferStmt:340 case *ast.ReturnStmt:341 case *ast.BranchStmt:342 case *ast.BlockStmt:343 case *ast.IfStmt:344 case *ast.CaseClause:345 case *ast.SwitchStmt:346 case *ast.TypeSwitchStmt:347 case *ast.CommClause:348 case *ast.SelectStmt:349 case *ast.ForStmt:350 case *ast.RangeStmt:351 case *ast.ImportSpec:352 return n.Path.Value + string(newline)353 case *ast.ValueSpec:354 inner := ""355 for _, v := range n.Names {356 inner += v.Name + " "357 }358 return inner + string(newline)359 case *ast.TypeSpec:360 case *ast.BadDecl:361 case *ast.GenDecl:362 return inspectGenDecl(n)363 case *ast.FuncDecl:364 return inspectFuncDecl(n)365 case *ast.File:366 //packageName := n.Name.Name367 inner := ""368 inner += printNode(n.Name)369 return "package " + inner + string(newline)370 case *ast.Package:371 return ""372 default:373 _ = n374 }375 return ""376}377type mprinter struct {378 output io.Writer379 fset *token.FileSet380 filter ast.FieldFilter381 ptrmap map[interface{}]interface{} // *T -> line number382 //ptrmap map[interface{}]int // *T -> line number383 indent int // current indentation level384 last byte // the last byte processed by Write385 line int // current line number386}387//var p = mprinter{os.Stdout,fset,nil,0,byte(0),0}388var p = mprinter{389 output: os.Stdout,390 fset: fset,391 filter: nil,392 ptrmap: make(map[interface{}]interface{}),393 last: '\n', // force printing of line number on first line394}395func print(x reflect.Value) {396 switch x.Kind() {397 case reflect.Interface:398 print(x.Elem())399 case reflect.Map:400 printf("%s (len = %d) {", x.Type(), x.Len())401 if x.Len() > 0 {402 p.indent++403 printf("\n")404 for _, key := range x.MapKeys() {405 print(key)406 printf(": ")407 print(x.MapIndex(key))408 printf("\n")409 }410 p.indent--411 }412 printf("}")413 case reflect.Ptr:414 printf("*")415 // type-checked ASTs may contain cycles - use ptrmap416 // to keep track of objects that have been printed417 // already and print the respective line number instead418 ptr := x.Interface()419 if line, exists := p.ptrmap[ptr]; exists {420 printf("(obj @ %d)", line)421 } else {422 p.ptrmap[ptr] = p.line423 print(x.Elem())424 }425 case reflect.Array:426 printf("%s {", x.Type())427 if x.Len() > 0 {428 p.indent++429 printf("\n")430 for i, n := 0, x.Len(); i < n; i++ {431 printf("%d: ", i)432 print(x.Index(i))433 printf("\n")434 }435 p.indent--436 }437 printf("}")438 case reflect.Slice:439 if s, ok := x.Interface().([]byte); ok {440 printf("%#q", s)441 return442 }443 printf("%s (len = %d) {", x.Type(), x.Len())444 if x.Len() > 0 {445 p.indent++446 printf("\n")447 for i, n := 0, x.Len(); i < n; i++ {448 printf("%d: ", i)449 print(x.Index(i))450 printf("\n")451 }452 p.indent--453 }454 printf("}")455 case reflect.Struct:456 t := x.Type()457 printf("%s {", t)458 p.indent++459 first := true460 for i, n := 0, t.NumField(); i < n; i++ {461 // exclude non-exported fields because their462 // values cannot be accessed via reflection463 if name := t.Field(i).Name; ast.IsExported(name) {464 value := x.Field(i)465 if first {466 printf("\n")467 first = false468 }469 printf("%s: ", name)470 print(value)471 printf("\n")472 }473 }474 p.indent--475 printf("}")476 ////test477 //xxxy := x.Interface().(ast.Node)478 //switch xxxy.(type){479 //case *ast.File:480 // fmt.Println("=================================file")481 //default:482 //483 //}484 ////test end485 default:486 v := x.Interface()487 switch v := v.(type) {488 case string:489 // print strings in quotes490 printf("%q", v)491 return492 case token.Pos:493 // position values can be printed nicely if we have a file set494 if p.fset != nil {495 printf("%s", p.fset.Position(v))496 return497 }498 }499 // default500 printf("%v", v)501 }502}503// printf is a convenience wrapper that takes care of print errors.504func printf(format string, args ...interface{}) {505 if _, err := fmt.Fprintf(p.output, format, args...); err != nil {506 panic(err)507 }508}509//从ast.Node中根据函数名查找指定函数510func findFuncByName(node ast.Node) bool {511 //ast.Print(fset,node)512 //ast.Fprint(os.Stdout,fset,node,nil)513 var wantName string514 wantName = "registerBrandcustomerClientConn"515 switch x := node.(type) {516 case *ast.FuncDecl:517 for _, v := range x.Body.List {518 switch decl := v.(type) {519 case *ast.DeclStmt:520 findFuncByName(decl.Decl)521 case *ast.ExprStmt:522 switch exp := decl.X.(type) {523 case *ast.CallExpr:524 funcName, pos := parseCallExpr(exp.Fun)525 if funcName == wantName {526 dummyData = append(dummyData, IdentInfo{527 Name: funcName,528 Pos: pos,529 })530 }531 }532 }533 }534 }535 return true536}537func parseCallExpr(cexpr ast.Expr) (string, token.Pos) {538 switch x := cexpr.(type) {539 case *ast.FuncLit:540 case *ast.Ident:541 return x.Name, x.Pos()542 }...

Full Screen

Full Screen

rewrite.go

Source:rewrite.go Github

copy

Full Screen

...14)15///*16// 替换节点17//*/18//func (h *HappyAst) ReplaceNode(pos token.Pos, newNode ast.Node) error {19// if pos == token.NoPos {20// return errors.New("pos not exist")21// }22// ast.Inspect(h.Ast, func(node ast.Node) bool {23// switch node.(type) {24// case ast.Node:25// if !node.Pos().IsValid() {26// return true27// }28// if node.Pos() == pos {29// node = newNode30// return false31// }32// }33// return true34// })35// return nil36//}37//38///*39// 替换节点40//*/41//func (h *HappyAst) ReplaceNode(pos token.Pos, newNode ast.Node) error {42// if pos == token.NoPos {43// return errors.New("pos not exist")44// }45// ast.Inspect(h.Ast, func(node ast.Node) bool {46// if node.Pos().IsValid() && node.Pos() == pos {47// node = newNode48// return false49// }50//51// return true52// })53// return nil54//}55/*56 替换节点57*/58func (h *HappyAst) ReplaceNode(pos token.Pos, newNode ast.Node) error {59 if pos == token.NoPos {60 return errors.New("pos not exist")61 }62 ast.Inspect(h.Ast, func(node ast.Node) bool {63 switch x := node.(type) {64 case *ast.Ident:65 if node.Pos().IsValid() && node.Pos() == pos {66 *x = *newNode.(*ast.Ident)67 return false68 }69 case *ast.BasicLit:70 if node.Pos().IsValid() && node.Pos() == pos {71 *x = *newNode.(*ast.BasicLit)72 return false73 }74 case *ast.File:75 if node.Pos().IsValid() && node.Pos() == pos {76 *x = *newNode.(*ast.File)77 return false78 }79 case *ast.ImportSpec:80 if node.Pos().IsValid() && node.Pos() == pos {81 *x = *newNode.(*ast.ImportSpec)82 return false83 }84 case *ast.Package:85 if node.Pos().IsValid() && node.Pos() == pos {86 *x = *newNode.(*ast.Package)87 return false88 }89 case *ast.AssignStmt:90 if node.Pos().IsValid() && node.Pos() == pos {91 *x = *newNode.(*ast.AssignStmt)92 return false93 }94 case *ast.RangeStmt:95 if node.Pos().IsValid() && node.Pos() == pos {96 *x = *newNode.(*ast.RangeStmt)97 return false98 }99 case *ast.BranchStmt:100 if node.Pos().IsValid() && node.Pos() == pos {101 *x = *newNode.(*ast.BranchStmt)102 return false103 }104 case *ast.BinaryExpr:105 if node.Pos().IsValid() && node.Pos() == pos {106 *x = *newNode.(*ast.BinaryExpr)107 return false108 }109 case *ast.IncDecStmt:110 if node.Pos().IsValid() && node.Pos() == pos {111 *x = *newNode.(*ast.IncDecStmt)112 return false113 }114 case *ast.ForStmt:115 if node.Pos().IsValid() && node.Pos() == pos {116 *x = *newNode.(*ast.ForStmt)117 return false118 }119 case *ast.SelectorExpr:120 if node.Pos().IsValid() && node.Pos() == pos {121 *x = *newNode.(*ast.SelectorExpr)122 return false123 }124 case *ast.CallExpr:125 if node.Pos().IsValid() && node.Pos() == pos {126 *x = *newNode.(*ast.CallExpr)127 return false128 }129 case *ast.ReturnStmt:130 if node.Pos().IsValid() && node.Pos() == pos {131 *x = *newNode.(*ast.ReturnStmt)132 return false133 }134 case *ast.BlockStmt:135 if node.Pos().IsValid() && node.Pos() == pos {136 *x = *newNode.(*ast.BlockStmt)137 return false138 }139 case *ast.IfStmt:140 if node.Pos().IsValid() && node.Pos() == pos {141 *x = *newNode.(*ast.IfStmt)142 return false143 }144 case *ast.InterfaceType:145 if node.Pos().IsValid() && node.Pos() == pos {146 *x = *newNode.(*ast.InterfaceType)147 return false148 }149 case *ast.FuncType:150 if node.Pos().IsValid() && node.Pos() == pos {151 *x = *newNode.(*ast.FuncType)152 return false153 }154 case *ast.ChanType:155 if node.Pos().IsValid() && node.Pos() == pos {156 *x = *newNode.(*ast.ChanType)157 return false158 }159 case *ast.MapType:160 if node.Pos().IsValid() && node.Pos() == pos {161 *x = *newNode.(*ast.MapType)162 return false163 }164 case *ast.ArrayType:165 if node.Pos().IsValid() && node.Pos() == pos {166 *x = *newNode.(*ast.ArrayType)167 return false168 }169 case *ast.TypeSpec:170 if node.Pos().IsValid() && node.Pos() == pos {171 *x = *newNode.(*ast.TypeSpec)172 return false173 }174 case *ast.GenDecl:175 if node.Pos().IsValid() && node.Pos() == pos {176 *x = *newNode.(*ast.GenDecl)177 return false178 }179 case *ast.UnaryExpr:180 if node.Pos().IsValid() && node.Pos() == pos {181 *x = *newNode.(*ast.UnaryExpr)182 return false183 }184 case *ast.ValueSpec:185 if node.Pos().IsValid() && node.Pos() == pos {186 *x = *newNode.(*ast.ValueSpec)187 return false188 }189 case *ast.DeclStmt:190 if node.Pos().IsValid() && node.Pos() == pos {191 *x = *newNode.(*ast.DeclStmt)192 return false193 }194 case *ast.FuncDecl:195 if node.Pos().IsValid() && node.Pos() == pos {196 *x = *newNode.(*ast.FuncDecl)197 return false198 }199 case *ast.KeyValueExpr:200 if node.Pos().IsValid() && node.Pos() == pos {201 *x = *newNode.(*ast.KeyValueExpr)202 return false203 }204 case *ast.BadDecl:205 if node.Pos().IsValid() && node.Pos() == pos {206 *x = *newNode.(*ast.BadDecl)207 return false208 }209 case *ast.BadExpr:210 if node.Pos().IsValid() && node.Pos() == pos {211 *x = *newNode.(*ast.BadExpr)212 return false213 }214 case *ast.CaseClause:215 if node.Pos().IsValid() && node.Pos() == pos {216 *x = *newNode.(*ast.CaseClause)217 return false218 }219 case *ast.CommClause:220 if node.Pos().IsValid() && node.Pos() == pos {221 *x = *newNode.(*ast.CommClause)222 return false223 }224 case *ast.CompositeLit:225 if node.Pos().IsValid() && node.Pos() == pos {226 *x = *newNode.(*ast.CompositeLit)227 return false228 }229 case *ast.DeferStmt:230 if node.Pos().IsValid() && node.Pos() == pos {231 *x = *newNode.(*ast.DeferStmt)232 return false233 }234 case *ast.Ellipsis:235 if node.Pos().IsValid() && node.Pos() == pos {236 *x = *newNode.(*ast.Ellipsis)237 return false238 }239 case *ast.EmptyStmt:240 if node.Pos().IsValid() && node.Pos() == pos {241 *x = *newNode.(*ast.EmptyStmt)242 return false243 }244 case *ast.ExprStmt:245 if node.Pos().IsValid() && node.Pos() == pos {246 *x = *newNode.(*ast.ExprStmt)247 return false248 }249 case *ast.Field:250 if node.Pos().IsValid() && node.Pos() == pos {251 *x = *newNode.(*ast.Field)252 return false253 }254 case *ast.FieldList:255 if node.Pos().IsValid() && node.Pos() == pos {256 *x = *newNode.(*ast.FieldList)257 return false258 }259 case *ast.SwitchStmt:260 if node.Pos().IsValid() && node.Pos() == pos {261 *x = *newNode.(*ast.SwitchStmt)262 return false263 }264 case *ast.TypeAssertExpr:265 if node.Pos().IsValid() && node.Pos() == pos {266 *x = *newNode.(*ast.TypeAssertExpr)267 return false268 }269 case *ast.TypeSwitchStmt:270 if node.Pos().IsValid() && node.Pos() == pos {271 *x = *newNode.(*ast.TypeSwitchStmt)272 return false273 }274 case *ast.StarExpr:275 if node.Pos().IsValid() && node.Pos() == pos {276 *x = *newNode.(*ast.StarExpr)277 return false278 }279 case *ast.SelectStmt:280 if node.Pos().IsValid() && node.Pos() == pos {281 *x = *newNode.(*ast.SelectStmt)282 return false283 }284 case *ast.IndexExpr:285 if node.Pos().IsValid() && node.Pos() == pos {286 *x = *newNode.(*ast.IndexExpr)287 return false288 }289 case *ast.LabeledStmt:290 if node.Pos().IsValid() && node.Pos() == pos {291 *x = *newNode.(*ast.LabeledStmt)292 return false293 }294 case *ast.GoStmt:295 if node.Pos().IsValid() && node.Pos() == pos {296 *x = *newNode.(*ast.GoStmt)297 return false298 }299 case *ast.SendStmt:300 if node.Pos().IsValid() && node.Pos() == pos {301 *x = *newNode.(*ast.SendStmt)302 return false303 }304 case *ast.ParenExpr:305 if node.Pos().IsValid() && node.Pos() == pos {306 *x = *newNode.(*ast.ParenExpr)307 return false308 }309 case *ast.SliceExpr:310 if node.Pos().IsValid() && node.Pos() == pos {311 *x = *newNode.(*ast.SliceExpr)312 return false313 }314 default:315 }316 return true317 })318 return nil319}320/*321 添加语句322 @deprecated323*/324func (h *HappyAst) AddStmt(bmt *ast.BlockStmt, location int, stmt ast.Stmt) {...

Full Screen

Full Screen

happy_ast.go

Source:happy_ast.go Github

copy

Full Screen

...22 h := ParseFromCode(srcode)23 h.Print()24 //h.Visit()25 //fmt.Println(h.Output())26 pos := h.FindStructDeclNode("Microservice")27 fmt.Println(h.Position(pos))28}29func DemoRewrite(codeFile string) {30 srcode := `package miclient31type Microservice struct {32ActivityHost string ` + "`" + `json:"activity_service_host"` + "`" + `33}`34 h := ParseFromCode(srcode)35 if codeFile != "" {36 h = ParseFromFile(codeFile)37 }38 tag := NewBasicLit(token.STRING, "`json:\"brandcustomer_service_host\"`")39 field := NewField([]string{"BrandHost"}, NewIdent("string"), ExprTypeIdent, tag)40 gpos := h.FindStructDeclNode("Microservice")41 gnode := h.NodeByPos(gpos)42 structNode := gnode.(*ast.TypeSpec).Type.(*ast.StructType)43 structNode.Fields.List = append(structNode.Fields.List, field)44 h.ReplaceNode(gpos, gnode)45 fmt.Println(h.Output(nil))46}47func ParseFromFile(codeFile string) *HappyAst {48 fset = token.NewFileSet()49 //astNodes, err := parser.ParseFile(fset, codeFile, nil,parser.ParseComments)50 astNodes, err := parser.ParseFile(fset, codeFile, nil, parser.ParseComments)51 if err != nil {52 panic(err)53 }54 h := &HappyAst{55 FileSet: fset,56 Ast: astNodes,57 }58 return h59}60func ParseFromCode(srccode string) *HappyAst {61 fset = token.NewFileSet()62 //astNodes, err := parser.ParseFile(fset, codeFile, nil,parser.ParseComments)63 astNodes, err := parser.ParseFile(fset, "", srccode, parser.ParseComments)64 if err != nil {65 panic(err)66 }67 h := &HappyAst{68 FileSet: fset,69 Ast: astNodes,70 }71 return h72}73// 根据参数查找节点位置74// name: 节点名称,不支持模糊查询75// tokenType: token.go规定的宏变量, ast.Ident,ast.BasicLit等等76// tokenKind: 节点种类,var,int,string等77// lineStart: 位置范围查询的开始,-1表示忽略78// lineEnd: 位置返回查询的截止,-1表示忽略79func (h HappyAst) PosOfNode(name string, tokenType string, tokenKind string, lineStart int, lineEnd int) (pos []token.Pos) {80 ast.Inspect(h.Ast, func(node ast.Node) bool {81 xname := ""82 xtype := ""83 xline := 084 xkind := ""85 switch x := node.(type) {86 case *ast.Ident:87 xname = x.Name88 xtype = TYPE_IDENT89 xline = h.Position(x.Pos()).Line90 xkind = ""91 if x.Obj != nil {92 xkind = x.Obj.Kind.String()93 }94 case *ast.BasicLit:95 xname = x.Value96 xtype = TYPE_BASICLIT97 xline = h.Position(x.Pos()).Line98 xkind = x.Kind.String()99 }100 // filter101 if name != "" && xname != name {102 return true103 }104 if tokenType != "" && xtype != tokenType {105 return true106 }107 if tokenKind != "" && xkind != tokenKind {108 return true109 }110 if lineStart >= 0 && xline < lineStart {111 return true112 }113 if lineEnd >= 0 && xline > lineEnd {114 return true115 }116 pos = append(pos, node.Pos())117 return true118 })119 return pos120}121func (h HappyAst) NodeByPos(pos token.Pos) (ret ast.Node) {122 if pos == token.NoPos {123 return nil124 }125 ast.Inspect(h.Ast, func(node ast.Node) bool {126 switch x := node.(type) {127 case *ast.Ident:128 if !node.Pos().IsValid() {129 return true130 }131 if node.Pos() == pos {132 ret = x133 return false134 }135 case *ast.BasicLit:136 if !node.Pos().IsValid() {137 return true138 }139 if x.Pos() == pos {140 ret = x141 return false142 }143 case *ast.File:144 if !node.Pos().IsValid() {145 return true146 }147 if x.Pos() == pos {148 ret = x149 return false150 }151 case *ast.ImportSpec:152 if !node.Pos().IsValid() {153 return true154 }155 if x.Pos() == pos {156 ret = x157 return false158 }159 case *ast.Package:160 if !node.Pos().IsValid() {161 return true162 }163 if x.Pos() == pos {164 ret = x165 return false166 }167 case *ast.AssignStmt:168 if !node.Pos().IsValid() {169 return true170 }171 if x.Pos() == pos {172 ret = x173 return false174 }175 case *ast.RangeStmt:176 if !node.Pos().IsValid() {177 return true178 }179 if x.Pos() == pos {180 ret = x181 return false182 }183 case *ast.BranchStmt:184 if !node.Pos().IsValid() {185 return true186 }187 if x.Pos() == pos {188 ret = x189 return false190 }191 case *ast.BinaryExpr:192 if !node.Pos().IsValid() {193 return true194 }195 if x.Pos() == pos {196 ret = x197 return false198 }199 case *ast.IncDecStmt:200 if !node.Pos().IsValid() {201 return true202 }203 if x.Pos() == pos {204 ret = x205 return false206 }207 case *ast.ForStmt:208 if !node.Pos().IsValid() {209 return true210 }211 if x.Pos() == pos {212 ret = x213 return false214 }215 case *ast.SelectorExpr:216 if !node.Pos().IsValid() {217 return true218 }219 if x.Pos() == pos {220 ret = x221 return false222 }223 case *ast.CallExpr:224 if !node.Pos().IsValid() {225 return true226 }227 if x.Pos() == pos {228 ret = x229 return false230 }231 case *ast.ReturnStmt:232 if !node.Pos().IsValid() {233 return true234 }235 if x.Pos() == pos {236 ret = x237 return false238 }239 case *ast.BlockStmt:240 if !node.Pos().IsValid() {241 return true242 }243 if x.Pos() == pos {244 ret = x245 return false246 }247 case *ast.IfStmt:248 if !node.Pos().IsValid() {249 return true250 }251 if x.Pos() == pos {252 ret = x253 return false254 }255 case *ast.InterfaceType:256 if !node.Pos().IsValid() {257 return true258 }259 if x.Pos() == pos {260 ret = x261 return false262 }263 case *ast.FuncType:264 if !node.Pos().IsValid() {265 return true266 }267 if x.Pos() == pos {268 ret = x269 return false270 }271 case *ast.ChanType:272 if !node.Pos().IsValid() {273 return true274 }275 if x.Pos() == pos {276 ret = x277 return false278 }279 case *ast.MapType:280 if !node.Pos().IsValid() {281 return true282 }283 if x.Pos() == pos {284 ret = x285 return false286 }287 case *ast.StructType:288 if !node.Pos().IsValid() {289 return true290 }291 if x.Pos() == pos {292 ret = x293 return false294 }295 case *ast.ArrayType:296 if !node.Pos().IsValid() {297 return true298 }299 if x.Pos() == pos {300 ret = x301 return false302 }303 case *ast.TypeSpec:304 if !node.Pos().IsValid() {305 return true306 }307 if x.Pos() == pos {308 ret = x309 return false310 }311 case *ast.GenDecl:312 if !node.Pos().IsValid() {313 return true314 }315 if x.Pos() == pos {316 ret = x317 return false318 }319 case *ast.UnaryExpr:320 if !node.Pos().IsValid() {321 return true322 }323 if x.Pos() == pos {324 ret = x325 return false326 }327 case *ast.ValueSpec:328 if !node.Pos().IsValid() {329 return true330 }331 if x.Pos() == pos {332 ret = x333 return false334 }335 case *ast.DeclStmt:336 if !node.Pos().IsValid() {337 return true338 }339 if x.Pos() == pos {340 ret = x341 return false342 }343 case *ast.FuncDecl:344 if !node.Pos().IsValid() {345 return true346 }347 if x.Pos() == pos {348 ret = x349 return false350 }351 case *ast.KeyValueExpr:352 if !node.Pos().IsValid() {353 return true354 }355 if x.Pos() == pos {356 ret = x357 return false358 }359 case *ast.BadDecl:360 if !node.Pos().IsValid() {361 return true362 }363 if x.Pos() == pos {364 ret = x365 return false366 }367 case *ast.BadExpr:368 if !node.Pos().IsValid() {369 return true370 }371 if x.Pos() == pos {372 ret = x373 return false374 }375 case *ast.CaseClause:376 if !node.Pos().IsValid() {377 return true378 }379 if x.Pos() == pos {380 ret = x381 return false382 }383 case *ast.CommClause:384 if !node.Pos().IsValid() {385 return true386 }387 if x.Pos() == pos {388 ret = x389 return false390 }391 case *ast.CompositeLit:392 if !node.Pos().IsValid() {393 return true394 }395 if x.Pos() == pos {396 ret = x397 return false398 }399 case *ast.DeferStmt:400 if !node.Pos().IsValid() {401 return true402 }403 if x.Pos() == pos {404 ret = x405 return false406 }407 case *ast.Ellipsis:408 if !node.Pos().IsValid() {409 return true410 }411 if x.Pos() == pos {412 ret = x413 return false414 }415 case *ast.EmptyStmt:416 if !node.Pos().IsValid() {417 return true418 }419 if x.Pos() == pos {420 ret = x421 return false422 }423 case *ast.ExprStmt:424 if !node.Pos().IsValid() {425 return true426 }427 if x.Pos() == pos {428 ret = x429 return false430 }431 case *ast.Field:432 if !node.Pos().IsValid() {433 return true434 }435 if x.Pos() == pos {436 ret = x437 return false438 }439 case *ast.FieldList:440 if !node.Pos().IsValid() {441 return true442 }443 if x.Pos() == pos {444 ret = x445 return false446 }447 case *ast.SwitchStmt:448 if !node.Pos().IsValid() {449 return true450 }451 if x.Pos() == pos {452 ret = x453 return false454 }455 case *ast.TypeAssertExpr:456 if !node.Pos().IsValid() {457 return true458 }459 if x.Pos() == pos {460 ret = x461 return false462 }463 case *ast.TypeSwitchStmt:464 if !node.Pos().IsValid() {465 return true466 }467 if x.Pos() == pos {468 ret = x469 return false470 }471 case *ast.StarExpr:472 if !node.Pos().IsValid() {473 return true474 }475 if x.Pos() == pos {476 ret = x477 return false478 }479 case *ast.SelectStmt:480 if !node.Pos().IsValid() {481 return true482 }483 if x.Pos() == pos {484 ret = x485 return false486 }487 case *ast.IndexExpr:488 if !node.Pos().IsValid() {489 return true490 }491 if x.Pos() == pos {492 ret = x493 return false494 }495 case *ast.LabeledStmt:496 if !node.Pos().IsValid() {497 return true498 }499 if x.Pos() == pos {500 ret = x501 return false502 }503 case *ast.GoStmt:504 if !node.Pos().IsValid() {505 return true506 }507 if x.Pos() == pos {508 ret = x509 return false510 }511 case *ast.SendStmt:512 if !node.Pos().IsValid() {513 return true514 }515 if x.Pos() == pos {516 ret = x517 return false518 }519 case *ast.ParenExpr:520 if !node.Pos().IsValid() {521 return true522 }523 if x.Pos() == pos {524 ret = x525 return false526 }527 case *ast.SliceExpr:528 if !node.Pos().IsValid() {529 return true530 }531 if x.Pos() == pos {532 ret = x533 return false534 }535 default:536 return true537 }538 return true539 })540 return ret541}...

Full Screen

Full Screen

pos

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)5 if err != nil {6 fmt.Println(err)7 }8 ast.Inspect(f, func(n ast.Node) bool {9 if n != nil {10 pos := fset.Position(n.Pos())11 fmt.Println("line:", pos.Line, "col:", pos.Column)12 }13 })14}

Full Screen

Full Screen

pos

Using AI Code Generation

copy

Full Screen

1import (2func main() {3import "fmt"4func main() {5 fmt.Println("Hello, World!")6}`7 fset := token.NewFileSet()8 f, err := parser.ParseFile(fset, "hello.go", src, 0)9 if err != nil {10 fmt.Println(err)11 }12 for _, s := range f.Decls {13 switch d := s.(type) {14 for _, spec := range d.Specs {15 switch s := spec.(type) {16 fmt.Println(fset.Position(s.Pos()))17 fmt.Println(fset.Position(s.End()))18 }19 }20 }21 }22}23import (24func main() {25import "fmt"26func main() {27 fmt.Println("Hello, World!")28}`29 fset := token.NewFileSet()30 f, err := parser.ParseFile(fset, "hello.go", src, 0)31 if err != nil {32 fmt.Println(err)33 }34 for _, s := range f.Decls {35 switch d := s.(type) {36 for _, spec := range d.Specs {37 switch s := spec.(type) {38 fmt.Println(fset.Position(s.Pos()))39 fmt.Println(fset.Position(s.End()))40 }41 }42 }43 }44}45import (

Full Screen

Full Screen

pos

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 f, err := parser.ParseFile(fset, "2.go", nil, parser.ImportsOnly)5 if err != nil {6 fmt.Println(err)7 }8 for _, s := range f.Imports {9 fmt.Println(fset.Position(s.Pos()), "-", fset.Position(s.End()))10 }11}12type Decl interface {13 declNode()14}15type GenDecl struct {16}17The ast.ImportSpec struct describes an import declaration:18type ImportSpec struct {19}

Full Screen

Full Screen

pos

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)5 if err != nil {6 panic(err)7 }8 ast.Inspect(f, func(n ast.Node) bool {9 if n != nil {10 fmt.Println(n.Pos())11 }12 })13}

Full Screen

Full Screen

pos

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 file, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)5 if err != nil {6 log.Fatal(err)7 }8 for _, decl := range file.Decls {9 switch decl := decl.(type) {10 if decl.Tok == token.IMPORT {11 fmt.Println("Import found")12 fmt.Println("Import line number: ", fset.Position(decl.Pos()).Line)13 }14 }15 }16}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful