public static void Go(OutputWriter writer, ReturnStatementSyntax statement)
        {
            if (Context.Instance.InLambdaBreakable > 0)
            {
                if (statement.Expression != null)
                {
                    writer.WriteIndent();
                    writer.Write("__lambdareturn = ");
                    Core.Write(writer, statement.Expression);
                    writer.Write(";\r\n");
                }

                writer.WriteLine("__lambdabreak.break();");
            }
            else
            {
                writer.WriteIndent();
                writer.Write("return");

                if (statement.Expression != null)
                {
                    writer.Write(" (");
                    Core.Write(writer, statement.Expression);
                    writer.Write(")");
                }
                writer.Write(";\r\n");
            }
        }
Beispiel #2
0
        public static void WriteLeadingTrivia(OutputWriter writer, SyntaxNode node)
        {
            var triviaList = node.GetLeadingTrivia();

            foreach (var trivia in triviaList)
            {
                if (trivia.CSharpKind() == SyntaxKind.SingleLineCommentTrivia ||
                    trivia.CSharpKind() == SyntaxKind.MultiLineCommentTrivia ||
                    trivia.CSharpKind() == SyntaxKind.SingleLineDocumentationCommentTrivia ||
                    trivia.CSharpKind() == SyntaxKind.MultiLineDocumentationCommentTrivia ||
                    trivia.CSharpKind() == SyntaxKind.WhitespaceTrivia)
                {
                    if (trivia.CSharpKind() == SyntaxKind.WhitespaceTrivia)
                    {
                        if (trivia.ToFullString().EndsWith("\n"))
                        {
                            writer.WriteLine();
                            writer.WriteIndent();
                        }
                    }
                    else
                    {
                        writer.WriteLine(trivia.ToFullString());
                    }
                }
            }
        }
Beispiel #3
0
        public static void Go(OutputWriter writer, ConstructorInitializerSyntax method)
        {
            writer.WriteIndent();
            //    var symbl = TypeProcessor.GetSymbolInfo(method);
            //	var mysymbl = TypeProcessor.GetSymbolInfo(method.Parent);

            //   var className = symbl.Symbol.ContainingType;
            if (method.ThisOrBaseKeyword.RawKind == (int)SyntaxKind.ThisKeyword)
            {
                writer.Write("this");
            }
            else
            {
                writer.Write("super");
            }
//                writer.Write(TypeProcessor.ConvertType(className));

            writer.Write("(");
            bool first = true;

            foreach (var expression in method.ArgumentList.Arguments)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    writer.Write(", ");
                }

                Core.Write(writer, expression.Expression);
            }
            writer.Write(")");
        }
        public static void Go(OutputWriter writer, ConstructorInitializerSyntax method)
        {
            writer.WriteIndent();
            //    var symbl = TypeProcessor.GetSymbolInfo(method);
            //	var mysymbl = TypeProcessor.GetSymbolInfo(method.Parent);

            //   var className = symbl.Symbol.ContainingType;
            if (method.ThisOrBaseKeyword.RawKind == (int) SyntaxKind.ThisKeyword)
                writer.Write("this");
            else
                writer.Write("super");
//                writer.Write(TypeProcessor.ConvertType(className));

            writer.Write("(");
            bool first = true;
            foreach (var expression in method.ArgumentList.Arguments)
            {
                if (first)
                    first = false;
                else
                    writer.Write(", ");

                Core.Write(writer, expression.Expression);
            }
            writer.Write(")");
        }
        public static void Go(OutputWriter writer, VariableDeclarationSyntax declaration)
        {
            foreach (var variable in declaration.Variables)
            {
                ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable);

                var isRef = false; //UsedAsRef(variable, symbol);

                writer.WriteIndent();
                // writer.Write("var ");

                //                if (isRef) //Not needed c++ can passby ref
                //                {
                //
                //                    var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type);
                //
                //                    var localSymbol = symbol as ILocalSymbol;
                //                    var ptr = localSymbol != null && !localSymbol.Type.IsValueType?"*" : "";
                //                                        writer.Write("gc::gc_ptr < " + typeStr+ ptr + " >");
                //                    writer.Write("" + typeStr + ptr + "");
                //
                //                    writer.Write(" ");
                //                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                //                    
                //                    Program.RefOutSymbols.TryAdd(symbol, null);
                //
                //                    writer.Write(" = std::make_shared < ");
                //                    writer.Write(typeStr + ptr);
                //                    writer.Write(" >(");
                //
                //                    WriteInitializer(writer, declaration, variable);
                //
                //                    writer.Write(")");
                //                }
                //                else
                {
                    var lsymbol = symbol as ILocalSymbol;

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                    {
                        writer.Write(" ");
// Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
                    }

                    writer.Write(TypeProcessor.ConvertType(declaration.Type));

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                        writer.Write(" ");

                    writer.Write(" ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                    writer.Write(" = ");

                    WriteInitializer(writer, declaration, variable);
                }

                writer.Write(";\r\n");
            }
        }
Beispiel #6
0
        public static void Go(OutputWriter writer, LockStatementSyntax statement)
        {
//            if (statement.DescendantNodes().OfType<ReturnStatementSyntax>().Any())
//                throw new Exception("Cannot return from within a lock statement " + Utility.Descriptor(statement));
            //synchronized
            writer.WriteIndent();
            writer.Write("synchronized("); //All d object implement a lock
            Core.Write(writer, statement.Expression);
            writer.Write(")");             //, () =>\r\n");
            writer.OpenBrace();
            Core.WriteStatementAsBlock(writer, statement.Statement, false);
            writer.Indent--;
            writer.WriteIndent();
            writer.CloseBrace();
            writer.WriteLine();
//            writer.Write("};\r\n");
        }
        public static void Go(OutputWriter writer, InitializerExpressionSyntax initializer)
        {
            writer.WriteIndent();
            var isCollectionInit = false;
            if (CSharpExtensions.CSharpKind(initializer) == SyntaxKind.CollectionInitializerExpression ||
                CSharpExtensions.CSharpKind(initializer) == SyntaxKind.ArrayInitializerExpression)
            {
                var tx = TypeProcessor.GetTypeInfo(initializer);

                var t = tx.Type;
                if (t == null)
                    t = tx.ConvertedType;
                if (t != null) // Initializer within initializer
                {
                    var elementType = t.As<IArrayTypeSymbol>().ElementType;
                    var ptr = !elementType.IsValueType; // ? "" : "";
                    var type = TypeProcessor.ConvertType(elementType);
                    var typeString = "Array_T!(" + type + ")";

                    if (elementType.TypeKind == TypeKind.TypeParameter)
                        writer.Write(" __TypeNew!(" + typeString + ")(");
                    else
                        writer.Write("new " + typeString + "(");
                }
                var variableDeclarationSyntax = initializer.Parent.Parent.Parent as VariableDeclarationSyntax;
                if (variableDeclarationSyntax != null)
                {
                    var atype = variableDeclarationSyntax.Type;
                    initializer.WriteArrayInitializer(writer, atype);
                }
                else
                    initializer.WriteArrayInitializer(writer,t);
                if (t != null)
                    writer.Write(")");
            }
            else
            {
                //            writer.Write("goto ");
                //            foreach (var expressionSyntax in method.Expressions)
                //            {
                //                Core.Write(writer, expressionSyntax);
                //            }

                bool first = true;
                foreach (var expression in initializer.Expressions)
                {
                    if (first)
                        first = false;
                    else
                        writer.Write(", ");

                    Core.Write(writer, expression);
                }
            }

            //            writer.Write(";");
        }
Beispiel #8
0
        private static void WriteSetter(OutputWriter writer, bool isProxy, bool hasSetter, string acccessmodifiers, string name, string typeString, ITypeSymbol iface, string isOverride, bool setterHasBody, SyntaxTokenList modifiers, bool isInterface, string fieldName, string setterbody, string parameters, bool isindexer, bool hasGetter)
        {
            if (isindexer)
            {
                name = "opIndexAssign";
            }

            var args = _set;

            if (hasSetter && isProxy)
            {
                if (!isindexer)
                {
                    writer.WriteLine(string.Format("{0} {2} {5}{1}({2} value{3}{4}){4} {{  __Value.{1} = value; return value;}}", acccessmodifiers, name, hasGetter ? typeString : "void", (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : ""), isOverride, args));
                }
                else
                {
                    writer.WriteLine(string.Format("{0} {2} {1}({2} value,{3}{4}) {4} {{  __Value.{1} = value;return value;}}", acccessmodifiers, name, typeString, parameters, isOverride));
                }
            }
            else if (hasSetter && !setterHasBody) //Setter
            {
                if (modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface)
                {
                    if (!isindexer)
                    {
                        writer.WriteLine(string.Format("{0} {2} {5}{1}({2} value{3}{4});", acccessmodifiers, name, hasGetter ? typeString : "void", (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : ""), isOverride, args));
                    }
                    else
                    {
                        writer.WriteLine(string.Format("{0} {2} {1}({2} value,{3}{4});", acccessmodifiers, name, typeString, parameters, isOverride));
                    }
                }
                else
                {
                    if (!isindexer)
                    {
                        var returnValue = hasGetter ? writer.WriteIndentToString() + "return value;" :"";
                        writer.WriteLine(string.Format("{0} {2} {6}{1}({2} value{3}){4} {{{5} = value;{7}}}", acccessmodifiers, name, hasGetter?typeString :"void", (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : ""), isOverride, fieldName, args, returnValue));
                    }
                    else
                    {
                        var returnValue = hasGetter ? writer.WriteIndentToString() + "return value;" : "";

                        writer.WriteLine(string.Format("{0} {2} {1}({2} value,{3}){4} {{{5} = value;{6}}}", acccessmodifiers, name, typeString, parameters, isOverride, fieldName, returnValue));
                    }
                }
            }
            else if (hasSetter)
            {
                writer.WriteIndent();
                writer.Write(acccessmodifiers);

                WriteRegion(false, setterbody, iface, writer, typeString, name, modifiers, parameters, isindexer, hasGetter);
            }
        }
Beispiel #9
0
        private static void WriteGetter(OutputWriter writer, bool isProxy, bool hasGetter, string acccessmodifiers, string typeString, string name, ITypeSymbol iface, bool getterHasBody, SyntaxTokenList modifiers, bool isInterface, string fieldName, string getterbody, string parameters, bool isindexer)
        {
            if (isindexer)
            {
                name = "opIndex";
            }

            var args = _get;

            if (hasGetter && isProxy)
            {
                if (!isindexer)
                {
                    writer.WriteLine(string.Format("{0}{1} {4}{2}({3}) {{ return __Value.{2};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : ""), args));
                }
                else
                {
                    writer.WriteLine(string.Format("{0}{1} {2}({3})  {{ return __Value.{2};}}", acccessmodifiers, typeString, name, parameters));
                }
            }
            else if (hasGetter && !getterHasBody) //Getter
            {
                if (modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface)
                {
                    if (!isindexer)
                    {
                        writer.WriteLine(string.Format("{0}{1} {4}{2}({3});", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : ""), args));
                    }
                    else
                    {
                        writer.WriteLine(string.Format("{0}{1} {2}({3});", acccessmodifiers, typeString, name, parameters));
                    }
                }

                else
                {
                    if (!isindexer)
                    {
                        writer.WriteLine(string.Format("{0}{1} {5}{2}({3}) {{ return {4};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : ""), fieldName, args));
                    }
                    else
                    {
                        writer.WriteLine(string.Format("{0}{1} {2}({3})  {{ return {4};}}", acccessmodifiers, typeString, name, parameters, fieldName));
                    }
                }
            }
            else if (hasGetter)
            {
                writer.WriteIndent();
                writer.Write(acccessmodifiers);
                WriteRegion(true, getterbody, iface, writer, typeString, name, modifiers, parameters, isindexer, hasGetter);
            }
        }
        public static void Go(OutputWriter writer, WhileStatementSyntax whileStatement)
        {
            var info = new LoopInfo(whileStatement);

            writer.WriteIndent();
            writer.Write("while (");
            Core.Write(writer, whileStatement.Condition);
            writer.Write(")\r\n");

            writer.OpenBrace();
            Core.WriteStatementAsBlock(writer, whileStatement.Statement, false);
            writer.CloseBrace();
        }
        public static void Go(OutputWriter writer, WhileStatementSyntax whileStatement)
        {
            var info = new LoopInfo(whileStatement);

            
            writer.WriteIndent();
            writer.Write("while (");
            Core.Write(writer, whileStatement.Condition);
            writer.Write(")\r\n");

            writer.OpenBrace();
            Core.WriteStatementAsBlock(writer, whileStatement.Statement, false);
            writer.CloseBrace();
        }
Beispiel #12
0
 public static void Go(OutputWriter writer, GotoStatementSyntax method)
 {
     writer.WriteIndent();
     writer.Write("goto ");
     writer.Write((method.CaseOrDefaultKeyword != default(SyntaxToken))
         ? method.CaseOrDefaultKeyword.ValueText
         : "");
     writer.Write(" ");
     if (method.Expression != null)
     {
         Core.Write(writer, method.Expression);
     }
     writer.Write(";\r\n");
 }
Beispiel #13
0
        public static void Go(OutputWriter writer, GotoStatementSyntax method)
        {
            writer.WriteIndent();
            writer.Write("goto ");
            writer.Write((method.CaseOrDefaultKeyword != default(SyntaxToken))
                ? method.CaseOrDefaultKeyword.Text
                : "");
            writer.Write(" ");

            if (method.Expression != null)
			if (method.Expression.ToString ().Trim() == "null")
				writer.Write("-1");
			else
                Core.Write(writer, method.Expression);
            writer.Write(";\r\n");
        }
Beispiel #14
0
        public static void Go(OutputWriter writer, ThrowStatementSyntax statement)
        {
            writer.WriteIndent();

            writer.Write("throw ");

            if (statement.Expression == null)
            {
                //On just "throw" with no exception name, navigate up the stack to find the nearest catch block and insert the exception's name
                CatchClauseSyntax catchBlock;
                SyntaxNode        node = statement;
                do
                {
                    catchBlock = (node = node.Parent) as CatchClauseSyntax;
                }while (catchBlock == null);

                if (catchBlock == null)
                {
                    throw new Exception("throw statement with no exception name, and could not locate a catch block " +
                                        Utility.Descriptor(statement));
                }

                if (catchBlock.Declaration == null || catchBlock.Declaration.Identifier.Value == null)
                {
                    //Some people write code in the form catch(Exception) ...grrr
                    writer.Write("__ex");
                }
                else
                {
                    var exName = WriteIdentifierName.TransformIdentifier(catchBlock.Declaration.Identifier.ValueText);

                    if (string.IsNullOrWhiteSpace(exName))
                    {
                        writer.Write("__ex");
                    }
                    else
                    {
                        writer.Write(exName);
                    }
                }
            }
            else
            {
                Core.Write(writer, statement.Expression);
            }
            writer.Write(";\r\n");
        }
Beispiel #15
0
        public static void Go(OutputWriter writer, IfStatementSyntax ifStatement, bool indent = true)
        {
            //  writer.WriteLine();

            var tempWriter = new TempWriter();

            if (indent)
            {
                tempWriter.WriteIndent();
            }
            tempWriter.Write("if(");
            Core.Write(tempWriter, ifStatement.Condition);
            tempWriter.Write(")");

            writer.WriteLine(tempWriter.ToString());

            Core.WriteStatementAsBlock(writer, ifStatement.Statement);

            if (ifStatement.Else == null)
            {
                return;
            }

            writer.WriteIndent();
            writer.Write("else");

            if (ifStatement.Else.Statement is BlockSyntax)
            {
                writer.Write("\r\n");
                Core.WriteBlock(writer, ifStatement.Else.Statement.As <BlockSyntax>());
            }
            else if (ifStatement.Else.Statement is IfStatementSyntax)
            {
                writer.Write(" ");
                Go(writer, ifStatement.Else.Statement.As <IfStatementSyntax>(), false);
            }
            else
            {
                writer.Write("\r\n");
                Core.WriteStatementAsBlock(writer, ifStatement.Else.Statement);
            }
        }
Beispiel #16
0
        public static void Go(OutputWriter writer, GotoStatementSyntax method)
        {
            writer.WriteIndent();
            writer.Write("goto ");
            writer.Write((method.CaseOrDefaultKeyword != default(SyntaxToken))
                ? method.CaseOrDefaultKeyword.Text
                : "");
            writer.Write(" ");

            if (method.Expression != null)
            {
                if (method.Expression.ToString().Trim() == "null")
                {
                    writer.Write("-1");
                }
                else
                {
                    Core.Write(writer, method.Expression);
                }
            }
            writer.Write(";\r\n");
        }
        public static void Go(OutputWriter writer, LocalDeclarationStatementSyntax declaration)
        {
            foreach (var variable in declaration.Declaration.Variables)
            {


                writer.WriteIndent();
               
                {
                    try
                    {
                        var str = TypeProcessor.ConvertType(declaration.Declaration.Type);
                        //This fails sometimes
                        // if (str == "NObject") // Dlangs casting is slow 
                        // Looks harmless but is actually a performance optimization ... makes CastTest improve by a whole lot
                        //   writer.Write("auto ");//Kills BoxingTest unfortunately as boxed types are also used to make unbound generics work :(
                        //else
                        writer.Write(str);
                    }
                    catch (Exception ex)
                    {
                        writer.Write("auto");   
                    }
                   

                    writer.Write(" ");



                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                    writer.Write(" = ");

                     WriteInitializer(writer, declaration, variable);
                }

                writer.Write(";\r\n");
            }
        }
        public static void Go(OutputWriter writer, ThrowStatementSyntax statement)
        {
            writer.WriteIndent();

            writer.Write("throw ");

            if (statement.Expression == null)
            {
                //On just "throw" with no exception name, navigate up the stack to find the nearest catch block and insert the exception's name
                CatchClauseSyntax catchBlock;
                SyntaxNode node = statement;
                do
                    catchBlock = (node = node.Parent) as CatchClauseSyntax;
                while (catchBlock == null);

                if (catchBlock == null)
                {
                    throw new Exception("throw statement with no exception name, and could not locate a catch block " +
                                        Utility.Descriptor(statement));
                }

                if (catchBlock.Declaration == null || catchBlock.Declaration.Identifier.Value == null)
                    //Some people write code in the form catch(Exception) ...grrr
                    writer.Write("__ex");
                else
                {
                    var exName = WriteIdentifierName.TransformIdentifier(catchBlock.Declaration.Identifier.Text);

                    if (string.IsNullOrWhiteSpace(exName))
                        writer.Write("__ex");
                    else
                        writer.Write(exName);
                }
            }
            else
                Core.Write(writer, statement.Expression);
            writer.Write(";\r\n");
        }
        public static void Go(OutputWriter writer, IfStatementSyntax ifStatement, bool indent = true)
        {
            //  writer.WriteLine();

            var tempWriter = new TempWriter();
            if (indent)
                tempWriter.WriteIndent();
            tempWriter.Write("if(");
            Core.Write(tempWriter, ifStatement.Condition);
            tempWriter.Write(")");

            writer.WriteLine(tempWriter.ToString());

            Core.WriteStatementAsBlock(writer, ifStatement.Statement);

            if (ifStatement.Else == null)
                return;

            writer.WriteIndent();
            writer.Write("else");

            if (ifStatement.Else.Statement is BlockSyntax)
            {
                writer.Write("\r\n");
                Core.WriteBlock(writer, ifStatement.Else.Statement.As<BlockSyntax>());
            }
            else if (ifStatement.Else.Statement is IfStatementSyntax)
            {
                writer.Write(" ");
                Go(writer, ifStatement.Else.Statement.As<IfStatementSyntax>(), false);
            }
            else
            {
                writer.Write("\r\n");
                Core.WriteStatementAsBlock(writer, ifStatement.Else.Statement);
            }
        }
        public static void Go(OutputWriter writer, LocalDeclarationStatementSyntax declaration)
        {
            foreach (var variable in declaration.Declaration.Variables)
            {
                writer.WriteIndent();

                {
                    try
                    {
                        var str = TypeProcessor.ConvertType(declaration.Declaration.Type);
                        //This fails sometimes
                        // if (str == "NObject") // Dlangs casting is slow
                        // Looks harmless but is actually a performance optimization ... makes CastTest improve by a whole lot
                        //   writer.Write("auto ");//Kills BoxingTest unfortunately as boxed types are also used to make unbound generics work :(
                        //else
                        writer.Write(str);
                    }
                    catch (Exception ex)
                    {
                        writer.Write("auto");
                    }


                    writer.Write(" ");



                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                    writer.Write(" = ");

                    WriteInitializer(writer, declaration, variable);
                }

                writer.Write(";\r\n");
            }
        }
 public static void WriteLeadingTrivia(OutputWriter writer, SyntaxNode node)
 {
     var triviaList = node.GetLeadingTrivia();
     foreach (var trivia in triviaList)
     {
         if (trivia.CSharpKind() == SyntaxKind.SingleLineCommentTrivia ||
             trivia.CSharpKind() == SyntaxKind.MultiLineCommentTrivia ||
             trivia.CSharpKind() == SyntaxKind.SingleLineDocumentationCommentTrivia ||
             trivia.CSharpKind() == SyntaxKind.MultiLineDocumentationCommentTrivia ||
             trivia.CSharpKind() == SyntaxKind.WhitespaceTrivia)
         {
             if (trivia.CSharpKind() == SyntaxKind.WhitespaceTrivia)
             {
                 if (trivia.ToFullString().EndsWith("\n"))
                 {
                     writer.WriteLine();
                     writer.WriteIndent();
                 }
             }
             else
                 writer.WriteLine(trivia.ToFullString());
         }
     }
 }
Beispiel #22
0
        private static void WriteOutOneType(OutputWriter parentModuleWriter, Context.SyntaxAndSymbol[] typeSymbols, bool fileExists)
        {
            TypeProcessor.ClearUsedTypes();
            var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace");

            var fullname = Context.Instance.Namespace + "." + Context.Instance.TypeName;

            if (TypeRenames.ContainsKey(fullname))
            {
                Context.Instance.TypeName = TypeRenames[fullname];
            }

            // + "." + TypeState.Instance.TypeName;
            // if (Driver.Verbose)
            //    Console.WriteLine("Writing out type: " + fullname);
            if (fullname.StartsWith(
                    "System.Collections.Generic.Dictionary"))
            {
            }

            var myUsingDirective     = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace));
            var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));
            // Required as certain functions like boxing are in this namespace
            var namespaces      = typeSymbols.First().Syntax.Parent.DescendantNodes().OfType <UsingDirectiveSyntax>().ToArray();
            var usingStatements = typeSymbols.First().Syntax.Parent.DescendantNodes().OfType <UsingStatementSyntax>().ToArray();
            var allTypeAliases  = typeSymbols.First().Syntax.DescendantNodes().OfType <QualifiedNameSyntax>().ToArray();

            Context.Instance.UsingDeclarations = namespaces
                                                 .Union(new[]
            {
                myUsingDirective, SystemUsingDirective
            }).ToArray();



            TypeProcessor.AddAlias(Context.Instance.Type.ContainingNamespace as INamespaceSymbol, Context.Instance.Type.ContainingNamespace.GetModuleName());


            foreach (var ns in namespaces)
            {
                //TODO: Add support for type aliases ...
                var symbol = TypeProcessor.GetSymbolInfo(ns.Name).Symbol;
                if (allTypeAliases.All(o => TypeProcessor.GetSymbolInfo(o.Left).Symbol != symbol))
                {
                    TypeProcessor.AddAlias(symbol as INamespaceSymbol, (symbol as INamespaceSymbol).GetModuleName());
                }
            }

            var aliases = allTypeAliases.DistinctBy(j => TypeProcessor.GetSymbolInfo(j.Left));

            foreach (var alias in aliases)
            {
                var left = alias.Left;
                var type = TypeProcessor.GetSymbolInfo(left).Symbol as INamespaceSymbol;
                var name = left.ToString();
                if (type != null && type.ToString() != name)
                {
                    TypeProcessor.AddAlias(type, name);
                }
            }
            OutputWriter writer = null;

            using (
                writer =
                    parentModuleWriter == null
                        ? new OutputWriter(Context.Instance.Namespace, Context.Instance.TypeName)
                        : new TempWriter())
            {
                writer.FileExists = fileExists;

                if (parentModuleWriter != null)
                {
                    writer.WriteLine();
                    writer.Indent = parentModuleWriter.Indent + 2;
                    writer.WriteIndent();
                }

                var bases    = new List <ITypeSymbol>();
                var baselist = typeSymbols.Select(k => k.Syntax.As <BaseTypeDeclarationSyntax>()).Select(o => o.BaseList).Where(k => k != null).ToArray();

                if (baselist.Any())
                {
                    bases = baselist.SelectMany(k => k.Types)
                            .Select(o => TypeProcessor.GetTypeInfo(o.Type).ConvertedType ?? TypeProcessor.GetTypeInfo(o.Type).Type)
                            .Where(k => k != null)
                            .Distinct()
                            .ToList();
                }

                //                var interfaces = bases.Where(o => o.TypeKind == TypeKind.Interface).ToList();

                if (Context.Instance.Type != Context.Object)
                {
                    if (bases != null && (!bases.Any((j => j.TypeKind != TypeKind.Interface)) &&
                                          !(typeSymbols.First().Symbol.TypeKind == TypeKind.Interface || typeSymbols.First().Symbol.TypeKind == TypeKind.Struct)))
                    {
                        //TODO: fix structs using mixins / alias this
                        bases.Add(Context.Object);
                    }
                }
                if (bases == null)
                {
                    bases = new List <ITypeSymbol>();
                }

                foreach (var type in bases)
                {
                    TypeProcessor.AddUsedType(type);
                }

                //TODO: Fix enum support
                if (typeSymbols.First().Syntax is EnumDeclarationSyntax)
                {
                    WriteEnum.Go(writer,
                                 Context.Instance.Partials.Select(o => o.Syntax)
                                 .Cast <EnumDeclarationSyntax>()
                                 .SelectMany(o => o.Members)
                                 .Where(o => !Program.DoNotWrite.ContainsKey(o)));

                    if (parentModuleWriter != null)
                    {
                        parentModuleWriter.Write(writer.ToString());
                    }

                    return;
                }

                Context.Instance.AllMembers =
                    typeSymbols.Select(k => k.Syntax.As <TypeDeclarationSyntax>()).SelectMany(o => o.Members)
                    .Where(o => !Program.DoNotWrite.ContainsKey(o))
                    .ToList();

                var allMembersToWrite = Context.Instance.AllMembers
                                        .Where(member => !(member is TypeDeclarationSyntax) &&
                                               !(member is EnumDeclarationSyntax) &&
                                               !(member is DelegateDeclarationSyntax) &&
                                               !(member is ConstructorDeclarationSyntax))
                                        .ToList();

                Context.Instance.MemberNames = allMembersToWrite.Select(k => k.GetCSharpName()).ToList();
                if (Context.Instance.Type.ContainingType != null)
                {
                    Context.Instance.MemberNames.AddRange(Context.Instance.Type.ContainingType.MemberNames);
                }


                {
                    //                    WriteStandardIncludes.Go(writer);

                    //                    writer.WriteLine(String.Format("#include \"{0}\"", TypeState.Instance.TypeName + ".h"));



                    WriteBcl.Go(writer);

                    //TypeState.Instance.DerivesFromObject = bases.Count == interfaces.Count;

                    var @namespace  = typeSymbols.First().Symbol.ContainingNamespace.FullName();
                    var genericArgs = Context.Instance.Type.TypeParameters.Select(l => l as ITypeSymbol).ToList();

                    //Module name = namespace + "." + typename;

                    WriteStandardIncludes.Go(writer);

                    //                    var namespaces = @namespace.Split(new string[] { "." }, StringSplitOptions.None);
                    //
                    //                    if (@namespace.Length > 0)
                    //                    {
                    //                        foreach (var ns in namespaces)
                    //                        {
                    //                            writer.WriteLine("namespace " + ns + "\r\n{");
                    //                            writer.WriteLine("namespace " + ns + "\r\n{");
                    //                        }
                    //
                    //                    }

                    var instanceCtors = Context.Instance.AllMembers.OfType <ConstructorDeclarationSyntax>()
                                        .Where(o => !o.Modifiers.Any(SyntaxKind.StaticKeyword))
                                        .ToList();

                    var staticCtors = Context.Instance.AllMembers.OfType <ConstructorDeclarationSyntax>()
                                      .Where(o => (o.Modifiers.Any(SyntaxKind.StaticKeyword)))
                                      .ToList();

                    //TODO: Add support for overloading constructing
                    //                    if (instanceCtors.Count > 1)
                    //                        throw new Exception(
                    //                            "Overloaded constructors are not supported.  Consider changing all but one to static Create methods " +
                    //                            Utility.Descriptor(first.Syntax));

                    //                    var ctorOpt = instanceCtors.SingleOrDefault();
                    //TODO: Handle interfaces by

                    /*
                     * class Interface
                     * {
                     * public:
                     *  virtual ~Interface() { }
                     *  virtual void test() = 0; // Functions, must all be virtual
                     * }
                     */

                    var membersToWrite = allMembersToWrite.ToList();
                    //.Where(o => IsStatic(o) == staticMembers).ToList();

                    //                    if (membersToWrite.Count == 0 && (partials.Any(o => o.Syntax.Modifiers.Any(SyntaxKind.StaticKeyword))))
                    //                        continue;

                    //                    if (staticMembers)
                    //                        writer.Write("object ");
                    //                    else if (first.Syntax.Kind == SyntaxKind.InterfaceDeclaration)
                    //                        writer.Write("trait ");
                    //                    else
                    //                    {
                    //                        if (partials.Any(o => o.Syntax.Modifiers.Any(SyntaxKind.AbstractKeyword)))
                    //                            writer.Write("abstract ");

                    //                    }

                    // writer.Write(TypeState.Instance.TypeName);

                    if (typeSymbols.First().Syntax is TypeDeclarationSyntax)
                    {
                        //Internal classes/structs are declared static in D to behave correctly
                        if (parentModuleWriter != null)
                        {
                            writer.Write("static ");
                        }
                        if (Context.Instance.Type.TypeKind == TypeKind.Class)
                        {
                            writer.Write("class ");
                        }
                        else if (Context.Instance.Type.TypeKind == TypeKind.Interface)
                        {
                            writer.Write("interface ");
                        }
                        else if (Context.Instance.Type.TypeKind == TypeKind.Struct)
                        {
                            writer.Write("struct ");
                            //						writer.Write (" class "); // Allows inheritance ... but too many issues, will look at this when it gets relevant
                        }
                        else
                        {
                            throw new Exception("don't know how to write type: " + Context.Instance.Type.TypeKind);
                        }
                        List <ITypeSymbol> parentTypeParameters;
                        if (Context.Instance.Type.ContainingType != null)
                        {
                            parentTypeParameters = GetParentTypeParameters(Context.Instance.Type);
                        }
                        else
                        {
                            parentTypeParameters = new List <ITypeSymbol>();
                        }

                        writer.Write(TypeName(Context.Instance.Type, false));
                        //TypeProcessor.ConvertType(Context.Instance.Type, true, false,true));

                        if (Context.Instance.Type.IsGenericType)
                        {
                            {
                                foreach (var @base in bases)
                                {
                                    var namedTypeSymbol = @base as INamedTypeSymbol;
                                    if (namedTypeSymbol != null)
                                    {
                                        foreach (var arg in namedTypeSymbol.TypeArguments)
                                        {
                                            if (arg.TypeKind == TypeKind.TypeParameter && !parentTypeParameters.Contains(arg))
                                            {
                                                if (!genericArgs.Any(k => k.Name == arg.Name))
                                                {
                                                    genericArgs.Add(arg);
                                                }
                                            }
                                        }
                                    }
                                }
                                if (genericArgs.Any())
                                {
                                    writer.Write("(" +
                                                 string.Join(" , ",
                                                             genericArgs.Select(o => TypeProcessor.ConvertType(o, true, true, false))) + ")");
                                }
                            }
                        }

                        bool firstBase = true;

                        if (Context.Instance.Type.TypeKind != TypeKind.Struct)
                        {
                            foreach (var baseType in bases.OrderBy(o => o.TypeKind == TypeKind.Interface ? 1 : 0))
                            {
                                var convertType = TypeProcessor.ConvertType(baseType);

                                writer.Write(firstBase ? " : " : " ,");

                                writer.Write(convertType);

                                firstBase = false;
                            }
                        }

                        string constraints = GetTypeConstraints((TypeDeclarationSyntax)typeSymbols.First().Syntax);
                        writer.Write(constraints);
                    }

                    writer.WriteLine();

                    writer.OpenBrace();

                    var nonFields = WriteFields(membersToWrite, typeSymbols.First(), writer);

                    foreach (var member in nonFields)
                    {
                        //                    writer.WriteLine();
                        Core.Write(writer, member);
                    }

                    WriteConstructors(instanceCtors, writer);

                    WriteStaticConstructors(staticCtors, writer);

                    //PInvoke is now centralized, so we can call it on all libraries etc without issue

                    writer.Indent--;
                    WriteOutNestedTypes(typeSymbols.First(), writer);

                    var methodSymbols = membersToWrite.OfType <MethodDeclarationSyntax>().Select(TypeProcessor.GetDeclaredSymbol);
                    //TypeProcessor.GetDeclaredSymbol(method);

                    if (!methodSymbols.OfType <IMethodSymbol>()
                        .Any(k => k.Name == "ToString" && k.Parameters.Length == 0 && k.ReturnType == Context.String))
                    {
                        if (Context.Instance.Type.TypeKind == TypeKind.Struct ||
                            (Context.Instance.Type.TypeKind == TypeKind.Class))
                        {
                            var overrideS = Context.Instance.Type.TypeKind == TypeKind.Struct ? "" : "override ";
                            writer.WriteLine();
                            writer.WriteLine("public " + overrideS + "String ToString()");
                            writer.OpenBrace();
                            writer.WriteLine("return GetType().FullName;");//Better names based on specialization
                            writer.CloseBrace();
                        }
                    }

                    WriteOutBoxed(writer, genericArgs, bases);
                }

                if (Context.Instance.Type.TypeKind == TypeKind.Struct)
                {
                    writer.WriteLine();
                    writer.WriteLine("public __Boxed_ __Get_Boxed()");
                    writer.OpenBrace();
                    writer.WriteLine("return new __Boxed_(this);");
                    writer.CloseBrace();
                    writer.WriteLine("alias __Get_Boxed this;");
                }

                if (Context.Instance.Type.TypeKind != TypeKind.Interface)
                {
                    writer.WriteLine();
                    if (Context.Instance.Type.TypeKind == TypeKind.Class)
                    {
                        writer.WriteLine("public override Type GetType()");
                    }
                    //					else if (Context.Instance.Type.TypeKind == TypeKind.Interface) // Messes with GetType overrides of objects
                    //					{
                    //						writer.WriteLine ("public final Type GetType()");
                    //					}
                    else if (Context.Instance.Type.TypeKind == TypeKind.Struct)
                    {
                        writer.WriteLine("public Type GetType()");
                    }
                    writer.OpenBrace();
                    //if (Context.Instance.Type.TypeKind == TypeKind.Class)
                    writer.WriteLine("return __TypeOf!(typeof(this));");
                    // else
                    //     writer.WriteLine("return __TypeOf!(__Boxed_);");

                    writer.CloseBrace();
                }

                writer.CloseBrace();

                WriteEntryMethod(writer);

                if (parentModuleWriter != null)
                {
                    writer.Finalize();
                    parentModuleWriter.Write(writer.ToString());
                }
            }
        }
Beispiel #23
0
        public static void Go(OutputWriter writer, InitializerExpressionSyntax initializer)
        {
            writer.WriteIndent();
            var isCollectionInit = false;

            if (CSharpExtensions.CSharpKind(initializer) == SyntaxKind.CollectionInitializerExpression ||
                CSharpExtensions.CSharpKind(initializer) == SyntaxKind.ArrayInitializerExpression)
            {
                var tx = TypeProcessor.GetTypeInfo(initializer);

                var t = tx.Type;
                if (t == null)
                {
                    t = tx.ConvertedType;
                }
                if (t != null) // Initializer within initializer
                {
                    var elementType = t.As <IArrayTypeSymbol>().ElementType;
                    var ptr         = !elementType.IsValueType; // ? "" : "";
                    var type        = TypeProcessor.ConvertType(elementType);
                    var typeString  = "Array_T!(" + type + ")";

                    if (elementType.TypeKind == TypeKind.TypeParameter)
                    {
                        writer.Write(" __TypeNew!(" + typeString + ")(");
                    }
                    else
                    {
                        writer.Write("new " + typeString + "(");
                    }
                }
                var variableDeclarationSyntax = initializer.Parent.Parent.Parent as VariableDeclarationSyntax;
                if (variableDeclarationSyntax != null)
                {
                    var atype = variableDeclarationSyntax.Type;
                    initializer.WriteArrayInitializer(writer, atype);
                }
                else
                {
                    initializer.WriteArrayInitializer(writer);
                }
                if (t != null)
                {
                    writer.Write(")");
                }
            }
            else
            {
                //            writer.Write("goto ");
                //            foreach (var expressionSyntax in method.Expressions)
                //            {
                //                Core.Write(writer, expressionSyntax);
                //            }

                bool first = true;
                foreach (var expression in initializer.Expressions)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        writer.Write(", ");
                    }

                    Core.Write(writer, expression);
                }
            }

            //            writer.Write(";");
        }
Beispiel #24
0
 public static void WriteStatement(OutputWriter writer, ExpressionStatementSyntax statement)
 {
     writer.WriteIndent();
     Write(writer, statement.Expression);
     writer.Write(";\r\n");
 }
Beispiel #25
0
        private static void WriteOneDelegate(OutputWriter outputWriter, Context.DelegateSyntaxAndSymbol first, bool fileExists)
        {
            Context.Instance.Namespace = first.Symbol.ContainingNamespace.FullName();
            Context.Instance.Type      = first.Symbol;
            TypeProcessor.ClearUsedTypes();
            var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace");
            // + "." + TypeState.Instance.TypeName;

            var myUsingDirective     = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace));
            var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));

            // Required as certain functions like boxing are in this namespace
            Context.Instance.UsingDeclarations =
                first.Syntax.Parent.DescendantNodes().OfType <UsingDirectiveSyntax>().ToArray()
                .Union(new[]
            {
                myUsingDirective, SystemUsingDirective
            }).ToArray();
            OutputWriter writer = null;

            using (
                writer =
                    outputWriter == null
                        ? new OutputWriter(Context.Instance.Namespace, Context.Instance.TypeName)
                        : new TempWriter())
            {
                if (outputWriter != null)
                {
                    writer.WriteLine();
                    writer.Indent = outputWriter.Indent + 2;
                    writer.WriteIndent();
                }

                writer.FileExists = fileExists;

                WriteBcl.Go(writer);

                WriteStandardIncludes.Go(writer);

                //Look for generic arguments

                {
                    List <TypeParameterSyntax> genericArgs = new List <TypeParameterSyntax>();
                    if (first.Syntax.TypeParameterList != null)
                    {
                        genericArgs = first.Syntax.TypeParameterList.Parameters.ToList();
                    }

                    var name = WriteType.TypeName(Context.Instance.Type, false); //Context.Instance.TypeName;

                    if (genericArgs.Count > 0)
                    {
                        name  = "template " + name;
                        name += ("(");
                        name += (string.Join(" , ", genericArgs.Select(o => o)));
                        name += (")");

                        writer.WriteLine(name);

                        writer.OpenBrace();

                        writer.WriteLine("alias __Delegate!(" + TypeProcessor.ConvertType(first.Syntax.ReturnType) + " delegate" +
                                         WriteMethod.GetParameterListAsString(first.Syntax.ParameterList.Parameters) + ") " +
                                         WriteType.TypeName(Context.Instance.Type, false) + ";");

                        writer.CloseBrace();
                    }
                    else
                    {
                        //Non-generic
                        writer.WriteLine("alias __Delegate!(" + TypeProcessor.ConvertType(first.Syntax.ReturnType) + " delegate" +
                                         WriteMethod.GetParameterListAsString(first.Syntax.ParameterList.Parameters) + ") " +
                                         WriteType.TypeName(Context.Instance.Type, false) + ";");
                    }
                }

                if (outputWriter != null)
                {
                    outputWriter.WriteLine(writer.ToString());
                }
            }
        }
        public static void Go(OutputWriter writer, VariableDeclarationSyntax declaration)
        {
            foreach (var variable in declaration.Variables)
            {
                ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable);

                var isRef = false; //UsedAsRef(variable, symbol);

                writer.WriteIndent();
                // writer.Write("var ");

                //                if (isRef) //Not needed c++ can passby ref
                //                {
                //
                //                    var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type);
                //
                //                    var localSymbol = symbol as ILocalSymbol;
                //                    var ptr = localSymbol != null && !localSymbol.Type.IsValueType?"*" : "";
                //                                        writer.Write("gc::gc_ptr < " + typeStr+ ptr + " >");
                //                    writer.Write("" + typeStr + ptr + "");
                //
                //                    writer.Write(" ");
                //                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                //
                //                    Program.RefOutSymbols.TryAdd(symbol, null);
                //
                //                    writer.Write(" = std::make_shared < ");
                //                    writer.Write(typeStr + ptr);
                //                    writer.Write(" >(");
                //
                //                    WriteInitializer(writer, declaration, variable);
                //
                //                    writer.Write(")");
                //                }
                //                else
                {
                    var lsymbol = symbol as ILocalSymbol;

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                    {
                        writer.Write(" ");
// Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
                    }

                    writer.Write(TypeProcessor.ConvertType(declaration.Type));

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                    {
                        writer.Write(" ");
                    }

                    writer.Write(" ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                    writer.Write(" = ");

                    WriteInitializer(writer, declaration, variable);
                }

                writer.Write(";\r\n");
            }
        }
        private static void WriteSetter(OutputWriter writer, bool isProxy, bool hasSetter, string acccessmodifiers, string name, string typeString, ITypeSymbol iface, string isOverride, bool setterHasBody, SyntaxTokenList modifiers, bool isInterface, string fieldName, string setterbody, string parameters, bool isindexer,bool hasGetter)
        {

            if (isindexer)
                name = "opIndexAssign";

            var args = _set;
            if (hasSetter && isProxy)
            {
                if (!isindexer)
                {
					writer.WriteLine (string.Format ("{0} {2} {5}{1}({2} value{3}{4}){4} {{  __Value.{1} = value; return value;}}", acccessmodifiers, name, hasGetter ? typeString : "void", (iface != null ? ("," + TypeProcessor.ConvertType (iface) + " __ig=null") : ""), isOverride, args));
                }
                else
                {
					writer.WriteLine (string.Format ("{0} {2} {1}({2} value,{3}{4}) {4} {{  __Value.{1} = value;return value;}}", acccessmodifiers, name, typeString, parameters, isOverride));
                }
            }
            else if (hasSetter && !setterHasBody) //Setter
            {
                if (modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface)
                {
                    if (!isindexer)
                    {
						writer.WriteLine (string.Format ("{0} {2} {5}{1}({2} value{3}{4});", acccessmodifiers, name, hasGetter ? typeString : "void", (iface != null ? ("," + TypeProcessor.ConvertType (iface) + " __ig=null") : ""), isOverride, args));
                    }
                    else
                    {
						writer.WriteLine (string.Format ("{0} {2} {1}({2} value,{3}{4});", acccessmodifiers, name, typeString, parameters, isOverride));
                    }
                }
                else
                {
                    if (!isindexer)
                    {
                        var returnValue = hasGetter ? writer.WriteIndentToString() + "return value;" :"";
                        writer.WriteLine (string.Format("{0} {2} {6}{1}({2} value{3}){4} {{{5} = value;{7}}}", acccessmodifiers, name, hasGetter?typeString :"void", (iface != null ? ("," + TypeProcessor.ConvertType (iface) + " __ig=null") : ""), isOverride, fieldName, args,returnValue));
                    }
                    else
                    {
                        var returnValue = hasGetter ? writer.WriteIndentToString() + "return value;" : "";

                        writer.WriteLine (string.Format("{0} {2} {1}({2} value,{3}){4} {{{5} = value;{6}}}" , acccessmodifiers, name, typeString, parameters, isOverride, fieldName, returnValue));
                    }
                }
            }
            else if (hasSetter)
            {
                writer.WriteIndent();
                writer.Write(acccessmodifiers);

                WriteRegion(false, setterbody, iface, writer, typeString, name, modifiers,parameters,isindexer,hasGetter);
            }
        }
Beispiel #28
0
        public static void Go(OutputWriter writer, ForEachStatementSyntax foreachStatement)
        {
            var info = new LoopInfo(foreachStatement);

            var types   = TypeProcessor.GetTypeInfo(foreachStatement.Expression);
            var typeStr = TypeProcessor.GenericTypeName(types.Type);

            writer.WriteLine("");


            //   writer.WriteOpenBrace();

//                writer.WriteIndent();

            var typeinfo = TypeProcessor.GetTypeInfo(foreachStatement.Expression);

//                var isPtr = typeinfo.Type != null && typeinfo.Type.IsValueType ? "" : "";
            var typeString = TypeProcessor.ConvertType(foreachStatement.Type) + " ";

            var foreachCount = Context.Instance.ForeachCount++;
            var isListT      = types.Type.OriginalDefinition == Context.ListT;
            var isArray      = types.Type is IArrayTypeSymbol;

            if (isArray || isListT)
            {//Lets just for through the array, iterators are slow ... really slow
                var forIter  = "__for" + foreachCount;
                var forArray = "__varfor" + foreachCount;

                var temp = new TempWriter();

                Core.Write(temp, foreachStatement.Expression);

                var expressiono = temp.ToString();

                // writer.WriteIndent();
                writer.WriteLine("auto {0} = {1};", forArray, expressiono);
                writer.WriteLine("for (int {0}=0;{0} < {2}.{3}; {0}++)", forIter, //Special case to support iterating "params" array
                                 WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), forArray, isListT?"Count" :"length");

                writer.OpenBrace();
                writer.WriteLine("auto {0} = {1}[{2}];", WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), forArray, forIter);
                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);
                writer.CloseBrace();


                return;
            }
            //It's faster to "while" through arrays than "for" through them

            var foreachIter = "__foreachIter" + foreachCount;

            if (typeinfo.Type.AllInterfaces.OfType <INamedTypeSymbol>().Any(j => j.MetadataName == "IEnumerable`1") ||
                typeinfo.Type.MetadataName == "IEnumerable`1")
            {
                var collections = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Collections.Generic"));


                Context.Instance.UsingDeclarations = Context.Instance.UsingDeclarations
                                                     .Union(new[]
                {
                    collections
                }).ToArray();

                writer.WriteLine("//ForEach");
//				writer.OpenBrace ();
                writer.WriteIndent();
                writer.Write(string.Format("auto {0} = ", foreachIter));
                Core.Write(writer, foreachStatement.Expression);
                writer.Write(String.Format(".GetEnumerator(cast(IEnumerable__G!({0}))null);\r\n", typeString));
                writer.WriteLine(string.Format("while({0}.MoveNext())", foreachIter));
                writer.OpenBrace();

                writer.WriteLine(string.Format("{0}{1} = {2}.Current(cast(IEnumerator__G!({0}))null);", typeString,
                                               WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), foreachIter));

                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);

                writer.CloseBrace();
                writer.WriteLine("");

//				writer.CloseBrace ();
                foreachCount++;
            }
            else
            {
                var collections = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Collections"));
                Context.Instance.UsingDeclarations = Context.Instance.UsingDeclarations
                                                     .Union(new[]
                {
                    collections
                }).ToArray();

                writer.WriteLine("//ForEach");
                writer.WriteIndent();
                writer.Write(string.Format("auto {0} = ", foreachIter));
                Core.Write(writer, foreachStatement.Expression);
                writer.Write(".GetEnumerator();\r\n");
                writer.WriteLine(string.Format("while({0}.MoveNext())", foreachIter));
                writer.OpenBrace();

                writer.WriteLine(string.Format("{0}{1} = UNBOX!({0})({2}.Current);", typeString,
                                               WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), foreachIter));

                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);

                writer.CloseBrace();
                writer.WriteLine("");

                foreachCount++;
            }
        }
Beispiel #29
0
        public static void Go(OutputWriter writer, IndexerDeclarationSyntax property)
        {
//			writer.WriteLine ("\r\n");
            var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

            var getter =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.GetKeyword);
            var setter =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.SetKeyword);
            var methodSymbol =
                (TypeProcessor.GetDeclaredSymbol(getter) ?? TypeProcessor.GetDeclaredSymbol(setter)) as IMethodSymbol;

            Action <AccessorDeclarationSyntax, bool> writeRegion = (region, get) =>
            {
                var typeinfo = TypeProcessor.GetTypeInfo(property.Type);
                var isPtr    = "";

                var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " ";

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                {
                    writer.Write(" abstract ");
                }

                if (property.Modifiers.Any(SyntaxKind.OverrideKeyword))
                {
                    writer.Write(" override ");
                }

                //TODO: look at final and other optimizations

                //no inline in D
                if (get)
                {
                    writer.Write(rEf + typeString + " ");
                }
                else
                {
                    writer.Write("void ");
                }

                var methodName         = (get ? "opIndex" : "opIndexAssign");
                var explicitHeaderNAme = "";
                if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation)
                {
                    var implementations = methodSymbol.ExplicitInterfaceImplementations[0];
                    if (implementations != null)
                    {
                        explicitHeaderNAme = implementations.Name;
                        methodName         =                       //implementations.ReceiverType.FullName() + "." +
                                             implementations.Name; //Explicit fix ?

                        //			writer.Write(methodSymbol.ContainingType + "." + methodName);
                        //Looks like internal classes are not handled properly here ...
                    }
                }
                if (methodSymbol != null)
                {
                    // methodName = methodName.Replace(methodSymbol.ContainingNamespace.FullName() + ".", methodSymbol.ContainingNamespace.FullName() + ".");

                    //   writer.Write((methodSymbol.ContainingType.FullName() + "." + methodName) + (get ? "()" : "( " + typeString + " value )")); //Dealting with explicit VMT7
                }
                if (property.Modifiers.Any(SyntaxKind.NewKeyword))
                {
                    methodName += "_";
                }

                var parameters = GetParameterList(methodSymbol.Parameters);

                writer.Write((!String.IsNullOrEmpty(explicitHeaderNAme) ? explicitHeaderNAme : methodName) + "( " +
                             (get ? "" : (typeString + " value, ")) + parameters + " )");

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                {
                    writer.Write(";\r\n");
                }
                else
                {
                    writer.OpenBrace();
                    Core.WriteBlock(writer, region.Body.As <BlockSyntax>());

                    writer.CloseBrace();
                    writer.Write("\r\n");
                }
            };

            if (getter == null && setter == null)
            {
                throw new Exception("Property must have either a get or a set");
            }

            {
//				var name = WriteIdentifierName.TransformIdentifier (property..ValueText);
                var type      = property.Type;
                var typeinfo  = TypeProcessor.GetTypeInfo(type);
                var modifiers = property.Modifiers;
                var isPtr     = typeinfo.Type != null &&
                                (typeinfo.Type.IsValueType || typeinfo.Type.TypeKind == TypeKind.TypeParameter)
                    ? ""
                    : "";
                var typeString = TypeProcessor.ConvertType(type) + isPtr + " ";
                var isStatic   = false;

                var acccessmodifiers = "";

                if (modifiers.Any(SyntaxKind.PrivateKeyword))
                {
                    acccessmodifiers += ("private ");
                }

                if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                    modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) ||
                    isInterface)
                {
                    acccessmodifiers += ("public ");
                }

                var IsStatic = "";

                if (modifiers.Any(SyntaxKind.StaticKeyword))
                {
                    isStatic          = true;
                    IsStatic          = "static ";
                    acccessmodifiers += IsStatic;
                }

                //Auto Property

//				var isOverride = property.Modifiers.Any (SyntaxKind.NewKeyword) ||
//				                 property.Modifiers.Any (SyntaxKind.OverrideKeyword)
//					? " override "
//					: "";
//				var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) ||
//					property.Modifiers.Any (SyntaxKind.AbstractKeyword) || isInterface
//					? " abstract "
//					: "";
//				if (!isInterface)

                //Getter
                if (getter != null)
                {
                    writer.WriteIndent();
                    writer.Write(acccessmodifiers);
                    writeRegion(getter, true);
                }

                //Setter
                if (setter != null)
                {
                    writer.WriteIndent();
                    writer.Write(acccessmodifiers);
                    writeRegion(setter, false);
                }
            }
        }
        public static void Go(OutputWriter writer, MemberDeclarationSyntax field, SyntaxTokenList modifiers, string name,
            TypeSyntax type, EqualsValueClauseSyntax initializerOpt = null, bool isThreadStatic =false)
        {
            writer.WriteIndent();

            var typeinfo = TypeProcessor.GetTypeInfo(type);

//            var isPtr = typeinfo.Type != null && (typeinfo.Type.IsValueType || typeinfo.Type.TypeKind==TypeKind.TypeParameter) ? "" : "";

            var typeStringNoPtr = TypeProcessor.ConvertType(type);

            var typeString = typeStringNoPtr + " ";

            var isConst = IsConst(modifiers, initializerOpt, type);

            var isStatic = isConst;
            //Handle Auto Properties

            // if (modifiers.Any(SyntaxKind.PrivateKeyword)) // Reflection cannot work with this, cant get address or set value
            //   writer.Write("private ");

            if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword))
                writer.Write("public ");


            if (isThreadStatic)
            {
                writer.Write("static ");
            }

            if (modifiers.Any(SyntaxKind.StaticKeyword) || modifiers.Any(SyntaxKind.ConstKeyword))
            {
                isStatic = true;
                writer.Write("__gshared ");
            }

          

            if (isConst && typeinfo.Type.IsPrimitive())
            {
              
                writer.Write("const "); //const has interesting semantics in Dlang 
            }

            var @event = field is EventFieldDeclarationSyntax;
            ITypeSymbol iface;
            ISymbol[] proxies;

            bool isInterface =false;
           // var ename = MemberUtilities.GetMethodName(field, ref isInterface, out iface, out proxies);
            if (@event)
            {
                typeString = ("__Event!(" + typeString + ")");

                if (field.Parent is InterfaceDeclarationSyntax)
                {
                    
                    //writer.Write(typeString);
                    writer.WriteLine(typeString + " " + name + "(" + TypeProcessor.ConvertType(field.Parent) +" __ij)" + "@property;");
                    return;
                }
            }

            writer.Write(typeString);


//                if (isStatic)
//                    writer.Write(typeString);

            writer.Write(name);
            if (isStatic)
            {
//                var fieldInfo = TypeProcessor.GetDeclaredSymbol(field.Parent);
//                if (fieldInfo != null)
//                    writer.Write((!string.IsNullOrEmpty(fieldInfo.ContainingNamespace.FullName())?(fieldInfo.ContainingNamespace.FullName()+".") :"") + fieldInfo.Name+"."+name);
//				writer.Write(name);
            }

            if (!isStatic || isConst)
            {
                if (initializerOpt != null)
                {
					writer.Write(String.Format(" = cast({0})", typeString));

                    if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression ||
                        CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
                    {
//                        writer.Write("gc::gc_ptr< " + typeStringNoPtr + " >(");
                        writer.Write(" new " + typeString + " (");
                        var intializer = initializerOpt.Value as InitializerExpressionSyntax;
                        intializer.WriteArrayInitializer(writer, type);

                        writer.Write(")");
                    }

                    else
                        Core.Write(writer, initializerOpt.Value);
                }

                else
                {
                   // if (typeinfo.Type.TypeKind != TypeKind.Struct)
                    {
                        writer.Write(" = ");
                        if (typeinfo.Type.TypeKind == TypeKind.Delegate)
                            writer.Write("new " + typeString + "()");
                        else
                            writer.Write(TypeProcessor.DefaultValue(type));
                    }
                }
            
            }
            else
            {
                var staticWriter = new TempWriter();

                if (initializerOpt != null)
                {
                    staticWriter.Write(name);

                    staticWriter.Write(" = ");

                    if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression ||
                        CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
                    {
                        staticWriter.Write("new " + typeStringNoPtr + " (");

                        var intializer = initializerOpt.Value as InitializerExpressionSyntax;

                        intializer.WriteArrayInitializer(staticWriter, type);
                        staticWriter.Write(")");
                    }
                    else

                        Core.Write(staticWriter, initializerOpt.Value);

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());

                }

                else if (typeinfo.Type.TypeKind != TypeKind.Struct)

                {
                    staticWriter.Write(name);
                    staticWriter.Write(" = ");

                    if (typeinfo.Type.TypeKind == TypeKind.Delegate)
                        staticWriter.Write("new " + typeString + "()");
                    else
                        staticWriter.Write(TypeProcessor.DefaultValue(type));

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());
                }

               


            }

           writer.Write(";");
                writer.WriteLine();
        }
Beispiel #31
0
        public static void Go(OutputWriter writer, MemberDeclarationSyntax field, SyntaxTokenList modifiers, string name,
                              TypeSyntax type, EqualsValueClauseSyntax initializerOpt = null)
        {
            writer.WriteIndent();

            var typeinfo = TypeProcessor.GetTypeInfo(type);

//            var isPtr = typeinfo.Type != null && (typeinfo.Type.IsValueType || typeinfo.Type.TypeKind==TypeKind.TypeParameter) ? "" : "";

            var typeStringNoPtr = TypeProcessor.ConvertType(type);

            var typeString = typeStringNoPtr + " ";

            var isConst = IsConst(modifiers, initializerOpt, type);

            var isStatic = isConst;

            //Handle Auto Properties

            if (modifiers.Any(SyntaxKind.PrivateKeyword))
            {
                writer.Write("private ");
            }

            if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword))
            {
                writer.Write("public ");
            }

            if (modifiers.Any(SyntaxKind.StaticKeyword) || modifiers.Any(SyntaxKind.ConstKeyword))
            {
                isStatic = true;
                writer.Write("static ");
            }

            if (isConst)
            {
                writer.Write("const ");
//                writer.Write("const ");
            }

            var @event = field is EventFieldDeclarationSyntax;

            if (@event)
            {
                typeString = ("Event!(" + typeString + ")");
            }

            writer.Write(typeString);
//                if (isStatic)
//                    writer.Write(typeString);

            writer.Write(name);
            if (isStatic)
            {
//                var fieldInfo = TypeProcessor.GetDeclaredSymbol(field.Parent);
//                if (fieldInfo != null)
//                    writer.Write((!string.IsNullOrEmpty(fieldInfo.ContainingNamespace.FullName())?(fieldInfo.ContainingNamespace.FullName()+".") :"") + fieldInfo.Name+"."+name);
//				writer.Write(name);
            }

            if (!isStatic || isConst)
            {
                if (initializerOpt != null)
                {
                    writer.Write(" = ");

                    if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression ||
                        CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
                    {
//                        writer.Write("gc::gc_ptr< " + typeStringNoPtr + " >(");
                        writer.Write(" new " + typeString + " (");
                        var intializer = initializerOpt.Value as InitializerExpressionSyntax;
                        intializer.WriteArrayInitializer(writer, type);

                        writer.Write(")");
                    }

                    else
                    {
                        Core.Write(writer, initializerOpt.Value);
                    }
                }

                else
                {
                    if (typeinfo.Type.TypeKind != TypeKind.Struct)
                    {
                        writer.Write(" = ");
                        if (typeinfo.Type.TypeKind == TypeKind.Delegate)
                        {
                            writer.Write("new " + typeString + "()");
                        }
                        else
                        {
                            writer.Write(TypeProcessor.DefaultValue(type));
                        }
                    }
                }
            }
            else
            {
                var staticWriter = new OutputWriter("", "", false);

                if (initializerOpt != null)
                {
                    staticWriter.Write(name);

                    staticWriter.Write(" = ");

                    if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression ||
                        CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
                    {
                        staticWriter.Write("new " + typeStringNoPtr + " (");

                        var intializer = initializerOpt.Value as InitializerExpressionSyntax;

                        intializer.WriteArrayInitializer(staticWriter, type);
                        staticWriter.Write(")");
                    }
                    else
                    {
                        Core.Write(staticWriter, initializerOpt.Value);
                    }
//                    if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
//                    {
//
//
//						staticWriter.Write("])");
//                    }
                }

                else if (typeinfo.Type.TypeKind != TypeKind.Struct)

                {
                    staticWriter.Write(name);
                    staticWriter.Write(" = ");

                    if (typeinfo.Type.TypeKind == TypeKind.Delegate)
                    {
                        staticWriter.Write("new " + typeString + "()");
                    }
                    else
                    {
                        staticWriter.Write(TypeProcessor.DefaultValue(type));
                    }
                }

//				staticWriter.Write (" SharpNative");

                staticWriter.Write(";");

                staticWriter.WriteLine();

                Context.Instance.StaticInits.Add(staticWriter.ToString());
            }

            writer.Write(";");
            writer.WriteLine();
        }
        public static void WriteAnonymousType(AnonymousObjectCreationExpressionSyntax syntax)
        {
            var type = TypeProcessor.GetTypeInfo(syntax).Type.As<INamedTypeSymbol>();

            Context.Instance.Type = type;

            TypeProcessor.ClearUsedTypes();

            var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace");
            // + "." + TypeState.Instance.TypeName;
            Context.Instance.Namespace = mynamespace;
            var myUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace));
            var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));
            // Required as certain functions like boxing are in this namespace

            Context.Instance.UsingDeclarations =
                syntax.Parent.DescendantNodes().OfType<UsingDirectiveSyntax>().ToArray()
                    .Union(new[]
                {
                    myUsingDirective, SystemUsingDirective
                }).ToArray();

            //using (var writer = new CppWriter (TypeState.Instance.Namespace, )) {

            //Ty

            var anonName = TypeName(type);
            using (var writer = new OutputWriter(Context.Instance.Namespace, StripGeneric(anonName)))
            {
                var fields = type.GetMembers().OfType<IPropertySymbol>().OrderBy(o => o.Name).ToList();

//                writer.WriteLine("namespace anonymoustypes {");
                WriteStandardIncludes.Go(writer);

                writer.WriteIndent();
                writer.Write("class ");
                writer.Write(anonName);

                writer.OpenBrace();

                foreach (var field in fields)
                {
                    writer.WriteIndent();
                    writer.Write("public ");
                    writer.Write(TypeProcessor.ConvertType(field.Type) + " ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(" = " + TypeProcessor.DefaultValue(field.Type));
                    writer.Write(";\r\n");
                }

                //Must Write a constructor here ...
                writer.Write("\r\nthis (");
                bool first = true;
                foreach (var field in fields)
                {
                    if (first)
                        first = false;
                    else
                        writer.Write(", ");

                    writer.Write(TypeProcessor.ConvertType(field.Type) + " ");
                    writer.Write("_" + WriteIdentifierName.TransformIdentifier(field.Name));
                }
                writer.Write(")\r\n");
                writer.OpenBrace();
                writer.Indent++;

                foreach (var field in fields)
                {
                    var fieldNAme = WriteIdentifierName.TransformIdentifier(field.Name);

                    writer.WriteLine(fieldNAme + " = _" + fieldNAme + ";");
                }
                writer.Indent--;

                writer.CloseBrace();

                writer.CloseBrace();
//                writer.Write("};");
//                writer.Write("}");
            }
        }
        public static void Go(OutputWriter writer, EventDeclarationSyntax property)
        {
            writer.WriteLine("\r\n");
            var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

            var add =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal) SyntaxKind.AddKeyword);
            var remove =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal) SyntaxKind.RemoveKeyword);
            var eventSymbol = TypeProcessor.GetDeclaredSymbol(property);

            var methodSymbol =
                (TypeProcessor.GetDeclaredSymbol(add) ?? TypeProcessor.GetDeclaredSymbol(remove)) as IMethodSymbol;

            ITypeSymbol interfaceImplemented;
            ISymbol[] proxies;
            ;

            var methodName = WriteIdentifierName.TransformIdentifier(MemberUtilities.GetMethodName(eventSymbol, ref isInterface, out interfaceImplemented, out proxies));

            Action<AccessorDeclarationSyntax, bool> writeRegion = (region, get) =>
            {
                writer.WriteIndent();

                //                if (property.Modifiers.Any(SyntaxKind.PrivateKeyword))
                //                    writer.HeaderWriter.Write("private:\n");
                //
                //                if (property.Modifiers.Any(SyntaxKind.PublicKeyword) || property.Modifiers.Any(SyntaxKind.InternalKeyword))
                //                    writer.HeaderWriter.Write("public ");
                var typeinfo = TypeProcessor.GetTypeInfo(property.Type);
                var isPtr = "";

                var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " ";

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                    writer.Write(" abstract ");

                if (property.Modifiers.Any(SyntaxKind.OverrideKeyword))
                    writer.Write(" override ");

               
                writer.Write("void ");
             
               
             

                writer.Write(
                    (get ? "Add_" : "Remove_") + methodName + "( " + typeString + " value");

                if (isInterface)
                {
                    writer.WriteLine(" , " + TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null");
                }

                    writer.Write(" )");

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                    writer.Write(";\r\n");
                else
                {
                    //                    writer.Write(";\r\n");

                    writer.OpenBrace();
                    // writer.Write(" =\r\n");
                    Core.WriteBlock(writer, region.Body.As<BlockSyntax>());

                    writer.CloseBrace();
                    writer.Write("\r\n");
                }
            };

            if (add == null && remove == null)
                throw new Exception("Event must have both a add and remove");

            {
               
                var name = WriteIdentifierName.TransformIdentifier(property.Identifier.Text);
                var type = property.Type;
                var typeinfo = TypeProcessor.GetTypeInfo(type);
                var modifiers = property.Modifiers;
                var typeString = TypeProcessor.ConvertType(type)  + " ";
                var isStatic = false;
                //Handle Auto Properties

                var accessors = property.AccessorList.Accessors; //.Where(o=>o.Body==null);
                var accessString = "";
                if (modifiers.Any(SyntaxKind.PrivateKeyword))
                    accessString += (" private ");

                if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                    modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) ||
                    isInterface)
                    accessString += (" public ");

             

                var IsStatic = "";

                if (modifiers.Any(SyntaxKind.StaticKeyword))
                {
                    isStatic = true;
                    IsStatic = accessString += " static ";
                    //  writer.HeaderWriter.Write("static ");
                }

                var fieldName = "__evt__" + name + (interfaceImplemented!=null?TypeProcessor.ConvertType(interfaceImplemented)
                    .Replace("(","_").Replace("!", "_").Replace(")", "_").Replace(".", "_") :"");
                if (!(property.Parent is InterfaceDeclarationSyntax))
                {
                    if (!isStatic)
                    {
                        writer.Write("private " + "__Event!(" + typeString + ") " + fieldName + ";\r\n");
                        // Internal Field used for event
                        writer.Write(accessString);
                        writer.WriteLine("__Event!(" + typeString + ") " + name + "(" + (interfaceImplemented!=null ? (  TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null") :"")+") @property");
                        writer.OpenBrace();

                        writer.WriteLine("if (" + fieldName + " is null)");
                        writer.OpenBrace();
                        writer.Write(fieldName + " =  new " + "__Event!(" + typeString + ")(new Action__G!(" +
                                     typeString +
                                     ")(&Add_" + name + "),new Action__G!(" + typeString + ")(&Remove_" + name + ") );");
                        writer.CloseBrace();
                        writer.Write("return " + fieldName + ";");
                        writer.CloseBrace();
                    }
                    else
                    {
                        writer.Write(IsStatic);
                        writer.Write("__Event!(" + typeString + ") " + name + ";\r\n");
                    }
                }

//
                var isOverride = property.Modifiers.Any(SyntaxKind.NewKeyword) ||
                                 property.Modifiers.Any(SyntaxKind.OverrideKeyword)
                    ? " override "
                    : "";
                var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) ||
                    property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface
                        ? " abstract "
                        : "";

                //Adder
                if (add != null && add.Body == null)
                {
                    writer.Write(IsStatic);
                    //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface)
                    {
                        writer.WriteLine(" " + isVirtual + " void Add_" + name + "(" + typeString + " value)" +
                                         isOverride + "" + ";");
                    }
//					else
//						writer.WriteLine(" "+isVirtual + " void Add_" + name + "(" + typeString + " value)" +
//							isOverride + " {" + fieldName + " = value;}");
                }
                else if (add != null)
                {
                    writer.Write(IsStatic);
                    writeRegion(add, true);
                }

                //Remover
                if (remove != null && remove.Body == null)
                {
                    writer.Write(IsStatic);
                    //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface)
                    {
                        writer.WriteLine(" " + isVirtual + " void Remove_" + name + "(" + typeString + " value)" +
                                         isOverride + "" + ";");
                    }
                  }
                else if (remove != null)
                {
                    writer.Write(IsStatic);
                    writeRegion(remove, false);
                }

                if (isStatic)
                {
                    var staticWriter = new OutputWriter("", "", false);

                    staticWriter.Write(name);

                    staticWriter.Write(" =  new " + "__Event!(" + typeString + ")(new Action__G!(" + typeString +
                                       ")(&Add_" + name + "),new Action__G!(" + typeString +
                                       ")(&Remove_" + name + ") )");

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());
                }

            }
        }
Beispiel #34
0
        public static void Go(OutputWriter writer, ForEachStatementSyntax foreachStatement)
        {
            var info = new LoopInfo(foreachStatement);

            var types   = TypeProcessor.GetTypeInfo(foreachStatement.Expression);
            var typeStr = TypeProcessor.GenericTypeName(types.Type);

            //  if (types.Type is IArrayTypeSymbol)
//            {
            //It's faster to "while" through arrays than "for" through them
            //   writer.WriteOpenBrace();
            writer.WriteLine("");

//                writer.WriteIndent();

            var typeinfo = TypeProcessor.GetTypeInfo(foreachStatement.Expression);

//                var isPtr = typeinfo.Type != null && typeinfo.Type.IsValueType ? "" : "";
            var typeString = TypeProcessor.ConvertType(foreachStatement.Type) + " ";

            var foreachIter = "__foreachIter" + foreachCount;

            if (typeinfo.Type.AllInterfaces.OfType <INamedTypeSymbol>().Any(j => j.MetadataName == "IEnumerable`1") ||
                typeinfo.Type.MetadataName == "IEnumerable`1")
            {
                writer.WriteLine("//ForEach");
//				writer.OpenBrace ();
                writer.WriteIndent();
                writer.Write(string.Format("auto {0} = ", foreachIter));
                Core.Write(writer, foreachStatement.Expression);
                writer.Write(".IEnumerable_T_GetEnumerator();\r\n");
                writer.WriteLine(string.Format("while({0}.IEnumerator_MoveNext())", foreachIter));
                writer.OpenBrace();

                writer.WriteLine(string.Format("{0}{1} = {2}.IEnumerator_T_Current;", typeString,
                                               WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.ValueText), foreachIter));

                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);

                writer.CloseBrace();
                writer.WriteLine("");

//				writer.CloseBrace ();
                foreachCount++;
            }
            else
            {
                writer.WriteLine("//ForEach");
                writer.WriteIndent();
                writer.Write(string.Format("auto {0} = ", foreachIter));
                Core.Write(writer, foreachStatement.Expression);
                writer.Write(".IEnumerable_GetEnumerator();\r\n");
                writer.WriteLine(string.Format("while({0}.IEnumerator_MoveNext())", foreachIter));
                writer.OpenBrace();

                writer.WriteLine(string.Format("{0}{1} = UNBOX!({0})({2}.IEnumerator_Current);", typeString,
                                               WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.ValueText), foreachIter));

                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);

                writer.CloseBrace();
                writer.WriteLine("");

                //				writer.CloseBrace ();
                foreachCount++;
            }
//				writer.Write(string.Format("foreach ({1}; ", typeString, WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.ValueText)));
//                writer.Write(")\r\n");
//
//                writer.OpenBrace();
//
//                writer.WriteIndent();
//
//                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);
//
//                writer.CloseBrace();

            //    writer.WriteCloseBrace();
//            }
//            else if (typeStr == "System.Collections.Generic.List<>"
//                //|| typeStr == "System.Collections.Generic.Dictionary<,>"
//                || typeStr == "System.Collections.Generic.Dictionary<,>.KeyCollection"
//                || typeStr == "System.Collections.Generic.Dictionary<,>.ValueCollection")
//            {
//                //It's faster to "while" over a list's iterator than to "for" through it
//                writer.WriteOpenBrace();
//                info.WritePreLoop(writer);
//
//                writer.WriteIndent();
//                writer.Write("val __foreachiterator = ");
//                Core.Write(writer, foreachStatement.Expression);
//                writer.Write(".iterator();\r\n");
//
//
//                writer.WriteLine("while (__foreachiterator.hasNext())");
//                writer.WriteOpenBrace();
//
//                writer.WriteIndent();
//                writer.Write("val ");
//                writer.Write(WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.ValueText));
//                writer.Write(" = __foreachiterator.next();\r\n");
//
//                info.WriteLoopOpening(writer);
//                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);
//                info.WriteLoopClosing(writer);
//                writer.WriteCloseBrace();
//
//                info.WritePostLoop(writer);
//                writer.WriteCloseBrace();
//            }
//            else
//            {
//
//                info.WritePreLoop(writer);
//                writer.WriteIndent();
//                writer.Write("for (");
//                writer.Write(WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.ValueText));
//                writer.Write(" = ");
//                Core.Write(writer, foreachStatement.Expression);
//                writer.Write(")\r\n");
//                writer.WriteOpenBrace();
//                info.WriteLoopOpening(writer);
//                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);
//                info.WriteLoopClosing(writer);
//                writer.WriteCloseBrace();
//                info.WritePostLoop(writer);
//            }
        }
        public static void Go(OutputWriter writer, ReturnStatementSyntax statement)
        {
            var slambda = statement.Ancestors().OfType <SimpleLambdaExpressionSyntax>().FirstOrDefault();
            var plambda = statement.Ancestors().OfType <ParenthesizedLambdaExpressionSyntax>().FirstOrDefault();
            var mlambda = statement.Ancestors().OfType <AnonymousMethodExpressionSyntax>().FirstOrDefault();


            var method    = statement.Ancestors().OfType <MethodDeclarationSyntax>().FirstOrDefault();
            var property  = statement.Ancestors().OfType <PropertyDeclarationSyntax>().FirstOrDefault();
            var indexer   = statement.Ancestors().OfType <IndexerDeclarationSyntax>().FirstOrDefault();
            var converter = statement.Ancestors().OfType <ConversionOperatorDeclarationSyntax>().FirstOrDefault();
            var @operator = statement.Ancestors().OfType <OperatorDeclarationSyntax>().FirstOrDefault();

            ITypeSymbol returnTypeSymbol = null;

            if (method != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(method.ReturnType).Type;
            }

            if (property != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(property.Type).Type;
            }

            if (indexer != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(indexer.Type).Type;
            }

            if (converter != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(converter.Type).Type;
            }


            if (@operator != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(@operator.ReturnType).Type;
            }

            if (plambda != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(plambda).Type;
            }

            if (slambda != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(slambda).Type;
            }

            if (mlambda != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(statement.Expression).ConvertedType;
            }


            writer.WriteIndent();
            writer.Write("return");

            if (statement.Expression != null)
            {
                {
                    var rightExpressionType = TypeProcessor.GetTypeInfo(statement.Expression);

                    var boxRight = rightExpressionType.ConvertedType != null &&
                                   (rightExpressionType.Type != null && (rightExpressionType.Type != rightExpressionType.ConvertedType) &&
                                    ((rightExpressionType.Type.IsValueType ||
                                      rightExpressionType.Type.TypeKind == TypeKind.TypeParameter) &&
                                     (rightExpressionType.ConvertedType.IsReferenceType)));
                    boxRight = boxRight && (rightExpressionType.Type != returnTypeSymbol);

                    if (!boxRight && returnTypeSymbol != Context.Object)
                    {
                        if (!Equals(returnTypeSymbol, rightExpressionType.Type) && !rightExpressionType.Type.IsSubclassOf(returnTypeSymbol))
                        {
                            writer.Write(" cast(" + TypeProcessor.ConvertType(returnTypeSymbol) + ")");
                        }
                    }

                    writer.Write(boxRight ? " BOX!(" + TypeProcessor.ConvertType(rightExpressionType.Type) + ")(" : " ");
                    Core.Write(writer, statement.Expression);

                    writer.Write(boxRight ? ")" : "");
                }
            }
            writer.Write(";\r\n");
        }
        private static void WriteGetter(OutputWriter writer, bool isProxy, bool hasGetter, string acccessmodifiers, string typeString, string name, ITypeSymbol iface, bool getterHasBody, SyntaxTokenList modifiers, bool isInterface, string fieldName, string getterbody, string parameters, bool isindexer)
        {
            if (isindexer)
                name = "opIndex";

            var args =_get;
            if (hasGetter && isProxy)
            {
                if (!isindexer)
                {
					writer.WriteLine (string.Format ("{0}{1} {4}{2}({3}) {{ return __Value.{2};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType (iface) + " __ig=null") : ""), args));
                }
                else
                {
					writer.WriteLine (string.Format ("{0}{1} {2}({3})  {{ return __Value.{2};}}", acccessmodifiers, typeString, name, parameters));
                }
            }
            else if (hasGetter && !getterHasBody) //Getter
            {
                if (modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface)
                {
                    if (!isindexer)
                    {
						writer.WriteLine (string.Format ("{0}{1} {4}{2}({3});", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType (iface) + " __ig=null") : ""), args));
                    }
                    else
                    {
						writer.WriteLine (string.Format ("{0}{1} {2}({3});", acccessmodifiers, typeString, name, parameters));
                    }
                }

                else
                {
                    if (!isindexer)
                    {
						writer.WriteLine (string.Format ("{0}{1} {5}{2}({3}) {{ return {4};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType (iface) + " __ig=null") : ""), fieldName, args));
                    }
                    else
                    {
						writer.WriteLine (string.Format ("{0}{1} {2}({3})  {{ return {4};}}", acccessmodifiers, typeString, name, parameters, fieldName));
                    }
                }
            }
            else if (hasGetter)
            {
                writer.WriteIndent();
                writer.Write(acccessmodifiers);
                WriteRegion(true, getterbody, iface, writer, typeString, name, modifiers,parameters,isindexer,hasGetter);
            }
        }
        public static void Go(OutputWriter writer, SwitchStatementSyntax switchStatement)
        {
            //  writer.WriteIndent();
            var isStringSwitch = false;
            var isEnumSwitch   = false;

            var symbol = TypeProcessor.GetTypeInfo(switchStatement.Expression);

            if (symbol.Type != null) // Sometimes its null why ?
            {
                if (symbol.Type.SpecialType == SpecialType.System_String)
                {
                    isStringSwitch = true;
                }

                if (symbol.Type.TypeKind == TypeKind.Enum)
                {
                    isEnumSwitch = true;
                }
            }

            if (!(switchStatement.Expression is LiteralExpressionSyntax))
            {
                writer.WriteLine("switch(" + Core.WriteString(switchStatement.Expression) + (isStringSwitch ? ".Hash" : "") + (isEnumSwitch ? ".__Value" : "") + ")");
            }
            else
            {
                var typeInfo = TypeProcessor.GetTypeInfo(switchStatement.Expression);
                if (typeInfo.Type.SpecialType == SpecialType.System_String)
                {
                    writer.WriteLine("switch(");
                    WriteLiteralExpression.Go(writer, (LiteralExpressionSyntax)switchStatement.Expression, true, true);
                    writer.WriteLine((isStringSwitch ? ".Hash" : "") + ")");
                }
                else
                {
                    writer.WriteLine("switch(" + Core.WriteString(switchStatement.Expression) + (isStringSwitch ? ".Hash" : "") + (isEnumSwitch ? ".__Value" : "") + ")");
                }
            }
            writer.OpenBrace();

            //First process all blocks except the section with the default block
            foreach (
                var section in
                switchStatement.Sections.Where(
                    o => o.Labels.None(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword)))
            {
                foreach (var label in section.Labels)
                {
                    writer.WriteIndent();
                    WriteLabel.Go(writer, (CaseSwitchLabelSyntax)label, isStringSwitch);
                }

                writer.OpenBrace(false);

                foreach (var statement in section.Statements)
                {
                    if (!(statement is BreakStatementSyntax))
                    {
                        writer.Write(Core.WriteString(statement, false, writer.Indent + 2));
                    }
                }

                writer.WriteLine("break;\r\n");
                writer.CloseBrace(false);
            }

            //Now write the default section
            var defaultSection =
                switchStatement.Sections.SingleOrDefault(
                    o => o.Labels.Any(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword));

            if (defaultSection != null)
            {
                foreach (var label in defaultSection.Labels)                 // Could be more than one label :P
                {
                    writer.WriteIndent();
                    if (label is CaseSwitchLabelSyntax)
                    {
                        WriteLabel.Go(writer, (CaseSwitchLabelSyntax)label, isStringSwitch);
                    }
                    else
                    {
                        writer.WriteLine(label.ToFullString().Trim());
                    }
                }

                // writer.WriteLine("default:");
                writer.OpenBrace(false);
                foreach (var statement in defaultSection.Statements)
                {
                    if (!(statement is BreakStatementSyntax))
                    {
                        writer.Write(Core.WriteString(statement, false, writer.Indent + 2));
                    }
                }
                writer.WriteLine("break;");
                writer.CloseBrace(false);
            }
            else
            {
                writer.WriteLine("default:");
                writer.WriteLine("break;");
            }

            writer.CloseBrace();
        }
        public static void Go(OutputWriter writer, ForEachStatementSyntax foreachStatement)
        {
            var info = new LoopInfo(foreachStatement);

            var types = TypeProcessor.GetTypeInfo(foreachStatement.Expression);
            var typeStr = TypeProcessor.GenericTypeName(types.Type);
            writer.WriteLine("");

           
            //   writer.WriteOpenBrace();

//                writer.WriteIndent();

            var typeinfo = TypeProcessor.GetTypeInfo(foreachStatement.Expression);

//                var isPtr = typeinfo.Type != null && typeinfo.Type.IsValueType ? "" : "";
            var typeString = TypeProcessor.ConvertType(foreachStatement.Type) + " ";

            var foreachCount = Context.Instance.ForeachCount++;
            var isListT = types.Type.OriginalDefinition == Context.ListT;
            var isArray = types.Type is IArrayTypeSymbol;
            if (isArray || isListT)
            {//Lets just for through the array, iterators are slow ... really slow
                var forIter = "__for" + foreachCount;
                var forArray = "__varfor" + foreachCount;

                var temp = new TempWriter();

                Core.Write(temp, foreachStatement.Expression);

                var expressiono = temp.ToString();

               // writer.WriteIndent();
                writer.WriteLine("auto {0} = {1};", forArray, expressiono);
                writer.WriteLine("for (int {0}=0;{0} < {2}.{3}; {0}++)", forIter, //Special case to support iterating "params" array
                    WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), forArray, isListT?"Count" :"length");
               
                writer.OpenBrace();
                writer.WriteLine("auto {0} = {1}[{2}];", WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), forArray, forIter);
                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);
                writer.CloseBrace();
               

                return;
            }
            //It's faster to "while" through arrays than "for" through them

            var foreachIter = "__foreachIter" + foreachCount;

            if (typeinfo.Type.AllInterfaces.OfType<INamedTypeSymbol>().Any(j => j.MetadataName == "IEnumerable`1") ||
                typeinfo.Type.MetadataName == "IEnumerable`1")
            {

                var collections = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Collections.Generic"));
               
               
                Context.Instance.UsingDeclarations = Context.Instance.UsingDeclarations
                    .Union(new[]
                {
                    collections
                }).ToArray();

                writer.WriteLine("//ForEach");
//				writer.OpenBrace ();
                writer.WriteIndent();
                writer.Write(string.Format("auto {0} = ", foreachIter));
                Core.Write(writer, foreachStatement.Expression);
                writer.Write(String.Format(".GetEnumerator(cast(IEnumerable__G!({0}))null);\r\n",typeString));
                writer.WriteLine(string.Format("while({0}.MoveNext())", foreachIter));
                writer.OpenBrace();

                writer.WriteLine(string.Format("{0}{1} = {2}.Current(cast(IEnumerator__G!({0}))null);", typeString,
                    WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), foreachIter));

                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);

                writer.CloseBrace();
                writer.WriteLine("");

//				writer.CloseBrace ();
                foreachCount++;
            }
            else
            {
                var collections = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Collections"));
                Context.Instance.UsingDeclarations = Context.Instance.UsingDeclarations
                  .Union(new[]
                {
                    collections
                }).ToArray();

                writer.WriteLine("//ForEach");
                writer.WriteIndent();
                writer.Write(string.Format("auto {0} = ", foreachIter));
                Core.Write(writer, foreachStatement.Expression);
                writer.Write(".GetEnumerator();\r\n");
                writer.WriteLine(string.Format("while({0}.MoveNext())", foreachIter));
                writer.OpenBrace();

                writer.WriteLine(string.Format("{0}{1} = UNBOX!({0})({2}.Current);", typeString,
                    WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), foreachIter));

                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);

                writer.CloseBrace();
                writer.WriteLine("");

                foreachCount++;
            }
        }
Beispiel #39
0
        public static void Go(OutputWriter writer, PropertyDeclarationSyntax property, bool isProxy = false)
        {
            writer.WriteLine();
            //var rEf = "";//" ref ";// ref should be used based on analysis, is the return type a single var or not
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

            var getter =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.GetKeyword);
            var setter =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.SetKeyword);
            var methodSymbol = TypeProcessor.GetDeclaredSymbol(property);
            var name         = WriteIdentifierName.TransformIdentifier(property.Identifier.ValueText);

            if (methodSymbol.ContainingType.TypeKind == TypeKind.Interface)
            {
                isInterface = true;
            }

            if (methodSymbol.ContainingType.TypeKind == TypeKind.Interface ||
                Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(methodSymbol), methodSymbol))
            {
                name = Regex.Replace(
                    TypeProcessor.ConvertType(methodSymbol.ContainingType.ConstructedFrom) + "_" + name,
                    @" ?!\(.*?\)", string.Empty);
            }

            if (name.Contains(".")) // Explicit Interface method
            {
                //
                name = name.SubstringAfterLast('.');
                name = name.Replace('.', '_');
            }

            var interfaceMethods =
                methodSymbol.ContainingType.AllInterfaces.SelectMany(
                    u =>
                    u.GetMembers(name)).ToArray();

            ISymbol interfaceMethod =
                interfaceMethods.FirstOrDefault(
                    o => methodSymbol.ContainingType.FindImplementationForInterfaceMember(o) == methodSymbol);

            if (interfaceMethod != null)
            {
                //This is an interface property //TO
                if (methodSymbol.ContainingType.SpecialType == SpecialType.System_Array)
                {
                    writer.Write("");
                }
                else
                {
                    var typenameI =
                        Regex.Replace(TypeProcessor.ConvertType(interfaceMethod.ContainingType.ConstructedFrom),
                                      @" ?!\(.*?\)", string.Empty);
                    //TODO: we should be able to get the original interface name, or just remove all generics from this

                    if (typenameI.Contains('.'))
                    {
                        typenameI = typenameI.SubstringAfterLast('.');
                    }
                    name = (typenameI + "_") + name;
                }
            }

            Action <AccessorDeclarationSyntax, bool> writeRegion = (region, get) =>
            {
                var accessString = "";

                //                var typeinfo = TypeProcessor.GetTypeInfo(property.Type);
                var isPtr = "";

                var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " ";

                //no inline in D
                if (get)
                {
                    writer.Write(typeString + " ");
                }
                else
                {
                    writer.Write("void ");
                }

                var methodName = (get ? "" : "") +
                                 name;
                var explicitHeaderNAme = "";

                if (property.Modifiers.Any(SyntaxKind.NewKeyword))
                {
                    methodName += "_";
                }

                writer.Write((!String.IsNullOrEmpty(explicitHeaderNAme) ? explicitHeaderNAme : methodName) +
                             (get ? "()" : "( " + typeString + " value )") + " @property");

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                {
                    writer.Write(";\r\n");
                }
                else
                {
                    writer.WriteLine();
                    writer.OpenBrace();
                    Core.WriteBlock(writer, region.Body.As <BlockSyntax>(), false);
                    writer.CloseBrace();
                    writer.WriteLine();
                }
            };

            if (getter == null && setter == null)
            {
                throw new Exception("Property must have either a get or a set");
            }
            {
                var type       = property.Type;
                var typeinfo   = TypeProcessor.GetTypeInfo(type);
                var modifiers  = property.Modifiers;
                var isPtr      = "";
                var typeString = TypeProcessor.ConvertType(type) + isPtr + " ";
                var isStatic   = false;

                var acccessmodifiers = "";

                if (modifiers.Any(SyntaxKind.PrivateKeyword))
                {
                    acccessmodifiers += ("private ");
                }

                if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                    modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) ||
                    isInterface)
                {
                    acccessmodifiers += ("public ");
                }

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword))
                {
                    acccessmodifiers += "abstract ";
                }

                if (property.Modifiers.Any(SyntaxKind.OverrideKeyword) && !isInterface)
                {
                    acccessmodifiers += "override ";
                }

                //TODO: look at final and other optimizations

                var IsStatic = "";

                if (modifiers.Any(SyntaxKind.StaticKeyword))
                {
                    isStatic          = true;
                    IsStatic          = "static ";
                    acccessmodifiers += IsStatic;
                }

                //Auto Property
                var fieldName = "__prop_" + name;

                var isOverride = (property.Modifiers.Any(SyntaxKind.NewKeyword) ||
                                  property.Modifiers.Any(SyntaxKind.OverrideKeyword)) && !isInterface
                    ? " override "
                    : "";
//                var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) ||
//                    property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface
//                        ? " abstract "
//                        : "";

                if (!isInterface) // Auto property
                {
                    if ((getter != null && getter.Body == null) &&
                        (setter != null && setter.Body == null) && (!property.Modifiers.Any(SyntaxKind.AbstractKeyword)))
                    {
                        writer.WriteLine("private " + typeString + fieldName + ";");
                    }
                }

                if (getter != null && isProxy)
                {
                    writer.WriteLine(acccessmodifiers + isOverride + typeString + "" + name + "() " + "@property " +
                                     "{ return Value." + name + ";}");
                }
                else
                //Getter
                if (getter != null && getter.Body == null)
                {
                    if (isProxy)
                    {
                    }
                    else if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface)
                    {
                        writer.WriteLine(acccessmodifiers + typeString + " " + name + "()" + isOverride +
                                         " @property;");
                    }

                    else
                    {
                        writer.WriteLine(acccessmodifiers + isOverride + typeString + "" + name + "() " +
                                         "@property " + "{ return " + fieldName + ";}");
                    }
                }
                else if (getter != null)
                {
                    writer.WriteIndent();
                    writer.Write(acccessmodifiers);
                    writeRegion(getter, true);
                }

                if (setter != null && isProxy)
                {
                    writer.WriteLine(acccessmodifiers + " void " + name + "(" + typeString + " value) @property" +
                                     isOverride + " {  Value." + name + " = value;}");
                }
                else
                //Setter
                if (setter != null && setter.Body == null)
                {
                    if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface)
                    {
                        writer.WriteLine(acccessmodifiers + " void " + name + "(" + typeString + " value)" +
                                         isOverride + "" + " @property;");
                    }
                    else
                    {
                        writer.WriteLine(acccessmodifiers + " void " + name + "(" + typeString + " value) @property" +
                                         isOverride + " {" + fieldName + " = value;}");
                    }
                }
                else if (setter != null)
                {
                    writer.WriteIndent();
                    writer.Write(acccessmodifiers);
                    writeRegion(setter, false);
                }
            }
        }
Beispiel #40
0
        public static void Go(OutputWriter writer, EventDeclarationSyntax property)
        {
            writer.WriteLine("\r\n");
            var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

            var add =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.AddKeyword);
            var remove =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.RemoveKeyword);
            var eventSymbol = TypeProcessor.GetDeclaredSymbol(property);

            var methodSymbol =
                (TypeProcessor.GetDeclaredSymbol(add) ?? TypeProcessor.GetDeclaredSymbol(remove)) as IMethodSymbol;

            ITypeSymbol interfaceImplemented;

            ISymbol[] proxies;
            ;

            var methodName = WriteIdentifierName.TransformIdentifier(MemberUtilities.GetMethodName(eventSymbol, ref isInterface, out interfaceImplemented, out proxies));

            Action <AccessorDeclarationSyntax, bool> writeRegion = (region, get) =>
            {
                writer.WriteIndent();

                //                if (property.Modifiers.Any(SyntaxKind.PrivateKeyword))
                //                    writer.HeaderWriter.Write("private:\n");
                //
                //                if (property.Modifiers.Any(SyntaxKind.PublicKeyword) || property.Modifiers.Any(SyntaxKind.InternalKeyword))
                //                    writer.HeaderWriter.Write("public ");
                var typeinfo = TypeProcessor.GetTypeInfo(property.Type);
                var isPtr    = "";

                var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " ";

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                {
                    writer.Write(" abstract ");
                }

                if (property.Modifiers.Any(SyntaxKind.OverrideKeyword))
                {
                    writer.Write(" override ");
                }


                writer.Write("void ");



                writer.Write(
                    (get ? "Add_" : "Remove_") + methodName + "( " + typeString + " value");

                if (isInterface)
                {
                    writer.WriteLine(" , " + TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null");
                }

                writer.Write(" )");

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                {
                    writer.Write(";\r\n");
                }
                else
                {
                    //                    writer.Write(";\r\n");

                    writer.OpenBrace();
                    // writer.Write(" =\r\n");
                    Core.WriteBlock(writer, region.Body.As <BlockSyntax>());

                    writer.CloseBrace();
                    writer.Write("\r\n");
                }
            };

            if (add == null && remove == null)
            {
                throw new Exception("Event must have both a add and remove");
            }

            {
                var name       = WriteIdentifierName.TransformIdentifier(property.Identifier.Text);
                var type       = property.Type;
                var typeinfo   = TypeProcessor.GetTypeInfo(type);
                var modifiers  = property.Modifiers;
                var typeString = TypeProcessor.ConvertType(type) + " ";
                var isStatic   = false;
                //Handle Auto Properties

                var accessors    = property.AccessorList.Accessors; //.Where(o=>o.Body==null);
                var accessString = "";
                if (modifiers.Any(SyntaxKind.PrivateKeyword))
                {
                    accessString += (" private ");
                }

                if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                    modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) ||
                    isInterface)
                {
                    accessString += (" public ");
                }



                var IsStatic = "";

                if (modifiers.Any(SyntaxKind.StaticKeyword))
                {
                    isStatic = true;
                    IsStatic = accessString += " static ";
                    //  writer.HeaderWriter.Write("static ");
                }

                var fieldName = "__evt__" + name + (interfaceImplemented != null?TypeProcessor.ConvertType(interfaceImplemented)
                                                    .Replace("(", "_").Replace("!", "_").Replace(")", "_").Replace(".", "_") :"");
                if (!(property.Parent is InterfaceDeclarationSyntax))
                {
                    if (!isStatic)
                    {
                        writer.Write("private " + "__Event!(" + typeString + ") " + fieldName + ";\r\n");
                        // Internal Field used for event
                        writer.Write(accessString);
                        writer.WriteLine("__Event!(" + typeString + ") " + name + "(" + (interfaceImplemented != null ? (TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null") :"") + ") @property");
                        writer.OpenBrace();

                        writer.WriteLine("if (" + fieldName + " is null)");
                        writer.OpenBrace();
                        writer.Write(fieldName + " =  new " + "__Event!(" + typeString + ")(new Action__G!(" +
                                     typeString +
                                     ")(&Add_" + name + "),new Action__G!(" + typeString + ")(&Remove_" + name + ") );");
                        writer.CloseBrace();
                        writer.Write("return " + fieldName + ";");
                        writer.CloseBrace();
                    }
                    else
                    {
                        writer.Write(IsStatic);
                        writer.Write("__Event!(" + typeString + ") " + name + ";\r\n");
                    }
                }

//
                var isOverride = property.Modifiers.Any(SyntaxKind.NewKeyword) ||
                                 property.Modifiers.Any(SyntaxKind.OverrideKeyword)
                    ? " override "
                    : "";
                var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) ||
                                property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface
                        ? " abstract "
                        : "";

                //Adder
                if (add != null && add.Body == null)
                {
                    writer.Write(IsStatic);
                    //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface)
                    {
                        writer.WriteLine(" " + isVirtual + " void Add_" + name + "(" + typeString + " value)" +
                                         isOverride + "" + ";");
                    }
//					else
//						writer.WriteLine(" "+isVirtual + " void Add_" + name + "(" + typeString + " value)" +
//							isOverride + " {" + fieldName + " = value;}");
                }
                else if (add != null)
                {
                    writer.Write(IsStatic);
                    writeRegion(add, true);
                }

                //Remover
                if (remove != null && remove.Body == null)
                {
                    writer.Write(IsStatic);
                    //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface)
                    {
                        writer.WriteLine(" " + isVirtual + " void Remove_" + name + "(" + typeString + " value)" +
                                         isOverride + "" + ";");
                    }
                }
                else if (remove != null)
                {
                    writer.Write(IsStatic);
                    writeRegion(remove, false);
                }

                if (isStatic)
                {
                    var staticWriter = new OutputWriter("", "", false);

                    staticWriter.Write(name);

                    staticWriter.Write(" =  new " + "__Event!(" + typeString + ")(new Action__G!(" + typeString +
                                       ")(&Add_" + name + "),new Action__G!(" + typeString +
                                       ")(&Remove_" + name + ") )");

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());
                }
            }
        }
        public static void Go(OutputWriter writer, ReturnStatementSyntax statement)
        {

            var slambda = statement.Ancestors().OfType<SimpleLambdaExpressionSyntax>().FirstOrDefault();
            var plambda = statement.Ancestors().OfType<ParenthesizedLambdaExpressionSyntax>().FirstOrDefault();
            var mlambda = statement.Ancestors().OfType<AnonymousMethodExpressionSyntax>().FirstOrDefault();


            var method = statement.Ancestors().OfType<MethodDeclarationSyntax>().FirstOrDefault();
            var property = statement.Ancestors().OfType<PropertyDeclarationSyntax>().FirstOrDefault();
            var indexer = statement.Ancestors().OfType<IndexerDeclarationSyntax>().FirstOrDefault();
            var converter = statement.Ancestors().OfType<ConversionOperatorDeclarationSyntax>().FirstOrDefault();
            var @operator = statement.Ancestors().OfType<OperatorDeclarationSyntax>().FirstOrDefault();

            ITypeSymbol returnTypeSymbol = null;

            if (method != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(method.ReturnType).Type;
            }

            if (property != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(property.Type).Type;
            }

            if (indexer != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(indexer.Type).Type;
            }

            if (converter != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(converter.Type).Type;
            }


            if (@operator != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(@operator.ReturnType).Type;
            }

            if (plambda != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(plambda).Type;
            }

            if (slambda != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(slambda).Type;
            }

            if (mlambda != null)
            {
                returnTypeSymbol = TypeProcessor.GetTypeInfo(statement.Expression).ConvertedType;
            }


            writer.WriteIndent();
            writer.Write("return");

            if (statement.Expression != null)
            {
                {

                    var rightExpressionType = TypeProcessor.GetTypeInfo(statement.Expression);

                    var boxRight = rightExpressionType.ConvertedType != null &&
                                   (rightExpressionType.Type != null && (rightExpressionType.Type!=rightExpressionType.ConvertedType) &&
                                    ((rightExpressionType.Type.IsValueType ||
                                      rightExpressionType.Type.TypeKind == TypeKind.TypeParameter) &&
                                     (rightExpressionType.ConvertedType.IsReferenceType)));
                    boxRight = boxRight && (rightExpressionType.Type != returnTypeSymbol);

                    if(!boxRight && returnTypeSymbol!=Context.Object)
					if (!Equals(returnTypeSymbol, rightExpressionType.Type) && !rightExpressionType.Type.IsSubclassOf(returnTypeSymbol))
                    {
                        writer.Write(" cast(" + TypeProcessor.ConvertType(returnTypeSymbol) + ")");
                    }

                   writer.Write (boxRight ? " BOX!(" + TypeProcessor.ConvertType(rightExpressionType.Type) + ")(" : " ");
                    Core.Write(writer, statement.Expression);

                    writer.Write(boxRight ? ")" : "");

                }
                

            }
            writer.Write(";\r\n");
        }
Beispiel #42
0
        public static void Go(OutputWriter writer, EventDeclarationSyntax property)
        {
            writer.WriteLine("\r\n");
            var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

            var add =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.AddKeyword);
            var remove =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.RemoveKeyword);

            var methodSymbol =
                (TypeProcessor.GetDeclaredSymbol(add) ?? TypeProcessor.GetDeclaredSymbol(remove)) as IMethodSymbol;

            Action <AccessorDeclarationSyntax, bool> writeRegion = (region, get) =>
            {
                writer.WriteIndent();

                //                if (property.Modifiers.Any(SyntaxKind.PrivateKeyword))
                //                    writer.HeaderWriter.Write("private:\n");
                //
                //                if (property.Modifiers.Any(SyntaxKind.PublicKeyword) || property.Modifiers.Any(SyntaxKind.InternalKeyword))
                //                    writer.HeaderWriter.Write("public ");
                var typeinfo = TypeProcessor.GetTypeInfo(property.Type);
                var isPtr    = "";

                var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " ";

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                {
                    writer.Write(" abstract ");
                }

                if (property.Modifiers.Any(SyntaxKind.OverrideKeyword))
                {
                    writer.Write(" override ");
                }

                //TODO: look at final and other optimizations
                //				if (!(property.Modifiers.Any (SyntaxKind.VirtualKeyword) || (property.Modifiers.Any (SyntaxKind.AbstractKeyword)) || isInterface || property.Modifiers.Any(SyntaxKind.OverrideKeyword)) ) {
                //					writer.Write(" final ");
                //				}

                //no inline in D
                //	if (get)
                //	{

                //		writer.Write(" " + rEf+ typeString + " ");
                //                    writer.Write(typeString + " ");
                //	}
                //	else
                //	{
                //                    writer.Write("_=(value");
                //                    writer.Write(TypeProcessor.ConvertTypeWithColon(property.Type));
                //                    writer.Write(")");

                writer.Write("void ");
                //                    writer.Write(" " + "void ");

                //	}
                //not needed for Dlang
                var methodName = (get ? "" : "") +
                                 WriteIdentifierName.TransformIdentifier(property.Identifier.ValueText);
                var explicitHeaderNAme = "";
                if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation)
                {
                    var implementations = methodSymbol.ExplicitInterfaceImplementations[0];
                    if (implementations != null)
                    {
                        explicitHeaderNAme = implementations.Name;
                        methodName         =                       //implementations.ReceiverType.FullName() + "." +
                                             implementations.Name; //Explicit fix ?

                        //			writer.Write(methodSymbol.ContainingType + "." + methodName);
                        //Looks like internal classes are not handled properly here ...
                    }
                }
                if (methodSymbol != null)
                {
                    // methodName = methodName.Replace(methodSymbol.ContainingNamespace.FullName() + ".", methodSymbol.ContainingNamespace.FullName() + ".");

                    //   writer.Write((methodSymbol.ContainingType.FullName() + "." + methodName) + (get ? "()" : "( " + typeString + " value )")); //Dealing with explicit VMT7
                }
                if (property.Modifiers.Any(SyntaxKind.NewKeyword))
                {
                    methodName += "_";
                }

                writer.Write(
                    //(!String.IsNullOrEmpty(explicitHeaderNAme) ? explicitHeaderNAme : methodName)
                    (get ? "Add_" : "Remove_") + methodName + "( " + typeString + " value )");

                if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null)
                {
                    writer.Write(";\r\n");
                }
                else
                {
                    //                    writer.Write(";\r\n");

                    writer.OpenBrace();
                    // writer.Write(" =\r\n");
                    Core.WriteBlock(writer, region.Body.As <BlockSyntax>());

                    writer.CloseBrace();
                    writer.Write("\r\n");
                }
            };

            if (add == null && remove == null)
            {
                throw new Exception("Property must have either a get or a set");
            }

            // if (getter != null && setter != null && setter.Body == null && getter.Body == null)
            {
                //Both get and set are null, which means this is an automatic property.  For our purposes, this is the equivilant of a field//Nope

                //                WriteField.Go(writer,property, property.Modifiers, WriteIdentifierName.TransformIdentifier(property.Identifier.ValueText), property.Type);
                var name      = WriteIdentifierName.TransformIdentifier(property.Identifier.ValueText);
                var type      = property.Type;
                var typeinfo  = TypeProcessor.GetTypeInfo(type);
                var modifiers = property.Modifiers;
                var isPtr     = typeinfo.Type != null &&
                                (typeinfo.Type.IsValueType || typeinfo.Type.TypeKind == TypeKind.TypeParameter)
                    ? ""
                    : "";
                var typeString = TypeProcessor.ConvertType(type) + isPtr + " ";
                var isStatic   = false;
                //Handle Auto Properties

                var accessors    = property.AccessorList.Accessors; //.Where(o=>o.Body==null);
                var accessString = "";
                if (modifiers.Any(SyntaxKind.PrivateKeyword))
                {
                    accessString += (" private ");
                }

                if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                    modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) ||
                    isInterface)
                {
                    accessString += (" public ");
                }

                //				if (!(property.Modifiers.Any (SyntaxKind.VirtualKeyword) || (property.Modifiers.Any (SyntaxKind.AbstractKeyword)))) {
                //					writer.Write(" final ");
                //				}

                //                if (modifiers.Any(SyntaxKind.PublicKeyword) || method.Modifiers.Any(SyntaxKind.InternalKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword))
                //                        writer.HeaderWriter.WriteLine("public: ");

                var IsStatic = "";

                if (modifiers.Any(SyntaxKind.StaticKeyword))
                {
                    isStatic = true;
                    IsStatic = accessString += " static ";
                    //  writer.HeaderWriter.Write("static ");
                }

                var fieldName = "__evt__" + name;
                if (!isStatic)
                {
                    writer.Write("private " + "Event!(" + typeString + ") " + fieldName + ";\r\n");
                    // Internal Field used for event
                    writer.Write(accessString);
                    writer.WriteLine("Event!(" + typeString + ") " + name + "() @property");
                    writer.OpenBrace();

                    writer.WriteLine("if (" + fieldName + " is null)");
                    writer.OpenBrace();
                    writer.Write(fieldName + " =  new " + "Event!(" + typeString + ")(new Action_T!(" + typeString +
                                 ")(&Add_" + name + "),new Action_T!(" + typeString + ")(&Remove_" + name + ") );");
                    writer.CloseBrace();
                    writer.Write("return " + fieldName + ";");
                    writer.CloseBrace();
                }
                else
                {
                    writer.Write(IsStatic);
                    writer.Write("Event!(" + typeString + ") " + name + ";\r\n");
                }

//
                var isOverride = property.Modifiers.Any(SyntaxKind.NewKeyword) ||
                                 property.Modifiers.Any(SyntaxKind.OverrideKeyword)
                    ? " override "
                    : "";
                var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) ||
                                property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface
                        ? " abstract "
                        : "";
//				if(!isInterface)
//				if ((add!=null && add.Body == null) ||
//					(remove != null && remove.Body == null) && (!property.Modifiers.Any(SyntaxKind.AbstractKeyword)))
//				{
//
//					writer.Write (IsStatic);
//					var initString = "";//isStatic?"":(" = " + TypeProcessor.DefaultValue (type));
//					writer.Write (typeString + fieldName + initString + ";\r\n");
//
//				}

                //Adder
                if (add != null && add.Body == null)
                {
                    writer.Write(IsStatic);
                    //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface)
                    {
                        writer.WriteLine(" " + isVirtual + " void Add_" + name + "(" + typeString + " value)" +
                                         isOverride + "" + ";");
                    }
//					else
//						writer.WriteLine(" "+isVirtual + " void Add_" + name + "(" + typeString + " value)" +
//							isOverride + " {" + fieldName + " = value;}");
                }
                else if (add != null)
                {
                    writer.Write(IsStatic);
                    writeRegion(add, true);
                }

                //Remover
                if (remove != null && remove.Body == null)
                {
                    writer.Write(IsStatic);
                    //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface)
                    {
                        writer.WriteLine(" " + isVirtual + " void Remove_" + name + "(" + typeString + " value)" +
                                         isOverride + "" + ";");
                    }
                    //else
                    //	writer.WriteLine(" "+isVirtual + " void Remove_" + name + "(" + typeString + " value)" +
                    //		isOverride + " {" + fieldName + " = value;}");
                }
                else if (remove != null)
                {
                    writer.Write(IsStatic);
                    writeRegion(remove, false);
                }

                if (isStatic)
                {
                    var staticWriter = new OutputWriter("", "", false);

                    staticWriter.Write(name);

                    staticWriter.Write(" =  new " + "Event!(" + typeString + ")(new Action_T!(" + typeString +
                                       ")(__ToDelegate(&Add_" + name + ")),new Action_T!(" + typeString +
                                       ")(__ToDelegate(&Remove_" + name + ")) )");

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());
                }
                else
                {
                    var staticWriter = new OutputWriter("", "", false);

                    staticWriter.Write(name);

                    staticWriter.Write(" =  new " + "Event!(" + typeString + ")(new Action_T!(" + typeString +
                                       ")((&Add_" + name + ")),new Action_T!(" + typeString + ")((&Remove_" + name +
                                       ")) )");

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.InstanceInits.Add(staticWriter.ToString());
                }
//						if (CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
//						{
//
//
//							staticWriter.Write ("new " + typeStringNoPtr + " ([");
//
//
//						}
//						Core.Write (staticWriter, initializerOpt.Value);
//						if (CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
//						{
//
//
//							staticWriter.Write ("])");
//						}
            }
        }
        public static void Go(OutputWriter writer, SwitchStatementSyntax switchStatement)
        {
            writer.WriteIndent();
            var isStringSwitch = false;
            var symbol         = TypeProcessor.GetTypeInfo(switchStatement.Expression);

            if (symbol.Type.SpecialType == SpecialType.System_String)
            {
                isStringSwitch = true;
            }

            writer.Write("switch( ");
            Core.Write(writer, switchStatement.Expression);

            writer.Write(isStringSwitch ? ".Text" : "");

            writer.Write(" )\n");
            writer.OpenBrace();

            //First process all blocks except the section with the default block
            foreach (
                var section in
                switchStatement.Sections.Where(
                    o => o.Labels.None(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword)))
            {
                writer.WriteIndent();

                foreach (var label in section.Labels)
                {
                    //Core.Write(writer, label, true);
                    WriteLabel.Go(writer, (CaseSwitchLabelSyntax)label, isStringSwitch);
                }
                //                writer.Write(" :\r\n");
                writer.Indent++;

                foreach (var statement in section.Statements)
                {
                    if (!(statement is BreakStatementSyntax))
                    {
                        Core.Write(writer, statement);
                    }
                }

                writer.WriteLine("break;");
                writer.Indent--;
            }

            //Now write the default section
            var defaultSection =
                switchStatement.Sections.SingleOrDefault(
                    o => o.Labels.Any(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword));

            if (defaultSection != null)
            {
                // if (defaultSection.Labels.Count > 1)
                //   throw new Exception("Cannot fall-through into or out of the default section of switch statement " + Utility.Descriptor(defaultSection));

                writer.WriteLine("default:\r\n");
                writer.Indent++;

                foreach (var statement in defaultSection.Statements)
                {
                    if (!(statement is BreakStatementSyntax))
                    {
                        Core.Write(writer, statement);
                    }
                }
                writer.WriteLine("break;");
                writer.Indent--;
            }
            else
            {
                writer.WriteLine("default:\r\nbreak;\r\n");
            }

            writer.CloseBrace();
        }
Beispiel #44
0
 public static void WriteStatement(OutputWriter writer, ExpressionStatementSyntax statement)
 {
     writer.WriteIndent();
     Write(writer, statement.Expression);
     writer.Write(";\r\n");
 }
        private static void Go(OutputWriter writer, IEnumerable<ParameterSyntax> parameters, SyntaxNode body,
            TypeInfo type)
        {
            var methodSymbol = type.ConvertedType.As<INamedTypeSymbol>().DelegateInvokeMethod.As<IMethodSymbol>();

            var typeStringNoPtr = TypeProcessor.ConvertType(type.ConvertedType);

            if (type.ConvertedType.TypeKind == TypeKind.TypeParameter)
                writer.Write(" __TypeNew!(" + typeStringNoPtr + ")(");
            else
                writer.Write("new " + typeStringNoPtr + "(");

            writer.Write("(");

            var parameterSyntaxs = parameters as ParameterSyntax[] ?? parameters.ToArray();
            for (int pi = 0; pi < parameterSyntaxs.Count(); pi++)
            {
                var parameter = parameterSyntaxs.ElementAt(pi);
                if (pi > 0)
                    writer.Write(", ");

                if (parameter.Type != null)
                    writer.Write(TypeProcessor.ConvertType(parameter.Type) + " ");
                else
                    writer.Write(TypeProcessor.ConvertType(methodSymbol.Parameters[pi].Type) + " ");
                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Identifier.Text));
            }

            writer.Write(")");

            bool returnsVoid = methodSymbol.ReturnType.ToString() == "void";

            if (body is BlockSyntax)
            {
                writer.Write("\r\n");
                writer.OpenBrace();

                var statements = body.As<BlockSyntax>().Statements;

                var lastStatement = statements.LastOrDefault() as ReturnStatementSyntax;

                var returnStatements = FindReturnStatements(body);

                {
                    foreach (var statement in statements)
                    {
                        if (statement == lastStatement)
                        {
                            writer.WriteIndent();

                            Core.Write(writer, lastStatement);
//                            writer.Write(";\r\n");
                        }
                        else
                            Core.Write(writer, statement);
                    }
                }

                writer.Indent--;
                writer.WriteIndent();
                writer.Write("}");
            }
            else
            {
                if (!returnsVoid)
                {
                    writer.Write("=> ");
                    Core.Write(writer, body);
                }
                else
                {
                    writer.Write(" { ");
                    Core.Write(writer, body);
                    writer.Write("; }");
                }
                //writer.Write(" { ");
                //if (!returnsVoid)
                //	writer.Write ("return ");
                //    writer.Write("; }");
            }

//            if (!returnsVoid)
//                writer.Write(TypeProcessor.ConvertTypeWithColon(methodSymbol.ReturnType));
            writer.Write(")");
        }
        private static void Go(OutputWriter writer, IEnumerable <ParameterSyntax> parameters, SyntaxNode body,
                               TypeInfo type)
        {
            var methodSymbol = type.ConvertedType.As <INamedTypeSymbol>().DelegateInvokeMethod.As <IMethodSymbol>();

            var typeStringNoPtr = TypeProcessor.ConvertType(type.ConvertedType);

            if (type.ConvertedType.TypeKind == TypeKind.TypeParameter)
            {
                writer.Write(" __TypeNew!(" + typeStringNoPtr + ")(");
            }
            else
            {
                writer.Write("new " + typeStringNoPtr + "(");
            }

            writer.Write("(");

            var parameterSyntaxs = parameters as ParameterSyntax[] ?? parameters.ToArray();

            for (int pi = 0; pi < parameterSyntaxs.Count(); pi++)
            {
                var parameter = parameterSyntaxs.ElementAt(pi);
                if (pi > 0)
                {
                    writer.Write(", ");
                }

                if (parameter.Type != null)
                {
                    writer.Write(TypeProcessor.ConvertType(parameter.Type) + " ");
                }
                else
                {
                    writer.Write(TypeProcessor.ConvertType(methodSymbol.Parameters[pi].Type) + " ");
                }
                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Identifier.Text));
            }

            writer.Write(")");

            bool returnsVoid = methodSymbol.ReturnType.ToString() == "void";

            if (body is BlockSyntax)
            {
                writer.Write("\r\n");
                writer.OpenBrace();

                var statements = body.As <BlockSyntax>().Statements;

                var lastStatement = statements.LastOrDefault() as ReturnStatementSyntax;

                var returnStatements = FindReturnStatements(body);

                {
                    foreach (var statement in statements)
                    {
                        if (statement == lastStatement)
                        {
                            writer.WriteIndent();

                            Core.Write(writer, lastStatement);
//                            writer.Write(";\r\n");
                        }
                        else
                        {
                            Core.Write(writer, statement);
                        }
                    }
                }

                writer.Indent--;
                writer.WriteIndent();
                writer.Write("}");
            }
            else
            {
                if (!returnsVoid)
                {
                    writer.Write("=> ");
                    Core.Write(writer, body);
                }
                else
                {
                    writer.Write(" { ");
                    Core.Write(writer, body);
                    writer.Write("; }");
                }
                //writer.Write(" { ");
                //if (!returnsVoid)
                //	writer.Write ("return ");
                //    writer.Write("; }");
            }

//            if (!returnsVoid)
//                writer.Write(TypeProcessor.ConvertTypeWithColon(methodSymbol.ReturnType));
            writer.Write(")");
        }
        public static void Go(OutputWriter writer, SwitchStatementSyntax switchStatement)
        {
          //  writer.WriteIndent();
            var isStringSwitch = false;
            var isEnumSwitch = false;

            var symbol = TypeProcessor.GetTypeInfo(switchStatement.Expression);
            if (symbol.Type != null) // Sometimes its null why ?
            {

                if (symbol.Type.SpecialType == SpecialType.System_String)
                    isStringSwitch = true;

                if (symbol.Type.TypeKind == TypeKind.Enum)
                    isEnumSwitch = true;
            }

            if (!(switchStatement.Expression is LiteralExpressionSyntax))
				writer.WriteLine ("switch(" + Core.WriteString (switchStatement.Expression) + (isStringSwitch ? ".Hash" : "") + (isEnumSwitch ? ".__Value" : "") + ")");
			else
			{
				var typeInfo = TypeProcessor.GetTypeInfo(switchStatement.Expression);
				if (typeInfo.Type.SpecialType == SpecialType.System_String)
				{
					writer.WriteLine ("switch(");
					WriteLiteralExpression.Go (writer, (LiteralExpressionSyntax)switchStatement.Expression, true, true);
					writer.WriteLine ((isStringSwitch ? ".Hash" : "") + ")");

				}
				else
				{
					writer.WriteLine ("switch(" + Core.WriteString (switchStatement.Expression) + (isStringSwitch ? ".Hash" : "") + (isEnumSwitch ? ".__Value" : "") + ")");

				}
			}
            writer.OpenBrace();

            //First process all blocks except the section with the default block
            foreach (
                var section in
                    switchStatement.Sections.Where(
                        o => o.Labels.None(z => z.Keyword.RawKind == (decimal) SyntaxKind.DefaultKeyword)))
            {

                foreach (var label in section.Labels)
                {
                    writer.WriteIndent();
                    WriteLabel.Go(writer, (CaseSwitchLabelSyntax) label, isStringSwitch);
                }
          
                writer.OpenBrace(false);

                foreach (var statement in section.Statements)
                {
                    if (!(statement is BreakStatementSyntax))
                        writer.Write(Core.WriteString(statement, false, writer.Indent+2));
                }

                writer.WriteLine("break;\r\n");
                writer.CloseBrace(false);
            }

            //Now write the default section
            var defaultSection =
                switchStatement.Sections.SingleOrDefault(
                    o => o.Labels.Any(z => z.Keyword.RawKind == (decimal) SyntaxKind.DefaultKeyword));
            if (defaultSection != null)
            {
 

				foreach (var label in defaultSection.Labels) // Could be more than one label :P
				{
					writer.WriteIndent();
					if (label is CaseSwitchLabelSyntax)
						WriteLabel.Go (writer, (CaseSwitchLabelSyntax)label, isStringSwitch);
					else
						writer.WriteLine (label.ToFullString().Trim());
				}

               // writer.WriteLine("default:");
                writer.OpenBrace(false);
                foreach (var statement in defaultSection.Statements)
                {
                    if (!(statement is BreakStatementSyntax))
                        writer.Write(Core.WriteString(statement,false, writer.Indent+2));
                }
                writer.WriteLine("break;");
                writer.CloseBrace(false);
            }
            else
            {
                writer.WriteLine("default:");
                    writer.WriteLine("break;");
            }

            writer.CloseBrace();
        }
Beispiel #48
0
        public static void Go(OutputWriter writer, MemberDeclarationSyntax field, SyntaxTokenList modifiers, string name,
                              TypeSyntax type, EqualsValueClauseSyntax initializerOpt = null, bool isThreadStatic = false)
        {
            writer.WriteIndent();

            var typeinfo = TypeProcessor.GetTypeInfo(type);

//            var isPtr = typeinfo.Type != null && (typeinfo.Type.IsValueType || typeinfo.Type.TypeKind==TypeKind.TypeParameter) ? "" : "";

            var typeStringNoPtr = TypeProcessor.ConvertType(type);

            var typeString = typeStringNoPtr + " ";

            var isConst = IsConst(modifiers, initializerOpt, type);

            var isStatic = isConst;

            //Handle Auto Properties

            // if (modifiers.Any(SyntaxKind.PrivateKeyword)) // Reflection cannot work with this, cant get address or set value
            //   writer.Write("private ");

            if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) ||
                modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword))
            {
                writer.Write("public ");
            }


            if (isThreadStatic)
            {
                writer.Write("static ");
            }

            if (modifiers.Any(SyntaxKind.StaticKeyword) || modifiers.Any(SyntaxKind.ConstKeyword))
            {
                isStatic = true;
                writer.Write("__gshared ");
            }



            if (isConst && typeinfo.Type.IsPrimitive())
            {
                writer.Write("const "); //const has interesting semantics in Dlang
            }

            var         @event = field is EventFieldDeclarationSyntax;
            ITypeSymbol iface;

            ISymbol[] proxies;

            bool isInterface = false;

            // var ename = MemberUtilities.GetMethodName(field, ref isInterface, out iface, out proxies);
            if (@event)
            {
                typeString = ("__Event!(" + typeString + ")");

                if (field.Parent is InterfaceDeclarationSyntax)
                {
                    //writer.Write(typeString);
                    writer.WriteLine(typeString + " " + name + "(" + TypeProcessor.ConvertType(field.Parent) + " __ij)" + "@property;");
                    return;
                }
            }

            writer.Write(typeString);


//                if (isStatic)
//                    writer.Write(typeString);

            writer.Write(name);
            if (isStatic)
            {
//                var fieldInfo = TypeProcessor.GetDeclaredSymbol(field.Parent);
//                if (fieldInfo != null)
//                    writer.Write((!string.IsNullOrEmpty(fieldInfo.ContainingNamespace.FullName())?(fieldInfo.ContainingNamespace.FullName()+".") :"") + fieldInfo.Name+"."+name);
//				writer.Write(name);
            }

            if (!isStatic || isConst)
            {
                if (initializerOpt != null)
                {
                    writer.Write(String.Format(" = cast({0})", typeString));

                    if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression ||
                        CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
                    {
//                        writer.Write("gc::gc_ptr< " + typeStringNoPtr + " >(");
                        writer.Write(" new " + typeString + " (");
                        var intializer = initializerOpt.Value as InitializerExpressionSyntax;
                        intializer.WriteArrayInitializer(writer, type);

                        writer.Write(")");
                    }

                    else
                    {
                        Core.Write(writer, initializerOpt.Value);
                    }
                }

                else
                {
                    // if (typeinfo.Type.TypeKind != TypeKind.Struct)
                    {
                        writer.Write(" = ");
                        if (typeinfo.Type.TypeKind == TypeKind.Delegate)
                        {
                            writer.Write("new " + typeString + "()");
                        }
                        else
                        {
                            writer.Write(TypeProcessor.DefaultValue(type));
                        }
                    }
                }
            }
            else
            {
                var staticWriter = new TempWriter();

                if (initializerOpt != null)
                {
                    staticWriter.Write(name);

                    staticWriter.Write(" = ");

                    if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression ||
                        CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
                    {
                        staticWriter.Write("new " + typeStringNoPtr + " (");

                        var intializer = initializerOpt.Value as InitializerExpressionSyntax;

                        intializer.WriteArrayInitializer(staticWriter, type);
                        staticWriter.Write(")");
                    }
                    else
                    {
                        Core.Write(staticWriter, initializerOpt.Value);
                    }

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());
                }

                else if (typeinfo.Type.TypeKind != TypeKind.Struct)

                {
                    staticWriter.Write(name);
                    staticWriter.Write(" = ");

                    if (typeinfo.Type.TypeKind == TypeKind.Delegate)
                    {
                        staticWriter.Write("new " + typeString + "()");
                    }
                    else
                    {
                        staticWriter.Write(TypeProcessor.DefaultValue(type));
                    }

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());
                }
            }

            writer.Write(";");
            writer.WriteLine();
        }
        public static void WriteAnonymousType(AnonymousObjectCreationExpressionSyntax syntax)
        {
            var type = TypeProcessor.GetTypeInfo(syntax).Type.As <INamedTypeSymbol>();

            Context.Instance.Type = type;

            TypeProcessor.ClearUsedTypes();

            var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace");

            // + "." + TypeState.Instance.TypeName;
            Context.Instance.Namespace = mynamespace;
            var myUsingDirective     = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace));
            var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));

            // Required as certain functions like boxing are in this namespace

            Context.Instance.UsingDeclarations =
                syntax.Parent.DescendantNodes().OfType <UsingDirectiveSyntax>().ToArray()
                .Union(new[]
            {
                myUsingDirective, SystemUsingDirective
            }).ToArray();

            //using (var writer = new CppWriter (TypeState.Instance.Namespace, )) {

            //Ty

            var anonName = TypeName(type);

            using (var writer = new OutputWriter(Context.Instance.Namespace, StripGeneric(anonName)))
            {
                var fields = type.GetMembers().OfType <IPropertySymbol>().OrderBy(o => o.Name).ToList();

//                writer.WriteLine("namespace anonymoustypes {");
                WriteStandardIncludes.Go(writer);

                writer.WriteIndent();
                writer.Write("class ");
                writer.Write(anonName);

                writer.OpenBrace();

                foreach (var field in fields)
                {
                    writer.WriteIndent();
                    writer.Write("public ");
                    writer.Write(TypeProcessor.ConvertType(field.Type) + " ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(" = " + TypeProcessor.DefaultValue(field.Type));
                    writer.Write(";\r\n");
                }

                //Must Write a constructor here ...
                writer.Write("\r\nthis (");
                bool first = true;
                foreach (var field in fields)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        writer.Write(", ");
                    }

                    writer.Write(TypeProcessor.ConvertType(field.Type) + " ");
                    writer.Write("_" + WriteIdentifierName.TransformIdentifier(field.Name));
                }
                writer.Write(")\r\n");
                writer.OpenBrace();
                writer.Indent++;

                foreach (var field in fields)
                {
                    var fieldNAme = WriteIdentifierName.TransformIdentifier(field.Name);

                    writer.WriteLine(fieldNAme + " = _" + fieldNAme + ";");
                }
                writer.Indent--;

                writer.CloseBrace();

                writer.CloseBrace();
//                writer.Write("};");
//                writer.Write("}");
            }
        }