-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexer.cs
More file actions
110 lines (96 loc) · 3.54 KB
/
Copy pathLexer.cs
File metadata and controls
110 lines (96 loc) · 3.54 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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace JCore
{
public class Token
{
public string Type { get; set; }
public string Value { get; set; }
public Token(string type, string value)
{
Type = type;
Value = value;
}
}
public class Lexer
{
private string _code;
private static readonly Dictionary<string, string> Keywords = new()
{
{ "say", "SAY" },
{ "let", "LET" },
{ "make", "MAKE" }
};
private static readonly Dictionary<string, string> Operators = new()
{
{ "=", "EQUAL" },
{ "+", "PLUS" },
{ "-", "MINUS" },
{ "*", "STAR" },
{ "/", "SLASH" },
{ "(", "LPAREN" },
{ ")", "RPAREN" }
};
private static readonly Regex TokenPattern = new(
@"(?<STRING>""[^""\\]*(?:\\.[^""\\]*)*"")|(?<OP>[=+\-*/()])|(?<NUMBER>\d+)|(?<IDENT>[a-zA-Z_][a-zA-Z0-9_]*)",
RegexOptions.Compiled);
public Lexer(string code)
{
_code = code;
}
public List<Token> Tokenize()
{
var tokens = new List<Token>();
_code = Regex.Replace(_code, @"/\*.*?\*/", "", RegexOptions.Singleline);
var lines = _code.Split('\n');
foreach (var rawLine in lines)
{
var line = StripInlineComment(rawLine.Trim());
if (string.IsNullOrWhiteSpace(line)) continue;
var matches = TokenPattern.Matches(line);
foreach (Match match in matches)
{
if (match.Groups["STRING"].Success)
{
var raw = match.Groups["STRING"].Value;
var str = raw.Substring(1, raw.Length - 2);
tokens.Add(new Token("STRING", str));
}
else if (match.Groups["NUMBER"].Success)
{
tokens.Add(new Token("NUMBER", match.Groups["NUMBER"].Value));
}
else if (match.Groups["IDENT"].Success)
{
var value = match.Groups["IDENT"].Value;
if (Keywords.TryGetValue(value, out var keywordType))
tokens.Add(new Token(keywordType, value));
else
tokens.Add(new Token("IDENT", value));
}
else if (match.Groups["OP"].Success)
{
var op = match.Groups["OP"].Value;
if (Operators.TryGetValue(op, out var opType))
tokens.Add(new Token(opType, op));
else
throw new Exception($"Unknown operator: {op}");
}
}
}
return tokens;
}
private string StripInlineComment(string line)
{
bool inString = false;
for (int i = 0; i < line.Length - 1; i++)
{
if (line[i] == '"') inString = !inString;
if (!inString && line[i] == '/' && line[i + 1] == '/')
return line.Substring(0, i).Trim();
}
return line;
}
}
}