Пример #1
0
        void VisitCodeStatement(CodeStatement statement)
        {
            WriteLine("VisitCodeStatement: " + statement.GetType().Name);
            CodeVariableDeclarationStatement codeVariableDeclarationStatement = statement as CodeVariableDeclarationStatement;
            CodeAssignStatement          codeAssignStatement          = statement as CodeAssignStatement;
            CodeConditionStatement       codeConditionStatement       = statement as CodeConditionStatement;
            CodeIterationStatement       codeIterationStatement       = statement as CodeIterationStatement;
            CodeExpressionStatement      codeExpressionStatement      = statement as CodeExpressionStatement;
            CodeTryCatchFinallyStatement codeTryCatchFinallyStatement = statement as CodeTryCatchFinallyStatement;

            if (codeVariableDeclarationStatement != null)
            {
                VisitCodeVariableDeclarationStatement(codeVariableDeclarationStatement);
            }
            else if (codeAssignStatement != null)
            {
                VisitCodeAssignStatement(codeAssignStatement);
            }
            else if (codeConditionStatement != null)
            {
                VisitCodeConditionStatement(codeConditionStatement);
            }
            else if (codeIterationStatement != null)
            {
                VisitCodeIterationStatement(codeIterationStatement);
            }
            else if (codeExpressionStatement != null)
            {
                VisitCodeExpressionStatement(codeExpressionStatement);
            }
            else if (codeTryCatchFinallyStatement != null)
            {
                VisitCodeTryCatchFinallyStatement(codeTryCatchFinallyStatement);
            }
            else
            {
                WriteLine("Unhandled statement: " + statement.GetType().Name);
            }
        }
        /// <summary>
        ///  Serializes a series of SetChildIndex() statements for each control iln a child control collection in
        ///  reverse order.
        /// </summary>
        private void SerializeZOrder(IDesignerSerializationManager manager, CodeStatementCollection statements, Control control)
        {
            using (TraceScope("ControlCodeDomSerializer::SerializeZOrder()"))
            {
                // Push statements in reverse order so the first guy in the
                // collection is the last one to be brought to the front.
                for (int i = control.Controls.Count - 1; i >= 0; i--)
                {
                    // Only serialize this control if it is (a) sited and
                    // (b) not being privately inherited
                    Control child = control.Controls[i];

                    if (child.Site == null || child.Site.Container != control.Site.Container)
                    {
                        continue;
                    }

                    InheritanceAttribute attr = (InheritanceAttribute)TypeDescriptor.GetAttributes(child)[typeof(InheritanceAttribute)];

                    if (attr.InheritanceLevel == InheritanceLevel.InheritedReadOnly)
                    {
                        continue;
                    }

                    // Create the "control.Controls.SetChildIndex" call
                    CodeExpression controlsCollection          = new CodePropertyReferenceExpression(SerializeToExpression(manager, control), "Controls");
                    CodeMethodReferenceExpression method       = new CodeMethodReferenceExpression(controlsCollection, "SetChildIndex");
                    CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression();
                    methodInvoke.Method = method;

                    // Fill in parameters
                    CodeExpression childControl = SerializeToExpression(manager, child);
                    methodInvoke.Parameters.Add(childControl);
                    methodInvoke.Parameters.Add(SerializeToExpression(manager, 0));
                    CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke);
                    statements.Add(statement);
                }
            }
        }
        protected static List <TCodeObject> FindCode <TCodeObject>(CodeStatementCollection statements, Predicate <TCodeObject> matchesFilter)
            where TCodeObject : CodeObject
        {
            List <TCodeObject> values = new List <TCodeObject>();

            foreach (CodeStatement statement in statements)
            {
                TCodeObject             typedStatement = statement as TCodeObject;
                CodeExpressionStatement expression     = statement as CodeExpressionStatement;
                if (typedStatement == null && expression != null)
                {
                    typedStatement = expression.Expression as TCodeObject;
                }

                if (typedStatement != null && matchesFilter(typedStatement))
                {
                    values.Add(typedStatement);
                }
            }

            return(values);
        }
Пример #4
0
        public void FixUpWriteStatementTest()
        {
            var invoke = new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("__w"), "Write");
            CodeExpressionStatement exprStmt = new CodeExpressionStatement(invoke);

            WebPageSurrogateControlBuilder.FixUpWriteStatement(exprStmt);
            Assert.AreEqual(invoke.Method.MethodName, "WriteLiteral");
            Assert.IsInstanceOfType(invoke.Method.TargetObject, typeof(CodeThisReferenceExpression));

            // @__w.Write case
            var code = " @__w.Write(\"hello\"); ";
            var stmt = new CodeSnippetStatement(code);

            WebPageSurrogateControlBuilder.FixUpWriteStatement(stmt);
            Assert.AreEqual(" WriteLiteral(\"hello\"); ", stmt.Value);

            // __w.Write case
            code = " __w.Write(\"hello\"); ";
            stmt = new CodeSnippetStatement(code);
            WebPageSurrogateControlBuilder.FixUpWriteStatement(stmt);
            Assert.AreEqual(" WriteLiteral(\"hello\"); ", stmt.Value);
        }
Пример #5
0
        CodeExpressionStatement[] ParseMultiExpression(string code)
        {
            var tokens = SplitTokens(code);

            #region Date/time

            int n = tokens.Count - 2;
            if (tokens.Count > 1 && ((string)tokens[n]).Length > 0 && ((string)tokens[n])[0] == Multicast)
            {
                string arg = ((string)tokens[n + 1]).ToUpperInvariant().Trim();
                arg = arg.Length == 1 ? arg : arg.TrimEnd('S');

                switch (arg)
                {
                case "S":
                case "SECOND":
                case "M":
                case "MINUTE":
                case "H":
                case "HOUR":
                case "D":
                case "DAY":
                    return(new[] { new CodeExpressionStatement(ParseDateExpression(code)) });
                }
            }

            #endregion

            var result     = ParseMultiExpression(tokens.ToArray());
            var statements = new CodeExpressionStatement[result.Length];

            for (int i = 0; i < result.Length; i++)
            {
                statements[i] = new CodeExpressionStatement(result[i]);
            }

            return(statements);
        }
 private void SerializeZOrder(IDesignerSerializationManager manager, CodeStatementCollection statements, Control control)
 {
     for (int i = control.Controls.Count - 1; i >= 0; i--)
     {
         Control control2 = control.Controls[i];
         if (control2.Site != null && control2.Site.Container == control.Site.Container)
         {
             InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(control2)[typeof(InheritanceAttribute)];
             if (inheritanceAttribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly)
             {
                 CodeExpression targetObject          = new CodePropertyReferenceExpression(base.SerializeToExpression(manager, control), "Controls");
                 CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(targetObject, "SetChildIndex");
                 CodeMethodInvokeExpression    codeMethodInvokeExpression = new CodeMethodInvokeExpression();
                 codeMethodInvokeExpression.Method = method;
                 CodeExpression value = base.SerializeToExpression(manager, control2);
                 codeMethodInvokeExpression.Parameters.Add(value);
                 codeMethodInvokeExpression.Parameters.Add(base.SerializeToExpression(manager, 0));
                 CodeExpressionStatement value2 = new CodeExpressionStatement(codeMethodInvokeExpression);
                 statements.Add(value2);
             }
         }
     }
 }
Пример #7
0
 private static void DumpStatement(StreamWriter writer, CodeStatement s)
 {
     indent++;
     if (s is CodeAssignStatement)
     {
         CodeAssignStatement stmt = (CodeAssignStatement)s;
         WriteLineIndent(stmt.Left.GetType().ToString());
         DumpExpression(stmt.Left);
         WriteLineIndent(stmt.Right.GetType().ToString());
         DumpExpression(stmt.Right);
     }
     else if (s is CodeExpressionStatement)
     {
         CodeExpressionStatement stmt = (CodeExpressionStatement)s;
         WriteLineIndent(stmt.Expression.GetType().ToString());
         DumpExpression(stmt.Expression);
     }
     if (s.UserData.Contains(XSharpCodeConstants.USERDATA_CODE))
     {
         WriteLineIndent("Original code: " + s.UserData[XSharpCodeConstants.USERDATA_CODE].ToString());
     }
     indent--;
 }
Пример #8
0
 private static void DumpStatement(StreamWriter writer, CodeStatement s)
 {
     indent++;
     if (s is CodeAssignStatement)
     {
         CodeAssignStatement stmt = (CodeAssignStatement)s;
         WriteLineIndent(stmt.Left.GetType().ToString());
         DumpExpression(stmt.Left);
         WriteLineIndent(stmt.Right.GetType().ToString());
         DumpExpression(stmt.Right);
     }
     else if (s is CodeExpressionStatement)
     {
         CodeExpressionStatement stmt = (CodeExpressionStatement)s;
         WriteLineIndent(stmt.Expression.GetType().ToString());
         DumpExpression(stmt.Expression);
     }
     if (s.HasSourceCode())
     {
         WriteLineIndent("Original code: " + s.GetSourceCode());
     }
     indent--;
 }
Пример #9
0
        /// <summary>
        ///     This emits a method invoke to ISupportInitialize.
        /// </summary>
        private void SerializeSupportInitialize(IDesignerSerializationManager manager, CodeStatementCollection statements, CodeExpression valueExpression, object value, string methodName)
        {
            Trace("Emitting {0}", methodName);

            CodeTypeReference             type         = new CodeTypeReference(typeof(ISupportInitialize));
            CodeCastExpression            castExp      = new CodeCastExpression(type, valueExpression);
            CodeMethodReferenceExpression method       = new CodeMethodReferenceExpression(castExp, methodName);
            CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression();

            methodInvoke.Method = method;

            CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke);

            if (methodName == "BeginInit")
            {
                statement.UserData["statement-ordering"] = "begin";
            }
            else
            {
                statement.UserData["statement-ordering"] = "end";
            }

            statements.Add(statement);
        }
Пример #10
0
 public int VisitSideEffect(CodeExpressionStatement side)
 {
     return(0);
 }
Пример #11
0
 protected override void GenerateExpressionStatement(CodeExpressionStatement e)
 {
 }
        public static void Generate(string nameSpace, string path, string displayName, string className = "PackagePath", string mainFlag = "/")
        {
            CodeCompileUnit unit         = new CodeCompileUnit();
            CodeNamespace   theNamespace = new CodeNamespace(nameSpace);

            unit.Namespaces.Add(theNamespace);

            theNamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));

            CodeTypeDeclaration theClass = new CodeTypeDeclaration(className);

            theClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Class;
            theNamespace.Types.Add(theClass);

            // LocalPath
            CodeMemberField LocalPath = new CodeMemberField(typeof(string), "LocalPath");

            LocalPath.Attributes     = MemberAttributes.Private | MemberAttributes.Const;
            LocalPath.InitExpression = new CodePrimitiveExpression($"Assets/_package_{mainFlag}");
            theClass.Members.Add(LocalPath);

            // DisplayName
            CodeMemberField DisplayName = new CodeMemberField(typeof(string), "DisplayName");

            DisplayName.Attributes     = MemberAttributes.Public | MemberAttributes.Const;
            DisplayName.InitExpression = new CodePrimitiveExpression(displayName);
            theClass.Members.Add(DisplayName);

            // _mainPath
            CodeMemberField _mainPath = new CodeMemberField(typeof(string), "_mainPath");

            _mainPath.Attributes = MemberAttributes.Private | MemberAttributes.Static;
            theClass.Members.Add(_mainPath);

            // public static bool IsDevelopment { get; private set; }
//            var IsDevelopment = new CodeMemberProperty();
//            IsDevelopment.Type = new CodeTypeReference(typeof(bool));
//            IsDevelopment.Attributes = MemberAttributes.Public | MemberAttributes.Static;
//            IsDevelopment.Name = "IsDevelopment";
//            IsDevelopment.HasGet = true;
//            IsDevelopment.HasSet = true;
//            IsDevelopment.SetStatements.Add(new CodeExpression());
//            theClass.Members.Add(IsDevelopment);

            // MainPath属性
            CodeMemberProperty MainPath = new CodeMemberProperty();

            MainPath.Type       = new CodeTypeReference(typeof(string));
            MainPath.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            MainPath.Name       = "MainPath";
            MainPath.HasGet     = true;
            MainPath.HasSet     = false;
            theClass.Members.Add(MainPath);

            // if语句
            CodeConditionStatement ifCondition = new CodeConditionStatement();

            ifCondition.Condition = new CodeVariableReferenceExpression("string.IsNullOrEmpty(_mainPath)");

            CodeExpressionStatement s = new CodeExpressionStatement();

            s.Expression = new CodeVariableReferenceExpression(
                $"var p = UnityEditor.PackageManager.PackageInfo.FindForAssembly(Assembly.GetAssembly(typeof({className})));");
            ifCondition.TrueStatements.Add(s);

            CodeConditionStatement ifCondition2 = new CodeConditionStatement();

            ifCondition2.Condition = new CodeVariableReferenceExpression("p == null");
            ifCondition2.TrueStatements.Add(new CodeVariableReferenceExpression("_mainPath = LocalPath"));
            ifCondition2.FalseStatements.Add(
                new CodeVariableReferenceExpression($"_mainPath = p.assetPath + \"{mainFlag}\""));
            ifCondition.TrueStatements.Add(ifCondition2);

            MainPath.GetStatements.Add(ifCondition);

            CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement();

            returnStatement.Expression = new CodeVariableReferenceExpression("_mainPath");

            MainPath.GetStatements.Add(returnStatement);

            //生成代码

            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BracingStyle = "C";

            options.BlankLinesBetweenMembers = true;

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path))
            {
                provider.GenerateCodeFromCompileUnit(unit, sw, options);
            }
        }
Пример #13
0
        private void Statements(List <CodeLine> lines)
        {
            for (int i = 0; i < lines.Count; i++)
            {
                #region Line

                string code = lines[i].Code;

                if (string.IsNullOrEmpty(code))
                {
                    continue;
                }

                line     = lines[i].LineNumber;
                fileName = lines[i].FileName;

                #endregion Line

                #region Blocks

                var    parent      = blocks.Count > 0 ? blocks.Peek().Statements : main.Statements;
                string codeTrim    = code.TrimStart(Spaces);
                int    blocksCount = -1;

                if (codeTrim.Length > 0)
                {
                    CodeBlock block;
                    char      sym  = codeTrim[0];
                    bool      skip = false;

                    switch (sym)
                    {
                    case BlockOpen:
                        if (blocks.Count == 0)
                        {
                            block = new CodeBlock(lines[i], Scope, new CodeStatementCollection(), CodeBlock.BlockKind.Dummy, blocks.Count == 0 ? null : blocks.Peek());
                            CloseTopSingleBlock();
                            blocks.Push(block);
                        }
                        block = blocks.Peek();
                        if (block.Type == CodeBlock.BlockType.Expect)
                        {
                            block.Type = CodeBlock.BlockType.Within;
                        }
                        skip = true;
                        break;

                    case BlockClose:
                        if (blocks.Count == 0)
                        {
                            throw new ParseException(ExUnexpected, lines[i]);
                        }
                        CloseBlock();
                        skip = true;
                        break;

                    default:
                        if (blocks.Count > 0 && blocks.Peek().Type == CodeBlock.BlockType.Expect)
                        {
                            blocksCount = blocks.Count;
                            block       = blocks.Peek();
                            block.Type  = CodeBlock.BlockType.Within;
                            block.Level = blocksCount;
                        }
                        break;
                    }

                    if (skip)
                    {
                        code = codeTrim.Substring(1);
                        if (code.Length == 0)
                        {
                            continue;
                        }
                        lines[i].Code = code;
                    }
                }

                codeTrim = null;

                #endregion Blocks

                #region Tokens

                var token = GetToken(code);

                try
                {
                    switch (token)
                    {
                    case Token.Assign:
                        var assign = ParseAssign(code);
                        assign.LinePragma = lines[i];
                        parent.Add(assign);
                        break;

                    case Token.Command:
                        var command = new CodeExpressionStatement(OptimiseExpression(ParseCommand(code)));

                        if (command.Expression == null)
                        {
                            continue;
                        }

                        command.LinePragma = lines[i];
                        parent.Add(command);
                        break;

                    case Token.Label:
                        var label = new CodeExpressionStatement(ParseLabel(lines[i]));
                        label.LinePragma = lines[i];
                        parent.Add(label);
                        break;

                    case Token.Hotkey:
                        var hotkey = ParseHotkey(lines, i);
                        hotkey.LinePragma = lines[i];
                        parent.Add(hotkey);
                        break;

                    case Token.Flow:
                    {
                        var result = ParseFlow(lines, i);
                        if (result != null)
                        {
                            for (int n = 0; n < result.Length; n++)
                            {
                                result[n].LinePragma = lines[i];
                            }
                            parent.AddRange(result);
                        }
                    }
                    break;

                    case Token.Expression:
                    {
                        int n = i + 1;
                        if (IsFunction(code, n < lines.Count ? lines[n].Code : string.Empty))
                        {
                            ParseFunction(lines[i]);
                        }
                        else
                        {
                            var statements = ParseMultiExpression(code);

                            for (n = 0; n < statements.Length; n++)
                            {
                                var expr = OptimiseLoneExpression(statements[n].Expression);

                                if (expr == null)
                                {
                                    continue;
                                }
                                else
                                {
                                    statements[n] = new CodeExpressionStatement(expr);
                                }

                                statements[n].LinePragma = lines[n];
                                parent.Add(statements[n]);
                            }
                        }
                    }
                    break;

                    case Token.Directive:
                        ParseDirective(code);
                        break;

                    case Token.Unknown:
                    default:
                        throw new ParseException(ExUnexpected, lines[i]);
                    }
                }
#if !DEBUG
                catch (ParseException e)
                {
                    throw new ParseException(e.Message, lines[i]);
                }
#endif
                finally
                {
                }

                #endregion Tokens

                #region Blocks

                if (blocks.Count == blocksCount && blocks.Peek().IsSingle)
                {
                    CloseBlock(blocksCount, blocks.Count > blocksCount && blocksCount != -1);
                }

                #endregion Blocks
            }

            #region Blocks

            CloseTopSingleBlocks();
            CloseTopLabelBlock();
            CloseTopSingleBlocks();
            CloseSingleLoopBlocks();

            if (blocks.Count > 0)
            {
                throw new ParseException(ExUnclosedBlock, blocks.Peek().Line);
            }

            #endregion Blocks
        }
Пример #14
0
 protected override void Visit(CodeExpressionStatement statement)
 {
     Enumerate(statement.Expression);
     base.Visit(statement);
 }
        private static CodeMemberProperty GenerateDLinqPrimitiveProperty(IPropertyMap propertyMap, string propertyName, string fieldName, string typeName)
        {
            CodeMemberProperty propertyMember = new CodeMemberProperty();

            propertyMember.Name = propertyName;

            CodeTypeReference typeReference = new CodeTypeReference(typeName);

            propertyMember.Type = typeReference;

            propertyMember.Attributes = MemberAttributes.Public;

            //Column attribute
            CodeAttributeDeclaration columnAttrib = new CodeAttributeDeclaration("Column");

            CodeAttributeArgument columnNameArg = new CodeAttributeArgument("Name", new CodePrimitiveExpression(propertyMap.Column));

            columnAttrib.Arguments.Add(columnNameArg);

            CodeAttributeArgument storageArg = new CodeAttributeArgument("Storage", new CodePrimitiveExpression(fieldName));

            columnAttrib.Arguments.Add(storageArg);

            if (propertyMap.IsIdentity)
            {
                CodeAttributeArgument idArg = new CodeAttributeArgument("Id", new CodePrimitiveExpression(true));
                columnAttrib.Arguments.Add(idArg);
            }

            if (propertyMap.IsAssignedBySource)
            {
                CodeAttributeArgument autoGenArg = new CodeAttributeArgument("AutoGen", new CodePrimitiveExpression(true));
                columnAttrib.Arguments.Add(autoGenArg);
            }

            propertyMember.CustomAttributes.Add(columnAttrib);


            CodeFieldReferenceExpression    fieldExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName);
            CodeVariableReferenceExpression valueVar        = new CodeVariableReferenceExpression("value");
            CodePrimitiveExpression         propNameEpr     = new CodePrimitiveExpression(propertyMap.Name);

            //Getter method
            CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(fieldExpression);

            propertyMember.GetStatements.Add(returnStmt);


            //Setter method
            CodeAssignStatement setStmt = new CodeAssignStatement(fieldExpression, valueVar);

            CodeExpressionStatement onPropertyChangingStmt = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanging", new CodeExpression[] { propNameEpr }));
            CodeExpressionStatement onPropertyChangedStmt  = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanged", new CodeExpression[] { propNameEpr }));

            CodeBinaryOperatorExpression ifExpression = new CodeBinaryOperatorExpression(fieldExpression, CodeBinaryOperatorType.IdentityInequality, valueVar);

            CodeConditionStatement ifStmt = new CodeConditionStatement(ifExpression, new CodeStatement[]
            {
                onPropertyChangingStmt,
                setStmt,
                onPropertyChangedStmt
            });

            propertyMember.SetStatements.Add(ifStmt);

            return(propertyMember);
        }
Пример #16
0
 private void ValidateExpressionStatement(CodeExpressionStatement e)
 {
     ValidateExpression(e.Expression);
 }
	protected override void GenerateExpressionStatement
				(CodeExpressionStatement e)
			{
				GenerateExpression(e.Expression);
				if(!outputForInit)
				{
					Output.WriteLine(";");
				}
			}
Пример #18
0
    public CodeMemberMethod GenerateMethod(Smoke* smoke, Smoke.Method* method, string mungedName, CodeTypeReference iface)
    {
        string cppSignature = smoke->GetMethodSignature(method);
        CodeMemberMethod cmm = GenerateBasicMethodDefinition(smoke, method, cppSignature, iface);
        if (cmm == null)
        {
            return null;
        }

        // put the method into the correct type
        CodeTypeDeclaration containingType = type;
        if (cmm.Name.StartsWith("operator") || cmm.Name.StartsWith("explicit "))
        {
            if (!data.CSharpTypeMap.TryGetValue(cmm.Parameters[0].Type.GetStringRepresentation(), out containingType))
            {
                if (cmm.Parameters.Count < 2 ||
                    !data.CSharpTypeMap.TryGetValue(cmm.Parameters[1].Type.GetStringRepresentation(), out containingType))
                {
                    Debug.Print("  |--Can't find containing type for {0} - skipping", cppSignature);
                }
                return null;
            }
        }

        // already implemented?
        if (containingType.HasMethod(cmm))
        {
            if (iface == null || (method->flags & (uint) Smoke.MethodFlags.mf_protected) > 0)
            {
                // protected methods are not available in interfaces
                Debug.Print("  |--Skipping already implemented method {0}", cppSignature);
                return null;
            }
            else
            {
                cmm.PrivateImplementationType = iface;
            }
        }

        if (PreMethodBodyHooks != null)
        {
            PreMethodBodyHooks(smoke, method, cmm, containingType);
        }

        // do we have pass-by-ref parameters?
        bool generateInvokeForRefParams = cmm.Parameters.Cast<CodeParameterDeclarationExpression>().Any(expr => expr.Direction == FieldDirection.Ref);

        // generate the SmokeMethod attribute
        CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeMethod",
                                                                     new CodeAttributeArgument(
                                                                     	new CodePrimitiveExpression(cppSignature)));
        cmm.CustomAttributes.Add(attr);

        // choose the correct 'interceptor'
        CodeMethodInvokeExpression invoke;
        if ((cmm.Attributes & MemberAttributes.Static) == MemberAttributes.Static)
        {
            invoke = new CodeMethodInvokeExpression(SmokeSupport.staticInterceptor_Invoke);
        }
        else
        {
            invoke = new CodeMethodInvokeExpression(SmokeSupport.interceptor_Invoke);
        }

        // first pass the munged name, then the C++ signature
        invoke.Parameters.Add(new CodePrimitiveExpression(mungedName));
        invoke.Parameters.Add(new CodePrimitiveExpression(cppSignature));

        // retrieve the return type
        CodeTypeReference returnType;
        if ((method->flags & (uint) Smoke.MethodFlags.mf_dtor) > 0)
        {
            // destructor
            returnType = new CodeTypeReference(typeof(void));
        }
        else if (cmm.Name.StartsWith("explicit operator "))
        {
            // strip 'explicit operator' from the name to get the return type
            returnType = new CodeTypeReference(cmm.Name.Substring(18));
        }
        else
        {
            returnType = cmm.ReturnType;
        }

        // add the return type
        invoke.Parameters.Add(new CodeTypeOfExpression(returnType));
        invoke.Parameters.Add(new CodePrimitiveExpression(generateInvokeForRefParams));
        invoke.Parameters.Add(new CodeVariableReferenceExpression("smokeArgs"));

        ProcessEqualityOperators(cmm);

        CodeArrayCreateExpression argsInitializer = new CodeArrayCreateExpression(typeof(object[]));

        // add the parameters
        foreach (CodeParameterDeclarationExpression param in cmm.Parameters)
        {
            argsInitializer.Initializers.Add(new CodeTypeOfExpression(param.Type));
            string argReference = param.Name;
            int indexOfSpace = argReference.IndexOf(' ');
            if (indexOfSpace > 0)
            {
                argReference = argReference.Substring(0, indexOfSpace);
            }
            argsInitializer.Initializers.Add(new CodeArgumentReferenceExpression(argReference));
        }

        CodeStatement argsStatement = new CodeVariableDeclarationStatement(typeof(object[]), "smokeArgs", argsInitializer);
        cmm.Statements.Add(argsStatement);

        // we have to call "CreateProxy()" in constructors
        if (cmm is CodeConstructor)
        {
            cmm.Statements.Add(
                new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "CreateProxy")));
        }

        // add the method call statement
        CodeStatement statement;

        if (!generateInvokeForRefParams)
        {
            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                statement = new CodeMethodReturnStatement(new CodeCastExpression(returnType, invoke));
            }
            else
            {
                statement = new CodeExpressionStatement(invoke);
            }
            cmm.Statements.Add(statement);
        }
        else
        {
            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                statement = new CodeVariableDeclarationStatement(returnType, "smokeRetval",
                                                                 new CodeCastExpression(returnType, invoke));
                cmm.Statements.Add(statement);
            }
            else
            {
                statement = new CodeExpressionStatement(invoke);
                cmm.Statements.Add(statement);
            }

            int i = 0;
            foreach (CodeParameterDeclarationExpression param in cmm.Parameters)
            {
                ++i;
                if (param.Direction != FieldDirection.Ref)
                {
                    continue;
                }
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(param.Name),
                                                           new CodeCastExpression(param.Type.BaseType,
                                                                                  new CodeArrayIndexerExpression(
                                                                                  	new CodeVariableReferenceExpression("smokeArgs"),
                                                                                  	new CodePrimitiveExpression(i*2 - 1)
                                                                                  	)
                                                           	)
                                   	));
            }

            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("smokeRetval")));
            }
        }
        containingType.Members.Add(cmm);

        if ((method->flags & (uint) Smoke.MethodFlags.mf_dtor) != 0)
        {
            containingType.BaseTypes.Add(new CodeTypeReference(typeof(IDisposable)));
            CodeMemberMethod dispose = new CodeMemberMethod();
            dispose.Name = "Dispose";
            dispose.Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final;
            dispose.Statements.AddRange(cmm.Statements);
            dispose.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                                               	new CodeTypeReferenceExpression("GC"), "SuppressFinalize",
                                                               	new CodeThisReferenceExpression()
                                                               	)));
            containingType.Members.Add(dispose);
        }
        return cmm;
    }
Пример #19
0
			public void Visit(CodeExpressionStatement o)
			{
				g.GenerateExpressionStatement(o);
			}
	protected override void GenerateExpressionStatement
				(CodeExpressionStatement e)
			{
				GenerateExpression(e.Expression);
				Output.WriteLine();
			}
Пример #21
0
        private void CallMethod(Instruction il, MethodDefinition method, bool isVirtual)
        {
            if (method.DeclaringType.FullName == "System.Runtime.CompilerServices.RuntimeHelpers" &&
                method.Name == "InitializeArray") {
                InitializeArray();
                return;
            }

            CodeInvokeExpression expr = new CodeInvokeExpression();
            PopParametersInto(method.Parameters, expr.Parameters);

            CodeExpression targetObject = GetTargetObject(method, isVirtual);
            expr.Method = new CodeMethodReference(targetObject, method);

            if (method.IsConstructor || method.ReturnType.FullName == "System.Void") {
                CodeExpressionStatement stmt = new CodeExpressionStatement(expr);
                AddStatment(stmt);
            }
            else {
                Push(expr);
            }
        }
Пример #22
0
 private void GenerateExpressionStatement(CodeExpressionStatement e)
 {
     GenerateExpression(e.Expression);
     if (!generatingForLoop)
     {
         Output.WriteLine(";");
     }
 }
Пример #23
0
 private void ConditionalBranch(Instruction il, CodeBinaryOperator op)
 {
     var rhs = Pop();
     var lhs = Pop();
     RefineBinaryExpression(lhs, rhs);
     var condition = OptimizeBinaryExpression(lhs, op, rhs);
     var stmt = new CodeExpressionStatement(condition);
     AddStatment(stmt);
 }
Пример #24
0
        /// <summary>
        /// Add the properties to the class.
        /// </summary>
        private void AddProperties()
        {
            int propertyCount = 0;
            CodeMemberProperty endProperty = null;

            // For each table in the database.
            foreach (var table in _tables)
            {
                if (_data.TableList.Contains(table.TableName.ToUpper(), new ToUpperComparer()) == !_tableListExclusion)
                {
                    // Create a new property member
                    // and the accessor type.
                    CodeMemberProperty tableProperty = new CodeMemberProperty();
                    tableProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;

                    // Add the region directive if at the beginning
                    if (propertyCount == 0)
                    {
                        // Create a custom region.
                        CodeRegionDirective startRegion = new CodeRegionDirective(CodeRegionMode.Start, "Public Context Extension Properties");
                        tableProperty.StartDirectives.Add(startRegion);

                        // Increment the count.
                        propertyCount++;
                    }

                    // Assign the name and get and set indictors.
                    tableProperty.Name   = table.TableName;
                    tableProperty.HasGet = true;

                    // Add the comments to the property.
                    tableProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
                    tableProperty.Comments.Add(new CodeCommentStatement("Gets, the " + table.TableName.ToLower() + " replica property for the object.", true));
                    tableProperty.Comments.Add(new CodeCommentStatement("</summary>", true));

                    // Assign the return type.
                    tableProperty.Type = new CodeTypeReference((!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + table.TableName);

                    //// Create a new code condition statement.
                    //CodeConditionStatement conditionalStatement = new CodeConditionStatement(
                    //    new CodeVariableReferenceExpression("(String.IsNullOrEmpty(_specificPath))"),
                    //    new CodeStatement[] {
                    //        new CodeExpressionStatement(
                    //            new CodeSnippetExpression("return new " +
                    //                (!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + table.TableName + "()")) },
                    //    new CodeStatement[] {
                    //        new CodeExpressionStatement(
                    //            new CodeSnippetExpression("return new " +
                    //                (!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + table.TableName + "(_specificPath)")) });

                    CodeExpressionStatement conditionalStatement = new CodeExpressionStatement(
                        new CodeSnippetExpression("return new " +
                                                  (!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + table.TableName + "()"));

                    // Add the condition statement.
                    tableProperty.GetStatements.Add(conditionalStatement);

                    // Assign each property until the end.
                    endProperty = tableProperty;

                    // Add the property to the class.
                    _targetClass.Members.Add(tableProperty);
                }
            }

            if (endProperty != null)
            {
                // Create a custom endregion.
                CodeRegionDirective endRegion = new CodeRegionDirective(CodeRegionMode.End, "");
                endProperty.EndDirectives.Add(endRegion);
            }

            propertyCount = 0;
            endProperty   = null;

            // if a views exist.
            if (GetDatabaseViews())
            {
                // For each table in the database.
                foreach (var view in _views)
                {
                    if (_data.TableList.Contains(view.TableName.ToUpper(), new ToUpperComparer()) == !_tableListExclusion)
                    {
                        // Create a new property member
                        // and the accessor type.
                        CodeMemberProperty tableProperty = new CodeMemberProperty();
                        tableProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;

                        // Add the region directive if at the beginning
                        if (propertyCount == 0)
                        {
                            // Create a custom region.
                            CodeRegionDirective startRegion = new CodeRegionDirective(CodeRegionMode.Start, "Public Context Extension Properties");
                            tableProperty.StartDirectives.Add(startRegion);

                            // Increment the count.
                            propertyCount++;
                        }

                        // Assign the name and get and set indictors.
                        tableProperty.Name   = view.TableName;
                        tableProperty.HasGet = true;

                        // Add the comments to the property.
                        tableProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
                        tableProperty.Comments.Add(new CodeCommentStatement("Gets, the " + view.TableName.ToLower() + " replica property for the object.", true));
                        tableProperty.Comments.Add(new CodeCommentStatement("</summary>", true));

                        // Assign the return type.
                        tableProperty.Type = new CodeTypeReference((!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + view.TableName);

                        //// Create a new code condition statement.
                        //CodeConditionStatement conditionalStatement = new CodeConditionStatement(
                        //    new CodeVariableReferenceExpression("(String.IsNullOrEmpty(_specificPath))"),
                        //    new CodeStatement[] {
                        //    new CodeExpressionStatement(
                        //        new CodeSnippetExpression("return new " +
                        //            (!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + view.TableName + "()")) },
                        //    new CodeStatement[] {
                        //    new CodeExpressionStatement(
                        //        new CodeSnippetExpression("return new " +
                        //            (!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + view.TableName + "(_specificPath)")) });

                        CodeExpressionStatement conditionalStatement = new CodeExpressionStatement(
                            new CodeSnippetExpression("return new " +
                                                      (!String.IsNullOrEmpty(_extendedName) ? "LinqToSql." + _extendedName + "." : "LinqToSql.") + "Replica." + view.TableName + "()"));

                        // Add the condition statement.
                        tableProperty.GetStatements.Add(conditionalStatement);

                        // Assign each property until the end.
                        endProperty = tableProperty;

                        // Add the property to the class.
                        _targetClass.Members.Add(tableProperty);
                    }
                }
            }

            if (endProperty != null)
            {
                // Create a custom endregion.
                CodeRegionDirective endRegion = new CodeRegionDirective(CodeRegionMode.End, "");
                endProperty.EndDirectives.Add(endRegion);
            }
        }
Пример #25
0
 public CodeStatement SideEffect(CodeExpression exp)
 {
     var sideeffect = new CodeExpressionStatement(exp);
     Scope.Add(sideeffect);
     return sideeffect;
 }
Пример #26
0
 private void Generate(CodeExpressionStatement statement)
 {
     this.Generate(statement.Expression);
     this.WriteLine(";");
 }
Пример #27
0
        /// <summary>生成Render方法</summary>
        /// <param name="blocks"></param>
        /// <param name="lineNumbers"></param>
        /// <param name="typeDec"></param>
        private static void CreateRenderMethod(List <Block> blocks, Boolean lineNumbers, CodeTypeDeclaration typeDec)
        {
            CodeMemberMethod method = new CodeMemberMethod();

            typeDec.Members.Add(method);
            method.Name       = "Render";
            method.Attributes = MemberAttributes.Override | MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(String));

            // 生成代码
            CodeStatementCollection statementsMain = method.Statements;
            Boolean firstMemberFound = false;

            foreach (Block block in blocks)
            {
                if (block.Type == BlockType.Directive)
                {
                    continue;
                }
                if (block.Type == BlockType.Member)
                {
                    // 遇到类成员代码块,标识取反
                    firstMemberFound = !firstMemberFound;
                    continue;
                }
                // 只要现在还在类成员代码块区域内,就不做处理
                if (firstMemberFound)
                {
                    continue;
                }

                if (block.Type == BlockType.Statement)
                {
                    // 代码语句,直接拼接
                    CodeSnippetStatement statement = new CodeSnippetStatement(block.Text);
                    if (lineNumbers)
                    {
                        AddStatementWithLinePragma(block, statementsMain, statement);
                    }
                    else
                    {
                        statementsMain.Add(statement);
                    }
                }
                else if (block.Type == BlockType.Text)
                {
                    // 模版文本,直接Write
                    if (!String.IsNullOrEmpty(block.Text))
                    {
                        CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodePrimitiveExpression(block.Text) });
                        //statementsMain.Add(exp);
                        CodeExpressionStatement statement = new CodeExpressionStatement(exp);
                        if (lineNumbers)
                        {
                            AddStatementWithLinePragma(block, statementsMain, statement);
                        }
                        else
                        {
                            statementsMain.Add(statement);
                        }
                    }
                }
                else
                {
                    // 表达式,直接Write
                    CodeMethodInvokeExpression exp       = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodeArgumentReferenceExpression(block.Text.Trim()) });
                    CodeExpressionStatement    statement = new CodeExpressionStatement(exp);
                    if (lineNumbers)
                    {
                        AddStatementWithLinePragma(block, statementsMain, statement);
                    }
                    else
                    {
                        statementsMain.Add(statement);
                    }
                }
            }

            statementsMain.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Output"), "ToString"), new CodeExpression[0])));
        }
Пример #28
0
 protected override void GenerateExpressionStatement(CodeExpressionStatement e)
 {
     Output.Write("expression");
 }
Пример #29
0
        /// <summary>生成成员代码块</summary>
        /// <param name="block"></param>
        /// <param name="generatorType"></param>
        /// <param name="lineNumbers"></param>
        /// <param name="provider"></param>
        /// <param name="options"></param>
        /// <param name="firstMemberFound"></param>
        /// <returns></returns>
        private static Boolean GenerateMemberForBlock(Block block, CodeTypeDeclaration generatorType, Boolean lineNumbers, CodeDomProvider provider, CodeGeneratorOptions options, Boolean firstMemberFound)
        {
            CodeSnippetTypeMember member = null;

            if (!firstMemberFound)
            {
                // 发现第一个<#!后,认为是类成员代码的开始,直到下一个<#!作为结束
                if (block.Type == BlockType.Member)
                {
                    firstMemberFound = true;
                    if (!String.IsNullOrEmpty(block.Text))
                    {
                        member = new CodeSnippetTypeMember(block.Text);
                    }
                }
            }
            else
            {
                // 再次遇到<#!,此时,成员代码准备结束
                if (block.Type == BlockType.Member)
                {
                    firstMemberFound = false;
                    if (!String.IsNullOrEmpty(block.Text))
                    {
                        member = new CodeSnippetTypeMember(block.Text);
                    }
                }
                else if (block.Type == BlockType.Text)
                {
                    CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodePrimitiveExpression(block.Text) });
                    CodeExpressionStatement    statement  = new CodeExpressionStatement(expression);
                    using (StringWriter writer = new StringWriter())
                    {
                        provider.GenerateCodeFromStatement(statement, writer, options);
                        member = new CodeSnippetTypeMember(writer.ToString());
                    }
                }
                else if (block.Type == BlockType.Expression)
                {
                    CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodeArgumentReferenceExpression(block.Text.Trim()) });
                    CodeExpressionStatement    statement  = new CodeExpressionStatement(expression);
                    using (StringWriter writer = new StringWriter())
                    {
                        provider.GenerateCodeFromStatement(statement, writer, options);
                        member = new CodeSnippetTypeMember(writer.ToString());
                    }
                }
                else if (block.Type == BlockType.Statement)
                {
                    member = new CodeSnippetTypeMember(block.Text);
                }
            }
            if (member != null)
            {
                if (lineNumbers)
                {
                    Boolean flag       = String.IsNullOrEmpty(block.Name);
                    Int32   lineNumber = (block.StartLine > 0) ? block.StartLine : 1;
                    if (flag)
                    {
                        generatorType.Members.Add(new CodeSnippetTypeMember("#line " + lineNumber));
                    }
                    else
                    {
                        member.LinePragma = new CodeLinePragma(block.Name, lineNumber);
                    }
                    generatorType.Members.Add(member);
                    if (flag)
                    {
                        generatorType.Members.Add(new CodeSnippetTypeMember("#line default"));
                    }
                }
                else
                {
                    generatorType.Members.Add(member);
                }
            }
            return(firstMemberFound);
        }
Пример #30
0
 protected virtual void Visit(CodeExpressionStatement statement)
 {
 }
Пример #31
0
        static CodeTypeDeclaration CreateAstComparisonVisitorClass(List <Type> nodeTypes)
        {
            CodeTypeDeclaration td = new CodeTypeDeclaration("AstComparisonVisitor");

            td.TypeAttributes = TypeAttributes.Public;
            td.IsPartial      = true;

            //td.BaseTypes.Add(new CodeTypeReference("IAstVisitor"));

            foreach (Type type in nodeTypes)
            {
                if (!type.IsAbstract)
                {
                    EasyMethod m = td.AddMethod(typeof(bool), VisitPrefix + type.Name);
                    m.Attributes = MemberAttributes.Public;
                    m.AddParameter(ConvertType(type), GetFieldName(type.Name));
                    const string right_hand_side_name = "d";
                    m.AddParameter(typeof(object), right_hand_side_name);

                    List <CodeStatement> assertions = new List <CodeStatement>();
                    string         varVariableName  = GetFieldName(type.Name);
                    CodeExpression var = Easy.Var(varVariableName);
                    assertions.Add(IfNullSetFailure(var));

                    if (varVariableName == "using")
                    {
                        varVariableName = "@using";
                    }

                    CodeExpression r_var = Easy.Var(right_hand_side_name);
                    assertions.Add(IfNullSetFailure(r_var));

                    // Confirm their types are the same.
                    m.Statements.Add(new CodeSnippetStatement("\t\t\tif(" + varVariableName + ".GetType() != " + right_hand_side_name + ".GetType()) {return SetFailure();}"));

                    // Cast the object parameter to whatever the other parameter is, and call the variable 'data'.
                    // Like so: AddHandlerStatement data = (AddHandlerStatement) d;
                    m.Statements.Add(new CodeSnippetStatement("\t\t\tvar data = (" + ConvertType(type).BaseType + ")d;"));

                    m.Statements.Add(new CodeConditionStatement(new CodeSnippetExpression("!IsMatch(" + varVariableName + ", data)"),
                                                                new CodeSnippetStatement("\t\t\t\treturn SetFailure();")));

                    AddFieldVisitCode(m, type, var, assertions, false);

                    if (type.GetCustomAttributes(typeof(HasChildrenAttribute), true).Length > 0)
                    {
                        m.Body.Return(var.InvokeMethod("AcceptChildren", Easy.This, Easy.Var(right_hand_side_name)));
                    }
                    else
                    {
                        CodeExpressionStatement lastStatement = null;
                        if (m.Statements.Count > 0)
                        {
                            lastStatement = m.Statements[m.Statements.Count - 1] as CodeExpressionStatement;
                        }
                        if (lastStatement != null)
                        {
                            m.Statements.RemoveAt(m.Statements.Count - 1);
                            m.Body.Return(lastStatement.Expression);
                        }
                        else
                        {
                            m.Body.Return(new CodeSnippetExpression("true"));
                        }
                    }

                    for (int i = 0; i < assertions.Count; i++)
                    {
                        m.Statements.Insert(i, assertions[i]);
                    }
                }
            }
            return(td);
        }
Пример #32
0
        /// <summary>
        /// Method to generate the code to implement the type
        /// </summary>
        /// <returns></returns>
        public override CodeTypeDeclaration GetCodeType()
        {
            CodeTypeDeclaration type = new CodeTypeDeclaration(Name);

            type.IsClass = true;
            type.BaseTypes.Add(new CodeTypeReference(typeof(BaseParser)));
            type.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            type.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(GuidAttribute)),
                                                                   new CodeAttributeArgument(new CodePrimitiveExpression(Uuid.ToString()))));

            if (DisplayClass != Guid.Empty)
            {
                type.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(DisplayClassAttribute)),
                                                                       new CodeAttributeArgument(new CodePrimitiveExpression(DisplayClass.ToString()))));
            }

            if (!String.IsNullOrWhiteSpace(_formatString))
            {
                type.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(FormatStringAttribute)),
                                                                       new CodeAttributeArgument(new CodePrimitiveExpression(_formatString))));
            }

            CodeConstructor defaultConstructor = new CodeConstructor();

            defaultConstructor.Attributes = MemberAttributes.Public;
            type.Members.Add(defaultConstructor);

            CodeConstructor fromStreamConstructor = new CodeConstructor();

            fromStreamConstructor.Attributes = MemberAttributes.Public;
            fromStreamConstructor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(DataReader)), "reader"));
            fromStreamConstructor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(StateDictionary)), "state"));
            fromStreamConstructor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(Logger)), "logger"));

            fromStreamConstructor.BaseConstructorArgs.Add(CodeGen.GetArgument("reader"));
            fromStreamConstructor.BaseConstructorArgs.Add(CodeGen.GetArgument("state"));
            fromStreamConstructor.BaseConstructorArgs.Add(CodeGen.GetArgument("logger"));
            type.Members.Add(fromStreamConstructor);

            CodeMemberMethod preSerializer = new CodeMemberMethod();

            preSerializer.Name       = "PreSerializer";
            preSerializer.Attributes = MemberAttributes.Private;

            CodeMemberMethod postSerializer = new CodeMemberMethod();

            postSerializer.Name       = "PostSerializer";
            postSerializer.Attributes = MemberAttributes.Private;

            CodeMemberMethod preDeserializer = new CodeMemberMethod();

            preDeserializer.Name       = "PreDeserializer";
            preDeserializer.Attributes = MemberAttributes.Private;

            CodeMemberMethod postDeserializer = new CodeMemberMethod();

            postDeserializer.Name       = "PostDeserializer";
            postDeserializer.Attributes = MemberAttributes.Private;

            CodeMemberMethod fromStreamMethod = new CodeMemberMethod();

            fromStreamMethod.Name       = "FromStream";
            fromStreamMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;

            CodeMemberMethod toStreamMethod = new CodeMemberMethod();

            toStreamMethod.Name       = "ToStream";
            toStreamMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;

            if (PreserializeExpression.IsValid)
            {
                toStreamMethod.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(), "Resolve", CodeGen.GetPrimitive(PreserializeExpression.Expression)));
            }

            foreach (MemberEntry entry in Members)
            {
                IMemberReaderWriter readerWriter = entry as IMemberReaderWriter;
                CodeMemberField     field        = entry.GetMemberDeclaration();
                if (entry.Hidden)
                {
                    field.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(HiddenMemberAttribute)),
                                                                            new CodeAttributeArgument(CodeGen.GetPrimitive(true))));
                }

                if (entry.ReadOnly)
                {
                    field.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ReadOnlyMemberAttribute)),
                                                                            new CodeAttributeArgument(CodeGen.GetPrimitive(true))));
                }

                if (entry.DisplayClass != Guid.Empty)
                {
                    field.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(DisplayClassAttribute)),
                                                                            new CodeAttributeArgument(CodeGen.GetPrimitive(entry.DisplayClass.ToString()))));
                }

                type.Members.Add(field);

                CodeMemberMethod serMethod       = entry.GetSerializerMethod();
                CodeMemberMethod deserMethod     = entry.GetDeserializerMethod();
                CodeMemberMethod preserMethod    = entry.GetPreSerializeMethod();
                CodeMemberMethod postserMethod   = entry.GetPostSerializeMethod();
                CodeMemberMethod predeserMethod  = entry.GetPreDeserializeMethod();
                CodeMemberMethod postdeserMethod = entry.GetPostDeserializeMethod();

                if (readerWriter == null)
                {
                    type.Members.Add(serMethod);
                    type.Members.Add(deserMethod);
                }

                if (preserMethod.Statements.Count > 0)
                {
                    type.Members.Add(preserMethod);
                    preSerializer.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(), preserMethod.Name));
                }

                if (postserMethod.Statements.Count > 0)
                {
                    type.Members.Add(postserMethod);
                    postSerializer.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(), postserMethod.Name));
                }

                if (predeserMethod.Statements.Count > 0)
                {
                    type.Members.Add(predeserMethod);
                    preDeserializer.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(),
                                                                      predeserMethod.Name));
                }

                if (postdeserMethod.Statements.Count > 0)
                {
                    type.Members.Add(postdeserMethod);
                    postDeserializer.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(),
                                                                       postserMethod.Name));
                }

                CodeStatement readStatement  = null;
                CodeStatement writeStatement = null;

                if (readerWriter != null)
                {
                    CodeExpression readExpression = readerWriter.GetReaderExpression(GetReader());

                    if (entry.ValidateExpression.IsValid)
                    {
                        readExpression = CodeGen.CallMethod(CodeGen.GetThis(), "V", readExpression, CodeGen.GetPrimitive(entry.ValidateExpression.Expression));
                    }

                    readStatement =
                        CodeGen.GetAssign(CodeGen.GetThisField(field.Name), readExpression);

                    writeStatement =
                        new CodeExpressionStatement(readerWriter.GetWriterExpression(GetWriter(), CodeGen.GetThisField(field.Name)));
                }
                else
                {
                    CodeExpression readExpression = CodeGen.CallMethod(CodeGen.GetThis(), deserMethod.Name, GetReader());

                    if (entry.ValidateExpression.IsValid)
                    {
                        readExpression = CodeGen.CallMethod(CodeGen.GetThis(), "V", readExpression, CodeGen.GetPrimitive(entry.ValidateExpression.Expression));
                    }

                    readStatement =
                        CodeGen.GetAssign(CodeGen.GetThisField(field.Name), readExpression);

                    writeStatement =
                        new CodeExpressionStatement(CodeGen.CallMethod(CodeGen.GetThis(), serMethod.Name,
                                                                       GetWriter(),
                                                                       CodeGen.GetThisField(field.Name)));
                }

                if (entry.OptionalExpression.IsValid)
                {
                    readStatement  = CodeGen.GetIf(entry.OptionalExpression.GetCheckExpression(), new[] { readStatement });
                    writeStatement = CodeGen.GetIf(entry.OptionalExpression.GetCheckExpression(), new[] { writeStatement });
                }

                fromStreamMethod.Statements.Add(readStatement);
                toStreamMethod.Statements.Add(writeStatement);
            }

            if (preDeserializer.Statements.Count > 0)
            {
                fromStreamMethod.Statements.Insert(0, CodeGen.GetStatement(CodeGen.CallMethod(CodeGen.GetThis(), "PreDeserializer")));
                type.Members.Add(preDeserializer);
            }

            toStreamMethod.Statements.Add(new CodeMethodInvokeExpression(GetWriter(), "Flush"));
            if (preSerializer.Statements.Count > 0)
            {
                toStreamMethod.Statements.Insert(0, CodeGen.GetStatement(CodeGen.CallMethod(CodeGen.GetThis(), "PreSerializer")));
                type.Members.Add(preSerializer);
            }

            if (postDeserializer.Statements.Count > 0)
            {
                fromStreamMethod.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(), "PostDeserializer"));
                type.Members.Add(postDeserializer);
            }

            if (PostDeserializeExpression.IsValid)
            {
                fromStreamMethod.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(), "Resolve", CodeGen.GetPrimitive(PostDeserializeExpression.Expression)));
            }

            if (postSerializer.Statements.Count > 0)
            {
                toStreamMethod.Statements.Add(CodeGen.CallMethod(CodeGen.GetThis(), "PostSerializer"));
                type.Members.Add(postSerializer);
            }

            type.Members.Add(fromStreamMethod);
            type.Members.Add(toStreamMethod);

            return(type);
        }
Пример #33
0
        private CodeTypeDeclaration CreateDataContext(XDocument dtmlXml, IEnumerable <DocType> docTypes)
        {
            string methodName = "OnCreated";
            CodeExpressionStatement statement = new CodeExpressionStatement(new CodeMethodInvokeExpression(null, methodName, new CodeExpression[0]));

            string dataContextName = dtmlXml.Root.Attribute("DataContextName").Value;

            //ensure the naming is standard
            if (!dataContextName.ToUpper().Contains("DATACONTEXT"))
            {
                dataContextName += "DataContext";
            }
            CodeTypeDeclaration dataContext = new CodeTypeDeclaration(dataContextName);

            dataContext.BaseTypes.Add("UmbracoDataContext");
            dataContext.IsClass   = true;
            dataContext.IsPartial = true;

            string partialOnCreated = string.Empty;

            if (IsCSharpCodeProvider())
            {
                partialOnCreated = " partial void " + methodName + "();\r\n";
            }
            else
            {
                partialOnCreated = " Partial Private Void " + methodName + "()\r\nEnd Sub\r\n";
            }
            CodeSnippetTypeMember onCreated = new CodeSnippetTypeMember(partialOnCreated);
            CodeRegionDirective   region    = new CodeRegionDirective(CodeRegionMode.Start, "Partials");

            onCreated.StartDirectives.Add(region);
            onCreated.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Partials"));
            dataContext.Members.Add(onCreated);

            //constructor with no arguments
            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Public;
            ctor.BaseConstructorArgs.Add(new CodePropertyReferenceExpression());
            ctor.Statements.Add(statement);
            dataContext.Members.Add(ctor);

            //constructor that takes an umbracoDataProvider
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(new CodeParameterDeclarationExpression("UmbracoDataProvider", "provider"));
            ctor.BaseConstructorArgs.Add(new CodePropertyReferenceExpression(null, "provider"));
            ctor.Statements.Add(statement);
            dataContext.Members.Add(ctor);

            //Generate the Tree<TDocType> for each docType
            foreach (var dt in docTypes)
            {
                string name = dt.TypeName;
                if (this.PluralizeCollections)
                {
                    name = PluraliseName(dt.TypeName);
                }
                var t = new CodeTypeReference("Tree");
                t.TypeArguments.Add(dt.TypeName);

                CodeMemberProperty p = new CodeMemberProperty();
                p.Name       = name;
                p.Type       = t;
                p.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                p.HasGet     = true;
                p.HasSet     = false;

                if (!Args.IsInterface)
                {
                    p.GetStatements.Add(
                        new CodeMethodReturnStatement(
                            new CodeMethodInvokeExpression(
                                new CodeMethodReferenceExpression(
                                    new CodeThisReferenceExpression(),
                                    "LoadTree",
                                    new CodeTypeReference[] {
                        new CodeTypeReference(dt.TypeName)
                    }),
                                new CodeExpression[0])
                            )
                        );
                }

                dataContext.Members.Add(p);
            }
            return(dataContext);
        }
Пример #34
0
            private void GenerateOnParentChangedMethod(IReference input, CodeMemberProperty property, ITransformationContext context)
            {
                var onParentChanged = new CodeMemberMethod()
                {
                    Name       = "OnParentChanged",
                    Attributes = MemberAttributes.Family | MemberAttributes.Override,
                    ReturnType = new CodeTypeReference(typeof(void))
                };

                onParentChanged.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IModelElement).ToTypeReference(), "newParent"));
                onParentChanged.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IModelElement).ToTypeReference(), "oldParent"));

                var appendix = property.Name;

                if (appendix == "Parent")
                {
                    appendix += "Reference";
                }
                var oldElementVar = new CodeVariableReferenceExpression("old" + appendix);
                var newElementVar = new CodeVariableReferenceExpression("new" + appendix);

                var castRef = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ModelHelper).ToTypeReference()), "CastAs", property.Type);
                var nullRef = new CodePrimitiveExpression(null);
                var thisRef = new CodeThisReferenceExpression();

                onParentChanged.Statements.Add(new CodeVariableDeclarationStatement(property.Type, oldElementVar.VariableName,
                                                                                    new CodeMethodInvokeExpression(castRef, new CodeArgumentReferenceExpression("oldParent"))));
                onParentChanged.Statements.Add(new CodeVariableDeclarationStatement(property.Type, newElementVar.VariableName,
                                                                                    new CodeMethodInvokeExpression(castRef, new CodeArgumentReferenceExpression("newParent"))));

                CodeStatement unsetOld;
                CodeStatement setNew;

                string oppositeName = context.Trace.ResolveIn(this, input.Opposite).Name;

                if (input.Opposite.UpperBound == 1)
                {
                    unsetOld = new CodeAssignStatement(new CodePropertyReferenceExpression(oldElementVar, oppositeName), nullRef);
                    setNew   = new CodeAssignStatement(new CodePropertyReferenceExpression(newElementVar, oppositeName), thisRef);
                }
                else
                {
                    unsetOld = new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                                               new CodePropertyReferenceExpression(oldElementVar, oppositeName), "Remove", thisRef));
                    setNew = new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                                             new CodePropertyReferenceExpression(newElementVar, oppositeName), "Add", thisRef));
                }

                onParentChanged.Statements.Add(new CodeConditionStatement(
                                                   new CodeBinaryOperatorExpression(oldElementVar, CodeBinaryOperatorType.IdentityInequality, nullRef), unsetOld));
                onParentChanged.Statements.Add(new CodeConditionStatement(
                                                   new CodeBinaryOperatorExpression(newElementVar, CodeBinaryOperatorType.IdentityInequality, nullRef), setNew));

                var valueChangedEvArgs = typeof(ValueChangedEventArgs).ToTypeReference();
                var valueChangeDef     = new CodeVariableDeclarationStatement(valueChangedEvArgs, "e",
                                                                              new CodeObjectCreateExpression(valueChangedEvArgs, oldElementVar, newElementVar));
                var valueChangeRef = new CodeVariableReferenceExpression(valueChangeDef.Name);

                onParentChanged.Statements.Add(valueChangeDef);
                var referenceRef = new CodeFieldReferenceExpression(null, "_" + input.Name.ToCamelCase() + "Reference");

                onParentChanged.Statements.Add(property.CreateOnChangedEventPattern(valueChangedEvArgs, valueChangeRef));
                onParentChanged.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanged",
                                                                              new CodePrimitiveExpression(property.Name), valueChangeRef, referenceRef));

                onParentChanged.Statements.Add(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(),
                                                                              onParentChanged.Name, new CodeArgumentReferenceExpression("newParent"), new CodeArgumentReferenceExpression("oldParent")));

                onParentChanged.WriteDocumentation("Gets called when the parent model element of the current model element changes",
                                                   null, new Dictionary <string, string>()
                {
                    {
                        "oldParent", "The old parent model element"
                    },
                    {
                        "newParent", "The new parent model element"
                    }
                });

                onParentChanged.SetMerge(other =>
                {
                    var mergedOnParent = new CodeMemberMethod()
                    {
                        Name       = "OnParentChanged",
                        Attributes = MemberAttributes.Family | MemberAttributes.Override,
                        ReturnType = new CodeTypeReference(typeof(void))
                    };
                    for (int i = 0; i < onParentChanged.Parameters.Count; i++)
                    {
                        mergedOnParent.Parameters.Add(onParentChanged.Parameters[i]);
                    }
                    var otherCasted = other as CodeMemberMethod;
                    mergedOnParent.Statements.AddRange(otherCasted.Statements);
                    mergedOnParent.Statements.RemoveAt(mergedOnParent.Statements.Count - 1);
                    mergedOnParent.Statements.AddRange(onParentChanged.Statements);
                    mergedOnParent.Statements.Remove(valueChangeDef);
                    return(mergedOnParent);
                });

                property.DependentMembers(true).Add(onParentChanged);
            }
 void AppendExpressionStatement(CodeExpressionStatement statement)
 {
     codeBuilder.AppendIndented(String.Empty);
     AppendExpression(statement.Expression);
     codeBuilder.AppendLine();
 }
Пример #36
0
        /// <summary>
        /// Generate all the necessary logic for serialization of payload types used by grain interfaces.
        /// </summary>
        internal static void GenerateSerializationForClass(Type t, CodeNamespace container, HashSet <string> referencedNamespaces, Language language)
        {
            var generateSerializers = !CheckForCustomSerialization(t);
            var generateCopier      = !CheckForCustomCopier(t);

            if (!generateSerializers && !generateCopier)
            {
                return; // If the class declares all custom implementations, then we don't need to do anything...
            }
            bool notVB         = (language != Language.VisualBasic);
            var  openGenerics  = notVB ? "<" : "(Of ";
            var  closeGenerics = notVB ? ">" : ")";

            // Add the class's namespace to this namespace's imports, as well as some other imports we use
            container.Imports.Add(new CodeNamespaceImport("System"));
            container.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            container.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            container.Imports.Add(new CodeNamespaceImport("Orleans.Serialization"));
            container.Imports.Add(new CodeNamespaceImport(t.Namespace));

            // Create the class declaration, including any required generic parameters
            // At one time this was a struct, not a class, so all the variable names are "structFoo". Too bad.
            // Note that we need to replace any periods in the type name with _ to properly handle nested classes
            var className = TypeUtils.GetSimpleTypeName(TypeUtils.GetFullName(t));
            var serializationClassName     = className.Replace('.', '_') + SERIALIZER_CLASS_NAME_SUFFIX;
            var serializationClassOpenName = serializationClassName;
            var classDecl = new CodeTypeDeclaration(serializationClassName)
            {
                IsClass = true
            };

            classDecl.Attributes     = (classDecl.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            classDecl.TypeAttributes = TypeAttributes.NotPublic;
            CodeGeneratorBase.MarkAsGeneratedCode(classDecl);

            if (!t.IsGenericType)
            {
                classDecl.CustomAttributes.Add(
                    new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute),
                                                                       CodeTypeReferenceOptions.GlobalReference)));
            }

            if (t.IsGenericType)
            {
                className += openGenerics;
                serializationClassOpenName += openGenerics;
                bool first = true;
                foreach (var genericParameter in t.GetGenericTypeDefinition().GetGenericArguments())
                {
                    var param = new CodeTypeParameter(genericParameter.Name);
                    if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != GenericParameterAttributes.None)
                    {
                        param.Constraints.Add(" class");
                    }
                    if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != GenericParameterAttributes.None)
                    {
                        param.Constraints.Add(" struct");
                    }

                    var constraints = genericParameter.GetGenericParameterConstraints();
                    foreach (var constraintType in constraints)
                    {
                        param.Constraints.Add(new CodeTypeReference(TypeUtils.GetParameterizedTemplateName(constraintType)));
                    }

                    if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != GenericParameterAttributes.None)
                    {
                        param.HasConstructorConstraint = true;
                    }

                    classDecl.TypeParameters.Add(param);
                    if (!first)
                    {
                        className += ", ";
                        serializationClassOpenName += ",";
                    }
                    className += genericParameter.Name;
                    first      = false;
                }
                className += closeGenerics;
                serializationClassOpenName += closeGenerics;
            }

            // A couple of repeatedly-used CodeDom snippets
            var classType                  = new CodeTypeOfExpression(className);
            var classTypeReference         = new CodeTypeReference(className);
            var objectTypeReference        = new CodeTypeReference(typeof(object));
            var serMgrRefExp               = new CodeTypeReferenceExpression(typeof(SerializationManager));
            var currentSerialzationContext = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(SerializationContext)), "Current");

            // Static DeepCopyInner method:
            var copier = new CodeMemberMethod();

            if (generateCopier)
            {
                classDecl.Members.Add(copier);
            }

            copier.Attributes = (copier.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            copier.Attributes = (copier.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            copier.Name       = "DeepCopier";
            copier.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "original"));
            bool shallowCopyable = t.IsOrleansShallowCopyable();

            if (shallowCopyable)
            {
                copier.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("original")));
            }
            else
            {
                copier.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input",
                                                                           new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("original"))));
            }

            copier.ReturnType = objectTypeReference;

            // Static serializer method:
            var serializer = new CodeMemberMethod();

            if (generateSerializers)
            {
                classDecl.Members.Add(serializer);
            }

            serializer.Attributes = (serializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            serializer.Attributes = (serializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            serializer.Name       = "Serializer";
            serializer.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "untypedInput"));
            serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream"));
            serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
            serializer.ReturnType = new CodeTypeReference(typeof(void));
            serializer.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input",
                                                                           new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("untypedInput"))));

            // Static deserializer method; note that this will never get called for null values or back references
            var deserializer = new CodeMemberMethod();

            if (generateSerializers)
            {
                classDecl.Members.Add(deserializer);
            }

            deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            deserializer.Name       = "Deserializer";
            deserializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
            deserializer.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(BinaryTokenStreamReader), CodeTypeReferenceOptions.GlobalReference), "stream"));
            deserializer.ReturnType = objectTypeReference;

            // Static constructor, which just calls the Init method
            var staticConstructor = new CodeTypeConstructor();

            classDecl.Members.Add(staticConstructor);
            staticConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(null, "Register")));

            // Init method, which registers the type with the serialization manager, and later may get some static FieldInfo initializers
            var init = new CodeMemberMethod();

            classDecl.Members.Add(init);
            init.Name       = "Register";
            init.Attributes = (init.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            init.Attributes = (init.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;

            if (generateCopier && generateSerializers)
            {
                init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType,
                                                                   new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"),
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"),
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer")));
            }
            else if (generateCopier)
            {
                init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType,
                                                                   new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"),
                                                                   null,
                                                                   null));
            }
            else
            {
                init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType,
                                                                   null,
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"),
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer")));
            }

            CodeStatement constructor;
            var           consInfo = t.GetConstructor(Type.EmptyTypes);

            if (consInfo != null)
            {
                if (!t.ContainsGenericParameters)
                {
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeObjectCreateExpression(t));
                }
                else
                {
                    var typeName = TypeUtils.GetParameterizedTemplateName(t, tt => tt.Namespace != container.Name && !referencedNamespaces.Contains(tt.Namespace), true);
                    if (language == Language.VisualBasic)
                    {
                        typeName = typeName.Replace("<", "(Of ").Replace(">", ")");
                    }
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result",
                                                                       new CodeObjectCreateExpression(typeName));
                }
            }
            else if (t.IsValueType)
            {
                constructor = !t.ContainsGenericParameters
                    ? new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(t)))
                    : new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(TypeUtils.GetTemplatedName(t))));
            }
            else
            {
                if (!t.ContainsGenericParameters)
                {
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result",
                                                                       new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)),
                                                                                                                                        "GetUninitializedObject", new CodeTypeOfExpression(t))));
                }
                else
                {
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result",
                                                                       new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)),
                                                                                                                                        "GetUninitializedObject", new CodeTypeOfExpression(TypeUtils.GetTemplatedName(t)))));
                }
            }
            if (!shallowCopyable)
            {
                copier.Statements.Add(constructor);
                copier.Statements.Add(new CodeMethodInvokeExpression(currentSerialzationContext, "RecordObject",
                                                                     new CodeVariableReferenceExpression("original"),
                                                                     new CodeVariableReferenceExpression("result")));
            }
            deserializer.Statements.Add(constructor);

            // For structs, once we encounter a field that we have to use reflection to set, we need to switch to a boxed representation and reflection
            // for the rest of the fields in the struct while setting. This flag indicates that we're in that mode.
            bool usingBoxedReflection = false;

            // For every field in the class:
            int counter             = 0;
            List <FieldInfo> fields = GetAllFields(t).ToList();

            fields.Sort(new FieldNameComparer());
            foreach (var fld in fields)
            {
                if (fld.IsNotSerialized || fld.IsLiteral)
                {
                    continue;
                }

                var fldType = fld.FieldType;
                if (TypeUtilities.IsTypeIsInaccessibleForSerialization(fldType, t.Module))
                {
                    ConsoleText.WriteStatus("Skipping generation of serializer for {0} because its field {1} is of a private type.", t.FullName, fld.Name);
                    return; // We cannot deserialize a class with a field of non-public type. Need to add a proper reporting here.
                }

                // Import the namespace for the field's type (and any of its parameters), just in case it's not already added
                ImportFieldNamespaces(fld.FieldType, container.Imports);
                SerializerGenerationManager.RecordTypeToGenerate(fld.FieldType);
                counter++;

                // Add the statements moving to and from a class instance, to the instance creation method and the non-default constructor
                // Getter and setter for this field's value from a class object
                CodeExpression  getter = null;
                SetterGenerator setter = null;

                var name = fld.Name;
                // Normalize the field name -- strip trailing @ (F#) and look for automatic properties
                var normalizedName = name.TrimEnd('@');
                if (name.StartsWith("<"))
                {
                    // Backing field for an automatic property; see if it's public so we can use it
                    var propertyName = name.Substring(1, name.IndexOf('>') - 1).TrimEnd('@');
                    var property     = t.GetProperty(propertyName);
                    // If the property is public and not hidden...
                    if ((property != null) && property.DeclaringType == fld.DeclaringType)
                    {
                        if (property.GetGetMethod() != null)
                        {
                            getter = new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("input"),
                                                                         propertyName);
                        }
                        if (!usingBoxedReflection && (property.GetSetMethod() != null))
                        {
                            setter = value =>
                            {
                                var s = new CodeAssignStatement
                                {
                                    Left  = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("result"), propertyName),
                                    Right = value
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s }));
                            };
                        }
                    }
                }

                var typeName = TypeUtils.GetTemplatedName(fld.FieldType, _ => !_.IsGenericParameter, language);

                // See if it's a public field
                if ((getter == null) || (setter == null))
                {
                    if (fld.Attributes.HasFlag(FieldAttributes.Public))
                    {
                        if (getter == null)
                        {
                            getter = new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("input"), normalizedName);
                        }

                        if (!usingBoxedReflection && (setter == null) && !fld.IsInitOnly)
                        {
                            setter = value =>
                            {
                                var s = new CodeAssignStatement
                                {
                                    Left  = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("result"), normalizedName),
                                    Right = value
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s }));
                            };
                        }
                    }
                }

                // Have to use reflection
                if ((getter == null) || (setter == null))
                {
                    // Add a static field for the FieldInfo, and a static constructor
                    string infoName = "fieldInfo" + counter;
                    var    info     = new CodeMemberField(typeof(FieldInfo), infoName);
                    info.Attributes |= MemberAttributes.Private | MemberAttributes.Static;
                    classDecl.Members.Add(info);
                    CodeTypeOfExpression fieldAccessType;
                    if (fld.DeclaringType == t)
                    {
                        fieldAccessType = classType;
                    }
                    else
                    {
                        FieldInfo fld2 = t.GetField(fld.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        if ((fld2 != null) && fld2.DeclaringType == fld.DeclaringType)
                        {
                            fieldAccessType = classType;
                        }
                        else
                        {
                            fieldAccessType = fld.DeclaringType.IsGenericType
                                ? new CodeTypeOfExpression(TypeUtils.GetTemplatedName(fld.DeclaringType))
                                : new CodeTypeOfExpression(fld.DeclaringType);
                        }
                    }

                    init.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(null, infoName),
                                                                new CodeMethodInvokeExpression(fieldAccessType, "GetField", new CodePrimitiveExpression(name),
                                                                                               new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance"),
                                                                                                                                CodeBinaryOperatorType.BitwiseOr,
                                                                                                                                new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public"),
                                                                                                                                                                 CodeBinaryOperatorType.BitwiseOr,
                                                                                                                                                                 new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "NonPublic"))))));

                    // Build the getter and setter
                    if (getter == null)
                    {
                        getter = new CodeMethodInvokeExpression(
                            new CodeMethodReferenceExpression(
                                new CodeFieldReferenceExpression(null, infoName), "GetValue"),
                            new CodeArgumentReferenceExpression("input"));
                    }

                    if (setter == null)
                    {
                        // If the type is a struct, then the setter becomes somewhat more complicated, so first treat non-structs
                        if (t.IsByRef)
                        {
                            setter = value =>
                            {
                                var s = new CodeExpressionStatement
                                {
                                    Expression =
                                        new CodeMethodInvokeExpression(
                                            new CodeMethodReferenceExpression(
                                                new CodeFieldReferenceExpression(null, infoName), "SetValue"),
                                            new CodeVariableReferenceExpression("result"), value)
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s }));
                            };
                        }
                        else
                        {
                            // If this is the first field to use setting by reflection in a struct, we need to box the struct before we can continue
                            if (!usingBoxedReflection)
                            {
                                usingBoxedReflection = true;
                                // NOTE: object objResult = (object)result;
                                if (!shallowCopyable)
                                {
                                    copier.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult",
                                                                                               new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result"))));
                                }

                                deserializer.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult",
                                                                                                 new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result"))));
                            }
                            var temp = "temp" + counter;
                            setter = value =>
                            {
                                var s1 = new CodeVariableDeclarationStatement(typeof(object), temp, value);
                                var s2 = new CodeExpressionStatement
                                {
                                    Expression = new CodeMethodInvokeExpression(
                                        new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(null, infoName), "SetValue"),
                                        new CodeVariableReferenceExpression("objResult"),
                                        new CodeVariableReferenceExpression(temp))
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s1, s2 }));
                            };
                        }
                    }
                }

                // Copy this field, if needed
                if (!shallowCopyable)
                {
                    if (fld.FieldType.IsOrleansShallowCopyable())
                    {
                        copier.Statements.AddRange(setter(getter));
                    }
                    else
                    {
                        copier.Statements.AddRange(fld.FieldType == typeof(object)
                            ? setter(new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter))
                            : setter(new CodeCastExpression(typeName,
                                                            new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter))));
                    }
                }

                // Serialize this field
                serializer.Statements.Add(new CodeMethodInvokeExpression(serMgrRefExp, "SerializeInner", getter, new CodeArgumentReferenceExpression("stream"),
                                                                         new CodeTypeOfExpression(typeName)));

                // Deserialize this field
                deserializer.Statements.AddRange(setter(new CodeCastExpression(typeName,
                                                                               new CodeMethodInvokeExpression(serMgrRefExp, "DeserializeInner",
                                                                                                              new CodeTypeOfExpression(typeName), new CodeArgumentReferenceExpression("stream")))));
            }

            // Add return statements, as needed
            if (!shallowCopyable)
            {
                copier.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result")));
            }

            deserializer.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result")));

            // Special processing for generic types, necessary so that the appropriate closed types will get generated at run-time
            if (t.IsGenericType)
            {
                var masterClassName = TypeUtils.GetSimpleTypeName(t) + "GenericMaster";

                var masterClass = new CodeTypeDeclaration(masterClassName);
                container.Types.Add(masterClass);
                masterClass.IsClass        = true;
                masterClass.Attributes    |= MemberAttributes.Static | MemberAttributes.Assembly | MemberAttributes.Final;
                masterClass.TypeAttributes = TypeAttributes.NotPublic;
                masterClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute), CodeTypeReferenceOptions.GlobalReference)));

                var masterInit = AddInitMethod(masterClass);
                masterInit.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register",
                                                                         new CodeTypeOfExpression(t),
                                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericCopier"),
                                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericSerializer"),
                                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericDeserializer")));

                var initClosed = new CodeMethodInvokeExpression
                {
                    Method = new CodeMethodReferenceExpression
                    {
                        MethodName   = "Invoke",
                        TargetObject =
                            new CodeMethodInvokeExpression(
                                new CodeVariableReferenceExpression
                                    ("closed"), "GetMethod",
                                new CodePrimitiveExpression(
                                    "Register"))
                    }
                };
                initClosed.Parameters.Add(new CodePrimitiveExpression(null));
                initClosed.Parameters.Add(new CodeArrayCreateExpression(typeof(object), 0));

                var create = new CodeMemberMethod();
                masterClass.Members.Add(create);
                create.Attributes = (create.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                create.Attributes = (create.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                create.Name       = "CreateConcreteType";
                create.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type[]), "typeParams"));
                create.ReturnType = new CodeTypeReference(typeof(Type));
                create.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(serializationClassOpenName),
                                                                                                   "MakeGenericType", new CodeArgumentReferenceExpression("typeParams"))));

                var cop = new CodeMemberMethod();
                masterClass.Members.Add(cop);
                cop.Attributes = (cop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                cop.Attributes = (cop.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                cop.Name       = "GenericCopier";
                cop.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
                cop.ReturnType = new CodeTypeReference(typeof(object));
                cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t",
                                                                        new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType",
                                                                                                       new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("obj"), "GetType"), "GetGenericArguments"))));
                cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f",
                                                                        new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("DeepCopier"))));
                cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args",
                                                                        new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("obj") })));
                cop.Statements.Add(new CodeMethodReturnStatement(
                                       new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(),
                                                                      new CodeVariableReferenceExpression("args"))));

                var ser = new CodeMemberMethod();
                masterClass.Members.Add(ser);
                ser.Attributes = (ser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                ser.Attributes = (ser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                ser.Name       = "GenericSerializer";
                ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "input"));
                ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream"));
                ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
                ser.ReturnType = new CodeTypeReference(typeof(void));
                ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t",
                                                                        new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType",
                                                                                                       new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("input"), "GetType"), "GetGenericArguments"))));
                ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f",
                                                                        new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Serializer"))));
                ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args",
                                                                        new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("input"),
                                                                                                                                             new CodeArgumentReferenceExpression("stream"), new CodeArgumentReferenceExpression("expected") })));
                ser.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(),
                                                                  new CodeVariableReferenceExpression("args")));

                var deser = new CodeMemberMethod();
                masterClass.Members.Add(deser);
                deser.Attributes = (deser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                deser.Attributes = (deser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                deser.Name       = "GenericDeserializer";
                deser.ReturnType = new CodeTypeReference(typeof(object));
                deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
                deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamReader), "stream"));
                deser.ReturnType = new CodeTypeReference(typeof(object));
                deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t",
                                                                          new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType",
                                                                                                         new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("expected"), "GetGenericArguments"))));
                deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f",
                                                                          new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Deserializer"))));
                deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args",
                                                                          new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("expected"),
                                                                                                                                               new CodeArgumentReferenceExpression("stream") })));
                deser.Statements.Add(new CodeMethodReturnStatement(
                                         new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(),
                                                                        new CodeVariableReferenceExpression("args"))));
            }
            container.Types.Add(classDecl);
        }
Пример #37
0
 private void ValidateExpressionStatement(CodeExpressionStatement e)
 {
     this.ValidateExpression(e.Expression);
 }
Пример #38
0
 protected abstract void GenerateExpressionStatement(CodeExpressionStatement e);
Пример #39
0
 private void ConditionalBranch(Instruction il, bool test)
 {
     var rhs = new CodePrimitiveExpression(test);
     var lhs = Pop();
     var condition = OptimizeBinaryExpression(lhs, CodeBinaryOperator.IdentityEquality, rhs);
     var stmt = new CodeExpressionStatement(condition);
     AddStatment(stmt);
 }
Пример #40
0
        static CodeTypeDeclaration CreateAstVisitorClass(List <Type> nodeTypes, bool transformer)
        {
            CodeTypeDeclaration td = new CodeTypeDeclaration(transformer ? "AbstractAstTransformer" : "AbstractAstVisitor");

            td.TypeAttributes = TypeAttributes.Public | TypeAttributes.Abstract;
            td.BaseTypes.Add(new CodeTypeReference("IAstVisitor"));

            if (transformer)
            {
                string comment =
                    "The AbstractAstTransformer will iterate through the whole AST,\n " +
                    "just like the AbstractAstVisitor. However, the AbstractAstTransformer allows\n " +
                    "you to modify the AST at the same time: It does not use 'foreach' internally,\n " +
                    "so you can add members to collections of parents of the current node (but\n " +
                    "you cannot insert or delete items as that will make the index used invalid).\n " +
                    "You can use the methods ReplaceCurrentNode and RemoveCurrentNode to replace\n " +
                    "or remove the current node, totally independent from the type of the parent node.";
                Easy.AddSummary(td, comment);

                CodeMemberField field = td.AddField(Easy.TypeRef("Stack", "INode"), "nodeStack");
                field.InitExpression = Easy.New(field.Type);

                /*
                 * CodeExpression nodeStack = Easy.Var("nodeStack");
                 * CodeMemberProperty p = new CodeMemberProperty();
                 * p.Name = "CurrentNode";
                 * p.Type = new CodeTypeReference("INode");
                 * p.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                 * p.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("currentNode")));
                 * p.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("currentNode"),
                 *                                          new CodePropertySetValueReferenceExpression()));
                 * td.Members.Add(p);
                 */

                EasyMethod m = td.AddMethod("ReplaceCurrentNode");
                m.AddParameter(Easy.TypeRef("INode"), "newNode");
                m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Pop"));
                m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Push", Easy.Var("newNode")));

                m = td.AddMethod("RemoveCurrentNode");
                m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Pop"));
                m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Push", Easy.Null));
            }

            foreach (Type type in nodeTypes)
            {
                if (!type.IsAbstract)
                {
                    EasyMethod m = td.AddMethod(typeof(object), VisitPrefix + type.Name);
                    m.Attributes = MemberAttributes.Public;
                    m.AddParameter(ConvertType(type), GetFieldName(type.Name));
                    m.AddParameter(typeof(object), "data");

                    List <CodeStatement> assertions = new List <CodeStatement>();
                    string         varVariableName  = GetFieldName(type.Name);
                    CodeExpression var = Easy.Var(varVariableName);
                    assertions.Add(AssertIsNotNull(var));

                    AddFieldVisitCode(m, type, var, assertions, transformer);

                    if (type.GetCustomAttributes(typeof(HasChildrenAttribute), true).Length > 0)
                    {
                        if (transformer)
                        {
                            m.Statements.Add(new CodeSnippetStatement(CreateTransformerLoop(varVariableName + ".Children", "INode")));
                            m.Body.Return(Easy.Null);
                        }
                        else
                        {
                            m.Body.Return(var.InvokeMethod("AcceptChildren", Easy.This, Easy.Var("data")));
                        }
                    }
                    else
                    {
                        CodeExpressionStatement lastStatement = null;
                        if (m.Statements.Count > 0)
                        {
                            lastStatement = m.Statements[m.Statements.Count - 1] as CodeExpressionStatement;
                        }
                        if (lastStatement != null)
                        {
                            m.Statements.RemoveAt(m.Statements.Count - 1);
                            m.Body.Return(lastStatement.Expression);
                        }
                        else
                        {
                            m.Body.Return(Easy.Null);
                        }
                    }

                    for (int i = 0; i < assertions.Count; i++)
                    {
                        m.Statements.Insert(i, assertions[i]);
                    }
                }
            }
            return(td);
        }
Пример #41
0
        private void FillXElementMembers(CodeStatementCollection statements)
        {
            foreach (var keyValue in builders)
            {
                statements.Add(new CodeCommentStatement(keyValue.Key));

                var            emitInitial = true;
                CodeExpression addCodeExpression;
                CodeExpression valueCodeExpression;
                CodeStatement  additionalStatement = null;

                if (!keyValue.Value.IsArray && !keyValue.Value.IsComplexType)
                {
                    if (!string.IsNullOrEmpty(keyValue.Value.Xml.DataType))
                    {
                        switch (keyValue.Value.Xml.DataType)
                        {
                        case "base64Binary":
                            valueCodeExpression = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(Convert)), "ToBase64String",
                                                                                 new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("obj"), keyValue.Key));
                            break;

                        default:
                            throw new NotSupportedException("The provided DataType is not supported");
                        }
                    }
                    else
                    {
                        if (keyValue.Value.TypeSerializerBuilder.type.IsEnum)
                        {
                            valueCodeExpression = new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("obj"), keyValue.Key), "ToString");
                        }
                        else if (keyValue.Value.TypeSerializerBuilder.type.FullName == "System.String")
                        {
                            valueCodeExpression = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("obj"), keyValue.Key);
                        }
                        else
                        {
                            valueCodeExpression = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(XmlConvert)), "ToString",
                                                                                 new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("obj"), keyValue.Key));
                        }
                    }
                }
                else
                {
                    valueCodeExpression = null;

                    if (keyValue.Value.IsArray)
                    {
                        if (string.IsNullOrEmpty(keyValue.Value.Xml.ArrayItemName))
                        {
                            emitInitial = false;
                        }

                        additionalStatement = new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(int), "i", new CodeSnippetExpression("0")),
                                                                         new CodeSnippetExpression("i < obj." + keyValue.Key + ".Length"), new CodeSnippetStatement("i++"),
                                                                         new CodeSnippetStatement(emitInitial ? "System.Xml.Linq.XElement xParentElement = (System.Xml.Linq.XElement)xElement.LastNode;" : "System.Xml.Linq.XElement xParentElement = xElement;"),
                                                                         new CodeSnippetStatement("xParentElement.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get(\"" + (emitInitial ? keyValue.Value.Xml.ArrayItemName:keyValue.Key) + "\", \"" + keyValue.Value.Xml.Namespace + "\")));"),
                                                                         new CodeSnippetStatement(keyValue.Value.TypeSerializerBuilder.MethodName + "( obj." + keyValue.Key + "[i], (System.Xml.Linq.XElement)xParentElement.LastNode);"));
                    }
                    else
                    {
                        additionalStatement = new CodeExpressionStatement(new CodeMethodInvokeExpression(null, keyValue.Value.TypeSerializerBuilder.MethodName,
                                                                                                         new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("obj"), keyValue.Key),
                                                                                                         new CodeCastExpression(typeof(XElement), new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("xElement"), "LastNode"))));
                    }
                }

                if (keyValue.Value.Xml.UsesAttribute)
                {
                    addCodeExpression = new CodeObjectCreateExpression(
                        typeof(XAttribute),
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(XName)),
                            "Get",
                            new CodePrimitiveExpression(keyValue.Value.Xml.Name)), valueCodeExpression
                        );
                }
                else
                {
                    if (valueCodeExpression == null)
                    {
                        addCodeExpression = new CodeObjectCreateExpression(
                            typeof(XElement),
                            new CodeMethodInvokeExpression(
                                new CodeTypeReferenceExpression(typeof(XName)),
                                "Get",
                                new CodePrimitiveExpression(keyValue.Value.Xml.Name), new CodePrimitiveExpression(keyValue.Value.Xml.Namespace)));
                    }
                    else
                    {
                        addCodeExpression = new CodeObjectCreateExpression(
                            typeof(XElement),
                            new CodeMethodInvokeExpression(
                                new CodeTypeReferenceExpression(typeof(XName)),
                                "Get",
                                new CodePrimitiveExpression(keyValue.Value.Xml.Name), new CodePrimitiveExpression(keyValue.Value.Xml.Namespace)),
                            valueCodeExpression);
                    }
                }

                var propertyStatements = new List <CodeStatement>();

                if (emitInitial)
                {
                    propertyStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("xElement"), "Add", addCodeExpression)));
                }

                if (additionalStatement != null)
                {
                    propertyStatements.Add(additionalStatement);
                }

                if (keyValue.Value.Xml.IsOptional)
                {
                    statements.Add(
                        new CodeConditionStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("obj"), keyValue.Key + "Specified"), propertyStatements.ToArray()));
                }
                else
                {
                    propertyStatements.ForEach(s => statements.Add(s));
                }
            }
        }