parseExpression method parses an expression with a given precedence level and returns the parsed expression as an AST node. It takes an integer value indicating the precedence level.
(precedence int)
| 598 | |
| 599 | // parseExpression method parses an expression with a given precedence level and returns the parsed expression as an AST node. It takes an integer value indicating the precedence level. |
| 600 | func (p *Parser) parseExpression(precedence int) (ast.Expression, error) { |
| 601 | var exp ast.Expression |
| 602 | var err error |
| 603 | |
| 604 | if p.currentTokenIs(token.NEWLINE) && p.previousTokenIs(token.LP, token.AND, token.OR, token.NOT, token.ASSIGN) { |
| 605 | p.next() // skip newline after operators |
| 606 | } // Newline handling complete |
| 607 | if p.currentTokenIs(token.LP) { |
| 608 | p.next() // Consume the left parenthesis. |
| 609 | exp, err = p.parseExpression(LOWEST) |
| 610 | if err != nil { |
| 611 | return nil, err |
| 612 | } |
| 613 | |
| 614 | if !p.expect(token.RP) { |
| 615 | return nil, p.Error() |
| 616 | } |
| 617 | p.next() // Consume the right parenthesis. |
| 618 | } else { |
| 619 | // get the prefix parsing function for the current token type |
| 620 | prefix := p.prefixParseFns[p.currentToken.Type] |
| 621 | if prefix == nil { |
| 622 | p.noPrefixParseFnError(p.currentToken.Type) |
| 623 | return nil, p.Error() |
| 624 | } |
| 625 | |
| 626 | // parse the prefix expression |
| 627 | exp, err = prefix() |
| 628 | if err != nil { |
| 629 | return nil, p.Error() |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | // continue parsing the expression while the next token has a higher precedence level than the current precedence level |
| 634 | for !p.peekTokenIs(token.NEWLINE) && precedence < p.peekPrecedence() { |
| 635 | // get the infix parsing function for the next token type |
| 636 | infix := p.infixParseFunc[p.peekToken.Type] |
| 637 | if infix == nil { |
| 638 | return exp, nil |
| 639 | } |
| 640 | p.next() |
| 641 | // parse the infix expression with the current expression as its left-hand side |
| 642 | exp, err = infix(exp) |
| 643 | if err != nil { |
| 644 | return nil, p.Error() |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | // return the parsed expression and nil for the error value |
| 649 | return exp, nil |
| 650 | } |
| 651 | |
| 652 | // parseInfixExpression parses an infix expression that has a left operand and an operator followed by |
| 653 | // a right operand, such as "a or b" or "x and y". |
no test coverage detected