forked from RickStrahl/Westwind.Scripting
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptParser.cs
More file actions
481 lines (406 loc) · 19.7 KB
/
Copy pathScriptParser.cs
File metadata and controls
481 lines (406 loc) · 19.7 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Westwind.Scripting
{
/// <summary>
/// A very simple C# script parser that parses the provided script
/// as a text string with embedded expressions and code blocks.
///
/// Literal text:
///
/// Parsed as plain text into the script output.
///
/// Expressions:
///
/// {{ DateTime.Now.ToString("d") }}
///
/// Code Blocks:
///
/// {{% for(int x; x<10; x++ { }}
/// {{ x }}. Hello World
/// {{% } }}
///
/// Uses the `.ScriptEngine` property for execution and provides
/// error information there.
/// </summary>
public class ScriptParser
{
/// <summary>
/// Script Engine used if none is passed in
/// </summary>
public CSharpScriptExecution ScriptEngine
{
get
{
if (_scriptEngine == null)
_scriptEngine = CreateScriptEngine();
return _scriptEngine;
}
set => _scriptEngine = value;
}
private CSharpScriptExecution _scriptEngine;
/// <summary>
/// Determines whether the was a compile time or runtime error
/// </summary>
public bool Error => ScriptEngine?.Error ?? false;
/// <summary>
/// Error Message if an error occurred
/// </summary>
public string ErrorMessage => ScriptEngine?.ErrorMessage;
/// <summary>
/// Type of error that occurred during compilation or execution of the template
/// </summary>
public ExecutionErrorTypes ErrorType => ScriptEngine?.ErrorType ?? ExecutionErrorTypes.None;
/// <summary>
/// Generated code that is compiled
/// </summary>
public string GeneratedClassCode => ScriptEngine?.GeneratedClassCode;
/// <summary>
/// Generated code with line numbers that is compiled. You can use this
/// to match error messages to code lines.
/// </summary>
public string GeneratedClassCodeWithLineNumbers => ScriptEngine?.GeneratedClassCodeWithLineNumbers;
#region Script Execution
/// <summary>
/// Executes a script that supports {{ expression }} and {{% code block }} syntax
/// and returns a string result.
///
/// You can optionally pass in a pre-configured `CSharpScriptExecution` instance
/// which allows setting references/namespaces and can capture error information.
///
/// Function returns `null` on error and `scriptEngine.Error` is set to `true`
/// along with the error message and the generated code.
/// </summary>
/// <param name="script">The template to execute that contains C# script</param>
/// <param name="model">A model that can be accessed in the template as `Model`. Pass null if you don't need to access values.</param>
/// <param name="scriptEngine">Optional CSharpScriptEngine so you can customize configuration and capture result errors</param>
/// <param name="startDelim">Optional start delimiter for script tags</param>
/// <param name="endDelim">Optional end delimiter for script tags</param>
/// <param name="codeIndicator">Optional Code block indicator that indicates raw code to create in the template (ie. `%` which uses `{{% }}`)</param>
/// <returns>expanded template or null. On null check `scriptEngine.Error` and `scriptEngine.ErrorMessage`</returns>
public string ExecuteScript(string script, object model,
CSharpScriptExecution scriptEngine = null,
string startDelim = "{{", string endDelim = "}}", string codeIndicator = "%")
{
if (string.IsNullOrEmpty(script) || !script.Contains("{{"))
return script;
var code = ParseScriptToCode(script, startDelim, endDelim, codeIndicator);
if (code == null)
return null;
// expose the parameter as Model
code = "dynamic Model = parameters[0];\n" + code;
if (scriptEngine != null)
ScriptEngine = scriptEngine;
return ScriptEngine.ExecuteCode(code, model) as string;
}
/// <summary>
/// Executes a script that supports {{ expression }} and {{% code block }} syntax
/// and returns a string result.
///
/// You can optionally pass in a pre-configured `CSharpScriptExecution` instance
/// which allows setting references/namespaces and can capture error information.
///
/// Function returns `null` on error and `scriptEngine.Error` is set to `true`
/// along with the error message and the generated code.
/// </summary>
/// <param name="script">The template to execute that contains C# script</param>
/// <param name="model">A model that can be accessed in the template as `Model`. Pass null if you don't need to access values.</param>
/// <param name="scriptEngine">Optional CSharpScriptEngine so you can customize configuration and capture result errors</param>
/// <param name="startDelim">Optional start delimiter for script tags</param>
/// <param name="endDelim">Optional end delimiter for script tags</param>
/// <param name="codeIndicator">Optional Code block indicator that indicates raw code to create in the template (ie. `%` which uses `{{% }}`)</param>
/// <returns>expanded template or null. On null check `scriptEngine.Error` and `scriptEngine.ErrorMessage`</returns>
public string ExecuteScript<TModelType>(string script, TModelType model,
CSharpScriptExecution scriptEngine = null,
string startDelim = "{{", string endDelim = "}}", string codeIndicator = "%")
{
if (string.IsNullOrEmpty(script) || !script.Contains("{{"))
return script;
var code = ParseScriptToCode(script, startDelim, endDelim, codeIndicator);
if (code == null)
return null;
if (scriptEngine != null)
ScriptEngine = scriptEngine;
return ScriptEngine.ExecuteCode<string, TModelType>(code, model) as string;
}
/// <summary>
/// Executes a script that supports {{ expression }} and {{% code block }} syntax
/// and returns a string result. This version allows for `async` code inside of
/// the template.
///
/// You can optionally pass in a pre-configured `CSharpScriptExecution` instance
/// which allows setting references/namespaces and can capture error information.
///
/// Function returns `null` on error and `scriptEngine.Error` is set to `true`
/// along with the error message and the generated code.
/// </summary>
/// <param name="script">The template to execute that contains C# script</param>
/// <param name="model">A model that can be accessed in the template as `Model`. Model is exposed as `dynamic`
/// which allows passing any value without requiring type dependencies at compile time.
///
/// Pass null if you don't need to access values.</param>
/// <param name="scriptEngine">Optional CSharpScriptEngine so you can customize configuration and capture result errors</param>
/// <param name="startDelim">Optional start delimiter for script tags</param>
/// <param name="endDelim">Optional end delimiter for script tags</param>
/// <param name="codeIndicator">Optional Code block indicator that indicates raw code to create in the template (ie. `%` which uses `{{% }}`)</param>
/// <returns>expanded template or null. On null check `scriptEngine.Error` and `scriptEngine.ErrorMessage`</returns>
public async Task<string> ExecuteScriptAsync(string script,
object model = null,
CSharpScriptExecution scriptEngine = null,
string startDelim = "{{", string endDelim = "}}",
string codeIndicator = "%")
{
if (string.IsNullOrEmpty(script) || !script.Contains("{{"))
return script;
var code = ParseScriptToCode(script, startDelim, endDelim, codeIndicator);
if (code == null)
return null;
// expose the parameter as Model
code = "dynamic Model = parameters[0];\n" + code;
if (scriptEngine != null)
ScriptEngine = scriptEngine;
string result = await ScriptEngine.ExecuteCodeAsync(code, model) as string;
return result;
}
/// <summary>
/// Executes a script that supports {{ expression }} and {{% code block }} syntax
/// and returns a string result. This version allows for `async` code inside of
/// the template.
///
/// You can optionally pass in a pre-configured `CSharpScriptExecution` instance
/// which allows setting references/namespaces and can capture error information.
///
/// Function returns `null` on error and `scriptEngine.Error` is set to `true`
/// along with the error message and the generated code.
/// </summary>
/// <param name="script">The template to execute that contains C# script</param>
/// <param name="model">A model that can be accessed in the template as `Model`. Model is exposed as `dynamic`
/// which allows passing any value without requiring type dependencies at compile time.
///
/// Pass null if you don't need to access values.</param>
/// <param name="scriptEngine">Optional CSharpScriptEngine so you can customize configuration and capture result errors</param>
/// <param name="startDelim">Optional start delimiter for script tags</param>
/// <param name="endDelim">Optional end delimiter for script tags</param>
/// <param name="codeIndicator">Optional Code block indicator that indicates raw code to create in the template (ie. `%` which uses `{{% }}`)</param>
/// <returns>expanded template or null. On null check `scriptEngine.Error` and `scriptEngine.ErrorMessage`</returns>
public async Task<string> ExecuteScriptAsync<TModelType>(string script,
TModelType model = default,
CSharpScriptExecution scriptEngine = null,
string startDelim = "{{", string endDelim = "}}",
string codeIndicator = "%")
{
if (string.IsNullOrEmpty(script) || !script.Contains("{{"))
return script;
var code = ParseScriptToCode(script, startDelim, endDelim, codeIndicator);
if (code == null)
return null;
// expose the parameter as Model
//code = "dynamic Model = parameters[0];\n" + code;
if (scriptEngine != null)
ScriptEngine = scriptEngine;
string result = await ScriptEngine.ExecuteCodeAsync<string, TModelType>(code, model) as string;
return result;
}
/// <summary>
/// Passes in a block of 'script' code into a string using
/// code that uses a text writer to output. You can feed the
/// output from this method in `ExecuteCode()` or similar to
/// parse the script into an output string that includes the
/// processed text.
/// </summary>
/// <param name="scriptText"></param>
/// <param name="startDelim">code and expression start delimiter</param>
/// <param name="endDelim">code and expression end delimiter</param>
/// <param name="codeIndicator">code block indicator that combines the start delim plus this character (ie. default of `%` combines to `{{%`)</param>
/// <returns></returns>
public string ParseScriptToCode(string scriptText, string startDelim = "{{", string endDelim = "}}",
string codeIndicator = "%")
{
var atStart = scriptText.IndexOf(startDelim);
// no script in string - just return - this should be handled higher up
// and is in ExecuteXXXX methods.
if (atStart == -1)
return "return " + EncodeStringLiteral(scriptText, true) + ";";
var literal = new StringBuilder();
using (var code = new StringWriter())
{
var atEnd = -1;
string expression = null;
string initialCode = @"
var writer = new StringWriter();
";
code.Write(initialCode);
while (atStart > -1)
{
atEnd = scriptText.IndexOf(endDelim);
if (atEnd == -1)
{
literal.Append(scriptText); // no end tag - take rest
break;
}
// take text up to the tag
literal.Append(scriptText.Substring(0, atStart));
expression = scriptText.Substring(atStart + startDelim.Length, atEnd - atStart - endDelim.Length);
// first we have to write out any left over literal
if (literal.Length > 0)
{
// output the code
code.WriteLine(
$"writer.Write({EncodeStringLiteral(literal.ToString(), true)});");
literal.Clear();
}
if (expression.StartsWith(codeIndicator))
{
// this should just be raw code - write out as is
expression = expression.Substring(1);
code.WriteLine(expression); // as is
// process Command (new line
}
else
{
code.WriteLine($"writer.Write( {expression} );");
}
// text that is left
scriptText = scriptText.Substring(atEnd + endDelim.Length);
// look for the next bit
atStart = scriptText.IndexOf("{{");
if (atStart < 0)
{
// write out remaining literal text
code.WriteLine(
$"writer.Write({EncodeStringLiteral(scriptText, true)});");
}
}
code.WriteLine("return writer.ToString();");
return code.ToString();
}
}
#endregion
#region Script Engine
/// <summary>
/// Creates an instance of a script engine with default configuration settings
/// set and the abililty to quickly specify addition references and namespaces.
///
/// You can pass this to ExecuteScript()/ExecuteScriptAsync()
/// </summary>
/// <param name="references">optional list of string assembly file names</param>
/// <param name="namespaces">optional list of name spaces</param>
/// <param name="referenceTypes">optional list of reference types</param>
/// <returns></returns>
public CSharpScriptExecution CreateScriptEngine(
string[] references = null,
string[] namespaces = null,
Type[] referenceTypes = null)
{
var exec = new CSharpScriptExecution() {SaveGeneratedCode = true};
exec.AddDefaultReferencesAndNamespaces();
if (references != null && references.Length > 0)
exec.AddAssemblies(references);
if (referenceTypes != null && referenceTypes.Length > 0)
{
for (int i = 0; i < referenceTypes.Length; i++)
exec.AddAssembly(referenceTypes[i]);
}
if (namespaces != null)
exec.AddNamespaces(namespaces);
return exec;
}
/// <summary>
/// Adds an assembly to the list of references for compilation
/// using a dll filename
/// </summary>
/// <param name="assemblyFile">Assembly filenames</param>
public void AddAssembly(string assemblyFile) => ScriptEngine.AddAssembly(assemblyFile);
/// <summary>
/// Adds an assembly to the list of references for compilation
/// using a type that is loaded and contained in the assembly
/// </summary>
/// <param name="typeInAssembly">type loaded and contained in the target assembly</param>
public void AddAssembly(Type typeInAssembly) => ScriptEngine.AddAssembly(typeInAssembly);
/// <summary>
/// Adds several assembly to the list of references for compilation
/// using a dll filenames.
/// </summary>
/// <param name="assemblies">Assembly file names</param>
public void AddAssemblies(params string[] assemblies) => ScriptEngine.AddAssemblies(assemblies);
/// <summary>
/// list of meta references to assemblies. Can be used with `Basic.References
/// </summary>
/// <param name="metaAssemblies"></param>
public void AddAssemblies(params PortableExecutableReference[] metaAssemblies) => ScriptEngine.AddAssemblies(metaAssemblies);
/// <summary>
/// Add a namespace for compilation of the template
/// </summary>
/// <param name="nameSpace"></param>
public void AddNamespace(string nameSpace) => ScriptEngine.AddNamespace(nameSpace);
/// <summary>
/// Add a list of namespaces for compilation of the template
/// </summary>
/// <param name="nameSpaces"></param>
public void AddNamespaces(params string[] nameSpaces) => ScriptEngine.AddNamespaces(nameSpaces);
#endregion
/// <summary>
/// Encodes a string to be represented as a C# style string literal.
///
/// Example output:
/// "Hello \"Rick\"!\r\nRock on"
/// </summary>
/// <param name="plainString">string to encode</param>
/// <param name="addQuotes">if true adds quotes around the encoded text</param>
/// <returns></returns>
public static string EncodeStringLiteral(string plainString, bool addQuotes = true)
{
if (plainString == null)
return "null";
var sb = new StringBuilder();
if (addQuotes)
sb.Append("\"");
foreach (char c in plainString)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
int i = (int) c;
if (i < 32)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
if (addQuotes)
sb.Append("\"");
return sb.ToString();
}
}
}