Skip to content

Instantly share code, notes, and snippets.

@KvanTTT
Created September 12, 2017 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KvanTTT/9f57ac8cd07df654ec50edcefdb63bb5 to your computer and use it in GitHub Desktop.
Save KvanTTT/9f57ac8cd07df654ec50edcefdb63bb5 to your computer and use it in GitHub Desktop.
Parser that can add and sum integer numbers
using System.Collections.Generic;
using static System.Console;
namespace Expressions
{
public enum Operation
{
Add,
Mult,
Int
}
public class Token
{
public Operation Type { get; set; }
public string Value { get; set; }
public Token(Operation type, string value)
{
Type = type;
Value = value;
}
}
public class Tokenizer
{
public List<Token> Tokenize(string input)
{
var tokens = new List<Token>();
int i = 0;
while (i < input.Length)
{
Token token = null;
if (char.IsDigit(input[i]))
{
int j = i;
while (j < input.Length && char.IsDigit(input[j]))
j++;
token = new Token(Operation.Int, input.Substring(i, j - i));
i = j;
}
else if (input[i] == '+')
{
token = new Token(Operation.Add, "+");
i++;
}
else if (input[i] == '*')
{
token = new Token(Operation.Mult, "*");
i++;
}
else
{
WriteLine($"Incorrect input symbol '{input[i]}'");
i++;
}
if (token != null)
tokens.Add(token);
}
return tokens;
}
}
public class Parser
{
public List<Token> Tokens { get; set; }
public int TokenIndex { get; private set; }
public int? Parse(List<Token> tokens)
{
Tokens = tokens;
TokenIndex = 0;
return Add();
}
private int? Add()
{
int? mult = Mult();
if (mult != null)
{
if (Accept(Operation.Add))
return mult + Add();
return mult;
}
return null;
}
private int? Mult()
{
if (Accept(Operation.Int))
{
if (!int.TryParse(Tokens[TokenIndex - 1].Value, out int value))
{
WriteLine($"Integer recognition error at {TokenIndex - 1}");
return null;
}
if (Accept(Operation.Mult))
return value * Mult();
return value;
}
WriteLine($"Parse error at index {TokenIndex}");
return null;
}
private bool Accept(Operation op)
{
if (TokenIndex < Tokens.Count && Tokens[TokenIndex].Type == op)
{
TokenIndex += 1;
return true;
}
return false;
}
}
class Program
{
static void Main(string[] args)
{
var tokenizer = new Tokenizer();
var parser = new Parser();
do
{
Write("Enter input: ");
string input = ReadLine();
List<Token> tokens = tokenizer.Tokenize(input);
int? result = parser.Parse(tokens);
if (result != null)
WriteLine($"Result: {result}");
WriteLine();
}
while (true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment