public void Setup() { _autofixture = new Fixture(); _registry = new Mock<IExpressionEvaluatorService>(MockBehavior.Strict); _sut = new SimpleEvaluatorSelector(_registry.Object); _evaluator = Mock.Of<IExpressionEvaluator>(); }
protected override DataObject OnEvaluate(IExpressionEvaluator evaluator) { var result = evaluator.Evaluate(Test).ToBoolean(); if (result == true) return evaluator.Evaluate(IfTrue); if (IfFalse != null) return evaluator.Evaluate(IfFalse); throw new InvalidOperationException(); }
protected override DataObject OnEvaluate(IExpressionEvaluator evaluator) { // Generate the TableExpressionFromSet hierarchy for the expression, TableExpressionFromSet fromSet = Planner.GenerateFromSet(SelectExpression, evaluator.Context.QueryContext.Connection); // Form the plan IQueryPlanNode plan = Planner.FormQueryPlan(evaluator.Context.QueryContext.Connection, SelectExpression, fromSet, new List<ByColumn>()); return new DataObject(PrimitiveTypes.Query(), plan); }
protected override DataObject OnEvaluate(IExpressionEvaluator evaluator) { var sortedEval = new[] { new SortedEvalInfo(0, Left), new SortedEvalInfo(1, Right) } .OrderByDescending(x => x.Precedence) .ToArray(); foreach (var evalInfo in sortedEval) { evalInfo.Result = evaluator.Evaluate(evalInfo.Expression); } var results = sortedEval .OrderBy(x => x.Offset) .Select(x => x.Result) .ToArray(); return EvaluateBinary(results[0], results[1], evaluator.Context); }
protected override DataObject OnEvaluate(IExpressionEvaluator evaluator) { return Value; }
public abstract Expression Expand(EXP expr, IExpressionEvaluator evaluator);
/// <summary> /// Build a SetEvaluator given a method to get an IEnumerable<U> and an /// IExpressionEvaluator for type U. /// </summary> /// <example> /// new SetEvaluator<Result, string>(result => result.Locations.Select(loc => loc.Id), new StringEvaluator<string>(value => value, StringComparison.OrdinalIgnoreCase) /// </example> /// <param name="getter">Getter to return a set of U given a T</param> /// <param name="innerEvaluator">IExpressionEvaluator<U> for which the getter returns just the item itself</param> public SetEvaluator(Func <T, IEnumerable <U> > getter, IExpressionEvaluator <U> innerEvaluator) { _getter = getter; _innerEvaluator = innerEvaluator; }
/// <summary> /// Performs evaluation & replacement of independent sub-trees in the body /// of an <see cref="LambdaExpression"/>. /// </summary> /// <param name="expFunc">The lambda expression whichs body to /// partially evaluate.</param> /// <returns>A new <see cref="LambdaExpression"/> with sub-trees in the body /// evaluated and replaced.</returns> public static LambdaExpression PartialEvalBody(LambdaExpression expFunc, IExpressionEvaluator evaluator) => Expression.Lambda(PartialEval(expFunc.Body, evaluator), expFunc.Parameters);
/// <summary> /// Performs evaluation & replacement of independent sub-trees /// </summary> /// <param name="expression">The root of the expression tree.</param> /// <returns>A new tree with sub-trees evaluated and replaced.</returns> public static Expression PartialEval(Expression expression, IExpressionEvaluator evaluator) => PartialEval(expression, evaluator, canBeEvaluated);
protected virtual DataObject OnEvaluate(IExpressionEvaluator evaluator) { throw new NotSupportedException(String.Format("Expression {0} does not support evaluation", ExpressionType)); }
protected override DataObject OnEvaluate(IExpressionEvaluator evaluator) { var ob = evaluator.Evaluate(Operand); return EvaluateUnary(ob, evaluator.Context); }
public static IAssertionTool SetExpressionEvaluator(this IAssertionTool assertTool, IExpressionEvaluator eval) { IExpressionEvaluator tmp; if (_EVALUATORS.TryGetValue(assertTool, out tmp)) { _EVALUATORS.Remove(assertTool); } _EVALUATORS.Add(assertTool, eval); return(assertTool); }
public object Get(IExpressionEvaluator parameter) => Get();
public void Setup() { this._evaluator = new RuntimeEvaluator(); }
public void SetupSut() { _variableRepository.Clear(); _expressionEvaluator = new ExpressionEvaluator(_variableRepository, _runEnvironment); }
private static IPythonModule GetModuleFromDottedName(ImmutableArray <NameExpression> names, int position, IExpressionEvaluator eval) { IPythonModule module = null; var index = position >= 0 ? names.IndexOf(n => n.StartIndex <= position && position <= n.EndIndex) : names.Count - 1; if (index >= 0) { module = eval.Interpreter.ModuleResolution.GetImportedModule(names[0].Name); for (var i = 1; module != null && i <= index; i++) { module = module.GetMember(names[i].Name) as IPythonModule; } } return(module); }
public LibraryAnalysis(IDocument document, int version, IGlobalScope globalScope, IExpressionEvaluator eval, IReadOnlyList <string> starImportMemberNames) { Check.ArgumentNotNull(nameof(document), document); Check.ArgumentNotNull(nameof(globalScope), globalScope); Document = document; Version = version; GlobalScope = globalScope; ExpressionEvaluator = eval; StarImportMemberNames = starImportMemberNames; }
/// <summary> /// Clone an expression and display it on the panel. /// </summary> /// <param name="newExpression">Expression to clone and display</param> /// <param name="thisType">Type to which CodeThisReferenceExpression /// is meant to refer within the CodeExpression</param> public void CloneAndSetExpression(CodeExpression newExpression, Type thisType) { if (currentExpressionValue != null) { this.DisableButtons(currentExpressionValue); this.highlightedAreas.Clear(); } this.currentExpressionValue = CloneExpression(newExpression); this.evaluator = EvaluatorGenerator.GenerateEvaluator(currentExpressionValue, thisType); this.AdornData(currentExpressionValue); this.Refresh(); this.CheckEvaluateButtonEnable(); }
public override bool Evaluate(IExpressionEvaluator evaluator) { return(evaluator.Evaluate(this)); }
public static T Sum <T>( this IExpressionEvaluator <T> evaluator, IEnumerable <T> values ) where T : struct, IComparable <T>, IEquatable <T> => values.Aggregate(evaluator.GetValue(0), (carry, current) => evaluator.Add(carry, current));
public abstract bool Evaluate(IExpressionEvaluator evaluator);
/// <summary> /// Performs evaluation & replacement of independent sub-trees /// </summary> /// <param name="expression">The root of the expression tree.</param> /// <param name="fnCanBeEvaluated">A function that decides whether a given expression node can be part of the local function.</param> /// <returns>A new tree with sub-trees evaluated and replaced.</returns> public static Expression PartialEval(Expression expression, IExpressionEvaluator evaluator, Func <Expression, bool> fnCanBeEvaluated) => new SubtreeEvaluator(evaluator, Nominator.Nominate(expression, fnCanBeEvaluated)).Eval(expression);
public override bool Evaluate(IExpressionEvaluator evaluator) { // this method should be guarded from being called by all BinaryExpressions throw new NotSupportedException(string.Format("Unable to evaluate an expression of type {0} with the value {1}.", this, Value)); }
/// <summary> /// Performs evaluation & replacement of independent sub-trees in the body /// of an typed <see cref="LambdaExpression"/>. /// </summary> /// <param name="expFunc">The lambda expression whichs body to /// partially evaluate.</param> /// <returns>A new typed <see cref="LambdaExpression"/> with sub-trees in the /// body evaluated and replaced.</returns> public static Expression <D> PartialEvalBody <D>(Expression <D> expFunc, IExpressionEvaluator evaluator) => expFunc.Update(PartialEval(expFunc.Body, evaluator), expFunc.Parameters);
public override bool Evaluate(IExpressionEvaluator evaluator) { return(Evaluate(Operands.Select(operand => operand.Evaluate(evaluator)))); }
internal SubtreeEvaluator(IExpressionEvaluator evaluator, HashSet <Expression> candidates) { this.candidates = candidates; this.evaluator = evaluator; }
public override bool Evaluate(IExpressionEvaluator evaluator) { // pass the operand through return(Evaluate(GetOperand().Evaluate(evaluator))); }
public Calc(IExpressionEvaluator expressionEvaluator) { _expressionEvaluator = expressionEvaluator; }
protected virtual DataObject OnEvaluate(IExpressionEvaluator evaluator) { throw new NotSupportedException(String.Format("Expression {0} does not support evaluation", ExpressionType)); }
/// <summary> /// Expands the given expression. /// </summary> /// <param name="evaluator">An evaluator that can be used by the custom /// <see cref="ExpressionExpander{EXP}"/>s</param> public static Expression Expand(Expression expr, IExpressionEvaluator evaluator) => new ExpressionExpanderVisitor(evaluator).Visit(expr);
public WorkflowLoader(IWorkflowRegistry registry, IScriptEngineHost scriptHost, IExpressionEvaluator expressionEvaluator, ICustomStepService stepService) { _registry = registry; _scriptHost = scriptHost; _expressionEvaluator = expressionEvaluator; _stepService = stepService; }
protected override DataObject OnEvaluate(IExpressionEvaluator evaluator) { return evaluator.Context.VariableResolver.Resolve(VariableName); }
/// <summary> /// Expands the given expression. /// </summary> /// <param name="evaluator">An evaluator that can be used by the custom /// <see cref="ExpressionExpander{EXP}"/>s</param> public static LambdaExpression ExpandBody(LambdaExpression expr, IExpressionEvaluator evaluator) => Expression.Lambda(Expand(expr.Body, evaluator), expr.Parameters);
public override sealed Number Evaluate(IExpressionEvaluator evaluator, IEnumerable<Expr> args) { return Value; }
/// <summary> /// Expands the given expression. /// </summary> /// <param name="evaluator">An evaluator that can be used by the custom /// <see cref="ExpressionExpander{EXP}"/>s</param> public static Expression <D> ExpandBody <D>(Expression <D> expr, IExpressionEvaluator evaluator) => expr.Update(Expand(expr.Body, evaluator), expr.Parameters);
public override Number Evaluate(IExpressionEvaluator evaluator, IEnumerable<Expr> args) { return Convolute(evaluator.Context, args).Visit(evaluator); }
private ExpressionExpanderVisitor(IExpressionEvaluator evaluator) { this.evaluator = evaluator; }
/// <summary> /// Default constructor. Sets all values to defaults. /// </summary> public RuleEvaluatorPanel() { // Perform initial layout. this.expressionRight = 0; this.evaluateButton = new Button(); this.evaluateButton.Text = "Evaluate"; Graphics graphics = this.CreateGraphics(); SizeF fontHeightF = graphics.MeasureString("T", this.Font); Size fontHeight = Size.Truncate(fontHeightF); int safeHeight = fontHeight.Height + 1; this.evaluateButton.Left = ExpressionLeft; this.evaluateButton.Top = ExpressionTop + safeHeight + 10; this.evaluateButton.Click += OnEvaluateClick; this.Controls.Add(evaluateButton); this.Height = evaluateButton.Bottom + 10; Label results = new Label(); results.Text = "Last Result:"; SizeF textLengthF = graphics.MeasureString(results.Text, results.Font); Size textLength = Size.Truncate(textLengthF); int safeWidth = textLength.Width + 1; results.Width = safeWidth; results.Top = evaluateButton.Top; results.Left = evaluateButton.Right + 10; this.Controls.Add(results); this.resultLabel = new Label(); this.resultLabel.Text = string.Empty; this.resultLabel.Font = new Font(this.Font, FontStyle.Bold); this.resultLabel.Top = results.Top; this.resultLabel.Left = results.Right + 5; this.resultLabel.Width = 0; this.Controls.Add(resultLabel); this.Width = resultLabel.Right + 10; this.sharedContextMenu = new ContextMenuStrip(); this.provider = CodeDomProvider.CreateProvider("C#"); this.evaluator = null; this.currentExpressionValue = null; this.highlightedAreas = new Dictionary<RectangleF, Brush>(); }
/// <summary> /// Creates set of arguments for a function call based on the call expression /// and the function signature. The result contains expressions /// for arguments, but not actual values. <see cref="Evaluate"/> on how to /// get values for actual parameters. /// </summary> /// <param name="fn">Function type.</param> /// <param name="overloadIndex">Function overload to call.</param> /// <param name="instance">Type instance the function is bound to. For derived classes it is different from the declared type.</param> /// <param name="callExpr">Call expression that invokes the function.</param> /// <param name="eval">Evaluator that can calculate values of arguments from their respective expressions.</param> public ArgumentSet(IPythonFunctionType fn, int overloadIndex, IPythonInstance instance, CallExpression callExpr, IExpressionEvaluator eval) { Eval = eval; OverloadIndex = overloadIndex; DeclaringModule = fn.DeclaringModule; Expression = callExpr; if (callExpr == null) { // Typically invoked by specialization code without call expression in the code. // Caller usually does not care about arguments. _evaluated = true; return; } var overload = fn.Overloads[overloadIndex]; var fd = overload.FunctionDefinition; if (fn.IsSpecialized) { // Typically specialized function, like TypeVar() that does not actually have AST definition. // Make the arguments from the call expression. If argument does not have name, // try using name from the function definition based on the argument position. _arguments = new List <Argument>(); for (var i = 0; i < callExpr.Args.Count; i++) { var name = callExpr.Args[i].Name; if (string.IsNullOrEmpty(name)) { name = i < overload.Parameters.Count ? overload.Parameters[i].Name : $"arg{i}"; } var node = fd != null && i < fd.Parameters.Length ? fd.Parameters[i] : null; _arguments.Add(new Argument(name, ParameterKind.Normal, callExpr.Args[i].Expression, null, node)); } return; } var callLocation = callExpr.GetLocation(eval); // https://www.python.org/dev/peps/pep-3102/#id5 // For each formal parameter, there is a slot which will be used to contain // the value of the argument assigned to that parameter. Slots which have // had values assigned to them are marked as 'filled'.Slots which have // no value assigned to them yet are considered 'empty'. var slots = new Argument[overload.Parameters.Count]; for (var i = 0; i < overload.Parameters.Count; i++) { var node = fd != null && i < fd.Parameters.Length ? fd.Parameters[i] : null; slots[i] = new Argument(overload.Parameters[i], node); } // Locate sequence argument, if any var sa = slots.Where(s => s.Kind == ParameterKind.List).ToArray(); if (sa.Length > 1) { // Error should have been reported at the function definition location by the parser. return; } var da = slots.Where(s => s.Kind == ParameterKind.Dictionary).ToArray(); if (da.Length > 1) { // Error should have been reported at the function definition location by the parser. return; } _listArgument = sa.Length == 1 && sa[0].Name.Length > 0 ? new ListArg(sa[0].Name, sa[0].ValueExpression, sa[0].Location) : null; _dictArgument = da.Length == 1 ? new DictArg(da[0].Name, da[0].ValueExpression, da[0].Location) : null; // Class methods var formalParamIndex = 0; if (fn.DeclaringType != null && fn.HasClassFirstArgument() && slots.Length > 0) { slots[0].Value = instance != null?instance.GetPythonType() : fn.DeclaringType; formalParamIndex++; } try { // Positional arguments var callParamIndex = 0; for (; callParamIndex < callExpr.Args.Count; callParamIndex++, formalParamIndex++) { var arg = callExpr.Args[callParamIndex]; if (!string.IsNullOrEmpty(arg.Name) && !arg.Name.StartsWithOrdinal("**")) { // Keyword argument. Done with positionals. break; } if (formalParamIndex >= overload.Parameters.Count) { // We ran out of formal parameters and yet haven't seen // any sequence or dictionary ones. This looks like an error. _errors.Add(new DiagnosticsEntry(Resources.Analysis_TooManyFunctionArguments, arg.GetLocation(eval).Span, ErrorCodes.TooManyFunctionArguments, Severity.Warning, DiagnosticSource.Analysis)); return; } var formalParam = overload.Parameters[formalParamIndex]; if (formalParam.Kind == ParameterKind.List) { if (string.IsNullOrEmpty(formalParam.Name)) { // If the next unfilled slot is a vararg slot, and it does not have a name, then it is an error. _errors.Add(new DiagnosticsEntry(Resources.Analysis_TooManyPositionalArgumentBeforeStar, arg.GetLocation(eval).Span, ErrorCodes.TooManyPositionalArgumentsBeforeStar, Severity.Warning, DiagnosticSource.Analysis)); return; } // If the next unfilled slot is a vararg slot then all remaining // non-keyword arguments are placed into the vararg slot. if (_listArgument == null) { _errors.Add(new DiagnosticsEntry(Resources.Analysis_TooManyFunctionArguments, arg.GetLocation(eval).Span, ErrorCodes.TooManyFunctionArguments, Severity.Warning, DiagnosticSource.Analysis)); return; } for (; callParamIndex < callExpr.Args.Count; callParamIndex++) { arg = callExpr.Args[callParamIndex]; if (!string.IsNullOrEmpty(arg.Name)) { // Keyword argument. Done here. break; } _listArgument._Expressions.Add(arg.Expression); } break; // Sequence or dictionary parameter found. Done here. } if (formalParam.Kind == ParameterKind.Dictionary) { // Next slot is a dictionary slot, but we have positional arguments still. _errors.Add(new DiagnosticsEntry(Resources.Analysis_TooManyPositionalArgumentBeforeStar, arg.GetLocation(eval).Span, ErrorCodes.TooManyPositionalArgumentsBeforeStar, Severity.Warning, DiagnosticSource.Analysis)); return; } // Regular parameter slots[formalParamIndex].ValueExpression = arg.Expression; } // Keyword arguments for (; callParamIndex < callExpr.Args.Count; callParamIndex++) { var arg = callExpr.Args[callParamIndex]; if (string.IsNullOrEmpty(arg.Name)) { _errors.Add(new DiagnosticsEntry(Resources.Analysis_PositionalArgumentAfterKeyword, arg.GetLocation(eval).Span, ErrorCodes.PositionalArgumentAfterKeyword, Severity.Warning, DiagnosticSource.Analysis)); return; } var nvp = slots.FirstOrDefault(s => s.Name.EqualsOrdinal(arg.Name)); if (nvp == null) { // 'def f(a, b)' and then 'f(0, c=1)'. Per spec: // if there is a 'keyword dictionary' argument, the argument is added // to the dictionary using the keyword name as the dictionary key, // unless there is already an entry with that key, in which case it is an error. if (_dictArgument == null) { _errors.Add(new DiagnosticsEntry(Resources.Analysis_UnknownParameterName, arg.GetLocation(eval).Span, ErrorCodes.UnknownParameterName, Severity.Warning, DiagnosticSource.Analysis)); return; } if (_dictArgument.Arguments.ContainsKey(arg.Name)) { _errors.Add(new DiagnosticsEntry(Resources.Analysis_ParameterAlreadySpecified.FormatUI(arg.Name), arg.GetLocation(eval).Span, ErrorCodes.ParameterAlreadySpecified, Severity.Warning, DiagnosticSource.Analysis)); return; } _dictArgument._Expressions[arg.Name] = arg.Expression; continue; } if (nvp.ValueExpression != null || nvp.Value != null) { // Slot is already filled. _errors.Add(new DiagnosticsEntry(Resources.Analysis_ParameterAlreadySpecified.FormatUI(arg.Name), arg.GetLocation(eval).Span, ErrorCodes.ParameterAlreadySpecified, Severity.Warning, DiagnosticSource.Analysis)); return; } // OK keyword parameter nvp.ValueExpression = arg.Expression; } // We went through all positionals and keywords. // For each remaining empty slot: if there is a default value for that slot, // then fill the slot with the default value. If there is no default value, // then it is an error. foreach (var slot in slots.Where(s => s.Kind != ParameterKind.List && s.Kind != ParameterKind.Dictionary && s.Value == null)) { if (slot.ValueExpression == null) { var parameter = overload.Parameters.First(p => p.Name == slot.Name); if (parameter.DefaultValue == null) { // TODO: parameter is not assigned and has no default value. _errors.Add(new DiagnosticsEntry(Resources.Analysis_ParameterMissing.FormatUI(slot.Name), callLocation.Span, ErrorCodes.ParameterMissing, Severity.Warning, DiagnosticSource.Analysis)); } // Note that parameter default value expression is from the function definition AST // while actual argument values are from the calling file AST. slot.ValueExpression = CreateExpression(parameter.Name, parameter.DefaultValueString); slot.Value = parameter.DefaultValue; slot.ValueIsDefault = true; } } } finally { // Optimistically return what we gathered, even if there are errors. _arguments = slots.Where(s => s.Kind != ParameterKind.List && s.Kind != ParameterKind.Dictionary).ToList(); } }
/// <summary> /// Creates an empty argument set with some context in how the argument set was used. /// </summary> /// <param name="expr">Expression associated with argument set.</param> /// <param name="eval">Evaluator for the expression involving the argument set.</param> /// <returns></returns> public static ArgumentSet Empty(Expression expr, IExpressionEvaluator eval) { return(new ArgumentSet(new List <IMember>(), expr, eval)); }
public static T Product <T>( this IExpressionEvaluator <T> evaluator, IEnumerable <T> values ) where T : struct, IComparable <T>, IEquatable <T> => values.Aggregate(evaluator.GetValue(1), (carry, current) => evaluator.Multiply(carry, current));