Beispiel #1
0
        private void CheckUniqueUser()
        {
            var path = Path;

            if (!path.StartsWith(string.Concat(Repository.ImsFolderPath, RepositoryPath.PathSeparator)) || Parent.Path == Repository.ImsFolderPath)
            {
                throw new InvalidOperationException("Invalid path: user nodes can only be saved under a /Root/IMS/[DomainName] folder.");
            }

            string domainPath = path.Substring(0, Repository.ImsFolderPath.Length + 1 + path.Substring(Repository.ImsFolderPath.Length + 1).IndexOf('/') + 1);

            //We validate here the uniqueness of the user. The constraint is the user name itself and that in Active Directory
            //there must not exist two users and/or groups with the same name under a domain. Organizational units may have
            //the same name as a user.

            //CONDITIONAL EXECUTE
            IEnumerable <int> identifiers;
            int count;

            if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance)
            {
                var query          = new NodeQuery();
                var nameExpression = new StringExpression(StringAttribute.Name, StringOperator.Equal, Name);
                var pathExpression = new StringExpression(StringAttribute.Path, StringOperator.StartsWith, domainPath);
                var orTypes        = new ExpressionList(ChainOperator.Or);
                orTypes.Add(new TypeExpression(ActiveSchema.NodeTypes["User"]));
                orTypes.Add(new TypeExpression(ActiveSchema.NodeTypes["Group"]));

                query.Add(pathExpression);
                query.Add(nameExpression);
                query.Add(orTypes);
                var result = query.Execute();
                identifiers = result.Identifiers;
                count       = result.Count;
            }
            else
            {
                var nodes = NodeQuery.QueryNodesByTypeAndPathAndName(new List <NodeType> {
                    ActiveSchema.NodeTypes["User"], ActiveSchema.NodeTypes["Group"]
                }, false, domainPath, false, Name).Nodes;

                var nodeList = nodes as NodeList <Node>;
                if (nodeList != null)
                {
                    identifiers = nodeList.GetIdentifiers();
                    count       = nodeList.Count;
                }
                else
                {
                    identifiers = nodes.Select(x => x.Id);
                    count       = identifiers.Count();
                }
            }

            if (count > 1 || (count == 1 && identifiers.First() != this.Id))
            {
                var ids = String.Join(", ", (from x in identifiers select x.ToString()).ToArray());
                throw GetUniqueUserException(domainPath, ids);
            }
        }
Beispiel #2
0
        private ActionResult SearchNodeQuery(string searchStr, string searchRoot, string contentTypes)
        {
            if (!string.IsNullOrEmpty(searchStr))
            {
                // simple nodequery
                var query = new NodeQuery();
                query.Add(new SearchExpression(searchStr));
                var nodes = query.Execute().Nodes;

                // filter with path
                if (!string.IsNullOrEmpty(searchRoot))
                {
                    nodes = nodes.Where(n => n.Path.StartsWith(searchRoot));
                }

                // filter with contenttypes
                if (!string.IsNullOrEmpty(contentTypes))
                {
                    var contentTypesArr = GetContentTypes(contentTypes);
                    nodes = nodes.Where(n => contentTypesArr.Contains(n.NodeType.Name));
                }
                var contents = nodes.Where(n => n != null).Select(n => new Content(n, true, false, false, false, 0, 0));

                return(Json(contents.ToArray(), JsonRequestBehavior.AllowGet));
            }
            else
            {
                if (string.IsNullOrEmpty(searchRoot) && string.IsNullOrEmpty(contentTypes))
                {
                    return(Json(null, JsonRequestBehavior.AllowGet));
                }

                var query         = new NodeQuery();
                var andExpression = new ExpressionList(ChainOperator.And);
                query.Add(andExpression);

                // filter with path
                if (!string.IsNullOrEmpty(searchRoot))
                {
                    andExpression.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, searchRoot));
                }

                // filter with contenttypes
                if (!string.IsNullOrEmpty(contentTypes))
                {
                    var contentTypesArr = GetContentTypes(contentTypes);
                    var orExpression    = new ExpressionList(ChainOperator.Or);
                    foreach (var contentType in contentTypesArr)
                    {
                        orExpression.Add(new TypeExpression(NodeType.GetByName(contentType), true));
                    }
                    andExpression.Add(orExpression);
                }

                var nodes    = query.Execute().Nodes;
                var contents = nodes.Select(n => new Content(n, true, false, false, false, 0, 0));

                return(Json(contents.ToArray(), JsonRequestBehavior.AllowGet));
            }
        }
        private User GetRegisteredUser(string resetEmail, string domain)
        {
            if (String.IsNullOrEmpty(resetEmail))
            {
                throw new ArgumentNullException("resetEmail");
            }
            if (String.IsNullOrEmpty(domain))
            {
                throw new ArgumentNullException("domain");
            }

            var query          = new NodeQuery();
            var expressionList = new ExpressionList(ChainOperator.And);

            expressionList.Add(new TypeExpression(ActiveSchema.NodeTypes[Configuration.UserTypeName], false));
            expressionList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, string.Concat(Repository.ImsFolderPath, RepositoryPath.PathSeparator, domain, RepositoryPath.PathSeparator)));
            expressionList.Add(new StringExpression(ActiveSchema.PropertyTypes["Email"], StringOperator.Equal, resetEmail));
            query.Add(expressionList);
            AccessProvider.ChangeToSystemAccount();
            var resultList = query.Execute();

            AccessProvider.RestoreOriginalUser();

            // no user has beeen found
            if (resultList.Count == 0)
            {
                return(null);
            }

            var u = resultList.Nodes.First() as User;

            return(u);
        }
Beispiel #4
0
        /// <summary>
        /// Sets datasource of listview.
        /// </summary>
        /// <remarks>
        /// Loads tags form Content Repository and adds the following properties of them to a datatable:
        /// DisplayName, Created By, Creation Date, Modification Date, Reference Count, Path, Is Blacklisted an Node ID.
        /// Sets this datatable as datasource to the listview.
        /// </remarks>
        private void SetDataSource()
        {
            var refCounts = TagManager.GetTagOccurrencies();

            var exprList = new ExpressionList(ChainOperator.And);

            exprList.Add(new TypeExpression(ActiveSchema.NodeTypes["Tag"], true));
            exprList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, TagPath));

            var nq = new NodeQuery(exprList);

            var result = nq.Execute();

            var dt = new DataTable();

            _tagsInRepository = new List <string>();

            dt.Columns.AddRange(new[] {
                new DataColumn("DisplayName", typeof(String)),
                new DataColumn("CreatedBy", typeof(String)),
                new DataColumn("CreationDate", typeof(DateTime)),
                new DataColumn("ModificationDate", typeof(DateTime)),
                new DataColumn("RefCount", typeof(Int32)),
                new DataColumn("Path", typeof(String)),
                new DataColumn("IsBlackListed", typeof(String)),
                new DataColumn("ID", typeof(Int32))
            });

            foreach (var item in result.Nodes.ToList())
            {
                var black = GetIsBlackListed(item.Id);

                dt.Rows.Add(new object[]
                {
                    item.DisplayName,
                    item.CreatedBy,
                    item.CreationDate,
                    item.ModificationDate,
                    refCounts.ContainsKey(item.DisplayName) ? refCounts[item.DisplayName] : 0,
                    item.Path, black,
                    Convert.ToInt32(item.Id)
                });
                if (black == "No")
                {
                    _tagsInRepository.Add(item.DisplayName);
                }
            }

            _allTags = TagManager.GetAllTags(null, SearchPaths);

            dt.DefaultView.Sort = !String.IsNullOrEmpty(Request.QueryString["OrderBy"]) ? String.Concat(Request.QueryString["OrderBy"], " " + Request.QueryString["Direction"]) : "DisplayName ASC";

            _lv = FindControl("LVTags") as ListView;
            if (_lv != null)
            {
                _lv.DataSource = dt.DefaultView;
                _lv.DataBind();
            }
        }
Beispiel #5
0
        public static IEnumerable <Node> GetPortletsFromRepo()
        {
            var query      = new NodeQuery();
            var expression = new ExpressionList(ChainOperator.And);

            expression.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, PortletsFolderPath));
            expression.Add(new TypeExpression(NodeType.GetByName("Portlet")));
            query.Add(expression);
            return(query.Execute().Nodes);
        }
Beispiel #6
0
        public Node ExprList()
        {
            var node = new ExpressionList();

            node.Add(Expr());
            while (CurrentToken == TokenCategory.COMMA)
            {
                Expect(TokenCategory.COMMA);
                node.Add(Expr());
            }
            return(node);
        }
Beispiel #7
0
        public Node ExprList()
        {
            var expressionList = new ExpressionList();

            expressionList.Add(Expr());
            while (firstOfListContinuation.Contains(CurrentToken))
            {
                Expect(TokenCategory.COMMA);
                expressionList.Add(Expr());
            }
            return(expressionList);
        }
Beispiel #8
0
 public void CopyToTest()
 {
     ExpressionList<ConstantTypes.Integer> list = new ExpressionList<ConstantTypes.Integer>();
     var zero = new ConstantTypes.Integer(0);
     var one = new ConstantTypes.Integer(1);
     list.Add(zero);
     list.Add(one);
     ConstantTypes.Integer[] array = new ConstantTypes.Integer[2];
     list.CopyTo(array, 0);
     Assert.IsTrue(array.Length == 2);
     Assert.IsTrue(array[0] == zero);
     Assert.IsTrue(array[1] == one);
 }
Beispiel #9
0
        //<expr-list>//
        public Node ExpressionList()
        {
            var elist = new ExpressionList();

            if (firstExpr.Contains(CurrentToken))
            {
                elist.Add(Expression());
                while (firstOfIdListCont.Contains(CurrentToken))
                {
                    Expect(TokenCategory.COMMA);
                    elist.Add(Expression());
                }
            }
            return(elist);
        }
Beispiel #10
0
 public void AddTest()
 {
     var list = new ExpressionList<ConstantTypes.Integer>();
     var one = new ConstantTypes.Integer(1);
     list.Add(one);
     Assert.IsTrue(list.Contains(one));
 }
Beispiel #11
0
        public Node ExprList()
        {
            var result = new ExpressionList();

            if (firstOfExpression.Contains(CurrentToken))
            {
                result.Add(Expression());

                while (CurrentToken == TokenCategory.LIST_ELEMENT)
                {
                    Expect(TokenCategory.LIST_ELEMENT);
                    result.Add(Expression());
                }
            }
            return(result);
        }
Beispiel #12
0
        /// <summary>
        /// Parses expressions into a tree until seperator is hit
        /// </summary>
        /// <returns></returns>
        ExpressionList ParseExpressions()
        {
            /* Note to self: Base must be after eventual paranthese to respect scope (E.g 'void method([HERE]...')) */

            ExpressionList expressions = new ExpressionList();
            int            Scope       = 1;

            while (Scope > 0)
            {
                //if (tokenReader.Expect(LexKind.ParentheseOpen))
                //{
                //    Scope++;
                //}
                //else
                if (tokenReader.Expect(LexKind.ParentheseClose))
                {
                    Scope = 0;
                }

                if (ParseExpression(out Expression expression))
                {
                    expressions.Add(expression);
                }
                else
                {
                    tokenReader.Skip(1);
                }
            }

            return(expressions);
        }
Beispiel #13
0
 public SearchedCase(params KeyValuePair<Predicate, Expression>[] cases)
 {
     SearchCases = new ExpressionList<SearchedCaseExpression>();
     foreach (var kvp in cases)
     {
         SearchCases.Add(new SearchedCaseExpression(kvp.Key, kvp.Value));
     }
 }
Beispiel #14
0
        public void NodeQuery_Bug2125()
        {
            Expression     exp;
            ExpressionList expList;

            var query1 = new NodeQuery();

            exp = new SearchExpression("dummy");
            query1.Add(exp);

            Assert.IsTrue(Object.ReferenceEquals(exp.Parent, query1), "#1");

            expList = new ExpressionList(ChainOperator.And);
            query1.Add(expList);

            Assert.IsTrue(Object.ReferenceEquals(expList.Parent, query1), "#2");

            exp = new StringExpression(StringAttribute.Name, StringOperator.Equal, "Root");
            expList.Add(exp);

            Assert.IsTrue(Object.ReferenceEquals(exp.Parent, expList), "#3");

            exp = new IntExpression(IntAttribute.Id, ValueOperator.Equal, 2);
            expList.Add(exp);

            Assert.IsTrue(Object.ReferenceEquals(exp.Parent, expList), "#4");

            //------------------------------------------------------------------------------------

            var query2 = new NodeQuery
                         (
                new SearchExpression("dummy"),
                new ExpressionList
                (
                    ChainOperator.And,
                    new StringExpression(StringAttribute.Name, StringOperator.Equal, "Root"),
                    new IntExpression(IntAttribute.Id, ValueOperator.Equal, 2)
                )
                         );

            Assert.IsTrue(Object.ReferenceEquals(query2.Expressions[0].Parent, query2), "#5");
            Assert.IsTrue(Object.ReferenceEquals(query2.Expressions[1].Parent, query2), "#6");
            Assert.IsTrue(Object.ReferenceEquals(((ExpressionList)query2.Expressions[1]).Expressions[0].Parent, query2.Expressions[1]), "#7");
            Assert.IsTrue(Object.ReferenceEquals(((ExpressionList)query2.Expressions[1]).Expressions[1].Parent, query2.Expressions[1]), "#8");
        }
Beispiel #15
0
 public void ClearTest()
 {
     var list = new ExpressionList<ConstantTypes.Integer>();
     var one = new ConstantTypes.Integer(1);
     list.Add(one);
     Assert.IsTrue(list.Count == 1);
     list.Clear();
     Assert.IsTrue(list.Count == 0);
 }
Beispiel #16
0
 public override Expression VisitRefTypeExpression(RefTypeExpression reftypexp) {
   if (reftypexp == null) return null;
   Expression result = base.VisitRefTypeExpression (reftypexp);
   if (result != reftypexp) return result;
   UnaryExpression refanytype = new UnaryExpression(reftypexp.Operand, NodeType.Refanytype, SystemTypes.RuntimeTypeHandle, reftypexp.SourceContext);
   ExpressionList arguments = new ExpressionList(1);
   arguments.Add(refanytype);
   MemberBinding mb = new MemberBinding(null, Runtime.GetTypeFromHandle);
   return new MethodCall(mb, arguments, NodeType.Call, SystemTypes.Type);
 }
        public Node ExprList()
        {
            var exprList = new ExpressionList();

            if (Current != TokenCategory.CLOSE_PARENTHESIS)
            {
                exprList.Add(Expr());
                ExprListCont(exprList);
            }
            return(exprList);
        }
Beispiel #18
0
        public static IEnumerable <Node> GetContainerUsers(Node container)
        {
            var            query          = new NodeQuery();
            ExpressionList expressionList = new ExpressionList(ChainOperator.And);

            // nodetype
            TypeExpression typeExpression = new TypeExpression(Common.GetNodeType(ADObjectType.User));

            expressionList.Add(typeExpression);

            // from container as root
            StringExpression pathExpression = new StringExpression(StringAttribute.Path, StringOperator.StartsWith, container.Path);

            expressionList.Add(pathExpression);

            query.Add(expressionList);

            var result = query.Execute();

            return(result.Nodes);
        }
Beispiel #19
0
        public static NodeQueryResult GetWebContentTypeList()
        {
            var contentTypeNames = ConfigurationManager.AppSettings[ContentTypeNameListKey];

            if (String.IsNullOrEmpty(contentTypeNames))
            {
                contentTypeNames = DefaultContentTypeName;
            }

            var list          = contentTypeNames.Split(',');
            var validCtdNames = new List <string>();

            foreach (var c in list)
            {
                if (IsValidContentType(c.Trim()))
                {
                    validCtdNames.Add(c.Trim());
                }
            }


            var expressionList = new ExpressionList(ChainOperator.Or);
            var query          = new NodeQuery();

            foreach (var ctd in validCtdNames)
            {
                var stringExpressionValue = RepositoryPath.Combine(Repository.ContentTypesFolderPath, String.Concat(ActiveSchema.NodeTypes[ctd].NodeTypePath, "/"));
                expressionList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, stringExpressionValue));
            }

            if (validCtdNames.Count == 0)
            {
                var stringExpressionValue = RepositoryPath.Combine(Repository.ContentTypesFolderPath, String.Concat(ActiveSchema.NodeTypes[DefaultContentTypeName].NodeTypePath, "/"));
                expressionList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, stringExpressionValue));
            }
            query.Add(expressionList);

            return(query.Execute());
        }
		ExpressionList Parse (int start, int end)
		{
			if (string.IsNullOrWhiteSpace (source))
				return new ExpressionList ();

			var ret = new ExpressionList ();
			while (start < end) {
				int bak = start;
				ret.Add (ParseSingle (ref start, end));
				if (bak == start)
					throw new Exception ("Parser failed to progress token position: " + source);
			}
			return ret;
		}
Beispiel #21
0
        public void AddClause(Expression expression, ChainOperator chainOp)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            ExpressionList finalExpList;
            var            origExpList = expression as ExpressionList;

            if (origExpList != null)
            {
                finalExpList = origExpList;
            }
            else
            {
                finalExpList = new ExpressionList(chainOp);
                finalExpList.Add(expression);
            }

            this.Text = AddFilterToNodeQuery(Text, finalExpList.ToXml());
        }
Beispiel #22
0
 public VisitedExpression Append(VisitedExpression expression)
 {
     ExpressionList.Add(expression);
     return(this);
 }
Beispiel #23
0
    /// <summary>
    /// Create a proxy method implementing the abstractMethod and which calls the implementingMethod.
    /// This is needed when the implementingMethod is supposed to be used for the implementation
    /// of the abstractMethod, but cannot be because it lives in another assembly or isn't virtual
    /// or the abstractMethod has an out-of-band contract and the implementingMethod must have
    /// an identical type signature (i.e., no optional type modifiers for the non-null types).
    /// </summary>
    /// <param name="type">The type containing the implementingMethod and to which the
    /// proxy will be added as a member.</param>
    /// <param name="abstractMethod">The abstract method that the proxy is an implementation of.</param>
    /// <param name="implementingMethod">The implementing method that is supposed to implement
    /// the abstractMethod, but is unable to for various reasons.</param>
    /// <returns>The newly created proxy method.</returns>
    private Method CreateProxy(TypeNode type, Method abstractMethod, Method implementingMethod) {
      ParameterList parameters = abstractMethod.Parameters;
      if (parameters == null)
        parameters = new ParameterList(0);
      else
        parameters = parameters.Clone();
      int m = parameters.Count;
      ExpressionList arguments = new ExpressionList(m);
      for (int j = 0; j < m; j++) {
        Parameter p = (Parameter)parameters[j].Clone();
        parameters[j] = p;
        if (this.typeSystem.IsNonNullType(p.Type)) {
          arguments.Add(this.typeSystem.ExplicitNonNullCoercion(p, p.Type));
        } else {
          arguments.Add(p);
        }
        p.Type = TypeNode.DeepStripModifiers(p.Type, (abstractMethod.Template!=null)?abstractMethod.Template.Parameters[j].Type:null, SystemTypes.NonNullType);
      }
      This ThisParameter = new This(this.currentType);
      StatementList statements = new StatementList(2);
      NodeType typeOfCall = type.IsValueType ? NodeType.Call : NodeType.Callvirt;
      MethodCall mCall = new MethodCall(new MemberBinding(ThisParameter, implementingMethod), arguments, typeOfCall, implementingMethod.ReturnType);
      if (implementingMethod.ReturnType != SystemTypes.Void) {
        statements.Add(new Return(mCall));
      } else {
        statements.Add(new ExpressionStatement(mCall));
        statements.Add(new Return());
      }
      TypeNode returnType = TypeNode.DeepStripModifiers(abstractMethod.ReturnType, (abstractMethod.Template != null) ? abstractMethod.Template.ReturnType : null, SystemTypes.NonNullType);
      ProxyMethod proxy = new ProxyMethod(type, null, new Identifier(abstractMethod.DeclaringType.Name + "." + abstractMethod.Name, implementingMethod.Name.SourceContext), parameters, returnType, new Block(statements));
      proxy.ProxyFor = implementingMethod;
      proxy.ThisParameter = ThisParameter;
      proxy.CallingConvention = CallingConventionFlags.HasThis;

      proxy.Flags = MethodFlags.CompilerControlled | MethodFlags.HideBySig | MethodFlags.NewSlot | MethodFlags.Virtual | MethodFlags.Final;
      proxy.ImplementedInterfaceMethods = new MethodList(abstractMethod);
      type.Members.Add(proxy);
      return proxy;
    }
        private void AddAsyncPost(List <Ensures> asyncPostconditions)
        {
            var origBody = new Block(this.checkPostBody);

            origBody.HasLocals = true;

            var newBodyBlock = new Block(new StatementList());

            newBodyBlock.HasLocals = true;

            var methodBody      = new StatementList();
            var methodBodyBlock = new Block(methodBody);

            methodBodyBlock.HasLocals = true;

            checkPostMethod.Body = methodBodyBlock;

            methodBody.Add(newBodyBlock);
            Block newExitBlock = new Block();

            methodBody.Add(newExitBlock);

            // Map closure locals to fields and initialize closure fields

            foreach (Ensures e in asyncPostconditions)
            {
                if (e == null)
                {
                    continue;
                }

                this.Visit(e);

                if (this.forwarder != null)
                {
                    this.forwarder.Visit(e);
                }

                ReplaceResult repResult = new ReplaceResult(
                    this.checkPostMethod, this.originalResultLocal,
                    this.rewriter.AssemblyBeingRewritten);

                repResult.Visit(e);

                if (repResult.ContractResultWasCapturedInStaticContext)
                {
                    this.contractResultCapturedInStaticContext.Add(e.Assertion.SourceContext);
                }

                // now need to initialize closure result fields
                foreach (var target in repResult.NecessaryResultInitializationAsync(this.closureLocals))
                {
                    // note: target here
                    methodBody.Add(new AssignmentStatement(target, this.originalResultLocal));
                }
            }

            // Emit normal postconditions

            SourceContext?lastEnsuresSourceContext = null;

            var ensuresChecks = new StatementList();

            Method contractEnsuresMethod = this.rewriter.RuntimeContracts.EnsuresMethod;

            foreach (Ensures e in GetTaskResultBasedEnsures(asyncPostconditions))
            {
                // TODO: Not sure that 'break' is enough! It seems that this is possible
                // only when something is broken, because normal postconditions
                // are using Contract.Result<T>() and this is possible only for
                // generic tasks.
                if (IsVoidTask())
                {
                    break;               // something is wrong in the original contract
                }
                lastEnsuresSourceContext = e.SourceContext;

                //
                // Call Contract.RewriterEnsures
                //

                ExpressionList args = new ExpressionList();
                args.Add(e.PostCondition);

                args.Add(e.UserMessage ?? Literal.Null);

                args.Add(e.SourceConditionText ?? Literal.Null);

                ensuresChecks.Add(
                    new ExpressionStatement(
                        new MethodCall(
                            new MemberBinding(null, contractEnsuresMethod),
                            args, NodeType.Call, SystemTypes.Void),
                        e.SourceContext));
            }

            this.rewriter.CleanUpCodeCoverage.VisitStatementList(ensuresChecks);

            //
            // Normal postconditions
            //

            // Wrapping normal ensures into following if statement
            // if (task.Status == TaskStatus.RanToCompletion)
            // { postcondition check }
            //
            // Implementation of this stuff is a bit tricky because if-statements
            // are inverse in the IL.
            // Basically, we need to generate following code:
            // if (!(task.Status == Task.Status.RanToCompletion))
            //   goto EndOfNormalPostcondition;
            // {postcondition check}
            // EndOfNormalPostcondition:
            // {other Code}

            // Marker for EndOfNormalPostcondition
            Block endOfNormalPostcondition = new Block();

            // Generate: if (task.Status != RanToCompletion) goto endOfNormalPostcondition;
            StatementList checkStatusStatements = CreateIfTaskResultIsEqualsTo(
                checkMethodTaskParameter, TaskStatus.RanToCompletion, endOfNormalPostcondition);

            methodBodyBlock.Statements.Add(new Block(checkStatusStatements));

            // Emit a check for __ContractsRuntime.insideContractEvaluation around Ensures
            this.rewriter.EmitRecursionGuardAroundChecks(this.checkPostMethod, methodBodyBlock, ensuresChecks);

            // Now, normal postconditions are written to the method body.
            // We need to add endOfNormalPostcondition block as a marker.
            methodBodyBlock.Statements.Add(endOfNormalPostcondition);

            //
            // Exceptional postconditions
            //

            var exceptionalPostconditions = GetExceptionalEnsures(asyncPostconditions).ToList();

            if (exceptionalPostconditions.Count > 0)
            {
                // For exceptional postconditions we need to generate CheckException method first
                Method checkExceptionMethod = CreateCheckExceptionMethod();

                EmitCheckExceptionBody(checkExceptionMethod, exceptionalPostconditions);

                this.closureClass.Members.Add(checkExceptionMethod);

                // Then, we're using the same trick as for normal postconditions:
                // wrapping exceptional postconditions only when task.Status is TaskStatus.Faulted
                Block checkExceptionBlock = new Block(new StatementList());

                // Marker for endOfExceptionPostcondition
                Block endOfExceptionPostcondition = new Block();

                StatementList checkStatusIsException = CreateIfTaskResultIsEqualsTo(
                    checkMethodTaskParameter, TaskStatus.Faulted, endOfExceptionPostcondition);

                checkExceptionBlock.Statements.Add(new Block(checkStatusIsException));

                // Now we need to emit actuall check for exceptional postconditions

                // Emit: var ae = task.Exception;

                var aeLocal = new Local(aggregateExceptionType.Value);

                checkExceptionBlock.Statements.Add(
                    new AssignmentStatement(aeLocal,
                                            new MethodCall(
                                                new MemberBinding(checkMethodTaskParameter,
                                                                  GetTaskProperty(checkMethodTaskParameter, "get_Exception")),
                                                new ExpressionList())));

                // Emit: CheckException(ae);

                // Need to store method result somewhere, otherwise stack would be corrupted
                var checkResultLocal = new Local(SystemTypes.Boolean);

                checkExceptionBlock.Statements.Add(
                    new AssignmentStatement(checkResultLocal,
                                            new MethodCall(new MemberBinding(null,
                                                                             checkExceptionMethod),
                                                           new ExpressionList(checkExceptionMethod.ThisParameter, aeLocal))));

                checkExceptionBlock.Statements.Add(endOfExceptionPostcondition);

                methodBody.Add(checkExceptionBlock);
            }

            // Copy original block to body statement for both: normal and exceptional postconditions.
            newBodyBlock.Statements.Add(origBody);

            Block returnBlock = CreateReturnBlock(checkMethodTaskParameter, lastEnsuresSourceContext);

            methodBody.Add(returnBlock);
        }
Beispiel #25
0
 void AddError(StatementList statements, Identifier reader, RuntimeError code, params Expression[] args) {
   ExpressionList list = new ExpressionList();
   list.Add(new Literal(code, Runtime.RuntimeError));
   foreach (Expression e in args) list.Add(e);
   statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Error")), list)));
 }
Beispiel #26
0
 void AddReadOptional(Block block, StatementList statements, Member mem, Expression target, Identifier reader, Expression result) {
   TypeNode boxed = Checker.GetMemberType(mem);
   TypeNode type = Checker.GetCollectionElementType(boxed);
   statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList())));
   Local nameLocal = new Local(Identifier.For("name"),SystemTypes.String, block);
   Local nsLocal = new Local(Identifier.For("ns"),SystemTypes.String, block);
   statements.Add(new AssignmentStatement(nameLocal, new QualifiedIdentifier(reader, Identifier.For("LocalName"))));
   statements.Add(new AssignmentStatement(nsLocal, new QualifiedIdentifier(reader, Identifier.For("NamespaceURI"))));
   StringBuilder expecting = new StringBuilder();
   Expression isFound = null;
   if (mem.IsAnonymous) {
     isFound = IsStartOf(block, type, statements, nameLocal, nsLocal, expecting);    
   } else {
     ExpressionList args = new ExpressionList();
     args.Add(new Literal(mem.Name.Name, SystemTypes.String));
     isFound = new MethodCall(new QualifiedIdentifier(reader, Identifier.For("IsStartElement")), args);
   }
   StatementList trueStatements = new StatementList();
   If ifIsFound = new If(isFound, new Block(trueStatements), null);
   statements.Add(ifIsFound);
   
   if (!AddReadSimpleType(type, trueStatements, reader, target, result, false)) {
     Local localRequired = new Local(Identifier.Empty,SystemTypes.Boolean,block);
     statements.Add(new AssignmentStatement(localRequired, Literal.True));
     AddCallDeserializer(type, trueStatements, reader, target, localRequired, result);            
   } 
 }
Beispiel #27
0
        public static Expression Convert(ConversionState state, ConversionResult expressionResult, MethodStruct methodStruct)
        {
            #region // result will be stored in a temporary value
            bool        complexIndexer;
            ComputeType receiverComputeType;
            if (methodStruct.Type is ARRAY_TYPE)
            {
                // result is array
                ComputeType.FromType(methodStruct.Type).TryGetValue(out receiverComputeType);
            }
            else
            {
                // result is scalar
                receiverComputeType = new ComputeType(ComputeScalarType.Single, 1);
            }
            Identifier receiverIdentifier = Identifier.For("ret");

            Expression[] indices = ConversionHelper.GetExpressionsFromIndexer(null, ref receiverComputeType, out complexIndexer);

            complexIndexer |= expressionResult.HasComplexIndexer;

            #endregion

            List <ConversionHelper.Argument> sortedArguments = ConversionHelper.ExtractArguments(state, false);
            List <ConversionHelper.Argument> scalarArguments = ConversionHelper.ExtractArguments(state, true);

            //ExpressionArgument receiverArgument;
            //ConversionHelper.ProcessReceiver(state, expressionResult, receiverIdentifier, receiverComputeType, indices, null, ref sortedArguments, complexIndexer, out receiverArgument);

            #region // add the temporary variable as a receiver
            ExpressionArgument receiverArgument = new ExpressionArgument(sortedArguments.Count, indices, null, -1);
            sortedArguments.Add(new ConversionHelper.Argument {
                Index     = receiverArgument.Index,
                Name      = receiverIdentifier.ToString(),
                Indexers  = receiverArgument.Indexers,
                IsRead    = false,
                IsWritten = true,
                IsCall    = receiverArgument.IsCall,
                CallRank  = receiverArgument.CallRank,
            });

            Identifier receiverDataIdentifier = Identifier.For("data" + receiverArgument.Index);
            if (!expressionResult.HasComplexIndexer)
            {
                // allocate receiver (1D array with size 1 for scalar result, matrix (vector) in other cases)
                ExpressionList ctorExpr = new ExpressionList();
                for (int index = 0; index < receiverComputeType.Rank; index++)
                {
                    ctorExpr.Add(NodeHelper.GetConstantIndexerForExpression(expressionResult.SizeIdentifier, index));
                }
                state.Constructor.Body.Statements.Add(
                    new AssignmentStatement {
                    Target = new AddressDereference {
                        Address = receiverDataIdentifier,
                        Type    = STANDARD.Data,
                    },
                    Source = new Construct {
                        Constructor = new MemberBinding {
                            BoundMember = STANDARD.Data.GetConstructor(SystemTypes.Array),
                        },
                        Operands = new ExpressionList(
                            new ConstructArray {
                            ElementType = expressionResult.Type.ScalarType.TypeNode,
                            Rank        = (methodStruct.Type is ARRAY_TYPE) ? receiverComputeType.Rank : 1,
                            Operands    = (methodStruct.Type is ARRAY_TYPE) ? ctorExpr : new ExpressionList(Literal.Int32One),
                        }
                            ),
                    }
                }
                    );
            }
            else
            {
                state.Constructor.Body.Statements.Add(new Block {
                    Statements = ConversionHelper.GenerateIndexedSize(expressionResult, receiverComputeType, receiverDataIdentifier, state.GetNextTempSizeIdentifier())
                });
            }
            #endregion

            #region // generate kernel
            ConversionResult?result = GenereteKernel(state, expressionResult, Identifier.For("buffer" + receiverArgument.Index.ToString()), methodStruct);
            ConversionResult finalConversionResult;
            if (result.HasValue)
            {
                finalConversionResult = result.Value;
            }
            else
            {
                return(null);
            }
            #endregion

            #region // generate delegates
            DelegateNode getOpenCLTimeDelegateType;
            DelegateNode startOpenCLDelegateType;
            ConversionHelper.GenerateOpenCLDelegates(state, out getOpenCLTimeDelegateType, out startOpenCLDelegateType);
            #endregion

            #region // generate get time method
            ConversionHelper.GenerateTimeMethod(state);
            #endregion

            #region // generate the codelets
            Identifier codeletsIdentifier;
            ConversionHelper.GenerateCodelets(state, getOpenCLTimeDelegateType, startOpenCLDelegateType, out codeletsIdentifier);
            #endregion

            #region // process all arguments - add them to parameters and data uses
            ExpressionList  ctorArgs   = new ExpressionList();
            ExpressionList  callArgs   = new ExpressionList();
            ParameterList   callParams = new ParameterList();
            List <TypeNode> typeList   = new List <TypeNode>();

            Identifier dataUsesIdentifier;
            ConversionHelper.ProcessArguments(state, sortedArguments, scalarArguments, complexIndexer, startOpenCLDelegateType, out dataUsesIdentifier, ref callParams, ref callArgs, ref state.Constructor.Parameters, ref ctorArgs, ref typeList);

            #endregion

            ConversionHelper.GenerateSubmitCodelet(state, codeletsIdentifier, dataUsesIdentifier);
            ConversionHelper.FinishOperation(state, finalConversionResult);

            Class actualOperationClass = CONTEXT._operationRegistry.RegisterOperation(finalConversionResult.CompleteExpression, state.Class);

            #region // create method 'call'
            Identifier callIdentifier = Identifier.For("call");
            Method     callMethod     = actualOperationClass.GetMethod(callIdentifier, typeList.ToArray());
            Expression returnExp;
            if (methodStruct.Type is ARRAY_TYPE)
            {
                returnExp = receiverIdentifier;
            }
            else
            {
                returnExp = new BinaryExpression {
                    NodeType = NodeType.Castclass,
                    Operand2 = new MemberBinding {
                        BoundMember = expressionResult.Type.ScalarType.TypeNode.GetArrayType(1)
                    },
                    Operand1 = new MethodCall {
                        Callee = new MemberBinding {
                            TargetObject = receiverIdentifier,
                            BoundMember  = STANDARD.Data.GetMethod(Identifier.For("GetHostArray")),
                        },
                    }
                };
            }
            if (methodStruct.Type is ARRAY_TYPE)
            {
            }
            else
            {
                returnExp = NodeHelper.GetConstantIndexerForExpression(returnExp, 0);
                if (methodStruct.Type is BOOLEAN_TYPE)
                {
                    // if it was a boolean operation invert the value (1 is false in OpenCL kernel)
                    returnExp = new BinaryExpression {
                        NodeType = NodeType.Eq,
                        Operand1 = returnExp,
                        Operand2 = Literal.Int32Zero
                    };
                }
            }
            if (callMethod == null)
            {
                actualOperationClass.Members.Add(new Method {
                    DeclaringType = state.Class,
                    Flags         = MethodFlags.Static,
                    ReturnType    = (methodStruct.Type is ARRAY_TYPE) ? STANDARD.Data : methodStruct.Type.convert() as TypeNode /*receiverComputeType.ScalarType.TypeNode*/,
                    Parameters    = callParams,
                    Name          = callIdentifier,
                    Body          = new Block {
                        Statements = new StatementList(
                            new VariableDeclaration {
                            Name = receiverIdentifier,
                            Type = STANDARD.Data,
                        },
                            new ExpressionStatement(new Construct {
                            Constructor = new MemberBinding {
                                BoundMember = actualOperationClass.GetConstructors()[0],
                            },
                            Operands = ctorArgs,
                        }),

                            new Return(returnExp)
                            )
                    }
                });
            }
            #endregion

            #region // return call to 'call'
            return(new MethodCall {
                Operands = callArgs,
                Callee = new MemberBinding(null, actualOperationClass.GetMethod(callIdentifier, typeList.ToArray())),
                Type = expressionResult.Type.ScalarType.TypeNode,
            });

            #endregion
        }
Beispiel #28
0
        public override Expression VisitMethodCall(MethodCall call)
        {
            // We only reach this point for calls to predicate methods within "wait"
            // join conditions.
            ZMethod method = (ZMethod)((MemberBinding)call.Callee).BoundMember;

            ExpressionList ctorArgs;
            QualifiedIdentifier methodClass = new QualifiedIdentifier(
                new QualifiedIdentifier(
                    new QualifiedIdentifier(Identifier.For("Z"), Identifier.For("Application")),
                    method.DeclaringType.Name),
                method.Name);

            MethodCall predCall =
                new MethodCall(
                    new QualifiedIdentifier(Identifier.For("p"), Identifier.For("CallPredicateMethod")),
                    new ExpressionList(
                        new Construct(
                            new MemberBinding(null, new TypeExpression(methodClass)),
                            ctorArgs = new ExpressionList())));

            ctorArgs.Add(Identifier.For("application"));

            if (!method.IsStatic)
                ctorArgs.Add(this.VisitExpression(((MemberBinding)call.Callee).TargetObject));

            for (int i = 0, n = call.Operands.Count; i < n; i++)
                ctorArgs.Add(this.VisitExpression(call.Operands[i]));

            return predCall;
        }
Beispiel #29
0
        public void NodeQuery_BuildFromXml()
        {
            SchemaEditor editor        = new SchemaEditor();
            NodeType     nodeType1     = editor.CreateNodeType(null, "nodeType1");
            NodeType     nodeType2     = editor.CreateNodeType(null, "nodeType2");
            PropertyType stringSlot1   = editor.CreatePropertyType("stringSlot1", DataType.String);
            PropertyType stringSlot2   = editor.CreatePropertyType("stringSlot2", DataType.String);
            PropertyType intSlot1      = editor.CreatePropertyType("intSlot1", DataType.Int);
            PropertyType intSlot2      = editor.CreatePropertyType("intSlot2", DataType.Int);
            PropertyType dateTimeSlot1 = editor.CreatePropertyType("dateTimeSlot1", DataType.DateTime);
            PropertyType dateTimeSlot2 = editor.CreatePropertyType("dateTimeSlot2", DataType.DateTime);
            PropertyType currencySlot1 = editor.CreatePropertyType("currencySlot1", DataType.Currency);
            PropertyType currencySlot2 = editor.CreatePropertyType("currencySlot2", DataType.Currency);
            PropertyType refSlot1      = editor.CreatePropertyType("refSlot1", DataType.Reference);
            PropertyType refSlot2      = editor.CreatePropertyType("refSlot2", DataType.Reference);

            NodeQuery query = new NodeQuery();

            //==== Operators
            ExpressionList strOpExp = new ExpressionList(ChainOperator.Or);

            query.Add(strOpExp);
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.Contains, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.EndsWith, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.Equal, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.GreaterThan, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.GreaterThanOrEqual, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.LessThan, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.LessThanOrEqual, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.NotEqual, "{path}"));
            strOpExp.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, "{path}"));

            //==== StringExpression
            ExpressionList strExp = new ExpressionList(ChainOperator.Or);

            query.Add(strExp);
            strExp.Add(new StringExpression(stringSlot1, StringOperator.Equal, "{value}"));
            strExp.Add(new StringExpression(stringSlot1, StringOperator.Equal, stringSlot2));
            strExp.Add(new StringExpression(stringSlot1, StringOperator.Equal, StringAttribute.Path));
            strExp.Add(new StringExpression(stringSlot1, StringOperator.Equal, (string)null));
            strExp.Add(new StringExpression(StringAttribute.Name, StringOperator.Equal, "{value}"));
            strExp.Add(new StringExpression(StringAttribute.Name, StringOperator.Equal, stringSlot2));
            strExp.Add(new StringExpression(StringAttribute.Name, StringOperator.Equal, StringAttribute.Path));
            strExp.Add(new StringExpression(StringAttribute.Name, StringOperator.Equal, (string)null));

            //==== IntExpression
            ExpressionList intExp = new ExpressionList(ChainOperator.Or);

            query.Add(intExp);
            intExp.Add(new IntExpression(IntAttribute.Index, ValueOperator.Equal, 123));
            intExp.Add(new IntExpression(IntAttribute.Index, ValueOperator.Equal, IntAttribute.MajorVersion));
            intExp.Add(new IntExpression(IntAttribute.Index, ValueOperator.Equal, intSlot2));
            intExp.Add(new IntExpression(IntAttribute.Index, ValueOperator.Equal, (int?)null));
            intExp.Add(new IntExpression(intSlot1, ValueOperator.Equal, 123));
            intExp.Add(new IntExpression(intSlot1, ValueOperator.Equal, IntAttribute.MajorVersion));
            intExp.Add(new IntExpression(intSlot1, ValueOperator.Equal, intSlot2));
            intExp.Add(new IntExpression(intSlot1, ValueOperator.Equal, (int?)null));

            //==== DateTimeExpression
            ExpressionList dtExp = new ExpressionList(ChainOperator.Or);

            query.Add(dtExp);
            dtExp.Add(new DateTimeExpression(DateTimeAttribute.CreationDate, ValueOperator.Equal, DateTime.Now));
            dtExp.Add(new DateTimeExpression(DateTimeAttribute.CreationDate, ValueOperator.Equal, DateTimeAttribute.ModificationDate));
            dtExp.Add(new DateTimeExpression(DateTimeAttribute.CreationDate, ValueOperator.Equal, dateTimeSlot2));
            dtExp.Add(new DateTimeExpression(DateTimeAttribute.CreationDate, ValueOperator.Equal, (DateTime?)null));
            dtExp.Add(new DateTimeExpression(dateTimeSlot1, ValueOperator.Equal, DateTime.Now));
            dtExp.Add(new DateTimeExpression(dateTimeSlot1, ValueOperator.Equal, DateTimeAttribute.ModificationDate));
            dtExp.Add(new DateTimeExpression(dateTimeSlot1, ValueOperator.Equal, dateTimeSlot2));
            dtExp.Add(new DateTimeExpression(dateTimeSlot1, ValueOperator.Equal, (DateTime?)null));

            //==== CurrencyExpression
            ExpressionList curExp = new ExpressionList(ChainOperator.Or);

            query.Add(curExp);
            curExp.Add(new CurrencyExpression(currencySlot1, ValueOperator.Equal, (decimal)123.456));
            curExp.Add(new CurrencyExpression(currencySlot1, ValueOperator.Equal, currencySlot2));
            curExp.Add(new CurrencyExpression(currencySlot1, ValueOperator.Equal, (decimal?)null));

            //==== ReferenceExpression
            ExpressionList subExp = new ExpressionList(ChainOperator.And);

            subExp.Add(new IntExpression(IntAttribute.Index, ValueOperator.GreaterThan, 123));
            subExp.Add(new DateTimeExpression(DateTimeAttribute.CreationDate, ValueOperator.GreaterThan, DateTime.Now));
            ExpressionList refExp = new ExpressionList(ChainOperator.Or);

            query.Add(refExp);
            refExp.Add(new ReferenceExpression(refSlot1));
            refExp.Add(new ReferenceExpression(ReferenceAttribute.LockedBy));
            refExp.Add(new ReferenceExpression(refSlot1, (Node)null));
            refExp.Add(new ReferenceExpression(refSlot1, Repository.Root));
            refExp.Add(new ReferenceExpression(ReferenceAttribute.LockedBy, (Node)null));
            refExp.Add(new ReferenceExpression(ReferenceAttribute.LockedBy, Repository.Root));
            refExp.Add(new ReferenceExpression(refSlot1, subExp));
            refExp.Add(new ReferenceExpression(ReferenceAttribute.LockedBy, subExp));

            //==== TypeExpression
            ExpressionList typeExp = new ExpressionList(ChainOperator.Or);

            query.Add(typeExp);
            typeExp.Add(new TypeExpression(nodeType1));
            typeExp.Add(new TypeExpression(nodeType2, true));

            //==== Negation
            Expression negExp = new NotExpression(
                new ExpressionList(ChainOperator.And,
                                   new StringExpression(StringAttribute.Path, StringOperator.StartsWith, "/Root1/"),
                                   new StringExpression(StringAttribute.Name, StringOperator.NotEqual, "name")
                                   ));

            query.Add(negExp);

            //==== Orders
            query.Orders.Add(new SearchOrder(DateTimeAttribute.ModificationDate, OrderDirection.Desc));
            query.Orders.Add(new SearchOrder(IntAttribute.MajorVersion, OrderDirection.Asc));
            query.Orders.Add(new SearchOrder(StringAttribute.Name, OrderDirection.Asc));

            //==== Paging
            query.PageSize   = 123;
            query.StartIndex = 987;

            string            queryString    = query.ToXml();
            NodeQueryAccessor queryAcc       = new NodeQueryAccessor(new NodeQuery());
            NodeQuery         newQuery       = queryAcc.Parse(queryString, editor);
            string            newQueryString = newQuery.ToXml();

            Assert.IsTrue(queryString != null && queryString == newQueryString);
        }
 public void Append(string literal)
 {
     ExpressionList.Add(new LiteralExpression(literal));
 }
Beispiel #31
0
        private Expression DecompileBooleanExpression(Block b)
        {
            ExpressionList eList = new ExpressionList();
            Expression     e     = null;
            int            i     = 0;

            while (i < b.Statements.Count)
            {
                if (b.Statements[i] is Branch)
                {
                    break;
                }
                Statement s = b.Statements[i];
                i++;
                if (s == null || s.NodeType == NodeType.Nop)
                {
                    continue;
                }
                ExpressionStatement es = s as ExpressionStatement;
                if (es != null)
                {
                    MethodCall mc = es.Expression as MethodCall;
                    if (mc != null)
                    {
                        MemberBinding mb = mc.Callee as MemberBinding;
                        if (mb != null)
                        {
                            Method m = mb.BoundMember as Method;
                            if (m != null)
                            {
                                if (this.contractNodes.IsPlainPrecondition(m) || this.contractNodes.IsPostcondition(m))
                                {
                                    eList.Add(mc.Operands[0]);
                                }
                                else
                                {
                                    eList.Add(es.Expression);
                                }
                            }
                        }
                        else
                        {
                            eList.Add(es.Expression);
                        }
                    }
                    else
                    {
                        eList.Add(SimplifyLiteral(es.Expression));
                    }
                }
            }
            if (i == b.Statements.Count) // no branch at end of block
            {
                return(eList[0]);
            }
            Branch br = b.Statements[b.Statements.Count - 1] as Branch;

            if (br.Condition == null) // unconditional branch
            {
                return(eList[0]);
            }
            e = TypeReconstructorAndExpressionSimplifier.ReconstructBooleanExpression(br.Condition); // should be: e = Combine(e, br.Condition);
            Expression trueBranch  = DecompileBooleanExpression(br.Target);
            Expression falseBranch = DecompileBooleanExpression(blocks[((int)block2Index[b.UniqueKey]) + 1]);
            Expression result      = Ternary(e, trueBranch, falseBranch);

            return(result);
        }
Beispiel #32
0
    void AddCallSerializer(TypeNode srcType, StatementList statements, Expression src, Identifier writer, Expression rootName, Expression rootNamespace ) {

      TypeNode type = Unwrap(srcType);

      Class memberSerializer = this.CreateSerializerFor(type);
      // call the Serialize method on it, passing the member we're serializing.
      ExpressionList args = new ExpressionList();
      args.Add(src);
      args.Add(writer);
      args.Add(rootName);
      args.Add(rootNamespace);
      MethodCall call = new MethodCall();
      Method serialize = memberSerializer.GetMethod(Identifier.For("Serialize"), new TypeNode[4] { type, Runtime.XmlSerializationWriter, SystemTypes.String, SystemTypes.String} );
      call.Callee = new MemberBinding(new MemberBinding(null, memberSerializer), serialize);
      call.Operands = args;
      statements.Add( new ExpressionStatement( call ) );    
    }
Beispiel #33
0
    void AddCallDeserializer(TypeNode type, StatementList statements, Identifier reader, 
      Expression target, Expression required, Expression result) {

      Class memberSerializer = this.CreateSerializerFor(type);      
      // call the Deserialize method on it, and assign result to target object.
      ExpressionList args = new ExpressionList();
      args.Add(reader);
      args.Add(required);
      if (result is Local) 
        result = new UnaryExpression(result, NodeType.AddressOf);
      args.Add(result);
      MethodCall call = new MethodCall();
      Method deserialize = memberSerializer.GetMethod(Identifier.For("Deserialize"), new TypeNode[3] { Runtime.XmlSerializationReader, SystemTypes.Boolean, SystemTypes.Boolean.GetReferenceType() } );
      call.Callee = new MemberBinding(new MemberBinding(null, memberSerializer), deserialize);
      call.Operands = args;
      statements.Add(new AssignmentStatement(target, call));
    }
Beispiel #34
0
 public VisitedExpression Append(string literal)
 {
     ExpressionList.Add(new LiteralExpression(literal));
     return(this);
 }
Beispiel #35
0
    /// <returns>A list of expression that should, by default, be tried as witness for the consistency of an expression of witnessType</returns>
    private static ExpressionList GetDefaultWitnesses(TypeNode witnessType) {
      ExpressionList result = new ExpressionList();

      if (witnessType.IsPrimitiveNumeric || witnessType == SystemTypes.Char) {
        result.Add(new Literal(0, witnessType, new SourceContext()));
        result.Add(new Literal(1, witnessType, new SourceContext()));
      } else if (witnessType is Struct) //for user-defined structs, return new S() as default (null doesn't work).
        //Note that primitive numeric types are also structs, so the order of the if and else brach matters.
        result.Add(new Local(StandardIds.NewObj, witnessType, new SourceContext()));
      else
        result.Add(new Literal(null, witnessType, new SourceContext()));

      //special-case String! and object! (for which we know a consistent constructor)
      OptionalModifier possibleNonNullType = (witnessType as OptionalModifier);
      TypeNode t = (possibleNonNullType != null ? possibleNonNullType.ModifiedType : null);
      if (witnessType == SystemTypes.String || witnessType == SystemTypes.Object || t == SystemTypes.String || t == SystemTypes.Object)
        result.Add(new Literal("Let's Boogie!", witnessType));

      return result;
    }
    public virtual Differences VisitExpressionList(ExpressionList list1, ExpressionList list2,
      out ExpressionList changes, out ExpressionList deletions, out ExpressionList insertions){
      changes = list1 == null ? null : list1.Clone();
      deletions = list1 == null ? null : list1.Clone();
      insertions = list1 == null ? new ExpressionList() : list1.Clone();
      //^ assert insertions != null;

      Differences differences = new Differences();
      for (int j = 0, n = list2 == null ? 0 : list2.Count; j < n; j++){
        //^ assert list2 != null;
        Expression nd2 = list2[j];
        if (nd2 == null) continue;
        insertions.Add(null);
      }
      TrivialHashtable savedDifferencesMapFor = this.differencesMapFor;
      this.differencesMapFor = null;
      TrivialHashtable matchedNodes = new TrivialHashtable();
      for (int i = 0, k = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
        //^ assert list1 != null && changes != null && deletions != null;
        Expression nd1 = list1[i]; 
        if (nd1 == null) continue;
        Differences diff;
        int j;
        Expression nd2 = this.GetClosestMatch(nd1, list1, list2, i, ref k, matchedNodes, out diff, out j);
        if (nd2 == null || diff == null){Debug.Assert(nd2 == null && diff == null); continue;}
        matchedNodes[nd1.UniqueKey] = nd1;
        matchedNodes[nd2.UniqueKey] = nd2;
        changes[i] = diff.Changes as Expression;
        deletions[i] = diff.Deletions as Expression;
        insertions[i] = diff.Insertions as Expression;
        insertions[n+j] = nd1; //Records the position of nd2 in list2 in case the change involved a permutation
        Debug.Assert(diff.Changes == changes[i] && diff.Deletions == deletions[i] && diff.Insertions == insertions[i]);
        differences.NumberOfDifferences += diff.NumberOfDifferences;
        differences.NumberOfSimilarities += diff.NumberOfSimilarities;
      }
      //Find deletions
      for (int i = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
        //^ assert list1 != null && changes != null && deletions != null;
        Expression nd1 = list1[i]; 
        if (nd1 == null) continue;
        if (matchedNodes[nd1.UniqueKey] != null) continue;
        changes[i] = null;
        deletions[i] = nd1;
        insertions[i] = null;
        differences.NumberOfDifferences += 1;
      }
      //Find insertions
      for (int j = 0, n = list1 == null ? 0 : list1.Count, m = list2 == null ? 0 : list2.Count; j < m; j++){
        //^ assert list2 != null;
        Expression nd2 = list2[j]; 
        if (nd2 == null) continue;
        if (matchedNodes[nd2.UniqueKey] != null) continue;
        insertions[n+j] = nd2;  //Records nd2 as an insertion into list1, along with its position in list2
        differences.NumberOfDifferences += 1; //REVIEW: put the size of the tree here?
      }
      if (differences.NumberOfDifferences == 0){
        changes = null;
        deletions = null;
        insertions = null;
      }
      this.differencesMapFor = savedDifferencesMapFor;
      return differences;
    }
Beispiel #37
0
    protected static Expression GetInferredWitness(ExpressionList eListIn, TypeNode resultType, Member theModelfield) {
      #region Split Conjunct and Disjuncts into NoAndOrList, then look for this.mf == P or this.mf <==> P, return P if found
      ExpressionList splitAndList = new ExpressionList();            
      foreach (Expression e in eListIn)         
        foreach (Expression e2 in SplitConjuncts(e))
          splitAndList.Add(e2);
      
      Expression inferredWitness = null; //stores the witness that we are constructing.
      //eList is a list of ensures or satisfies clauses.
      //if eList contains an expression "this.theModelfield == B", then either B is a witness or the mfC does not have a witness.      
      foreach (Expression e in splitAndList) {
        if (e.NodeType == NodeType.Eq || e.NodeType == NodeType.Iff) {        
          inferredWitness = Checker.GetWitnessHelper(e, theModelfield);
          if (inferredWitness != null)
            return inferredWitness; //witness found          
        }
      }

      //split conjuncts and disjuncts for better chance of finding witness:
      //ignore, will be replace anyway
      /*
      ExpressionList splitAndOrList = new ExpressionList();
      foreach (Expression e in splitAndList)
        WitnessAndOrSplit(e, splitAndOrList);

       */
      ExpressionList splitAndOrList = splitAndList;

      //try again
      foreach (Expression e in splitAndOrList) {
        if (e.NodeType == NodeType.Eq) {        
          inferredWitness = Checker.GetWitnessHelper(e, theModelfield);
          if (inferredWitness != null)
            return inferredWitness; //witness found          
        }
      }
      #endregion

      /*
      foreach (Expression e in eList) {
        BinaryExpression eBinary = e as BinaryExpression;
        if (eBinary != null && e.NodeType == NodeType.Eq) {
          //equality found. Check if it is of the shape this.mf == P (where mf is the modelfield). If so, either P is a witness, or no witness exists.           
          MemberBinding posMf = eBinary.Operand1 as MemberBinding;
          //can't compare against theModelfieldBinding as they are not the same object. 
          //not completely sure if the This check is good enough (no type info) but I think it should be enough (can't be of the wrong type as type is added automatically)
          if (posMf != null && posMf.TargetObject is This && posMf.BoundMember == theModelfield)
            return eBinary.Operand2;
          posMf = eBinary.Operand2 as MemberBinding;
          if (posMf != null && posMf.TargetObject is This && posMf.BoundMember == theModelfield)
            return eBinary.Operand1;          
        }
      }
      */

      //no equalities.                
      if (resultType.IsPrimitiveNumeric || resultType == SystemTypes.Char) {
        #region try numeric heuristics and return result
        //Lets try our heuristics for >, <, <=, >=, !=.            
        bool greaterOk = true;
        bool smallerOk = true;
        foreach (Expression e in splitAndOrList) {          
          Expression improver = Checker.GetWitnessHelper(e, theModelfield);
          if (improver == null) continue; //Not of the shape "this.themodelfield op B", no heuristic applies: we have to hope that the witness we come up with will satisfy this constraint.
          NodeType addOrSub = NodeType.DefaultValue;
          bool improve = true;
          if (e.NodeType == NodeType.Ge && greaterOk) { //improve witness to max(inferredWitness, improver)
            smallerOk = false;
          } else if (e.NodeType == NodeType.Gt && greaterOk) { //improve witness to max(inferredWitness, improver + 1)
            addOrSub = NodeType.Add;
            smallerOk = false;
          } else if (e.NodeType == NodeType.Le && smallerOk) {//improve witness to min(inferredWitness, improver)
            greaterOk = false;
          } else if (e.NodeType == NodeType.Lt && smallerOk) {//improve witness to min(inferredWitness, improver - 1)
            addOrSub = NodeType.Sub;
            greaterOk = false;
          } else if (e.NodeType == NodeType.Ne) {
            if (greaterOk)
              addOrSub = NodeType.Add; //improve witness to inferredWitness != improver ? inferredWitness : improver + 1)
            else if (smallerOk)
              addOrSub = NodeType.Sub; //improve witness to inferredWitness != improver ? inferredWitness : improver - 1)
            //do not change greaterOk and smallerOk: any value but improver is ok as a witness
          } else
            improve = false;
          if (improve) {
            Expression condition = new BinaryExpression(inferredWitness, improver, e.NodeType, new TypeExpression(new Literal(TypeCode.Boolean), 0));             
            if (addOrSub != NodeType.DefaultValue)
              improver = new BinaryExpression(improver, new Literal(1, resultType), addOrSub, resultType);            
            if (inferredWitness == null)
              inferredWitness = improver;
            else {              
              inferredWitness = new TernaryExpression(condition, inferredWitness, improver, NodeType.Conditional, inferredWitness.Type);
            }              
          }
        }
        if (inferredWitness == null)
          inferredWitness = new Literal(0, resultType); //no witness candidate found, try 0 and hope for the best.        
        return inferredWitness;
        #endregion
      } else if (resultType.TypeCode == System.TypeCode.Boolean) {
        #region try boolean heuristics and return result
        //Try heuristics for ==> and != (note that we already checked for equalities in noAndOrList)
        inferredWitness = new Literal(false, resultType); //false deals with this.theModelfield ==> P
        Expression improver;
        foreach (Expression e in splitAndOrList) {
          if (e.NodeType == NodeType.Ne) {
            improver = Checker.GetWitnessHelper(e, theModelfield);
            if (improver != null) { //this.theModelfield != improver found.
              return new UnaryExpression(improver, NodeType.Neg); //improve witness to !inferredWitness and return.              
            }
          } 
          if (e.NodeType != NodeType.Implies) continue; //no heuristic applies.
          improver = Checker.GetWitnessHelper(e, theModelfield, false);
          if (improver != null) //found improver ==> this.theModelfield. Improve witness to inferredWitness || improver.
            inferredWitness = new BinaryExpression(inferredWitness, improver, NodeType.Or);          
        }        
        return inferredWitness;        
        #endregion
      }
      //no heuristic applies. Return a default witness.
      return Checker.GetDefaultWitnesses(resultType)[0]; //Allowing multiple witnesses for modelfields has not been implemented yet. Just return the first one for now.
       
                 
    }
Beispiel #38
0
        // The method added by Jiri Adamek
        // It generates NAtiveZOM calls
        private void GenerateNativeZOMCall(Block block, MethodCall call, bool callIsAsync, AssignmentStatement assignmentStatement)
        {
            ZMethod method = (ZMethod)((MemberBinding)call.Callee).BoundMember;

            // Eventually, this will be checked by an earlier phase.
            Debug.Assert(method.Parameters.Count == call.Operands.Count);

            // Asynchronous calls
            Debug.Assert(!callIsAsync, "async not supporrted for NativeZOM calls");

            // Debugging - parameters
            for (int i = 0, n = call.Operands.Count; i < n; i++)
            {
                Parameter param = method.Parameters[i];

                Debug.Assert(param != null);

                // In fact, call.operands[i] MAY BE null due to the error recovery (if the type of the
                // expression does not match the type in the method definition)
                //
                // Debug.Assert(call.Operands[i] != null);

                Debug.Assert((param.Flags & ParameterFlags.Out) == 0, "out parameters not supported for NativeZOM calls");
            }

            Expression typename = new QualifiedIdentifier(new Identifier("Microsoft.Zing"), method.DeclaringType.Name);
            Expression callee;

            if (!method.IsStatic)
            {
                callee = Templates.GetExpressionTemplate("NativeZOMCallee");
                Replacer.Replace(callee, "_TypeName", typename);
                Expression pointer = this.VisitExpression(((MemberBinding)call.Callee).TargetObject);
                Replacer.Replace(callee, "_Pointer", pointer);
                Replacer.Replace(callee, "_MethodName", method.Name);
            }
            else
            {
                callee = Templates.GetExpressionTemplate("NativeZOMStaticCall");
                Replacer.Replace(callee, "_ClassName", typename);
                Replacer.Replace(callee, "_MethodName", method.Name);
            }

            ExpressionList argumentList = new ExpressionList();
            argumentList.Add(Templates.GetExpressionTemplate("NativeZOMCallFirstArgument"));
            foreach (Expression operand in call.Operands) argumentList.Add(this.VisitExpression(operand));
            MethodCall nativeCall = new MethodCall(callee, argumentList);

            Statement newStatement;
            if (assignmentStatement != null)
            {
                newStatement = Templates.GetStatementTemplate("NativeZOMCallWithAssignment");
                Replacer.Replace(newStatement, "_Dest", this.VisitExpression(assignmentStatement.Target));
                Replacer.Replace(newStatement, "_Source", nativeCall);
            }
            else
            {
                newStatement = new ExpressionStatement(nativeCall);
            }

            block.Statements.Add(newStatement);
        }
Beispiel #39
0
 public static void SplitConjuncts(Expression e, ExpressionList el) {
   if (e == null) return;
   BinaryExpression be = e as BinaryExpression;
   if (be == null) { el.Add(e); return; }
   if (be.NodeType != NodeType.LogicalAnd) { el.Add(e); return; }
   SplitConjuncts(be.Operand1, el);
   SplitConjuncts(be.Operand2, el);
 }
        private Content[] GetFeed2Private(string feedPath, bool onlyFiles, bool onlyFolders, int start, int limit)
        {
            Node container = GetNodeById(feedPath);

            if (container == null)
            {
                throw new NodeLoadException("Error loading path");
            }
            IFolder folder = container as IFolder;

            if (folder == null)
            {
                return new Content[] { }
            }
            ;

            IEnumerable <Node> nodeList;
            NodeQuery          query;

            if (onlyFiles || onlyFolders)
            {
                nodeList = onlyFiles ?
                           from child in folder.Children where child is IFile select child :
                           from child in folder.Children where child is IFolder select child;
            }
            else
            {
                //nodeList = folder.Children;
                if (start == 0 && limit == 0)
                {
                    nodeList = folder.Children;
                }
                else
                {
                    SmartFolder smartFolder = folder as SmartFolder;
                    if (folder is SmartFolder)
                    {
                        query = new NodeQuery();
                        string queryString = ((SmartFolder)folder).Query;

                        ExpressionList orExp = new ExpressionList(ChainOperator.Or);

                        if (!string.IsNullOrEmpty(queryString))
                        {
                            orExp.Add(NodeQuery.Parse(queryString));
                        }

                        orExp.Add(new IntExpression(IntAttribute.ParentId, ValueOperator.Equal, container.Id));
                        query.Add(orExp);
                    }
                    else
                    {
                        query = new NodeQuery();
                        query.Add(new IntExpression(IntAttribute.ParentId, ValueOperator.Equal, container.Id));
                    }
                    query.PageSize   = limit;
                    query.StartIndex = start == 0 ? 1 : start;
                    nodeList         = query.Execute().Nodes;
                }
            }

            return(nodeList.Select(node => new Content(node, false, false, false, false, start, limit)).ToArray());
        }
Beispiel #41
0
 /// <summary>
 /// <para>
 /// Serializes the expressions in toSerialize to an attribute determined by ctor, as if they come from module containingModule.
 /// Uses the SourceContext information of <param name="sc">sc</param> for the source context for the attribute.
 /// </para>
 /// <para><code>
 /// requires ctor != null &amp;&amp; sc != null;
 /// </code></para>
 /// <para><code>
 /// requires ctor.DeclaringType &lt;: Microsoft.Contracts.AttributeWithContext;
 /// </code></para>
 /// </summary>
 /// <returns></returns>
 public static AttributeNode SerializeExpressions(InstanceInitializer/*!*/ ctor, ExpressionList dontSerialize, ExpressionList toSerialize, SourceContext/*!*/ sc, Module containingModule) {
   MemberBinding attrBinding = new MemberBinding(null, ctor);
   ExpressionList args = new ExpressionList();
   if (dontSerialize != null) {
     foreach (Expression e in dontSerialize) {
       args.Add(e);
     }
   }
   if (toSerialize != null) {
     foreach (Expression e in toSerialize) {
       ContractSerializer cs = new ContractSerializer(containingModule);
       cs.Visit(e);
       string val = cs.SerializedContract;
       args.Add(new Literal(val, SystemTypes.String));
     }
   }
   if (sc.SourceText != null) {
     args.Add(new NamedArgument(Identifier.For("Filename"), new Literal(sc.Document.Name, SystemTypes.String)));
     args.Add(new NamedArgument(Identifier.For("StartLine"), new Literal(sc.StartLine, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("StartColumn"), new Literal(sc.StartColumn, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("EndLine"), new Literal(sc.EndLine, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("EndColumn"), new Literal(sc.EndColumn, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("SourceText"), new Literal(sc.SourceText, SystemTypes.String)));
   }
   return new AttributeNode(attrBinding, args, (AttributeTargets)0);
 }    
Beispiel #42
0
    void AddReadStream(Block block, TypeNode type, StatementList statements, Identifier reader, 
      Expression target, Expression result){
      // Read next element and figure out if it matches the stream element type, if so read it and add it to the list
      // If not, then return (throw an error if there are no items and the list is the non-empty type).

      // flexArray = new flexarray();
      // while (reader.Read() && read.NodeType != XmlNodeType.EndElement) {
      //    if (reader.NodeType == XmlNodeType.Element) {
      //      readchild(flexarray);
      //    }
      // }
      // target = flexArray; 

      Local nameLocal = new Local(Identifier.For("name"),SystemTypes.String, block);
      Local nsLocal = new Local(Identifier.For("ns"),SystemTypes.String, block);
      Local nodeType = new Local(Identifier.For("nodeType"),Runtime.XmlNodeType, block);
      Local optional = new Local(Identifier.Empty, SystemTypes.Boolean, block);
      Local foundChild = new Local(Identifier.Empty, SystemTypes.Boolean, block);
      statements.Add(new AssignmentStatement(optional, Literal.False));

      TypeNode eType = Checker.GetCollectionElementType(type);
      Local local = new Local(Identifier.Empty, eType, block);
      Method addMethod = null;
      Local localArray = null;

      if (type.Template == SystemTypes.GenericBoxed) {

        addMethod = null; // only needs one!

      } else if (Checker.IsGenericList(type)) {
        //TODO: this call is invalid if the eType is not public
        TypeNode flexArrayType = SystemTypes.GenericList.GetTemplateInstance(this.module, eType);
        localArray = new Local(Identifier.For("stream"+streamCount++), flexArrayType, block);

        statements.Add(new AssignmentStatement(localArray,
          new Construct(new MemberBinding(null, flexArrayType), new ExpressionList(), flexArrayType)));

        addMethod = flexArrayType.GetMethod(Identifier.For("Add"), eType);
      } else  {        
        TypeNode arrayType = SystemTypes.ArrayList;
        localArray = new Local(Identifier.Empty, arrayType, block);
        statements.Add(new AssignmentStatement(localArray,
          new Construct(new MemberBinding(null, arrayType), new ExpressionList(), arrayType)));

        addMethod = arrayType.GetMethod(Identifier.For("Add"), SystemTypes.Object);
      }

      Block whileBody = new Block(new StatementList());
      MethodCall moveToContent = new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList());
      BinaryExpression notAtEnd = new BinaryExpression(moveToContent, 
        new QualifiedIdentifier(Identifier.For("XmlNodeType"), Identifier.For("EndElement")), NodeType.Ne);
      BinaryExpression notEOF = new BinaryExpression(
        new QualifiedIdentifier(reader, Identifier.For("EOF")), Literal.True, NodeType.Ne);

      While w = new While(new BinaryExpression(notAtEnd, notEOF, NodeType.And), whileBody);
      statements.Add(w);

      whileBody.Statements.Add(new AssignmentStatement(nameLocal, new QualifiedIdentifier(reader, Identifier.For("LocalName"))));
      whileBody.Statements.Add(new AssignmentStatement(nsLocal, new QualifiedIdentifier(reader, Identifier.For("NamespaceURI"))));
      whileBody.Statements.Add(new AssignmentStatement(nodeType, new QualifiedIdentifier(reader, Identifier.For("NodeType"))));

      StatementList trueStatements = whileBody.Statements;
      if (type.Template == SystemTypes.GenericBoxed){
        type = Checker.GetCollectionElementType(type);
      }

      trueStatements.Add(new AssignmentStatement(foundChild, Literal.False));

      if (eType is TupleType || eType is TypeUnion || IsStream(eType)) {
        AddCallDeserializer(eType, trueStatements, reader, local, optional, foundChild);        
      } else  {
        AddReadChild(whileBody, trueStatements, Checker.GetDefaultElementName(eType), eType, local, reader, foundChild, true, false);
      }

      If ifFound = new If(new BinaryExpression(foundChild, Literal.True, NodeType.Eq),
        new Block(new StatementList()), new Block(new StatementList()));
      ifFound.TrueBlock.Statements.Add(new AssignmentStatement(result, Literal.True)); // set our result to true then.
      ifFound.FalseBlock.Statements.Add(new Exit()); // break out of loop then.

      trueStatements.Add(ifFound);

      if (addMethod == null) {        
        trueStatements.Add(new AssignmentStatement(target, 
          CastTo(local, type))); // box the result.
        trueStatements.Add(new Exit()); // break out of loop we have it!
      } else {
        MemberBinding addCall = new MemberBinding(localArray, addMethod);
        trueStatements.Add(new ExpressionStatement(new MethodCall(addCall, 
          new ExpressionList(new Expression[1] {local}))));
      }

      // clear out the local, it is a struct of some sort.
      if (local.Type.IsValueType && ! local.Type.IsPrimitive) {
        trueStatements.Add(new AssignmentStatement(local, 
          new Construct(new MemberBinding(null,local.Type), new ExpressionList(), local.Type)));
      }

      // end while
      // assign resulting array to the target object (if we have anything to assign).
      If ifResult = new If(new BinaryExpression(result, Literal.True, NodeType.Eq),
        new Block(new StatementList()), null);
      statements.Add(ifResult);
      statements = ifResult.TrueBlock.Statements;

      if (addMethod != null) {
        if (type is ArrayType) {
          // target = (type)localArray.ToArray(etype);
          Method toArray = SystemTypes.ArrayList.GetMethod(Identifier.For("ToArray"), SystemTypes.Type);
          ExpressionList args = new ExpressionList();
          args.Add(new UnaryExpression(new Literal(eType, SystemTypes.Type), NodeType.Typeof, SystemTypes.Type));
          statements.Add(new AssignmentStatement(target, 
            CastTo(new MethodCall(new MemberBinding(localArray, toArray), 
                     args, NodeType.Callvirt, SystemTypes.Array), type)));

        } else if (type.Template == SystemTypes.GenericNonEmptyIEnumerable) {
          // Explicit coercion of IEnumerable to NonEmptyIEnumerable requires constructing 
          // the NonEmptyIEnumerable object passing in the IEnumerable as an argument.
          TypeNode ienumtype = Checker.GetIEnumerableTypeFromNonEmptyIEnumerableStruct(this.module, type);
          Debug.Assert(ienumtype!=null);
          //TODO: this call is invalid if the eType is not public
          TypeNode nonEmptyIEnum = SystemTypes.GenericNonEmptyIEnumerable.GetTemplateInstance(this.module, eType);

          InstanceInitializer ii = nonEmptyIEnum.GetConstructor(ienumtype);
          Construct c = new Construct(new MemberBinding(null, ii), new ExpressionList(localArray), nonEmptyIEnum);
          statements.Add(new AssignmentStatement(target, c));
        } else {
          statements.Add(new AssignmentStatement(target, localArray));
        }
      }
    }
Beispiel #43
0
 /// <summary>
 /// requires serFor is Method || serFor is ModelfieldContract
 /// </summary>        
 protected virtual void SerializeWUCList(System.Collections.Generic.List<Checker.WitnessUnderConstruction>/*!*/ toSer, bool isNotLowerbound, Node serFor) {
   ModelfieldContract mfC = serFor as ModelfieldContract;
   foreach (WitnessUnderConstruction wuc in toSer) {
     InstanceInitializer ctor = SystemTypes.WitnessAttribute.GetConstructor(SystemTypes.Boolean, SystemTypes.Int32,
                                                                            SystemTypes.String, SystemTypes.String, SystemTypes.String);
     ExpressionList serList = new ExpressionList(wuc.Guard, wuc.Witness);
     if (mfC != null)
       serList.Add(new MemberBinding(new This(mfC.Modelfield.DeclaringType), mfC.Modelfield)); //add the name of the modelfield
     else
       serList.Add(null); //The witness-attribute will sit on the node, no need to add identifier
     AttributeNode wa = Checker.SerializeExpressions(ctor, serList, wuc.Witness.SourceContext, this.currentModule);
     //Now add the remaining 2 expressions to wa 
     ExpressionList eList = new ExpressionList(new Literal(isNotLowerbound, SystemTypes.Boolean), new Literal(wuc.NrOfDuplications, SystemTypes.Int32));
     for (int i = 0; i < wa.Expressions.Count; i++) //use for loop to make sure the order of the expressions is preserved
       eList.Add(wa.Expressions[i]);
     wa.Expressions = eList;
     if (mfC != null)
       mfC.DeclaringType.Attributes.Add(wa);
     else
       (serFor as Method).Attributes.Add(wa);
   }
 }
Beispiel #44
0
    If AddReadChild(Block scope, StatementList statements, Identifier name, TypeNode type, Expression target, Identifier reader, Expression result, bool unwrapChild, bool ignoreNamespace) {
      ExpressionList args = new ExpressionList();
      args.Add(new Literal(name.Name, SystemTypes.String));
      if (name.Prefix != null) args.Add(new Literal(name.Prefix.Name, SystemTypes.String));
      
      // see if we're on a text node...
      Local nodeType = new Local(Identifier.For("nodeType"), Runtime.XmlNodeType, scope);
      statements.Add(new AssignmentStatement(nodeType, new QualifiedIdentifier(reader, Identifier.For("NodeType"))));
      StatementList ifTextStatements = new StatementList();      
      If ifIsText = new If(
        new BinaryExpression(IsTextNode(nodeType),
          new BinaryExpression(nodeType,
            new QualifiedIdentifier(Identifier.For("XmlNodeType"), Identifier.For("EndElement")), NodeType.Eq),
        NodeType.Or), new Block(ifTextStatements), new Block(new StatementList()));            
      statements.Add(ifIsText);
      
      // then see if we can force the text into the desired type.
      TypeNode unwrapped = UnwrapSingletonTuple(Unwrap(type), false);
      if (unwrapped == null) unwrapped = type;
      Expression readString = new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadString")), null, NodeType.Callvirt, SystemTypes.String);
      Expression coercion = GetConvertFromString(unwrapped, readString, false);
      if (coercion != null) {
        ifTextStatements = ifIsText.TrueBlock.Statements;
        ifTextStatements.Add(new AssignmentStatement(target, CastTo(CastTo(coercion, unwrapped),type)));
        ifTextStatements.Add(new AssignmentStatement(result, Literal.True));        
      }
      statements = ifIsText.FalseBlock.Statements;

      If ifFound = null;
      string method = ignoreNamespace ? "IsStartElementIgnoreNamespace" : "IsStartElement";
      MethodCall isStartEle = new MethodCall(new QualifiedIdentifier(reader, Identifier.For(method)), args);
      ifFound = new If(isStartEle, new Block(new StatementList()), new Block(new StatementList()));
      statements.Add(ifFound);
      statements = ifFound.TrueBlock.Statements;       
      
      statements.Add(new AssignmentStatement(result, Literal.True));

      // body of if test, parse the child element as the specified type.
      MethodCall read = new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Read")), new ExpressionList());
      bool isStructuralType = this.IsStructuralType(type);
      if (isStructuralType && unwrapChild) {
        // consume member element wrapper.
        statements.Add(new ExpressionStatement(read));
      }
      if (type.Template == SystemTypes.GenericBoxed){
        type = Checker.GetCollectionElementType(type);
      }

      if (!AddReadSimpleType(type, statements, reader, target, result, false)) {
        AddCallDeserializer(type, statements, reader, target, result, result);
      }
      if (isStructuralType && unwrapChild) {
        // consume member element end tag wrapper.
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadEndTag")), new ExpressionList(new Literal(name.Name, SystemTypes.String)))));
      }
      return ifFound;
    }
        private void EmitCheckExceptionBody(Method checkExceptionMethod, List <EnsuresExceptional> exceptionalPostconditions)
        {
            Contract.Requires(checkExceptionMethod != null);

            Contract.Requires(exceptionalPostconditions != null);
            Contract.Requires(exceptionalPostconditions.Count > 0);

            // We emit the following method:
            //   bool CheckException(Exception e) {
            //     var ex = e as C1;
            //     if (ex != null) {
            //       EnsuresOnThrow(predicate)
            //     }
            //     else {
            //       var ex2 = e as AggregateException;
            //       if (ex2 != null) {
            //         ex2.Handle(CheckException);
            //       }
            //     }
            //
            //     // Method always returns true. This is by design!
            //     // We need to check all exceptions in the AggregateException
            //     // and fail in EnsuresOnThrow if the postcondition is not met.
            //     return true; // handled

            var body        = checkExceptionMethod.Body.Statements;
            var returnBlock = new Block(new StatementList());

            foreach (var e in exceptionalPostconditions)
            {
                // The catchBlock contains the catchBody, and then
                // an empty block that is used in the EH.
                // TODO ST: name is confusing because there is no catch blocks in this method!
                Block catchBlock = new Block(new StatementList());

                // local is: var ex1 = e as C1;
                Local localEx = new Local(e.Type);

                body.Add(
                    new AssignmentStatement(localEx,
                                            new BinaryExpression(checkExceptionMethod.Parameters[0],
                                                                 new MemberBinding(null, e.Type),
                                                                 NodeType.Isinst)));

                Block skipBlock = new Block();
                body.Add(new Branch(new UnaryExpression(localEx, NodeType.LogicalNot), skipBlock));
                body.Add(catchBlock);
                body.Add(skipBlock);

                // call Contract.EnsuresOnThrow
                ExpressionList args = new ExpressionList();
                args.Add(e.PostCondition);

                args.Add(e.UserMessage ?? Literal.Null);

                args.Add(e.SourceConditionText ?? Literal.Null);

                args.Add(localEx);
                var checks = new StatementList();

                checks.Add(
                    new ExpressionStatement(
                        new MethodCall(
                            new MemberBinding(null, this.rewriter.RuntimeContracts.EnsuresOnThrowMethod),
                            args,
                            NodeType.Call,
                            SystemTypes.Void),
                        e.SourceContext));

                this.rewriter.CleanUpCodeCoverage.VisitStatementList(checks);

                // TODO ST: actually I can't see this recursion guard check in the resulting IL!!
                rewriter.EmitRecursionGuardAroundChecks(checkExceptionMethod, catchBlock, checks);

                catchBlock.Statements.Add(new Branch(null, returnBlock));
            }

            // recurse on AggregateException itself
            {
                // var ae = e as AggregateException;
                // if (ae != null) {
                //   ae.Handle(this.CheckException);
                // }
                Block catchBlock    = new Block(new StatementList());
                var   aggregateType = aggregateExceptionType.Value;

                // var ex2 = e as AggregateException;
                Local localEx2 = new Local(aggregateType);
                body.Add(
                    new AssignmentStatement(localEx2,
                                            new BinaryExpression(
                                                checkExceptionMethod.Parameters[0],
                                                new MemberBinding(null, aggregateType),
                                                NodeType.Isinst)));

                Block skipBlock = new Block();
                body.Add(new Branch(new UnaryExpression(localEx2, NodeType.LogicalNot), skipBlock));
                body.Add(catchBlock);
                body.Add(skipBlock);

                var funcType = func2Type.Value;
                funcType = funcType.GetTemplateInstance(this.rewriter.AssemblyBeingRewritten, SystemTypes.Exception, SystemTypes.Boolean);

                var handleMethod = aggregateType.GetMethod(Identifier.For("Handle"), funcType);

                var funcLocal = new Local(funcType);
                var ldftn     =
                    new UnaryExpression(
                        new MemberBinding(null, checkExceptionMethod),
                        NodeType.Ldftn,
                        CoreSystemTypes.IntPtr);

                catchBlock.Statements.Add(
                    new AssignmentStatement(funcLocal,
                                            new Construct(
                                                new MemberBinding(null, funcType.GetConstructor(SystemTypes.Object, SystemTypes.IntPtr)),
                                                new ExpressionList(checkExceptionMethod.ThisParameter, ldftn))));

                catchBlock.Statements.Add(
                    new ExpressionStatement(new MethodCall(new MemberBinding(localEx2, handleMethod),
                                                           new ExpressionList(funcLocal))));
            }

            // add return true to CheckException method
            body.Add(returnBlock);
            body.Add(new Return(Literal.True));
        }
Beispiel #46
0
    bool AddWriteSimpleAttribute(TypeNode type, Identifier name, StatementList statements, TypeNode referringType, Identifier writer, Expression src) {
      ExpressionList args = new ExpressionList();
      args.Add(GetXmlNameFromId(name));
      args.Add(GetXmlNamespaceFromId(name));
      args.Add(src);

      if (type == SystemTypes.String) {
        statements = AddCheckForNull(statements, Duplicate(src, referringType), type);
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeString")), args)));
      } else if( type == SystemTypes.Boolean) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeBoolean")), args)));
      } else if( type == SystemTypes.Int8) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeSByte")), args)));
      } else if( type == SystemTypes.Char) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeChar")), args)));
      } else if( type == SystemTypes.DateTime) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeDateTime")), args)));
      } else if( type == SystemTypes.Decimal) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeDecimal")), args)));
      } else if( type == SystemTypes.Double) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeDouble")), args)));
      } else if( type == SystemTypes.Guid) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeGuid")), args)));
      } else if( type == SystemTypes.Int16) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeInt16")), args)));
      } else if( type == SystemTypes.Int32) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeInt32")), args)));
      } else if( type == SystemTypes.Int64) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeInt64")), args)));
      } else if( type == SystemTypes.UInt8) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeByte")), args)));
      } else if( type == SystemTypes.Single) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeSingle")), args)));
      } else if( type == SystemTypes.TimeSpan) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeTimeSpan")), args)));
      } else if( type == SystemTypes.UInt16 ) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeUInt16")), args)));
      } else if( type == SystemTypes.UInt32) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeUInt32")), args)));
      } else if( type == SystemTypes.UInt64) {
        statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeUInt64")), args)));
      } else {
        Expression conversion = GetConvertToString(type, src, true);
        if (conversion != null) {         
          statements = AddCheckForNull(statements, Duplicate(src, referringType), type);
          ExpressionList args2 = new ExpressionList();
          args2.Add(args[0]);
          args2.Add(args[1]);
          args2.Add(conversion);          
          statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, Identifier.For("WriteAttributeString")), args2)));
        } else {
          return false;
        } 
      }
      return true;
    }
Beispiel #47
0
 public virtual Expression VisitBinaryExpression(BinaryExpression binaryExpression, Expression opnd1, Expression opnd2, TypeNode t1, TypeNode t2){
   if (binaryExpression == null){Debug.Assert(false); return null;}
   if (t1 == SystemTypes.String || t2 == SystemTypes.String) {
     switch (binaryExpression.NodeType) {
       case NodeType.Add:
         if (opnd1 is Literal && opnd2 is Literal && t1 == SystemTypes.String && t2 == SystemTypes.String) {
           string s1 = ((Literal)opnd1).Value as string;
           string s2 = ((Literal)opnd2).Value as string;
           return new Literal(s1 + s2, SystemTypes.String, binaryExpression.SourceContext);
         }
         Method operatorMethod = this.GetBinaryOperatorOverload(binaryExpression);
         if (operatorMethod != null) break;
         if (this.typeSystem.ImplicitCoercionFromTo(t1, SystemTypes.String, this.TypeViewer) && this.typeSystem.ImplicitCoercionFromTo(t2, SystemTypes.String, this.TypeViewer))
           return new MethodCall(new MemberBinding(null, Runtime.StringConcatStrings), new ExpressionList(opnd1, opnd2),
             NodeType.Call, SystemTypes.String, binaryExpression.SourceContext);
         else
           return new MethodCall(new MemberBinding(null, Runtime.StringConcatObjects), new ExpressionList(opnd1, opnd2),
             NodeType.Call, SystemTypes.String, binaryExpression.SourceContext);
       case NodeType.Eq:
       case NodeType.Ne:
         binaryExpression.Type = SystemTypes.Boolean;
         if (t1 == SystemTypes.String && t2 == SystemTypes.String)
           return this.StringValueComparison(binaryExpression);
         else if (t1 == SystemTypes.Object || t2 == SystemTypes.Object)
           return binaryExpression;
         else
           break;
     }
   }
   if ((t1 is DelegateNode) && (t2 is DelegateNode) && t1 != t2 && (binaryExpression.NodeType == NodeType.Eq || binaryExpression.NodeType == NodeType.Ne)) {
     this.HandleError(binaryExpression, Error.BadBinaryOps,
       binaryExpression.NodeType == NodeType.Eq ? "==" : "!=", this.GetTypeName(t1), this.GetTypeName(t2));
     return null;
   }
   if ((t1 != SystemTypes.Object && t2 != SystemTypes.Object) ||
     !(binaryExpression.NodeType == NodeType.Eq || binaryExpression.NodeType == NodeType.Ne) ||
     (t1.Template == SystemTypes.GenericBoxed || t2.Template == SystemTypes.GenericBoxed)){
     Method operatorMethod = this.GetBinaryOperatorOverload(binaryExpression);
     if (operatorMethod != null) {
       MemberBinding callee = new MemberBinding(null, operatorMethod);
       ExpressionList arguments = new ExpressionList(2);
       if (t1 == SystemTypes.Delegate && t2 is DelegateNode && (binaryExpression.NodeType == NodeType.Eq || binaryExpression.NodeType == NodeType.Ne)) {
         if (opnd1 is MemberBinding && ((MemberBinding)opnd1).BoundMember is Method)
           opnd1 = this.VisitExpression(new Construct(new MemberBinding(null, t2), new ExpressionList(opnd1)));
       }
       arguments.Add(opnd1);
       if (t1 is DelegateNode && t2 == SystemTypes.Delegate && (binaryExpression.NodeType == NodeType.Eq || binaryExpression.NodeType == NodeType.Ne)) {
         if (opnd2 is MemberBinding && ((MemberBinding)opnd2).BoundMember is Method)
           opnd2 = this.VisitExpression(new Construct(new MemberBinding(null, t1), new ExpressionList(opnd2)));
       }
       arguments.Add(opnd2);
       MethodCall call = new MethodCall(callee, arguments);
       call.SourceContext = binaryExpression.SourceContext;
       call.Type = operatorMethod.ReturnType;
       switch (binaryExpression.NodeType) {
         case NodeType.LogicalAnd:
         case NodeType.LogicalOr:
           binaryExpression.Operand1 = new Local(call.Type);
           binaryExpression.Operand2 = call;
           binaryExpression.Type = call.Type;
           return binaryExpression;
       }
       return call;
     }else if ((t1 == SystemTypes.String || t2 == SystemTypes.String) &&
       (binaryExpression.NodeType == NodeType.Eq || binaryExpression.NodeType == NodeType.Ne) &&
       this.typeSystem.ImplicitCoercionFromTo(t1, SystemTypes.String, this.TypeViewer) &&
       this.typeSystem.ImplicitCoercionFromTo(t2, SystemTypes.String, this.TypeViewer)){
       return this.StringValueComparison(binaryExpression);
     }
   }
   if (t1 is DelegateNode || t2 is DelegateNode){
     if (binaryExpression.NodeType == NodeType.Add || binaryExpression.NodeType == NodeType.Sub) {
       binaryExpression.Type = this.typeSystem.ImplicitCoercionFromTo(opnd1, t1, t2, this.TypeViewer) ? t2 : t1;
       return binaryExpression;
     }
   }
   if ((t1 is Pointer || t2 is Pointer) && (binaryExpression.NodeType == NodeType.Add || binaryExpression.NodeType == NodeType.Sub)){
     TypeNode elementType = t1 is Pointer ? ((Pointer)t1).ElementType : ((Pointer)t2).ElementType;
     Expression sizeOf = this.VisitUnaryExpression(new UnaryExpression(new Literal(elementType, SystemTypes.Type), NodeType.Sizeof, SystemTypes.UInt32));
     if (binaryExpression.NodeType == NodeType.Sub) {
       if (elementType == SystemTypes.Void) {
         this.HandleError(binaryExpression, Error.VoidError);
         return null;
       }
       if (t1 is Pointer && t2 is Pointer && ((Pointer)t1).ElementType == ((Pointer)t2).ElementType) {
         binaryExpression.Operand1 = new BinaryExpression(opnd1, new Literal(SystemTypes.Int64, SystemTypes.Type), NodeType.ExplicitCoercion, SystemTypes.Int64, opnd1.SourceContext);
         binaryExpression.Operand2 = new BinaryExpression(opnd2, new Literal(SystemTypes.Int64, SystemTypes.Type), NodeType.ExplicitCoercion, SystemTypes.Int64, opnd2.SourceContext);
         binaryExpression.Type = SystemTypes.Int64;
         return new BinaryExpression(binaryExpression, sizeOf, NodeType.Div, SystemTypes.Int64, binaryExpression.SourceContext);
       }
     }
     if (!(t1 is Pointer && t2 is Pointer)) {
       binaryExpression.Type = t1 is Pointer ? t1 : t2;
       if (elementType == SystemTypes.Void) {
         this.HandleError(binaryExpression, Error.VoidError);
         return null;
       }
       sizeOf.Type = SystemTypes.IntPtr;
       if (t1 is Pointer) {
         Literal lit = binaryExpression.Operand2 as Literal;
         if (lit == null || !(lit.Value is int) || ((int)lit.Value) != 1) {
           if (!(sizeOf is Literal) || !(((Literal)sizeOf).Value is int) || (int)((Literal)sizeOf).Value != 1) {
             if (binaryExpression.Operand2.Type == SystemTypes.Int32) binaryExpression.Operand2.Type = SystemTypes.IntPtr;
             binaryExpression.Operand2 = new BinaryExpression(binaryExpression.Operand2, sizeOf, NodeType.Mul, SystemTypes.IntPtr, binaryExpression.Operand2.SourceContext);
           }
         } else
           binaryExpression.Operand2 = sizeOf;
       } else {
         if (binaryExpression.NodeType == NodeType.Sub) return binaryExpression; //Let Checker issue a message
         Literal lit = binaryExpression.Operand1 as Literal;
         if (lit == null || !(lit.Value is int) || ((int)lit.Value) != 1) {
           if (!(sizeOf is Literal) || !(((Literal)sizeOf).Value is int) || (int)((Literal)sizeOf).Value != 1) {
             if (binaryExpression.Operand1.Type == SystemTypes.Int32) binaryExpression.Operand1.Type = SystemTypes.IntPtr;
             binaryExpression.Operand1 = new BinaryExpression(binaryExpression.Operand1, sizeOf, NodeType.Mul, SystemTypes.IntPtr, binaryExpression.Operand1.SourceContext);
           }
         } else
           binaryExpression.Operand1 = sizeOf;
       }
       return binaryExpression;
     }
   }
   binaryExpression.Type = this.InferTypeOfBinaryExpression(t1, t2, binaryExpression);
   if (binaryExpression.Operand1 == null || binaryExpression.Operand2 == null) binaryExpression.IsErroneous = true;
   try{
     bool savedCheckOverflow = this.typeSystem.checkOverflow;
     this.typeSystem.checkOverflow = !this.typeSystem.suppressOverflowCheck;
     MemberBinding mb = opnd1 as MemberBinding;
     if (mb != null && mb.Type == SystemTypes.Delegate && mb.BoundMember is Method && binaryExpression.NodeType == NodeType.Is) { return Literal.False; }
     Literal lit = PureEvaluator.EvalBinaryExpression(this.EvaluateAsLiteral(opnd1), this.EvaluateAsLiteral(opnd2), binaryExpression, this.typeSystem);
     this.typeSystem.checkOverflow = savedCheckOverflow;
     if (lit != null){
       if (binaryExpression.Type != lit.Type) {
         EnumNode enType = binaryExpression.Type as EnumNode;
         if (enType != null && this.typeSystem.ImplicitCoercionFromTo(lit, lit.Type, enType.UnderlyingType, this.TypeViewer))
           lit.Type = enType;
         else if (binaryExpression.Type == SystemTypes.Single && lit.Type == SystemTypes.Double)
           lit.Type = SystemTypes.Single;
         else if (binaryExpression.Type is EnumNode && ((EnumNode)binaryExpression.Type).UnderlyingType == SystemTypes.UInt32 &&
           lit.Type == SystemTypes.Int64 && ((long)lit.Value) <= uint.MaxValue)
           lit = new Literal((uint)(long)lit.Value, SystemTypes.UInt32);
         else if (binaryExpression.Type == SystemTypes.Int64 && lit.Type == SystemTypes.UInt64)
           binaryExpression.Type = SystemTypes.UInt64;
       }
       lit.SourceExpression = binaryExpression;
       lit.SourceContext = binaryExpression.SourceContext;
       if (binaryExpression.NodeType == NodeType.ExplicitCoercion){
         lit.SourceExpression = opnd1;
         lit.TypeWasExplicitlySpecifiedInSource = true;
       }
       return lit;
     }
   }catch (OverflowException){
     if (binaryExpression.Type is EnumNode && this.currentField != null) {
       this.HandleError(binaryExpression, Error.EnumerationValueOutOfRange, this.GetMemberSignature(this.currentField));
       return Literal.Int32Zero;
     }
     this.HandleError(binaryExpression, Error.CTOverflow);
     return null;
   }catch{} //TODO: be more specific
   return binaryExpression;
 }
Beispiel #48
0
    void AddReadAllGroup(Class serializer, Block block, TypeNode type, StatementList statements, Identifier reader, 
      Expression target, Expression required, Expression result, ArrayList members, Member mixedMember) {

      // todo: keep track of which members have been read and report error on duplicates
      MethodCall read = new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Read")), new ExpressionList());

      Local sb = new Local(SystemTypes.StringBuilder);
      bool isMixed = mixedMember != null;
      if (isMixed) {
        statements.Add(new AssignmentStatement(sb,
          new Construct(new MemberBinding(null, SystemTypes.StringBuilder), new ExpressionList(), SystemTypes.StringBuilder)));
      }

      Block whileBody = new Block(new StatementList());
      BinaryExpression notEndTag = new BinaryExpression(
        new QualifiedIdentifier(reader, Identifier.For("NodeType")) ,
        new QualifiedIdentifier(Identifier.For("XmlNodeType"), Identifier.For("EndElement")), NodeType.Ne);
      BinaryExpression notEOF = new BinaryExpression(
        new QualifiedIdentifier(reader, Identifier.For("EOF")), Literal.True, NodeType.Ne);
      While w = new While(new BinaryExpression(notEndTag, notEOF, NodeType.And), whileBody);
      statements.Add(w);

      Local nameLocal = new Local(Identifier.For("name"),SystemTypes.String,block);
      Local nsLocal = new Local(Identifier.For("ns"),SystemTypes.String,block);
      Local nodeType = new Local(Identifier.For("nodeType"),Runtime.XmlNodeType,block);

      whileBody.Statements.Add(new AssignmentStatement(nameLocal, new QualifiedIdentifier(reader, Identifier.For("LocalName"))));
      whileBody.Statements.Add(new AssignmentStatement(nsLocal, new QualifiedIdentifier(reader, Identifier.For("NamespaceURI"))));
      whileBody.Statements.Add(new AssignmentStatement(nodeType, new QualifiedIdentifier(reader, Identifier.For("NodeType"))));
      
      Block childBlock = whileBody;

      if (isMixed) {
        // Append the text node to the current StringBuilder contents.
        childBlock = new Block(new StatementList());
        If ifText = new If(IsTextNode(nodeType), new Block(new StatementList()), childBlock);

        whileBody.Statements.Add(ifText);
        ExpressionList args = new ExpressionList();
        args.Add(new QualifiedIdentifier(reader, Identifier.For("Value")));
        ifText.TrueBlock.Statements.Add(new ExpressionStatement(new MethodCall(
          new QualifiedIdentifier(sb, Identifier.For("Append")), args)));
        ifText.TrueBlock.Statements.Add(new ExpressionStatement(read)); // advance to next node
      }      

      If ifElement = new If(new BinaryExpression(nodeType,
        new QualifiedIdentifier(Identifier.For("XmlNodeType"), Identifier.For("Element")), NodeType.Eq),
        new Block(new StatementList()), new Block(new StatementList()));
      childBlock.Statements.Add(ifElement);
      childBlock = ifElement.TrueBlock;

      //AddConsoleWrite(statements, new Literal("name=",SystemTypes.String));
      //AddConsoleWriteLine(statements, nameLocal);
      //AddConsoleWrite(statements, new Literal("nodeType=",SystemTypes.String));
      //AddConsoleWriteLine(statements, nodeType);

      foreach (NamedNode childNode in members) {
        if (!(childNode.Member is Field || childNode.Member is Property)) {
          AddError(statements, reader, RuntimeError.SerializationOfTypeNotSupported, 
            new Literal(childNode.Member.GetType().FullName, SystemTypes.String));
        } else {
          Expression mb = GetMemberBinding(target, childNode.Member);
          childBlock = AddReadChild(block, childBlock.Statements, childNode.Name, childNode.TypeNode, mb, reader, result, true, false).FalseBlock;
          // todo: throw error if child is required. (e.g. NonEmptyIEnumerable...)
        }
      }
      // if it isn't any of the expected elements then throw an error.
      AddError(childBlock.Statements, reader, RuntimeError.NoSuchMember,
        new Expression[2]{new Literal(tempChecker.GetTypeName(type),SystemTypes.String), nameLocal});

      // If it's not an element then consume it anyway to keep the reader advancing.
      // Probably a comment or PI or something.
      ifElement.FalseBlock.Statements.Add(new ExpressionStatement(new MethodCall(
        new QualifiedIdentifier(reader, Identifier.For("Skip")), new ExpressionList())));

      if (isMixed) {
        statements.Add(new AssignmentStatement(GetMemberBinding(target, mixedMember), 
          new MethodCall(new QualifiedIdentifier(sb, Identifier.For("ToString")), new ExpressionList())));         
      }
      statements.Add(new AssignmentStatement(result, Literal.True));

    }
Beispiel #49
0
 public virtual Expression StringValueComparison(BinaryExpression binaryExpression){
   if (binaryExpression == null) return null;
   ExpressionList arguments = new ExpressionList(2);
   arguments.Add(binaryExpression.Operand1);
   arguments.Add(binaryExpression.Operand2);
   MethodCall mcall = new MethodCall(new MemberBinding(null, Runtime.StringEquals), arguments, NodeType.Call);
   mcall.Type = SystemTypes.Boolean;
   mcall.SourceContext = binaryExpression.SourceContext;
   if (binaryExpression.NodeType == NodeType.Eq) return mcall;
   UnaryExpression uex = new UnaryExpression(mcall, NodeType.LogicalNot);
   uex.Type = SystemTypes.Boolean;
   uex.SourceContext = binaryExpression.SourceContext;
   return uex;
 }
Beispiel #50
0
 public virtual ExpressionList VisitExpressionList(ExpressionList expressions, ExpressionList changes, ExpressionList deletions, ExpressionList insertions){
   if (changes == null || deletions == null || insertions == null) return expressions;
   int n = expressions == null ? 0 : expressions.Count;
   if (n > changes.Count){Debug.Assert(false); n = changes.Count;}
   if (n > deletions.Count){Debug.Assert(false); n = deletions.Count;}
   if (n > insertions.Count){Debug.Assert(false); n = insertions.Count;}
   if (expressions != null)
     for (int i = 0; i < n; i++)
       expressions[i] = this.VisitExpression(expressions[i], changes[i], deletions[i], insertions[i]);
   ExpressionList result = new ExpressionList(insertions.Count-n);
   for (int i = n, m = insertions.Count; i < m; i++)
     result.Add(insertions[i]);
   return result;
 }
Beispiel #51
0
 public virtual Expression VisitBooleanExpression(Expression expr) {
   UnaryExpression uexpr = expr as UnaryExpression;
   if (uexpr != null && uexpr.NodeType == NodeType.LogicalNot) {
     Expression e = uexpr.Operand = this.VisitBooleanExpression(uexpr.Operand);
     if (e == null) return null;
     MethodCall mcall = e as MethodCall;
     if (mcall != null) {
       MemberBinding mb = mcall.Callee as MemberBinding;
       Member m = null;
       if (mb == null || (m = mb.BoundMember) == null) return null;
       if (m == this.GetTypeView(m.DeclaringType).GetOpTrue()) {
         Method meth = this.GetTypeView(m.DeclaringType).GetOpFalse();
         if (meth != null) {
           mb.BoundMember = meth; return mcall;
         }
       } else if (m == this.GetTypeView(m.DeclaringType).GetOpFalse()) {
         Method meth = this.GetTypeView(m.DeclaringType).GetOpTrue();
         if (meth != null) {
           mb.BoundMember = meth; return mcall;
         }
       }
     }
   } else
     expr = this.VisitExpression(expr);
   TypeNode eType = null;
   if (expr == null || (eType = expr.Type) == null) return null;
   if (!this.typeSystem.ImplicitCoercionFromTo(eType, SystemTypes.Boolean, this.TypeViewer)) {
     Method opTrue = this.GetTypeView(eType).GetOpTrue();
     if (opTrue != null) {
       ExpressionList args = new ExpressionList(1);
       args.Add(this.typeSystem.ImplicitCoercion(expr, opTrue.DeclaringType, this.TypeViewer));
       return new MethodCall(new MemberBinding(null, opTrue), args, NodeType.Call, SystemTypes.Boolean, expr.SourceContext);
     }
   }
   return this.typeSystem.ImplicitCoercion(expr, SystemTypes.Boolean, this.TypeViewer);
 }
 public void Append(VisitedExpression expression)
 {
     ExpressionList.Add(expression);
 }
Beispiel #53
0
    public virtual void CoerceArguments(ParameterList parameters, ref ExpressionList arguments, bool doNotVisitArguments, CallingConventionFlags callingConvention) {
      if (arguments == null) arguments = new ExpressionList();
      int n = arguments.Count;
      int m = parameters == null ? 0 : parameters.Count;
      //if fewer arguments than parameters, supply default values
      for (; n < m; n++) {
        Parameter p = parameters[n];
        TypeNode type = p == null ? null : p.Type;
        if (type == null) type = SystemTypes.Object;
        type = TypeNode.StripModifiers(type);
        if (p.DefaultValue != null)
          arguments.Add(p.DefaultValue);
        else {
          //There should already have been a complaint. Just recover.
          TypeNode elementType = parameters[n].GetParamArrayElementType();
          if (elementType != null) break;
          arguments.Add(new UnaryExpression(new Literal(type, SystemTypes.Type), NodeType.DefaultValue, type));
        }
      }
      if (m > 0) {
        TypeNode elementType = TypeNode.StripModifiers(parameters[m-1].GetParamArrayElementType());
        TypeNode lastArgType = null;
        if (elementType != null && (n > m || (n == m - 1) || n == m
          && (lastArgType = TypeNode.StripModifiers(arguments[m-1].Type)) != null && 
              !this.GetTypeView(lastArgType).IsAssignableTo(TypeNode.StripModifiers(parameters[m-1].Type)) &&
          !(arguments[m-1].Type == SystemTypes.Object && arguments[m-1] is Literal && ((Literal)arguments[m-1]).Value == null))) {
          ExpressionList varargs = new ExpressionList(n-m+1);
          for (int i = m-1; i < n; i++)
            varargs.Add(arguments[i]);
          Debug.Assert(m <= n || m == n+1);
          while (m > n++) arguments.Add(null);
          arguments[m-1] = new ConstructArray(parameters[m-1].GetParamArrayElementType(), varargs);
          arguments.Count = m;
          n = m;
        }
      }
      if (n > m) {
        // Handle Varargs
        Debug.Assert(n == m+1);
        Debug.Assert((callingConvention & CallingConventionFlags.VarArg) != 0);
        ArglistArgumentExpression ale = arguments[n-1] as ArglistArgumentExpression;
        if (ale != null) {
          // rewrite nested arguments to one level.
          // otherwise, the method does not match and I expect the Checker to issue a nice message.
          ExpressionList newArgs = new ExpressionList(n - 1 + ale.Operands.Count);
          for (int i=0; i<n-1; i++) {
            newArgs.Add(arguments[i]);
          }
          for (int i=0; i<ale.Operands.Count; i++) {
            newArgs.Add(ale.Operands[i]);
          }
          arguments = newArgs;
          // adjust formal parameters to actuals
          parameters = (ParameterList)parameters.Clone();
          for (int i=0; i<ale.Operands.Count; i++) {
            if (arguments[i+m] != null) {
              TypeNode pType = arguments[i+m].Type;
              Reference r = pType as Reference;
              if (r != null) pType = r.ElementType;
              parameters.Add(new Parameter(null, pType));
            } else {
              parameters.Add(new Parameter(null, SystemTypes.Object));
            }
          }
          m = arguments.Count;
          n = m;
        } else {
          // leave arguments and let type coercion fail
          // adjust formal parameters to actuals
          parameters = (ParameterList)parameters.Clone();
          parameters.Add(Resolver.ArglistDummyParameter);
          n = parameters.Count;
        }
      }
      if (doNotVisitArguments) {
        for (int i = 0; i < n; i++) {
          Parameter p = this.typeSystem.currentParameter = parameters[i];
          Literal lit = arguments[i] as Literal;
          if (lit != null && lit.Value is TypeNode && p.Type == SystemTypes.Type)
            arguments[i] = lit;
          else {
            if (!this.DoNotVisitArguments(p.DeclaringMethod)) {
              Expression e = arguments[i] = this.typeSystem.ImplicitCoercion(arguments[i], p.Type, this.TypeViewer);
              if (e is BinaryExpression && e.NodeType == NodeType.Box) e = arguments[i] = ((BinaryExpression)e).Operand1;
            }
          }
        }
      } else {
        for (int i = 0; i < n; i++) {

          Parameter p = this.typeSystem.currentParameter = parameters[i];

          bool savedMayReferenceThisAndBase = this.MayReferenceThisAndBase;
          if (p.IsOut
            && this.currentMethod is InstanceInitializer) {
            // allow calls "f(out this.x)" before the explicit base ctor call
            this.MayReferenceThisAndBase = true;
          }

          arguments[i] = this.CoerceArgument(this.VisitExpression(arguments[i]), p);

          this.MayReferenceThisAndBase = savedMayReferenceThisAndBase;
        }
      }
      this.typeSystem.currentParameter = null;
    }
        private static void AddInterfaceImplementationWrapper(Class Class, Method intfMethod, Method baseMethod)
        {
            var d = new Duplicator(Class.DeclaringModule, Class);
            
            d.SkipBodies = true;

            var copy = d.VisitMethod(baseMethod);
            
            copy.Flags = MethodFlags.Private | MethodFlags.HideBySig | MethodFlags.Virtual | MethodFlags.NewSlot |
                         MethodFlags.Final;
            
            copy.ImplementedInterfaceMethods = new MethodList(intfMethod);
            copy.Name = Identifier.For("InheritedInterfaceImplementationContractWrapper$" + intfMethod.Name.Name);
            copy.ClearBody();
            copy.ThisParameter.Type = Class;
            
            var bodyBlock = new Block(new StatementList());
            copy.Body = new Block(new StatementList(bodyBlock));

            // add call to baseMethod
            var calledMethod = (baseMethod.TemplateParameters != null && baseMethod.TemplateParameters.Count > 0)
                ? baseMethod.GetTemplateInstance(Class, copy.TemplateParameters)
                : baseMethod;

            var argList = new ExpressionList();
            for (int i = 0; i < copy.Parameters.Count; i++)
            {
                argList.Add(copy.Parameters[i]);
            }

            var callExpression = new MethodCall(new MemberBinding(copy.ThisParameter, calledMethod), argList);
            if (HelperMethods.IsVoidType(intfMethod.ReturnType))
            {
                bodyBlock.Statements.Add(new ExpressionStatement(callExpression));
            }
            else
            {
                bodyBlock.Statements.Add(new Return(callExpression));
            }
            
            Class.Members.Add(copy);
        }
Beispiel #55
0
 public virtual AttributeNode VisitAttributeNode(AttributeNode attribute, Node target) {
   if (attribute == null || target == null) return null;
   attribute.Constructor = this.VisitAttributeConstructor(attribute, target);
   ExpressionList expressions = attribute.Expressions = this.VisitExpressionList(attribute.Expressions);
   MemberBinding mb = attribute.Constructor as MemberBinding;
   if (mb == null || mb.BoundMember == null) {
     Debug.Assert(attribute.Constructor == null);
     return null;
   }
   //Check arguments for validity
   TypeNode attributeType = mb.BoundMember.DeclaringType;
   if (attributeType == null) return null;
   InstanceInitializer ctor = (InstanceInitializer)mb.BoundMember;
   ParameterList pars = ctor.Parameters;
   ExpressionList positionalArgs = new ExpressionList();
   TrivialHashtable alreadySeenNames = new TrivialHashtable();
   for (int i = 0, n = expressions == null ? 0 : expressions.Count; i < n; i++) {
     Expression e = expressions[i];
     this.TypeInVariableContext(e as Literal);
     NamedArgument narg = e as NamedArgument;
     if (narg == null) { positionalArgs.Add(e); expressions[i] = null; continue; }
     if (narg.Name == null) { expressions[i] = null; continue; }
     if (alreadySeenNames[narg.Name.UniqueIdKey] != null) {
       this.HandleError(narg.Name, Error.DuplicateNamedAttributeArgument, narg.Name.ToString());
       expressions[i] = null; continue;
     }
     alreadySeenNames[narg.Name.UniqueIdKey] = narg.Name;
     Member mem = null;
     TypeNode aType = attributeType;
     while (aType != null) {
       MemberList members = this.GetTypeView(aType).GetMembersNamed(narg.Name);
       for (int j = 0, m = members == null ? 0 : members.Count; j < m; j++) {
         mem = members[j];
         if (mem == null) continue;
         switch (mem.NodeType) {
           case NodeType.Field:
             if (!mem.IsPublic) goto error;
             Field f = (Field)mem;
             if (f.IsInitOnly || f.IsLiteral || f.IsStatic) goto error;
             if (!this.IsValidTypeForCustomAttributeParameter(f.Type)) {
               this.HandleError(narg, Error.BadNamedAttributeArgumentType, this.GetMemberSignature(f));
               this.HandleRelatedError(f);
               return null;
             }
             this.CheckForObsolesence(narg, f);
             narg.IsCustomAttributeProperty = false;
             e = this.typeSystem.ImplicitCoercion(narg.Value, narg.Type = f.Type, this.TypeViewer);
             if (!this.IsValidTypeForCustomAttributeArgument(e, narg.Value)) return null;
             if (e is BinaryExpression && e.NodeType == NodeType.Box) {
               narg.ValueIsBoxed = true;
               e = ((BinaryExpression)e).Operand1;
             }
             narg.Value = e;
             goto doneWithArg;
           case NodeType.Property:
             if (!mem.IsPublic) goto error;
             Property p = (Property)mem;
             if (!this.IsValidTypeForCustomAttributeParameter(p.Type)) {
               this.HandleError(narg, Error.BadNamedAttributeArgumentType, this.GetMemberSignature(p));
               this.HandleRelatedError(p);
               return null;
             }
             if (p.Setter == null || p.Getter == null || p.IsStatic || !p.Setter.IsPublic || !p.Getter.IsPublic) goto error;
             this.CheckForObsolesence(narg, p);
             narg.IsCustomAttributeProperty = true;
             e = this.typeSystem.ImplicitCoercion(narg.Value, narg.Type = p.Type, this.TypeViewer);
             if (!this.IsValidTypeForCustomAttributeArgument(e, narg.Value)) return null;
             if (e is BinaryExpression && e.NodeType == NodeType.Box) {
               narg.ValueIsBoxed = true;
               e = ((BinaryExpression)e).Operand1;
             }
             narg.Value = e;
             goto doneWithArg;
         }
       }
       aType = aType.BaseType;
     }
   error:
     if (mem != null) {
       this.HandleError(narg, Error.BadNamedAttributeArgument, narg.Name.ToString());
       this.HandleRelatedError(mem);
     } else
       this.HandleError(narg, Error.NoSuchMember, this.GetTypeName(attributeType), narg.Name.ToString());
   doneWithArg: ;
   }
   ExpressionList exprs = positionalArgs.Clone();
   this.CoerceArguments(pars, ref positionalArgs, true, ctor.CallingConvention);
   attribute.Expressions = positionalArgs;
   for (int i = 0, n = positionalArgs == null ? 0 : positionalArgs.Count; i < n; i++) {
     Expression e = positionalArgs[i];
     if (e == null) continue;
     if (!this.IsValidTypeForCustomAttributeArgument(e, exprs[i])) return null;
     if (e is BinaryExpression && e.NodeType == NodeType.Box) e = ((BinaryExpression)e).Operand1;
     positionalArgs[i] = e;
   }
   for (int i = 0, n = expressions == null ? 0 : expressions.Count; i < n; i++) {
     Expression e = expressions[i];
     if (e == null) continue;
     positionalArgs.Add(e);
   }
   attribute.Expressions = positionalArgs;
   //Now call specific visitors to deal with any pseudo custom attributes that describe metadata settings for target
   switch (target.NodeType) {
     case NodeType.Assembly: return this.VisitAssemblyAttribute(attribute, (AssemblyNode)target);
     case NodeType.Field: return this.VisitFieldAttribute(attribute, (Field)target);
     case NodeType.InstanceInitializer:
     case NodeType.StaticInitializer:
     case NodeType.Method: return this.VisitMethodAttribute(attribute, (Method)target);
     case NodeType.Property: return this.VisitPropertyAttribute(attribute, (Property)target);
     case NodeType.Parameter: return this.VisitParameterAttribute(attribute, (Parameter)target);
     default:
       TypeNode t = target as TypeNode;
       if (t != null) return this.VisitTypeAttribute(attribute, t);
       break;
   }
   return attribute;
 }