Skip to content

Commit 332b1ec

Browse files
author
Sébastien Geiser
committed
Typed Variables
1 parent e9c6448 commit 332b1ec

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
/* Script0067 */
2-
List<int> myList = new List<int>{1, 2, 3, 4}.Json;
2+
List<int> myList = new List<int>{1, 2, 3, 4};
3+
4+
myList.Json;

CodingSeb.ExpressionEvaluator/ExpressionEvaluator.cs

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2117,19 +2117,20 @@ protected virtual bool EvaluateVarOrFunc(string expression, Stack<object> stack,
21172117
else if ((Variables.TryGetValue(varFuncName, out object cusVarValueToPush) || varFuncMatch.Groups["assignationOperator"].Success)
21182118
&& (cusVarValueToPush == null || !TypesToBlock.Contains(cusVarValueToPush.GetType())))
21192119
{
2120-
StronglyTypedVariable stronglyTypedVariable;
2121-
21222120
if (stack.Count == 1 && stack.Peek() is ClassOrEnumType classOrEnum && varFuncMatch.Groups["assignationOperator"].Success)
21232121
{
21242122
stack.Pop();
21252123

2126-
stronglyTypedVariable = new StronglyTypedVariable
2124+
Variables[varFuncName] = new StronglyTypedVariable
21272125
{
21282126
Type = classOrEnum.Type,
21292127
Value = !varFuncMatch.Groups["assignationOperator"].Success && classOrEnum.Type.IsValueType ? Activator.CreateInstance(classOrEnum.Type) : null,
21302128
};
21312129
}
21322130

2131+
if (cusVarValueToPush is StronglyTypedVariable typedVariable)
2132+
cusVarValueToPush = typedVariable.Value;
2133+
21332134
stack.Push(cusVarValueToPush);
21342135

21352136
if (OptionVariableAssignationActive)
@@ -2180,7 +2181,29 @@ protected virtual bool EvaluateVarOrFunc(string expression, Stack<object> stack,
21802181
}
21812182

21822183
if (assign)
2183-
Variables[varFuncName] = cusVarValueToPush;
2184+
{
2185+
if (Variables.ContainsKey(varFuncName) && Variables[varFuncName] is StronglyTypedVariable stronglyTypedVariable)
2186+
{
2187+
if(cusVarValueToPush == null && !stronglyTypedVariable.Type.IsValueType)
2188+
{
2189+
throw new ExpressionEvaluatorSyntaxErrorException($"Can not cast null to {stronglyTypedVariable.Type} because it's not a nullable valueType");
2190+
}
2191+
2192+
Type typeToAssign = cusVarValueToPush?.GetType();
2193+
if (typeToAssign == null || stronglyTypedVariable.Type.IsAssignableFrom(typeToAssign))
2194+
{
2195+
stronglyTypedVariable.Value = cusVarValueToPush;
2196+
}
2197+
else
2198+
{
2199+
throw new InvalidCastException($"A object of type {typeToAssign} can not be cast implicitely in {stronglyTypedVariable.Type}");
2200+
}
2201+
}
2202+
else
2203+
{
2204+
Variables[varFuncName] = cusVarValueToPush;
2205+
}
2206+
}
21842207
}
21852208
else if (varFuncMatch.Groups["assignationOperator"].Success)
21862209
{

0 commit comments

Comments
 (0)