public void TestExpressionVariables() { ExpressionContext context1 = new ExpressionContext(); context1.Imports.Add(new Import(typeof(Math))); var exp1 = new DynamicExpression("sin(pi)", ExpressionLanguage.Flee); var boundExp1 = exp1.Bind(context1); ExpressionContext context2 = new ExpressionContext(); context2.Imports.Add(new Import(typeof(Math))); var exp2 = new DynamicExpression<double>("cos(pi/2)", ExpressionLanguage.Flee); var boundExp2 = exp2.Bind(context2); ExpressionContext context3 = new ExpressionContext(); context3.Variables.Add("a", boundExp1); context3.Variables.Add("b", boundExp2); var exp3 = new DynamicExpression("cast(a, double) + b", ExpressionLanguage.Flee); double a = Math.Sin(Math.PI); double b = Math.Cos(Math.PI / 2); Assert.AreEqual(a + b, exp3.Invoke(context3)); ExpressionContext context4 = new ExpressionContext(); context4.Variables.Add("a", boundExp1); context4.Variables.Add("b", boundExp2); var exp4 = new DynamicExpression<double>("(cast(a, double) * b) + (b - cast(a, double))", ExpressionLanguage.Flee); Assert.AreEqual((a * b) + (b - a), exp4.Invoke(context4)); }
public void TestFastVariables() { // Test should take 200ms or less const int EXPECTED_TIME = 200; const int ITERATIONS = 100000; ExpressionContext context = new ExpressionContext(); VariableCollection vars = context.Variables; vars.DefineVariable("a", typeof(Int32)); vars.DefineVariable("b", typeof(Int32)); IDynamicExpression e = this.CreateDynamicExpression("a + b * (a ^ 2)", context); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i <= ITERATIONS - 1; i++) { object result = e.Evaluate(); vars["a"] = 200; vars["b"] = 300; } sw.Stop(); this.PrintSpeedMessage("Fast variables", ITERATIONS, sw); NUnit.Framework.Assert.Less((decimal)sw.ElapsedMilliseconds, EXPECTED_TIME, "Test time above expected value"); }
public void Compile(ExpressionContext context) { // TODO: verify wheather the expression is a value (no need to compile) bool isValue = false; if (!isValue) eDynamic = context.CompileDynamic(AssignmentExpression); }
/// <summary> /// Creates a new instance of the <see cref="DynamicCalculator"/>. /// </summary> public DynamicCalculator() { m_variableNames = new HashSet<string>(); m_keyMapping = new Dictionary<MeasurementKey, string>(); m_nonAliasedTokens = new SortedDictionary<int, string>(); m_expressionContext = new ExpressionContext(); }
public PMNameNode(ExpressionNode node, string tokenString, ExpressionContext context) : base(node, tokenString, context) { string[] parts = Name.Split('.'); if (parts.Length == 3) { isAttribute = true; ObjectName = (PMObjectType)Enum.Parse(typeof(PMObjectType), parts[0], true); FieldName = parts[2].Trim('[',']').Trim(); } else if (parts.Length == 2) { ObjectName = (PMObjectType)Enum.Parse(typeof(PMObjectType), parts[0], true); if (parts[1].Trim().EndsWith("_Attributes")) { isAttribute = true; FieldName = parts[1].Substring(0, parts[1].Length - 11); } else FieldName = parts[1]; } else { ObjectName = PMObjectType.PMTran; FieldName = Name; } }
/* private void BuildExpression() { foreach (Assignment assignment in _assignments) { string stringDelim = "\""; if (assignment.Variable.VariableDataType != VariableDataType.String) stringDelim = string.Empty; _expression += assignment.Variable.Mnemonic + " = " + stringDelim + assignment.AssignmentExpression + stringDelim + ";"; } } */ private void Parse(ExpressionContext context, CalculationMemory calculationMemory) { _assignments.Clear(); // assignments seprator token string[] temp = _expression.Split(';'); int idx = 0; //temp.OrderBy? foreach (string assignmentExpression in temp) { if (assignmentExpression != string.Empty) { // assignment token string[] temp2 = assignmentExpression.Split('='); if (temp2.Length != 2) throw new InequationEngineException(ExceptionType.NumberOfAssigmentTokens); string variableName = temp2[0].ToLower().Trim(); Variable variable = calculationMemory[variableName]; if (variable == null) throw new InequationEngineException(ExceptionType.VariableNotFoundInCalcMemory); Assignment assignment = new Assignment(variable, temp2[1]); _assignments.Add(idx, assignment); idx++; } } }
private static ExpressionContext GetExpressionContext() { var expressionOwner = new TestData { Id = "World" }; var context = new ExpressionContext(expressionOwner); context.Imports.AddType(typeof(TestDataExtensions)); return context; }
public void TestExpressionClone() { ExpressionContext context = new ExpressionContext(); context.Variables.Add("a", 100); context.Variables.Add("b", 200); IGenericExpression<int> exp1 = this.CreateGenericExpression<int>("(a * b)", context); IGenericExpression<int> exp2 = exp1.Clone() as IGenericExpression<int>; Assert.AreNotSame(exp1.Context.Variables, exp2.Context.Variables); exp2.Context.Variables["a"] = 10; exp2.Context.Variables["b"] = 20; Assert.AreEqual(10 * 20, exp2.Evaluate()); Thread t1 = new Thread(ThreadRunClone); Thread t2 = new Thread(ThreadRunClone); t1.Start(exp1); t2.Start(exp2); IDynamicExpression exp3 = this.CreateDynamicExpression("a * b", context); IDynamicExpression exp4 = exp3.Clone() as IDynamicExpression; Assert.AreEqual(100 * 200, exp4.Evaluate()); }
internal ExpressionOptions(ExpressionContext owner) { MyOwner = owner; MyProperties = new PropertyDictionary(); this.InitializeProperties(); }
private string processGlobal(string expr) { var val = PluginMain.debugManager.FlashInterface.Session.getGlobal(expr); //var val = PluginMain.debugManager.FlashInterface.Session.getValue(Convert.ToInt64(expr)); var ctx = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]); return ctx.FormatValue(val); }
public void TestBatchLoad() { // Test that we can add expressions in any order CalculationEngine engine = new CalculationEngine(); ExpressionContext context = new ExpressionContext(); int interest = 2; context.Variables.Add("interest", interest); BatchLoader loader = engine.CreateBatchLoader(); loader.Add("c", "a + b", context); loader.Add("a", "100 + interest", context); loader.Add("b", "a + 1 + a", context); // Test an expression with a reference in a string loader.Add("d", "\"str \\\" str\" + a + \"b\"", context); engine.BatchLoad(loader); int result = engine.GetResult<int>("b"); Assert.AreEqual((100 + interest) + 1 + (100 + interest), result); interest = 300; context.Variables["interest"] = interest; engine.Recalculate("a"); result = engine.GetResult<int>("b"); Assert.AreEqual((100 + interest) + 1 + (100 + interest), result); result = engine.GetResult<int>("c"); Assert.AreEqual((100 + interest) + 1 + (100 + interest) + (100 + interest), result); Assert.AreEqual("str \" str400b", engine.GetResult<string>("d")); }
/** * <summary>Creates a new tokenizer for the specified input * stream.</summary> * * <param name='input'>the input stream to read</param> * <param name='expressionContext'>the expression context to work on</param> * * <exception cref='ParserCreationException'>if the tokenizer * couldn't be initialized correctly</exception> */ public ExpressionTokenizer(TextReader input, ExpressionContext expressionContext) : base(input, true) { _expressionContext = expressionContext; CreatePatterns(); }
public InequationEngine() { _context = new ExpressionContext(); _context.Imports.AddType(typeof(CustomFunctions)); _context.Options.EmitToAssembly = false; _calculationMemory = new CalculationMemory(_context); }
public void RankedArrayIndexOnOwner() { var context = new ExpressionContext(null, new Owner()); Resolve(context, "RankedProperty[0,0]", 1); Resolve(context, "RankedProperty[1,1]", 4); }
internal ElementInit ToElementInit(ExpressionContext context) { return Expression.ElementInit( this.AddMethod.ToMemberInfo(context), (this.Arguments ?? new ExpressionNodeList()).GetExpressions(context)); }
internal ExpressionParserOptions(ExpressionContext owner) { MyOwner = owner; MyProperties = new PropertyDictionary(); MyParseCulture = CultureInfo.InvariantCulture; this.InitializeProperties(); }
/// <summary> /// Creates a new instance of the <see cref="EmailNotifier"/>. /// </summary> public EmailNotifier() { m_variableNames = new HashSet<string>(); m_keyMapping = new Dictionary<MeasurementKey, string>(); m_nonAliasedTokens = new SortedDictionary<int, string>(); m_expressionContext = new ExpressionContext(); m_mailClient = new Mail(); }
public void Resolve(IServiceProvider services) { MyServices = services; MyOptions = (ExpressionOptions)services.GetService(typeof(ExpressionOptions)); MyContext = (ExpressionContext)services.GetService(typeof(ExpressionContext)); this.ResolveInternal(); this.Validate(); }
public void ObjectParamsWithMatchingArg() { var context = new ExpressionContext(new[] { new Import("Owner", typeof(Owner)) }); context.Variables.Add(new Variable("Variable") { Value = new[] { "hi" } }); Resolve(context, "Owner.ObjectParams(0, Variable)", 2); }
public DateTimeLiteralElement(string image, ExpressionContext context) { ExpressionParserOptions options = context.ParserOptions; if (DateTime.TryParseExact(image, options.DateTimeFormat, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out MyValue) == false) { base.ThrowCompileException(CompileErrorResourceKeys.CannotParseType, CompileExceptionReason.InvalidFormat, typeof(DateTime).Name); } }
public void Test() { string translatedString = "uppercase(\"hello\")"; var expr = new DynamicExpression(translatedString, ExpressionLanguage.Csharp); var context = new ExpressionContext(null, new CustomOwner(), true); var boundExpression = expr.Bind(context); object res = boundExpression.Invoke(); }
public void ComparingWithNull() { var context = new ExpressionContext(); context.Variables.Add("Variable", new List<int>()); Resolve(context, "Variable = null", false); }
public void Execute(ExpressionContext context, CalculationMemory calculationMemory) { // Execute inequation and call action block if (Inequation.Execute(context)) TrueActionBlock.Execute(context, calculationMemory); else FalseActionBlock.Execute(context, calculationMemory); }
public void Execute(ExpressionContext context, CalculationMemory calculationMemory) { if (eDynamic == null) this.Compile(context); _variable.Value = eDynamic.Evaluate(); calculationMemory[_variable.Mnemonic] = _variable; }
public void Compile(ExpressionContext context, CalculationMemory calculationMemory) { // Compile inequation expression Inequation.Compile(context); // Compile Action Blocks TrueActionBlock.Compile(context, calculationMemory); FalseActionBlock.Compile(context, calculationMemory); }
public void ConstantAndVariable() { var context = new ExpressionContext(); context.Variables.Add(new Variable("Variable1") { Value = 1 }); context.Variables.Add(new Variable("Variable2") { Value = 1.1 }); Resolve(context, "Variable1 + 1", 2); Resolve(context, "Variable2 + 1", 2.1); }
protected override void ComputeToken(int id, string name, PerCederberg.Grammatica.Runtime.TokenPattern.PatternType type, string pattern, ExpressionContext context) { ExpressionParserOptions options = context.ParserOptions; char digitsBeforePattern = (options.RequireDigitsBeforeDecimalPoint ? '+' : '*'); pattern = string.Format(pattern, digitsBeforePattern, options.DecimalSeparator); this.SetData(id, name, type, pattern); }
private string processExpr(string expr) { IASTBuilder builder = new ASTBuilder(true); ValueExp exp = builder.parse(new java.io.StringReader(expr)); var ctx = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]); var obj = exp.evaluate(ctx); if (obj is Variable) return ctx.FormatValue(((Variable)obj).getValue()); if (obj is Value) return ctx.FormatValue((Value)obj); return obj.toString(); }
public SimpleCalcEngineTests() { SimpleCalcEngine engine = new SimpleCalcEngine(); ExpressionContext context = new ExpressionContext(); context.Imports.AddType(typeof(Math)); context.Imports.AddType(typeof(Math), "math"); engine.Context = context; MyEngine = engine; }
public void Compile(ExpressionContext context, CalculationMemory calculationMemory) { this.Parse(context, calculationMemory); //_assignments.OrderBy() foreach(Assignment assignment in _assignments.Values) { assignment.Compile(context); } }
private void CompileExpression(ExpressionContext expressionContext, string expression) { new DynamicExpression(expression, ExpressionLanguage.Flee).Invoke(expressionContext); }
/// <summary> /// All expression elements must be able to emit their own Intermediate language /// </summary> /// <param name="ilGenerator"></param> /// <param name="context"></param> public abstract void Emit(YaleIlGenerator ilGenerator, ExpressionContext context);
public ArrayList CtrlSpace(int caretLine, int caretColumn, string fileName, string fileContent, ExpressionContext context) { ArrayList result = new ArrayList(); if (language == NR.SupportedLanguage.VBNet) { foreach (KeyValuePair <string, string> pair in TypeReference.PrimitiveTypesVB) { if ("System." + pair.Key != pair.Value) { IClass c = GetPrimitiveClass(pair.Value, pair.Key); if (c != null) { result.Add(c); } } } result.Add("Global"); result.Add("New"); } else { foreach (KeyValuePair <string, string> pair in TypeReference.PrimitiveTypesCSharp) { IClass c = GetPrimitiveClass(pair.Value, pair.Key); if (c != null) { result.Add(c); } } } ParseInformation parseInfo = HostCallback.GetParseInformation(fileName); if (parseInfo == null) { return(null); } this.caretLine = caretLine; this.caretColumn = caretColumn; lookupTableVisitor = new LookupTableVisitor(language); cu = parseInfo.MostRecentCompilationUnit; if (cu != null) { callingClass = cu.GetInnermostClass(caretLine, caretColumn); } callingMember = GetCurrentMember(); if (callingMember != null) { CompilationUnit parsedCu = ParseCurrentMemberAsCompilationUnit(fileContent); if (parsedCu != null) { lookupTableVisitor.VisitCompilationUnit(parsedCu, null); } } CtrlSpaceResolveHelper.AddContentsFromCalling(result, callingClass, callingMember); foreach (KeyValuePair <string, List <LocalLookupVariable> > pair in lookupTableVisitor.Variables) { if (pair.Value != null && pair.Value.Count > 0) { foreach (LocalLookupVariable v in pair.Value) { if (IsInside(new NR.Location(caretColumn, caretLine), v.StartPos, v.EndPos)) { // convert to a field for display result.Add(CreateLocalVariableField(v, pair.Key)); break; } } } } if (callingMember is IProperty) { IProperty property = (IProperty)callingMember; if (property.SetterRegion.IsInside(caretLine, caretColumn)) { result.Add(new DefaultField.ParameterField(property.ReturnType, "value", property.Region, callingClass)); } } CtrlSpaceResolveHelper.AddImportedNamespaceContents(result, cu, callingClass); return(result); }
public ResolveResult ResolveInternal(Expression expr, ExpressionContext context) { TypeVisitor typeVisitor = new TypeVisitor(this); IReturnType type; if (expr is PrimitiveExpression) { if (((PrimitiveExpression)expr).Value is int) { return(new IntegerLiteralResolveResult(callingClass, callingMember, projectContent.SystemTypes.Int32)); } } else if (expr is InvocationExpression) { IMethodOrProperty method = typeVisitor.GetMethod(expr as InvocationExpression); if (method != null) { return(CreateMemberResolveResult(method)); } else { // InvocationExpression can also be a delegate/event call ResolveResult invocationTarget = ResolveInternal((expr as InvocationExpression).TargetObject, ExpressionContext.Default); if (invocationTarget == null) { return(null); } type = invocationTarget.ResolvedType; if (type == null) { return(null); } IClass c = type.GetUnderlyingClass(); if (c == null || c.ClassType != ClassType.Delegate) { return(null); } // We don't want to show "System.EventHandler.Invoke" in the tooltip // of "EventCall(this, EventArgs.Empty)", we just show the event/delegate for now // but for DelegateCall(params).* completion, we use the delegate's // return type instead of the delegate type itself method = c.Methods.Find(delegate(IMethod innerMethod) { return(innerMethod.Name == "Invoke"); }); if (method != null) { invocationTarget.ResolvedType = method.ReturnType; } return(invocationTarget); } } else if (expr is IndexerExpression) { return(CreateMemberResolveResult(typeVisitor.GetIndexer(expr as IndexerExpression))); } else if (expr is FieldReferenceExpression) { FieldReferenceExpression fieldReferenceExpression = (FieldReferenceExpression)expr; if (fieldReferenceExpression.FieldName == null || fieldReferenceExpression.FieldName.Length == 0) { // NRefactory creates this "dummy" fieldReferenceExpression when it should // parse a primitive type name (int, short; Integer, Decimal) if (fieldReferenceExpression.TargetObject is TypeReferenceExpression) { type = TypeVisitor.CreateReturnType(((TypeReferenceExpression)fieldReferenceExpression.TargetObject).TypeReference, this); if (type != null) { return(new TypeResolveResult(callingClass, callingMember, type)); } } } type = fieldReferenceExpression.TargetObject.AcceptVisitor(typeVisitor, null) as IReturnType; if (type != null) { ResolveResult result = ResolveMemberReferenceExpression(type, fieldReferenceExpression); if (result != null) { return(result); } } } else if (expr is IdentifierExpression) { ResolveResult result = ResolveIdentifier(((IdentifierExpression)expr).Identifier, context); if (result != null) { return(result); } } else if (expr is TypeReferenceExpression) { type = TypeVisitor.CreateReturnType(((TypeReferenceExpression)expr).TypeReference, this); if (type != null) { if (type is TypeVisitor.NamespaceReturnType) { return(new NamespaceResolveResult(callingClass, callingMember, type.FullyQualifiedName)); } IClass c = type.GetUnderlyingClass(); if (c != null) { return(new TypeResolveResult(callingClass, callingMember, type, c)); } } return(null); } type = expr.AcceptVisitor(typeVisitor, null) as IReturnType; if (type == null || type.FullyQualifiedName == "") { return(null); } if (expr is ObjectCreateExpression) { List <IMethod> constructors = new List <IMethod>(); foreach (IMethod m in type.GetMethods()) { if (m.IsConstructor && !m.IsStatic) { constructors.Add(m); } } if (constructors.Count == 0) { // Class has no constructors -> create default constructor IClass c = type.GetUnderlyingClass(); if (c != null) { return(CreateMemberResolveResult(Constructor.CreateDefault(c))); } } IReturnType[] typeParameters = null; if (type.IsConstructedReturnType) { typeParameters = new IReturnType[type.CastToConstructedReturnType().TypeArguments.Count]; type.CastToConstructedReturnType().TypeArguments.CopyTo(typeParameters, 0); } ResolveResult rr = CreateMemberResolveResult(typeVisitor.FindOverload(constructors, typeParameters, ((ObjectCreateExpression)expr).Parameters, null)); if (rr != null) { rr.ResolvedType = type; } return(rr); } return(new ResolveResult(callingClass, callingMember, type)); }
public void ParamsWithMultipleNullArg() { var context = new ExpressionContext(new[] { new Import("Owner", typeof(Owner)) }); Resolve(context, "Owner.Params(0, null, null)", 2); }
protected SqlProvider() { Params = new DynamicParameters(); ExpressionContext = new ExpressionContext(); }
protected IDynamicExpression CreateDynamicExpression(string expression, ExpressionContext context) { return(context.CompileDynamic(expression)); }
public abstract ExpressionInfo ParseExpression(string expression, ExpressionContext context, DetectionFlags flag, out bool reportParameterReferenced, out string reportParameterName, out bool userCollectionReferenced);
protected void Resolve(ExpressionContext expressionContext, string expression, object expected) { Resolve(expressionContext, expression, expected, null); }
public void MethodOnOwner() { var context = new ExpressionContext(null, new Owner()); Resolve(context, "Method()", 7); }
public void NestedPropertyOnOwner() { var context = new ExpressionContext(null, new Owner()); Resolve(context, "Item.IntProperty", 7); }
public void ParamsWithoutArgs() { var context = new ExpressionContext(new[] { new Import("Owner", typeof(Owner)) }); Resolve(context, "Owner.Params(0)", 0); }
public void ParamsWithMultipleArg() { var context = new ExpressionContext(new[] { new Import("Owner", typeof(Owner)) }); Resolve(context, "Owner.Params(0, \"a\", \"a\")", 4); }
public abstract ExpressionInfo ParseExpression(string expression, ExpressionContext context, out bool userCollectionReferenced);
public void StaticsOnOwner() { var context = new ExpressionContext(null, new Owner()); Resolve(context, "StaticMethod(1)", 1); }
public abstract ExpressionInfo ParseExpression(string expression, ExpressionContext context);
public void ObjectParamsWithNullAndActualArg() { var context = new ExpressionContext(new[] { new Import("Owner", typeof(Owner)) }); Resolve(context, "Owner.ObjectParams(0, null, \"a\", null)", 4); }
protected IGenericExpression <T> CreateGenericExpression <T>(string expression, ExpressionContext context) { var e = context.CompileGeneric <T>(expression); return(e); }
public void ObjectParamsWithSingleArg() { var context = new ExpressionContext(new[] { new Import("Owner", typeof(Owner)) }); Resolve(context, "Owner.ObjectParams(0, \"a\")", 2); }
/// <summary> /// Evaluate the IF field. /// </summary> public override void Evaluate() { // This will clear out the literal area of the field. The main idea of evaluation is to replace the contents of this part of the field with the // evaluated data. The original field -- the stuff before the field seperator -- remains pretty much in tact. this.ClearLiteral(); // Recursively evaluate each of the child fields before the parent is evaluated. foreach (WordField wordField in this) { wordField.Evaluate(); } // This is a general purpose expression evaluator. It is used to determine the veracity of the expression in the 'IF' statement and depending on // the resulting value, will either add the 'True' clause or the 'False' clause to the document. ExpressionContext context = new ExpressionContext(); // The first step to evaluating a conditional statement to provide distinct variables for all the merge fields. foreach (WordField wordField in this) { if (wordField is MergeField) { MergeField mergeField = wordField as MergeField; if (!context.Variables.ContainsKey(mergeField.Reference)) { context.Variables.Add(mergeField.Reference, mergeField.Value); } } } try { // This is the part where the expression that was parsed out of the field is evaluated. At this point all the variables having been set to // values from the merged database and the expression can be compiled and evaluated. Also note that this will catch any compile time errors // and produce a field in the output document that contains the error. IDynamicExpression iDynamicExpression = context.CompileDynamic(this.expression); List <Node> statement = Convert.ToBoolean(iDynamicExpression.Evaluate()) ? this.trueExpression : this.falseExpression; // The literal part of the field has been cleared out and now that the expression has been evaluated it can be filled in with either the data // collected from the 'True' or' 'False' statements (depending on the outcome of the evaluation done above). foreach (Node replacementNode in statement) { this.FieldStart.ParentNode.InsertBefore(replacementNode, this.FieldEnd); } // Adding elements from the 'True' or 'False' statements has the potential to add child fields to this field. This pass will look generate // any new fields and immediately evaluate them. Like a real programming language, conditional clauses are not evaluated until the condition // has been resolved. foreach (Node replacementNode in statement) { if (replacementNode.NodeType == NodeType.FieldStart) { WordField wordField = WordField.CreateField(replacementNode as FieldStart); wordField.Evaluate(); } } } catch (Exception exception) { // This inserts the error message into the document. Run run = new Run(this.FieldStart.Document, String.Format("Error! {0}", exception.Message)); this.FieldStart.ParentNode.InsertAfter(run, this.FieldEnd); } }
public override Expression Evaluate(ExpressionContext context) { return(this); }