示例#1
0
        //this implements pratt parsing(top down recursive parsing)
        //DaBeaz's course implemented this with loop instead of recursion (so although top down, it is not recursive). Look in "Solution Items/stuff" folder
        //for snapshots showing his approach. Not only is it not recursive(he uses loops), but he has also created a func for each precendence level.
        //his approach is more readable than what we have here.
        private AST_Helper.Expression parseExpression(Parser_Helper.precedence precedence)
        {
            if (!this.prefixParseFns.ContainsKey(this.curToken.Type))
            {
                noPrefixParseFnError(this.curToken.Type);
                return(null);
            }
            Parser_Helper.prefixParserFn prefixParserFn = this.prefixParseFns[this.curToken.Type];

            AST_Helper.Expression leftExpr = prefixParserFn();

            while (!this.peekTokenIs(TokenHelper.TokenType.SEMICOLON) && precedence < this.peekPrecedence())
            {
                if (!this.infixParseFns.ContainsKey(this.peekToken.Type))
                {
                    return(leftExpr);
                }

                Parser_Helper.infixParseFn infixParseFn = this.infixParseFns[this.peekToken.Type];
                this.nextToken();
                leftExpr = infixParseFn(leftExpr);//construct a new leftExpr expression using current leftExpr and next expr as rightExpr
            }

            return(leftExpr);
        }
示例#2
0
        private AST_Helper.Expression parseInfixExpression(AST_Helper.Expression left)
        {
            InfixExpression infixExpression = new InfixExpression {
                Token = this.curToken, Operator = this.curToken.Literal, Left = left
            };

            Parser_Helper.precedence precedence = this.curPrecedence();//precedence level of current token
            this.nextToken();

            //recursice call back to parseExpression. Control arrived here from parseExpression which we are now calling back
            infixExpression.Right = this.parseExpression(precedence);//it is here we pass precedence using the current context

            return(infixExpression);
        }