-
Notifications
You must be signed in to change notification settings - Fork 0
/
Precompiler.cs
242 lines (221 loc) · 10.8 KB
/
Precompiler.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
using System.IO;
using System.Text;
using System.Collections.Generic;
using System;
using System.Collections;
using System.Text.RegularExpressions;
namespace csscript
{
/// <summary>
/// This class is a container for information related to the script precompilation.
/// <para>It is used to pass an input information from the script engine to the <c>precompiler</c> instance as well as to pass back
/// to the script engine some output information (e.g. added referenced assemblies)</para> .
/// </summary>
internal class PrecompilationContext
{
///// <summary>
///// Full path of the script being passed for precompilation.
///// </summary>
//public string ScriptFileName;
///// <summary>
///// Flag, which indicates if the script passed for precompilation is an entry script (primary script).
///// <para>This field can be used to determine the precompilation algorithm based on the entry script. For example
///// generating the <c>static Main()</c> wrapper for classless scripts should be done only for an entry script but not for other included/imported script. </para>
///// </summary>
//public bool IsPrimaryScript = true;
/// <summary>
/// Collection of the referenced assemblies to be added to the process script referenced assemblies.
/// <para>You may want to add new items to the referenced assemblies because of the precompilation logic (e.g. some code using assemblies not referenced by the primary script
/// is injected in the script).</para>
/// </summary>
public List<string> NewReferences = new List<string>();
/// <summary>
/// Collection of the new dependency items (files).
/// <para>Dependency files are checked before the script execution in order to understand if the script should be recompiled or it can be loaded from
/// the cache. If any of the dependency files is changed since the last script execution the script engine will recompile the script. In the simple execution
/// scenarios the script file is a dependency file.</para>
/// </summary>
public List<string> NewDependencies = new List<string>();
/// <summary>
/// Collection of the new 'include' items (dependency source files).
/// </summary>
public List<string> NewIncludes = new List<string>();
/// <summary>
/// Collection of the assembly and script probing directories to be added to the process search directories.
/// <para>You may want to add new items to the process search directories because of the precompilation logic.</para>
/// </summary>
public List<string> NewSearchDirs = new List<string>();
/// <summary>
/// Collection of the process assembly and script probing directories.
/// </summary>
public string[] SearchDirs = new string[0];
}
///// <summary>
///// The interface that all CS-Script precompilers need to implement.
///// <para>
///// The following is an example of the precompiler for sanitizing the script containing hashbang string on Linux.
///// </para>
///// <code>
///// public class HashBangPrecompiler : IPrecompiler
///// {
///// public bool Compile(ref string code, PrecompilationContext context)
///// {
///// if (code.StartsWith("#!"))
///// {
///// code = "//" + code; //comment the Linux hashbang line to keep C# compiler happy
///// return true;
///// }
/////
///// return false;
///// }
///// }
///// </code>
///// </summary>
//public interface IPrecompiler
//{
// /// <summary>
// /// Compiles/modifies the specified code.
// /// <para>
// /// </para>
// /// </summary>
// /// <param name="code">The code to be compiled.</param>
// /// <param name="context">The context.</param>
// /// <returns><c>True</c> if the <paramref name="code"/> code has been modified and <c>False</c> </returns>
// bool Compile(ref string code, PrecompilationContext context);
//}
internal class DefaultPrecompiler
{
public static bool Compile(ref string code, string scriptFile, bool IsPrimaryScript, Hashtable context)
{
if (code.StartsWith("#!"))
{
code = "//" + code; //comment the Linux hashbang line to keep C# compiler happy
return true;
}
return false;
}
}
/// <summary>
/// AutoclassGenerator to be used by external applications for generating the auto-class from the classless scripts
/// </summary>
public class AutoclassGenerator
{
/// <summary>
/// Processes the specified code.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="injectionPos">The injection position.</param>
/// <param name="injectionLength">Length of the injection.</param>
/// <returns></returns>
static public string Process(string code, out int injectionPos, out int injectionLength)
{
return AutoclassPrecompiler.Process(code, out injectionPos, out injectionLength);
}
/// <summary>
/// Processes the specified code.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="position">The position.</param>
/// <returns></returns>
static public string Process(string code, ref int position)
{
int injectionPos;
int injectionLength;
string retval = AutoclassGenerator.Process(code, out injectionPos, out injectionLength);
if (position > injectionPos)
position += injectionLength;
return retval;
}
}
internal class AutoclassPrecompiler// : IPrecompiler
{
//static string FileToClassName(string text)
//{
// return Path.GetFileNameWithoutExtension(text).Replace("_", ""); //double '_' are not allowed for class names
//}
public static bool Compile(ref string content, string scriptFile, bool IsPrimaryScript, Hashtable context)
{
if (!IsPrimaryScript)
return false;
int injectionPos;
int injectionLength;
content = AutoclassPrecompiler.Process(content, out injectionPos, out injectionLength);
return true;
}
public static string Process(string content, out int injectionPos, out int injectionLength)
{
int entryPointInjectionPos = -1;
injectionPos = -1;
injectionLength = 0;
StringBuilder code = new StringBuilder(4096);
//code.Append("//Auto-generated file" + Environment.NewLine); //cannot use AppendLine as it is not available in StringBuilder v1.1
//code.Append("using System;\r\n");
bool headerProcessed = false;
string line;
using (StringReader sr = new StringReader(content))
{
bool autoCodeInjected = false;
while ((line = sr.ReadLine()) != null)
{
if (!headerProcessed && !line.TrimStart().StartsWith("using ")) //not using...; statement of the file header
if (!line.StartsWith("//") && line.Trim() != "") //not comments or empty line
{
headerProcessed = true;
injectionPos = code.Length;
string tempText = "public class ScriptClass { public ";
code.Append(tempText);
injectionLength += tempText.Length;
entryPointInjectionPos = code.Length;
}
if (!autoCodeInjected && entryPointInjectionPos != -1 && !Utils.IsNullOrWhiteSpace(line))
{
string text = line.TrimStart();
if (!text.StartsWith("//"))
{
//static void Main(string[] args)
//or
//int main(string[] args)
MatchCollection matches = Regex.Matches(text, @"\s+main\s*\(", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
if (match.Value.Contains("main")) //assembly pseudo entry point "instance main"
{
bool noargs = Regex.Matches(text, @"\s+main\s*\(\s*\)").Count != 0;
bool noReturn = Regex.Matches(text, @"void\s+main\s*\(").Count != 0;
string actualArgs = (noargs ? "" : "args");
string entryPointDefinition = "static int Main(string[] args) { ";
if (noReturn)
{
entryPointDefinition += "try { System.Console.OutputEncoding = System.Text.Encoding.UTF8; } catch { } new ScriptClass().main(" + actualArgs + "); return 0;";
}
else
{
entryPointDefinition += "return (int)new ScriptClass().main(" + actualArgs + ");";
}
entryPointDefinition += "} ///CS-Script auto-class generation" + Environment.NewLine;
injectionLength += entryPointDefinition.Length;
code.Insert(entryPointInjectionPos, entryPointDefinition);
}
else if (match.Value.Contains("Main")) //assembly entry point "static Main"
{
if (!match.Value.Contains("static"))
{
string tempText = "static ";
injectionLength += tempText.Length;
code.Insert(entryPointInjectionPos, tempText);
}
}
autoCodeInjected = true;
break;
}
}
}
code.Append(line);
code.Append(Environment.NewLine);
}
}
code.Append("} ///CS-Script auto-class generation" + Environment.NewLine);
return code.ToString();
}
}
}