68 lines
2.7 KiB
C#
68 lines
2.7 KiB
C#
using Convention.RScript.Parser;
|
|
using System;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
namespace Convention.RScript.Runner
|
|
{
|
|
public class DefineVariableRunner : IRSentenceRunner
|
|
{
|
|
[return: MaybeNull]
|
|
public object Run(ExpressionParser parser, RScriptSentence sentence, RScriptContext context)
|
|
{
|
|
// 定义变量
|
|
var varTypeName = sentence.info[0];
|
|
var varName = sentence.info[1];
|
|
var varInitExpression = sentence.info[2];
|
|
Type varType;
|
|
object varDefaultValue;
|
|
{
|
|
if (varTypeName == "string")
|
|
{
|
|
varType = typeof(string);
|
|
varDefaultValue = varInitExpression == null ? string.Empty : varInitExpression;
|
|
}
|
|
else if (varTypeName == "int")
|
|
{
|
|
varType = typeof(int);
|
|
varDefaultValue = varInitExpression == null ? 0 : parser.Evaluate<int>(varInitExpression);
|
|
}
|
|
else if (varTypeName == "double")
|
|
{
|
|
varType = typeof(double);
|
|
varDefaultValue = varInitExpression == null ? 0.0 : parser.Evaluate<double>(varInitExpression);
|
|
}
|
|
else if (varTypeName == "float")
|
|
{
|
|
varType = typeof(float);
|
|
varDefaultValue = varInitExpression == null ? 0.0f : parser.Evaluate<float>(varInitExpression);
|
|
}
|
|
else if (varTypeName == "bool")
|
|
{
|
|
varType = typeof(bool);
|
|
varDefaultValue = varInitExpression == null ? false : parser.Evaluate<bool>(varInitExpression);
|
|
}
|
|
else if (varTypeName == "var")
|
|
{
|
|
varType = typeof(object);
|
|
varDefaultValue = varInitExpression == null ? new object() : parser.Evaluate(varInitExpression);
|
|
}
|
|
else
|
|
{
|
|
throw new RScriptRuntimeException($"Unsupported variable type '{varTypeName}'.", context.CurrentRuntimePointer);
|
|
}
|
|
}
|
|
if (context.CurrentLocalSpaceVariableNames.Peek().Contains(varName) == false)
|
|
{
|
|
context.Variables.Add(varName, new(varType, varDefaultValue));
|
|
parser.context.Variables[varName] = varDefaultValue;
|
|
context.CurrentLocalSpaceVariableNames.Peek().Add(varName);
|
|
}
|
|
else
|
|
{
|
|
throw new RScriptRuntimeException($"Variable '{varName}' already defined on this namespace.", context.CurrentRuntimePointer);
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
}
|