using System.Collections.Generic;
public enum TokenTypes { Symbol, Number }
public TokenTypes Type { get; set; }
public object Value { get; set; }
public Token(TokenTypes T, object v) { Value = v; Type = T; }
public override string ToString() { return "<" + Type + ", " + Value.ToString() + ">"; }
private IList<Token> Tokens;
private int CurrentCharPos;
private char CurrentChar { get { return (CurrentCharPos >= Input.Length) ? '\0' : Input[CurrentCharPos]; } }
private char NextChar { get { return (CurrentCharPos + 1 >= Input.Length) ? '\0' : Input[CurrentCharPos + 1]; } }
private bool IsEOF { get { return CurrentCharPos >= Input.Length; } }
return (CurrentChar == '+' || CurrentChar == '-' || CurrentChar == '*' || CurrentChar == '/') || (CurrentChar == '(' || CurrentChar == ')');
private bool IsDigit { get { return (CurrentChar >= '0' && CurrentChar <= '9'); } }
private bool IsNegNumber { get { return (CurrentChar == '-' && (NextChar >= '0' && NextChar <= '9')); } }
private void ScanNumber(bool neg = false)
if (neg) ++CurrentCharPos;
while (!IsEOF && IsDigit) {
thestring += CurrentChar;
int val = int.Parse(thestring);
Tokens.Add(new Token(TokenTypes.Number, val));
private void ScanSymbol()
Tokens.Add(new Token(TokenTypes.Symbol, CurrentChar));
public IList<Token> Scan(string inp)
CurrentCharPos = 0; Tokens.Clear(); Input = inp;
if (CurrentChar == ' ' || CurrentChar == '\t' || CurrentChar == '\r' || CurrentChar == '\n')
Console.WriteLine("Unexpected character: " + CurrentChar + "\n");
Tokens = new List<Token>(); Input = "";
public static IDictionary<char, int> Precedence;
public static void Configure() {
Precedence = new Dictionary<char, int>();
public static void PrintInfix(IList<Token> toks) {
foreach (Token t in toks) Console.Write(t.Value.ToString() + " ");
public static void PrintPostfix(IList<Token> toks) {
List<Token> tmptoks = new List<Token>();
Stack<Token> OpStack = new Stack<Token>();
if (toks[i].Type == TokenTypes.Number)
tmptoks.Add(toks[i]); ++i;
else if (toks[i].Type == TokenTypes.Symbol)
if (Precedence[(char)OpStack.Peek().Value] < Precedence[(char)toks[i].Value])
OpStack.Push(toks[i]); tmptoks.Add(toks[++i]);
public static void PrintPrefix(IList<Token> toks) {
public static void Main()
Lexer L = new Lexer(); string s = "";
Converter.PrintInfix(L.Scan(s));