-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLexer.cs
126 lines (95 loc) · 3.38 KB
/
Lexer.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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
using System.Text;
namespace SlimScript;
internal class Lexer
{
public static List<List<Token>> Lex(string[] source, SourceChunk chunk)
{
try
{
int _line = 0;
List<List<Token>> Lines = new();
void addLine()
{
_line++;
Lines.Add(new());
}
addLine();
for (int i = 0; i < source.Length; i++)
{
string element = source[i];
Token token = new(element);
if (token.Type == TokenType.EOL)
{
addLine();
continue;
}
Lines[_line -1].Add(token);
}
Lines = Lines.Where(line => line.Count != 0).ToList();
if (!Program.interactive)
{
StringBuilder? sb = null;
if (Program.Debug)
sb = new();
StringBuilder? compressed = null;
if (Program.CompressStandalone)
compressed = new();
bool first = false;
if (sb == null && compressed == null)
return Lines;
foreach (var tokens in Lines)
{
first = true;
foreach (var token in tokens)
{
sb?.Append($"[{token}: {token.Text}] ");
compressed?.Append($"{(first ? string.Empty : " ")}{token.Text}");
first = false;
}
sb?.AppendLine();
compressed?.AppendLine();
}
if (Program.Debug && (Path.GetFileNameWithoutExtension(chunk._file) != "???"))
File.WriteAllText(
$"{Path.GetFileNameWithoutExtension(chunk._file) ?? string.Empty}_l.sso",
sb?.ToString()
);
if (Program.CompressStandalone)
File.WriteAllBytes(
$"{Path.GetFileNameWithoutExtension(chunk._file) ?? string.Empty}.csso",
Program.Compress(Encoding.UTF8.GetBytes(compressed?.ToString() ?? ""))
);
if (Program.CompressStandalone)
{
Console.ForegroundColor = ConsoleColor.Green;
Write.StandartOutput.WriteLine(
$"Successfully created and compressed standalone script file {Path.GetFileNameWithoutExtension(chunk._file) ?? string.Empty}.csso"
);
Program.Exit(ExitCode.Normal);
}
}
return Lines;
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Write.StandartOutput.WriteLine(
$"An Error occured during Lexical Analysis.\nMessage:{e.Message}"
);
Program.Exit(ExitCode.LexerError);
return new();
}
}
public static List<Token> LexLine(string[] line)
{
List<Token> result = new();
foreach (var item in line)
{
Token token = new(item);
if (token.Type == TokenType.EOL)
break;
result.Add(token);
}
return result;
}
}