public Expression ParseExpression(int precedence = 0) { var token = Take(); IPrefixParselet prefix; IInfixParselet infix; if (!PrefixParselets.TryGetValue(token.ID, out prefix)) { throw new RantException(_src, token, "Invalid expression '\{token.Value}'."); } var left = prefix.Parse(this, token); // Break when the next token's precedence is less than or equal to the current precedence // This will assure that higher precedence operations like multiplication are parsed before lower operations. while (GetPrecedence() > precedence) { token = Take(); if (!InfixParselets.TryGetValue(token.ID, out infix)) { throw new RantException(_src, token, "Invalid operator '\{token.Value}'."); } // Replace the left expression with the next parsed expression. left = infix.Parse(this, left, token); } return(left); }
/// <summary> /// Returns the precedence of the next infix operator, or 0 if there is none. /// </summary> /// <returns></returns> private int GetPrecedence() { if (_pos == _tokens.Length) { return(0); } IInfixParselet infix; InfixParselets.TryGetValue(Peek().ID, out infix); return(infix?.Precedence ?? 0); }