-
Notifications
You must be signed in to change notification settings - Fork 399
Expand file tree
/
Copy pathSharedEvaluatorDefinition.cs
More file actions
294 lines (253 loc) · 12.2 KB
/
Copy pathSharedEvaluatorDefinition.cs
File metadata and controls
294 lines (253 loc) · 12.2 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Util;
using Microsoft.TemplateEngine.Utils;
namespace Microsoft.TemplateEngine.Core.Expressions.Shared
{
public abstract class SharedEvaluatorDefinition<TSelf, TTokens>
where TSelf : SharedEvaluatorDefinition<TSelf, TTokens>, new()
where TTokens : struct
{
private static readonly TSelf Instance = new();
private static readonly IOperatorMap<Operators, TTokens> Map = Instance.GenerateMap();
private static readonly bool DereferenceInLiteralsSetting = Instance.DereferenceInLiterals;
private static readonly string NullToken = Instance.NullTokenValue;
private static readonly IOperationProvider[] NoOperationProviders = [];
protected abstract string NullTokenValue { get; }
protected abstract bool DereferenceInLiterals { get; }
public static bool Evaluate(IProcessorState processor, ref int bufferLength, ref int currentBufferPosition, out bool faulted)
{
bool result = Evaluate(processor, ref bufferLength, ref currentBufferPosition, out string? faultedMessage, null, false);
faulted = !string.IsNullOrEmpty(faultedMessage);
return result;
}
/// <summary>
/// Inspect the passed string, creates the expression, substitutes parameters within expression, evaluates substituted expression and returns result.
/// If non-null bag for variable references is passed, it will be populated with references of variables used within the evaluable expression.
/// </summary>
/// <param name="logger">The logger to be used to log the messages during evaluation.</param>
/// <param name="text">The string to be inspected and turned into expression.</param>
/// <param name="variables">Variables to be substituted within the expression.</param>
/// <returns>A boolean value indicating the result of the evaluation.</returns>
public static bool EvaluateFromString(ILogger logger, string text, IVariableCollection variables)
{
return EvaluateFromString(logger, text, variables, out string? _, null);
}
/// <summary>
/// Inspect the passed string, creates the expression, substitutes parameters within expression, evaluates substituted expression and returns result.
/// If non-null bag for variable references is passed, it will be populated with references of variables used within the evaluable expression.
/// </summary>
/// <param name="logger">The logger to be used to log the messages during evaluation.</param>
/// <param name="text">The string to be inspected and turned into expression.</param>
/// <param name="variables">Variables to be substituted within the expression.</param>
/// <param name="faultedMessage">Error message detailing failing evaluation, should it fail.</param>
/// <param name="referencedVariablesKeys">If passed (if not null) it will be populated with references to variables used within the inspected expression.</param>
/// <returns>A boolean value indicating the result of the evaluation.</returns>
public static bool EvaluateFromString(ILogger logger, string text, IVariableCollection variables, out string? faultedMessage, HashSet<string>? referencedVariablesKeys = null)
{
using MemoryStream ms = new(Encoding.UTF8.GetBytes(text));
using MemoryStream res = new();
EngineConfig cfg = new(logger, variables);
IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders);
int len = (int)ms.Length;
int pos = 0;
return Evaluate(state, ref len, ref pos, out faultedMessage, referencedVariablesKeys, true);
}
/// <summary>
/// Creates the evaluable expression based on passed string,
/// collects used symbols in the expression and reports if any errors occurs on expression creation.
/// </summary>
/// <param name="logger">The logger to be used to log the messages during building the evaluable expression.</param>
/// <param name="text">The string to be inspected and turned into expression.</param>
/// <param name="variables">Variables to be substituted within the expression.</param>
/// <param name="evaluableExpressionError">Error message detailing failing building evaluable expression.</param>
/// <param name="referencedVariablesKeys">If passed (if not null) it will be populated with references to variables used within the inspected expression.</param>
/// <returns>Evaluable expression that represents decomposed <paramref name="text"></paramref>.</returns>
public static IEvaluable? GetEvaluableExpression(
ILogger logger,
string text,
IVariableCollection variables,
out string? evaluableExpressionError,
HashSet<string> referencedVariablesKeys)
{
using MemoryStream ms = new(Encoding.UTF8.GetBytes(text));
using MemoryStream res = new();
EngineConfig cfg = new(logger, variables);
IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders);
int len = (int)ms.Length;
int pos = 0;
return GetEvaluableExpression(state, ref len, ref pos, out evaluableExpressionError, referencedVariablesKeys);
}
protected static int Compare(object? left, object? right)
{
if (Equals(right, NullToken))
{
right = null;
}
if (Equals(left, NullToken))
{
left = null;
}
return AttemptNumericComparison(left, right)
?? AttemptBooleanComparison(left, right)
?? AttemptVersionComparison(left, right)
?? AttemptMultiValueComparison(left, right)
?? AttemptLexicographicComparison(left, right)
?? AttemptComparableComparison(left, right)
?? 0;
}
protected abstract IOperatorMap<Operators, TTokens> GenerateMap();
protected abstract ITokenTrie GetSymbols(IProcessorState processor);
private static IEvaluable? GetEvaluableExpression(
IProcessorState processor,
ref int bufferLength,
ref int currentBufferPosition,
out string? faultedMessage,
HashSet<string> referencedVariablesKeys)
{
faultedMessage = null;
ITokenTrie tokens = Instance.GetSymbols(processor);
ScopeBuilder<Operators, TTokens> builder = processor.ScopeBuilder(tokens, Map, DereferenceInLiteralsSetting);
string? faultedSection = null;
return builder.Build(
ref bufferLength,
ref currentBufferPosition,
x => faultedSection = processor.Encoding.GetString(x.ToArray()),
referencedVariablesKeys);
}
private static bool Evaluate(
IProcessorState processor,
ref int bufferLength,
ref int currentBufferPosition,
out string? faultedMessage,
HashSet<string>? referencedVariablesKeys,
// indicates whether passed buffer within processor contains only the analyzed expression,
// or it can possibly contain other content (e.g. the full template)
bool shouldProcessWholeBuffer)
{
string? faultedSection = null;
IEvaluable? expression = GetEvaluableExpression(
processor,
ref bufferLength,
ref currentBufferPosition,
out faultedMessage,
referencedVariablesKeys ?? new HashSet<string>());
bool result;
if (faultedSection != null)
{
faultedMessage = faultedSection;
result = false;
}
else
{
// Buffer continues after expression - let's populate error only if this is single expression evaluation
// as we want to avoid creation of message that would contain whole template content after some condition
if (shouldProcessWholeBuffer && bufferLength != 0)
{
faultedMessage = LocalizableStrings.Error_Evaluation_Expression_Substring +
processor.Encoding.GetString(
processor.CurrentBuffer,
currentBufferPosition,
bufferLength - currentBufferPosition);
}
try
{
object? evalResult = expression?.Evaluate();
result = (bool)Convert.ChangeType(evalResult, typeof(bool));
}
catch (Exception e)
{
faultedMessage = faultedMessage == null
? e.Message
: (faultedMessage + Environment.NewLine + e.Message);
result = false;
}
}
if (!string.IsNullOrEmpty(faultedMessage))
{
processor.Config.Logger.LogDebug(LocalizableStrings.Error_Evaluation_Expression + faultedMessage);
}
return result;
}
private static int? AttemptBooleanComparison(object? left, object? right)
{
bool leftIsBool = Map.TryConvert(left, out bool lb);
bool rightIsBool = Map.TryConvert(right, out bool rb);
if (!leftIsBool || !rightIsBool)
{
return null;
}
return lb.CompareTo(rb);
}
private static int? AttemptComparableComparison(object? left, object? right)
{
if (left is not IComparable ls || right is not IComparable rs)
{
return null;
}
return ls.CompareTo(rs);
}
private static int? AttemptMultiValueComparison(object? left, object? right)
{
if (MultiValueParameter.TryPerformMultiValueEqual(left!, right!, out bool result))
{
return result ? 0 : -1;
}
return null;
}
private static int? AttemptLexicographicComparison(object? left, object? right)
{
if (left is not string ls || right is not string rs)
{
return null;
}
return string.Compare(ls, rs, StringComparison.OrdinalIgnoreCase);
}
private static int? AttemptNumericComparison(object? left, object? right)
{
bool leftIsDouble = Map.TryConvert(left, out double ld);
bool rightIsDouble = Map.TryConvert(right, out double rd);
if (!leftIsDouble)
{
if (!Map.TryConvert(left, out long ll))
{
return null;
}
ld = ll;
}
if (!rightIsDouble)
{
if (!Map.TryConvert(right, out long rl))
{
return null;
}
rd = rl;
}
return ld.CompareTo(rd);
}
private static int? AttemptVersionComparison(object? left, object? right)
{
Version? lv = left as Version;
if (lv == null)
{
if (left is not string ls || !Version.TryParse(ls, out lv))
{
return null;
}
}
Version? rv = right as Version;
if (rv == null)
{
if (right is not string rs || !Version.TryParse(rs, out rv))
{
return null;
}
}
return lv.CompareTo(rv);
}
}
}