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
|
/*
* GNU AFFERO GENERAL PUBLIC LICENSE
* Version 3, 19 November 2007
* Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace UVtools.Core.Scripting
{
public static class ScriptParser
{
public static string ParseScriptFromFile(string path)
{
return ParseScriptFromText(File.ReadAllText(path));
}
/// <summary>
/// Parse the script and clean forbidden keywords
/// </summary>
/// <param name="text">Text to parse</param>
/// <returns>The parsed text</returns>
public static string ParseScriptFromText(string text)
{
if(!Regex.Match(text, @"(void\s*ScriptInit\s*\(\s*\))").Success)
{
throw new ArgumentException("The method \"void ScriptInit()\" was not found on script, please verify the script.");
}
if (!Regex.Match(text, @"(string\s*ScriptValidate\s*\(\s*\))").Success)
{
throw new ArgumentException("The method \"string ScriptValidate()\" was not found on script, please verify the script.");
}
if (!Regex.Match(text, @"(bool\s*ScriptExecute\s*\(\s*\))").Success)
{
throw new ArgumentException("The method \"bool ScriptExecute()\" was not found on script, please verify the script.");
}
var textLength = text.Length;
sbyte bracketsToRemove = 0;
text = Regex.Replace(text, @"(namespace .*\n*.*{)", string.Empty);
if (textLength != text.Length) bracketsToRemove++;
textLength = text.Length;
text = Regex.Replace(text, "(.*class .*\n*.*{)", string.Empty);
if (textLength != text.Length) bracketsToRemove++;
if (bracketsToRemove <= 0) return text;
for (textLength = text.Length - 1; textLength >= 0 && bracketsToRemove > 0; textLength--)
{
if (text[textLength] == '}') bracketsToRemove--;
}
return text.Substring(0, textLength);
}
}
}
|