public NumericMethodExpression(IObjectExpression containingObject, MethodInfo methodInfo, ListExpression argumentsExpr)
        {
            this.containingObject = containingObject;
            this.methodInfo       = methodInfo;
            this.argumentsExpr    = argumentsExpr;

            Type       containingObjectType = containingObject.ObjectType;
            Type       returnType           = methodInfo.ReturnType;
            MethodInfo generateEvaluatorMethod;

            ParameterInfo[] parameters = methodInfo.GetParameters();

            switch (parameters.Length)
            {
            case 0:
                generateEvaluatorMethod = GetType()
                                          .GetMethod("GenerateFunctor0", BindingFlags.NonPublic | BindingFlags.Static)
                                          .MakeGenericMethod(containingObjectType, returnType);
                break;

            case 1:
                generateEvaluatorMethod = GetType()
                                          .GetMethod("GenerateFunctor1", BindingFlags.NonPublic | BindingFlags.Static)
                                          .MakeGenericMethod(containingObjectType, parameters[0].ParameterType, returnType);
                break;

            case 2:
                generateEvaluatorMethod = GetType()
                                          .GetMethod("GenerateFunctor2", BindingFlags.NonPublic | BindingFlags.Static)
                                          .MakeGenericMethod(containingObjectType,
                                                             parameters[0].ParameterType,
                                                             parameters[1].ParameterType,
                                                             returnType);
                break;

            case 3:
                generateEvaluatorMethod = GetType()
                                          .GetMethod("GenerateFunctor3", BindingFlags.NonPublic | BindingFlags.Static)
                                          .MakeGenericMethod(containingObjectType,
                                                             parameters[0].ParameterType,
                                                             parameters[1].ParameterType,
                                                             parameters[2].ParameterType,
                                                             returnType);
                break;

            default:
                throw new NotSupportedException();
            }

            var generateEvaluatorDelegate = ReflectionHelper
                                            .CreateDelegate <MethodInfo, ListExpression, Func <Dictionary <string, object>, object, double> >(generateEvaluatorMethod);

            evaluator = generateEvaluatorDelegate(methodInfo, argumentsExpr);
        }
Ejemplo n.º 2
0
        public void CreateListWithVariableAsTail()
        {
            Context context = new Context();
            var expr = new ListExpression(new IExpression[] { new ConstantExpression(1), new ConstantExpression(2) }, new VariableExpression(new Variable("Tail")));

            var result = expr.Evaluate(context, true);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(List));
            Assert.AreEqual("[1,2|Tail]", result.ToString());
        }
        /// <summary>
        /// Provides the expression text
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string retVal = OPERATOR + " " + ListExpression.ToString();

            if (Condition != null)
            {
                retVal += " | " + Condition.ToString();
            }

            return(retVal);
        }
        /// <summary>
        /// Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation, bool apply)
        {
            Variables.IVariable variable = ListExpression.GetVariable(context);
            if (variable != null)
            {
                // HacK : ensure that the value is a correct rigth side
                // and keep the result of the right side operation
                Values.ListValue listValue = variable.Value.RightSide(variable, false) as Values.ListValue;
                variable.Value = listValue;
                if (listValue != null)
                {
                    Values.ListValue newListValue = new Values.ListValue(listValue);

                    int i = 0;
                    foreach (Values.IValue current in newListValue.Val)
                    {
                        IteratorVariable.Value = current;
                        if (conditionSatisfied(context))
                        {
                            break;
                        }
                        i += 1;
                    }

                    if (i < newListValue.Val.Count)
                    {
                        Values.IValue value = Value.GetValue(context);
                        if (value != null)
                        {
                            newListValue.Val[i] = value;
                            Rules.Change change = new Rules.Change(variable, variable.Value, newListValue);
                            changes.Add(change, apply);
                            explanation.SubExplanations.Add(new ExplanationPart(Root, change));
                        }
                        else
                        {
                            Root.AddError("Cannot find value for " + Value.ToString());
                        }
                    }
                    else
                    {
                        Root.AddError("Cannot find value in " + ListExpression.ToString() + " which satisfies " + Condition.ToString());
                    }
                }
                else
                {
                    Root.AddError("Variable " + ListExpression.ToString() + " does not contain a list value");
                }
            }
            else
            {
                Root.AddError("Cannot find variable for " + ListExpression.ToString());
            }
        }
Ejemplo n.º 5
0
        public void ConstructUsing_FactoryMethod_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.ConstructUsing(() => new Request());

            expression.ModelActivatorDefinition.Method.Should().NotBeNull();
            expression.ModelActivatorDefinition.FactoryType.Should().BeNull();
            expression.ModelActivatorDefinition.Factory.Should().BeNull();
            expression.ModelActivatorDefinition.Method(typeof(Request)).Should().BeOfType <Request>();
        }
        public IMember GetValueFromList(ListExpression expression)
        {
            var contents = new List <IMember>();

            foreach (var item in expression.Items.Take(MaxCollectionSize))
            {
                var value = GetValueFromExpression(item) ?? UnknownType;
                contents.Add(value);
            }
            return(PythonCollectionType.CreateList(Module.Interpreter, contents, exact: expression.Items.Count <= MaxCollectionSize));
        }
Ejemplo n.º 7
0
        public void SortDirection_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.SortDirection();
            var definition = expression.SortDirectionDefinition;

            definition.RequestProperty.Should().BeNull();
            definition.ResultProperty.Should().BeNull();
            definition.DefaultValue.Should().BeNull();
            definition.Name.Should().BeNull();
        }
Ejemplo n.º 8
0
        public void SortDirection_Property_DefaultValueByAttribute_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.SortDirection(x => x.Sortd);
            var definition = expression.SortDirectionDefinition;

            definition.RequestProperty.Name.Should().Be("Sortd");
            definition.ResultProperty.Should().BeNull();
            definition.DefaultValue.Should().Be(Direction.Ascending);
            definition.Name.Should().BeNull();
        }
Ejemplo n.º 9
0
        public void SortDirection_Property_MapTo_Property_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.SortDirection(x => x.Ordd, x => x.MapTo(m => m.Ordd));
            var definition = expression.SortDirectionDefinition;

            definition.RequestProperty.Name.Should().Be("Ordd");
            definition.ResultProperty.Name.Should().Be("Ordd");
            definition.DefaultValue.Should().BeNull();
            definition.Name.Should().BeNull();
        }
Ejemplo n.º 10
0
        public void Rows_Name_DefaultValue_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Rows("Rows", x => x.DefaultValue(2));
            var definition = expression.RowsDefinition;

            definition.RequestProperty.Should().BeNull();
            definition.ResultProperty.Should().BeNull();
            definition.Name.Should().Be("Rows");
            definition.DefaultValue.Should().Be(2);
        }
Ejemplo n.º 11
0
        public void Rows_Property_DefaultValueByAttribute_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Rows(x => x.CurrentRows);
            var definition = expression.RowsDefinition;

            definition.RequestProperty.Name.Should().Be("CurrentRows");
            definition.ResultProperty.Should().BeNull();
            definition.Name.Should().BeNullOrWhiteSpace();
            definition.DefaultValue.Should().Be(2);
        }
Ejemplo n.º 12
0
        public void Rows_Property_MapTo_Property_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Rows(x => x.Rows, x => x.MapTo(m => m.Rows));
            var definition = expression.RowsDefinition;

            definition.RequestProperty.Name.Should().Be("Rows");
            definition.ResultProperty.Name.Should().Be("Rows");
            definition.Name.Should().BeNullOrWhiteSpace();
            definition.DefaultValue.Should().BeNull();
        }
Ejemplo n.º 13
0
        public void Page_Name_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Page("Page");
            var definition = expression.PageDefinition;

            definition.RequestProperty.Should().BeNull();
            definition.ResultProperty.Should().BeNull();
            definition.Name.Should().Be("Page");
            definition.DefaultValue.Should().BeNull();
        }
Ejemplo n.º 14
0
        public void Page_Property_DefaultValue_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Page(x => x.Page, x => x.DefaultValue(2));
            var definition = expression.PageDefinition;

            definition.RequestProperty.Name.Should().Be("Page");
            definition.ResultProperty.Should().BeNull();
            definition.Name.Should().BeNullOrWhiteSpace();
            definition.DefaultValue.Should().Be(2);
        }
Ejemplo n.º 15
0
        public void Property_Property_DefaultValueByAttribute_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Property(x => x.NotAQuery);
            var definition = expression.PropertyDefinitions.First().Value;

            definition.RequestProperty.Name.Should().Be("NotAQuery");
            definition.ResultProperty.Should().BeNull();
            definition.DefaultValue.Should().Be("Test");
            definition.Ignore.Should().BeNull();
        }
Ejemplo n.º 16
0
        public void Property_Property_Ignore_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Property(x => x.Query, x => x.Ignore());
            var definition = expression.PropertyDefinitions.First(x => x.Key.Name == "Query").Value;

            definition.RequestProperty.Name.Should().Be("Query");
            definition.ResultProperty.Should().BeNull();
            definition.DefaultValue.Should().BeNull();
            definition.Ignore.Should().BeTrue();
        }
Ejemplo n.º 17
0
        public void Rows_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.Rows();
            var definition = expression.RowsDefinition;

            definition.RequestProperty.Should().BeNull();
            definition.ResultProperty.Should().BeNull();
            definition.Name.Should().BeNullOrWhiteSpace();
            definition.DefaultValue.Should().BeNull();
        }
Ejemplo n.º 18
0
        public void SortDirection_Name_DefaultValue_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.SortDirection("Direction", x => x.DefaultValue(Direction.Ascending));
            var definition = expression.SortDirectionDefinition;

            definition.RequestProperty.Should().BeNull();
            definition.ResultProperty.Should().BeNull();
            definition.DefaultValue.Should().Be(Direction.Ascending);
            definition.Name.Should().Be("Direction");
        }
Ejemplo n.º 19
0
    public static ListExpression ParseExpressionListStr(string code, out string remCode)
    {
        ListExpression expList = new ListExpression();

        char[] codeArr     = code.ToCharArray();
        int    subExpStart = 0;

        for (int i = 0; i < code.Length; i++)
        {
            if (' ' == codeArr[i] ||
                '\t' == codeArr[i])
            {
                string var = code.Substring(subExpStart, i - subExpStart);

                if (!String.IsNullOrEmpty(var))
                {
                    VariableExpression subExp = new VariableExpression {
                        Variable = var
                    };
                    expList.expList.Add(subExp);
                }

                subExpStart = i + 1;
                continue;
            }

            if (')' == codeArr[i])
            {
                string var = code.Substring(subExpStart, i - subExpStart);

                if (!String.IsNullOrEmpty(var))
                {
                    VariableExpression subExp = new VariableExpression {
                        Variable = var
                    };
                    expList.expList.Add(subExp);
                }

                remCode = code.Substring(i + 1);
                //return expList;
            }

            if ('(' == codeArr[i])
            {
                code = code.Substring(i + 1);
                expList.expList.Add(ParseExpressionListStr(code, out remCode));
                code = remCode;
            }
        }

        remCode = "";
        return(expList);
    }
        public async Task <IMember> GetValueFromListAsync(ListExpression expression, CancellationToken cancellationToken = default)
        {
            var contents = new List <IMember>();

            foreach (var item in expression.Items)
            {
                var value = await GetValueFromExpressionAsync(item, cancellationToken) ?? UnknownType;

                contents.Add(value);
            }
            return(PythonCollectionType.CreateList(Module.Interpreter, GetLoc(expression), contents));
        }
Ejemplo n.º 21
0
 protected virtual void EmitListExpression(ListExpression expression)
 {
     AppendFormat("( ");
     for (int index = 0; index < expression.Expressions.Count; index++)
     {
         if (index > 0)
         {
             EmitListSeparator();
         }
         EmitExpression(expression.Expressions[index]);
     }
     AppendFormat(" )");
 }
Ejemplo n.º 22
0
        public void SortColumn_Property_DefaultValueByAttribute_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.SortColumn(x => x.Sortx);
            var definition = expression.SortColumnDefinition;

            definition.RequestProperty.Name.Should().Be("Sortx");
            definition.ResultProperty.Should().BeNull();
            definition.DefaultProperty.Should().BeNull();
            definition.DefaultValue.Should().Be("Text");
            definition.Name.Should().BeNull();
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Checks the statement for semantical errors
        /// </summary>
        public override void CheckStatement()
        {
            InterpretationContext context = new InterpretationContext(Root);

            Types.Collection listExpressionType = ListExpression.GetExpressionType() as Types.Collection;
            if (listExpressionType == null)
            {
                Root.AddError("Target does not references a list variable");
            }

            context.LocalScope.setVariable(IteratorVariable);
            Call.CheckStatement(context);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Provides the expression text
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string retVal = OPERATOR + " " + ListExpression.ToString();

            if (Condition != null)
            {
                retVal += " | " + Condition.ToString();
            }

            retVal = retVal + " USING " + IteratorExpression.ToString() + " INITIAL_VALUE " + InitialValue.ToString();

            return(retVal);
        }
Ejemplo n.º 25
0
        public void SortColumn_DefaultValue_Property_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.SortColumn("", x => x.DefaultTo(s => s.Text));
            var definition = expression.SortColumnDefinition;

            definition.RequestProperty.Should().BeNull();
            definition.ResultProperty.Should().BeNull();
            definition.DefaultProperty.Name.Should().Be("Text");
            definition.DefaultValue.Should().BeNull();
            definition.Name.Should().BeNull();
        }
Ejemplo n.º 26
0
 public Task <List <Model.Expression> > Handle(ListExpression message, CancellationToken cancellationToken)
 {
     return(repository
            .Query
            .Where(e => e.UserId == message.UserId)
            .Select(e => new Model.Expression()
     {
         ExpressionString = e.ExpressionString,
         Id = e.Id,
         Name = e.Name
     })
            .ToListAsync());
 }
Ejemplo n.º 27
0
        public void ConstructUsing_ServiceProvider_Succeeds()
        {
            var expression = new ListExpression <Request, Item, Result>();

            expression.ConstructUsing(sp => sp.GetRequiredService <Request>());
            var sp = new ServiceCollection().AddSingleton <Request>().BuildServiceProvider();

            expression.ModelActivatorDefinition.Method.Should().BeNull();
            expression.ModelActivatorDefinition.FactoryType.Should().BeNull();
            expression.ModelActivatorDefinition.Factory.Should().NotBeNull();

            expression.ModelActivatorDefinition.Factory(sp, typeof(Request)).Should().BeOfType <Request>();
        }
Ejemplo n.º 28
0
        public override bool VisitListExpression(ListExpression expression)
        {
            nodeStack.Push(CurrentNode.Nodes.Add("ListExpression"));
            CurrentNode.Tag = expression;

            CurrentNode.EnsureVisible();

            base.VisitListExpression(expression);

            nodeStack.Pop();

            return(true);
        }
Ejemplo n.º 29
0
        public void CreateListWithTail()
        {
            Context context = new Context();
            var list = List.MakeList(new object[] { 3, 4 });
            context.SetValue("Tail", list);
            var expr = new ListExpression(new IExpression[] { new ConstantExpression(1), new ConstantExpression(2) }, new VariableExpression(new Variable("Tail")));

            var result = expr.Evaluate(context);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(List));
            Assert.AreEqual("[1,2,3,4]", result.ToString());
        }
        private void AddNames(ListExpression list)
        {
            // only support the form of __all__ = [ ... ]
            if (list == null)
            {
                return;
            }

            foreach (var item in list.Items)
            {
                AddName(item);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        ///     Checks the statement for semantical errors
        /// </summary>
        public override void CheckStatement()
        {
            if (ListExpression != null)
            {
                if (ListExpression.Ref is Parameter)
                {
                    Root.AddError("Cannot change the list value which is a parameter (" + ListExpression + ")");
                }

                Collection targetListType = ListExpression.GetExpressionType() as Collection;
                if (targetListType != null)
                {
                    Type elementType = Value.GetExpressionType();
                    if (elementType != targetListType.Type)
                    {
                        Root.AddError("Inserted element type does not corresponds to list type");
                    }

                    if (Condition != null)
                    {
                        Condition.CheckExpression();
                        BoolType conditionType = Condition.GetExpressionType() as BoolType;
                        if (conditionType == null)
                        {
                            Root.AddError("Condition does not evaluates to boolean");
                        }
                    }
                    else
                    {
                        Root.AddError("Condition should be provided");
                    }
                }
                else
                {
                    Root.AddError("Cannot determine collection type of " + ListExpression);
                }
            }
            else
            {
                Root.AddError("List should be specified");
            }

            if (Value != null)
            {
                Value.CheckExpression();
            }
            else
            {
                Root.AddError("Value should be specified");
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        ///     Provides the surface of this function if it has been statically defined
        /// </summary>
        /// <param name="context">the context used to create the surface</param>
        /// <param name="xParam">The X axis of this surface</param>
        /// <param name="yParam">The Y axis of this surface</param>
        /// <param name="explain"></param>
        /// <returns>The surface which corresponds to this expression</returns>
        public override Surface CreateSurface(InterpretationContext context, Parameter xParam, Parameter yParam,
                                              ExplanationPart explain)
        {
            Surface retVal = base.CreateSurface(context, xParam, yParam, explain);

            Surface surface = InitialValue.CreateSurface(context, xParam, yParam, explain);

            if (surface != null)
            {
                ListValue value = ListExpression.GetValue(context, explain) as ListValue;
                if (value != null)
                {
                    int token = PrepareIteration(context);
                    AccumulatorVariable.Value = surface.Function;

                    foreach (IValue v in value.Val)
                    {
                        if (v != EfsSystem.Instance.EmptyValue)
                        {
                            // All elements should always be != from EmptyValue
                            ElementFound           = true;
                            IteratorVariable.Value = v;
                            if (ConditionSatisfied(context, explain))
                            {
                                MatchingElementFound      = true;
                                AccumulatorVariable.Value = IteratorExpression.GetValue(context, explain);
                            }
                        }
                        NextIteration();
                    }
                    Function function = AccumulatorVariable.Value as Function;
                    if (function != null)
                    {
                        retVal = function.Surface;
                    }
                    else
                    {
                        throw new Exception("Expression does not reduces to a function");
                    }
                    EndIteration(context, explain, token);
                }
            }
            else
            {
                throw new Exception("Cannot create surface for initial value " + InitialValue);
            }
            retVal.XParameter = xParam;
            retVal.YParameter = yParam;

            return(retVal);
        }
Ejemplo n.º 33
0
        public void CreateSimpleList()
        {
            Context context = new Context();
            var expr = new ListExpression(new IExpression[] { new ConstantExpression(1), new AtomExpression(new Atom("x")), new AtomExpression(new Atom("y")) });

            Assert.IsFalse(expr.HasVariable());

            var result = expr.Evaluate(context, true);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(List));

            var list = (List)result;

            Assert.IsNotNull(list.Head);
            Assert.IsNotNull(list.Tail);

            Assert.AreEqual("[1,x,y]", list.ToString());
        }
        public void GetPossibleMatchLengthsOf_List_AB_LookAhead_BB_NegativeLookAhead_AA_At_4_Returns2()
        {
            int index = 4;
             int [] lengths = {1};
             var expression =
            //            new ListExpression<char> (
            //               new LookBackExpression<char> (
                  new ListExpression<char> (
                     m_A,
                     m_B,
                     new LookAheadExpression<char> (new RepeatExpression<char>(m_B,2)),
                     new NegativeLookAheadExpression<char> (new RepeatExpression<char>(m_A,2))
                     )
            //                     ),
            //               new GreedyRepeatExpression<char> (m_any)//,
            //            )
            //               m_B)
            ;

             var possibleLengths = expression.GetPossibleMatchLengths (index).ToList ();
             Assert.AreEqual (1, possibleLengths.Count, "Count");
             Assert.AreEqual (2, possibleLengths[0], "PossibleLength[0]");
        }
        public void GetMatchesOf_LookBack_Start_GreedyAny_B_ForAAABBBReturnsAAABBB()
        {
            int index = 0;
             int [] lengths = new []{6,5,4};
             var expression =
            new ListExpression<char> (
               new LookBackExpression<char> (
                  new StartExpression<char> ()),
               new GreedyRepeatExpression<char> (m_any),
               m_B);

             var list = AAABBB;
             var matches = expression.GetMatches (list, index).ToList ();

             Assert.AreEqual (lengths.Length, matches.Count, "Count");
             for (int matchIndex = 0; matchIndex < matches.Count; matchIndex++)
             {
            var match = matches [matchIndex];
            Assert.AreEqual (index, match.Index, "match.Index");
            Assert.AreEqual (lengths[matchIndex], match.Length, "match.Length");
            Assert.IsTrue (match.Success, "match.Success");
            Assert.AreEqual (lengths[matchIndex], match.Items.Count, "match.Items.Count at");
            for (int i = 0; i < lengths[matchIndex]; i++)
            {
               Assert.AreEqual (list[index + i], match.Items [i], "match.Items [" + i + "]");
            }
             }
        }
        public void GetMatchesOf_LookBack_List_AB_LookAhead_BB_GreedyAny_B_ForAAABBBReturnsBB()
        {
            int index = 4;
             int [] lengths = {2,1};
             var expression =
            new ListExpression<char> (
               new LookBackExpression<char> (
                  new ListExpression<char> (
                     m_A,
                     m_B,
                     new LookAheadExpression<char> (new RepeatExpression<char>(m_B,2)),
                     new NegativeLookAheadExpression<char> (new RepeatExpression<char>(m_A,2))
                     )),
               new GreedyRepeatExpression<char> (m_any),
               m_B);

             var list = AAABBB;
             var matches = expression.GetMatches (list, index).ToList ();

             Assert.AreEqual (lengths.Length, matches.Count (), "Count");
             for(int matchIndex = 0; matchIndex < lengths.Length; matchIndex++)
             {
            var match = matches[matchIndex];
            Assert.AreEqual (index, match.Index, "match.Index");
            Assert.AreEqual (lengths[matchIndex], match.Length, "match.Length");
            Assert.IsTrue (match.Success, "match.Success");
            Assert.AreEqual (lengths[matchIndex], match.Items.Count, "match.Items.Count at");
            for (int i = 0; i < lengths[matchIndex]; i++)
            {
               Assert.AreEqual (list[index + i], match.Items [i], "match.Items [" + i + "]");
            }
             }
        }
        public void GetMatchesOf_LookBack_A_B_2_ForAAABBBReturnsBB()
        {
            int index = 3;
             int length = 2;
             var expression =
            new ListExpression<char> (
               new LookBackExpression<char> (m_A),
               new RepeatExpression<char> (m_B, length));

             var list = AAABBB;
             var matches = expression.GetMatches (list, index).ToList ();

             Assert.AreEqual (1, matches.Count (), "Count");
             foreach (var match in matches)
             {
            Assert.AreEqual (index, match.Index, "match.Index");
            Assert.AreEqual (length, match.Length, "match.Length");
            Assert.IsTrue (match.Success, "match.Success");
            Assert.AreEqual (length, match.Items.Count, "match.Items.Count");
            for (int i = 0; i < length; i++)
            {
               Assert.AreEqual (list[index + i], match.Items [i], "match.Items [" + i + "]");
            }
             }
        }
        public void GetMatchesOf_GreedyA_NegativeLookAhead_B_ForAAABBBReturnsA()
        {
            var expression =
            new ListExpression<char> (
               new GreedyRepeatExpression<char> (m_A),
               new NegativeLookAheadExpression<char> (m_B));

             expression.AssertMatches ("AAABBB", @"A*(?!B)");
        }
Ejemplo n.º 39
0
 // ListExpression
 public virtual bool Walk(ListExpression node) { return true; }
Ejemplo n.º 40
0
        // listmaker: expression ( list_for | (',' expression)* [','] )
        private Expression FinishListValue() {
            string proceedingWhiteSpace = _tokenWhiteSpace;

            var oStart = GetStart();
            var oEnd = GetEnd();
            int grouping = _tokenizer.GroupingLevel;

            Expression ret;
            bool ateRightBracket;
            if (MaybeEat(TokenKind.RightBracket)) {
                ret = new ListExpression();
                ateRightBracket = true;
            } else {
                bool prevAllow = _allowIncomplete;
                try {
                    _allowIncomplete = true;
                    Expression t0 = ParseExpression();
                    if (MaybeEat(TokenKind.Comma)) {
                        string commaWhiteSpace = _tokenWhiteSpace;
                        bool trailingComma;
                        List<string> listWhiteSpace;
                        var l = ParseTestListAsExpr(t0, out listWhiteSpace, out trailingComma);
                        ateRightBracket = Eat(TokenKind.RightBracket);
                        
                        ret = new ListExpression(l.ToArray());
                        
                        if (listWhiteSpace != null) {                            
                            AddListWhiteSpace(ret, listWhiteSpace.ToArray());
                        }
                    } else if (PeekToken(Tokens.KeywordForToken)) {
                        ret = FinishListComp(t0, out ateRightBracket);
                    } else {
                        ateRightBracket = Eat(TokenKind.RightBracket);
                        ret = new ListExpression(t0);
                    }
                } finally {
                    _allowIncomplete = prevAllow;
                }
            }

            if (_verbatim) {
                AddPreceedingWhiteSpace(ret, proceedingWhiteSpace);
                AddSecondPreceedingWhiteSpace(ret, _tokenWhiteSpace);
                if (!ateRightBracket) {
                    AddErrorMissingCloseGrouping(ret);
                }
            }

            var cStart = GetStart();
            var cEnd = GetEnd();

            ret.SetLoc(oStart, cEnd);
            return ret;
        }
Ejemplo n.º 41
0
 public override void PostWalk(ListExpression node) { PostWalkWorker(node); }
Ejemplo n.º 42
0
 // ListExpression
 public override bool Walk(ListExpression node) { return ShouldWalkWorker(node); }
Ejemplo n.º 43
0
 public void SupportsLookBack_For_LookBackSupported()
 {
     var expression = new ListExpression<char> (LookBackSupported);
      Assert.IsTrue (expression.SupportsLookBack);
 }
Ejemplo n.º 44
0
 public void AnyLength_For_AnyLength_NotAnyLength()
 {
     var expression = new ListExpression<char> (AnyLength, NotAnyLength);
      Assert.IsTrue (expression.AnyLength);
 }
Ejemplo n.º 45
0
        private IExpression ParseTerm()
        {
            Token token = this.NextToken();
            IExpression expression = null;

            if (token == null)
                return null;

            if (token.Type == TokenType.Variable)
            {
                expression = new VariableExpression(new Variable(token.Value));

                if (this.TryParseToken(TokenType.Separator, "("))
                {
                    var list = this.ParseExpressionList();
                    this.ParseToken(TokenType.Separator, ")");
                    expression = new CallExpression(expression, list);
                }
            }
            else if (token.Type == TokenType.Atom)
            {
                if (token.Value == "false")
                    return new ConstantExpression(false);
                if (token.Value == "true")
                    return new ConstantExpression(true);

                if (token.Value == "fun")
                    return this.ParseFunExpression();

                if (token.Value == "receive")
                    return this.ParseReceiveExpression();

                expression = new AtomExpression(new Atom(token.Value));

                if (this.TryParseToken(TokenType.Separator, "("))
                {
                    var list = this.ParseExpressionList();
                    this.ParseToken(TokenType.Separator, ")");
                    expression = new CallExpression(expression, list);
                }
                else if (this.TryParseToken(TokenType.Separator, ":"))
                {
                    var nexpression = new AtomExpression(new Atom(this.ParseAtom()));
                    this.ParseToken(TokenType.Separator, "(");
                    var list = this.ParseExpressionList();
                    this.ParseToken(TokenType.Separator, ")");
                    expression = new QualifiedCallExpression(expression, nexpression, list);
                }
            }
            else if (token.Type == TokenType.Integer)
                expression = new ConstantExpression(int.Parse(token.Value, CultureInfo.InvariantCulture));
            else if (token.Type == TokenType.Real)
                expression = new ConstantExpression(double.Parse(token.Value, CultureInfo.InvariantCulture));
            else if (token.Type == TokenType.String)
                expression = new ConstantExpression(token.Value);
            else if (token.Type == TokenType.Separator && token.Value == "(")
            {
                expression = this.ParseSimpleExpression();
                this.ParseToken(TokenType.Separator, ")");
            }
            else if (token.Type == TokenType.Separator && token.Value == "{")
            {
                var expressions = this.ParseExpressionList();
                this.ParseToken(TokenType.Separator, "}");
                expression = new TupleExpression(expressions);
            }
            else if (token.Type == TokenType.Separator && token.Value == "[")
            {
                var expressions = this.ParseExpressionList();
                IExpression tailexpression = null;

                if (this.TryParseToken(TokenType.Separator, "|"))
                    tailexpression = this.ParseSimpleExpression();

                this.ParseToken(TokenType.Separator, "]");
                expression = new ListExpression(expressions, tailexpression);
            }
            else
                this.PushToken(token);

            return expression;
        }
Ejemplo n.º 46
0
 public override bool Walk(ListExpression node) {
     return UpdateLineInfo(node, true);
 }
Ejemplo n.º 47
0
 // ListExpression
 public override bool Walk(ListExpression node) { return Location >= node.StartIndex && Location <= node.EndIndex; }
Ejemplo n.º 48
0
        public void RaiseWhenUnboundVariable()
        {
            Context context = new Context();
            var expr = new ListExpression(new IExpression[] { new ConstantExpression(1), new VariableExpression(new Variable("X")), new AtomExpression(new Atom("y")) });

            Assert.IsTrue(expr.HasVariable());

            try
            {
                expr.Evaluate(context, false);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.AreEqual("variable 'X' is unbound", ex.Message);
            }
        }
        public void GetMatchesOf_A_3_BForAAABBB_GetEnumerator_MoveNextTooManyTimesThrows()
        {
            int index = 0;
             var expression =
            new ListExpression<char> (
               new RepeatExpression<char> (m_A, 3),
               m_B);

             var list = AAABBB;
             var matches = expression.GetMatches (list, index).ToList ();
             var enumerator = matches.GetEnumerator ();
             var current = enumerator.Current;
             Assert.IsNull (current, "current");
             for (int i = 0; i < 100; i++)
             {
            enumerator.MoveNext ();
             }
        }
        public void GetMatchesOf_GreedyA_NegativeLookAheadBx3_ForAAABBBReturnsAA()
        {
            //string [] expectedValues = new [] {"AA", "A", ""};
             //int index = 0;
             var expression =
            new ListExpression<char> (
               new GreedyRepeatExpression<char> (m_A),
               new NegativeLookAheadExpression<char> (
                  new RepeatExpression<char> (m_B, 3)));

             expression.AssertMatches ("AAABBB", @"A*(?!B{3})");
             //var list = AAABBB;
             //var matches = expression.GetMatches (list, index).ToList ();

             //Assert.AreEqual (expectedValues.Length, matches.Count (), "Count");
             //for (int i = 0; i < matches.Count; i++)
             //{
             //   var match = matches[i];
             //   int length = expectedValues[i].Length;
             //   Assert.AreEqual (index, match.Index, "match.Index");
             //   Assert.AreEqual (length, match.Length, "match.Length");
             //   Assert.IsTrue (match.Success, "match.Success");
             //   Assert.AreEqual (expectedValues[i], new string (match.Items.ToArray()), "match.Items.Count at");
             //}
        }
Ejemplo n.º 51
0
 public void ConstructorSucceedsForNonNullInput()
 {
     var expression = new ListExpression<char> (m_a, m_any);
 }
Ejemplo n.º 52
0
 // ListExpression
 public override bool Walk(ListExpression node) { return false; }
        public void GetMatchesOf_A_3_BForAAABBBReturnsAAAB()
        {
            int index = 0;
             int length = 4;
             var expression =
            new ListExpression<char> (
               new GreedyRepeatExpression<char> (m_A, 3),
               m_B);

             var list = AAABBB;
             var matches = expression.GetMatches (list, index).ToList ();

             Assert.AreEqual (1, matches.Count (), "Count");
             foreach (var match in matches)
             {
            Assert.AreEqual (index, match.Index, "match.Index");
            Assert.AreEqual (length, match.Length, "match.Length");
            Assert.IsTrue (match.Success, "match.Success");
            Assert.AreEqual (length, match.Items.Count, "match.Items.Count at");
            for (int i = 0; i < length; i++)
            {
               Assert.AreEqual (list[index + i], match.Items [i], "match.Items [" + i + "]");
            }
             }
        }
Ejemplo n.º 54
0
 public void ConstructorThrowArgumentNullExceptionForFirst()
 {
     var expression = new ListExpression<char> ((IExpression<char>) null, m_a);
 }
Ejemplo n.º 55
0
 public override bool Walk(ListExpression node) {
     return WalkCollection(node, node.Items);
 }
Ejemplo n.º 56
0
 public void ConstructorThrowArgumentNullExceptionForSecond()
 {
     var expression = new ListExpression<char> (m_a, (IExpression<char>) null);
 }
Ejemplo n.º 57
0
 public override void PostWalk(ListExpression node) { }
Ejemplo n.º 58
0
 public override bool Walk(ListExpression node) {
     AddTagIfNecessary(node);
     return base.Walk(node);
 }
Ejemplo n.º 59
0
 public virtual void PostWalk(ListExpression node) { }
Ejemplo n.º 60
0
        public void RaiseIfUnboundVariableAsTail()
        {
            Context context = new Context();
            var expr = new ListExpression(new IExpression[] { new ConstantExpression(1), new ConstantExpression(2) }, new VariableExpression(new Variable("Tail")));

            try
            {
                expr.Evaluate(context, false);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.AreEqual("variable 'Tail' is unbound", ex.Message);
            }
        }