How to use next method of ast Package

Best Syzkaller code snippet using ast.next

expression.go

Source:expression.go Github

copy

Full Screen

...10 idx := self.idx11 if self.mode&StoreComments != 0 {12 self.comments.MarkComments(ast.LEADING)13 }14 self.next()15 exp := &ast.Identifier{16 Name: literal,17 Idx: idx,18 }19 if self.mode&StoreComments != 0 {20 self.comments.SetExpression(exp)21 }22 return exp23}24func (self *_parser) parsePrimaryExpression() ast.Expression {25 literal := self.literal26 idx := self.idx27 switch self.token {28 case token.IDENTIFIER:29 self.next()30 if len(literal) > 1 {31 tkn, strict := token.IsKeyword(literal)32 if tkn == token.KEYWORD {33 if !strict {34 self.error(idx, "Unexpected reserved word")35 }36 }37 }38 return &ast.Identifier{39 Name: literal,40 Idx: idx,41 }42 case token.NULL:43 self.next()44 return &ast.NullLiteral{45 Idx: idx,46 Literal: literal,47 }48 case token.BOOLEAN:49 self.next()50 value := false51 switch literal {52 case "true":53 value = true54 case "false":55 value = false56 default:57 self.error(idx, "Illegal boolean literal")58 }59 return &ast.BooleanLiteral{60 Idx: idx,61 Literal: literal,62 Value: value,63 }64 case token.STRING:65 self.next()66 value, err := parseStringLiteral(literal[1 : len(literal)-1])67 if err != nil {68 self.error(idx, err.Error())69 }70 return &ast.StringLiteral{71 Idx: idx,72 Literal: literal,73 Value: value,74 }75 case token.NUMBER:76 self.next()77 value, err := parseNumberLiteral(literal)78 if err != nil {79 self.error(idx, err.Error())80 value = 081 }82 return &ast.NumberLiteral{83 Idx: idx,84 Literal: literal,85 Value: value,86 }87 case token.SLASH, token.QUOTIENT_ASSIGN:88 return self.parseRegExpLiteral()89 case token.LEFT_BRACE:90 return self.parseObjectLiteral()91 case token.LEFT_BRACKET:92 return self.parseArrayLiteral()93 case token.LEFT_PARENTHESIS:94 self.expect(token.LEFT_PARENTHESIS)95 expression := self.parseExpression()96 if self.mode&StoreComments != 0 {97 self.comments.Unset()98 }99 self.expect(token.RIGHT_PARENTHESIS)100 return expression101 case token.THIS:102 self.next()103 return &ast.ThisExpression{104 Idx: idx,105 }106 case token.FUNCTION:107 return self.parseFunction(false)108 }109 self.errorUnexpectedToken(self.token)110 self.nextStatement()111 return &ast.BadExpression{From: idx, To: self.idx}112}113func (self *_parser) parseRegExpLiteral() *ast.RegExpLiteral {114 offset := self.chrOffset - 1 // Opening slash already gotten115 if self.token == token.QUOTIENT_ASSIGN {116 offset -= 1 // =117 }118 idx := self.idxOf(offset)119 pattern, err := self.scanString(offset)120 endOffset := self.chrOffset121 self.next()122 if err == nil {123 pattern = pattern[1 : len(pattern)-1]124 }125 flags := ""126 if self.token == token.IDENTIFIER { // gim127 flags = self.literal128 self.next()129 endOffset = self.chrOffset - 1130 }131 var value string132 // TODO 15.10133 {134 // Test during parsing that this is a valid regular expression135 // Sorry, (?=) and (?!) are invalid (for now)136 pattern, err := TransformRegExp(pattern)137 if err != nil {138 if pattern == "" || self.mode&IgnoreRegExpErrors == 0 {139 self.error(idx, "Invalid regular expression: %s", err.Error())140 }141 } else {142 _, err = regexp.Compile(pattern)143 if err != nil {144 // We should not get here, ParseRegExp should catch any errors145 self.error(idx, "Invalid regular expression: %s", err.Error()[22:]) // Skip redundant "parse regexp error"146 } else {147 value = pattern148 }149 }150 }151 literal := self.str[offset:endOffset]152 return &ast.RegExpLiteral{153 Idx: idx,154 Literal: literal,155 Pattern: pattern,156 Flags: flags,157 Value: value,158 }159}160func (self *_parser) parseVariableDeclaration(declarationList *[]*ast.VariableExpression) ast.Expression {161 if self.token != token.IDENTIFIER {162 idx := self.expect(token.IDENTIFIER)163 self.nextStatement()164 return &ast.BadExpression{From: idx, To: self.idx}165 }166 literal := self.literal167 idx := self.idx168 self.next()169 node := &ast.VariableExpression{170 Name: literal,171 Idx: idx,172 }173 if self.mode&StoreComments != 0 {174 self.comments.SetExpression(node)175 }176 if declarationList != nil {177 *declarationList = append(*declarationList, node)178 }179 if self.token == token.ASSIGN {180 if self.mode&StoreComments != 0 {181 self.comments.Unset()182 }183 self.next()184 node.Initializer = self.parseAssignmentExpression()185 }186 return node187}188func (self *_parser) parseVariableDeclarationList(var_ file.Idx) []ast.Expression {189 var declarationList []*ast.VariableExpression // Avoid bad expressions190 var list []ast.Expression191 for {192 if self.mode&StoreComments != 0 {193 self.comments.MarkComments(ast.LEADING)194 }195 decl := self.parseVariableDeclaration(&declarationList)196 list = append(list, decl)197 if self.token != token.COMMA {198 break199 }200 if self.mode&StoreComments != 0 {201 self.comments.Unset()202 }203 self.next()204 }205 self.scope.declare(&ast.VariableDeclaration{206 Var: var_,207 List: declarationList,208 })209 return list210}211func (self *_parser) parseObjectPropertyKey() (string, string) {212 idx, tkn, literal := self.idx, self.token, self.literal213 value := ""214 if self.mode&StoreComments != 0 {215 self.comments.MarkComments(ast.KEY)216 }217 self.next()218 switch tkn {219 case token.IDENTIFIER:220 value = literal221 case token.NUMBER:222 var err error223 _, err = parseNumberLiteral(literal)224 if err != nil {225 self.error(idx, err.Error())226 } else {227 value = literal228 }229 case token.STRING:230 var err error231 value, err = parseStringLiteral(literal[1 : len(literal)-1])232 if err != nil {233 self.error(idx, err.Error())234 }235 default:236 // null, false, class, etc.237 if matchIdentifier.MatchString(literal) {238 value = literal239 }240 }241 return literal, value242}243func (self *_parser) parseObjectProperty() ast.Property {244 literal, value := self.parseObjectPropertyKey()245 if literal == "get" && self.token != token.COLON {246 idx := self.idx247 _, value := self.parseObjectPropertyKey()248 parameterList := self.parseFunctionParameterList()249 node := &ast.FunctionLiteral{250 Function: idx,251 ParameterList: parameterList,252 }253 self.parseFunctionBlock(node)254 return ast.Property{255 Key: value,256 Kind: "get",257 Value: node,258 }259 } else if literal == "set" && self.token != token.COLON {260 idx := self.idx261 _, value := self.parseObjectPropertyKey()262 parameterList := self.parseFunctionParameterList()263 node := &ast.FunctionLiteral{264 Function: idx,265 ParameterList: parameterList,266 }267 self.parseFunctionBlock(node)268 return ast.Property{269 Key: value,270 Kind: "set",271 Value: node,272 }273 }274 if self.mode&StoreComments != 0 {275 self.comments.MarkComments(ast.COLON)276 }277 self.expect(token.COLON)278 exp := ast.Property{279 Key: value,280 Kind: "value",281 Value: self.parseAssignmentExpression(),282 }283 if self.mode&StoreComments != 0 {284 self.comments.SetExpression(exp.Value)285 }286 return exp287}288func (self *_parser) parseObjectLiteral() ast.Expression {289 var value []ast.Property290 idx0 := self.expect(token.LEFT_BRACE)291 for self.token != token.RIGHT_BRACE && self.token != token.EOF {292 value = append(value, self.parseObjectProperty())293 if self.token == token.COMMA {294 if self.mode&StoreComments != 0 {295 self.comments.Unset()296 }297 self.next()298 continue299 }300 }301 if self.mode&StoreComments != 0 {302 self.comments.MarkComments(ast.FINAL)303 }304 idx1 := self.expect(token.RIGHT_BRACE)305 return &ast.ObjectLiteral{306 LeftBrace: idx0,307 RightBrace: idx1,308 Value: value,309 }310}311func (self *_parser) parseArrayLiteral() ast.Expression {312 idx0 := self.expect(token.LEFT_BRACKET)313 var value []ast.Expression314 for self.token != token.RIGHT_BRACKET && self.token != token.EOF {315 if self.token == token.COMMA {316 // This kind of comment requires a special empty expression node.317 empty := &ast.EmptyExpression{self.idx, self.idx}318 if self.mode&StoreComments != 0 {319 self.comments.SetExpression(empty)320 self.comments.Unset()321 }322 value = append(value, empty)323 self.next()324 continue325 }326 exp := self.parseAssignmentExpression()327 value = append(value, exp)328 if self.token != token.RIGHT_BRACKET {329 if self.mode&StoreComments != 0 {330 self.comments.Unset()331 }332 self.expect(token.COMMA)333 }334 }335 if self.mode&StoreComments != 0 {336 self.comments.MarkComments(ast.FINAL)337 }338 idx1 := self.expect(token.RIGHT_BRACKET)339 return &ast.ArrayLiteral{340 LeftBracket: idx0,341 RightBracket: idx1,342 Value: value,343 }344}345func (self *_parser) parseArgumentList() (argumentList []ast.Expression, idx0, idx1 file.Idx) {346 if self.mode&StoreComments != 0 {347 self.comments.Unset()348 }349 idx0 = self.expect(token.LEFT_PARENTHESIS)350 if self.token != token.RIGHT_PARENTHESIS {351 for {352 exp := self.parseAssignmentExpression()353 if self.mode&StoreComments != 0 {354 self.comments.SetExpression(exp)355 }356 argumentList = append(argumentList, exp)357 if self.token != token.COMMA {358 break359 }360 if self.mode&StoreComments != 0 {361 self.comments.Unset()362 }363 self.next()364 }365 }366 if self.mode&StoreComments != 0 {367 self.comments.Unset()368 }369 idx1 = self.expect(token.RIGHT_PARENTHESIS)370 return371}372func (self *_parser) parseCallExpression(left ast.Expression) ast.Expression {373 argumentList, idx0, idx1 := self.parseArgumentList()374 exp := &ast.CallExpression{375 Callee: left,376 LeftParenthesis: idx0,377 ArgumentList: argumentList,378 RightParenthesis: idx1,379 }380 if self.mode&StoreComments != 0 {381 self.comments.SetExpression(exp)382 }383 return exp384}385func (self *_parser) parseDotMember(left ast.Expression) ast.Expression {386 period := self.expect(token.PERIOD)387 literal := self.literal388 idx := self.idx389 if !matchIdentifier.MatchString(literal) {390 self.expect(token.IDENTIFIER)391 self.nextStatement()392 return &ast.BadExpression{From: period, To: self.idx}393 }394 self.next()395 return &ast.DotExpression{396 Left: left,397 Identifier: &ast.Identifier{398 Idx: idx,399 Name: literal,400 },401 }402}403func (self *_parser) parseBracketMember(left ast.Expression) ast.Expression {404 idx0 := self.expect(token.LEFT_BRACKET)405 member := self.parseExpression()406 idx1 := self.expect(token.RIGHT_BRACKET)407 return &ast.BracketExpression{408 LeftBracket: idx0,409 Left: left,410 Member: member,411 RightBracket: idx1,412 }413}414func (self *_parser) parseNewExpression() ast.Expression {415 idx := self.expect(token.NEW)416 callee := self.parseLeftHandSideExpression()417 node := &ast.NewExpression{418 New: idx,419 Callee: callee,420 }421 if self.token == token.LEFT_PARENTHESIS {422 argumentList, idx0, idx1 := self.parseArgumentList()423 node.ArgumentList = argumentList424 node.LeftParenthesis = idx0425 node.RightParenthesis = idx1426 }427 if self.mode&StoreComments != 0 {428 self.comments.SetExpression(node)429 }430 return node431}432func (self *_parser) parseLeftHandSideExpression() ast.Expression {433 var left ast.Expression434 if self.token == token.NEW {435 left = self.parseNewExpression()436 } else {437 if self.mode&StoreComments != 0 {438 self.comments.MarkComments(ast.LEADING)439 self.comments.MarkPrimary()440 }441 left = self.parsePrimaryExpression()442 }443 if self.mode&StoreComments != 0 {444 self.comments.SetExpression(left)445 }446 for {447 if self.token == token.PERIOD {448 left = self.parseDotMember(left)449 } else if self.token == token.LEFT_BRACKET {450 left = self.parseBracketMember(left)451 } else {452 break453 }454 }455 return left456}457func (self *_parser) parseLeftHandSideExpressionAllowCall() ast.Expression {458 allowIn := self.scope.allowIn459 self.scope.allowIn = true460 defer func() {461 self.scope.allowIn = allowIn462 }()463 var left ast.Expression464 if self.token == token.NEW {465 var newComments []*ast.Comment466 if self.mode&StoreComments != 0 {467 newComments = self.comments.FetchAll()468 self.comments.MarkComments(ast.LEADING)469 self.comments.MarkPrimary()470 }471 left = self.parseNewExpression()472 if self.mode&StoreComments != 0 {473 self.comments.CommentMap.AddComments(left, newComments, ast.LEADING)474 }475 } else {476 if self.mode&StoreComments != 0 {477 self.comments.MarkComments(ast.LEADING)478 self.comments.MarkPrimary()479 }480 left = self.parsePrimaryExpression()481 }482 if self.mode&StoreComments != 0 {483 self.comments.SetExpression(left)484 }485 for {486 if self.token == token.PERIOD {487 left = self.parseDotMember(left)488 } else if self.token == token.LEFT_BRACKET {489 left = self.parseBracketMember(left)490 } else if self.token == token.LEFT_PARENTHESIS {491 left = self.parseCallExpression(left)492 } else {493 break494 }495 }496 return left497}498func (self *_parser) parsePostfixExpression() ast.Expression {499 operand := self.parseLeftHandSideExpressionAllowCall()500 switch self.token {501 case token.INCREMENT, token.DECREMENT:502 // Make sure there is no line terminator here503 if self.implicitSemicolon {504 break505 }506 tkn := self.token507 idx := self.idx508 if self.mode&StoreComments != 0 {509 self.comments.Unset()510 }511 self.next()512 switch operand.(type) {513 case *ast.Identifier, *ast.DotExpression, *ast.BracketExpression:514 default:515 self.error(idx, "Invalid left-hand side in assignment")516 self.nextStatement()517 return &ast.BadExpression{From: idx, To: self.idx}518 }519 exp := &ast.UnaryExpression{520 Operator: tkn,521 Idx: idx,522 Operand: operand,523 Postfix: true,524 }525 if self.mode&StoreComments != 0 {526 self.comments.SetExpression(exp)527 }528 return exp529 }530 return operand531}532func (self *_parser) parseUnaryExpression() ast.Expression {533 switch self.token {534 case token.PLUS, token.MINUS, token.NOT, token.BITWISE_NOT:535 fallthrough536 case token.DELETE, token.VOID, token.TYPEOF:537 tkn := self.token538 idx := self.idx539 if self.mode&StoreComments != 0 {540 self.comments.Unset()541 }542 self.next()543 return &ast.UnaryExpression{544 Operator: tkn,545 Idx: idx,546 Operand: self.parseUnaryExpression(),547 }548 case token.INCREMENT, token.DECREMENT:549 tkn := self.token550 idx := self.idx551 if self.mode&StoreComments != 0 {552 self.comments.Unset()553 }554 self.next()555 operand := self.parseUnaryExpression()556 switch operand.(type) {557 case *ast.Identifier, *ast.DotExpression, *ast.BracketExpression:558 default:559 self.error(idx, "Invalid left-hand side in assignment")560 self.nextStatement()561 return &ast.BadExpression{From: idx, To: self.idx}562 }563 return &ast.UnaryExpression{564 Operator: tkn,565 Idx: idx,566 Operand: operand,567 }568 }569 return self.parsePostfixExpression()570}571func (self *_parser) parseMultiplicativeExpression() ast.Expression {572 next := self.parseUnaryExpression573 left := next()574 for self.token == token.MULTIPLY || self.token == token.SLASH ||575 self.token == token.REMAINDER {576 tkn := self.token577 if self.mode&StoreComments != 0 {578 self.comments.Unset()579 }580 self.next()581 left = &ast.BinaryExpression{582 Operator: tkn,583 Left: left,584 Right: next(),585 }586 }587 return left588}589func (self *_parser) parseAdditiveExpression() ast.Expression {590 next := self.parseMultiplicativeExpression591 left := next()592 for self.token == token.PLUS || self.token == token.MINUS {593 tkn := self.token594 if self.mode&StoreComments != 0 {595 self.comments.Unset()596 }597 self.next()598 left = &ast.BinaryExpression{599 Operator: tkn,600 Left: left,601 Right: next(),602 }603 }604 return left605}606func (self *_parser) parseShiftExpression() ast.Expression {607 next := self.parseAdditiveExpression608 left := next()609 for self.token == token.SHIFT_LEFT || self.token == token.SHIFT_RIGHT ||610 self.token == token.UNSIGNED_SHIFT_RIGHT {611 tkn := self.token612 if self.mode&StoreComments != 0 {613 self.comments.Unset()614 }615 self.next()616 left = &ast.BinaryExpression{617 Operator: tkn,618 Left: left,619 Right: next(),620 }621 }622 return left623}624func (self *_parser) parseRelationalExpression() ast.Expression {625 next := self.parseShiftExpression626 left := next()627 allowIn := self.scope.allowIn628 self.scope.allowIn = true629 defer func() {630 self.scope.allowIn = allowIn631 }()632 switch self.token {633 case token.LESS, token.LESS_OR_EQUAL, token.GREATER, token.GREATER_OR_EQUAL:634 tkn := self.token635 if self.mode&StoreComments != 0 {636 self.comments.Unset()637 }638 self.next()639 exp := &ast.BinaryExpression{640 Operator: tkn,641 Left: left,642 Right: self.parseRelationalExpression(),643 Comparison: true,644 }645 return exp646 case token.INSTANCEOF:647 tkn := self.token648 if self.mode&StoreComments != 0 {649 self.comments.Unset()650 }651 self.next()652 exp := &ast.BinaryExpression{653 Operator: tkn,654 Left: left,655 Right: self.parseRelationalExpression(),656 }657 return exp658 case token.IN:659 if !allowIn {660 return left661 }662 tkn := self.token663 if self.mode&StoreComments != 0 {664 self.comments.Unset()665 }666 self.next()667 exp := &ast.BinaryExpression{668 Operator: tkn,669 Left: left,670 Right: self.parseRelationalExpression(),671 }672 return exp673 }674 return left675}676func (self *_parser) parseEqualityExpression() ast.Expression {677 next := self.parseRelationalExpression678 left := next()679 for self.token == token.EQUAL || self.token == token.NOT_EQUAL ||680 self.token == token.STRICT_EQUAL || self.token == token.STRICT_NOT_EQUAL {681 tkn := self.token682 if self.mode&StoreComments != 0 {683 self.comments.Unset()684 }685 self.next()686 left = &ast.BinaryExpression{687 Operator: tkn,688 Left: left,689 Right: next(),690 Comparison: true,691 }692 }693 return left694}695func (self *_parser) parseBitwiseAndExpression() ast.Expression {696 next := self.parseEqualityExpression697 left := next()698 for self.token == token.AND {699 if self.mode&StoreComments != 0 {700 self.comments.Unset()701 }702 tkn := self.token703 self.next()704 left = &ast.BinaryExpression{705 Operator: tkn,706 Left: left,707 Right: next(),708 }709 }710 return left711}712func (self *_parser) parseBitwiseExclusiveOrExpression() ast.Expression {713 next := self.parseBitwiseAndExpression714 left := next()715 for self.token == token.EXCLUSIVE_OR {716 if self.mode&StoreComments != 0 {717 self.comments.Unset()718 }719 tkn := self.token720 self.next()721 left = &ast.BinaryExpression{722 Operator: tkn,723 Left: left,724 Right: next(),725 }726 }727 return left728}729func (self *_parser) parseBitwiseOrExpression() ast.Expression {730 next := self.parseBitwiseExclusiveOrExpression731 left := next()732 for self.token == token.OR {733 if self.mode&StoreComments != 0 {734 self.comments.Unset()735 }736 tkn := self.token737 self.next()738 left = &ast.BinaryExpression{739 Operator: tkn,740 Left: left,741 Right: next(),742 }743 }744 return left745}746func (self *_parser) parseLogicalAndExpression() ast.Expression {747 next := self.parseBitwiseOrExpression748 left := next()749 for self.token == token.LOGICAL_AND {750 if self.mode&StoreComments != 0 {751 self.comments.Unset()752 }753 tkn := self.token754 self.next()755 left = &ast.BinaryExpression{756 Operator: tkn,757 Left: left,758 Right: next(),759 }760 }761 return left762}763func (self *_parser) parseLogicalOrExpression() ast.Expression {764 next := self.parseLogicalAndExpression765 left := next()766 for self.token == token.LOGICAL_OR {767 if self.mode&StoreComments != 0 {768 self.comments.Unset()769 }770 tkn := self.token771 self.next()772 left = &ast.BinaryExpression{773 Operator: tkn,774 Left: left,775 Right: next(),776 }777 }778 return left779}780func (self *_parser) parseConditionlExpression() ast.Expression {781 left := self.parseLogicalOrExpression()782 if self.token == token.QUESTION_MARK {783 if self.mode&StoreComments != 0 {784 self.comments.Unset()785 }786 self.next()787 consequent := self.parseAssignmentExpression()788 if self.mode&StoreComments != 0 {789 self.comments.Unset()790 }791 self.expect(token.COLON)792 exp := &ast.ConditionalExpression{793 Test: left,794 Consequent: consequent,795 Alternate: self.parseAssignmentExpression(),796 }797 return exp798 }799 return left800}801func (self *_parser) parseAssignmentExpression() ast.Expression {802 left := self.parseConditionlExpression()803 var operator token.Token804 switch self.token {805 case token.ASSIGN:806 operator = self.token807 case token.ADD_ASSIGN:808 operator = token.PLUS809 case token.SUBTRACT_ASSIGN:810 operator = token.MINUS811 case token.MULTIPLY_ASSIGN:812 operator = token.MULTIPLY813 case token.QUOTIENT_ASSIGN:814 operator = token.SLASH815 case token.REMAINDER_ASSIGN:816 operator = token.REMAINDER817 case token.AND_ASSIGN:818 operator = token.AND819 case token.AND_NOT_ASSIGN:820 operator = token.AND_NOT821 case token.OR_ASSIGN:822 operator = token.OR823 case token.EXCLUSIVE_OR_ASSIGN:824 operator = token.EXCLUSIVE_OR825 case token.SHIFT_LEFT_ASSIGN:826 operator = token.SHIFT_LEFT827 case token.SHIFT_RIGHT_ASSIGN:828 operator = token.SHIFT_RIGHT829 case token.UNSIGNED_SHIFT_RIGHT_ASSIGN:830 operator = token.UNSIGNED_SHIFT_RIGHT831 }832 if operator != 0 {833 idx := self.idx834 if self.mode&StoreComments != 0 {835 self.comments.Unset()836 }837 self.next()838 switch left.(type) {839 case *ast.Identifier, *ast.DotExpression, *ast.BracketExpression:840 default:841 self.error(left.Idx0(), "Invalid left-hand side in assignment")842 self.nextStatement()843 return &ast.BadExpression{From: idx, To: self.idx}844 }845 exp := &ast.AssignExpression{846 Left: left,847 Operator: operator,848 Right: self.parseAssignmentExpression(),849 }850 if self.mode&StoreComments != 0 {851 self.comments.SetExpression(exp)852 }853 return exp854 }855 return left856}857func (self *_parser) parseExpression() ast.Expression {858 next := self.parseAssignmentExpression859 left := next()860 if self.token == token.COMMA {861 sequence := []ast.Expression{left}862 for {863 if self.token != token.COMMA {864 break865 }866 self.next()867 sequence = append(sequence, next())868 }869 return &ast.SequenceExpression{870 Sequence: sequence,871 }872 }873 return left874}...

Full Screen

Full Screen

package_text.go

Source:package_text.go Github

copy

Full Screen

...56 p.scanner.Mode = scanner.ScanIdents | scanner.ScanInts | scanner.ScanStrings |57 scanner.ScanComments | scanner.ScanChars | scanner.SkipComments58 p.scanner.Whitespace = 1<<'\t' | 1<<' ' | 1<<'\r' | 1<<'\v' | 1<<'\f'59 p.scanner.Filename = "package.go"60 p.next()61 // and the built-in "unsafe" package to the path_to_name map62 p.path_to_name = map[string]string{"unsafe": "unsafe"}63 p.pfc = pfc64}65func (p *gc_parser) next() {66 p.tok = p.scanner.Scan()67 switch p.tok {68 case scanner.Ident, scanner.Int, scanner.String:69 p.lit = p.scanner.TokenText()70 default:71 p.lit = ""72 }73}74func (p *gc_parser) error(msg string) {75 panic(errors.New(msg))76}77func (p *gc_parser) errorf(format string, args ...interface{}) {78 p.error(fmt.Sprintf(format, args...))79}80func (p *gc_parser) expect(tok rune) string {81 lit := p.lit82 if p.tok != tok {83 p.errorf("expected %s, got %s (%q)", scanner.TokenString(tok),84 scanner.TokenString(p.tok), lit)85 }86 p.next()87 return lit88}89func (p *gc_parser) expect_keyword(keyword string) {90 lit := p.expect(scanner.Ident)91 if lit != keyword {92 p.errorf("expected keyword: %s, got: %q", keyword, lit)93 }94}95func (p *gc_parser) expect_special(what string) {96 i := 097 for i < len(what) {98 if p.tok != rune(what[i]) {99 break100 }101 nc := p.scanner.Peek()102 if i != len(what)-1 && nc <= ' ' {103 break104 }105 p.next()106 i++107 }108 if i < len(what) {109 p.errorf("expected: %q, got: %q", what, what[0:i])110 }111}112// dotIdentifier = "?" | ( ident | '·' ) { ident | int | '·' } .113// we're doing lexer job here, kind of114func (p *gc_parser) parse_dot_ident() string {115 if p.tok == '?' {116 p.next()117 return "?"118 }119 ident := ""120 sep := 'x'121 i, j := 0, -1122 for (p.tok == scanner.Ident || p.tok == scanner.Int || p.tok == '·') && sep > ' ' {123 ident += p.lit124 if p.tok == '·' {125 ident += "·"126 j = i127 i++128 }129 i += len(p.lit)130 sep = p.scanner.Peek()131 p.next()132 }133 // middot = \xc2\xb7134 if j != -1 && i > j+1 {135 c := ident[j+2]136 if c >= '0' && c <= '9' {137 ident = ident[0:j]138 }139 }140 return ident141}142// ImportPath = string_lit .143// quoted name of the path, but we return it as an identifier, taking an alias144// from 'pathToAlias' map, it is filled by import statements145func (p *gc_parser) parse_package() *ast.Ident {146 path, err := strconv.Unquote(p.expect(scanner.String))147 if err != nil {148 panic(err)149 }150 return ast.NewIdent(path)151}152// ExportedName = "@" ImportPath "." dotIdentifier .153func (p *gc_parser) parse_exported_name() *ast.SelectorExpr {154 p.expect('@')155 pkg := p.parse_package()156 if pkg.Name == "" {157 pkg.Name = "!" + p.pfc.name + "!" + p.pfc.defalias158 } else {159 pkg.Name = p.path_to_name[pkg.Name]160 }161 p.expect('.')162 name := ast.NewIdent(p.parse_dot_ident())163 return &ast.SelectorExpr{X: pkg, Sel: name}164}165// Name = identifier | "?" | ExportedName .166func (p *gc_parser) parse_name() (string, ast.Expr) {167 switch p.tok {168 case scanner.Ident:169 name := p.lit170 p.next()171 return name, ast.NewIdent(name)172 case '?':173 p.next()174 return "?", ast.NewIdent("?")175 case '@':176 en := p.parse_exported_name()177 return en.Sel.Name, en178 }179 p.error("name expected")180 return "", nil181}182// Field = Name Type [ string_lit ] .183func (p *gc_parser) parse_field() *ast.Field {184 var tag string185 name, _ := p.parse_name()186 typ := p.parse_type()187 if p.tok == scanner.String {188 tag = p.expect(scanner.String)189 }190 var names []*ast.Ident191 if name != "?" {192 names = []*ast.Ident{ast.NewIdent(name)}193 }194 return &ast.Field{195 Names: names,196 Type: typ,197 Tag: &ast.BasicLit{Kind: token.STRING, Value: tag},198 }199}200// Parameter = ( identifier | "?" ) [ "..." ] Type [ string_lit ] .201func (p *gc_parser) parse_parameter() *ast.Field {202 // name203 name, _ := p.parse_name()204 // type205 var typ ast.Expr206 if p.tok == '.' {207 p.expect_special("...")208 typ = &ast.Ellipsis{Elt: p.parse_type()}209 } else {210 typ = p.parse_type()211 }212 var tag string213 if p.tok == scanner.String {214 tag = p.expect(scanner.String)215 }216 return &ast.Field{217 Names: []*ast.Ident{ast.NewIdent(name)},218 Type: typ,219 Tag: &ast.BasicLit{Kind: token.STRING, Value: tag},220 }221}222// Parameters = "(" [ ParameterList ] ")" .223// ParameterList = { Parameter "," } Parameter .224func (p *gc_parser) parse_parameters() *ast.FieldList {225 flds := []*ast.Field{}226 parse_parameter := func() {227 par := p.parse_parameter()228 flds = append(flds, par)229 }230 p.expect('(')231 if p.tok != ')' {232 parse_parameter()233 for p.tok == ',' {234 p.next()235 parse_parameter()236 }237 }238 p.expect(')')239 return &ast.FieldList{List: flds}240}241// Signature = Parameters [ Result ] .242// Result = Type | Parameters .243func (p *gc_parser) parse_signature() *ast.FuncType {244 var params *ast.FieldList245 var results *ast.FieldList246 params = p.parse_parameters()247 switch p.tok {248 case scanner.Ident, '[', '*', '<', '@':249 fld := &ast.Field{Type: p.parse_type()}250 results = &ast.FieldList{List: []*ast.Field{fld}}251 case '(':252 results = p.parse_parameters()253 }254 return &ast.FuncType{Params: params, Results: results}255}256// MethodOrEmbedSpec = Name [ Signature ] .257func (p *gc_parser) parse_method_or_embed_spec() *ast.Field {258 name, nameexpr := p.parse_name()259 if p.tok == '(' {260 typ := p.parse_signature()261 return &ast.Field{262 Names: []*ast.Ident{ast.NewIdent(name)},263 Type: typ,264 }265 }266 return &ast.Field{267 Type: nameexpr,268 }269}270// int_lit = [ "-" | "+" ] { "0" ... "9" } .271func (p *gc_parser) parse_int() {272 switch p.tok {273 case '-', '+':274 p.next()275 }276 p.expect(scanner.Int)277}278// number = int_lit [ "p" int_lit ] .279func (p *gc_parser) parse_number() {280 p.parse_int()281 if p.lit == "p" {282 p.next()283 p.parse_int()284 }285}286//-------------------------------------------------------------------------------287// gc_parser.types288//-------------------------------------------------------------------------------289// InterfaceType = "interface" "{" [ MethodOrEmbedList ] "}" .290// MethodOrEmbedList = MethodOrEmbedSpec { ";" MethodOrEmbedSpec } .291func (p *gc_parser) parse_interface_type() ast.Expr {292 var methods []*ast.Field293 parse_method := func() {294 meth := p.parse_method_or_embed_spec()295 methods = append(methods, meth)296 }297 p.expect_keyword("interface")298 p.expect('{')299 if p.tok != '}' {300 parse_method()301 for p.tok == ';' {302 p.next()303 parse_method()304 }305 }306 p.expect('}')307 return &ast.InterfaceType{Methods: &ast.FieldList{List: methods}}308}309// StructType = "struct" "{" [ FieldList ] "}" .310// FieldList = Field { ";" Field } .311func (p *gc_parser) parse_struct_type() ast.Expr {312 var fields []*ast.Field313 parse_field := func() {314 fld := p.parse_field()315 fields = append(fields, fld)316 }317 p.expect_keyword("struct")318 p.expect('{')319 if p.tok != '}' {320 parse_field()321 for p.tok == ';' {322 p.next()323 parse_field()324 }325 }326 p.expect('}')327 return &ast.StructType{Fields: &ast.FieldList{List: fields}}328}329// MapType = "map" "[" Type "]" Type .330func (p *gc_parser) parse_map_type() ast.Expr {331 p.expect_keyword("map")332 p.expect('[')333 key := p.parse_type()334 p.expect(']')335 elt := p.parse_type()336 return &ast.MapType{Key: key, Value: elt}337}338// ChanType = ( "chan" [ "<-" ] | "<-" "chan" ) Type .339func (p *gc_parser) parse_chan_type() ast.Expr {340 dir := ast.SEND | ast.RECV341 if p.tok == scanner.Ident {342 p.expect_keyword("chan")343 if p.tok == '<' {344 p.expect_special("<-")345 dir = ast.SEND346 }347 } else {348 p.expect_special("<-")349 p.expect_keyword("chan")350 dir = ast.RECV351 }352 elt := p.parse_type()353 return &ast.ChanType{Dir: dir, Value: elt}354}355// ArrayOrSliceType = ArrayType | SliceType .356// ArrayType = "[" int_lit "]" Type .357// SliceType = "[" "]" Type .358func (p *gc_parser) parse_array_or_slice_type() ast.Expr {359 p.expect('[')360 if p.tok == ']' {361 // SliceType362 p.next() // skip ']'363 return &ast.ArrayType{Len: nil, Elt: p.parse_type()}364 }365 // ArrayType366 lit := p.expect(scanner.Int)367 p.expect(']')368 return &ast.ArrayType{369 Len: &ast.BasicLit{Kind: token.INT, Value: lit},370 Elt: p.parse_type(),371 }372}373// Type =374// BasicType | TypeName | ArrayType | SliceType | StructType |375// PointerType | FuncType | InterfaceType | MapType | ChanType |376// "(" Type ")" .377// BasicType = ident .378// TypeName = ExportedName .379// SliceType = "[" "]" Type .380// PointerType = "*" Type .381// FuncType = "func" Signature .382func (p *gc_parser) parse_type() ast.Expr {383 switch p.tok {384 case scanner.Ident:385 switch p.lit {386 case "struct":387 return p.parse_struct_type()388 case "func":389 p.next()390 return p.parse_signature()391 case "interface":392 return p.parse_interface_type()393 case "map":394 return p.parse_map_type()395 case "chan":396 return p.parse_chan_type()397 default:398 lit := p.lit399 p.next()400 return ast.NewIdent(lit)401 }402 case '@':403 return p.parse_exported_name()404 case '[':405 return p.parse_array_or_slice_type()406 case '*':407 p.next()408 return &ast.StarExpr{X: p.parse_type()}409 case '<':410 return p.parse_chan_type()411 case '(':412 p.next()413 typ := p.parse_type()414 p.expect(')')415 return typ416 }417 p.errorf("unexpected token: %s", scanner.TokenString(p.tok))418 return nil419}420//-------------------------------------------------------------------------------421// gc_parser.declarations422//-------------------------------------------------------------------------------423// ImportDecl = "import" identifier string_lit .424func (p *gc_parser) parse_import_decl() {425 p.expect_keyword("import")426 alias := p.expect(scanner.Ident)427 path := p.parse_package()428 fullName := "!" + path.Name + "!" + alias429 p.path_to_name[path.Name] = fullName430 p.pfc.add_package_to_scope(fullName, path.Name)431}432// ConstDecl = "const" ExportedName [ Type ] "=" Literal .433// Literal = bool_lit | int_lit | float_lit | complex_lit | string_lit .434// bool_lit = "true" | "false" .435// complex_lit = "(" float_lit "+" float_lit ")" .436// rune_lit = "(" int_lit "+" int_lit ")" .437// string_lit = `"` { unicode_char } `"` .438func (p *gc_parser) parse_const_decl() (string, *ast.GenDecl) {439 // TODO: do we really need actual const value? gocode doesn't use this440 p.expect_keyword("const")441 name := p.parse_exported_name()442 var typ ast.Expr443 if p.tok != '=' {444 typ = p.parse_type()445 }446 p.expect('=')447 // skip the value448 switch p.tok {449 case scanner.Ident:450 // must be bool, true or false451 p.next()452 case '-', '+', scanner.Int:453 // number454 p.parse_number()455 case '(':456 // complex_lit or rune_lit457 p.next() // skip '('458 if p.tok == scanner.Char {459 p.next()460 } else {461 p.parse_number()462 }463 p.expect('+')464 p.parse_number()465 p.expect(')')466 case scanner.Char:467 p.next()468 case scanner.String:469 p.next()470 default:471 p.error("expected literal")472 }473 return name.X.(*ast.Ident).Name, &ast.GenDecl{474 Tok: token.CONST,475 Specs: []ast.Spec{476 &ast.ValueSpec{477 Names: []*ast.Ident{name.Sel},478 Type: typ,479 Values: []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: "0"}},480 },481 },482 }483}484// TypeDecl = "type" ExportedName Type .485func (p *gc_parser) parse_type_decl() (string, *ast.GenDecl) {486 p.expect_keyword("type")487 name := p.parse_exported_name()488 typ := p.parse_type()489 return name.X.(*ast.Ident).Name, &ast.GenDecl{490 Tok: token.TYPE,491 Specs: []ast.Spec{492 &ast.TypeSpec{493 Name: name.Sel,494 Type: typ,495 },496 },497 }498}499// VarDecl = "var" ExportedName Type .500func (p *gc_parser) parse_var_decl() (string, *ast.GenDecl) {501 p.expect_keyword("var")502 name := p.parse_exported_name()503 typ := p.parse_type()504 return name.X.(*ast.Ident).Name, &ast.GenDecl{505 Tok: token.VAR,506 Specs: []ast.Spec{507 &ast.ValueSpec{508 Names: []*ast.Ident{name.Sel},509 Type: typ,510 },511 },512 }513}514// FuncBody = "{" ... "}" .515func (p *gc_parser) parse_func_body() {516 p.expect('{')517 for i := 1; i > 0; p.next() {518 switch p.tok {519 case '{':520 i++521 case '}':522 i--523 }524 }525}526// FuncDecl = "func" ExportedName Signature [ FuncBody ] .527func (p *gc_parser) parse_func_decl() (string, *ast.FuncDecl) {528 // "func" was already consumed by lookahead529 name := p.parse_exported_name()530 typ := p.parse_signature()531 if p.tok == '{' {532 p.parse_func_body()533 }534 return name.X.(*ast.Ident).Name, &ast.FuncDecl{535 Name: name.Sel,536 Type: typ,537 }538}539func strip_method_receiver(recv *ast.FieldList) string {540 var sel *ast.SelectorExpr541 // find selector expression542 typ := recv.List[0].Type543 switch t := typ.(type) {544 case *ast.StarExpr:545 sel = t.X.(*ast.SelectorExpr)546 case *ast.SelectorExpr:547 sel = t548 }549 // extract package path550 pkg := sel.X.(*ast.Ident).Name551 // write back stripped type552 switch t := typ.(type) {553 case *ast.StarExpr:554 t.X = sel.Sel555 case *ast.SelectorExpr:556 recv.List[0].Type = sel.Sel557 }558 return pkg559}560// MethodDecl = "func" Receiver Name Signature .561// Receiver = "(" ( identifier | "?" ) [ "*" ] ExportedName ")" [ FuncBody ] .562func (p *gc_parser) parse_method_decl() (string, *ast.FuncDecl) {563 recv := p.parse_parameters()564 pkg := strip_method_receiver(recv)565 name, _ := p.parse_name()566 typ := p.parse_signature()567 if p.tok == '{' {568 p.parse_func_body()569 }570 return pkg, &ast.FuncDecl{571 Recv: recv,572 Name: ast.NewIdent(name),573 Type: typ,574 }575}576// Decl = [ ImportDecl | ConstDecl | TypeDecl | VarDecl | FuncDecl | MethodDecl ] "\n" .577func (p *gc_parser) parse_decl() (pkg string, decl ast.Decl) {578 switch p.lit {579 case "import":580 p.parse_import_decl()581 case "const":582 pkg, decl = p.parse_const_decl()583 case "type":584 pkg, decl = p.parse_type_decl()585 case "var":586 pkg, decl = p.parse_var_decl()587 case "func":588 p.next()589 if p.tok == '(' {590 pkg, decl = p.parse_method_decl()591 } else {592 pkg, decl = p.parse_func_decl()593 }594 }595 p.expect('\n')596 return597}598// Export = PackageClause { Decl } "$$" .599// PackageClause = "package" identifier [ "safe" ] "\n" .600func (p *gc_parser) parse_export(callback func(string, ast.Decl)) {601 p.expect_keyword("package")602 p.pfc.defalias = p.expect(scanner.Ident)...

Full Screen

Full Screen

parser.go

Source:parser.go Github

copy

Full Screen

...16 infixParseFns map[token.TokenType]infixParseFn17}18func New(l *lexer.Lexer) *Parser {19 p := &Parser{l: l, errors: []string{}} // Read two tokens, so curToken and peekToken are both set20 p.nextToken()21 p.nextToken()22 p.prefixParseFns = make(map[token.TokenType]prefixParseFn)23 p.registerPrefix(token.IDENT, p.parseIdentifier)24 p.registerPrefix(token.INT, p.parseIntegerLiteral)25 p.registerPrefix(token.BANG, p.parsePrefixExpression)26 p.registerPrefix(token.MINUS, p.parsePrefixExpression)27 p.registerPrefix(token.TRUE, p.parseBoolean)28 p.registerPrefix(token.FALSE, p.parseBoolean)29 p.registerPrefix(token.LPAREN, p.parseGroupedExpression)30 p.registerPrefix(token.IF, p.parseIfExpression)31 p.registerPrefix(token.FUNCTION, p.parseFunctionLiteral)32 p.infixParseFns = make(map[token.TokenType]infixParseFn)33 p.registerInfix(token.PLUS, p.parseInfixExpression)34 p.registerInfix(token.MINUS, p.parseInfixExpression)35 p.registerInfix(token.SLASH, p.parseInfixExpression)36 p.registerInfix(token.ASTERISK, p.parseInfixExpression)37 p.registerInfix(token.EQ, p.parseInfixExpression)38 p.registerInfix(token.NOT_EQ, p.parseInfixExpression)39 p.registerInfix(token.LT, p.parseInfixExpression)40 p.registerInfix(token.GT, p.parseInfixExpression)41 p.registerInfix(token.LPAREN, p.parseCallExpression)42 return p43}44func (p *Parser) Errors() []string {45 return p.errors46}47func (p *Parser) peekError(t token.TokenType) {48 msg := fmt.Sprintf("expected next token to be %s, got %s instead", t, p.peekToken.Type)49 p.errors = append(p.errors, msg)50}51func (p *Parser) nextToken() {52 p.curToken = p.peekToken53 p.peekToken = p.l.NextToken()54}55func (p *Parser) ParseProgram() *ast.Program {56 program := &ast.Program{}57 program.Statements = []ast.Statement{}58 for p.curToken.Type != token.EOF {59 stmt := p.parseStatement()60 if stmt != nil {61 program.Statements = append(program.Statements, stmt)62 }63 p.nextToken()64 }65 return program66}67func (p *Parser) parseStatement() ast.Statement {68 switch p.curToken.Type {69 case token.LET:70 return p.parseLetStatement()71 case token.RETURN:72 return p.parseReturnStatement()73 default:74 return p.parseExpressionStatement()75 }76}77func (p *Parser) parseReturnStatement() *ast.ReturnStatement {78 stmt := &ast.ReturnStatement{Token: p.curToken}79 p.nextToken()80 stmt.ReturnValue = p.parseExpression(LOWEST)81 if p.peekTokenIs(token.SEMICOLON) {82 p.nextToken()83 }84 return stmt85}86func (p *Parser) parseLetStatement() *ast.LetStatement {87 stmt := &ast.LetStatement{Token: p.curToken}88 if !p.expectPeek(token.IDENT) {89 return nil90 }91 stmt.Name = &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}92 if !p.expectPeek(token.ASSIGN) {93 return nil94 }95 p.nextToken()96 stmt.Value = p.parseExpression(LOWEST)97 if p.peekTokenIs(token.SEMICOLON) {98 p.nextToken()99 }100 return stmt101}102func (p *Parser) parseExpressionStatement() *ast.ExpressionStatement {103 stmt := &ast.ExpressionStatement{Token: p.curToken}104 stmt.Expression = p.parseExpression(LOWEST)105 if p.peekTokenIs(token.SEMICOLON) {106 p.nextToken()107 }108 return stmt109}110func (p *Parser) noPrefixParseFnError(t token.TokenType) {111 msg := fmt.Sprintf("no prefix parse function for %s found", t)112 p.errors = append(p.errors, msg)113}114func (p *Parser) parseExpression(precedence int) ast.Expression {115 prefix := p.prefixParseFns[p.curToken.Type]116 if prefix == nil {117 p.noPrefixParseFnError(p.curToken.Type)118 return nil119 }120 leftExp := prefix()121 for !p.peekTokenIs(token.SEMICOLON) && precedence < p.peekPrecedence() {122 infix := p.infixParseFns[p.peekToken.Type]123 if infix == nil {124 return leftExp125 }126 p.nextToken()127 leftExp = infix(leftExp)128 }129 return leftExp130}131func (p *Parser) parseIdentifier() ast.Expression {132 return &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}133}134func (p *Parser) parseIntegerLiteral() ast.Expression {135 lit := &ast.IntegerLiteral{Token: p.curToken}136 value, err := strconv.ParseInt(p.curToken.Literal, 0, 64)137 if err != nil {138 msg := fmt.Sprintf("could not parse %q as integer", p.curToken.Literal)139 p.errors = append(p.errors, msg)140 return nil141 }142 lit.Value = value143 return lit144}145func (p *Parser) parsePrefixExpression() ast.Expression {146 expression := &ast.PrefixExpression{Token: p.curToken, Operator: p.curToken.Literal}147 p.nextToken()148 expression.Right = p.parseExpression(PREFIX)149 return expression150}151func (p *Parser) parseInfixExpression(left ast.Expression) ast.Expression {152 expression := &ast.InfixExpression{153 Token: p.curToken,154 Operator: p.curToken.Literal,155 Left: left,156 }157 precedence := p.curPrecedence()158 p.nextToken()159 expression.Right = p.parseExpression(precedence)160 return expression161}162func (p *Parser) parseBoolean() ast.Expression {163 return &ast.Boolean{Token: p.curToken, Value: p.curTokenIs(token.TRUE)}164}165func (p *Parser) parseGroupedExpression() ast.Expression {166 p.nextToken()167 exp := p.parseExpression(LOWEST)168 if !p.expectPeek(token.RPAREN) {169 return nil170 }171 return exp172}173func (p *Parser) parseIfExpression() ast.Expression {174 expression := &ast.IfExpression{Token: p.curToken}175 if !p.expectPeek(token.LPAREN) {176 return nil177 }178 p.nextToken()179 expression.Condition = p.parseExpression(LOWEST)180 if !p.expectPeek(token.RPAREN) {181 return nil182 }183 if !p.expectPeek(token.LBRACE) {184 return nil185 }186 expression.Consequence = p.parseBlockStatement()187 if p.peekTokenIs(token.ELSE) {188 p.nextToken()189 if !p.expectPeek(token.LBRACE) {190 return nil191 }192 expression.Alternative = p.parseBlockStatement()193 }194 return expression195}196func (p *Parser) parseBlockStatement() *ast.BlockStatement {197 block := &ast.BlockStatement{Token: p.curToken}198 block.Statements = []ast.Statement{}199 p.nextToken()200 for !p.curTokenIs(token.RBRACE) && !p.curTokenIs(token.EOF) {201 stmt := p.parseStatement()202 if stmt != nil {203 block.Statements = append(block.Statements, stmt)204 }205 p.nextToken()206 }207 return block208}209func (p *Parser) parseCallExpression(function ast.Expression) ast.Expression {210 exp := &ast.CallExpression{Token: p.curToken, Function: function}211 exp.Arguments = p.parseCallArguments()212 return exp213}214func (p *Parser) parseCallArguments() []ast.Expression {215 args := []ast.Expression{}216 if p.peekTokenIs(token.RPAREN) {217 p.nextToken()218 return args219 }220 p.nextToken()221 args = append(args, p.parseExpression(LOWEST))222 for p.peekTokenIs(token.COMMA) {223 p.nextToken()224 p.nextToken()225 args = append(args, p.parseExpression(LOWEST))226 }227 if !p.expectPeek(token.RPAREN) {228 return nil229 }230 return args231}232const (233 _ int = iota234 LOWEST235 EQUALS236 LESSGREATER237 SUM238 PRODUCT239 PREFIX240 CALL241)242var precedences = map[token.TokenType]int{243 token.EQ: EQUALS,244 token.NOT_EQ: EQUALS,245 token.LT: LESSGREATER,246 token.GT: LESSGREATER,247 token.PLUS: SUM,248 token.MINUS: SUM,249 token.SLASH: PRODUCT,250 token.ASTERISK: PRODUCT,251 token.LPAREN: CALL,252}253func (p *Parser) peekPrecedence() int {254 if p, ok := precedences[p.peekToken.Type]; ok {255 return p256 }257 return LOWEST258}259func (p *Parser) curPrecedence() int {260 if p, ok := precedences[p.curToken.Type]; ok {261 return p262 }263 return LOWEST264}265func (p *Parser) parseFunctionLiteral() ast.Expression {266 lit := &ast.FunctionLiteral{Token: p.curToken}267 if !p.expectPeek(token.LPAREN) {268 return nil269 }270 lit.Parameters = p.parseFunctionParameters()271 if !p.expectPeek(token.LBRACE) {272 return nil273 }274 lit.Body = p.parseBlockStatement()275 return lit276}277func (p *Parser) parseFunctionParameters() []*ast.Identifier {278 identifiers := []*ast.Identifier{}279 if p.peekTokenIs(token.RPAREN) {280 p.nextToken()281 return identifiers282 }283 p.nextToken()284 ident := &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}285 identifiers = append(identifiers, ident)286 for p.peekTokenIs(token.COMMA) {287 p.nextToken()288 p.nextToken()289 ident := &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}290 identifiers = append(identifiers, ident)291 }292 if !p.expectPeek(token.RPAREN) {293 return nil294 }295 return identifiers296}297func (p *Parser) curTokenIs(t token.TokenType) bool {298 return p.curToken.Type == t299}300func (p *Parser) peekTokenIs(t token.TokenType) bool {301 return p.peekToken.Type == t302}303func (p *Parser) expectPeek(t token.TokenType) bool {304 if p.peekTokenIs(t) {305 p.nextToken()306 return true307 } else {308 p.peekError(t)309 return false310 }311}312type (313 prefixParseFn func() ast.Expression314 infixParseFn func(ast.Expression) ast.Expression315)316func (p *Parser) registerPrefix(tokenType token.TokenType, fn prefixParseFn) {317 p.prefixParseFns[tokenType] = fn318}319func (p *Parser) registerInfix(tokenType token.TokenType, fn infixParseFn) {...

Full Screen

Full Screen

next

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 node, err := parser.ParseFile(fset, "1.go", nil, 0)5 if err != nil {6 fmt.Println(err)7 }8 ast.Inspect(node, func(n ast.Node) bool {9 switch x := n.(type) {10 fmt.Println(x)11 fmt.Println(x.Body.List)12 fmt.Println(x.Body.List[0])13 fmt.Println(x.Body.List[0].(*ast.ExprStmt).X)14 fmt.Println(x.Body.List[0].(*ast.ExprStmt).X.(*ast.CallExpr))15 fmt.Println(x.Body.List[0].(*ast.ExprStmt).X.(*ast.CallExpr).Fun)16 fmt.Println(x.Body.List[0].(*ast.ExprStmt).X.(*ast.CallExpr).Fun.(*ast.SelectorExpr))17 fmt.Println(x.Body.List[0].(*ast.ExprStmt).X.(*ast.CallExpr).Fun.(*ast.SelectorExpr).X)18 fmt.Println(x.Body.List[0].(*ast.ExprStmt).X.(*ast.CallExpr).Fun.(*ast.SelectorExpr).Sel)

Full Screen

Full Screen

next

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 node, err := parser.ParseFile(fset, "2.go", nil, parser.ParseComments)4 if err != nil {5 fmt.Println(err)6 }7 ast.Inspect(node, func(n ast.Node) bool {8 switch x := n.(type) {9 for _, spec := range x.Specs {10 fmt.Println(spec)11 }12 fmt.Println(x.Name)13 }14 })15}

Full Screen

Full Screen

next

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 panic(err)7 }8 for _, s := range f.Imports {9 fmt.Println(s.Path.Value)10 }11}

Full Screen

Full Screen

next

Using AI Code Generation

copy

Full Screen

1if (node instanceof ast) {2 ast a = (ast)node;3 a.next();4}5if (node instanceof ast) {6 ast a = (ast)node;7 a.next();8}9if (node instanceof ast) {10 ast a = (ast)node;11 a.next();12}13if (node instanceof ast) {14 ast a = (ast)node;15 a.next();16}17if (node instanceof ast) {18 ast a = (ast)node;19 a.next();20}21if (node instanceof ast) {22 ast a = (ast)node;23 a.next();24}25if (node instanceof ast) {26 ast a = (ast)node;27 a.next();28}29if (node instanceof ast) {30 ast a = (ast)node;31 a.next();32}33if (node instanceof ast) {34 ast a = (ast)node;35 a.next();36}37if (node instanceof ast) {38 ast a = (ast)node;39 a.next();40}41if (node instanceof ast) {42 ast a = (ast)node;43 a.next();44}45if (node instanceof ast) {46 ast a = (ast)node;47 a.next();48}49if (node instanceof ast) {50 ast a = (ast)node;51 a.next();52}53if (node instanceof

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