How to use parseResource method of ast Package

Best Syzkaller code snippet using ast.parseResource

parser.go

Source:parser.go Github

copy

Full Screen

...47 switch getStringVal(p.nextToken.Lit) {48 case "request":49 p.parseRequest()50 case "resource":51 p.parseResource()52 default:53 p.errorInfo("invalid char")54 }55 case token.STRUCT:56 p.parseStruct()57 case token.ENUM:58 p.parseEnum()59 case token.PACKAGE:60 p.parsePackage()61 case token.IMPORT:62 p.parseImport()63 default:64 p.errorInfo("invalid char")65 }66 }67 return nil68}69func (p *Parser) isIdentifier(ident string) {70 if p.needCheckIdentifier {71 if !token.IsIdentifier(ident) {72 p.errorInfo(fmt.Sprintf("%s is invalid identifier", ident))73 }74 }75}76func (p *Parser) parseStruct() {77 stru := &ast.Struct{78 Tok: p.nextToken,79 }80 p.NextTokenMust(token.STRUCT)81 tokInfo := p.NextTokenMust(token.STR)82 stru.Name = getStringVal(tokInfo.Lit)83 p.isIdentifier(stru.Name)84 p.NextTokenMust(token.COLON)85 stru.Fields = p.parseStructBody()86 p.AddStructToPool(stru)87}88func (p *Parser) parseStructBody() []*ast.StructField {89 var fields []*ast.StructField90 p.NextTokenMust(token.LBRACE)91 for p.nextToken.Tok != token.RBRACE {92 fields = append(fields, p.parseStructField())93 }94 p.NextTokenMust(token.RBRACE)95 return fields96}97// "name": {{STRING}},98func (p *Parser) parseStructField() *ast.StructField {99 structField := &ast.StructField{100 Tok: p.nextToken,101 Name: "",102 }103 // 字段名称104 p.NextTokenMust(token.STR)105 name := getStringVal(p.curToken.Lit)106 p.isIdentifier(name)107 structField.Name = name108 // :109 p.NextTokenMust(token.COLON)110 // 类型111 structField.Type = p.parseFieldType()112 // 检查是否有逗号, 如果有就跳过113 if p.nextToken.Tok == token.COMMA {114 p.NextTokenMust(token.COMMA)115 }116 return structField117}118// 解析字符表示的类型,例如:"{{STRING}}"119func (p *Parser) parseFieldTypeFromStr() ast.Type {120 p.NextTokenMust(token.STR)121 // 从字符串中解析类型122 src := []byte(getStringVal(p.curToken.Lit))123 pos := scanner.Pos{124 File: p.curToken.Pos.GetFile(),125 Row: p.curToken.Pos.GetRow(),126 Col: p.curToken.Pos.GetCol() - len(p.nextToken.Lit),127 }128 e := p.parseInsertBytes(src, pos, p.parseFieldTypeWrapper)129 if e != nil {130 panic(e)131 }132 return p.typ133}134func (p *Parser) parseFieldTypeWrapper() error {135 // 存储在全局临时空间中,上层使用136 p.typ = p.parseFieldType()137 return nil138}139// 解析含有{{}}的type140func (p *Parser) parseFieldTypeHasBrace() ast.Type {141 p.NextTokenMust(token.LBRACE)142 p.NextTokenMust(token.LBRACE)143 t := p.parseFieldType()144 p.NextTokenMust(token.RBRACE)145 p.NextTokenMust(token.RBRACE)146 return t147}148func (p *Parser) parseFieldType() ast.Type {149 switch p.nextToken.Tok {150 case token.INT, token.INT32, token.INT64,151 token.UINT32, token.UINT64, token.DOUBLE, token.FLOAT, token.BOOL, token.BOOLEAN, token.STRING:152 p.Scan()153 return ast.NewBasicType(p.curToken)154 case token.MAP:155 return p.parseMap()156 case token.ENUM:157 return p.parseEnumType()158 case token.LBRACK:159 return p.parseArray()160 case token.LBRACE:161 return p.parseFieldTypeHasBrace()162 case token.STR:163 return p.parseFieldTypeFromStr()164 case token.IDENT:165 p.NextTokenMust(token.IDENT)166 return ast.NewStructType(p.curToken)167 default:168 p.errExpect("field type")169 }170 return nil171}172func (p *Parser) parseArray() *ast.Array {173 array := ast.NewArrayType(p.nextToken)174 p.NextTokenMust(token.LBRACK)175 array.ItemType = p.parseFieldType()176 p.NextTokenMust(token.RBRACK)177 return array178}179func (p *Parser) parseMap() *ast.Map {180 m := ast.NewMapType(p.nextToken)181 p.NextTokenMust(token.MAP)182 p.NextTokenMust(token.LSS)183 m.Key = p.parseMapKeyType()184 p.NextTokenMust(token.COMMA)185 m.Val = p.parseMapValType()186 p.NextTokenMust(token.GTR)187 return m188}189func (p *Parser) parseMapKeyType() ast.Type {190 return p.parseFieldType()191}192func (p *Parser) parseMapValType() ast.Type {193 return p.parseFieldType()194}195func (p *Parser) parseEnumType() ast.Type {196 p.NextTokenMust(token.ENUM)197 enum := ast.NewEnumType(p.curToken)198 // 兼容老版本,如果没有<>199 // 当做STRING类型处理200 if p.nextToken.Tok != token.LSS {201 p.curToken.Tok = token.STRING202 return ast.NewBasicType(p.curToken)203 }204 p.NextTokenMust(token.LSS)205 enum.ValType = p.parseFieldType()206 p.NextTokenMust(token.GTR)207 return enum208}209/*210* enum "city" : {211* "beijin": 1",212* "shanghai": 2,213* }214 */215func (p *Parser) parseEnum() {216 enum := &ast.Enum{217 Tok: p.nextToken,218 Name: "",219 }220 p.NextTokenMust(token.ENUM)221 tokInfo := p.NextTokenMust(token.STR)222 enum.Name = getStringVal(tokInfo.Lit)223 p.isIdentifier(enum.Name)224 p.NextTokenMust(token.COLON)225 p.NextTokenMust(token.LBRACE)226 if p.nextToken.Tok != token.STR {227 p.errorInfo("enum value can not be empty")228 }229 for p.nextToken.Tok != token.RBRACE {230 enum.Fields = append(enum.Fields, p.parseEnumField())231 }232 p.NextTokenMust(token.RBRACE)233 p.AddEnumToPool(enum)234}235func (p *Parser) parseEnumField() *ast.EnumField {236 field := &ast.EnumField{237 Tok: p.nextToken,238 }239 tokInfo := p.NextTokenMust(token.STR)240 field.Name = getStringVal(tokInfo.Lit)241 p.isIdentifier(field.Name)242 p.NextTokenMust(token.COLON)243 tokInfo = p.NextTokenMust(token.INTEGER)244 tag, _ := strconv.Atoi(tokInfo.Lit)245 field.Tag = ast.EnumTag{246 Tag: tag,247 Tok: tokInfo,248 }249 // 检查是否有逗号, 如果有就跳过250 if p.nextToken.Tok == token.COMMA {251 p.NextTokenMust(token.COMMA)252 }253 return field254}255func (p *Parser) parseRequest() {256 req := &ast.Request{}257 p.NextTokenMustWithLit(token.STR, `"request"`)258 p.NextTokenMust(token.COLON)259 p.NextTokenMust(token.LBRACE)260 p.NextTokenMustWithLit(token.STR, `"url"`)261 p.NextTokenMust(token.COLON)262 tokenInfo := p.NextTokenMust(token.STR)263 req.Url = ast.RequestUrl{264 Tok: tokenInfo,265 Name: getStringVal(tokenInfo.Lit),266 }267 p.AddRequestToPool(req)268 if p.nextToken.Tok == token.COMMA {269 p.NextTokenMust(token.COMMA)270 }271 // 如果下一个直接是'}',说明没有params,272 if p.nextToken.Tok == token.RBRACE {273 p.NextTokenMust(token.RBRACE)274 return275 }276 p.NextTokenMustWithLit(token.STR, `"params"`)277 paramToken := p.curToken278 p.NextTokenMust(token.COLON)279 // 如果是 { 根据规则自动生成struct280 if p.nextToken.Tok == token.LBRACE {281 fields := p.parseStructBody()282 if len(fields) == 0 {283 // 如果为空,则认为没有params284 return285 }286 paramStructName := req.GeneParamsName()287 // 添加param288 strcu := &ast.Struct{289 Tok: paramToken,290 Name: paramStructName,291 Fields: fields,292 }293 p.AddStructToPool(strcu)294 req.Params = &ast.RequestParams{295 Tok: p.curToken,296 StructName: paramStructName,297 }298 } else {299 // 如果不是{,那么就应该是直接指定了struct的名称300 p.parseFieldType()301 if p.nextToken.Tok == token.COMMA {302 p.NextTokenMust(token.COMMA)303 }304 typ, ok := p.typ.(ast.StructType)305 if !ok {306 p.errorInfo("params must be a struct type")307 }308 req.Params = &ast.RequestParams{309 Tok: paramToken,310 StructName: typ.Name,311 }312 }313 p.NextTokenMust(token.RBRACE)314}315func (p *Parser) parseResource() {316}317func (p *Parser) parsePackage() {318 p.NextTokenMust(token.PACKAGE)319 p.NextTokenMust(token.IDENT)320 p.NextTokenMust(token.SEMICOLON)321}322func (p *Parser) parseImport() {323 p.NextTokenMustWithLit(token.IDENT, "import")324 tokenInfo := p.NextTokenMust(token.STR)325 fileName := getStringVal(tokenInfo.Lit)326 p.NextTokenMust(token.SEMICOLON)327 // curFileName328 curFileName := p.scan[p.level].FileName()329 curImp := p.getImport(curFileName)...

Full Screen

Full Screen

analyzer.go

Source:analyzer.go Github

copy

Full Screen

...75 return76 }77 unary := result.(*ast.UnaryExpr)78 compositeLit := unary.X.(*ast.CompositeLit)79 parseResource(compositeLit, pass)80 })81 return nil, nil82}83func parseResource(compositeLit *ast.CompositeLit, pass *analysis.Pass) {84 selExpr := compositeLit.Type.(*ast.SelectorExpr)85 // Only consider schema.Resource86 if fmt.Sprintf("%s", selExpr.X) != "schema" || fmt.Sprintf("%s", selExpr.Sel) != "Resource" {87 return88 }89 var schemaKeyValueExpr *ast.KeyValueExpr90 for _, expr := range compositeLit.Elts {91 keyValueExpr := expr.(*ast.KeyValueExpr)92 // Only consider schema.Schema definition93 if fmt.Sprintf("%s", keyValueExpr.Key) == "Schema" {94 schemaKeyValueExpr = keyValueExpr95 break96 }97 }98 // Return if schema.Schema is not found99 if schemaKeyValueExpr == nil {100 return101 }102 // For each attribute, check the order of the fields103 attributes := schemaKeyValueExpr.Value.(*ast.CompositeLit)104 for _, expr := range attributes.Elts {105 field := expr.(*ast.KeyValueExpr)106 checkFieldOrder(field, pass)107 }108 return109}110func checkFieldOrder(field *ast.KeyValueExpr, pass *analysis.Pass) {111 fieldDef := field.Value.(*ast.CompositeLit)112 sorted := make([]int, len(fieldDef.Elts))113 for i, expr := range fieldDef.Elts {114 keyValueExpr := expr.(*ast.KeyValueExpr)115 key := fmt.Sprintf("%s", keyValueExpr.Key)116 v, ok := orderMap[key]117 if ok {118 sorted[i] = v119 } else {120 pass.Reportf(keyValueExpr.Pos(), "found new field name: %s", key)121 // Prevent other fields from conflicting with this field122 sorted[i] = len(ordering) + 1123 }124 }125 sort.Ints(sorted)126 indexes := make([]int, len(fieldDef.Elts))127 for i, expr := range fieldDef.Elts {128 keyValueExpr := expr.(*ast.KeyValueExpr)129 key := fmt.Sprintf("%s", keyValueExpr.Key)130 v, ok := orderMap[key]131 if ok {132 indexes[i] = v133 } else {134 pass.Reportf(keyValueExpr.Pos(), "found new field name: %s", key)135 // Prevent other fields from conflicting with this field136 indexes[i] = len(ordering) + 1137 }138 index := getWrongIndex(indexes, v, i)139 if index == - 1 {140 continue141 } else {142 name2 := ordering[indexes[index]]143 pass.Reportf(keyValueExpr.Pos(), "%s should come before %s", key, name2)144 }145 // Handle nested resource definitions146 if key == "Elem" {147 unary := keyValueExpr.Value.(*ast.UnaryExpr)148 compositeLit := unary.X.(*ast.CompositeLit)149 parseResource(compositeLit, pass)150 }151 }152}153func getWrongIndex(slice []int, val int, end int) int {154 smallestValue := 0155 smallestIndex := -1156 for i := 0; i < end; i++ {157 v := slice[i]158 if v < val {159 continue160 }161 if smallestIndex == -1 || v < smallestValue {162 smallestValue = v163 smallestIndex = i...

Full Screen

Full Screen

parser_test.go

Source:parser_test.go Github

copy

Full Screen

...8 "github.com/stackoverflow/novah-go/test"9)10var fmtt = ast.NewFormatter()11func TestOperators(t *testing.T) {12 mod := parseResource("../../test_data/operators.novah", t)13 pick := func(i int) string {14 return fmtt.ShowExpr(mod.Decls[i].(ast.SValDecl).Exp)15 }16 x := "w || r && x || p"17 fl := "(a >> b >> c) 1"18 fr := "(a << b << c) 1"19 l1 := "3 + 7 ^ 4 * 6 * 9"20 l2 := "3 ^ (7 * 4) * 6 + 9"21 r1 := "bla 3 $ df 4 $ pa"22 r2 := "3 :: 5 :: 7 :: Nil"23 ap := "fn 3 4 5"24 a2 := "fn (fn2 8)"25 co := "fn 'x' y (Some (3 + 4) 1)"26 test.Equals(t, pick(0), x)27 test.Equals(t, pick(1), fl)28 test.Equals(t, pick(2), fr)29 test.Equals(t, pick(3), l1)30 test.Equals(t, pick(4), l2)31 test.Equals(t, pick(5), r1)32 test.Equals(t, pick(6), r2)33 test.Equals(t, pick(7), ap)34 test.Equals(t, pick(8), a2)35 test.Equals(t, pick(9), co)36}37func TestLambdas(t *testing.T) {38 mod := parseResource("../../test_data/lambda.novah", t)39 l1 := mod.Decls[0].(ast.SValDecl).Exp40 l2 := mod.Decls[1].(ast.SValDecl).Exp41 expl1 := "\\x -> x"42 expl2 := "\\x y z -> 1"43 test.Equals(t, fmtt.ShowExpr(l1), expl1)44 test.Equals(t, fmtt.ShowExpr(l2), expl2)45}46func TestComments(t *testing.T) {47 mod := parseResource("../../test_data/comments.novah", t)48 data := mod.Decls[0].GetComment()49 typ := mod.Decls[1].GetComment()50 val := mod.Decls[2].GetComment()51 nocomm := mod.Decls[3].GetComment()52 test.Equals(t, data.Text, " comments on type definitions work")53 test.Equals(t, typ.Text, "\n comments on var\n types work\n")54 test.Equals(t, val.Text, " comments on var declaration work\n and are concatenated")55 test.Equals(t, nocomm, nil)56}57func TestTypeHints(t *testing.T) {58 mod := parseResource("../../test_data/hints.novah", t)59 x := mod.Decls[0].(ast.SValDecl).Exp.(ast.SAnn)60 test.Equals(t, fmtt.ShowType(x.Type), "String")61}62func TestRecords(t *testing.T) {63 parseResource("../../test_data/records.novah", t)64 // should not panic65}66func parseResource(input string, t *testing.T) ast.SModule {67 reader, _ := os.Open(input)68 defer reader.Close()69 return parseString(reader, input, t)70}71func parseString(reader io.Reader, name string, t *testing.T) ast.SModule {72 lexer := lexer.New(name, reader)73 parser := NewParser(lexer)74 mod, errs := parser.ParseFullModule()75 if len(errs) > 0 {76 for _, err := range errs {77 t.Errorf(err.FormatToConsole())78 }79 panic("Error in parsing")80 }...

Full Screen

Full Screen

parseResource

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, parseResource)9}10func parseResource(n ast.Node) bool {11 if n == nil {12 }13 switch x := n.(type) {14 if x.Name.Name == "Resource" {15 fmt.Println(x.Name.Name)16 }17 for _, field := range x.Fields.List {

Full Screen

Full Screen

parseResource

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := parser.ParseFile(fset, "1.go", nil, 0)4 if err != nil {5 fmt.Println(err)6 }7 ast.Print(fset, f)8}9./2.go:18: cannot use astObj1 (type ast.AST) as type ast.AST in assignment10Is there any way to assign the result of ast.ParseResource() to a variable of type ast.Node() or ast.AST()?11import (12func main() {13 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {14 fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))15 })16 http.ListenAndServe(":8080", nil)17}18fset := token.NewFileSet()19astFile, err := parser.ParseFile(fset, "main.go", nil, parser.ParseComments)20import (21func main() {22 f, err := parser.ParseFile(fset, "1.go", nil, 0)23 if err != nil {24 fmt.Println(err)25 }26 ast.Print(fset, f)27}

Full Screen

Full Screen

parseResource

Using AI Code Generation

copy

Full Screen

1ast := &ast{}2ast.parseResource("test.json")3ast := &ast{}4ast.parseResource("test.json")5ast := &ast{}6ast.parseResource("test.json")7ast := &ast{}8ast.parseResource("test.json")9ast := &ast{}10ast.parseResource("test.json")11ast := &ast{}12ast.parseResource("test.json")13ast := &ast{}14ast.parseResource("test.json")15ast := &ast{}16ast.parseResource("test.json")17ast := &ast{}18ast.parseResource("test.json")19ast := &ast{}20ast.parseResource("test.json")21ast := &ast{}22ast.parseResource("test.json")23ast := &ast{}24ast.parseResource("test.json")25ast := &ast{}26ast.parseResource("test.json")27ast := &ast{}28ast.parseResource("test.json")29ast := &ast{}30ast.parseResource("test.json")31ast := &ast{}32ast.parseResource("test.json")33ast := &ast{}34ast.parseResource("test.json")

Full Screen

Full Screen

parseResource

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := []byte(`4 resource "aws_instance" "web" {5 }6 file := &ast.File{7 Node: ast.Node{8 },9 }10 ast.ParseResource(data, file)11 fmt.Println(file)12}13&{FILE [{RESOURCE aws_instance.web [{ASSIGN {=} {IDENT ami} {STRING 21f78e11}} {ASSIGN {=} {IDENT instance_type} {STRING t2.micro}}]}]}

Full Screen

Full Screen

parseResource

Using AI Code Generation

copy

Full Screen

1import (2type ast struct {3}4func (a ast) parseResource() {5 fmt.Println("method parseResource called")6}7func main() {8 a := ast{}9 reflect.ValueOf(a).MethodByName("parseResource").Call([]reflect.Value{reflect.ValueOf("hello"), reflect.ValueOf("world")})10}11import (12type ast struct {13}14func (a ast) parseResource(name string, age int) {15 fmt.Println("method parseResource called with arguments:", name, age)16}17func main() {18 a := ast{}19 reflect.ValueOf(a).MethodByName("parseResource").Call([]reflect.Value{reflect.ValueOf("hello"), reflect.ValueOf(18)})20}

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