Esempio n. 1
0
        public void TestIntegerEqual()
        {
            var gen  = new VariableGenerator();
            var i1   = gen.GenerateInt(1, 9);
            var i2   = gen.GenerateInt(1, 9);
            var expr = i1.EqualCondition(i2);

            Assert.Equal(9, expr.children.Count);
            CheckType <ExpressionOr> (expr);

            foreach (var child in expr.children)
            {
                Assert.Equal(18, child.children.Count);
                CheckType <ExpressionAnd> (child);
                int count = 0;
                foreach (var child2 in child.children)
                {
                    CheckType <ExpressionInteger> (child2);
                    var ins = (ExpressionInteger)child2;
                    if (ins.positive)
                    {
                        count++;
                    }
                }
                Assert.Equal(2, count);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Method to fetch fields which are of OBJECT primitive type.
        /// </summary>
        /// <param name="variableList">
        /// @return </param>
        //JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
        //ORIGINAL LINE: private static java.util.ArrayList<? extends edu.uta.cse.proggen.classLevelElements.Field> getObjects(java.util.ArrayList<? extends edu.uta.cse.proggen.classLevelElements.Field> variableList)
        //JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
        //ORIGINAL LINE: private static java.util.ArrayList<? extends edu.uta.cse.proggen.classLevelElements.Field> getObjects(java.util.ArrayList<? extends edu.uta.cse.proggen.classLevelElements.Field> variableList)
        //static void Cat<T> (IList<T> sources)



        //Veena : Again unreachable Code.
        // THis is if Objects are being created. Since we are not doing inheritence/Objects, it's Unreacheble.
        //So dont waste time converting it. Get a Life :P
        //private static List<T> getObjects(List<T> variableList) where ? : edu.uta.cse.proggen.classLevelElements.Field where T1 : edu.uta.cse.proggen.classLevelElements.Field
        //{
        //    List<Field> objList = new List<Field>();

        //    foreach (Field @var in variableList)
        //    {
        //        if (@var.Type.Type == Type.Primitives.OBJECT)
        //        {
        //            objList.Add(@var);
        //        }
        //    }
        //    return objList;
        //}

        private static string getParametersForList(List <Variable> parameterList, Method method)
        {
            string parameters = "";

            foreach (Variable @var in parameterList)
            {
                if (@var.Name.Equals("recursionCounter"))
                {
                    parameters += "recursionCounter,";
                    continue;
                }

                Operand         operand;
                Type.Primitives primitive             = @var.Type.getType();//.Type.Type;
                int             optionVariableOrField = (new Random()).Next(1);
                if (optionVariableOrField == 0)
                {
                    operand = VariableGenerator.getRandomizedVariable(method, primitive);
                }
                else
                {
                    operand = FieldGenerator.getRandomField(method.AssociatedClass, primitive, method.Static);
                }
                parameters += operand + ",";
            }
            parameters = parameters.Substring(0, parameters.Length - 1);
            return(parameters);
        }
Esempio n. 3
0
        public override void OnBeforeFromClauseVisited(Expression expression)
        {
            base.OnBeforeFromClauseVisited(expression);

            // TODO: Move into OnBeforeSelectClauseVisited.
            if (expression is ConstantExpression)
            {
                ConstantExpression constantExpression = expression as ConstantExpression;

                IQueryable queryable = constantExpression.Value as IQueryable;

                if (queryable != null && typeof(Resource).IsAssignableFrom(queryable.ElementType))
                {
                    SparqlVariable s = VariableGenerator.GlobalSubject;

                    SetSubjectVariable(s);

                    VariableGenerator.SetSubjectVariable(expression, s);
                }
                else
                {
                    throw new NotSupportedException(constantExpression.Value.GetType().ToString());
                }
            }
            else
            {
                // TODO: Create unit test for QuerySourceReferenceExpression, SubQueryExpression
                throw new NotImplementedException(expression.GetType().ToString());
            }
        }
Esempio n. 4
0
        public void FilterNotRegex(MemberExpression expression, string pattern, bool ignoreCase)
        {
            SparqlVariable s = VariableGenerator.TryGetSubjectVariable(expression) ?? SubjectVariable;
            SparqlVariable o = VariableGenerator.TryGetObjectVariable(expression) ?? VariableGenerator.CreateObjectVariable(expression);

            BuildMemberAccess(expression);

            FilterNotRegex(o, pattern, ignoreCase);
        }
Esempio n. 5
0
        public void TestInteger()
        {
            var gen = new VariableGenerator();
            var i1  = gen.GenerateInt(1, 3);
            var i2  = gen.GenerateInt(1, 3);
            var i3  = gen.GenerateId();

            Assert.Equal(6, i3);
        }
Esempio n. 6
0
 /// <summary>
 /// A list with all the generators
 /// </summary>
 /// <param name="context">The context</param>
 public AllGenerators(WalkerContext context)
 {
     AddAssignment              = new AssignmentGenerator(context, AssignmentType.Add);
     AddressOfExpression        = new AddressOfExpressionGenerator(context);
     ArgumentList               = new ArgumentListGenerator(context);
     ArrayCreationExpression    = new ArrayCreationExpressionGenerator(context);
     ArrayInitializerExpression = new ArrayInitializerGenerator(context);
     BinaryAndAssignment        = new AssignmentGenerator(context, AssignmentType.BinaryAnd);
     BinaryOrAssignment         = new AssignmentGenerator(context, AssignmentType.BinaryOr);
     Block          = new BlockGenerator(context);
     CastExpression = new CastExpressionGenerator(context);
     ConditionalAccessExpression = new ConditionalAccessExpressionGenerator(context);
     ClassCode           = new ClassCodeGenerator(context);
     DelegateDeclaration = new DelegateDeclarationGenerator(context);
     DoStatement         = new DoStatementGenerator(context);
     DivideAssignment    = new AssignmentGenerator(context, AssignmentType.Divide);
     ElementAccess       = new ElementAccessGenerator(context);
     Enum = new EnumGenerator(context);
     ExclusiveOrAssignment         = new AssignmentGenerator(context, AssignmentType.ExclusiveOr);
     Expression                    = new ExpressionGenerator(context);
     ExpressionStatement           = new ExpressionStatementGenerator(context);
     FixedStatement                = new FixedStatementGenerator(context);
     ForStatement                  = new ForStatementGenerator(context);
     GotoStatement                 = new GotoStatementGenerator(context);
     IfStatement                   = new IfStatementGenerator(context);
     Invocation                    = new InvocationGenerator(context);
     Interface                     = new InterfaceGenerator(context);
     IdentifierName                = new IdentifierNameGenerator(context);
     LabeledStatement              = new LabeledStatementGenerator(context);
     LeftShiftAssignment           = new AssignmentGenerator(context, AssignmentType.LeftShift);
     LocalDeclaration              = new LocalDeclarationGenerator(context);
     MethodDeclaration             = new MethodGenerator(context);
     ModuloAssignment              = new AssignmentGenerator(context, AssignmentType.Modulo);
     MultiplyAssignment            = new AssignmentGenerator(context, AssignmentType.Multiply);
     ObjectCreationExpression      = new ObjectCreationExpressionGenerator(context);
     PreIncrementExpression        = new PrePostExpressionGenerator(context, ExpressionType.PreIncrement);
     PreDecrementExpression        = new PrePostExpressionGenerator(context, ExpressionType.PreDecrement);
     PostIncrementExpression       = new PrePostExpressionGenerator(context, ExpressionType.PostIncrement);
     PostDecrementExpression       = new PrePostExpressionGenerator(context, ExpressionType.PostDecrement);
     PointerMemberAccessExpression = new PointerMemberAccessGenerator(context);
     Property             = new PropertyGenerator(context);
     ReturnStatement      = new ReturnStatementGenerator(context);
     RightShiftAssignment = new AssignmentGenerator(context, AssignmentType.RightShift);
     SimpleAssignment     = new SimpleAssignmentGenerator(context);
     SimpleMemberAccess   = new SimpleMemberAccessGenerator(context);
     SizeOfExpression     = new SizeofExpressionGenerator(context);
     Struct = new StructGenerator(context);
     SubstractAssignment = new AssignmentGenerator(context, AssignmentType.Substract);
     SwitchStatement     = new SwitchStatementGenerator(context);
     checkedStatement    = new checkedStatementGenerator(context);
     Variable            = new VariableGenerator(context);
     WhileStatement      = new WhileStatementGenerator(context);
 }
Esempio n. 7
0
        public override void OnBeforeFromClauseVisited(Expression expression)
        {
            SparqlVariable s = null;
            SparqlVariable o = null;

            if (expression is MemberExpression)
            {
                QuerySourceReferenceExpression sourceExpression = expression.TryGetQuerySourceReference();

                s = VariableGenerator.TryGetSubjectVariable(sourceExpression) ?? VariableGenerator.TryGetObjectVariable(sourceExpression);
                o = VariableGenerator.CreateObjectVariable(expression);

                // The from clause is parsed first when handling a query. This allows us to detect if the
                // query source is a subquery and proceed with implementing it _before_ hanlding its results.
                MemberExpression memberExpression = expression as MemberExpression;

                if (s.IsGlobal())
                {
                    Type type = memberExpression.Member.DeclaringType;

                    if (type.IsSubclassOf(typeof(Resource)))
                    {
                        WhereResourceOfType(s, type);
                    }
                }

                // If the query model has a numeric result operator, we make all the following
                // expressions optional in order to also allow to count zero occurences.
                if (QueryModel.HasNumericResultOperator())
                {
                    GraphPatternBuilder optionalBuilder = new GraphPatternBuilder(GraphPatternType.Optional);

                    Child(optionalBuilder);

                    PatternBuilder = optionalBuilder;
                }
            }
            else
            {
                s = VariableGenerator.TryGetSubjectVariable(expression);
                o = VariableGenerator.TryGetObjectVariable(expression);
            }

            if (s != null && o != null)
            {
                // Set the variable name of the query source reference as subject of the current query.
                SetSubjectVariable(s, true);
                SetObjectVariable(o, true);
            }
        }
Esempio n. 8
0
        public void WhereResourceNotOfType(SparqlVariable s, Type type)
        {
            RdfClassAttribute t = type.TryGetCustomAttribute <RdfClassAttribute>();

            if (t != null)
            {
                Uri a = new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");

                SparqlVariable o = VariableGenerator.CreateObjectVariable();

                ConstantExpression c = Expression.Constant(t.MappedUri);

                PatternBuilder.Where(e => e.Subject(s).PredicateUri(a).Object(o));
                PatternBuilder.Filter(e => e.Variable(o.Name) != c.AsIriExpression() || !e.Bound(o.Name));
            }
        }
Esempio n. 9
0
        public override void OnSelectClauseVisited(Expression selector)
        {
            base.OnSelectClauseVisited(selector);

            // If we are in the root query generator and have not yet selected the
            // subject variable, set it from the given selector.
            if (IsRoot && !SelectedVariables.Any())
            {
                SparqlVariable o = VariableGenerator.TryGetObjectVariable(selector);

                if (o != null && !IsSelectedVariable(o))
                {
                    SelectVariable(o);
                }
            }
        }
Esempio n. 10
0
        protected void BuildBuiltInCall(MemberExpression memberExpression, Func <NumericExpression, BooleanExpression> buildFilter)
        {
            SparqlVariable o = VariableGenerator.TryGetObjectVariable(memberExpression.Expression) ?? ObjectVariable;

            MemberInfo member = memberExpression.Member;

            if (member.DeclaringType == typeof(String))
            {
                switch (member.Name)
                {
                case "Length":
                    PatternBuilder.Filter(e => buildFilter(e.StrLen(e.Variable(o.Name))));
                    break;

                default:
                    throw new NotSupportedException(memberExpression.ToString());
                }
            }
            else if (member.DeclaringType == typeof(DateTime))
            {
                // TODO: YEAR, MONTH, DAY, HOURS, MINUTES, SECONDS, TIMEZONE, TZ
                throw new NotImplementedException(member.DeclaringType.ToString());
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Generates an appropriate return statement for the Method.
        /// </summary>
        private void generateReturnStatement()
        {
            StringBuilder builder = new StringBuilder("return ");

            builder.Append("(");
            builder.Append(this.returnType);
            builder.Append(")");

            int     choiceVarOrLiteral = (new Random()).Next(1);
            Operand operand;

            if (choiceVarOrLiteral == 0)
            {
                operand = VariableGenerator.getRandomizedVariable(this, this.returnType);
            }
            else
            {
                operand = new Literal(this.returnType);
            }

            builder.Append(operand);
            builder.Append(";\n");
            this.returnStatement = builder.ToString();
        }
Esempio n. 12
0
        public void WhereResourceNotOfType(Expression expression, Type type)
        {
            SparqlVariable so = VariableGenerator.TryGetSubjectVariable(expression) ?? VariableGenerator.TryGetObjectVariable(expression);

            WhereResourceNotOfType(so, type);
        }
Esempio n. 13
0
        public void WhereResource(Expression expression, SparqlVariable p, SparqlVariable o)
        {
            SparqlVariable s = VariableGenerator.TryGetSubjectVariable(expression) ?? SubjectVariable;

            PatternBuilder.Where(t => t.Subject(s).Predicate(p).Object(o));
        }
Esempio n. 14
0
        private SparqlVariable BuildMemberAccess(MemberExpression memberExpression, IGraphPatternBuilder patternBuilder)
        {
            MemberInfo member = memberExpression.Member;

            // If we do access a member of a system type, like string.Length we actually select the
            // the declaring member and invoke a SPARQL built in call to get the value.
            if (member.IsBuiltInCall())
            {
                MemberExpression parentMember = memberExpression.Expression as MemberExpression;

                return(BuildMemberAccess(parentMember, patternBuilder));
            }
            else if (memberExpression.Expression is MemberExpression)
            {
                MemberExpression parentMember = memberExpression.Expression as MemberExpression;

                // Note: When we build an optional property path, we consider the relation to the
                // parent properties of the accessed property to be non-optional.
                IGraphPatternBuilder builder = member.IsUriType() ? patternBuilder : PatternBuilder;

                // We might encounter property paths (i.e. contact.Organization.Name). Therefore,
                // implement the parent expression of the current member recursively..
                SparqlVariable po = BuildMemberAccess(parentMember, builder);

                // If we are building a node on a property path (parentExpression != null), we associate
                // the object variable with the parent expression so that it becomes the subject of the parent.
                VariableGenerator.SetSubjectVariable(memberExpression, po);
            }

            if (member.IsUriType())
            {
                // When we access the .Uri member of a resource we do not need a property mapping and return the subject as the bound variable.

                // We create a triple pattern describing the resource in the local scope just in case it has not been described yet.
                // Todo: Improve. Check if triples actually need to be asserted.
                SparqlVariable s = VariableGenerator.TryGetSubjectVariable(memberExpression) ?? SubjectVariable;
                SparqlVariable p = VariableGenerator.CreatePredicateVariable();
                SparqlVariable o = VariableGenerator.CreateObjectVariable(memberExpression);

                patternBuilder.Where(t => t.Subject(s).Predicate(p).Object(o));

                VariableGenerator.SetSubjectVariable(memberExpression, s);

                return(s);
            }
            else if (memberExpression.Expression is QuerySourceReferenceExpression)
            {
                QuerySourceReferenceExpression querySource = memberExpression.Expression as QuerySourceReferenceExpression;

                if (VariableGenerator.TryGetSubjectVariable(memberExpression) == VariableGenerator.GlobalSubject)
                {
                    // In case the accessed member is the global query subject (i.e. from x select x.Y)..
                    SparqlVariable s = VariableGenerator.TryGetSubjectVariable(querySource);
                    SparqlVariable o = VariableGenerator.GlobalSubject;

                    if (s == null)
                    {
                        s = VariableGenerator.CreateSubjectVariable(querySource);

                        BuildMemberAccess(memberExpression, patternBuilder, member, s, o);
                    }

                    return(o);
                }
                else
                {
                    // Otherwise we are accessing a member of the globale query subject (i.e. from x where x.Y select x)
                    SparqlVariable s = VariableGenerator.TryGetSubjectVariable(querySource) ?? VariableGenerator.GlobalSubject;
                    SparqlVariable o = VariableGenerator.TryGetObjectVariable(memberExpression) ?? VariableGenerator.CreateObjectVariable(memberExpression);

                    BuildMemberAccess(memberExpression, patternBuilder, member, s, o);

                    return(o);
                }
            }
            else
            {
                SparqlVariable s = VariableGenerator.TryGetSubjectVariable(memberExpression) ?? VariableGenerator.CreateSubjectVariable(memberExpression);
                SparqlVariable o = VariableGenerator.TryGetObjectVariable(memberExpression) ?? VariableGenerator.CreateObjectVariable(memberExpression);

                BuildMemberAccess(memberExpression, patternBuilder, member, s, o);

                return(o);
            }
        }
Esempio n. 15
0
        public static bool TryConvert(Expression parameter, Type sourceType, Type destType, out Action <List <Expression>, ParameterExpression, PropertyInfo, Func <Expression, Expression> > act, out ParameterExpression variable)
        {
            Expression expression = null;

            variable = null;
            act      = null;
            var typeCode = Type.GetTypeCode(sourceType);

            if (typeCode == TypeCode.Empty || typeCode == TypeCode.DBNull)
            {
                return(false);
            }
            MethodInfo method = null;

            //判断是否可以显式转换
            if (destType.GetMethod("op_Explicit", new Type[] { sourceType }) != null)
            {
                expression = Expression.Convert(parameter, destType);
            }
            //判断是否可以隐式转换
            else if (destType.GetMethod("op_Implicit", new Type[] { sourceType }) != null)
            {
                expression = parameter;
            }
            //判断是否存在继承关系
            //Base base=Derive
            else if (destType.IsAssignableFrom(sourceType))
            {
                expression = parameter;
            }
            //判断是否存在Convert.ToXX方法
            else if (typeCode != TypeCode.String && typeCode != TypeCode.Object && Type.GetTypeCode(destType) != TypeCode.Object)
            {
                method = typeof(Convert).GetMethod("To" + destType.Name, BindingFlags.Static | BindingFlags.Public, null, new Type[] { sourceType }, new ParameterModifier[0]);
                if (method != null)
                {
                    expression = Expression.Call(null, method, parameter);
                }
            }
            if (expression != null)
            {
                act = (list, p1, srcPropertyInfo, func) =>
                {
                    list.Add(Expression.Assign(Expression.MakeMemberAccess(p1, srcPropertyInfo), func == null ? expression : func(expression)));
                };
                return(true);
            }
            bool skipChangeType = false;

            //                      目标类型是否存在TryParse方法————————否——————————ChangeType
            //                          |                                                                 |
            //                          |是                                                               |
            //                          |                       否                                  否    |
            //                      源类型是否为string———————————是否存在ToString方法—————
            //                          |                                           |
            //                          |是                                         |是
            //                          |——————————————————————
            //                          |
            //                          |
            //                      调用目标类型上的TryParse方法
            if ((method = _tryParseDic.GetOrAdd(destType, t => t.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string), t.MakeByRefType() }, new ParameterModifier[0]))) != null)
            {
                skipChangeType = true;
                MethodInfo toStringMethod = null;
                //首先判断sourceType是不是string
                var r = typeCode != TypeCode.String;
                if (r)
                {
                    //如果类型不是string,就需要看该类是否定义了自己的ToString方法
                    //BindingFlags.DeclaredOnly 标识只获取该类定义的方法,屏蔽继承的方法
                    if ((toStringMethod = _toStringDic.GetOrAdd(sourceType, t => t.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, Type.EmptyTypes, new ParameterModifier[0]))) == null)
                    {
                        skipChangeType = false;
                    }
                }
                if (skipChangeType)
                {
                    Expression temp = parameter;
                    //如果sourceType不是string
                    if (r)
                    {
                        temp = Expression.Call(parameter, toStringMethod);
                    }
                    ParameterExpression p = VariableGenerator.Generate(destType);
                    expression = Expression.Call(null, method, temp, p);
                    act        = (list, p1, srcPropertyInfo, func) =>
                    {
                        expression = Expression.IfThen(expression, Expression.Assign(Expression.MakeMemberAccess(p1, srcPropertyInfo), p));
                        list.Add(expression);
                    };
                    variable = p;
                }
            }
            if (!skipChangeType)
            {
                expression = Expression.Convert(Expression.Call(null, ChangeTypeMethod, Expression.Convert(parameter, typeof(object)), Expression.Constant(Type.GetTypeCode(destType), typeof(TypeCode))), destType);
                act        = (list, p1, srcPropertyInfo, func) =>
                {
                    list.Add(Expression.Assign(Expression.MakeMemberAccess(p1, srcPropertyInfo), func == null ? expression : func(expression)));
                };
            }
            return(true);
        }
Esempio n. 16
0
        public override void OnBeforeSelectClauseVisited(Expression selector)
        {
            base.OnBeforeSelectClauseVisited(selector);

            Type selectedType = TryGetSelectedType(selector);

            if (selectedType == null || !typeof(Resource).IsAssignableFrom(selectedType))
            {
                throw new NotSupportedException(selectedType.ToString());
            }

            // 1. We always create an outer query which selects all triples that describe our resources.
            SparqlVariable s_ = VariableGenerator.GlobalSubject;
            SparqlVariable p_ = VariableGenerator.GlobalPredicate;
            SparqlVariable o_ = VariableGenerator.GlobalObject;

            VariableGenerator.SetSubjectVariable(selector, s_);
            VariableGenerator.SetPredicateVariable(selector, p_);
            VariableGenerator.SetObjectVariable(selector, o_);

            SetSubjectVariable(s_);
            SetObjectVariable(o_);

            SelectVariable(s_);
            SelectVariable(p_);
            SelectVariable(o_);

            WhereResource(s_, p_, o_);

            // If we are describing resources using a SKIP or TAKE operator, we need to make sure that
            // these operations are on a per-resource basis and all triples for the described resources
            // are contained in the result.
            if (QueryModel.HasResultOperator <SkipResultOperator>() ||
                QueryModel.HasResultOperator <TakeResultOperator>() ||
                QueryModel.HasResultOperator <FirstResultOperator>() ||
                QueryModel.HasResultOperator <LastResultOperator>())
            {
                // ..which are described in an inner query on which the LIMIT and OFFSET operators are set.
                // This results in a SELECT query that acts like a DESCRIBE but ist faster on most triple
                // stores as the triples can be returend via bindings and must not be parsed.
                ISparqlQueryGenerator subGenerator = QueryGeneratorTree.CreateSubQueryGenerator(this, selector);

                subGenerator.SetSubjectVariable(s_, true);
                subGenerator.SetObjectVariable(o_);

                GenerateTypeConstraintOnSubject(subGenerator, selector);

                QueryGeneratorTree.CurrentGenerator = subGenerator;

                // NOTE: We set the subGenerator as a child *AFTER* the select clause and body clauses
                // have been processed (see <c>OnSelectClauseVisited</c>). This is because the dotNetRDF
                // query generator does not correctly handle result operators when it is already set as a child.
            }
            else if (!QueryModel.HasTypeConstraintOnExpression(selector))
            {
                // NOTE: This should not be done here. Simply because the HasTypeConstraintOnExpression
                // requires us to look ahead at the body clauses which is already done in more detail
                // by the expression visitor. We need a way to generate the type constraint after the query
                // has been visited and no type constraint was generated.
                GenerateTypeConstraintOnSubject(this, selector);
            }

            if (selector is MemberExpression)
            {
                MemberExpression memberExpression = selector as MemberExpression;

                BuildMemberAccess(memberExpression);
            }
        }
        public override void SetObjectOperator(ResultOperatorBase resultOperator)
        {
            base.SetObjectOperator(resultOperator);

            if (ObjectVariable != null)
            {
                if (resultOperator is AnyResultOperator)
                {
                    // When using x.Any(), we add a LIMIT 1 the query results in the SparqlQueryGenerator.

                    // When using .Any(x => ..), the variable x is locally scoped and cannot be
                    // used in outer queries. Therefore do not need to actually select it.

                    // This avoids issues with Stardog:
                    // https://community.stardog.com/t/sparql-union-only-working-with-inferencing-enabled/1040/9
                }
                else if (resultOperator is AverageResultOperator)
                {
                    var aggregate = new AverageAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is CountResultOperator)
                {
                    var aggregate = new CountDistinctAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is FirstResultOperator)
                {
                    // "Using LIMIT and OFFSET to select different subsets of the query solutions
                    // will not be useful unless the order is made predictable by using ORDER BY."
                    // Source: https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#modOffset

                    // Therefore, if no ordering exists we add an ordering on the current subject
                    // to make the query result predictable.
                    if (!QueryModel.BodyClauses.OfType <OrderByClause>().Any())
                    {
                        OrderBy(SubjectVariable);
                    }
                    else
                    {
                        // In case the order was make explicit, we have to do nothing.
                    }

                    Limit(1);
                }
                else if (resultOperator is LastResultOperator)
                {
                    // "Using LIMIT and OFFSET to select different subsets of the query solutions
                    // will not be useful unless the order is made predictable by using ORDER BY."
                    // Source: https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#modOffset

                    // Therefore, if no ordering exists we add an ordering on the current subject
                    // to make the query result predictable.
                    if (!QueryModel.BodyClauses.OfType <OrderByClause>().Any())
                    {
                        OrderByDescending(SubjectVariable);
                    }
                    else
                    {
                        // Inverting the direction of the first ordering is handled in SparqlQueryModelVisitor.VisitOrdering().
                        // This is because the orderings are not necessarily processed *before* the result operators..
                    }

                    Limit(1);
                }
                else if (resultOperator is MaxResultOperator)
                {
                    var aggregate = new MaxAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is MinResultOperator)
                {
                    var aggregate = new MinAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is SumResultOperator)
                {
                    var aggregate = new SumAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is OfTypeResultOperator)
                {
                    OfTypeResultOperator ofType = resultOperator as OfTypeResultOperator;
                    RdfClassAttribute    type   = ofType.SearchedItemType.TryGetCustomAttribute <RdfClassAttribute>();

                    if (type == null)
                    {
                        throw new ArgumentException("No RdfClass attrribute declared on type: " + ofType.SearchedItemType);
                    }

                    SparqlVariable s = ObjectVariable;
                    SparqlVariable p = VariableGenerator.CreatePredicateVariable();
                    SparqlVariable o = VariableGenerator.CreateObjectVariable();

                    WhereResource(s, p, o);
                    WhereResourceOfType(o, ofType.SearchedItemType);
                }
                else if (resultOperator is SkipResultOperator)
                {
                    SkipResultOperator op = resultOperator as SkipResultOperator;
                    Offset(int.Parse(op.Count.ToString()));
                }
                else if (resultOperator is TakeResultOperator)
                {
                    TakeResultOperator op = resultOperator as TakeResultOperator;
                    Limit(int.Parse(op.Count.ToString()));
                }
                else
                {
                    throw new NotImplementedException(resultOperator.ToString());
                }
            }
        }
Esempio n. 18
0
        public static Statement getRandomizedStatement(Method method, List <ClassGenerator> classList)
        {
            Statement stmt   = new Statement();
            Random    rand   = new Random();
            int       option = 0;

            option = rand.Next(100) % 3;
            switch (option)
            {
            case 0:             // Assignment statement
                stmt.stmt = (new AssignmentExpression(method)).ToString();
                //FIXME: if there is no local variable available to assign, it will simply use print statement.
                // following line will add an extra line to the LOC
                method.Loc = method.Loc + 1;
                break;

            case 1:             // Print statements: Max. 5 lines in a block
                stmt.stmt = (new PrintStatement(method)).ToString();
                break;

            case 2:             // method calls: restrict it to MAX_ALLOWED_METH_CALL
                int methCalledCounterValue = method.MethodCallCounter + 1;
                method.MethodCallCounter = methCalledCounterValue;
                if (methCalledCounterValue < method.MaxAllowedMethodCalls)
                {
                    if (ProgGenUtil.coinFlip())
                    {
                        stmt.stmt += ProgGenUtil.getMethodCall(method, classList);
                    }
                    else
                    {
                        //wire it to variables in scope
                        Operand lhs;
                        Random  random = new Random();

                        HashSet <Type.Primitives> validPrimitivesInScope = ProgGenUtil.getValidPrimitivesInScope(method);

                        //Pick a type
                        object[] primitivesArray = validPrimitivesInScope.ToArray();

                        if (primitivesArray.Length == 0)
                        {
                            stmt.stmt += ProgGenUtil.getMethodCall(method, classList);
                            break;
                        }

                        Type.Primitives selectedPrimitive = (Type.Primitives)primitivesArray[random.Next(primitivesArray.Length)];

                        // Introducing any variable
                        lhs = VariableGenerator.getRandomizedVariable(method, selectedPrimitive);

                        string methodCall = ProgGenUtil.getMethodCallForReturnType(method, classList, new Type(selectedPrimitive, ""), lhs);
                        stmt.stmt += methodCall + "\n";
                    }
                }
                else
                {
                    stmt.stmt = (new PrintStatement(method)).ToString();
                }
                break;

            default:
                stmt.stmt = (new IfStmtIfStmt(method, classList)).ToString();
                break;
            }

            return(stmt);
        }
Esempio n. 19
0
        public override void OnBeforeSelectClauseVisited(Expression selector)
        {
            base.OnBeforeSelectClauseVisited(selector);

            QuerySourceReferenceExpression sourceExpression = selector.TryGetQuerySourceReference();

            if (sourceExpression != null)
            {
                // Register the query source with the global variable for sub-queries.
                SparqlVariable s = VariableGenerator.TryGetSubjectVariable(sourceExpression) ?? VariableGenerator.GlobalSubject;

                // Assert the object type.
                if (sourceExpression.Type.IsSubclassOf(typeof(Resource)))
                {
                    WhereResourceOfType(s, sourceExpression.Type);
                }

                if (selector is MemberExpression)
                {
                    MemberExpression memberExpression = selector as MemberExpression;

                    SparqlVariable o = VariableGenerator.CreateObjectVariable(memberExpression);

                    // Select all triples having the resource as subject.
                    SetSubjectVariable(s);
                    SetObjectVariable(o, true);

                    // If the member expression is not selected in the WHERE block, we add it here.
                    // Scenarios:
                    // - from x in Model.AsQueryable<X>() select x.B
                    // - from x in Model.AsQueryable<X>() where x.A select x.B
                    string e = memberExpression.ToString();

                    if (!QueryModel.BodyClauses.OfType <WhereClause>().Any(c => c.Predicate.ToString().Contains(e)))
                    {
                        // We select the member without a constraint on its value.
                        QueryModel.BodyClauses.Add(new WhereClause(memberExpression));

                        // Since there is no constraint on the member, we also need to select the ones that are not bound.
                        Type memberType = memberExpression.Member.GetMemberType();

                        // TODO: There might be a different default value on the member using the DefaultValue() attribute.
                        object defaultValue = TypeHelper.GetDefaultValue(memberType);

                        if (defaultValue != null && memberType != typeof(string))
                        {
                            ConstantExpression coalescedValue = Expression.Constant(defaultValue);

                            // Mark the variable to be coalesced with the default value when selected.
                            CoalescedVariables[o] = coalescedValue.AsLiteralExpression();
                        }
                    }
                }
                else if (QueryModel.HasNumericResultOperator())
                {
                    // If we have a numeric result operator on the root query, make the
                    // subject variable known so that the model visitor can handle it.
                    SetSubjectVariable(s);
                }
            }
        }