-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.cs
79 lines (69 loc) · 2.23 KB
/
Parser.cs
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
namespace Luminor
{
public enum NodeType
{
Program,
Assignment,
Print
}
public class Node
{
public NodeType Type { get; }
public string? Name { get; }
public object? Value { get; set; }
public List<Node> Body { get; }
public Node(NodeType type, string? name, object? value)
{
Type = type;
Name = name;
Value = value;
Body = new List<Node>();
}
public override string ToString()
{
return $"{Type}: {Name} = {Value}";
}
}
public class Parser(List<Token> tokens)
{
public Node Parse()
{
var cursor = 0;
var program = new Node(NodeType.Program, string.Empty, null);
while (cursor < tokens.Count)
{
var token = tokens[cursor];
if (token.Type == TokenType.Keyword && token.Value == "lu")
{
cursor++;
var declaration = new Node(NodeType.Assignment, tokens[cursor].Value, null);
cursor++;
var nextToken = tokens[cursor];
if (nextToken.Type == TokenType.Operator && nextToken.Value == "=")
{
cursor++;
var expression = string.Empty;
while (tokens.Count > 0 && tokens[cursor].Type != TokenType.Keyword)
{
expression += tokens[cursor].Value;
cursor++;
}
declaration.Value = expression;
program.Body.Add(declaration);
}
continue;
}
if (token.Type == TokenType.Keyword && token.Value == "le")
{
cursor++;
var nextToken = tokens[cursor];
var print = new Node(NodeType.Print, name: null, nextToken.Value);
program.Body.Add(print);
continue;
}
break;
}
return program;
}
}
}