示例#1
0
        public void monadicEachOperatorTest2()
        {
            string      input  = "| each {(5;-2.7;-Inf)}";
            AplusParser parser = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Monadic operator Parsing FAILED!");

            #region expected AST
            ExpressionList expectedTree = Node.ExpressionList(
                Node.ExpressionList(
                    Node.EachOperator(
                        Node.Token(Tokens.ABSOLUTEVALUE, "|"),
                        Node.Strand(
                            Node.ConstantList(
                                Node.IntConstant("5")
                                ),
                            Node.ConstantList(
                                Node.FloatConstant("-2.7")
                                ),
                            Node.ConstantList(
                                Node.InfConstant("-Inf")
                                )
                            )
                        )
                    )
                );
            #endregion

            Assert.AreEqual(expectedTree, parser.Tree, "Incorrect AST generated!");
        }
示例#2
0
        public static Literal GetNamedAttributeValue(AttributeNode attr, Identifier name)
        {
            if (attr == null)
            {
                return(null);
            }
            ExpressionList exprs = attr.Expressions;

            if (exprs == null)
            {
                return(null);
            }
            for (int i = 0, n = exprs.Count; i < n; i++)
            {
                NamedArgument na = exprs[i] as NamedArgument;
                if (na == null)
                {
                    continue;
                }
                if (na.Name.UniqueIdKey == name.UniqueIdKey)
                {
                    return(na.Value as Literal);
                }
            }
            return(null);
        }
示例#3
0
        public void dyadicEachOperatorTest2()
        {
            string      input  = "(3;4) <= each (8;1)";
            AplusParser parser = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Dyadic operator Parsing FAILED!");

            #region expected AST
            ExpressionList expectedTree = Node.ExpressionList(
                Node.ExpressionList(
                    Node.EachOperator(
                        Node.Token(Tokens.LTE, "<="),
                        Node.Strand(
                            Node.ConstantList(
                                Node.IntConstant("3")
                                ),
                            Node.ConstantList(
                                Node.IntConstant("4")
                                )
                            ),
                        Node.Strand(
                            Node.ConstantList(
                                Node.IntConstant("8")
                                ),
                            Node.ConstantList(
                                Node.IntConstant("1")
                                )
                            )
                        )
                    )
                );
            #endregion

            Assert.AreEqual(expectedTree, parser.Tree, "Incorrect AST generated!");
        }
        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);
        }
示例#5
0
        public void dyadicEachOperatorTest1()
        {
            string      input  = "3 ((f[0])each) 7";
            AplusParser parser = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Dyadic operator Parsing FAILED!");

            #region expected AST
            ExpressionList expectedTree = Node.ExpressionList(
                Node.ExpressionList(
                    Node.EachOperator(
                        Node.Indexing(
                            Node.Identifier("f", IdentifierType.UnQualifiedName),
                            Node.ExpressionList(
                                Node.ConstantList(
                                    Node.IntConstant("0")
                                    )
                                )
                            ),
                        Node.ConstantList(
                            Node.IntConstant("3")
                            ),
                        Node.ConstantList(
                            Node.IntConstant("7")
                            )
                        )
                    )
                );
            #endregion

            Assert.AreEqual(expectedTree, parser.Tree, "Incorrect AST generated!");
        }
示例#6
0
 public void AddTest()
 {
     var list = new ExpressionList<ConstantTypes.Integer>();
     var one = new ConstantTypes.Integer(1);
     list.Add(one);
     Assert.IsTrue(list.Contains(one));
 }
        ////////////////////////////////////////////

        ////////////////////////////////////////////
        public override Expression substitute(ExpressionSubstitution s)
        {
            string ss = makeSubstitutionString(s);

            if (substitutionCache.ContainsKey(ss))
            {
                return(substitutionCache[ss]);
            }

            bool needSubstitution = false;

            foreach (var fv in freeVariables)
            {
                if (s.lookup(fv.name) != null)
                {
                    needSubstitution = true;
                }
            }
            foreach (var ftv in freeTypeVariables)
            {
                if (s.typeSubstitution.map(ftv) != null)
                {
                    needSubstitution = true;
                }
            }

            Expression result = this;

            if (needSubstitution)
            {
                ExpressionList sArgs = arguments.substitute(s);
                if (function.name == "==<>")
                {
                    Debug.Assert(sArgs.count == 2);
                    if (sArgs[0].type.ToStringN() == sArgs[1].type.ToStringN())
                    {
                        result =
                            new BasicFAE(
                                BFunctionTemplate.eq.getInstance(TypeTuple.make(new[] { sArgs[0].type })), sArgs);
                    }
                    else if (sArgs.freeTypeVariables.Count > 0)
                    {
                        result =
                            new BasicFAE(
                                BFunctionTemplate.eqG.getInstance(TypeTuple.make(from a in sArgs select a.type)), sArgs);
                    }
                    else
                    {
                        result = new BasicLiteralExpression(BooleanValue.makeBooleanValue(false));
                    }
                    //equality of different types
                }
                else
                {
                    result = new BasicFAE(function.substitute(s.typeSubstitution), sArgs);
                }
            }
            substitutionCache[ss] = result;
            return(result);
        }
示例#8
0
        //public void visitVoid(Void v)
        //{
        //    throw new NotImplementedException();
        //}

        //public void visitComponent(Component c)
        //{
        //    throw new NotImplementedException();
        //}

        //public void visitContract(Contract c)
        //{
        //    throw new NotImplementedException();
        //}

        //public void visitImplementation(Implementation i)
        //{
        //    throw new NotImplementedException();
        //}

        public void visitExpressionList(ExpressionList el)
        {
            foreach (Node n in el)
            {
                n.accept(this);
            }
        }
示例#9
0
 public TestMethodDeclaration(String name, StatementList stmts, ExpressionList exps, SymbolExpression error)
     : base(name)
 {
     this.statements = stmts;
     this.assertions = exps;
     this.error      = error;
 }
示例#10
0
        public override Base VisitRange_clause([NotNull] GolangParser.Range_clauseContext context)
        {
            var expr = context.expression().Accept(this) as Expression;

            ExpressionList values = null;

            if (context.identifier_list() != null)
            {
                values = new ExpressionList();
                var idents = context.identifier_list().Accept(this) as RawNodeList;
                int index  = 0;
                foreach (var ident in idents.Items)
                {
                    var vd = new VarDeclaration(
                        ident.Text,
                        new IteratorType(
                            new ExpressionType(expr),
                            index++));
                    m_currentScope.AddVarDeclaration(vd);
                    values.AddChild(new IdentifierExpression(vd.Identifier));
                }
            }
            else if (context.expression_list() != null)
            {
                values = context.expression_list().Accept(this) as ExpressionList;
            }

            return(new RangeClause(
                       values,
                       expr));
        }
示例#11
0
 InterProcMapping(PTGraph caller, PTGraph callee, Variable thisRef, ExpressionList arguments)
 {
   this.calleePTG = callee;
   this.callerPTG = caller;
   this.callerThisRef = thisRef;
   this.arguments = arguments;
 }
        /// <summary>
        /// Visits the call.
        /// </summary>
        /// <param name="destination">The destination.</param>
        /// <param name="receiver">The receiver.</param>
        /// <param name="callee">The callee.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="isVirtualCall">if set to <c>true</c> [is virtual call].</param>
        /// <param name="programContext">The program context.</param>
        /// <param name="stateBeforeInstruction">The state before instruction.</param>
        /// <param name="stateAfterInstruction">The state after instruction.</param>
        public override void VisitCall(
            Variable destination, 
            Variable receiver, 
            Method callee, 
            ExpressionList arguments, 
            bool isVirtualCall, 
            Microsoft.Fugue.IProgramContext programContext, 
            Microsoft.Fugue.IExecutionState stateBeforeInstruction, 
            Microsoft.Fugue.IExecutionState stateAfterInstruction)
        {
            if ((callee.DeclaringType.GetRuntimeType() == typeof(X509ServiceCertificateAuthentication) ||
                 callee.DeclaringType.GetRuntimeType() == typeof(X509ClientCertificateAuthentication)) &&
                 (callee.Name.Name.Equals("set_CertificateValidationMode", StringComparison.InvariantCultureIgnoreCase)))
            {
                IAbstractValue value = stateBeforeInstruction.Lookup((Variable)arguments[0]);
                IIntValue intValue = value.IntValue(stateBeforeInstruction);

                if (intValue != null)
                {
                    X509CertificateValidationMode mode = (X509CertificateValidationMode)intValue.Value;
                    if (mode != X509CertificateValidationMode.ChainTrust)
                    {
                        Resolution resolution = base.GetResolution(mode.ToString(), 
                            X509CertificateValidationMode.ChainTrust.ToString());
                        Problem problem = new Problem(resolution, programContext);
                        base.Problems.Add(problem);
                    }
                }
            }

            base.VisitCall(destination, receiver, callee, arguments, isVirtualCall, programContext, stateBeforeInstruction, stateAfterInstruction);
        }
示例#13
0
 public virtual ExpressionList VisitExpressionList(ExpressionList list)
 {
     if (list == null) return null;
     for (int i = 0, n = list.Count; i < n; i++)
         list[i] = (Expression)this.Visit(list[i]);
     return list;
 }
示例#14
0
 public DeleteAndStoreStatement(ExpressionList deletables, ExpressionList storables, IExpression metadata, StatementList andThen)
 {
     this.deletables = deletables;
     this.storables  = storables;
     this.metadata   = metadata;
     this.andThen    = andThen;
 }
示例#15
0
 public FunctionApplicationTerm(Logic.Function function, ExpressionList arguments)
 {
     Debug.Assert(function != null);
     Debug.Assert(arguments != null);
     this.function  = function;
     this.arguments = arguments;
 }
示例#16
0
        private void button1_Click(object sender, EventArgs e)
        {
            String deletedExpression = ExpressionList.GetItemText(ExpressionList.SelectedItem);

            ExpressionList.Items.Remove(deletedExpression);
            _cl.DeleteExpression(deletedExpression);
        }
示例#17
0
 public LiteralElement()
   : base((NodeType)SpecSharpNodeType.None){
   this.AttributeNames = new IdentifierList();
   this.AttributeValues = new ExpressionList();
   this.Contents = new ExpressionList();
   this.ContentsType = new Int32List();
 }
示例#18
0
        public void monadicOperatorTest1()
        {
            string      input  = "+/ 5 6 , */ 45 6";
            AplusParser parser = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Monadic operator Parsing FAILED!");

            #region expected AST
            ExpressionList expectedTree = Node.ExpressionList(
                Node.ExpressionList(
                    Node.MonadicFunction(
                        Node.Token(Tokens.RADD, "+/"),
                        Node.DyadicFunction(
                            Node.Token(Tokens.CATENATE, ","),
                            Node.ConstantList(
                                Node.IntConstant("5"),
                                Node.IntConstant("6")
                                ),
                            Node.MonadicFunction(
                                Node.Token(Tokens.RMULTIPLY, "*/"),
                                Node.ConstantList(
                                    Node.IntConstant("45"),
                                    Node.IntConstant("6")
                                    )
                                )
                            )
                        )
                    )
                );
            #endregion

            Assert.AreEqual(expectedTree, parser.Tree, "Incorrect AST generated!");
        }
示例#19
0
        protected virtual void Visit(ExpressionList expressionList)
        {
            Visit((Node)expressionList);

            // Get the type from the last item
            expressionList.TypeInference = (TypeInference)expressionList[expressionList.Count - 1].TypeInference.Clone();
        }
示例#20
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);
            }
        }
 private static ExpressionList Clone(ExpressionList expression)
 {
     var parameters = new Expression[expression.Count];
     for (int i = 0; i < expression.Count; ++i)
         parameters[i] = Clone(expression[i]);
     return new ExpressionList(parameters);
 }
示例#22
0
        public void IntConstantListTest()
        {
            string      input  = "2 5 6 [2]";
            AplusParser parser = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Indexed int list parsing FAILED!");

            #region expected AST
            ExpressionList expectedTree = Node.ExpressionList(
                Node.ExpressionList(
                    Node.Indexing(
                        Node.ConstantList(
                            Node.IntConstant("2"),
                            Node.IntConstant("5"),
                            Node.IntConstant("6")
                            ),
                        Node.ExpressionList(
                            Node.ConstantList(
                                Node.IntConstant("2")
                                )
                            )
                        )
                    )
                );
            #endregion

            Assert.AreEqual(expectedTree, parser.Tree, "Incorrect AST generated!");
        }
示例#23
0
        public void FloatConstantListTest()
        {
            string      input  = "-3. .12 -2.2 4e2 -2.1e2 4.1e+4 .2.2.23.4 Inf -Inf";
            AplusParser parser = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Float list parsing FAILED!");

            #region expected AST
            ExpressionList expectedTree = Node.ExpressionList(
                Node.ExpressionList(
                    Node.ConstantList(
                        Node.FloatConstant("-3."),
                        Node.FloatConstant(".12"),
                        Node.FloatConstant("-2.2"),
                        Node.FloatConstant("4e2"),
                        Node.FloatConstant("-2.1e2"),
                        Node.FloatConstant("4.1e+4"),
                        Node.FloatConstant(".2"),
                        Node.FloatConstant(".2"),
                        Node.FloatConstant(".23"),
                        Node.FloatConstant(".4"),
                        Node.InfConstant("Inf"),
                        Node.InfConstant("-Inf")
                        )
                    )
                );
            #endregion

            Assert.AreEqual(expectedTree, parser.Tree, "Incorrect AST generated!");
        }
示例#24
0
        public void SingeQuotedKanaKanjiConstantTest()
        {
            string      input        = "'こんにちは世界'";
            string      expectedText = "こんにちは世界";
            AplusParser parser       = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Singe quoted constant input parse FAILED");

            ExpressionList expectedNodeA = Node.ExpressionList(
                Node.ExpressionList(
                    Node.SingeQuotedConstant(expectedText)
                    )
                );
            ExpressionList expectedNodeB = Node.ExpressionList(
                Node.ExpressionList(
                    // for Single quoted characters remove the leading and trailing '
                    new Constant(expectedText, ConstantType.CharacterConstant)
                    )
                );

            Assert.AreEqual(expectedNodeA, parser.Tree, "Invalid Node created! (Helper method used)");
            Assert.AreEqual(expectedNodeB, parser.Tree, "Invalid Node created!");

            Assert.IsTrue(parser.Tree == expectedNodeA, "Operator == Compare Failed!");
        }
示例#25
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);
        }
示例#26
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));
            }
        }
示例#27
0
        ////////////////////////////////////////////////////////////////////////////
        public override Expression getEarliestIncarnation(ExpressionList indices, PropositionalFormula condition)
        {
            var earlyIncarnations       = new List <Expression>();
            PropositionalFormula c      = mapAnalyzer.pathCondition & condition;
            Expression           result = null;

            foreach (var p in predecessors)
            {
                PropositionalFormula pc = p.Item2 & c;
                if (!pc.isFalse)
                {
                    if (p.Item1 == null)
                    {
                        result = incarnation;
                        break;
                    }
                    else
                    {
                        earlyIncarnations.Add(p.Item1.getEarliestIncarnation(indices, c));
                    }
                }
            }
            if (result == null)
            {
                result = findEarliestSafeIncarnation(incarnation, earlyIncarnations);
            }
            return(result);
        }
            ExpressionType TranslateExpression(CallExpression e)
            {
                Entry func = Env.ValueEnvironment[e.Func] as Entry;

                if (func == null || !(func is FunctionEntry))
                {
                    Error.Report(e.Pos, "Undefined function '" + e.Func.ToString() + "'");
                    return(new ExpressionType(null, Types.Type._void));
                }

                Types.RECORD formals = (func as FunctionEntry).Formals;
                List <Exp>   list    = new List <Exp>();

                for (ExpressionList args = e.Args; args != null; args = args.Tail, formals = formals.Tail)
                {
                    if (formals == null)
                    {
                        Error.Report(e.Pos, "Too much parameters in call '" + e.Func.ToString() + "'");
                        return(new ExpressionType(null, (func as FunctionEntry).Result));
                    }
                    ExpressionType et = TranslateExpression(args.Head);
                    if (!et.Type.CoerceTo(formals.FieldType))
                    {
                        Error.Report(args.Head.Pos, "Type mismatch for parameter '" + formals.FieldName.ToString() + "'");
                        return(new ExpressionType(null, (func as FunctionEntry).Result));
                    }
                    list.Add(et.Exp);
                }
                if (formals != null)
                {
                    Error.Report(e.Pos, "Too few parameters in call '" + e.Func.ToString() + "'");
                }
                return(new ExpressionType(Translate.TranslateCallExp(Level, (func as FunctionEntry).Level, (func as FunctionEntry).Label, list), (func as FunctionEntry).Result.Actual));
            }
示例#29
0
        public void ExpressionListTestB()
        {
            string      input  = "+{(2);4 5}; -{(12)}; { 1;3;\n4;5}";
            AplusParser parser = TestUtils.BuildASCIIParser(input);

            Assert.IsTrue(parser.Parse(), "Expression List Parsing FAILED!");

            #region expected AST
            ExpressionList expectedTree = Node.ExpressionList(
                Node.ExpressionList(
                    Node.DyadicFunction(
                        Node.Token(Tokens.ADD, "+"),
                        Node.ConstantList(Node.IntConstant("2")),
                        Node.ConstantList(Node.IntConstant("4"), Node.IntConstant("5"))
                        ),
                    Node.MonadicFunction(
                        Node.Token(Tokens.NEGATE, "-"),
                        Node.ConstantList(Node.IntConstant("12"))
                        ),
                    Node.ExpressionList(
                        Node.ConstantList(Node.IntConstant("1")),
                        Node.ConstantList(Node.IntConstant("3")),
                        Node.ConstantList(Node.IntConstant("4")),
                        Node.ConstantList(Node.IntConstant("5"))
                        )
                    )
                );
            #endregion

            Assert.AreEqual(expectedTree, parser.Tree, "Incorrect AST generated!");
        }
示例#30
0
        /// <summary>
        /// Visits the call.
        /// </summary>
        /// <param name="destination">The destination.</param>
        /// <param name="receiver">The receiver.</param>
        /// <param name="callee">The callee.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="isVirtualCall">if set to <c>true</c> [is virtual call].</param>
        /// <param name="programContext">The program context.</param>
        /// <param name="stateBeforeInstruction">The state before instruction.</param>
        /// <param name="stateAfterInstruction">The state after instruction.</param>
        public override void VisitCall(
            Variable destination,
            Variable receiver,
            Method callee,
            ExpressionList arguments,
            bool isVirtualCall,
            Microsoft.Fugue.IProgramContext programContext,
            Microsoft.Fugue.IExecutionState stateBeforeInstruction,
            Microsoft.Fugue.IExecutionState stateAfterInstruction)
        {
            if ((callee.DeclaringType.GetRuntimeType() == typeof(X509ServiceCertificateAuthentication) ||
                 callee.DeclaringType.GetRuntimeType() == typeof(X509ClientCertificateAuthentication)) &&
                (callee.Name.Name.Equals("set_CertificateValidationMode", StringComparison.InvariantCultureIgnoreCase)))
            {
                IAbstractValue value    = stateBeforeInstruction.Lookup((Variable)arguments[0]);
                IIntValue      intValue = value.IntValue(stateBeforeInstruction);

                if (intValue != null)
                {
                    X509CertificateValidationMode mode = (X509CertificateValidationMode)intValue.Value;
                    if (mode != X509CertificateValidationMode.ChainTrust)
                    {
                        Resolution resolution = base.GetResolution(mode.ToString(),
                                                                   X509CertificateValidationMode.ChainTrust.ToString());
                        Problem problem = new Problem(resolution, programContext);
                        base.Problems.Add(problem);
                    }
                }
            }

            base.VisitCall(destination, receiver, callee, arguments, isVirtualCall, programContext, stateBeforeInstruction, stateAfterInstruction);
        }
示例#31
0
        public virtual bool IsExposedAttribute(AttributeNode attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }

            // check whether attribte type is exposed
            TypeNode attributeType = attribute.Type;

            if (!IsExposedType(attributeType))
            {
                return(false);
            }

            // check whether expressions used to instantiate attribute are exposed
            ExpressionList expressions = attribute.Expressions;

            for (int i = 0; i < expressions.Count; i++)
            {
                if (!IsExposedExpression(expressions[i]))
                {
                    return(false);
                }
            }

            // apply user filters to attribute
            return(attributeFilter.IsExposedType(attributeType));
        }
示例#32
0
        private Expression GetNestedExpression(Expression parent)
        {
            Expression result;

            using (Tokenizer.ExpectBrackets())
            {
                result = ReadCriteriaList(parent);
                if (Tokenizer.IsNextToken(Constants.Comma))
                {
                    var list = new ExpressionList();
                    list.Identifiers.Add(result);

                    do
                    {
                        Tokenizer.ExpectToken(Constants.Comma);

                        result = ReadCriteriaList(parent);
                        list.Identifiers.Add(result);
                    } while (Tokenizer.IsNextToken(Constants.Comma));

                    result = list;
                }
            }

            NestedExpression nestedExpression = new NestedExpression(parent)
            {
                Expression = result
            };

            result.Parent = nestedExpression;
            return(nestedExpression);
        }
示例#33
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();
            }
        }
示例#34
0
        /// <summary>
        /// Visits the specified expression list.
        /// </summary>
        /// <param name="expressionList">The expression list.</param>
        public override Node Visit(ExpressionList expressionList)
        {
            base.Visit(expressionList);

            // Get the type from the last item
            expressionList.TypeInference = (TypeInference)expressionList[expressionList.Count - 1].TypeInference.Clone();
            return(expressionList);
        }
示例#35
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));
     }
 }
示例#36
0
 public virtual T Visit(ExpressionList node)
 {
     foreach (Node n in node.nodes)
     {
         traverse(n);
     }
     return(DefaultReturnValue());
 }
示例#37
0
 public LiteralElement()
     : base((NodeType)SpecSharpNodeType.None)
 {
     this.AttributeNames  = new IdentifierList();
     this.AttributeValues = new ExpressionList();
     this.Contents        = new ExpressionList();
     this.ContentsType    = new Int32List();
 }
示例#38
0
 public GroupByClause(ExpressionList exprList)
 {
     foreach (Expression e in exprList) {
         e.Parent = this;
         _exprs.Add(e);
     }
     this.ExpressionType = ExpressionType.QL_SELECT_GROUP_BY;
 }
示例#39
0
 public WhereClause(ExpressionList exprList)
 {
     foreach (Expression e in exprList) {
         e.Parent = this;
         _exprs.Add(e);
     }
     this.ExpressionType = ExpressionType.QL_SELECT_WHERE_CLAUSE;
 }
示例#40
0
 InterProcMapping(InterProcMapping ipm)
 {
   this.calleePTG = ipm.calleePTG;
   this.callerPTG = ipm.callerPTG;
   this.callerThisRef = ipm.callerThisRef;
   this.arguments = ipm.arguments;
   this.mapping = new Dictionary<IPTAnalysisNode, Nodes>(ipm.mapping);
 }
示例#41
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);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ParenthesizedExpression"/> class.
 /// </summary>
 /// <param name="content">The content.</param>
 public ParenthesizedExpression(params Expression[] content)
 {
     if (content != null)
     {
         if (content.Length == 1)
             Content = content[0];
         else
             Content = new ExpressionList(content);
     }
 }
示例#43
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 AbbreviationDuplicator(Method sourceMethod, Method targetMethod, ContractNodes contractNodes,
            Method abbreviation, Expression targetObject, ExpressionList actuals)
            : base(targetMethod.DeclaringType.DeclaringModule, sourceMethod, targetMethod, contractNodes, false)
        {
            this.targetObject = targetObject;
            this.abbreviation = abbreviation;
            this.actuals = actuals;

            this.localsInActuals = new TrivialHashtable();

            PopulateLocalsInActuals();
        }
    public override ExpressionList VisitExpressionList(ExpressionList expressions)
    {
      if (expressions == null) return null;

      for(int i = expressions.Count-1; i >= 0; i--) 
      {
        Expression elem = this.VisitExpression(expressions[i]);
        System.Diagnostics.Debug.Assert(elem != null, "VisitExpression must return non null if passed non null");
        expressions[i] = elem;
      }
      return expressions;
    }
示例#46
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);
 }
		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;
		}
        public void ShouldGetOneProblemWithClientCertificateValidationModePeerOrChainTrustRuleViolation()
        {
            CertificateValidationMode rule = new CertificateValidationMode();
            Method callee = Method.GetMethod(typeof(X509ClientCertificateAuthentication).GetMethod("set_CertificateValidationMode"));
            ExpressionList arguments = new ExpressionList(new Variable(NodeType.VariableDeclaration));
            rule.VisitCall(
                null, null,
                callee,
                arguments,
                false, new MockProgramContext(),
                new MockStateBeforeInstruction((int)X509CertificateValidationMode.PeerOrChainTrust), null);

            Assert.IsNotNull(rule.Problems);
            Assert.AreEqual(1, rule.Problems.Count);
        }
 public Alternatives()
 {
     this.Expressions = new ExpressionList();
     //this.Image = ImageType.Alternative;
     this.Literal = "";
 }
        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);
        }
示例#51
0
		string Evaluate (string source, ExpressionList exprList)
		{
			if (exprList == null)
				throw new ArgumentNullException ("exprList");
			return string.Concat (exprList.Select (e => e.EvaluateAsString (CreateContext (source))));
		}
示例#52
0
        public override ExpressionList VisitExpressionList(ExpressionList list)
        {
            if (list == null) return null;
            for (int i = 0, n = list.Count; i < n; i++)
            {
                this.VisitExpression(list[i]);

                if (i < (n - 1))
                    Write(", ");
            }
            return list;
        }
示例#53
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;
 }
示例#54
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));

    }
示例#55
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 ) );    
    }
示例#56
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;
    }
示例#57
0
    bool AddWriteSimpleType(TypeNode simpleType, StatementList statements, TypeNode referringType, Identifier writer, Expression src, Expression name, Expression ns) {

      Identifier method = null;
      TypeNode type = Unwrap(simpleType);

      ExpressionList args = new ExpressionList(src);

      if (type == SystemTypes.String) {
        method = Identifier.For("WriteString");
      } else if( type == SystemTypes.Boolean) {
        method = Identifier.For("WriteBoolean");
      } else if( type == SystemTypes.Int8) {
        method = Identifier.For("WriteSByte");
      } else if( type == SystemTypes.Char) {
        method = Identifier.For("WriteChar");
      } else if( type == SystemTypes.DateTime) {
        method = Identifier.For("WriteDateTime");
      } else if( type == SystemTypes.Decimal) {
        method = Identifier.For("WriteDecimal");
      } else if( type == SystemTypes.Double) {
        method = Identifier.For("WriteDouble");
      } else if( type == SystemTypes.Guid) {
        method = Identifier.For("WriteGuid");
      } else if( type == SystemTypes.Int16) {
        method = Identifier.For("WriteInt16");
      } else if( type == SystemTypes.Int32) {
        method = Identifier.For("WriteInt32");
      } else if( type == SystemTypes.Int64) {
        method = Identifier.For("WriteInt64");
      } else if( type == SystemTypes.UInt8) {
        method = Identifier.For("WriteByte");
      } else if( type == SystemTypes.Single) {
        method = Identifier.For("WriteSingle");
      } else if( type == SystemTypes.TimeSpan) {
        method = Identifier.For("WriteTimeSpan");
      } else if( type == SystemTypes.UInt16 ) {
        method = Identifier.For("WriteUInt16");
      } else if( type == SystemTypes.UInt32) {
        method = Identifier.For("WriteUInt32");
      } else if( type == SystemTypes.UInt64) {
        method = Identifier.For("WriteUInt64");
      } else {
        Expression conversion = GetConvertToString(type, src, false);
        if (conversion != null) {
          statements = AddCheckForNull(statements, Duplicate(src, referringType), type);
          method = Identifier.For("WriteString");
          args = new ExpressionList(conversion);
        } else {
          return false;
        } 
      }
    
      if (name != null) {        
        Identifier id = Checker.GetDefaultElementName(type);
        string defaultName = id.Name;
        string defaultNamespace = (id.Prefix != null) ? id.Prefix.Name : null;
        Expression localName = new Local(SystemTypes.String);
        Expression localNamespace = new Local(SystemTypes.String);
        Expression safeName = name;
        if (name is Literal) {
          if (name == Literal.Null) {
            localName =  new Literal(defaultName, SystemTypes.String);
            localNamespace = new Literal(defaultNamespace, SystemTypes.String);
          } else {
            localName = name;
            localNamespace = ns;
          }
        } else {
          If nameNull = new If(new BinaryExpression(name, Literal.Null, NodeType.Eq), new Block(new StatementList()), new Block(new StatementList()));
          nameNull.TrueBlock.Statements.Add(new AssignmentStatement(localName, new Literal(defaultName, SystemTypes.String)));
          nameNull.TrueBlock.Statements.Add(new AssignmentStatement(localNamespace, new Literal(defaultNamespace, SystemTypes.String)));
          nameNull.FalseBlock.Statements.Add(new AssignmentStatement(localName, name));
          nameNull.FalseBlock.Statements.Add(new AssignmentStatement(localNamespace, ns));
          statements.Add(nameNull);
        }

        MethodCall call = new MethodCall();
        call.Callee = new QualifiedIdentifier(writer,Identifier.For("WriteStartElement"));
        call.Operands = new ExpressionList();
        call.Operands.Add(localName);
        call.Operands.Add(localNamespace);
        statements.Add( new ExpressionStatement( call ) );
      }
      StatementList notNull = statements;
      if (!type.IsValueType) {
        notNull = AddCheckForNull(statements, Duplicate(src, referringType), type);
      }        
      notNull.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(writer, method), args)));

      if (name != null) {
        MethodCall call = new MethodCall();
        call.Callee = new QualifiedIdentifier(writer,Identifier.For("WriteEndElement"));
        call.Operands = new ExpressionList();
        statements.Add( new ExpressionStatement( call ) );      
      }
      return true;
    }
示例#58
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));
    }
示例#59
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;
    }
示例#60
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)));
 }