public string ReplaceVariables(MatchExpression expression, Dictionary <string, string> replaces)
        {
            var input    = new StringBuilder(expression.Expression);
            var padIndex = 0;

            foreach (var match in expression.Matches)
            {
                var replace = replaces[match.Value];

                if (replace == null)
                {
                    continue;
                }

                var calculatedIndex = match.Index + padIndex;
                input.Remove(calculatedIndex, match.Length);
                input.Insert(calculatedIndex, replace);

                if (match.Length != replace.Length)
                {
                    padIndex += replace.Length - match.Length;
                }
            }

            return(input.ToString());
        }
Exemple #2
0
        private void regexColorRowGrid1_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            if (e.ColumnIndex == _expressionIndex)
            {
                var grid      = (DataGridView)sender;
                var row       = _bindingList[e.RowIndex];
                var foreColor = Color.Black;

                // If the MatchExpression is null, parsing failed, so we create a default expression where
                // the regular expression is the Expression that failed to parse and the matchOptions are default ones (see GetDefaultMatchExpression)
                if (row.MatchExpression == null)
                {
                    if (!row.InvalidMatchOptions && MatchExpression.IsRegexValid(row.Expression))
                    {
                        row.Expression = GetDefaultMatchExpression(row.Expression).ToString();
                    }
                    else
                    {
                        foreColor = Color.Red;
                    }
                }

                grid[e.ColumnIndex, e.RowIndex].Style.ForeColor = foreColor;
            }
        }
Exemple #3
0
 private void Init(MatchExpression matchExpression, List <string> whereToSearch, Room roomToLeave)
 {
     this.matchExpression = matchExpression;
     whereToSearchString  = whereToSearch;
     this.roomToLeave     = roomToLeave;
     isSearchListString   = true;
 }
        public override void Accept(MatchExpression match)
        {
            AstNode value = match.Children [0];

            value.Visit(this);
            int temporary = methodBuilder.CreateTemporary();

            methodBuilder.EmitInstruction(match.Location, Opcode.StoreLocal, temporary);
            PatternCompiler compiler = new PatternCompiler(symbolTable, methodBuilder,
                                                           temporary,
                                                           this);
            IodineLabel nextLabel = methodBuilder.CreateLabel();
            IodineLabel endLabel  = methodBuilder.CreateLabel();

            for (int i = 1; i < match.Children.Count; i++)
            {
                if (i > 1)
                {
                    methodBuilder.MarkLabelPosition(nextLabel);
                    nextLabel = methodBuilder.CreateLabel();
                }
                CaseExpression clause = match.Children [i] as CaseExpression;
                clause.Pattern.Visit(compiler);
                methodBuilder.EmitInstruction(match.Location, Opcode.JumpIfFalse, nextLabel);
                if (clause.Condition != null)
                {
                    clause.Condition.Visit(this);
                    methodBuilder.EmitInstruction(match.Location, Opcode.JumpIfFalse, nextLabel);
                }
                clause.Value.Visit(this);
                methodBuilder.EmitInstruction(match.Location, Opcode.Jump, endLabel);
            }
            methodBuilder.MarkLabelPosition(endLabel);
        }
Exemple #5
0
        private IExpression ParseMatchExpression()
        {
            IExpression expression = this.ParseSimpleExpression();

            Token token = this.NextToken();

            if (expression == null)
            {
                if (token == null)
                {
                    return(null);
                }
                else
                {
                    throw new ParserException(string.Format("Unexpected '{0}'", token.Value));
                }
            }

            if (token != null && token.Type == TokenType.Operator && token.Value == "=")
            {
                expression = new MatchExpression(expression, this.ParseSimpleExpression());
                return(expression);
            }
            else if (token != null && token.Type == TokenType.Operator && token.Value == "!")
            {
                expression = new SendExpression(expression, this.ParseSimpleExpression());
                return(expression);
            }
            else
            {
                this.PushToken(token);
            }

            return(expression);
        }
        private void UpdateGrid(MatchExpression validForExpr)
        {
            if (!_allowUpdateGrid)
            {
                return;
            }

            var expr = GetCurrentMatchExpression();

            if (!Equals(expr, validForExpr))
            {
                return;
            }

            bindingSource1.DataSource   = null;
            expressionTextBox.ForeColor = Color.Black;

            if (!expr.IsRegexValid())
            {
                expressionTextBox.ForeColor = Color.Red;
                return;
            }

            if (_filteredRows != null)
            {
                bindingSource1.DataSource = new BindingList <StringWrapper>(_filteredRows);
                _filteredRows             = null;
            }
            else
            {
                bindingSource1.DataSource = new BindingList <StringWrapper>(_foldChangeRows.Select(row =>
                                                                                                   RowToString(expr, row)).ToArray());
            }
        }
Exemple #7
0
 public MatchExprInfo(MatchExpression matchExpression, VolcanoPlotPointsInfo expectedPointsInfo, List <string> expectedMatches, bool perProtein)
 {
     MatchExpression    = matchExpression;
     ExpectedPointsInfo = expectedPointsInfo;
     ExpectedMatches    = expectedMatches;
     PerProtein         = perProtein;
 }
Exemple #8
0
        public void HasVariablesWithVariable()
        {
            Variable        variable = new Variable("X");
            MatchExpression expr     = new MatchExpression(new VariableExpression(variable), new ConstantExpression(123));

            Assert.IsTrue(expr.HasVariable());
        }
        /// <summary>
        /// Visit match expression
        /// </summary>
        /// <param name="matchExpression"></param>
        /// <returns></returns>
        public Expression VisitMatch([NotNull] MatchExpression expression)
        {
            Check.NotNull(expression, nameof(expression));

            var optional = expression.Optional
                ? "OPTIONAL "
                : String.Empty;

            _commandBuilder
            .Append($"{optional}MATCH ");
            Visit(expression.Pattern);

            if (!(expression.Where is null))
            {
                // TODO: optimize where

                _commandBuilder
                .AppendLine()
                .Append("WHERE ");

                Visit(expression.Where);
            }

            return(expression);
        }
Exemple #10
0
 private void Init(MatchExpression matchExpression, List <Room> whereToSearch, Room roomToLeave)
 {
     this.matchExpression = matchExpression;
     whereToSearchRoom    = whereToSearch;
     this.roomToLeave     = roomToLeave;
     isSearchListRoom     = true;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="GenericMatcher{T}"/> class.
        /// </summary>
        /// <param name="matchExpression">The test that is performed to check if the value matches expectation.</param>
        /// <exception cref="ArgumentNullException"><c>matchExpression</c> is null.</exception>
        public GenericMatcher(MatchExpression matchExpression)
            : base("generic match")
        {
            if (matchExpression == null)
            {
                throw new ArgumentNullException("matchExpression", "matchExpression must not be null.");
            }

            this.matchExpression = matchExpression;
        }
Exemple #12
0
        public void MatchVariableWithInteger()
        {
            Context         context  = new Context();
            Variable        variable = new Variable("X");
            MatchExpression expr     = new MatchExpression(new VariableExpression(variable), new ConstantExpression(123));

            Assert.AreEqual(123, expr.Evaluate(context));

            Assert.AreEqual(123, context.GetValue("X"));
        }
        /// <summary>
        /// Single selection.
        /// </summary>
        /// <returns></returns>
        public ItemType SelectScalar <ItemType>(MatchExpression matchExpression)
            where ItemType : class, IDBPersistent, new()
        {
            List <ItemType> results = Select <ItemType>(matchExpression, 1);

            if (results.Count > 0)
            {
                return(results[0]);
            }
            return(null);
        }
        /// <summary>
        /// Single selection.
        /// </summary>
        /// <returns></returns>
        public bool SelectScalar <ItemType>(ItemType item, MatchExpression matchExpression)
            where ItemType : class, IDBPersistent
        {
            DataSet set = Select(new string[] { GetTypeTableName(typeof(ItemType)) }, matchExpression, 1);

            if (set != null && set.Tables.Count > 0 && set.Tables[0].Rows.Count > 0)
            {
                return(UpdateItemValues <ItemType>(item, GetTypePersistableProperties(typeof(ItemType), true, true, true), set.Tables[0].Rows[0]));
            }
            return(false);
        }
        /// <summary>
        /// Evaluates a set of claims using the authorization operation.
        /// </summary>
        /// <param name="claimSet">The set of claims to be evaluated.</param>
        /// <returns>True if the set of claims evaluates to true; otherwise false.</returns>
        public override bool Evaluate(IEnumerable <Claim> claims)
        {
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            IList <Claim> list = null;

            Capl.Authorization.Operations.Operation operation = null;
            MatchExpression exp = Capl.Authorization.Matching.MatchExpression.Create(this.MatchExpression.Type, null);

            list = exp.MatchClaims(claims, this.MatchExpression.ClaimType, this.MatchExpression.Value);

            if (list.Count == 0)
            {
                return(!this.MatchExpression.Required);
            }

            if (this.Issuer != null)
            {
                int count = list.Count;
                for (int index = 0; index < count; index++)
                {
                    if (list[index].Issuer != this.Issuer)
                    {
                        list.Remove(list[index]);
                        index--;
                        count--;
                    }
                }
            }

            operation = Capl.Authorization.Operations.Operation.Create(this.Operation.Type, null);

            foreach (Claim claim in list)
            {
                bool eval = operation.Execute(claim.Value, this.Operation.ClaimValue);

                if (this.Evaluates && eval)
                {
                    return(true);
                }

                if (!this.Evaluates && eval)
                {
                    return(false);
                }
            }

            return(!this.Evaluates);
        }
        /// <summary>
        /// This will create object instances based on the type column names. All instances types must be child
        /// types to the BaseItemType.
        /// This is useful to store multiple types with same base type in a single table.
        /// </summary>
        public List <ItemBaseType> SelectDynamicType <ItemBaseType>(MatchExpression matchExpression,
                                                                    string assemblyQualifiedTypeColumnName, int?limit)
            where ItemBaseType : class, IDBPersistent
        {
            List <ItemBaseType> results = new List <ItemBaseType>();

            string tableName          = _tablesTypeNames[typeof(ItemBaseType)];
            List <PropertyInfo> infos = this.GetTypePersistableProperties(typeof(ItemBaseType), true, true, true);
            DataSet             set   = Select(new string[] { tableName }, matchExpression, limit);

            foreach (DataRow row in set.Tables[0].Rows)
            {
                string typeName = (string)row[assemblyQualifiedTypeColumnName];
                if (string.IsNullOrEmpty(typeName))
                {
                    SystemMonitor.Error("Type name column not found.");
                    return(null);
                }

                ItemBaseType item = null;
                Type         type = Type.GetType(typeName);
                if (type == null)
                {
                    SystemMonitor.Error("Type provided was not found.");
                    return(null);
                }

                if (type.IsSubclassOf(typeof(ItemBaseType)) == false &&
                    type.GetInterface(typeof(ItemBaseType).Name) == null)
                {
                    SystemMonitor.Error("Base type not corresponding.");
                    return(null);
                }

                ConstructorInfo constructor = type.GetConstructor(new Type[] { });
                if (constructor == null)
                {
                    SystemMonitor.Error("Type parameterless constructor not found.");
                    return(null);
                }

                item = (ItemBaseType)constructor.Invoke(null);

                if (UpdateItemValues(item, infos, row))
                {
                    results.Add(item);
                }
            }

            return(results);
        }
Exemple #17
0
        public void NoMatchWithException()
        {
            MatchExpression expr = new MatchExpression(new ConstantExpression(123), new ConstantExpression("foo"));

            try
            {
                expr.Evaluate(null);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
                Assert.AreEqual("no match of right hand side value foo", ex.Message);
            }
        }
Exemple #18
0
 public void AssertCorrect()
 {
     try
     {
         var parsed = MatchExpression.Parse(Expression);
         Assert.AreEqual(Expected.RegExpr, parsed.RegExpr);
         CollectionAssert.AreEqual(Expected.matchOptions, parsed.matchOptions);
     }
     catch (Exception ex)
     {
         if (ExceptionType == null || ExceptionType != ex.GetType())
         {
             Assert.Fail();
         }
     }
 }
Exemple #19
0
        public void ParseSimpleMatch()
        {
            Parser parser = new Parser("X=ok.");

            IExpression expression = parser.ParseExpression();

            Assert.IsNotNull(expression);
            Assert.IsInstanceOfType(expression, typeof(MatchExpression));

            MatchExpression matchexpression = (MatchExpression)expression;

            Assert.IsNotNull(matchexpression.LeftExpression);
            Assert.IsNotNull(matchexpression.RightExpression);

            Assert.IsNull(parser.ParseExpression());
        }
Exemple #20
0
        public override void Accept(MatchExpression match)
        {
            bool hasCatchall     = false;
            bool hasTruePattern  = false;
            bool hasFalsePattern = false;

            foreach (AstNode node in match.MatchCases)
            {
                var matchCase = node as CaseExpression;


                if (matchCase != null)
                {
                    var nameExpr = matchCase.Pattern as NameExpression;

                    if (nameExpr != null && nameExpr.Value == "_")
                    {
                        hasCatchall = true;
                    }

                    var trueExpr = matchCase.Pattern as TrueExpression;

                    if (trueExpr != null)
                    {
                        hasTruePattern = true;
                    }

                    var falseExpr = matchCase.Pattern as FalseExpression;


                    if (falseExpr != null)
                    {
                        hasFalsePattern = true;
                    }
                }
            }

            bool isLegal = hasCatchall || (hasTruePattern && hasFalsePattern);

            if (!isLegal)
            {
                errorLog.Add(Errors.MatchDoesNotAccountForAllConditions,
                             match.Location);
            }

            base.Accept(match);
        }
Exemple #21
0
        /// <summary>
        ///     Evaluates a set of claims using the authorization operation.
        /// </summary>
        /// <param name="claimSet">The set of claims to be evaluated.</param>
        /// <returns>True if the set of claims evaluates to true; otherwise false.</returns>
        public override bool Evaluate(IEnumerable <Claim> claims)
        {
            _ = claims ?? throw new ArgumentNullException(nameof(claims));

            MatchExpression exp = Matching.MatchExpression.Create(MatchExpression.Type, null);

            IList <Claim> list = exp.MatchClaims(claims, MatchExpression.ClaimType, MatchExpression.Value);

            if (list.Count == 0)
            {
                return(!MatchExpression.Required);
            }

            if (Issuer != null)
            {
                int count = list.Count;
                for (int index = 0; index < count; index++)
                {
                    if (list[index].Issuer != Issuer)
                    {
                        list.Remove(list[index]);
                        index--;
                        count--;
                    }
                }
            }

            Operation operation = Operations.Operation.Create(Operation.Type, null);

            foreach (Claim claim in list)
            {
                bool eval = operation.Execute(claim.Value, Operation.ClaimValue);

                if (Evaluates && eval)
                {
                    return(true);
                }

                if (!Evaluates && eval)
                {
                    return(false);
                }
            }

            return(!Evaluates);
        }
        /// <summary>
        ///
        /// </summary>
        public long Count <ItemType>(MatchExpression matchExpression)
            where ItemType : class, IDBPersistent
        {
            TracerHelper.TraceEntry(typeof(ItemType).Name);

            string tableName = _tablesTypeNames[typeof(ItemType)];

            StringBuilder commandText = new StringBuilder();

            commandText.Append("SELECT count(*) FROM " + tableName);

            if (matchExpression != null && matchExpression.ClauseCount > 0)
            {
                commandText.Append(" WHERE ");
            }

            _countMutex.WaitOne();
            SQLiteCommand command;
            long          result = 0;

            try
            {
                using (SQLiteConnection connection = GenerateConnection())
                {
                    using (command = new SQLiteCommand(connection))
                    {
                        if (matchExpression != null)
                        {
                            matchExpression.SetupCommandParameters(command, commandText);
                        }

                        command.CommandText = commandText.ToString();

                        connection.Open();
                        result = (long)command.ExecuteScalar();
                    }
                }
            }
            finally
            {
                _countMutex.ReleaseMutex();
            }

            TracerHelper.TraceExit();
            return(result);
        }
Exemple #23
0
        public void RaiseIfMatchVariableInTupleWithTwoDifferentValues()
        {
            Context  context = new Context();
            Variable x       = new Variable("X");

            MatchExpression expr = new MatchExpression(new TupleExpression(new IExpression[] { new VariableExpression(x), new VariableExpression(x) }), new TupleExpression(new IExpression[] { new ConstantExpression(1), new ConstantExpression(2) }));

            try
            {
                expr.Evaluate(context);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
                Assert.AreEqual("no match of right hand side value {1,2}", ex.Message);
            }
        }
Exemple #24
0
        public void ParseMatchVariableWithInteger()
        {
            Parser parser = new Parser("X=1.");

            IExpression expression = parser.ParseExpression();

            Assert.IsNotNull(expression);
            Assert.IsInstanceOfType(expression, typeof(MatchExpression));

            MatchExpression matchexpression = (MatchExpression)expression;

            Assert.IsNotNull(matchexpression.LeftExpression);
            Assert.IsInstanceOfType(matchexpression.LeftExpression, typeof(VariableExpression));
            Assert.IsNotNull(matchexpression.RightExpression);
            Assert.IsInstanceOfType(matchexpression.RightExpression, typeof(ConstantExpression));

            Assert.IsNull(parser.ParseExpression());
        }
Exemple #25
0
        public void MatchVariablesInTupleWithConcreteTuple()
        {
            Context  context = new Context();
            Variable x       = new Variable("X");
            Variable y       = new Variable("Y");

            MatchExpression expr = new MatchExpression(new TupleExpression(new IExpression[] { new VariableExpression(x), new VariableExpression(y) }), new TupleExpression(new IExpression[] { new ConstantExpression(1), new ConstantExpression(2) }));

            expr.Evaluate(context);

            var result1 = context.GetValue("X");
            var result2 = context.GetValue("Y");

            Assert.IsNotNull(result1);
            Assert.AreEqual(1, result1);
            Assert.IsNotNull(result2);
            Assert.AreEqual(2, result2);
        }
        public void simple_match_expression()
        {
            var target = new MatchExpression
                {
                    new GuardNode
                        {
                            Test = new[] {new BoolLiteral(true),},
                            Result = new BoolLiteral(true)
                        },
                    new GuardNode
                        {
                            Test = new[] {new BoolLiteral(false),},
                            Result = new BoolLiteral(false)
                        }
                };
            target.Match = new[] {new BoolLiteral(true),};

            Mother.Test(target.Compile(Mother.CreateRuntime()), true);
        }
Exemple #27
0
        public void RaiseIfMatchBoundVariableWithInteger()
        {
            Context  context  = new Context();
            Variable variable = new Variable("X");

            context.SetValue("X", 1);
            MatchExpression expr = new MatchExpression(new VariableExpression(variable), new ConstantExpression(123));

            try
            {
                expr.Evaluate(context);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
                Assert.AreEqual("no match of right hand side value 123", ex.Message);
            }
        }
Exemple #28
0
        /// <summary>
        /// Executes the transform.
        /// </summary>
        /// <param name="claimSet">Input set of claims to transform.</param>
        /// <returns>Transformed set of claims.</returns>
        public override IEnumerable <Claim> TransformClaims(IEnumerable <Claim> claims)
        {
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            TransformAction     action            = null;
            IList <Claim>       matchedClaims     = null;
            IEnumerable <Claim> transformedClaims = null;
            bool eval = false;

            action = TransformAction.Create(this.Type, null);

            if (this.MatchExpression != null)
            {
                MatchExpression matcher = MatchExpressionDictionary.Default[this.MatchExpression.Type.ToString()]; //CaplConfigurationManager.MatchExpressions[this.MatchExpression.Type.ToString()];
                matchedClaims = matcher.MatchClaims(claims, this.MatchExpression.ClaimType, this.MatchExpression.Value);
            }

            if (this.Expression == null)
            {
                eval = true;
            }
            else
            {
                eval = this.Expression.Evaluate(claims);
            }

            if (eval)
            {
                transformedClaims = action.Execute(claims, matchedClaims, this.TargetClaim);
            }

            if (transformedClaims != null)
            {
                return(transformedClaims);
            }
            else
            {
                return(claims);
            }
        }
        /// <summary>
        /// Extract type instances from storage, matching the provided criterias.
        /// </summary>
        /// <typeparam name="ItemType"></typeparam>
        /// <param name="matchExpression">Pass null to include all items in select.</param>
        /// <param name="limit">Pass null to specify no limit.</param>
        /// <returns></returns>
        public List <ItemType> Select <ItemType>(MatchExpression matchExpression, int?limit)
            where ItemType : class, IDBPersistent, new()
        {
            List <ItemType> results = new List <ItemType>();

            string tableName          = _tablesTypeNames[typeof(ItemType)];
            List <PropertyInfo> infos = this.GetTypePersistableProperties(typeof(ItemType), true, true, true);
            DataSet             set   = Select(new string[] { tableName }, matchExpression, limit);

            foreach (DataRow row in set.Tables[0].Rows)
            {
                ItemType item = new ItemType();
                if (UpdateItemValues(item, infos, row))
                {
                    results.Add(item);
                }
            }

            return(results);
        }
        public void simple_match_expression()
        {
            var target = new MatchExpression
            {
                new GuardNode
                {
                    Test   = new[] { new BoolLiteral(true), },
                    Result = new BoolLiteral(true)
                },
                new GuardNode
                {
                    Test   = new[] { new BoolLiteral(false), },
                    Result = new BoolLiteral(false)
                }
            };

            target.Match = new[] { new BoolLiteral(true), };

            Mother.Test(target.Compile(Mother.CreateRuntime()), true);
        }
Exemple #31
0
        // ReSharper restore PossibleMultipleEnumeration

        private static TextObj CreateLabel(PointPair point, Color color, float size)
        {
            var row = point.Tag as FoldChangeBindingSource.FoldChangeRow;

            if (row == null)
            {
                return(null);
            }

            var text = MatchExpression.GetRowDisplayText(row.Protein, row.Peptide);

            var textObj = new TextObj(text, point.X, point.Y, CoordType.AxisXYScale, AlignH.Center, AlignV.Bottom)
            {
                IsClippedToChartRect = true,
                FontSpec             = CreateFontSpec(color, size),
                ZOrder = ZOrder.A_InFront
            };

            return(textObj);
        }