private int Func(LexemeBuffer lexemeBuffer) { string name = lexemeBuffer.Next.Value; Lexeme lexeme = lexemeBuffer.Next; if (lexeme.Type != LexemeType.LEFT_BRACKET) { throw new Exception("Wrong function call syntax at " + lexeme.Value); } List <int> args = new List <int>(); lexeme = lexemeBuffer.Next; if (lexeme.Type != LexemeType.RIGHT_BRACKET) { lexemeBuffer.Back(); do { args.Add(Expr(lexemeBuffer)); lexeme = lexemeBuffer.Next; if (lexeme.Type != LexemeType.COMMA && lexeme.Type != LexemeType.RIGHT_BRACKET) { throw new Exception("Wrong function call syntax at " + lexeme.Value); } } while (lexeme.Type == LexemeType.COMMA); } functionMap.TryGetValue(name, out IFunction value); return(value.Apply(args)); }
private int Multdiv(LexemeBuffer lexemes) { int value = Factor(lexemes); while (true) { Lexeme lexeme = lexemes.Next; switch (lexeme.Type) { case LexemeType.OP_MUL: value *= Factor(lexemes); break; case LexemeType.OP_DIV: value /= Factor(lexemes); break; case LexemeType.EOF: case LexemeType.RIGHT_BRACKET: case LexemeType.OP_PLUS: case LexemeType.OP_MINUS: case LexemeType.COMMA: lexemes.Back(); return(value); default: throw new Exception("Unexpected token: " + lexeme.Value + " at position: " + lexemes.Position); } } }
private int Factor(LexemeBuffer lexemes) { Lexeme lexeme = lexemes.Next; switch (lexeme.Type) { case LexemeType.NUMBER: return(int.Parse(lexeme.Value)); case LexemeType.NAME: lexemes.Back(); return(Func(lexemes)); case LexemeType.OP_MINUS: int value = Factor(lexemes); return(-value); case LexemeType.LEFT_BRACKET: value = Plusminus(lexemes); lexeme = lexemes.Next; if (lexeme.Type != LexemeType.RIGHT_BRACKET) { throw new Exception("Unexpected token: " + lexeme.Value + " at position: " + lexemes.Position); } return(value); default: throw new Exception("Unexpected token: " + lexeme.Value + " at position: " + lexemes.Position); } }
public int Expr(LexemeBuffer lexemes) { Lexeme lexeme = lexemes.Next; if (lexeme.Type == LexemeType.EOF) { return(0); } else { lexemes.Back(); return(Plusminus(lexemes)); } }