-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExampleHandler.cs
More file actions
341 lines (294 loc) · 13 KB
/
Copy pathExampleHandler.cs
File metadata and controls
341 lines (294 loc) · 13 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
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
333
334
335
336
337
338
339
340
341
using System.Reflection;
using System.Text;
using SER.Code.Extensions;
using SER.Code.Helpers.ResultSystem;
using SER.Code.MethodSystem.Methods.CustomRoleMethods.Structures;
using SER.Code.ScriptSystem;
using SER.Code.ScriptSystem.Structures;
namespace SER.Code.Helpers;
public static class ExampleHandler
{
private static Dictionary<string, string>? _cachedExamples;
private const string RootFolder = "Example_Scripts";
public static Dictionary<string, string> GetAllExamples()
{
if (_cachedExamples != null) return _cachedExamples;
var assembly = Assembly.GetExecutingAssembly();
// Look for resources that contain our root folder and end with .ser
var resourceNames = assembly.GetManifestResourceNames()
.Where(n => n.Contains(RootFolder) && n.EndsWith(".ser"));
var examples = new Dictionary<string, string>();
foreach (var name in resourceNames)
{
using var stream = assembly.GetManifestResourceStream(name);
if (stream == null) continue;
using var reader = new StreamReader(stream);
string content = reader.ReadToEnd();
string relativePath = GetRelativePath(name);
examples[relativePath] = content;
}
return _cachedExamples = examples;
}
private static string GetRelativePath(string resourceName)
{
// 1. Find where the "Example Scripts" folder starts in the namespace string
int rootIndex = resourceName.IndexOf(RootFolder, StringComparison.InvariantCulture);
if (rootIndex == -1) return resourceName;
// 2. Get everything after "Example Scripts."
string pathWithExtension = resourceName[(rootIndex + RootFolder.Length + 1)..];
// 3. Remove the .ser extension
int lastDot = pathWithExtension.LastIndexOf(".ser", StringComparison.InvariantCulture);
string pathWithoutExtension = pathWithExtension[..lastDot];
// 4. Convert dots to directory separators (optional, but cleaner for "folders")
// e.g., "UI.Inventory" instead of "UI/Inventory" if you prefer keeping it as a key
return pathWithoutExtension.Replace('.', '/');
}
public static string? GetExample(string path)
{
return GetAllExamples().TryGetValue(path, out var content) ? content : null;
}
[UsedImplicitly]
public static (string?, string[]) Verify(string? projectDirectory = null)
{
var examples = GetAllExamples();
foreach (var example in examples)
{
// example.Key now contains the folder path (e.g., "Combat/Fireball")
if (ScriptSection.Split(example.Key, example.Value)
.HasErrored(out var exampleSplitError, out var exampleSections))
{
return (new Result(false, $"while splitting example '{example.Key}'") + exampleSplitError.AsError(),
examples.Keys.ToArray());
}
foreach (var section in exampleSections)
{
if (Script.CreateByVerifiedSection(section, ScriptExecutor.Get())
.Compile()
.HasErrored(out var error))
{
return (new Result(false, $"in example section '{section.Name}'") + error.AsError(),
examples.Keys.ToArray());
}
}
}
if (VerifyDocumentationExamples(projectDirectory).HasErrored(out var documentationError))
{
return (documentationError, examples.Keys.ToArray());
}
var regressionScripts = new Dictionary<string, string>
{
["event_toggle_returns"] =
"$disabled = DisableEvent \"Hurting\"\n$enabled = EnableEvent \"Hurting\"",
["sermethod_returning_shape"] = "DB.Exists \"..\""
};
foreach (var regressionScript in regressionScripts)
{
var script = Script.CreateAnonymous(regressionScript.Key, regressionScript.Value);
if (script.Compile().HasErrored(out var error))
{
return (new Result(false, $"in regression script '{regressionScript.Key}'") + error.AsError(),
examples.Keys.ToArray());
}
if (regressionScript.Key == "sermethod_returning_shape" &&
!script.IsSingleSynchronousReturningMethod)
{
return ("The sermethod regression was not recognized as a synchronous returning method.",
examples.Keys.ToArray());
}
}
var invalidScripts = new Dictionary<string, string>
{
["missing_end"] = "if true\n Print \"this block is intentionally not closed\"",
["extra_end"] = "end"
};
foreach (var invalidScript in invalidScripts)
{
if (!Script.CreateAnonymous(invalidScript.Key, invalidScript.Value)
.Compile()
.HasErrored())
{
return ($"The validator accepted invalid regression script '{invalidScript.Key}'.",
examples.Keys.ToArray());
}
}
const string multiSectionContent =
"# file comment\n\n" +
"!-- OnEvent RoundStarted\n" +
"Print \"round started\"\n\n" +
"!-- CustomCommand status\n" +
"Print \"status\"";
if (ScriptSection.Split("multi_section", multiSectionContent)
.HasErrored(out var splitError, out var sections))
{
return ($"The multi-section regression could not be split: {splitError}", examples.Keys.ToArray());
}
if (sections.Length != 2
|| sections[0].Name.ToString() != "multi_section:1"
|| sections[0].StartLine != 3
|| sections[1].Name.ToString() != "multi_section:2"
|| sections[1].StartLine != 6
|| sections[0].Content.Contains("CustomCommand"))
{
return ("The multi-section regression produced incorrect boundaries or identities.",
examples.Keys.ToArray());
}
foreach (var section in sections)
{
if (Script.CreateByVerifiedSection(section, ScriptExecutor.Get())
.Compile()
.HasErrored(out var sectionError))
{
return ($"Multi-section regression '{section.Name}' failed to compile: {sectionError}",
examples.Keys.ToArray());
}
}
if (!ScriptSection.Split("invalid_preamble", "Print \"outside\"\n!-- Function\nPrint \"inside\"")
.HasErrored())
{
return ("The multi-section splitter accepted executable content before the first flag.",
examples.Keys.ToArray());
}
FileSystem.FileSystem.ParseSectionSelector("cRoleSpawn:3", out var selectedFile, out var selectedSection);
if (selectedFile != "cRoleSpawn" || selectedSection != 3)
{
return ("A bare multi-section selector did not resolve to its physical script file.",
examples.Keys.ToArray());
}
FileSystem.FileSystem.ParseSectionSelector(
@"C:\SER\custom roles\cRoleSpawn.ser:1",
out selectedFile,
out selectedSection);
if (selectedFile != "cRoleSpawn" || selectedSection != 1)
{
return ("A full-path multi-section selector did not resolve to its physical script file.",
examples.Keys.ToArray());
}
if (!CRole.PassesSpawnChance(1f, 0.999999999)
|| CRole.PassesSpawnChance(0f, 0d)
|| !CRole.PassesSpawnChance(0.5f, 0.49d)
|| CRole.PassesSpawnChance(0.5f, 0.5d)
|| CRole.GetCappedSpawnCount(5, 1) != 1
|| CRole.GetCappedSpawnCount(5, null) != 5
|| CRole.GetCappedSpawnCount(5, -1) != 0)
{
return ("Custom-role spawn chance boundary handling is incorrect.", examples.Keys.ToArray());
}
const string invalidSecondSection =
"!-- Function\n" +
"Print \"valid\"\n" +
"!-- Function\n" +
"end";
if (ScriptSection.Split("section_lines", invalidSecondSection)
.HasErrored(out splitError, out sections)
|| !Script.CreateByVerifiedSection(sections[1], ScriptExecutor.Get())
.Compile()
.HasErrored(out var lineError)
|| !lineError.Contains("Line 4"))
{
return ("Multi-section compilation did not preserve physical source line numbers.",
examples.Keys.ToArray());
}
return (null, examples.Keys.ToArray());
}
private static Result VerifyDocumentationExamples(string? projectDirectory)
{
var documentationDirectory = !string.IsNullOrWhiteSpace(projectDirectory)
? Path.Combine(projectDirectory, "docs")
: FindDocumentationDirectory();
if (documentationDirectory is null)
{
return new(false, "Documentation directory was not found from the build or assembly path.");
}
foreach (var filename in Directory.GetFiles(documentationDirectory, "*.md", SearchOption.AllDirectories))
{
var relativeFilename = filename[(documentationDirectory.Length + 1)..]
.Replace(Path.DirectorySeparatorChar, '/');
var blockNumber = 0;
var blockStartLine = 0;
var insideSerBlock = false;
var content = new StringBuilder();
var lineNumber = 0;
foreach (var line in File.ReadLines(filename))
{
lineNumber++;
var trimmedLine = line.Trim();
if (!insideSerBlock)
{
if (!trimmedLine.Equals("```ser", StringComparison.OrdinalIgnoreCase))
{
continue;
}
insideSerBlock = true;
blockNumber++;
blockStartLine = lineNumber + 1;
content.Clear();
continue;
}
if (!trimmedLine.Equals("```", StringComparison.Ordinal))
{
content.AppendLine(line);
continue;
}
// Optional integrations are not loaded by every build configuration.
// Their snippets remain executable on matching servers, while the
// generated method manifest verifies that their API still exists.
if (content.ToString().TrimStart()
.StartsWith("# requires ", StringComparison.OrdinalIgnoreCase))
{
insideSerBlock = false;
continue;
}
var snippetName = $"docs_{Path.GetFileNameWithoutExtension(filename)}_{blockNumber}";
if (ScriptSection.Split(snippetName, content.ToString(), filename)
.HasErrored(out var splitError, out var sections))
{
return new Result(false,
$"while splitting SER block {blockNumber} in '{relativeFilename}' (line {blockStartLine})")
+ splitError.AsError();
}
foreach (var section in sections)
{
if (Script.CreateByVerifiedSection(section, ScriptExecutor.Get())
.Compile()
.HasErrored(out var compileError))
{
return new Result(false,
$"in SER block {blockNumber} in '{relativeFilename}' (line {blockStartLine})")
+ compileError.AsError();
}
}
insideSerBlock = false;
}
if (insideSerBlock)
{
return new(false,
$"Unterminated SER block {blockNumber} in '{relativeFilename}' (line {blockStartLine - 1}).");
}
}
return new(true, string.Empty);
}
private static string? FindDocumentationDirectory()
{
var startingDirectories = new List<DirectoryInfo>
{
new(Directory.GetCurrentDirectory())
};
var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!string.IsNullOrWhiteSpace(assemblyDirectory))
{
startingDirectories.Add(new(assemblyDirectory));
}
foreach (var startingDirectory in startingDirectories)
{
for (var directory = startingDirectory; directory is not null; directory = directory.Parent)
{
var candidate = Path.Combine(directory.FullName, "docs");
if (Directory.Exists(candidate) && File.Exists(Path.Combine(candidate, "SUMMARY.md")))
{
return candidate;
}
}
}
return null;
}
}