-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
332 lines (280 loc) · 10.8 KB
/
Program.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
using SourceGenerator.Grammar;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
namespace SourceGenerator;
using static Token;
internal class Program
{
#if DEBUG
public const string BIND_INTERFACE = "0.0.0.0";
#else
public const string BIND_INTERFACE = "127.0.0.1";
#endif
public const int PORT = 58994;
public static Fsa Dfa { get; private set; }
public static int ThreadId => Environment.CurrentManagedThreadId;
private static readonly ConcurrentDictionary<int, StringBuilder> sourceBuilders = new();
private static StringBuilder SourceBuilder => sourceBuilders[ThreadId];
public static void Main(string[] _)
{
InitializeFsa();
var ip = new IPEndPoint(IPAddress.Parse(BIND_INTERFACE), PORT);
using var server = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
server.Bind(ip);
server.Listen(PORT);
var consoleLine = new TrackedConsoleLine();
consoleLine.Write($"LISTENING ON PORT {PORT}", color: ConsoleColor.Cyan);
while (true)
{
var client = server.Accept();
new Thread(() => HandleClient(client)).Start();
}
}
private static void HandleClient(Socket client)
{
var consoleLine = new TrackedConsoleLine();
consoleLine.Write((client.RemoteEndPoint as IPEndPoint).Address.ToString(), color: ConsoleColor.Cyan);
var recvBuffer = new byte[2048];
var sourceText = new StringBuilder();
using (client)
{
var unterminated = true;
while (unterminated)
{
var readBytes = client.Receive(recvBuffer);
if (readBytes == 0)
{
break;
}
sourceText.Append(Encoding.UTF8.GetString(recvBuffer
.Take(readBytes)
.TakeWhile((it) => unterminated &= it != '\0')
.ToArray()));
}
var source = new TokenStream()
{
Grammar = Dfa,
Source = sourceText.ToString()
};
try
{
if (source.Poll() != (int)Ident)
{
throw new Exception("Provide compilation or action command");
}
var command = source.Text;
if (source.Next != (int)LCurly)
{
throw new Exception("Provide encoded name of source file");
}
var fileName = TopLevelGrammar.MatchCSharp(source);
consoleLine.Write($" [] RECEIVED {fileName} AT {DateTime.Now:yyyy-MM-dd HH:mm:ss}", color: ConsoleColor.White);
var output = command switch
{
"generate" => Generate(fileName, source, consoleLine),
"highlight" => Highlight(fileName, source, consoleLine),
_ => throw new Exception("Invalid command")
};
client.Send(Encoding.UTF8.GetBytes(output));
} catch (Exception ex)
{
var fullMessage = ex.InnerException is null
? ex.Message
: $"{ex.Message} - {ex.InnerException.Message}";
consoleLine.Write($" !! {fullMessage}", color: ConsoleColor.Red);
client.Send(Encoding.UTF8.GetBytes(fullMessage));
}
}
}
public static void Append(string source, params object[] args)
{
SourceBuilder.Append(string.Format(source, args));
}
public static void AppendLine(string source, params object[] args)
{
SourceBuilder.AppendLine(string.Format(source, args));
}
private static void InitializeFsa()
{
var startTime = DateTime.Now;
var nfa = new Fsa();
nfa.Build("schema", (int)Schema);
nfa.Build("partial", (int)Partial);
nfa.Build("repo", (int)Repo);
nfa.Build("service", (int)Service);
nfa.Build("json", (int)Json);
nfa.Build("state", (int)State);
nfa.Build("interface", (int)Interface);
nfa.Build("dto", (int)Dto);
nfa.Build("api", (int)Api);
nfa.Build("[a-zA-Z_]([a-zA-Z0-9_\\<\\>\\[\\]\\.\\?]+)?", (int)Ident);
nfa.Build("\\{", (int)LCurly);
nfa.Build("\\}", (int)RCurly);
nfa.Build("\\(", (int)LParen);
nfa.Build("\\)", (int)RParen);
nfa.Build("\\,", (int)Comma);
nfa.Build("\\.\\.\\.", (int)Splat);
nfa.Build("\\=", (int)Assign);
nfa.Build("\\=\\>", (int)Arrow);
nfa.Build("\\<\\>", (int)LRfReduce);
nfa.Build("\\<\\/\\>", (int)RRfReduce);
nfa.Build("\\<\\\"\\>", (int)LMultiLine);
nfa.Build("\\<\\/\\\"\\>", (int)RMultiLine);
nfa.Build("\\|", (int)Bar);
nfa.Build("[ \n\r\t]+", 9999);
var consoleLine = new TrackedConsoleLine();
consoleLine.Write($"CREATED NFA IN {(DateTime.Now - startTime).TotalMilliseconds}ms", color: ConsoleColor.Cyan);
startTime = DateTime.Now;
Dfa = nfa.ConvertToDfa().MinimizeDfa();
consoleLine.Write($" [] CREATED DFA IN {(DateTime.Now - startTime).TotalMilliseconds}ms", color: ConsoleColor.Cyan);
}
public static string Generate(string fileName, TokenStream source, TrackedConsoleLine consoleLine)
{
sourceBuilders[ThreadId] = new();
// Must remain at character zero of a successful result
AppendLine("/* DO NOT EDIT THIS FILE */");
var startTime = DateTime.Now;
AppendLine($"// GENERATED FROM {fileName} AT {startTime:yyyy-MM-dd HH:mm:ss}");
AppendLine("#nullable disable");
AppendLine("namespace Generated;");
var ext = Path.GetExtension(fileName).ToLowerInvariant();
var modelName = Path.GetFileNameWithoutExtension(fileName);
try
{
switch (ext)
{
case ".model":
TopLevelGrammar.MatchModel(source, modelName);
break;
case ".view":
TopLevelGrammar.MatchView(source, modelName);
break;
}
} catch (Exception ex)
{
sourceBuilders.Remove(ThreadId, out var _);
int lineNumber = 1, prevLine = 0;
for (int i = 0; i <= source.Offset && i < source.Source.Length; i++)
{
if (source.Source[i] == '\n')
{
lineNumber++;
prevLine = i;
}
}
var lineChar = source.Offset - prevLine + 1;
throw new Exception($"{fileName}:{lineNumber}:{lineChar}", ex);
}
var millis = (DateTime.Now - startTime).TotalMilliseconds;
AppendLine($"// GENERATED IN {millis}ms");
consoleLine.Write($" [] GENERATED IN {millis}ms", ConsoleColor.Green);
return sourceBuilders.Remove(ThreadId, out var _v)
? _v.ToString()
: throw new Exception("String builder missing from dictionary");
}
private static readonly ConcurrentDictionary<int, (TokenStream source, List<MatchSpan> spanList)> spanLists = new();
private static (TokenStream source, List<MatchSpan> spanList) SourceSpanList => spanLists[ThreadId];
public static void StartSpan(ClassType classification, int? index = null)
{
if (!spanLists.ContainsKey(ThreadId))
{
return;
}
var (source, spanList) = SourceSpanList;
index ??= source.Offset;
var prev = spanList.LastOrDefault();
if (prev is not null)
{
if (prev.l == -1)
{
prev.l = index.Value - prev.s;
}
//if (prev.s + prev.l < index.Value)
//{
// spanList.Add(new()
// {
// c = ClassType.PlainText,
// s = prev.s + prev.l,
// l = index.Value - (prev.s + prev.l)
// });
//}
}
spanList.Add(new()
{
c = classification,
s = index.Value
});
}
public static void EndSpan(int? index = null)
{
if (!spanLists.ContainsKey(ThreadId))
{
return;
}
var (source, spanList) = SourceSpanList;
index ??= source.Offset;
var prev = spanList.LastOrDefault();
if (prev is not null && prev.l == -1)
{
prev.l = index.Value - prev.s;
}
}
public static string Highlight(string fileName, TokenStream source, TrackedConsoleLine consoleLine)
{
var startTime = DateTime.Now;
spanLists[ThreadId] = (source, []);
var ext = Path.GetExtension(fileName).ToLowerInvariant();
var modelName = Path.GetFileNameWithoutExtension(fileName);
try
{
_ = source.Next;
var sourceStart = source.Offset;
StartSpan(ClassType.PlainText, sourceStart);
switch (ext)
{
case ".model":
TopLevelGrammar.MatchModel(source, modelName, meta: true);
break;
case ".view":
TopLevelGrammar.MatchView(source, modelName, meta: true);
break;
}
EndSpan();
var (_, spanList) = SourceSpanList;
//var last = spanList.LastOrDefault();
//if (last.s + last.l < source.Source.Length)
//{
// spanList.Add(new()
// {
// c = ClassType.PlainText,
// s = source.Offset,
// l = source.Source.Length - (last.s + last.l)
// });
//}
spanList.ForEach((it) => it.s -= sourceStart);
spanList.RemoveAll((it) => it.l == 0);
} catch (Exception ex)
{
spanLists.Remove(ThreadId, out var _);
int lineNumber = 1, prevLine = 0;
for (int i = 0; i <= source.Offset && i < source.Source.Length; i++)
{
if (source.Source[i] == '\n')
{
lineNumber++;
prevLine = i;
}
}
var lineChar = source.Offset - prevLine + 1;
throw new Exception($"{fileName}:{lineNumber}:{lineChar}", ex);
}
var millis = (DateTime.Now - startTime).TotalMilliseconds;
consoleLine.Write($" [] HIGHLIGHTED IN {millis}ms", ConsoleColor.Magenta);
return spanLists.Remove(ThreadId, out var _v)
? JsonSerializer.Serialize(_v.spanList, MatchSpanJsonContext.Default.ListMatchSpan)
: throw new Exception("Match spans missing from dictionary");
}
}