Exemplo n.º 1
0
 public virtual void Evaluate(EvaluationContext evaluationContext, Action<string> write)
 {
     foreach (ITemplate templateItem in this.Children)
     {
         templateItem.Evaluate(evaluationContext, write);
     }
 }
Exemplo n.º 2
0
		protected override object Evaluate(object context, EvaluationContext evalContext)
		{
			object left = Left.EvaluateInternal(context, evalContext);
			object right = Right.EvaluateInternal(context, evalContext);

			if (NumberUtils.IsNumber(left) && NumberUtils.IsNumber(right))
			{
				return NumberUtils.Add(left, right);
			}
			else if (left is DateTime && (right is TimeSpan || right is string || NumberUtils.IsNumber(right)))
			{
				if (NumberUtils.IsNumber(right))
				{
					right = TimeSpan.FromDays(System.Convert.ToDouble(right));
				}
				else if (right is string)
				{
					right = TimeSpan.Parse((string) right);
				}

				return (DateTime) left + (TimeSpan) right;
			}
			else if (left is String || right is String)
			{
				return left.ToString() + right.ToString();
			}
			else
			{
				throw new ArgumentException("Cannot add instances of '"
					+ left.GetType().FullName
					+ "' and '"
					+ right.GetType().FullName
					+ "'.");
			}		
		}
        /// <summary>
        /// Returns a value for the logical "greater than or equal" operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            object left = GetLeftValue( context, evalContext );
            object right = GetRightValue( context, evalContext );

            return CompareUtils.Compare(left, right) >= 0;
        }
Exemplo n.º 4
0
 /// <summary>
 /// Method called by the EvaluationEngine to evaluate the function.
 /// </summary>
 /// <param name="context">The evaluation context instance.</param>
 /// <param name="args">The IFuctionParameters that will be used as arguments to the function.</param>
 /// <returns></returns>
 public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args)
 {
     if (context == null) throw new ArgumentNullException("context");
     if (args == null) throw new ArgumentNullException("args");
     int argCount = GetIntegerArgument(args, 0);
     if (args.Length - 1 < argCount)
     {
         return EvaluationValue.Indeterminate;
     }
     else if (argCount == 0)
     {
         return EvaluationValue.True;
     }
     else
     {
         int count = 0;
         for (int i = 1; i < args.Length; i++)
         {
             if (GetBooleanArgument(args, i))
             {
                 count++;
             }
             if (count == argCount)
             {
                 return EvaluationValue.True;
             }
         }
         return EvaluationValue.False;
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Returns a value for the logical inequality operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            object leftVal = GetLeftValue( context, evalContext );
            object rightVal = GetRightValue( context, evalContext );

            if (leftVal == null)
            {
                return (rightVal != null);
            }
            else if (rightVal == null)
            {
                return true;
            }
            else if (leftVal.GetType() == rightVal.GetType())
            {
                if (leftVal is Array)
                {
                    return !ArrayUtils.AreEqual(leftVal as Array, rightVal as Array);
                }
                else
                {
                    return !leftVal.Equals(rightVal);
                }
            }
            else
            {
                return CompareUtils.Compare(leftVal, rightVal) != 0;
            }
        }
Exemplo n.º 6
0
    }//constructor

/*
    public override void OnCodeAnalysis(CodeAnalysisArgs args) {
      //process child nodes first, so that NameRef is processed
      base.OnCodeAnalysis(args);
      switch (args.Phase) {
        case CodeAnalysisPhase.Binding:
          if (NameRef.Slot != null) {
            NameRef.Slot.Flags |= SlotFlags.UsedAsCallTarget;
          } else {
            // Slot does not exist so it is not locally-defined method. Let's try global/library function
            // TODO: implement support for library references at scope level, so that all "import.." statements are checked 
            //  before checking global methods
            FixedTargetInfo = args.Context.Runtime.GetFunctionBindingInfo(NameRef.Name, Arguments);
            if (FixedTargetInfo == null) {
              args.Context.ReportError(this.Location, "Method not found: {0}", NameRef.Name);
              return;
            }
          }//else
          break;
        case CodeAnalysisPhase.MarkTailCalls:
          _isTail = IsSet(AstNodeFlags.IsTail) && this.Scope.Level > 0;
          break; 
        case CodeAnalysisPhase.Optimization:
          if (this.FixedTargetInfo != null)
            this.Evaluate = InvokeFixed;
          else
            this.Evaluate = InvokeDynamic;
          break;
      }//switch
    }//method

 */
 
    protected void InvokeDynamic(EvaluationContext context) {
      NameRef.Evaluate(context);
      Closure target;
      try {
        target = (Closure)context.CurrentResult;
        if (target.MethodName == null)
          target.MethodName = NameRef.Name;
      } catch (InvalidCastException castExc) {
        throw new RuntimeException("Method [" + NameRef.Name + "] not found or method reference is not set.", castExc, NameRef.Location);
      } catch (NullReferenceException) {
        throw new RuntimeException("Method reference is not set in variable " + NameRef.Name, null, NameRef.Location);
      }

      EvaluateArgs(context, target.BindingInfo);
      if (_isTail) {
        context.Tail = target;
        return; 
      } 
      //execute non-tail call
      target.Evaluate(context);
      if (context.Tail == null) return;
      //check returning tail
      while (context.Tail != null) {
        Closure tail = context.Tail;
        context.Tail = null;
        tail.Evaluate(context);
      }
      context.CallArgs = null;
    }
Exemplo n.º 7
0
        public override sealed double Evaluate(Tree<SyntaxToken> tree, EvaluationContext context)
        {
            var leaf = tree.Leafs[0];
            double value = leaf.Value.Evaluate(leaf, context);

            return Evaluate(value);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Returns left operand if it is not null, or the right operand if it is.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            object leftVal = GetValue(Left, context, evalContext);
            object rightVal = GetValue(Right, context, evalContext);

            return (leftVal != null ? leftVal : rightVal);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates new instance of the type defined by this node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            object[] argValues = ResolveArguments(evalContext);
            IDictionary namedArgValues = ResolveNamedArguments(evalContext);

            if (constructor == null)
            {
                lock(this)
                {
                    if (constructor == null)
                    {
                        constructor = InitializeNode(argValues, namedArgValues);
                    }
                }
            }

            object[] paramValues = (isParamArray ? ReflectionUtils.PackageParamArray(argValues, argumentCount, paramArrayType) : argValues);
            object instance = constructor.Invoke(paramValues);
            if (namedArgValues != null)
            {
                SetNamedArguments(instance, namedArgValues);
            }
            
            return instance;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns a value for the string literal node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            if (!initialized)
            {
                lock (this)
                {
                    if (!initialized)
                    {
                        AST node = this.getFirstChild();
                        condition = (BaseNode) node;
                        node = node.getNextSibling();
                        trueExp = (BaseNode) node;
                        node = node.getNextSibling();
                        falseExp = (BaseNode) node;

                        initialized = true;
                    }
                }
            }

            if (Convert.ToBoolean(GetValue(condition, context, evalContext)))
            {
                return GetValue(trueExp, context, evalContext);
            }
            else
            {
                return GetValue(falseExp, context, evalContext);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Evaluates function represented by this node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Result of the function evaluation.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            var name = getText();

            var argValues = ResolveArguments(evalContext);

            var function = evalContext.Variables[name];

            // delegate?
            var callback = function as Delegate;
            if (callback != null)
            {
                return InvokeDelegate(callback, argValues);
            }

            // lambda?
            var lambda = function as LambdaExpressionNode;
            if (lambda != null)
            {
                try
                {
                    return GetValueWithArguments(lambda, context, evalContext, argValues);
                }
                catch (ArgumentMismatchException ame)
                {
                    throw new InvalidOperationException( "Failed executing function " + name + ": " + ame.Message );
                }
            }

            if (function == null)
            {
                throw new InvalidOperationException("Function '" + name + "' is not defined.");
            }
            throw new InvalidOperationException("Function '" + name + "' is defined but of unknown type.");
        }
Exemplo n.º 12
0
 public override void Evaluate(EvaluationContext evaluationContext, Action<string> write)
 {
     foreach (ITemplate expression in this.Children)
     {
         expression.Evaluate(evaluationContext, write);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Returns a value for the logical equality operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            var lhs = GetLeftValue(context, evalContext);
            var rhs = GetRightValue(context, evalContext);

            if (lhs == null)
            {
                return (rhs == null);
            }
            if (rhs == null)
            {
                return false;
            }
            if (lhs.GetType() == rhs.GetType())
            {
                if (lhs is Array)
                {
                    return ArrayUtils.AreEqual(lhs as Array, rhs as Array);
                }
                return lhs.Equals(rhs);
            }
            if (lhs.GetType().IsEnum && rhs is string)
            {
                return lhs.Equals(Enum.Parse(lhs.GetType(), (string)rhs));
            }
            if (rhs.GetType().IsEnum && lhs is string)
            {
                return rhs.Equals(Enum.Parse(rhs.GetType(), (string)lhs));
            }
            return CompareUtils.Compare(lhs, rhs) == 0;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Returns a value for the logical "greater than or equal" operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            var lhs = GetLeftValue( context, evalContext );
            var rhs = GetRightValue( context, evalContext );

            return CompareUtils.Compare(lhs, rhs) >= 0;
        }
Exemplo n.º 15
0
		protected override object Evaluate(object context, EvaluationContext evalContext)
		{
			if (_value == null)
			{
				lock (this)
				{
					if (_value == null)
					{
						string n = this.getText();
						char lastChar = n.ToLower()[n.Length - 1];
						if (Char.IsDigit(lastChar))
						{
							_value = Double.Parse(n, NumberFormatInfo.InvariantInfo);
						}
						else
						{
							n = n.Substring(0, n.Length - 1);
							if (lastChar == 'm')
							{
								_value = Decimal.Parse(n, NumberFormatInfo.InvariantInfo);
							}
							else if (lastChar == 'f')
							{
								_value = Single.Parse(n, NumberFormatInfo.InvariantInfo);
							}
							else
							{
								_value = Double.Parse(n, NumberFormatInfo.InvariantInfo);
							}
						}
					}
				}
			}
			return _value;
		}
Exemplo n.º 16
0
		protected override object Evaluate(object context, EvaluationContext evalContext)
		{
			object left = Left.EvaluateInternal( context, evalContext );
			object right = Right.EvaluateInternal( context, evalContext );

			if (left == null)
			{
				return (right == null);
			}
			else if (right == null)
			{
				return false;
			}
			else if (left.GetType() == right.GetType())
			{
				return left.Equals(right);                    
			}
			else if (left.GetType().IsEnum && right is string)
			{
				return left.Equals(Enum.Parse(left.GetType(), (string) right));
			}
			else if (right.GetType().IsEnum && left is string)
			{
				return right.Equals(Enum.Parse(right.GetType(), (string) left));
			}
			else
			{
				return CompareUtils.Compare(left, right) == 0;
			}		
		}
Exemplo n.º 17
0
		protected override object Evaluate(object context, EvaluationContext evalContext)
		{
			object n = Operand.EvaluateInternal( context, evalContext );
			if (!NumberUtils.IsNumber(n))
				throw new ArgumentException("Specified operand is not a number. Only numbers support unary minus operator.");
			return NumberUtils.Negate(n);
		}
Exemplo n.º 18
0
        /// <summary>
        /// Method called by the EvaluationEngine to evaluate the function.
        /// </summary>
        /// <param name="context">The evaluation context instance.</param>
        /// <param name="args">The IFuctionParameters that will be used as arguments to the function.</param>
        /// <returns></returns>
        public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (args == null) throw new ArgumentNullException("args");
            IFunction function = args[0].GetFunction(0);
            if (!Equals(function.Returns, DataTypeDescriptor.Boolean))
            {
                return EvaluationValue.Indeterminate;
            }
            foreach (var par1 in args[1].Elements)
            {
                bool hasFound = false;
                foreach (var par2 in args[2].Elements)
                {
                    EvaluationValue retVal = function.Evaluate(
                        context,
                        new EvaluationValue(par1, args[1].GetType(context)),
                        new EvaluationValue(par2, args[2].GetType(context)));
                    if (!retVal.BoolValue)
                    {
                        hasFound = true;
                        break;
                    }
                }
                if (!hasFound)
                {
                    return EvaluationValue.True;
                }

            }
            return EvaluationValue.False;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Returns the last context item that matches selection expression.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            IList list = context as IList;

            if (list == null)
            {
                throw new ArgumentException(
                    "Selection can only be used on an instance of the type that implements IList.");
            }

            using (evalContext.SwitchThisContext())
            {
                BaseNode expression = (BaseNode) this.getFirstChild();
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    object listItem = list[i];
                    evalContext.ThisContext = listItem;
                    bool isMatch = (bool)GetValue(expression, listItem, evalContext );
                    if (isMatch)
                    {
                        return listItem;
                    }
                }
            }
            return null;
        }
Exemplo n.º 20
0
        /// <summary>
        ///     Creates new instance of the type defined by this node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            var argValues = ResolveArguments(evalContext);
            var namedArgValues = ResolveNamedArguments(evalContext);

            if (_constructor == null)
            {
                lock (this)
                {
                    if (_constructor == null)
                    {
                        _constructor = InitializeNode(argValues, namedArgValues);
                    }
                }
            }

            var paramValues = (_isParamArray
                ? ReflectionUtils.PackageParamArray(argValues, _argumentCount, _paramArrayType)
                : argValues);
            var instance = _constructor.Invoke(paramValues);
            if (namedArgValues != null)
            {
                SetNamedArguments(instance, namedArgValues);
            }

            return instance;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Returns a value for the string literal node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            if (!_initialized)
            {
                lock (this)
                {
                    if (!_initialized)
                    {
                        var node = getFirstChild();
                        _condition = (BaseNode) node;
                        node = node.getNextSibling();
                        _trueExp = (BaseNode) node;
                        node = node.getNextSibling();
                        _falseExp = (BaseNode) node;

                        _initialized = true;
                    }
                }
            }

            if (Convert.ToBoolean(GetValue(_condition, context, evalContext)))
            {
                return GetValue(_trueExp, context, evalContext);
            }
            return GetValue(_falseExp, context, evalContext);
        }
Exemplo n.º 22
0
        public override void Evaluate(EvaluationContext evaluationContext, Action<string> write)
        {
            string reference = this.Arguments;
            object evaluationResult = evaluationContext.GetValue(reference);

            write( evaluationResult == null ? string.Empty : evaluationResult.ToString() );
        }
Exemplo n.º 23
0
        /// <summary>
        /// Evaluates the function.
        /// </summary>
        /// <param name="context">The evaluation context instance.</param>
        /// <param name="args">The function arguments.</param>
        /// <returns>The result value of the function evaluation.</returns>
        public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (args == null) throw new ArgumentNullException("args");

            var retBag = new BagValue(DataType);
            IFunction functionDup = DataType.IsInFunction;
            foreach (object par1 in args[0].Elements)
            {
                EvaluationValue retVal = functionDup.Evaluate(context, new EvaluationValue(par1, args[0].GetType(context)), retBag);
                if (!retVal.BoolValue)
                {
                    retBag.Add(new EvaluationValue(par1, args[0].GetType(context)));
                }
            }
            foreach (object par2 in args[1].Elements)
            {
                EvaluationValue retVal = functionDup.Evaluate(context, new EvaluationValue(par2, args[1].GetType(context)), retBag);
                if (!retVal.BoolValue)
                {
                    retBag.Add(new EvaluationValue(par2, args[1].GetType(context)));
                }
            }
            return new EvaluationValue(retBag, DataType);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Returns a value for the logical AND operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            var lhs = GetLeftValue(context, evalContext);

            if (NumberUtils.IsInteger(lhs))
            {
                var rhs = GetRightValue(context, evalContext);
                if (NumberUtils.IsInteger(rhs))
                {
                    return NumberUtils.BitwiseAnd(lhs, rhs);
                }
            }
            else if (lhs is Enum)
            {
                var rhs = GetRightValue(context, evalContext);
                if (lhs.GetType() == rhs.GetType())
                {
                    var enumType = lhs.GetType();
                    var integralType = Enum.GetUnderlyingType(enumType);
                    lhs = Convert.ChangeType(lhs, integralType);
                    rhs = Convert.ChangeType(rhs, integralType);
                    var result = NumberUtils.BitwiseAnd(lhs, rhs);
                    return Enum.ToObject(enumType, result);
                }
            }

            return Convert.ToBoolean(lhs) &&
                Convert.ToBoolean(GetRightValue(context, evalContext));
        }
        public override object Eval(EvaluationContext.Context evaluationContext)
        {
            string baseCurrencyCode = _baseCurrencyCode.Eval(evaluationContext) as string;
            string variableCurrencyCode = _variableCurrencyCode.Eval(evaluationContext) as string;

            return evaluationContext.CurrencyDataSource.GetCurrencyPairData(baseCurrencyCode, variableCurrencyCode).ExchangeRates;
        }
Exemplo n.º 26
0
        /// <summary>
        /// Evaluates the function.
        /// </summary>
        /// <param name="context">The evaluation context instance.</param>
        /// <param name="args">The function arguments.</param>
        /// <returns>The result value of the function evaluation.</returns>
        public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (args == null) throw new ArgumentNullException("args");
            IFunction function = DataType.EqualFunction;
            foreach (object par1 in args[0].Elements)
            {
                bool hasFound = false;
                foreach (object par2 in args[1].Elements)
                {
                    EvaluationValue retVal = function.Evaluate(context, new EvaluationValue(par1, args[0].GetType(context)), new EvaluationValue(par2, args[1].GetType(context)));
                    if (retVal.BoolValue)
                    {
                        hasFound = true;
                        break;
                    }
                }
                if (!hasFound)
                {
                    return EvaluationValue.False;
                }

            }
            return EvaluationValue.True;
        }
Exemplo n.º 27
0
        protected override object Evaluate(object context, EvaluationContext evalContext)
        {
			string text = Left.EvaluateInternal( context, evalContext ) as string;
			string pattern = Right.EvaluateInternal( context, evalContext ) as string;
			return StrLike(text, pattern);

        }
Exemplo n.º 28
0
        /// <summary>
        /// Returns a value for the logical AND operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            object l = GetLeftValue(context, evalContext);

            if (NumberUtils.IsInteger(l))
            {
                object r = GetRightValue(context, evalContext);
                if (NumberUtils.IsInteger(r))
                {
                    return NumberUtils.BitwiseAnd(l, r);
                }
            }
            else if (l is Enum)
            {
                object r = GetRightValue(context, evalContext);
                if (l.GetType() == r.GetType())
                {
                    Type enumType = l.GetType();
                    Type integralType = Enum.GetUnderlyingType(enumType);
                    l = Convert.ChangeType(l, integralType);
                    r = Convert.ChangeType(r, integralType);
                    object result = NumberUtils.BitwiseAnd(l, r);
                    return Enum.ToObject(enumType, result);
                }
            }

            return Convert.ToBoolean(l) &&
                Convert.ToBoolean(GetRightValue(context, evalContext));
        }
Exemplo n.º 29
0
        public override object Eval(EvaluationContext.Context evaluationContext)
        {
            int numberOfDays = (int)_length.LengthExpr.Eval(evaluationContext);
            if (_length.PeriodicType == PeriodicType.Month)
            {
                numberOfDays *= 30;
            }
            
            DateTime requestDate = (DateTime) _requestDate.Eval(evaluationContext);


            if (TimeDataSetAccessor is ExchangeRateAccessor)
            {
                FXStrategy.DataAccess.TimeSeriesCollection<FXStrategy.DataAccess.ExchangeRateBid> timeSeries
                    = (FXStrategy.DataAccess.TimeSeriesCollection<FXStrategy.DataAccess.ExchangeRateBid>)
                    _timeDataSetAccessor.Eval(evaluationContext);
                return timeSeries.MovingAvg(requestDate, numberOfDays);          
            }
            else if (TimeDataSetAccessor is InterestRateAccessor)
            {
                FXStrategy.DataAccess.TimeSeriesCollection<FXStrategy.DataAccess.InterestRate> timeSeries 
                    = (FXStrategy.DataAccess.TimeSeriesCollection<FXStrategy.DataAccess.InterestRate>)
                    _timeDataSetAccessor.Eval(evaluationContext);
                return timeSeries.MovingAvg(requestDate, numberOfDays);          
            }
            else
                throw new Exception("Unhandled TimeDataSetAccessor: " + TimeDataSetAccessor.GetType().Name);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Evaluates the function.
        /// </summary>
        /// <param name="context">The evaluation context instance.</param>
        /// <param name="args">The function arguments.</param>
        /// <returns>The result value of the function evaluation.</returns>
        public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (args == null) throw new ArgumentNullException("args");
            XmlDocument doc = context.ContextDocument.XmlDocument;

            if (context.ContextDocument.XmlNamespaceManager == null)
            {
                context.ContextDocument.AddNamespaces(context.PolicyDocument.Namespaces);
            }

            string xPath = GetStringArgument(args, 0);
            Debug.Assert(doc.DocumentElement != null, "doc.DocumentElement != null");
            XmlNodeList firstList = doc.DocumentElement.SelectNodes(xPath, context.ContextDocument.XmlNamespaceManager);

            xPath = GetStringArgument(args, 1);
            XmlNodeList secondList = doc.DocumentElement.SelectNodes(xPath, context.ContextDocument.XmlNamespaceManager);

            Debug.Assert(firstList != null, "firstList != null");
            Debug.Assert(secondList != null, "secondList != null");
            foreach (XmlNode firstNode in firstList)
            {
                foreach (XmlNode secondNode in secondList)
                {
                    if (firstNode == secondNode)
                    {
                        return EvaluationValue.True;
                    }
                }
            }
            return EvaluationValue.False;
        }
        public void ContextDisambiguatesAFullyQualifiedGlobPointingInAnotherRelativeGlobsCone(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
        {
            if (policy == EvaluationContext.SharingPolicy.Shared)
            {
                // This test case has a dependency on our glob expansion caching policy. If the evaluation context is reused
                // between evaluations and files are added to the filesystem between evaluations, the cache may be returning
                // stale results. Run only the Isolated variant.
                return;
            }

            var project1Directory     = _env.DefaultTestDirectory.CreateDirectory("Project1");
            var project1GlobDirectory = project1Directory.CreateDirectory("Glob").CreateDirectory("1").Path;

            var project2Directory = _env.DefaultTestDirectory.CreateDirectory("Project2");

            var context = EvaluationContext.Create(policy);

            var evaluationCount = 0;

            File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), "");

            EvaluateProjects(
                new []
            {
                // first project uses a relative path
                new ProjectSpecification(
                    Path.Combine(project1Directory.Path, "1"),
                    $@"<Project>
                            <ItemGroup>
                                <i Include=`{Path.Combine("Glob", "**", "*.cs")}` />
                            </ItemGroup>
                        </Project>"),
                // second project reaches out into first project's cone via a fully qualified path
                new ProjectSpecification(
                    Path.Combine(project2Directory.Path, "2"),
                    $@"<Project>
                            <ItemGroup>
                                <i Include=`{Path.Combine(project1Directory.Path, "Glob", "**", "*.cs")}` />
                            </ItemGroup>
                        </Project>")
            },
                context,
                project =>
            {
                var projectName = Path.GetFileNameWithoutExtension(project.FullPath);

                // globs have the fixed directory part prepended, so add it to the expected results
                var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]
                                            .Select(i => Path.Combine("Glob", "1", i))
                                            .ToArray();

                // project 2 has fully qualified directory parts, so make the results for 2 fully qualified
                if (projectName.Equals("2"))
                {
                    expectedGlobExpansion = expectedGlobExpansion
                                            .Select(i => Path.Combine(project1Directory.Path, i))
                                            .ToArray();
                }

                var actualGlobExpansion = project.GetItems("i");
                ObjectModelHelpers.AssertItems(expectedGlobExpansion, actualGlobExpansion);

                evaluationCount++;

                File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), "");
            }
                );
        }
        /// <summary>
        /// Should be at least two test projects to test cache visibility between projects
        /// </summary>
        private void EvaluateProjects(IEnumerable <ProjectSpecification> projectSpecs, EvaluationContext context, Action <Project> afterEvaluationAction)
        {
            var collection = _env.CreateProjectCollection().Collection;

            var projects = new List <Project>();

            foreach (var(projectFilePath, projectContents) in projectSpecs)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(projectFilePath));
                File.WriteAllText(projectFilePath, projectContents.Cleanup());

                var project = Project.FromFile(
                    projectFilePath,
                    new ProjectOptions
                {
                    ProjectCollection = collection,
                    EvaluationContext = context,
                    LoadSettings      = ProjectLoadSettings.IgnoreMissingImports
                });

                afterEvaluationAction?.Invoke(project);

                projects.Add(project);
            }

            foreach (var project in projects)
            {
                project.AddItem("a", "b");
                project.ReevaluateIfNecessary(context);

                afterEvaluationAction?.Invoke(project);
            }
        }
Exemplo n.º 33
0
 public ArrayAdaptor(EvaluationContext ctx, CorValRef obj)
 {
     this.obj = obj;
     this.ctx = (CorEvaluationContext)ctx;
 }
Exemplo n.º 34
0
 // Constructeur
 public QuestionPropositionRepository(EvaluationContext context)
 {
     evaluationContext = context ?? throw new ArgumentNullException($"{nameof(context)} in EvaluationRepository");
 }
Exemplo n.º 35
0
 public override DataTypeValue Evaluate(DataTypeValue[] @params, EvaluationContext ctx)
 {
     return(this.Evaluate(@params, ctx, typeof(BooleanDataType)));
 }
Exemplo n.º 36
0
 public Add_mul_id_c_id_Rule(EvaluationContext ctx)
 {
     this.ctx = ctx;
 }
Exemplo n.º 37
0
 public IntroduceImports(EvaluationContext context)
 {
     this._evaluationContext = context;
 }
Exemplo n.º 38
0
 public IdCopyPropagationRule(EvaluationContext ctx)
 {
     this.ctx = ctx;
 }
Exemplo n.º 39
0
        private static AssemblyIdentity GetMissingAssemblyIdentity(ErrorCode code, params object[] arguments)
        {
            var missingAssemblyIdentities = EvaluationContext.GetMissingAssemblyIdentitiesHelper(code, arguments, EvaluationContextBase.SystemCoreIdentity);

            return(missingAssemblyIdentities.IsDefault ? null : missingAssemblyIdentities.Single());
        }
Exemplo n.º 40
0
 public ConvertConvertRule(EvaluationContext ctx)
 {
     this.ctx = ctx;
 }
Exemplo n.º 41
0
        private object[] datas; //  Various types of data contained in the expression.

        /// <summary>
        /// Evaluates the current expression.
        /// </summary>
        /// <param name="context">The context of the evaluation.</param>
        /// <param name="res">The variable which will contain the result of the evaluation.</param>
        protected override void Evaluate(EvaluationContext context, out EvaluationResult res)
        {
            res = new EvaluationResult(CommonStatusCodes.Success, this, Value, datas);
        }
Exemplo n.º 42
0
 public IdConstant(EvaluationContext ctx, Unifier u, DecompilerEventListener listener)
 {
     this.ctx      = ctx;
     this.unifier  = u;
     this.listener = listener;
 }
Exemplo n.º 43
0
        public void Evaluate(EvaluationContext ctx, IPolicyLanguageModel[] evals, string ID)
        {
            if (ctx.GetResult(ID).HasDecision())
            {
                return;
            }

            bool atLeastOneErrorD  = false;
            bool atLeastOneErrorP  = false;
            bool atLeastOneErrorDP = false;
            bool atLeastOnePermit  = false;

            string PermitID = null;

            for (int i = 0; i < evals.Length; i++)
            {
                evals[i].Evaluate(ctx, ID);
                Decision _Decision = ctx.GetResult(evals[i].ElementId).Decision;

                if (_Decision.IsDeny)
                {
                    ctx.GetResult(ID).Decision = Decision.Deny;
                    ctx.GetResult(ID).PassObligationsAndAdvices(ctx.GetResult(evals[i].ElementId));
                    return;
                }

                if (_Decision.IsPermit)
                {
                    atLeastOnePermit = true;
                    PermitID         = evals[i].ElementId;
                    continue;
                }

                if (_Decision.IsDecisionIndeterminateD)
                {
                    atLeastOneErrorD = true;
                    continue;
                }

                if (_Decision.IsDecisionIndeterminateP)
                {
                    atLeastOneErrorP = true;
                    continue;
                }

                if (_Decision.IsDecisionIndeterminateDP)
                {
                    atLeastOneErrorDP = true;
                    continue;
                }
            }
            if (atLeastOneErrorDP)
            {
                ctx.GetResult(ID).Decision = Decision.IndeterminateDP;
            }
            else if (atLeastOneErrorD && (atLeastOneErrorP || atLeastOnePermit))
            {
                ctx.GetResult(ID).Decision = Decision.IndeterminateDP;
            }
            else if (atLeastOneErrorD)
            {
                ctx.GetResult(ID).Decision = Decision.IndeterminateD;
            }
            else if (atLeastOnePermit)
            {
                ctx.GetResult(ID).Decision = Decision.Permit;
                ctx.GetResult(ID).PassObligationsAndAdvices(ctx.GetResult(PermitID));
            }
            else if (atLeastOneErrorP)
            {
                ctx.GetResult(ID).Decision = Decision.IndeterminateP;
            }
            else
            {
                ctx.GetResult(ID).Decision = Decision.NotApplicable;
            }
        }
Exemplo n.º 44
0
        public void AddNewFormThenRemoveItReturnsTrue()
        {
            var options = new DbContextOptionsBuilder <EvaluationContext>()
                          .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name)
                          .Options;

            using (var memoryContext = new EvaluationContext(options))
            {
                // Arrange
                IFormRepository                formRepository                = new FormRepository(memoryContext);
                IQuestionRepository            questionRepository            = new QuestionRepository(memoryContext);
                IQuestionPropositionRepository questionPropositionRepository = new QuestionPropositionRepository(memoryContext);

                #region Form

                var Form1 = new FormTO
                {
                    Name = new MultiLanguageString
                           (
                        "Daily evaluation form",
                        "Formulaire d'évaluation journalier",
                        "Dagelijks evaluatieformulier"
                           ),
                };

                var Form2 = new FormTO
                {
                    Name = new MultiLanguageString
                           (
                        "Daily evaluation form2",
                        "Formulaire d'évaluation journalier2",
                        "Dagelijks evaluatieformulier2"
                           ),
                };

                var Form3 = new FormTO
                {
                    Name = new MultiLanguageString
                           (
                        "Daily evaluation form3",
                        "Formulaire d'évaluation journalier3",
                        "Dagelijks evaluatieformulier3"
                           ),
                };


                var formAdded1 = formRepository.Add(Form1);
                var formAdded2 = formRepository.Add(Form2);
                var formAdded3 = formRepository.Add(Form3);
                memoryContext.SaveChanges();

                #endregion

                #region Questions

                var Question1 = new QuestionTO
                {
                    FormId   = formAdded1.Id,
                    Position = 1,
                    Libelle  = new MultiLanguageString
                               (
                        "What is your general impression after this first day of training ?",
                        "Quelle est votre impression générale après cette première journée de formation ?",
                        "Wat is je algemene indruk na deze eerste dag van training ?"
                               ),
                    Type = QuestionType.SingleChoice,
                };

                var Question2 = new QuestionTO
                {
                    FormId   = formAdded1.Id,
                    Position = 2,
                    Libelle  = new MultiLanguageString
                               (
                        "Is the pace right for you ?",
                        "Est-ce que le rythme vous convient ?",
                        "Is het tempo geschikt voor u ?"
                               ),
                    Type = QuestionType.SingleChoice,
                };

                var Question3 = new QuestionTO
                {
                    FormId   = formAdded1.Id,
                    Position = 3,
                    Libelle  = new MultiLanguageString
                               (
                        "Do you have questions related to the subject studied today ?",
                        "Avez-vous des questions relatives à la matière étudiée aujourd’hui ?",
                        "Heb je vragen over het onderwerp dat vandaag is bestudeerd ?"
                               ),
                    Type = QuestionType.Open
                };

                var Question4 = new QuestionTO
                {
                    FormId   = formAdded1.Id,
                    Position = 4,
                    Libelle  = new MultiLanguageString
                               (
                        "Do you have specific questions / particular topics that you would like deepen during this training ?",
                        "Avez-vous des questions spécifiques/sujets particuliers que vous aimeriez approfondir durant cette formation ?",
                        "Heeft u specifieke vragen / specifieke onderwerpen die u graag zou willen verdiepen tijdens deze training ?"
                               ),
                    Type = QuestionType.Open
                };

                var Question5 = new QuestionTO
                {
                    FormId   = formAdded1.Id,
                    Position = 5,
                    Libelle  = new MultiLanguageString
                               (
                        "What objectives do you pursue by following this training ?",
                        "Quels objectifs poursuivez-vous en suivant cette formation ?",
                        "Welke doelstellingen streeft u na door deze training te volgen?"
                               ),
                    Type = QuestionType.Open
                };

                var questionAdded1 = questionRepository.Add(Question1);
                var questionAdded2 = questionRepository.Add(Question2);
                var questionAdded3 = questionRepository.Add(Question3);
                var questionAdded4 = questionRepository.Add(Question4);
                var questionAdded5 = questionRepository.Add(Question5);
                memoryContext.SaveChanges();

                #endregion

                #region QuestionProposition
                var QuestionProposition1 = new QuestionPropositionTO
                {
                    QuestionId = questionAdded1.Id,
                    Libelle    = new MultiLanguageString("good", "bonne", "goed"),
                    Position   = 1
                };

                var QuestionProposition2 = new QuestionPropositionTO
                {
                    QuestionId = questionAdded1.Id,
                    Libelle    = new MultiLanguageString("medium", "moyenne", "gemiddelde"),
                    Position   = 2
                };

                var QuestionProposition3 = new QuestionPropositionTO
                {
                    QuestionId = questionAdded1.Id,
                    Libelle    = new MultiLanguageString("bad", "mauvaise", "slecht"),
                    Position   = 3
                };

                var QuestionProposition4 = new QuestionPropositionTO
                {
                    QuestionId = questionAdded2.Id,
                    Libelle    = new MultiLanguageString("yes", "oui", "ja"),
                    Position   = 1
                };

                var QuestionProposition5 = new QuestionPropositionTO
                {
                    QuestionId = questionAdded2.Id,
                    Libelle    = new MultiLanguageString("too fast", "trop rapide", "te snel"),
                    Position   = 2
                };

                var QuestionProposition6 = new QuestionPropositionTO
                {
                    QuestionId = questionAdded2.Id,
                    Libelle    = new MultiLanguageString("too slow", "trop lent", "te langzaam"),
                    Position   = 3
                };

                var questionPropositionAdded1 = questionPropositionRepository.Add(QuestionProposition1);
                var questionPropositionAdded2 = questionPropositionRepository.Add(QuestionProposition2);
                var questionPropositionAdded3 = questionPropositionRepository.Add(QuestionProposition3);
                var questionPropositionAdded4 = questionPropositionRepository.Add(QuestionProposition4);
                var questionPropositionAdded5 = questionPropositionRepository.Add(QuestionProposition5);
                var questionPropositionAdded6 = questionPropositionRepository.Add(QuestionProposition6);
                memoryContext.SaveChanges();
                #endregion

                // act
                var result1 = formRepository.Remove(formAdded1);
                var result2 = formRepository.Remove(formAdded2.Id);
                memoryContext.SaveChanges();
                var count = formRepository.GetAll().Count();

                // assert
                Assert.IsTrue(result1);
                Assert.IsTrue(result2);
                Assert.AreEqual(1, count);
            }
        }
Exemplo n.º 45
0
        public override ISqlExpression ConvertExpressionImpl <TContext>(ISqlExpression expression, ConvertVisitor <TContext> visitor,
                                                                        EvaluationContext context)
        {
            expression = base.ConvertExpressionImpl(expression, visitor, context);

            switch (expression.ElementType)
            {
            case QueryElementType.SqlBinaryExpression:
            {
                var be = (SqlBinaryExpression)expression;

                switch (be.Operation)
                {
                case "%":
                {
                    var type1 = be.Expr1.SystemType !.ToUnderlying();

                    if (type1 == typeof(double) || type1 == typeof(float))
                    {
                        return(new SqlBinaryExpression(
                                   be.Expr2.SystemType !,
                                   new SqlFunction(typeof(int), "Convert", SqlDataType.Int32, be.Expr1),
                                   be.Operation,
                                   be.Expr2));
                    }

                    break;
                }
                }

                break;
            }

            case QueryElementType.SqlFunction:
            {
                var func = (SqlFunction)expression;

                switch (func.Name)
                {
                case "Convert":
                {
                    if (func.SystemType.ToUnderlying() == typeof(ulong) &&
                        func.Parameters[1].SystemType !.IsFloatType())
                    {
                        return(new SqlFunction(
                                   func.SystemType,
                                   func.Name,
                                   false,
                                   func.Precedence,
                                   func.Parameters[0],
                                   new SqlFunction(func.SystemType, "Floor", func.Parameters[1])));
                    }

                    if (Type.GetTypeCode(func.SystemType.ToUnderlying()) == TypeCode.DateTime)
                    {
                        var type1 = func.Parameters[1].SystemType !.ToUnderlying();

                        if (IsTimeDataType(func.Parameters[0]))
                        {
                            if (type1 == typeof(DateTimeOffset) || type1 == typeof(DateTime))
                            {
                                if (_sqlVersion >= SqlServerVersion.v2008)
                                {
                                    return(new SqlExpression(
                                               func.SystemType, "CAST({0} AS TIME)", Precedence.Primary, func.Parameters[1]));
                                }
                                else
                                {
                                    return(new SqlExpression(
                                               func.SystemType, "Cast(Convert(Char, {0}, 114) as DateTime)", Precedence.Primary, func.Parameters[1]));
                                }
                            }

                            if (func.Parameters[1].SystemType == typeof(string))
                            {
                                return(func.Parameters[1]);
                            }

                            return(new SqlExpression(
                                       func.SystemType, "Convert(Char, {0}, 114)", Precedence.Primary, func.Parameters[1]));
                        }

                        if (type1 == typeof(DateTime) || type1 == typeof(DateTimeOffset))
                        {
                            if (IsDateDataType(func.Parameters[0], "Datetime"))
                            {
                                return(new SqlExpression(
                                           func.SystemType, "Cast(Floor(Cast({0} as Float)) as DateTime)", Precedence.Primary, func.Parameters[1]));
                            }
                        }

                        if (func.Parameters.Length == 2 && func.Parameters[0] is SqlDataType && func.Parameters[0] == SqlDataType.DateTime)
                        {
                            return(new SqlFunction(func.SystemType, func.Name, func.IsAggregate, func.Precedence, func.Parameters[0], func.Parameters[1], new SqlValue(120)));
                        }
                    }


                    break;
                }
                }

                break;
            }
            }

            return(expression);
        }
 public IndexerValueReference(EvaluationContext ctx, TargetStructObject target, TargetObject[] index, TargetPropertyInfo indexerProp) : base(ctx)
 {
     this.indexer = indexerProp;
     this.target  = target;
     this.index   = index;
 }
Exemplo n.º 47
0
 /// <inheritdoc/>
 public override GraceObject Respond(EvaluationContext ctx, GraceObject self, MethodRequest req)
 {
     MethodHelper.CheckNoInherits(ctx, req);
     return(returnValue);
 }
Exemplo n.º 48
0
 protected override void Initialize(EvaluationContext context)
 {
     _body      = Build(_statement.Body);
     _labelName = _statement.Label.Name;
 }
Exemplo n.º 49
0
 /// <inheritdoc/>
 public override GraceObject Respond(EvaluationContext ctx,
                                     GraceObject self,
                                     MethodRequest req)
 {
     return(method(ctx, req, self));
 }
Exemplo n.º 50
0
 protected override ExpressionResult EvaluateInternal(EvaluationContext context)
 {
     return(_canBuildFast
         ? BuildObjectFast(context)
         : BuildObjectNormal(context));
 }
Exemplo n.º 51
0
 protected override ExpressionResult EvaluateInternal(EvaluationContext context)
 {
     return(NormalCompletion(EvaluateConstantOrExpression(context)));
 }
Exemplo n.º 52
0
 /// <inheritdoc/>
 public override GraceObject Respond(EvaluationContext ctx, GraceObject self, MethodRequest req)
 {
     MethodHelper.CheckArity(ctx, req, 0);
     return(method());
 }
Exemplo n.º 53
0
        DbgDotNetCompilationResult CompileExpressionCore(DbgDotNetAlias[] aliases, string expression, DbgEvaluationOptions options, VisualBasicEvalContextState state, EvaluationContext evalCtx, CancellationToken cancellationToken)
        {
            state.MetadataContext = new VisualBasicMetadataContext(evalCtx.Compilation, evalCtx);
            var compilationFlags = DkmEvaluationFlags.None;

            if ((options & DbgEvaluationOptions.Expression) != 0)
            {
                compilationFlags |= DkmEvaluationFlags.TreatAsExpression;
            }
            var           compileResult = evalCtx.CompileExpression(expression, compilationFlags, CreateAliases(aliases), out var resultProperties, out var errorMessage);
            DbgDotNetText name;

            if ((options & DbgEvaluationOptions.NoName) != 0)
            {
                name = DbgDotNetText.Empty;
            }
            else if (compileResult == null || errorMessage != null)
            {
                name = CreateErrorName(expression);
            }
            else
            {
                name = GetExpressionText(state.MetadataContext.EvaluationContext, state.MetadataContext.Compilation, expression, cancellationToken);
            }
            return(CreateCompilationResult(expression, compileResult, resultProperties, errorMessage, name));
        }
Exemplo n.º 54
0
 public static GraceObject Instantiate(
     EvaluationContext ctx)
 {
     return(new ExposedCompiler());
 }
Exemplo n.º 55
0
 /// <summary>Native method for Grace ++</summary>
 /// <param name="ctx">Current interpreter</param>
 /// <param name="other">Second iterable to concatenate</param>
 public GraceObject Concat(EvaluationContext ctx, GraceObject other)
 {
     return(Iterables.Concatenate(this, other));
 }
Exemplo n.º 56
0
 public override Completion GetValue(EvaluationContext context)
 {
     // need to notify correct node when taking shortcut
     context.LastSyntaxNode = _expression;
     return(Completion.Normal(EvaluateConstantOrExpression(context), _expression.Location));
 }
Exemplo n.º 57
0
 /// <summary>
 /// Resolves the named argument.
 /// </summary>
 /// <param name="name">Argument name.</param>
 /// <param name="evalContext">Current expression evaluation context.</param>
 /// <returns>Resolved named argument value.</returns>
 private object ResolveNamedArgument(string name, EvaluationContext evalContext)
 {
     return(GetValue(((BaseNode)namedArgs[name]), evalContext.ThisContext, evalContext));
 }
Exemplo n.º 58
0
 /// <summary>Reusable native method for concatenation</summary>
 /// <param name="ctx">Current interpreter</param>
 /// <param name="receiver">Object on which the method was
 /// requested</param>
 /// <param name="other">Argument to the method</param>
 public static GraceObject MConcat(EvaluationContext ctx,
                                   GraceObject receiver,
                                   GraceObject other)
 {
     return(Iterables.Concatenate(receiver, other));
 }
Exemplo n.º 59
0
        public LazyItemEvaluator(IEvaluatorData <P, I, M, D> data, IItemFactory <I, I> itemFactory, LoggingContext loggingContext, EvaluationProfiler evaluationProfiler, EvaluationContext evaluationContext)
        {
            _outerEvaluatorData = data;
            _outerExpander      = new Expander <P, I>(_outerEvaluatorData, _outerEvaluatorData, evaluationContext.FileSystem);
            _evaluatorData      = new EvaluatorData(_outerEvaluatorData, itemType => GetItems(itemType));
            _expander           = new Expander <P, I>(_evaluatorData, _evaluatorData, evaluationContext.FileSystem);
            _itemFactory        = itemFactory;
            _loggingContext     = loggingContext;
            _evaluationProfiler = evaluationProfiler;

            FileSystem          = evaluationContext.FileSystem;
            EngineFileUtilities = evaluationContext.EngineFileUtilities;
        }
 public VariableValueReference(EvaluationContext ctx, string name, LocalVariable variable) : base(ctx)
 {
     this.name     = name;
     this.variable = variable;
 }