private ValueExpression EvaluateVariableExpression(IExpression expr) { VariableExpression variableExpr = (VariableExpression)expr; return(_variables.TryGetValue(variableExpr.Name, out double value) ? new ValueExpression(value) : throw LangException.UnassignedVariable(variableExpr)); }
private string ReadIdentifier(ISourceText stream) { const char identifierTerminator = '}'; StringBuilder builder = new StringBuilder("{", 12); stream.MoveNext(); if (char.IsLetter(stream.Current) || stream.Current == '_') { builder.Append(stream.Current); stream.MoveNext(); } else { Token token = new Token(TokenType.Unknown, stream.Current.ToString(), stream.Position); throw LangException.UnexpectedToken(token, TokenType.Identifier); } while (stream.Current != identifierTerminator) { if (char.IsLetterOrDigit(stream.Current) || stream.Current == '_') { builder.Append(stream.Current); stream.MoveNext(); } else { Token token = new Token(TokenType.Unknown, stream.Current.ToString(), stream.Position); throw LangException.UnexpectedToken(token, identifierTerminator); } } builder.Append(stream.Current); stream.MoveNext(); string text = builder.ToString(); if (text.Length == 2) { Token token = new Token(TokenType.Unknown, identifierTerminator.ToString(), stream.Position - 1); throw LangException.UnexpectedToken(token, identifierTerminator); } return(text); }
private IExpression ParsePrimaryExpression() { switch (_currentToken.Type) { case TokenType.Number: return(new ConstantExpression(Take().Text)); case TokenType.Identifier: VariableExpression rep = new VariableExpression(Take().Text); _variables.Add(rep.Name); return(rep); case TokenType.OpenParen: return(ParseGroupingExpression()); default: throw LangException.UnexpectedToken(_currentToken); } }
private string ReadNumber(ISourceText stream) { StringBuilder builder = new StringBuilder(8); bool hasDot = false; while (true) { if (stream.Current == '.') { if (!hasDot) { hasDot = true; builder.Append(stream.Current); stream.MoveNext(); } else { Token token = new Token(TokenType.Unknown, stream.Current.ToString(), stream.Position); throw LangException.UnexpectedToken(token, TokenType.Number); } } else if (char.IsDigit(stream.Current)) { builder.Append(stream.Current); stream.MoveNext(); } else { break; } } char peeked = stream.Peek(-1); if (peeked == '.') { Token token = new Token(TokenType.Unknown, peeked.ToString(), stream.Position); throw LangException.UnexpectedToken(token, TokenType.Number); } return(builder.ToString()); }
private Token Match(TokenType tokenType) { return(_currentToken.Type == tokenType ? Take() : throw LangException.UnexpectedToken(_currentToken, tokenType)); }