-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cs
More file actions
53 lines (47 loc) · 1.75 KB
/
Copy pathParser.cs
File metadata and controls
53 lines (47 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
namespace expr
{
class Parser
{
private Lexer lexer;
private List<Token> tokens;
private Dictionary<OperatorsType, int> PRECEDENCE = new Dictionary<OperatorsType, int>();
public Parser(Lexer lexer)
{
this.lexer = lexer;
this.tokens = lexer.Tokenize();
this.PRECEDENCE.Add(OperatorsType.MULTIPLY, 14);
this.PRECEDENCE.Add(OperatorsType.DIVIDE, 14);
this.PRECEDENCE.Add(OperatorsType.PLUS, 13);
this.PRECEDENCE.Add(OperatorsType.MINUS, 13);
}
private List<Token> CreatePostFix() {
List<Token> operandList = new List<Token>();
Stack<Token> operatorStack = new Stack<Token>();
foreach(Token token in this.tokens) {
if(token.Type == TokenType.OPERAND) {
operandList.Add(token);
} else {
if(operatorStack.Count > 0) {
for(int i = 0; i < operatorStack.Count; i++) {
if(this.PRECEDENCE[operatorStack.Peek().Operator] >= this.PRECEDENCE[token.Operator]) {
operandList.Add(operatorStack.Pop());
} else {
break;
}
}
}
operatorStack.Push(token);
}
}
Token[] remunants = operatorStack.ToArray();
foreach(Token remunant in remunants)
operandList.Add(remunant);
return operandList;
}
public List<Token> Parse() {
return this.CreatePostFix();
}
}
}