Best Syzkaller code snippet using ast.parseField
visitor.go
Source:visitor.go  
...121	}122	v.depth++123	return v124}125func (v *visitor) parseField(d *ast.Field) Field {126	f := Field{}127	names := make([]string, 0)128	for _, id := range d.Names {129		names = append(names, id.Name)130	}131	f.Names = names132	f.FieldType = d.Type133	imports := make(map[Import]struct{})134	getFieldImports(d.Type, v.res.Imports, imports)135	f.RelatedImport = imports136	return f137}138func getFieldImports(t ast.Expr, imports map[Import]struct{}, filtered map[Import]struct{}) {139	getImport := func(pkg string) Import {140		for imp := range imports {141			if pkg == imp.Name || strings.HasSuffix(imp.Path, "/"+pkg+"\"") {142				return imp143			}144		}145		return Import{}146	}147	doSel := func(sel *ast.SelectorExpr) {148		if id, okID := sel.X.(*ast.Ident); okID {149			pkg := id.Name150			imp := getImport(pkg)151			if imp.Path != "" {152				filtered[imp] = struct{}{}153			}154		}155	}156CONTINUE:157	if sel, okSel := t.(*ast.SelectorExpr); okSel {158		doSel(sel)159	} else if star, okStar := t.(*ast.StarExpr); okStar {160		t = star.X161		goto CONTINUE162	} else if arr, okArr := t.(*ast.ArrayType); okArr {163		if sel, okSel := arr.Elt.(*ast.SelectorExpr); okSel {164			doSel(sel)165		} else if arr, okArr := arr.Elt.(*ast.ArrayType); okArr {166			t = arr167			goto CONTINUE168		}169	} else if mt, okM := t.(*ast.MapType); okM {170		if sel, okSel := mt.Key.(*ast.SelectorExpr); okSel {171			doSel(sel)172		} else if sel, okSel := mt.Key.(*ast.StarExpr); okSel {173			if sel, okSel := sel.X.(*ast.SelectorExpr); okSel {174				doSel(sel)175			}176		}177		if vt, okV := mt.Value.(*ast.SelectorExpr); okV {178			doSel(vt)179		} else if vt, okV := mt.Value.(*ast.MapType); okV {180			t = vt181			goto CONTINUE182		} else if vs, okVS := mt.Value.(*ast.StarExpr); okVS {183			if sel, okSel := vs.X.(*ast.SelectorExpr); okSel {184				doSel(sel)185			}186		} else if ar, okA := mt.Value.(*ast.ArrayType); okA {187			if sel, okS := ar.Elt.(*ast.SelectorExpr); okS {188				doSel(sel)189			} else if arr, okArr := ar.Elt.(*ast.ArrayType); okArr {190				t = arr191				goto CONTINUE192			}193		}194	}195}196func (v *visitor) parseStoreField(d *ast.Field) {197	if v.inClass && d.Doc != nil {198		list := strings.Split(d.Doc.Text(), "\n")199		for _, doc := range list {200			doc = strings.TrimSpace(doc)201			if doc == "@:public:store:cache" {202				cacheField := v.parseField(d)203				if e, ok := d.Type.(*ast.MapType); ok {204					if e, ok := e.Value.(*ast.MapType); ok {205						if _, ok := e.Value.(*ast.MapType); ok {206							v.reportErr("contract cannot support more than two level map", d.Pos())207						}208					}209				}210				v.res.StoreCaches = append(v.res.StoreCaches, cacheField)211			} else if doc == "@:public:store" {212				storeField := v.parseField(d)213				if e, ok := d.Type.(*ast.MapType); ok {214					if e, ok := e.Value.(*ast.MapType); ok {215						if _, ok := e.Value.(*ast.MapType); ok {216							v.reportErr("contract cannot support more than two level map", d.Pos())217						}218					}219				}220				v.res.Stores = append(v.res.Stores, storeField)221			}222		}223		v.initVariableCallee()224	}225}226func (v *visitor) initVariableCallee() {227	for _, s := range v.res.Stores {228		variableCallee[s.Names[0]] = struct{}{}229	}230	for _, sc := range v.res.StoreCaches {231		variableCallee[sc.Names[0]] = struct{}{}232	}233}234func (v *visitor) parseAllFunc(d *ast.FuncDecl) {235	f := v.parseFunction(d)236	if d.Doc != nil {237		// fmt.Println("FUNCTION::: name(", d.Name.Name, ") =>[[", d.Doc.Text(), "]]")238		if v.hasConstructorInComments(d) {239			if d.Name.Name == "InitChain" {240				if v.res.IsExistInitChain == true {241					v.reportErr("the InitChain function must be only one", d.Type.Pos())242				}243				v.res.InitChain = v.parseInitChain(f, d)244				v.res.IsExistInitChain = true245			} else if d.Name.Name == "UpdateChain" {246				if v.res.IsExistUpdateChain == true {247					v.reportErr("the UpdateChain function must be only one", d.Type.Pos())248				}249				v.res.UpdateChain = v.parseUpdateChain(f, d)250				v.res.IsExistUpdateChain = true251			}252		} else if v.hasMineInComments(d) {253			if d.Name.Name == "Mine" &&254				d.Type.Results != nil &&255				len(d.Type.Results.List) == 1 &&256				d.Type.Results.List[0].Type.(*ast.Ident).Name == "int64" {257				//if d.Name.Name == "Mine" {258				if v.res.IsExistMine == true {259					v.reportErr("the Mine function must be only one", d.Type.Pos())260				}261				v.res.Mine = v.parseMine(f, d)262				v.res.IsExistMine = true263			}264		}265		mGas, mB := v.getGasFromComments(d, methodGasPrefix)266		iGas, iB := v.getGasFromComments(d, interfaceGasPrefix)267		tGas, tB := v.getGasFromComments(d, ibcGasPrefix)268		if iGas < 0 {269			v.reportErr("interface gas must greater than zero", d.Pos())270		}271		if tGas != 0 && v.res.ContractName != "ibc" {272			v.reportErr("ibc interface gas must be zero", d.Pos())273		}274		if mB || iB || tB {275			v.res.Functions = append(v.res.Functions, f)276			if mB {277				f.MGas = mGas278				v.res.MFunctions = append(v.res.MFunctions, f)279			}280			if iB {281				if HaveUserDefinedStruct(f.Method) {282					v.reportErr("The method params/results type cannot use struct", f.pos)283				}284				f.IGas = iGas285				v.res.IFunctions = append(v.res.IFunctions, f)286			}287			if tB {288				f.TGas = tGas289				v.res.TFunctions = append(v.res.TFunctions, f)290			}291		}292	}293}294func (v *visitor) parseFunction(d *ast.FuncDecl) Function {295	// check296	f := Function{}297	if d.Recv != nil {298		f.Receiver = v.parseField(d.Recv.List[0])299	}300	f.Name = d.Name.Name301	f.pos = d.Pos()302	f.Params = make([]Field, 0)303	for _, param := range d.Type.Params.List {304		f.Params = append(f.Params, v.parseField(param))305	}306	f.Results = make([]Field, 0)307	if d.Type.Results != nil {308		for _, res := range d.Type.Results.List {309			f.Results = append(f.Results, v.parseField(res))310		}311	}312	f.Comments = d.Doc.Text()313	return f314}315func (v *visitor) parseInitChain(f Function, d *ast.FuncDecl) Function {316	if len(d.Type.Params.List) > 0 {317		v.reportErr("InitChain must have no params", d.Pos())318	}319	if d.Type.Results != nil && len(d.Type.Results.List) > 0 {320		v.reportErr("InitChain must have no results", d.Pos())321	}322	if d.Recv == nil || len(d.Recv.List) != 1 {323		v.reportErr("InitChain has wrong receiver", d.Pos())324	}325	if d.Recv != nil {326		f.Receiver = v.parseField(d.Recv.List[0])327		if f.Receiver.FieldType.(*ast.StarExpr).X.(*ast.Ident).Name != v.res.ContractStructure {328			v.reportErr("InitChain has wrong receiver", d.Pos())329		}330	}331	f.pos = d.Pos()332	return f333}334func (v *visitor) parseUpdateChain(f Function, d *ast.FuncDecl) Function {335	if len(d.Type.Params.List) > 0 {336		v.reportErr("UpdateChain must have no params", d.Pos())337	}338	if d.Type.Results != nil && len(d.Type.Results.List) > 0 {339		v.reportErr("UpdateChain must have no results", d.Pos())340	}341	if d.Recv == nil || len(d.Recv.List) != 1 {342		v.reportErr("UpdateChain has wrong receiver", d.Pos())343	}344	if d.Recv != nil {345		f.Receiver = v.parseField(d.Recv.List[0])346		if f.Receiver.FieldType.(*ast.StarExpr).X.(*ast.Ident).Name != v.res.ContractStructure {347			v.reportErr("UpdateChain has wrong receiver", d.Pos())348		}349	}350	f.pos = d.Pos()351	return f352}353func (v *visitor) parseMine(f Function, d *ast.FuncDecl) Function {354	if len(d.Type.Params.List) > 0 {355		v.reportErr("Mine must have no params", d.Pos())356	}357	if len(d.Type.Results.List) != 1 {358		v.reportErr("Mine must have one result", d.Pos())359	}360	if d.Recv == nil || len(d.Recv.List) != 1 {361		v.reportErr("Mine has wrong receiver", d.Pos())362	}363	if d.Recv != nil {364		f.Receiver = v.parseField(d.Recv.List[0])365		if f.Receiver.FieldType.(*ast.StarExpr).X.(*ast.Ident).Name != v.res.ContractStructure {366			v.reportErr("Mine has wrong receiver", d.Pos())367		}368	}369	f.pos = d.Pos()370	return f371}372func (v *visitor) hasConstructorInComments(d *ast.FuncDecl) bool {373	l := strings.Split(d.Doc.Text(), "\n")374	for _, c := range l {375		c = strings.TrimSpace(c)376		if strings.HasPrefix(c, "@:constructor") {377			return true378		}379	}380	return false381}382func (v *visitor) hasMineInComments(d *ast.FuncDecl) bool {383	l := strings.Split(d.Doc.Text(), "\n")384	for _, c := range l {385		c = strings.TrimSpace(c)386		if strings.HasPrefix(c, "@:public:mine") {387			return true388		}389	}390	return false391}392func (v *visitor) getGasFromComments(d *ast.FuncDecl, prefix string) (int64, bool) {393	l := strings.Split(d.Doc.Text(), "\n")394	for _, c := range l {395		c = strings.TrimSpace(c)396		if strings.HasPrefix(c, prefix) {397			if !d.Name.IsExported() {398				v.reportErr("func name invalid", d.Pos())399				return 0, false400			}401			if d.Recv == nil {402				v.reportErr("receiver required", d.Pos())403				return 0, false404			}405			if len(d.Recv.List) != 1 {406				v.reportErr("no receiver", d.Pos())407				return 0, false408			}409			if v.res.ContractStructure != d.Recv.List[0].Type.(*ast.StarExpr).X.(*ast.Ident).String() {410				v.reportErr("receiver incorrect", d.Pos())411				return 0, false412			}413			gas := c[len(prefix) : len(c)-1]414			i, e := strconv.ParseInt(gas, 10, 64)415			if e != nil {416				v.reportErr("method and interface gas must be a number", d.Pos())417			}418			return i, true419		}420	}421	return 0, false422}423// Id @ level 1 is package name424func (v *visitor) parsePackageName(d *ast.Ident) {425	if v.depth == 1 {426		if d.Name == "std" {427			v.reportErr("Contract package name cannot use std", d.Pos())428		} else if d.Name == "ibc" {429			v.reportErr("Contract package name cannot use ibc", d.Pos())430		} else {431			v.res.PackageName = d.Name432		}433	}434}435func (v *visitor) parseGenDeclare(d *ast.GenDecl) {436	if d.Tok == token.IMPORT {437		v.parseImport(d)438	} else if d.Tok == token.VAR {439		v.parseVar(d)440	} else {441		v.parseStructsNInterface(d)442	}443}444func (v *visitor) parseImport(d *ast.GenDecl) {445	for _, spec := range d.Specs {446		if imp, ok := spec.(*ast.ImportSpec); ok {447			path := imp.Path.Value448			if _, okPKG := WhiteListPKG[path]; !okPKG && !isWhitePrefix(path) {449				v.res.ErrFlag = true450				v.res.ErrorDesc = append(v.res.ErrorDesc, "INVALID IMPORT: "+path)451				v.res.ErrorPos = append(v.res.ErrorPos, d.Pos())452			} else {453				im := Import{Path: path}454				if imp.Name != nil {455					im.Name = imp.Name.Name456				}457				v.res.Imports[im] = struct{}{}458			}459		}460	}461}462func isWhitePrefix(path string) bool {463	for _, pre := range WhiteListPkgPrefix {464		if strings.HasPrefix(path, pre) {465			return true466		}467	}468	return false469}470func (v *visitor) parseVar(d *ast.GenDecl) {471	for _, spec := range d.Specs {472		if value, ok := spec.(*ast.ValueSpec); ok {473			for _, name := range value.Names {474				if name.Name == "_" {475					continue476				}477				if v.depth <= 1 {478					v.reportErr("GLOBAL VAR:"+name.Name, d.Pos())479				} else if strings.HasPrefix(name.Obj.Name, "float") {480					v.reportErr("FLOAT VAR:"+name.Name, d.Pos())481				}482			}483		}484	}485}486func (v *visitor) parseStructsNInterface(d *ast.GenDecl) {487	for _, spec := range d.Specs {488		if typ, ok := spec.(*ast.TypeSpec); ok {489			if v.depth == 1 && d.Doc != nil {490				if _, ok := typ.Type.(*ast.InterfaceType); ok {491					v.parseInterface(d, typ)492					v.parseImportInterface(d, typ)493				}494				if _, ok := typ.Type.(*ast.StructType); ok {495					v.parseStructs(d, typ)496				}497			}498		}499	}500}501// parse interface annotation (receipt)502func (v *visitor) parseInterface(d *ast.GenDecl, typ *ast.TypeSpec) {503	// fmt.Println("INTERFACE::: name(", typ.Name, ") =>[[", d.Doc.Text(), "]]")504	if v.isReceipt(d) {505		if v.res.Receipts == nil {506			v.res.Receipts = make([]Method, 0)507		}508		it, _ := typ.Type.(*ast.InterfaceType)509		for _, am := range it.Methods.List {510			if am.Names[0].Name[:4] != "emit" {511				v.reportErr("Method os receipt interface must start with 'emit'", typ.Pos())512			}513			if m, ok := am.Type.(*ast.FuncType); ok {514				params := make([]Field, 0)515				for _, p := range m.Params.List {516					params = append(params, v.parseField(p))517				}518				results := make([]Field, 0)519				if m.Results != nil {520					for _, r := range m.Results.List {521						results = append(results, v.parseField(r))522					}523				}524				v.res.Receipts = append(v.res.Receipts, Method{525					Name:    am.Names[0].Name,526					Params:  params,527					Results: results,528				})529			}530		}531	}532}533func (v *visitor) isReceipt(d *ast.GenDecl) bool {534	for _, l := range d.Doc.List {535		doc := strings.TrimSpace(l.Text)536		if strings.ToLower(doc) == "//@:public:receipt" {537			return true538		}539	}540	return false541}542// parse import interface annotation (import)543func (v *visitor) parseImportInterface(d *ast.GenDecl, typ *ast.TypeSpec) {544	// fmt.Println("INTERFACE::: name(", typ.Name, ") =>[[", d.Doc.Text(), "]]")545	isImport, importContract := v.isImport(d)546	if isImport {547		if v.isExist(importContract) {548			v.reportErr("import contract must unique", d.Pos())549		}550		if importContract == typ.Name.Name {551			v.reportErr("import flag name cannot same to type name", typ.Pos())552		}553		imCon := ImportContract{Name: importContract, Interfaces: make([]Method, 0), Pos: d.Pos()}554		it, _ := typ.Type.(*ast.InterfaceType)555		for _, am := range it.Methods.List {556			if m, ok := am.Type.(*ast.FuncType); ok {557				params := make([]Field, 0)558				for _, p := range m.Params.List {559					params = append(params, v.parseField(p))560				}561				results := make([]Field, 0)562				if m.Results != nil {563					for _, r := range m.Results.List {564						results = append(results, v.parseField(r))565					}566				}567				imCon.Interfaces = append(imCon.Interfaces, Method{568					Name:    am.Names[0].Name,569					Params:  params,570					Results: results,571				})572				if HaveUserDefinedStruct(imCon.Interfaces[len(imCon.Interfaces)-1]) {573					v.reportErr("The method params/results type cannot use struct", d.Pos())574				}575			}576		}577		v.res.ImportContracts = append(v.res.ImportContracts, imCon)578	}...scanner.go
Source:scanner.go  
...124		// Can be a vannilla handler. Need to check the param for *gin.Context125		if numParams == 1 {126			fui.ParamsOpening = f.Type.Params.Opening127			p := f.Type.Params.List[0]128			fi := parseField(fs, p, iResolver)129			// Should parseFuncDecl based on gin.Context... At the moment parseFuncDecl *gin.Context130			if fi.QType == "github.com/gin-gonic/gin/Context" {131				fui.Params = []FieldInfo{fi}132				fui.FType = GIN_SimpleHandler133			} else {134				log.Trace().Str("function", f.Name.Name).Str("param", fi.String()).Msg("param not of *gin.Context")135			}136		} else {137			log.Trace().Str("function", f.Name.Name).Msg("function is not a gin handler")138		}139	}140	if numResults == 1 {141		// Can be a wrapper..142		p := f.Type.Results.List[0]143		switch tp := p.Type.(type) {144		case *ast.FuncType:145			if tp.Params != nil && len(tp.Params.List) == 1 && tp.Results == nil {146				fi1 := parseField(fs, tp.Params.List[0], iResolver)147				if fi1.QType == "github.com/gin-gonic/gin/Context" {148					fui.FType = GIN_Closure_Func149				}150			}151		default:152			fi := parseField(fs, p, iResolver)153			if fi.QType == "github.com/gin-gonic/gin/HandlerFunc" || fi.QType == "H" {154				fui.Result = fi155				fui.FType = GIN_Closure_HandlerFunc156			}157		}158		if numParams > 0 {159			/*160			 * Should try to match comment annotations.161			 */162			pStart := f.Type.Params.Opening163			fui.ParamsOpening = f.Type.Params.Opening164			for _, p := range f.Type.Params.List {165				fi := parseField(fs, p, iResolver)166				cg := findFieldComment(pStart, fi.Pos, comments)167				if cg != nil {168					a, err := parseComments(cg)169					if err != nil {170						log.Error().Str("function", f.Name.Name).Str("field", fi.Name).Err(err).Msg("error in parsing comments")171						return fui, nil172					}173					fi.Annotations = a174				}175				fui.Params = append(fui.Params, fi)176				// Increment the starting pos to next param.177				pStart = fi.End178			}179		}180	}181	// More than one result: function filtered.182	return fui, nil183}184func findFieldComment(paramsStartPos token.Pos, paramNameStartPos token.Pos, cmms []*ast.CommentGroup) *ast.CommentGroup {185	for _, cg := range cmms {186		if cg.Pos() > paramsStartPos && cg.Pos() < paramNameStartPos {187			return cg188		}189	}190	return nil191}192func parseField(fs *token.FileSet, field *ast.Field, resolver *importResolver) FieldInfo {193	fi := FieldInfo{}194	if len(field.Names) > 0 {195		fi.Name = field.Names[0].Name196	}197	fi.FilePos = fs.Position(field.Pos())198	fi.Pos = field.Pos()199	fi.End = field.End()200	switch tt := field.Type.(type) {201	case *ast.StarExpr:202		fi.Pointer = true203		switch ttt := tt.X.(type) {204		case *ast.SelectorExpr:205			fi.Sel = ttt.Sel.Name206			fi.X = ttt.X.(*ast.Ident).Name...helpers.go
Source:helpers.go  
...26		return ast.NewIdent("object")27	}28	return expr.(*ast.Ident)29}30func parseField(f *ast.Field) *StructField {31	if len(f.Names) > 0 {32		ident := getEndIdent(f.Type)33		field := NewStructField(f.Names[0].Name, ident.Name)34		if _, ok := f.Type.(*ast.StarExpr); ok {35			field.Pointer = true36		}37		if f.Doc != nil {38			for _, c := range f.Doc.List {39				field.Annotations.addLine(c.Text)40			}41		}42		if f.Comment != nil {43			for _, c := range f.Comment.List {44				field.Annotations.addLine(c.Text)45			}46		}47		return field48	}49	return nil50}51func parseStructSpec(decl *ast.GenDecl) (s *Struct) {52	if spec, ok := decl.Specs[0].(*ast.TypeSpec); ok {53		if structType, ok := spec.Type.(*ast.StructType); ok {54			if decl.Doc != nil {55				s = NewStruct(spec.Name.Name)56				for _, cg := range decl.Doc.List {57					s.Annotations.addLine(cg.Text)58				}59				for _, f := range structType.Fields.List {60					parsed := parseField(f)61					if parsed != nil {62						s.Fields = append(s.Fields, parseField(f))63					}64				}65			}66		}67	}68	return69}...parseField
Using AI Code Generation
1import (2func main() {3	import "fmt"4	func main() {5		fmt.Println("Hello, world.")6	}7	f, err := parser.ParseFile(fset, "hello.go", src, parser.ParseComments)8	if err != nil {9		fmt.Println(err)10	}11	fmt.Println("Imports:")12	for _, s := range f.Imports {13		fmt.Println(s.Path.Value)14	}15}16import (17func main() {18	import "fmt"19	func main() {20		fmt.Println("Hello, world.")21	}22	f, err := parser.ParseFile(fset, "hello.go", src, parser.ParseComments)23	if err != nil {24		fmt.Println(err)25	}26	fmt.Println("Declarations:")27	for _, d := range f.Decls {28		fmt.Printf("%T29	}30}31import (32func main() {33	import "fmt"34	func main() {35		fmt.Println("Hello, world.")36	}37	f, err := parser.ParseFile(fset, "hello.go", src, parser.ParseComments)38	if err != nil {39		fmt.Println(err)40	}41	fmt.Println("Statements:")42	for _, d := range f.Decls {43		gd, ok := d.(*ast.FuncDecl)44		if !ok {45		}parseField
Using AI Code Generation
1import (2func main() {3	f, err := parser.ParseFile(fset, "2.go", nil, 0)4	if err != nil {5		fmt.Println(err)6	}7	ast.Print(fset, f)8	fmt.Println("----")9	ast.Print(fset, f.Decls[0])10	fmt.Println("----")11	ast.Print(fset, f.Decls[0].(*ast.GenDecl).Specs[0])12	fmt.Println("----")13	ast.Print(fset, f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type)14	fmt.Println("----")15	ast.Print(fset, f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type.(*ast.StructType).Fields)16	fmt.Println("----")17	ast.Print(fset, f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type.(*ast.StructType).Fields.List[0])18	fmt.Println("----")19	ast.Print(fset, f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type.(*ast.StructType).Fields.List[0].Type)20	fmt.Println("----")21	ast.Print(fset, f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type.(*ast.StructType).Fields.List[0].Type.(*ast.Ident))22	fmt.Println("----")23	ast.Print(fset, f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type.(*ast.StructType).Fields.List[0].Type.(*ast.Ident).Obj)24	fmt.Println("----")parseField
Using AI Code Generation
1import (2func main() {3	f, err := parser.ParseFile(fset, "1.go", nil, parser.ImportsOnly)4	if err != nil {5		log.Fatal(err)6	}7	fmt.Println("Imports:")8	for _, s := range f.Imports {9		fmt.Println(s.Path.Value)10	}11}parseField
Using AI Code Generation
1func main() {2    f, err := parser.ParseFile(fset, "2.go", nil, parser.ParseComments)3    if err != nil {4        log.Fatal(err)5    }6    ast.Inspect(f, func(n ast.Node) bool {7        switch x := n.(type) {8            fmt.Println("Tag:", x.Tag)9            fmt.Println("Type:", x.Type)10            fmt.Println("Names:", x.Names)11        }12    })13}14func main() {15    fset := token.NewFileSet()parseField
Using AI Code Generation
1func parseField(field *ast.Field) string {2    buf.WriteString(field.Names[0].Name)3    buf.WriteString(" ")4    buf.WriteString(field.Type.(*ast.Ident).Name)5    return buf.String()6}7func parseFieldList(list *ast.FieldList) string {8    for i, field := range list.List {9        if i > 0 {10            buf.WriteString(", ")11        }12        buf.WriteString(parseField(field))13    }14    return buf.String()15}16func parseFuncType(ft *ast.FuncType) string {17    buf.WriteString("func(")18    buf.WriteString(parseFieldList(ft.Params))19    buf.WriteString(")")20    return buf.String()21}22func parseFuncDecl(decl *ast.FuncDecl) string {23    buf.WriteString(parseFuncType(decl.Type))24    return buf.String()25}26func parseDecl(decl ast.Decl) string {27    switch decl := decl.(type) {28        return parseFuncDecl(decl)29    }30}31func parseFile(filename string) ([]string, error) {32    fset := token.NewFileSet()33    f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)34    if err != nil {35    }36    for _, decl := range f.Decls {37        decls = append(decls, parseDecl(decl))38    }39}40func parseFiles(filenames []string) error {41    for _, filename := range filenames {42        decls, err := parseFile(filename)43        if err != nil {44        }45        for _, decl := range decls {46            fmt.Println(decl)47        }48    }49}parseField
Using AI Code Generation
1func main() {2    f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)3    if err != nil {4        fmt.Println(err)5    }6    ast.Inspect(f, func(n ast.Node) bool {7        switch x := n.(type) {8            fmt.Println(parseField(x))9        }10    })11}12import "fmt"13func main() {14    f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)15    if err != nil {16        fmt.Println(err)17    }18    ast.Inspect(f, func(n ast.Node) bool {19        switch x := n.(type) {20            fmt.Println(parseField(x))21        }22    })23}parseField
Using AI Code Generation
1import (2func main() {3type t struct {4}5func main() {6	t1 := t{x: 1, y: "hello"}7	fmt.Println(t1)8}9	f, err := parser.ParseFile(fset, "", src, 0)10	if err != nil {11		fmt.Println(err)12	}13	ast.Inspect(f, func(n ast.Node) bool {14		st, ok := n.(*ast.StructType)15		if !ok {16		}17		for _, field := range st.Fields.List {18			fmt.Printf("Field: %s %s19		}20	})21}22import (23func main() {24type t struct {25}26func main() {27	t1 := t{x: 1, y: "hello"}28	fmt.Println(t1)29}30	f, err := parser.ParseFile(fset, "", src, 0)31	if err != nil {32		fmt.Println(err)33	}34	ast.Inspect(f, func(n ast.Node) bool {35		st, ok := n.(*ast.StructType)36		if !ok {37		}38		for _, field := range st.Fields.List {39			fmt.Printf("Field: %s %s40		}41	})42}parseField
Using AI Code Generation
1func parseField(field *ast.Field) string {2	if len(names) == 0 {3	}4}5func parseType(field *ast.Field) string {6	return field.Type.(*ast.Ident).Name7}8func parseTag(field *ast.Field) string {9	return reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]).Get("json")10}11func parseStruct(strct *ast.StructType) []StructField {12	for _, field := range strct.Fields.List {13		if field.Names == nil {14		}15		fields = append(fields, StructField{16			Name: parseField(field),17			Type: parseType(field),18			Tag:  parseTag(field),19		})20	}21}22func parseStructType(strct *ast.TypeSpec) StructType {23	return StructType{24		Fields: parseStruct(strct.Type.(*ast.StructType)),25	}26}27func parseStructTypes(file *ast.File) []StructType {28	for _, decl := range file.Decls {29		if genDecl, ok := decl.(*ast.GenDecl); ok {30			for _, spec := range genDecl.Specs {31				if typeSpec, ok := spec.(*ast.TypeSpec); ok {32					if _, ok := typeSpec.Type.(*ast.StructType); okLearn 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!!
