Best Syzkaller code snippet using ast.String
gen.go
Source:gen.go
1package main2import (3 "fmt"4 "go/ast"5 "go/parser"6 "go/printer"7 "go/token"8 "os"9 "strings"10)11func getexprs(e ast.Expr) string {12 if lit, ok := e.(*ast.BasicLit); ok {13 return lit.Value14 }15 if ident, ok := e.(*ast.Ident); ok {16 return ident.Name17 }18 return ""19}20func genatomdecl(origfn *ast.FuncDecl, origname, origtag string) (decls []ast.Decl) {21 fieldslist := &ast.FieldList{}22 typespec := &ast.TypeSpec{23 Name: ast.NewIdent(origname),24 Type: &ast.StructType{Fields: fieldslist},25 }26 for _, _stmt := range origfn.Body.List {27 stmt := _stmt.(*ast.ExprStmt)28 callexpr := stmt.X.(*ast.CallExpr)29 typ := callexpr.Fun.(*ast.Ident).Name30 if strings.HasPrefix(typ, "_") {31 if typ == "_unknowns" {32 fieldslist.List = append(fieldslist.List, &ast.Field{33 Names: []*ast.Ident{ast.NewIdent("Unknowns")},34 Type: ast.NewIdent("[]Atom"),35 })36 }37 continue38 }39 name := getexprs(callexpr.Args[0])40 name2 := ""41 if len(callexpr.Args) > 1 {42 name2 = getexprs(callexpr.Args[1])43 }44 len3 := ""45 if len(callexpr.Args) > 2 {46 len3 = getexprs(callexpr.Args[2])47 }48 if strings.HasPrefix(name, "_") {49 continue50 }51 switch typ {52 case "fixed16":53 typ = "float64"54 case "fixed32":55 typ = "float64"56 case "bytesleft":57 typ = "[]byte"58 case "bytes":59 typ = "[" + name2 + "]byte"60 case "uint24":61 typ = "uint32"62 case "time64", "time32":63 typ = "time.Time"64 case "atom":65 typ = "*" + name266 case "atoms":67 typ = "[]*" + name268 case "slice":69 typ = "[]" + name270 case "array":71 typ = "[" + len3 + "]" + name272 }73 fieldslist.List = append(fieldslist.List, &ast.Field{74 Names: []*ast.Ident{ast.NewIdent(name)},75 Type: ast.NewIdent(typ),76 })77 }78 if origtag != "" {79 fieldslist.List = append(fieldslist.List, &ast.Field{80 Type: ast.NewIdent("AtomPos"),81 })82 }83 gendecl := &ast.GenDecl{84 Tok: token.TYPE,85 Specs: []ast.Spec{86 typespec,87 },88 }89 decls = append(decls, gendecl)90 return91}92func typegetlen(typ string) (n int) {93 switch typ {94 case "uint8":95 n = 196 case "uint16":97 n = 298 case "uint24":99 n = 3100 case "uint32":101 n = 4102 case "int16":103 n = 2104 case "int32":105 n = 4106 case "uint64":107 n = 8108 case "time32":109 n = 4110 case "time64":111 n = 8112 case "fixed32":113 n = 4114 case "fixed16":115 n = 2116 }117 return118}119func typegetlens(typ string) string {120 n := typegetlen(typ)121 if n == 0 {122 return "Len" + typ123 } else {124 return fmt.Sprint(n)125 }126}127func typegetvartype(typ string) string {128 switch typ {129 case "uint8":130 return "uint8"131 case "uint16":132 return "uint16"133 case "uint24":134 return "uint32"135 case "uint32":136 return "uint32"137 case "uint64":138 return "uint64"139 case "int16":140 return "int16"141 case "int32":142 return "int32"143 }144 return ""145}146func typegetputfn(typ string) (fn string) {147 fn = typ148 switch typ {149 case "uint8":150 fn = "pio.PutU8"151 case "uint16":152 fn = "pio.PutU16BE"153 case "uint24":154 fn = "pio.PutU24BE"155 case "uint32":156 fn = "pio.PutU32BE"157 case "int16":158 fn = "pio.PutI16BE"159 case "int32":160 fn = "pio.PutI32BE"161 case "uint64":162 fn = "pio.PutU64BE"163 case "time32":164 fn = "PutTime32"165 case "time64":166 fn = "PutTime64"167 case "fixed32":168 fn = "PutFixed32"169 case "fixed16":170 fn = "PutFixed16"171 default:172 fn = "Put" + typ173 }174 return175}176func typegetgetfn(typ string) (fn string) {177 fn = typ178 switch typ {179 case "uint8":180 fn = "pio.U8"181 case "uint16":182 fn = "pio.U16BE"183 case "uint24":184 fn = "pio.U24BE"185 case "uint32":186 fn = "pio.U32BE"187 case "int16":188 fn = "pio.I16BE"189 case "int32":190 fn = "pio.I32BE"191 case "uint64":192 fn = "pio.U64BE"193 case "time32":194 fn = "GetTime32"195 case "time64":196 fn = "GetTime64"197 case "fixed32":198 fn = "GetFixed32"199 case "fixed16":200 fn = "GetFixed16"201 default:202 fn = "Get" + typ203 }204 return205}206func addns(n string) (stmts []ast.Stmt) {207 assign := &ast.AssignStmt{208 Tok: token.ADD_ASSIGN,209 Lhs: []ast.Expr{ast.NewIdent("n")},210 Rhs: []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: n}},211 }212 stmts = append(stmts, assign)213 return214}215func addn(n int) (stmts []ast.Stmt) {216 return addns(fmt.Sprint(n))217}218func simplecall(fun string, args ...string) *ast.ExprStmt {219 _args := []ast.Expr{}220 for _, s := range args {221 _args = append(_args, ast.NewIdent(s))222 }223 return &ast.ExprStmt{224 X: &ast.CallExpr{225 Fun: ast.NewIdent(fun),226 Args: _args,227 },228 }229}230func getxx(typ string, pos, name string, conv bool) (stmts []ast.Stmt) {231 fn := typegetgetfn(typ)232 assign := &ast.AssignStmt{233 Tok: token.ASSIGN,234 Lhs: []ast.Expr{ast.NewIdent(name)},235 Rhs: []ast.Expr{simplecall(fn, "b["+pos+":]").X},236 }237 stmts = append(stmts, assign)238 return239}240func putxx(typ string, pos, name string, conv bool) (stmts []ast.Stmt) {241 if conv {242 name = fmt.Sprintf("%s(%s)", typ, name)243 }244 fn := typegetputfn(typ)245 stmts = append(stmts, simplecall(fn, "b["+pos+":]", name))246 return247}248func putxxadd(fn string, name string, conv bool) (stmts []ast.Stmt) {249 n := typegetlen(fn)250 stmts = append(stmts, putxx(fn, "n", name, conv)...)251 stmts = append(stmts, addn(n)...)252 return253}254func newdecl(origname, name string, params, res []*ast.Field, stmts []ast.Stmt) *ast.FuncDecl {255 return &ast.FuncDecl{256 Recv: &ast.FieldList{257 List: []*ast.Field{258 &ast.Field{259 Names: []*ast.Ident{ast.NewIdent("self")},260 Type: ast.NewIdent(origname),261 },262 },263 },264 Name: ast.NewIdent(name),265 Type: &ast.FuncType{266 Params: &ast.FieldList{267 List: params,268 },269 Results: &ast.FieldList{270 List: res,271 },272 },273 Body: &ast.BlockStmt{List: stmts},274 }275}276func getstructputgetlenfn(origfn *ast.FuncDecl, origname string) (decls []ast.Decl) {277 getstmts := []ast.Stmt{}278 putstmts := []ast.Stmt{}279 totlen := 0280 for _, _stmt := range origfn.Body.List {281 stmt := _stmt.(*ast.ExprStmt)282 callexpr := stmt.X.(*ast.CallExpr)283 typ := callexpr.Fun.(*ast.Ident).Name284 name := getexprs(callexpr.Args[0])285 getstmts = append(getstmts, getxx(typ, fmt.Sprint(totlen), "self."+name, false)...)286 putstmts = append(putstmts, putxx(typ, fmt.Sprint(totlen), "self."+name, false)...)287 totlen += typegetlen(typ)288 }289 getstmts = append(getstmts, &ast.ReturnStmt{})290 decls = append(decls, &ast.FuncDecl{291 Name: ast.NewIdent("Get" + origname),292 Type: &ast.FuncType{293 Params: &ast.FieldList{294 List: []*ast.Field{295 &ast.Field{Names: []*ast.Ident{ast.NewIdent("b")}, Type: ast.NewIdent("[]byte")},296 },297 },298 Results: &ast.FieldList{299 List: []*ast.Field{300 &ast.Field{Names: []*ast.Ident{ast.NewIdent("self")}, Type: ast.NewIdent(origname)},301 },302 },303 },304 Body: &ast.BlockStmt{List: getstmts},305 })306 decls = append(decls, &ast.FuncDecl{307 Name: ast.NewIdent("Put" + origname),308 Type: &ast.FuncType{309 Params: &ast.FieldList{310 List: []*ast.Field{311 &ast.Field{Names: []*ast.Ident{ast.NewIdent("b")}, Type: ast.NewIdent("[]byte")},312 &ast.Field{Names: []*ast.Ident{ast.NewIdent("self")}, Type: ast.NewIdent(origname)},313 },314 },315 },316 Body: &ast.BlockStmt{List: putstmts},317 })318 decls = append(decls, &ast.GenDecl{319 Tok: token.CONST,320 Specs: []ast.Spec{321 &ast.ValueSpec{322 Names: []*ast.Ident{ast.NewIdent("Len" + origname)},323 Values: []ast.Expr{ast.NewIdent(fmt.Sprint(totlen))},324 },325 },326 })327 return328}329func cc4decls(name string) (decls []ast.Decl) {330 constdecl := &ast.GenDecl{331 Tok: token.CONST,332 Specs: []ast.Spec{333 &ast.ValueSpec{334 Names: []*ast.Ident{335 ast.NewIdent(strings.ToUpper(name)),336 },337 Values: []ast.Expr{338 &ast.CallExpr{339 Fun: ast.NewIdent("Tag"),340 Args: []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("0x%x", []byte(name))}},341 },342 },343 },344 },345 }346 decls = append(decls, constdecl)347 return348}349func codeclonereplace(stmts []ast.Stmt, doit []ast.Stmt) (out []ast.Stmt) {350 out = append([]ast.Stmt(nil), stmts...)351 for i := range out {352 if ifstmt, ok := out[i].(*ast.IfStmt); ok {353 newifstmt := &ast.IfStmt{354 Cond: ifstmt.Cond,355 Body: &ast.BlockStmt{356 List: codeclonereplace(ifstmt.Body.List, doit),357 },358 }359 if ifstmt.Else != nil {360 newifstmt.Else = &ast.BlockStmt{361 List: codeclonereplace(ifstmt.Else.(*ast.BlockStmt).List, doit),362 }363 }364 out[i] = newifstmt365 } else if exprstmt, ok := out[i].(*ast.ExprStmt); ok {366 if callexpr, ok := exprstmt.X.(*ast.CallExpr); ok {367 if getexprs(callexpr.Fun) == "doit" {368 out[i] = &ast.BlockStmt{List: doit}369 }370 }371 }372 }373 return374}375func getatommarshalfn(origfn *ast.FuncDecl,376 origname, origtag string,377 tagnamemap map[string]string,378) (decls []ast.Decl) {379 marstmts := []ast.Stmt{}380 unmarstmts := []ast.Stmt{}381 lenstmts := []ast.Stmt{}382 childrenstmts := []ast.Stmt{}383 parseerrreturn := func(debug string) (stmts []ast.Stmt) {384 return []ast.Stmt{385 &ast.AssignStmt{386 Tok: token.ASSIGN,387 Lhs: []ast.Expr{ast.NewIdent("err")},388 Rhs: []ast.Expr{ast.NewIdent(fmt.Sprintf(`parseErr("%s", n+offset, err)`, debug))},389 },390 &ast.ReturnStmt{},391 }392 }393 callmarshal := func(name string) (stmts []ast.Stmt) {394 callexpr := &ast.CallExpr{395 Fun: ast.NewIdent(name + ".Marshal"),396 Args: []ast.Expr{ast.NewIdent("b[n:]")},397 }398 assign := &ast.AssignStmt{399 Tok: token.ADD_ASSIGN,400 Lhs: []ast.Expr{ast.NewIdent("n")},401 Rhs: []ast.Expr{callexpr},402 }403 stmts = append(stmts, assign)404 return405 }406 callputstruct := func(typ, name string) (stmts []ast.Stmt) {407 stmts = append(stmts, &ast.ExprStmt{408 X: &ast.CallExpr{409 Fun: ast.NewIdent(typegetputfn(typ)),410 Args: []ast.Expr{ast.NewIdent("b[n:]"), ast.NewIdent(name)},411 },412 })413 stmts = append(stmts, &ast.AssignStmt{414 Tok: token.ADD_ASSIGN,415 Lhs: []ast.Expr{ast.NewIdent("n")},416 Rhs: []ast.Expr{ast.NewIdent(typegetlens(typ))},417 })418 return419 }420 calllenstruct := func(typ, name string) (stmts []ast.Stmt) {421 inc := typegetlens(typ) + "*len(" + name + ")"422 stmts = append(stmts, &ast.AssignStmt{423 Tok: token.ADD_ASSIGN,424 Lhs: []ast.Expr{ast.NewIdent("n")},425 Rhs: []ast.Expr{ast.NewIdent(inc)},426 })427 return428 }429 calllen := func(name string) (stmts []ast.Stmt) {430 callexpr := &ast.CallExpr{431 Fun: ast.NewIdent(name + ".Len"),432 Args: []ast.Expr{},433 }434 assign := &ast.AssignStmt{435 Tok: token.ADD_ASSIGN,436 Lhs: []ast.Expr{ast.NewIdent("n")},437 Rhs: []ast.Expr{callexpr},438 }439 stmts = append(stmts, assign)440 return441 }442 foreach := func(name, field string, block []ast.Stmt) (stmts []ast.Stmt) {443 rangestmt := &ast.RangeStmt{444 Key: ast.NewIdent("_"),445 Value: ast.NewIdent(name),446 Body: &ast.BlockStmt{447 List: block,448 },449 Tok: token.DEFINE,450 X: ast.NewIdent(field),451 }452 stmts = append(stmts, rangestmt)453 return454 }455 foreachatom := func(field string, block []ast.Stmt) (stmts []ast.Stmt) {456 return foreach("atom", field, block)457 }458 foreachentry := func(field string, block []ast.Stmt) (stmts []ast.Stmt) {459 return foreach("entry", field, block)460 }461 foreachi := func(field string, block []ast.Stmt) (stmts []ast.Stmt) {462 rangestmt := &ast.RangeStmt{463 Key: ast.NewIdent("i"),464 Body: &ast.BlockStmt{465 List: block,466 },467 Tok: token.DEFINE,468 X: ast.NewIdent(field),469 }470 stmts = append(stmts, rangestmt)471 return472 }473 foreachunknowns := func(block []ast.Stmt) (stmts []ast.Stmt) {474 return foreachatom("self.Unknowns", block)475 }476 declvar := func(name, typ string) (stmts []ast.Stmt) {477 stmts = append(stmts, &ast.DeclStmt{478 Decl: &ast.GenDecl{479 Tok: token.VAR,480 Specs: []ast.Spec{481 &ast.ValueSpec{482 Names: []*ast.Ident{483 ast.NewIdent(typ),484 },485 Type: ast.NewIdent(name),486 },487 },488 },489 })490 return491 }492 makeslice := func(name, typ, size string) (stmts []ast.Stmt) {493 stmts = append(stmts, &ast.ExprStmt{494 X: ast.NewIdent(fmt.Sprintf("%s = make([]%s, %s)", name, typ, size)),495 })496 return497 }498 simpleassign := func(tok token.Token, l, r string) *ast.AssignStmt {499 return &ast.AssignStmt{500 Tok: tok,501 Lhs: []ast.Expr{ast.NewIdent(l)},502 Rhs: []ast.Expr{ast.NewIdent(r)},503 }504 }505 struct2tag := func(s string) string {506 name := tagnamemap[s]507 return name508 }509 foreachatomsappendchildren := func(field string) (stmts []ast.Stmt) {510 return foreachatom(field, []ast.Stmt{511 simpleassign(token.ASSIGN, "r", "append(r, atom)"),512 })513 }514 var hasunknowns bool515 var atomnames []string516 var atomtypes []string517 var atomarrnames []string518 var atomarrtypes []string519 slicenamemap := map[string]string{}520 unmarshalatom := func(typ, init string) (stmts []ast.Stmt) {521 return []ast.Stmt{522 &ast.AssignStmt{Tok: token.DEFINE,523 Lhs: []ast.Expr{ast.NewIdent("atom")}, Rhs: []ast.Expr{ast.NewIdent("&" + typ + "{" + init + "}")},524 },525 &ast.IfStmt{526 Init: &ast.AssignStmt{527 Tok: token.ASSIGN,528 Lhs: []ast.Expr{ast.NewIdent("_"), ast.NewIdent("err")},529 Rhs: []ast.Expr{ast.NewIdent("atom.Unmarshal(b[n:n+size], offset+n)")},530 },531 Cond: ast.NewIdent("err != nil"),532 Body: &ast.BlockStmt{List: parseerrreturn(struct2tag(typ))},533 },534 }535 }536 unmrashalatoms := func() (stmts []ast.Stmt) {537 blocks := []ast.Stmt{}538 blocks = append(blocks, &ast.AssignStmt{Tok: token.DEFINE, Lhs: []ast.Expr{ast.NewIdent("tag")},539 Rhs: []ast.Expr{ast.NewIdent("Tag(pio.U32BE(b[n+4:]))")},540 })541 blocks = append(blocks, &ast.AssignStmt{Tok: token.DEFINE, Lhs: []ast.Expr{ast.NewIdent("size")},542 Rhs: []ast.Expr{ast.NewIdent("int(pio.U32BE(b[n:]))")},543 })544 blocks = append(blocks, &ast.IfStmt{545 Cond: ast.NewIdent("len(b) < n+size"),546 Body: &ast.BlockStmt{List: parseerrreturn("TagSizeInvalid")},547 })548 cases := []ast.Stmt{}549 for i, atom := range atomnames {550 cases = append(cases, &ast.CaseClause{551 List: []ast.Expr{ast.NewIdent(strings.ToUpper(struct2tag(atomtypes[i])))},552 Body: []ast.Stmt{&ast.BlockStmt{553 List: append(unmarshalatom(atomtypes[i], ""), simpleassign(token.ASSIGN, "self."+atom, "atom")),554 }},555 })556 }557 for i, atom := range atomarrnames {558 selfatom := "self." + atom559 cases = append(cases, &ast.CaseClause{560 List: []ast.Expr{ast.NewIdent(strings.ToUpper(struct2tag(atomarrtypes[i])))},561 Body: []ast.Stmt{&ast.BlockStmt{562 List: append(unmarshalatom(atomarrtypes[i], ""),563 simpleassign(token.ASSIGN, selfatom, "append("+selfatom+", atom)")),564 }},565 })566 }567 if hasunknowns {568 init := "Tag_: tag, Data: b[n:n+size]"569 selfatom := "self.Unknowns"570 cases = append(cases, &ast.CaseClause{571 Body: []ast.Stmt{&ast.BlockStmt{572 List: append(unmarshalatom("Dummy", init), simpleassign(token.ASSIGN, selfatom, "append("+selfatom+", atom)")),573 }},574 })575 }576 blocks = append(blocks, &ast.SwitchStmt{577 Tag: ast.NewIdent("tag"),578 Body: &ast.BlockStmt{List: cases},579 })580 blocks = append(blocks, addns("size")...)581 stmts = append(stmts, &ast.ForStmt{582 Cond: ast.NewIdent("n+8 < len(b)"),583 Body: &ast.BlockStmt{List: blocks},584 })585 return586 }587 marshalwrapstmts := func() (stmts []ast.Stmt) {588 stmts = append(stmts, putxx("uint32", "4", strings.ToUpper(origtag), true)...)589 stmts = append(stmts, addns("self.marshal(b[8:])+8")...)590 stmts = append(stmts, putxx("uint32", "0", "n", true)...)591 stmts = append(stmts, &ast.ReturnStmt{})592 return593 }594 ifnotnil := func(name string, block []ast.Stmt) (stmts []ast.Stmt) {595 stmts = append(stmts, &ast.IfStmt{596 Cond: &ast.BinaryExpr{597 X: ast.NewIdent(name),598 Op: token.NEQ,599 Y: ast.NewIdent("nil"),600 },601 Body: &ast.BlockStmt{List: block},602 })603 return604 }605 getchildrennr := func(name string) (stmts []ast.Stmt) {606 stmts = append(stmts, &ast.AssignStmt{607 Tok: token.DEFINE,608 Lhs: []ast.Expr{ast.NewIdent(name)},609 Rhs: []ast.Expr{ast.NewIdent("0")},610 })611 for _, atom := range atomnames {612 stmts = append(stmts, ifnotnil("self."+atom, []ast.Stmt{613 &ast.IncDecStmt{X: ast.NewIdent(name), Tok: token.INC},614 })...)615 }616 if hasunknowns {617 assign := &ast.AssignStmt{618 Tok: token.ADD_ASSIGN,619 Lhs: []ast.Expr{ast.NewIdent("_childrenNR")},620 Rhs: []ast.Expr{ast.NewIdent("len(self.Unknowns)")},621 }622 stmts = append(stmts, assign)623 }624 return625 }626 checkcurlen := func(inc, debug string) (stmts []ast.Stmt) {627 stmts = append(stmts, &ast.IfStmt{628 Cond: &ast.BinaryExpr{629 X: ast.NewIdent("len(b)"),630 Op: token.LSS,631 Y: ast.NewIdent("n+" + inc),632 },633 Body: &ast.BlockStmt{List: parseerrreturn(debug)},634 })635 return636 }637 checklendo := func(typ, name, debug string) (stmts []ast.Stmt) {638 stmts = append(stmts, checkcurlen(typegetlens(typ), debug)...)639 stmts = append(stmts, getxx(typ, "n", name, false)...)640 stmts = append(stmts, addns(typegetlens(typ))...)641 return642 }643 checkstructlendo := func(typ, name, debug string,644 foreach func(string, []ast.Stmt) []ast.Stmt,645 ) (stmts []ast.Stmt) {646 inc := typegetlens(typ) + "*len(" + name + ")"647 stmts = append(stmts, checkcurlen(inc, debug)...)648 stmts = append(stmts, foreach(name, append(649 []ast.Stmt{650 &ast.AssignStmt{651 Tok: token.ASSIGN,652 Lhs: []ast.Expr{653 ast.NewIdent(name + "[i]"),654 },655 Rhs: []ast.Expr{656 &ast.CallExpr{657 Fun: ast.NewIdent(typegetgetfn(typ)),658 Args: []ast.Expr{ast.NewIdent("b[n:]")},659 },660 },661 },662 },663 addns(typegetlens(typ))...,664 ))...)665 return666 }667 checklencopy := func(name string) (stmts []ast.Stmt) {668 lens := fmt.Sprintf("len(self.%s)", name)669 stmts = append(stmts, checkcurlen(lens, name)...)670 stmts = append(stmts, simplecall("copy", fmt.Sprintf("self.%s[:]", name), "b[n:]"))671 stmts = append(stmts, addns(lens)...)672 return673 }674 appendcode := func(args []ast.Expr,675 marstmts *[]ast.Stmt, lenstmts *[]ast.Stmt, unmarstmts *[]ast.Stmt,676 defmarstmts []ast.Stmt, deflenstmts []ast.Stmt, defunmarstmts []ast.Stmt,677 ) {678 bodylist := func(i int, doit []ast.Stmt) []ast.Stmt {679 return codeclonereplace(args[i].(*ast.FuncLit).Body.List, doit)680 }681 if len(args) == 1 {682 *marstmts = append(*marstmts, bodylist(0, defmarstmts)...)683 *lenstmts = append(*lenstmts, bodylist(0, deflenstmts)...)684 *unmarstmts = append(*unmarstmts, bodylist(0, defunmarstmts)...)685 } else {686 *marstmts = append(*marstmts, bodylist(0, defmarstmts)...)687 *lenstmts = append(*lenstmts, bodylist(1, deflenstmts)...)688 *unmarstmts = append(*unmarstmts, bodylist(2, defunmarstmts)...)689 }690 }691 getdefaultstmts := func(692 typ, name, name2 string,693 marstmts *[]ast.Stmt, lenstmts *[]ast.Stmt,694 unmarstmts *[]ast.Stmt, childrenstmts *[]ast.Stmt,695 ) {696 switch typ {697 case "bytes", "bytesleft":698 *marstmts = append(*marstmts, simplecall("copy", "b[n:]", "self."+name+"[:]"))699 *marstmts = append(*marstmts, addns(fmt.Sprintf("len(self.%s[:])", name))...)700 *lenstmts = append(*lenstmts, addns(fmt.Sprintf("len(self.%s[:])", name))...)701 if typ == "bytes" {702 *unmarstmts = append(*unmarstmts, checklencopy(name)...)703 } else {704 *unmarstmts = append(*unmarstmts, simpleassign(token.ASSIGN, "self."+name, "b[n:]"))705 *unmarstmts = append(*unmarstmts, addns("len(b[n:])")...)706 }707 case "array":708 *marstmts = append(*marstmts, foreachentry("self."+name, callputstruct(name2, "entry"))...)709 *lenstmts = append(*lenstmts, calllenstruct(name2, "self."+name+"[:]")...)710 *unmarstmts = append(*unmarstmts, checkstructlendo(name2, "self."+name, name, foreachi)...)711 case "atoms":712 *marstmts = append(*marstmts, foreachatom("self."+name, callmarshal("atom"))...)713 *lenstmts = append(*lenstmts, foreachatom("self."+name, calllen("atom"))...)714 *childrenstmts = append(*childrenstmts, foreachatomsappendchildren("self."+name)...)715 case "slice":716 *marstmts = append(*marstmts, foreachentry("self."+name, callputstruct(name2, "entry"))...)717 *lenstmts = append(*lenstmts, calllenstruct(name2, "self."+name)...)718 *unmarstmts = append(*unmarstmts, checkstructlendo(name2, "self."+name, name2, foreachi)...)719 case "atom":720 *marstmts = append(*marstmts, ifnotnil("self."+name, callmarshal("self."+name))...)721 *lenstmts = append(*lenstmts, ifnotnil("self."+name, calllen("self."+name))...)722 *childrenstmts = append(*childrenstmts, ifnotnil("self."+name, []ast.Stmt{723 simpleassign(token.ASSIGN, "r", fmt.Sprintf("append(r, %s)", "self."+name)),724 })...)725 default:726 *marstmts = append(*marstmts, putxxadd(typ, "self."+name, false)...)727 *lenstmts = append(*lenstmts, addn(typegetlen(typ))...)728 *unmarstmts = append(*unmarstmts, checklendo(typ, "self."+name, name)...)729 }730 }731 for _, _stmt := range origfn.Body.List {732 stmt := _stmt.(*ast.ExprStmt)733 callexpr := stmt.X.(*ast.CallExpr)734 typ := callexpr.Fun.(*ast.Ident).Name735 if typ == "_unknowns" {736 hasunknowns = true737 } else if typ == "atom" {738 name := getexprs(callexpr.Args[0])739 name2 := getexprs(callexpr.Args[1])740 atomnames = append(atomnames, name)741 atomtypes = append(atomtypes, name2)742 } else if typ == "atoms" {743 name := getexprs(callexpr.Args[0])744 name2 := getexprs(callexpr.Args[1])745 atomarrnames = append(atomarrnames, name)746 atomarrtypes = append(atomarrtypes, name2)747 } else if typ == "slice" {748 name := getexprs(callexpr.Args[0])749 name2 := getexprs(callexpr.Args[1])750 slicenamemap[name] = name2751 }752 }753 lenstmts = append(lenstmts, addn(8)...)754 unmarstmts = append(unmarstmts, simplecall("(&self.AtomPos).setPos", "offset", "len(b)"))755 unmarstmts = append(unmarstmts, addn(8)...)756 for _, _stmt := range origfn.Body.List {757 stmt := _stmt.(*ast.ExprStmt)758 callexpr := stmt.X.(*ast.CallExpr)759 typ := callexpr.Fun.(*ast.Ident).Name760 name := ""761 if len(callexpr.Args) > 0 {762 name = getexprs(callexpr.Args[0])763 }764 name2 := ""765 if len(callexpr.Args) > 1 {766 name2 = getexprs(callexpr.Args[1])767 }768 var defmarstmts, deflenstmts, defunmarstmts, defchildrenstmts []ast.Stmt769 getdefaultstmts(typ, name, name2,770 &defmarstmts, &deflenstmts, &defunmarstmts, &defchildrenstmts)771 var code []ast.Expr772 for _, arg := range callexpr.Args {773 if fn, ok := arg.(*ast.CallExpr); ok {774 if getexprs(fn.Fun) == "_code" {775 code = fn.Args776 }777 }778 }779 if code != nil {780 appendcode(code,781 &marstmts, &lenstmts, &unmarstmts,782 defmarstmts, deflenstmts, defunmarstmts,783 )784 continue785 }786 if strings.HasPrefix(typ, "_") {787 if typ == "_unknowns" {788 marstmts = append(marstmts, foreachunknowns(callmarshal("atom"))...)789 lenstmts = append(lenstmts, foreachunknowns(calllen("atom"))...)790 childrenstmts = append(childrenstmts, simpleassign(token.ASSIGN, "r", "append(r, self.Unknowns...)"))791 }792 if typ == "_skip" {793 marstmts = append(marstmts, addns(name)...)794 lenstmts = append(lenstmts, addns(name)...)795 unmarstmts = append(unmarstmts, addns(name)...)796 }797 if typ == "_code" {798 appendcode(callexpr.Args,799 &marstmts, &lenstmts, &unmarstmts,800 defmarstmts, deflenstmts, defunmarstmts,801 )802 }803 continue804 }805 if name == "_childrenNR" {806 marstmts = append(marstmts, getchildrennr(name)...)807 marstmts = append(marstmts, putxxadd(typ, name, true)...)808 lenstmts = append(lenstmts, addn(typegetlen(typ))...)809 unmarstmts = append(unmarstmts, addn(typegetlen(typ))...)810 continue811 }812 if strings.HasPrefix(name, "_len_") {813 field := name[len("_len_"):]814 marstmts = append(marstmts, putxxadd(typ, "len(self."+field+")", true)...)815 lenstmts = append(lenstmts, addn(typegetlen(typ))...)816 unmarstmts = append(unmarstmts, declvar(typegetvartype(typ), name)...)817 unmarstmts = append(unmarstmts, getxx(typ, "n", name, false)...)818 unmarstmts = append(unmarstmts, addn(typegetlen(typ))...)819 unmarstmts = append(unmarstmts, makeslice("self."+field, slicenamemap[field], name)...)820 continue821 }822 marstmts = append(marstmts, defmarstmts...)823 lenstmts = append(lenstmts, deflenstmts...)824 unmarstmts = append(unmarstmts, defunmarstmts...)825 childrenstmts = append(childrenstmts, defchildrenstmts...)826 }827 if len(atomnames) > 0 || len(atomarrnames) > 0 || hasunknowns {828 unmarstmts = append(unmarstmts, unmrashalatoms()...)829 }830 marstmts = append(marstmts, &ast.ReturnStmt{})831 lenstmts = append(lenstmts, &ast.ReturnStmt{})832 unmarstmts = append(unmarstmts, &ast.ReturnStmt{})833 childrenstmts = append(childrenstmts, &ast.ReturnStmt{})834 decls = append(decls, newdecl(origname, "Marshal", []*ast.Field{835 &ast.Field{Names: []*ast.Ident{ast.NewIdent("b")}, Type: ast.NewIdent("[]byte")},836 }, []*ast.Field{837 &ast.Field{Names: []*ast.Ident{ast.NewIdent("n")}, Type: ast.NewIdent("int")},838 }, marshalwrapstmts()))839 decls = append(decls, newdecl(origname, "marshal", []*ast.Field{840 &ast.Field{Names: []*ast.Ident{ast.NewIdent("b")}, Type: ast.NewIdent("[]byte")},841 }, []*ast.Field{842 &ast.Field{Names: []*ast.Ident{ast.NewIdent("n")}, Type: ast.NewIdent("int")},843 }, marstmts))844 decls = append(decls, newdecl(origname, "Len", []*ast.Field{}, []*ast.Field{845 &ast.Field{Names: []*ast.Ident{ast.NewIdent("n")}, Type: ast.NewIdent("int")},846 }, lenstmts))847 decls = append(decls, newdecl("*"+origname, "Unmarshal", []*ast.Field{848 &ast.Field{Names: []*ast.Ident{ast.NewIdent("b")}, Type: ast.NewIdent("[]byte")},849 &ast.Field{Names: []*ast.Ident{ast.NewIdent("offset")}, Type: ast.NewIdent("int")},850 }, []*ast.Field{851 &ast.Field{Names: []*ast.Ident{ast.NewIdent("n")}, Type: ast.NewIdent("int")},852 &ast.Field{Names: []*ast.Ident{ast.NewIdent("err")}, Type: ast.NewIdent("error")},853 }, unmarstmts))854 decls = append(decls, newdecl(origname, "Children", []*ast.Field{}, []*ast.Field{855 &ast.Field{Names: []*ast.Ident{ast.NewIdent("r")}, Type: ast.NewIdent("[]Atom")},856 }, childrenstmts))857 return858}859func genatoms(filename, outfilename string) {860 // Create the AST by parsing src.861 fset := token.NewFileSet() // positions are relative to fset862 file, err := parser.ParseFile(fset, filename, nil, 0)863 if err != nil {864 panic(err)865 }866 gen := &ast.File{}867 gen.Name = ast.NewIdent("mp4io")868 gen.Decls = []ast.Decl{869 &ast.GenDecl{870 Tok: token.IMPORT,871 Specs: []ast.Spec{872 &ast.ImportSpec{Path: &ast.BasicLit{Kind: token.STRING, Value: `"github.com/aliveyun/vdk/utils/bits/pio"`}},873 },874 },875 &ast.GenDecl{876 Tok: token.IMPORT,877 Specs: []ast.Spec{878 &ast.ImportSpec{Path: &ast.BasicLit{Kind: token.STRING, Value: `"time"`}},879 },880 },881 }882 tagnamemap := map[string]string{}883 tagnamemap["ElemStreamDesc"] = "esds"884 splittagname := func(fnname string) (ok bool, tag, name string) {885 if len(fnname) > 5 && fnname[4] == '_' {886 tag = fnname[0:4]887 tag = strings.Replace(tag, "_", " ", 1)888 name = fnname[5:]889 ok = true890 } else {891 name = fnname892 }893 return894 }895 for _, decl := range file.Decls {896 if fndecl, ok := decl.(*ast.FuncDecl); ok {897 ok, tag, name := splittagname(fndecl.Name.Name)898 if ok {899 tagnamemap[name] = tag900 }901 }902 }903 tagfuncdecl := func(name, tag string) (decls ast.Decl) {904 return newdecl(name, "Tag", []*ast.Field{}, []*ast.Field{905 &ast.Field{Type: ast.NewIdent("Tag")},906 }, []ast.Stmt{907 &ast.ReturnStmt{908 Results: []ast.Expr{ast.NewIdent(strings.ToUpper(tag))}}})909 }910 for k, v := range tagnamemap {911 gen.Decls = append(gen.Decls, cc4decls(v)...)912 gen.Decls = append(gen.Decls, tagfuncdecl(k, v))913 }914 gen.Decls = append(gen.Decls, cc4decls("mdat")...)915 for _, decl := range file.Decls {916 if fndecl, ok := decl.(*ast.FuncDecl); ok {917 ok, tag, name := splittagname(fndecl.Name.Name)918 if ok {919 gen.Decls = append(gen.Decls, genatomdecl(fndecl, name, tag)...)920 gen.Decls = append(gen.Decls, getatommarshalfn(fndecl, name, tag, tagnamemap)...)921 } else {922 gen.Decls = append(gen.Decls, genatomdecl(fndecl, name, tag)...)923 gen.Decls = append(gen.Decls, getstructputgetlenfn(fndecl, name)...)924 }925 }926 }927 outfile, _ := os.Create(outfilename)928 printer.Fprint(outfile, fset, gen)929 outfile.Close()930}931func parse(filename, outfilename string) {932 fset := token.NewFileSet()933 file, err := parser.ParseFile(fset, filename, nil, 0)934 if err != nil {935 panic(err)936 }937 outfile, _ := os.Create(outfilename)938 ast.Fprint(outfile, fset, file, nil)939 outfile.Close()940}941func main() {942 switch os.Args[1] {943 case "parse":944 parse(os.Args[2], os.Args[3])945 case "gen":946 genatoms(os.Args[2], os.Args[3])947 }948}...
String
Using AI Code Generation
1import (2func main() {3func main() {4 fmt.Println("Hello, playground")5}6 f, err := parser.ParseFile(fset, "hello.go", src, 0)7 if err != nil {8 fmt.Println(err)9 }10 ast.Print(fset, f)11}
String
Using AI Code Generation
1import (2func main() {3 fset := token.NewFileSet()4 f, err := parser.ParseFile(fset, "1.go", nil, 0)5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(fset.Position(f.Pos()))9 fmt.Println(fset.Position(f.End()))10 fmt.Println(fset.Position(f.Scope.Pos()))11 fmt.Println(fset.Position(f.Scope.End()))12 fmt.Println(fset.Position(f.Decls[0].Pos()))13 fmt.Println(fset.Position(f.Decls[0].End()))14 fmt.Println(fset.Position(f.Decls[1].Pos()))15 fmt.Println(fset.Position(f.Decls[1].End()))16 fmt.Println(fset.Position(f.Decls[2].Pos()))17 fmt.Println(fset.Position(f.Decls[2].End()))18 fmt.Println(fset.Position(f.Decls[3].Pos()))19 fmt.Println(fset.Position(f.Decls[3].End()))20 fmt.Println(fset.Position(f.Decls[4].Pos()))21 fmt.Println(fset.Position(f.Decls[4].End()))22 fmt.Println(fset.Position(f.Decls[5].Pos()))23 fmt.Println(fset.Position(f.Decls[5].End()))24 fmt.Println(fset.Position(f.Comments[0].Pos()))25 fmt.Println(fset.Position(f.Comments[0].End()))26 fmt.Println(fset.Position(f.Comments[1].Pos()))27 fmt.Println(fset.Position(f.Comments[1].End()))28 fmt.Println(fset.Position(f.Comments[2].Pos()))29 fmt.Println(fset.Position(f.Comments[2].End()))30 fmt.Println(fset.Position(f.Comments[3].Pos()))31 fmt.Println(fset.Position(f.Comments[3].End()))32 fmt.Println(fset.Position(f.Comments[4].Pos()))33 fmt.Println(fset.Position(f.Comments[4].End()))34 fmt.Println(fset.Position(f.Comments[5].Pos()))35 fmt.Println(fset.Position(f.Comments[5].End()))36 fmt.Println(fset.Position(f.Comments[6].Pos()))37 fmt.Println(fset.Position(f.Comments[6].End()))38 fmt.Println(fset.Position(f.Comments[7].Pos()))39 fmt.Println(fset.Position(f.Comments[7].End()))40 fmt.Println(fset.Position(f.Comments[8].Pos()))41 fmt.Println(fset.Position(f.Comments[8].End()))42 fmt.Println(fset.Position(f
String
Using AI Code Generation
1import (2func main() {3 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)4 if err != nil {5 panic(err)6 }7 fmt.Println("Imports:")8 for _, s := range f.Imports {9 fmt.Println(s.Path.Value)10 }11}12import (13func main() {14 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)15 if err != nil {16 panic(err)17 }18 fmt.Println("Comments:")19 for _, s := range f.Comments {20 fmt.Println(s.Text())21 }22}
String
Using AI Code Generation
1import (2func main() {3 fset := token.NewFileSet()4 node, err := parser.ParseFile(fset, "test.go", nil, 0)5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(node)9}10import (11func main() {12 fset := token.NewFileSet()13 node, err := parser.ParseFile(fset, "test.go", nil, 0)14 if err != nil {15 fmt.Println(err)16 }17 ast.Print(fset, node)18}19import (20func main() {21 fset := token.NewFileSet()22 node, err := parser.ParseFile(fset, "test.go", nil, 0)23 if err != nil {24 fmt.Println(err)25 }26 ast.Print(fset, node)27}28import (29func main() {30 fset := token.NewFileSet()31 node, err := parser.ParseFile(fset, "test.go", nil, 0)32 if err != nil {33 fmt.Println(err)34 }35 ast.Print(fset, node)36}37import (38func main() {39 fset := token.NewFileSet()40 node, err := parser.ParseFile(fset, "test.go", nil, 0)41 if err != nil {42 fmt.Println(err)43 }44 ast.Print(fset, node)45}46import (47func main() {48 fset := token.NewFileSet()49 node, err := parser.ParseFile(fset, "test.go", nil,
String
Using AI Code Generation
1import (2func main() {3func main() {4 fmt.Println("Hello, playground")5}`6 f, err := parser.ParseFile(fset, "src.go", src, parser.ImportsOnly)7 if err != nil {8 fmt.Println(err)9 }10 for _, s := range f.Imports {11 fmt.Println(s.Path.Value)12 }13}14import (15func main() {16func main() {17 fmt.Println("Hello, playground")18}`19 f, err := parser.ParseFile(fset, "src.go", src, parser.DeclarationErrors)20 if err != nil {21 fmt.Println(err)22 }23 for _, s := range f.Decls {24 fmt.Println(s)25 }26}27func main() {28 fmt.Println("Hello, playground")29}30import (31func main() {32func main() {33 fmt.Println("Hello, playground")34}`35 f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)36 if err != nil {37 fmt.Println(err)38 }
String
Using AI Code Generation
1import "go/ast"2import "fmt"3func main() {4 s := ast.NewIdent("Hello")5 fmt.Println(s.String())6}7import "go/ast"8import "fmt"9func main() {10 s := ast.NewIdent("Hello")11 fmt.Println(s.Pos())12}13import "go/ast"14import "fmt"15func main() {16 s := ast.NewIdent("Hello")17 fmt.Println(s.End())18}19import "go/ast"20import "fmt"21func main() {22 s := ast.NewIdent("Hello")23 fmt.Println(s.IsExported())24}25import "go/ast"26import "fmt"27func main() {28 s := ast.NewIdent("Hello")29 fmt.Println(s.NamePos())30}31import "go/ast"32import "fmt"33func main() {34 s := ast.NewIdent("Hello")35 fmt.Println(s.NameEnd())36}37import "go/ast"38import "fmt"39func main() {40 s := ast.NewIdent("Hello")41 fmt.Println(s.Name)42}43import "go/ast"44import "fmt"45func main() {46 s := ast.NewIdent("Hello")47 fmt.Println(s.Obj)48}49import "go/ast"50import "fmt"51func main() {52 s := ast.NewIdent("Hello")53 fmt.Println(s.IsBlank())54}55import "go/ast"56import "fmt"57func main() {58 s := ast.NewIdent("Hello")59 fmt.Println(s.Comment)60}
String
Using AI Code Generation
1import (2func main() {3 fmt.Println(ast.NewIdent("ast.NewIdent(name)"))4}5ast.NewIdent(name)6import (7func main() {8 fmt.Println(ast.NewIdent("ast.NewIdent(name)").String())9}10ast.NewIdent(name)11import (12func main() {13 fmt.Println(ast.NewIdent("ast.NewIdent(name)").String())14}15ast.NewIdent(name)16import (17func main() {18 fmt.Println(ast.NewIdent("ast.NewIdent(name)").String())19}20ast.NewIdent(name)21import (22func main() {23 fmt.Println(ast.NewIdent("ast.NewIdent(name)").String())24}25ast.NewIdent(name)26import (27func main() {28 fmt.Println(ast.NewIdent("ast.NewIdent(name)").String())29}30ast.NewIdent(name)31import (32func main() {33 fmt.Println(ast.NewIdent("ast.NewIdent(name)").String())34}35ast.NewIdent(name)36import (37func main() {38 fmt.Println(ast.NewIdent("ast.NewIdent(name)").String())39}40ast.NewIdent(name)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!