public static void Go(OutputWriter writer, ImplicitArrayCreationExpressionSyntax array)
        {
            var ti = TypeProcessor.GetTypeInfo(array);
            var t  = ti.Type;

            if (ti.ConvertedType != null && !(ti.ConvertedType == t)) // Alot of times we are using covariance here
            {
                t = ti.ConvertedType;
            }
            var ptr         = !t.As <IArrayTypeSymbol>().ElementType.IsValueType; // ? "" : "";
            var elementType = t.As <IArrayTypeSymbol>().ElementType;
            var type        = TypeProcessor.ConvertType(elementType);
            var typeString  = "Array_T!(" + type + ")";

            var tempWriter = new TempWriter();

            tempWriter.Indent = writer.Indent;

            if (elementType.TypeKind == TypeKind.TypeParameter)
            {
                tempWriter.Write(" __TypeNew!(" + typeString + ")([");
            }
            else
            {
                tempWriter.Write("new " + typeString + "(");
            }



            //__ARRAY
            var variableDeclarationSyntax = array.Parent.Parent.Parent as VariableDeclarationSyntax;

            // var argumentSyntax = array.Parent as ArgumentSyntax;

            if (variableDeclarationSyntax != null)
            {
                var atype = variableDeclarationSyntax.Type;
                array.Initializer.WriteArrayInitializer(tempWriter, atype);
            }
            else
            {
                array.Initializer.WriteArrayInitializer(tempWriter, t);
            }


            tempWriter.Write(")");

            var tempString = tempWriter.ToString();

            var oldString = tempString;

            tempString = tempString.Replace("new " + typeString + "(__CC!(" + type + "[])(", "__ARRAY!(" + type + ")(");

            if (tempString != oldString)
            {
                tempString = tempString.RemoveFromEndOfString(")");
            }

            writer.Write(tempString);
        }
Ejemplo n.º 2
0
        public static string WriteBlock(BlockSyntax block, bool writeBraces = true, int indent = 0)
        {
            var writer = new TempWriter();

            writer.Indent = indent;
            if (writeBraces)
            {
                writer.OpenBrace();
            }

            //writer.Indent++;
            foreach (var statement in block.Statements)
            {
                // writer.WriteIndent();
                Write(writer, statement);
            }

            TriviaProcessor.ProcessTrivias(writer, block.DescendantTrivia());
            // writer.Indent--;

            if (writeBraces)
            {
                writer.CloseBrace();
            }

            return(writer.ToString());
        }
Ejemplo n.º 3
0
        public static string WriteString(SyntaxNode node, bool isConst = false, int indent = 0)
        {
            var writer = new TempWriter();
            writer.Indent = indent;

            Write(writer, node, isConst);

            return writer.ToString();
        }
Ejemplo n.º 4
0
        public static string WriteString(SyntaxNode node, bool isConst = false, int indent = 0)
        {
            var writer = new TempWriter();

            writer.Indent = indent;

            Write(writer, node, isConst);

            return(writer.ToString());
        }
Ejemplo n.º 5
0
        public static string GetParameterListAsString(ParameterListSyntax list, bool includeTypes = true)
        {
            var writer = new TempWriter(); // Temp Writer

            writer.Write("(");
            var firstParam = true;

            foreach (var parameter in list.Parameters)
            {
                var refKeyword = "";

                if (parameter.Modifiers.Any(SyntaxKind.RefKeyword))
                {
                    refKeyword = " ref ";
                }

                if (parameter.Modifiers.Any(SyntaxKind.OutKeyword))
                {
                    refKeyword = " out ";
                }

                if (parameter.Modifiers.Any(SyntaxKind.InKeyword))
                {
                    refKeyword = " in ";
                }

                bool isRef = parameter.Modifiers.Any(SyntaxKind.OutKeyword) ||
                             parameter.Modifiers.Any(SyntaxKind.RefKeyword);
                // || parameter.Modifiers.Any (SyntaxKind.InKeyword);
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    writer.Write(", ");
                }

                var s = refKeyword + TypeProcessor.ConvertType(parameter.Type) + " ";
                if (includeTypes)
                {
                    writer.Write(s);
                }

                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Identifier.ValueText));
                if (parameter.Default == null)
                {
                    continue;
                }
                writer.Write(" = ");
                Core.Write(writer, parameter.Default.Value);
            }
            writer.Write(")");
            return(writer.ToString());
        }
        public static void Go(OutputWriter writer, ImplicitArrayCreationExpressionSyntax array)
        {
            var ti = TypeProcessor.GetTypeInfo(array);
            var t = ti.Type;
            if (ti.ConvertedType!=null && !(ti.ConvertedType == t)) // Alot of times we are using covariance here
            {
                t = ti.ConvertedType;
            }
            var ptr = !t.As<IArrayTypeSymbol>().ElementType.IsValueType; // ? "" : "";
            var elementType = t.As<IArrayTypeSymbol>().ElementType;
            var type = TypeProcessor.ConvertType(elementType);
            var typeString = "Array_T!(" + type + ")";

            var tempWriter = new TempWriter();
            tempWriter.Indent = writer.Indent;

            if (elementType.TypeKind == TypeKind.TypeParameter)
                tempWriter.Write(" __TypeNew!(" + typeString + ")([");
            else
            {
                tempWriter.Write("new " + typeString + "(");
            }



            //__ARRAY
            var variableDeclarationSyntax = array.Parent.Parent.Parent as VariableDeclarationSyntax;
           // var argumentSyntax = array.Parent as ArgumentSyntax;

            if (variableDeclarationSyntax != null)
            {
                var atype = variableDeclarationSyntax.Type;
                array.Initializer.WriteArrayInitializer(tempWriter, atype);
            }
           else
                array.Initializer.WriteArrayInitializer(tempWriter,t);


            tempWriter.Write(")");

            var tempString = tempWriter.ToString();

            var oldString = tempString;

            tempString = tempString.Replace("new " + typeString + "(__CC!(" + type + "[])(", "__ARRAY!(" + type + ")(");

            if (tempString != oldString)
                tempString = tempString.RemoveFromEndOfString(")");

            writer.Write(tempString);

            
        }
Ejemplo n.º 7
0
        public static void Go(OutputWriter writer, ConversionOperatorDeclarationSyntax method)
        {
            //TODO: Need to find a way of dealing with this ... Quickly moving towards the idea of compile/decompile using ILSPY
            //  if (method.ImplicitOrExplicitKeyword.RawKind != (decimal) SyntaxKind.ExplicitKeyword)
            //     throw new Exception("Implicit cast operators are not supported " + Utility.Descriptor(method));

            var temp = new TempWriter();

//            temp.WriteIndent();

            temp.Write("public static " + TypeProcessor.ConvertType(method.Type));

            temp.Write(" " +
                       ((method.ImplicitOrExplicitKeyword.RawKind != (decimal)SyntaxKind.ExplicitKeyword)
                           ? ("op_Implicit_" + TypeProcessor.ConvertType(method.Type, false, true, false).Replace(".", "_"))
                           : "op_Explicit"));
            //writer.Write(" op_Explicit");
//            writer.Write(TypeProcessor.ConvertType(method.Type));
            temp.Write("(");

            bool firstParam = true;

            foreach (var param in method.ParameterList.Parameters)
            {
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    temp.Write(", ");
                }

                temp.Write(TypeProcessor.ConvertType(param.Type) + " ");

                temp.Write(WriteIdentifierName.TransformIdentifier(param.Identifier.Text));
            }

            temp.Write(")");

            writer.WriteLine(temp.ToString());

            writer.OpenBrace();

            foreach (var statement in method.Body.Statements)
            {
                Core.Write(writer, statement);
            }

            writer.CloseBrace();
        }
        public static void Go(OutputWriter writer, ConversionOperatorDeclarationSyntax method)
        {
            //TODO: Need to find a way of dealing with this ... Quickly moving towards the idea of compile/decompile using ILSPY
            //  if (method.ImplicitOrExplicitKeyword.RawKind != (decimal) SyntaxKind.ExplicitKeyword)
            //     throw new Exception("Implicit cast operators are not supported " + Utility.Descriptor(method));

            var temp = new TempWriter();

//            temp.WriteIndent();

            temp.Write("public static " + TypeProcessor.ConvertType(method.Type));

            temp.Write(" " +
                       ((method.ImplicitOrExplicitKeyword.RawKind != (decimal) SyntaxKind.ExplicitKeyword)
                           ? ("op_Implicit_" + TypeProcessor.ConvertType(method.Type,false,true,false).Replace(".", "_"))
                           : "op_Explicit"));
            //writer.Write(" op_Explicit");
//            writer.Write(TypeProcessor.ConvertType(method.Type));
            temp.Write("(");

            bool firstParam = true;
            foreach (var param in method.ParameterList.Parameters)
            {
                if (firstParam)
                    firstParam = false;
                else
                    temp.Write(", ");

                temp.Write(TypeProcessor.ConvertType(param.Type) + " ");

                temp.Write(WriteIdentifierName.TransformIdentifier(param.Identifier.Text));
            }

            temp.Write(")");

            writer.WriteLine(temp.ToString());

            writer.OpenBrace();

            foreach (var statement in method.Body.Statements)
                Core.Write(writer, statement);

            writer.CloseBrace();
        }
Ejemplo n.º 9
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);
            }
        }
Ejemplo n.º 10
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);
            }
        }
        public static void Go(OutputWriter writer, OperatorDeclarationSyntax method)
        {
            var methodSymbol = (IMethodSymbol)TypeProcessor.GetDeclaredSymbol(method);
            var actualMethodName = OverloadResolver.MethodName(methodSymbol);

            writer.Write("\n");


            var returnType = "";
            if (method.ReturnType.ToString() == "void")
                returnType = ("void ");
            else
            {
                returnType = TypeProcessor.ConvertType(method.ReturnType) + " ";

                //                writer.Write(returnType);
            }

            var methodName = "";

            if (BinaryOperators.ContainsKey(actualMethodName))
            {
                methodName = "opBinary";
                var typeSymbolParam0 = TypeProcessor.GetTypeInfo(method.ParameterList.Parameters[0].Type);

                var typeSymbolParent = (methodSymbol.ContainingType);

                if (typeSymbolParam0.Type != typeSymbolParent)
                    methodName += "Right";
            }

            if (UnaryOperators.ContainsKey(actualMethodName))
                methodName = "opUnary";

            if (EqualsOperators.ContainsKey(actualMethodName))
                methodName = "opEquals";

            if (CmpOperators.ContainsKey(actualMethodName))
                methodName = "opCmp";

            if (AssignOperators.ContainsKey(actualMethodName))
                methodName = "opAssign";

            if (AssignOpOperators.ContainsKey(actualMethodName))
                methodName = "opOpAssign"; // need to remove = from the name


            var paramType = method.ParameterList.Parameters[0];

            if (method.ParameterList.Parameters.Count == 2)
            {
                if (methodName.EndsWith("Right"))
                    paramType = method.ParameterList.Parameters[0];
                else
                    paramType = method.ParameterList.Parameters[1];
            }

            var token = method.OperatorToken.Text;

            var methodBody = "";

            var temp = new TempWriter();

            foreach (var statement in method.Body.Statements)
                Core.Write(temp, statement);

            TriviaProcessor.ProcessTrivias(temp, method.Body.DescendantTrivia());

            methodBody = temp.ToString();


            if (methodName == "opOpAssign")
                token = token.Substring(0, 1);

            //We are going to have to rewrite this bit later ... for now all overloads are called directly
        /*    if (methodName == "opBinary")
            {

                writer.WriteLine("public final " + returnType + " " + methodName +
                String.Format(
                    " (string _op) ({0} other)\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this,other); \r\n\t}}\r\n\r\n",
                    TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));

                //Add Assignment operator if it doesn't exist
                if (!methodSymbol.ContainingType.GetMembers(AssignOpOperators.FirstOrDefault(k => k.Value == token + "=").Key).Any())
                {
                    writer.WriteLine("public final " + returnType + " opOpAssign" +
                String.Format(
                    " (string _op) ({0} other)\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this,other); \r\n\t}}\r\n\r\n",
                    TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));
                }
            }
            else if (methodName == "opUnary")//TODO unary operators are mostly going to be direct methodCalls
            {

                writer.WriteLine("public final " + returnType + " " + methodName +
                    String.Format(
                        " (string _op) ()\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this); \r\n\t}}\r\n\r\n",
                        TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));
                //				writer.WriteLine ("public final ref " + returnType + " " + methodName +
                //					String.Format (
                //						" (string _op) ()\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\t{3}\r\n\t}}\r\n\r\n",
                //TypeProcessor.ConvertType (paramType.Type), actualMethodName, token, methodBody.Replace(method.ParameterList.Parameters[0].Identifier.ValueText,"this")));
            }
            else
            {
                writer.WriteLine("public final " + returnType + " " + methodName +
                    String.Format(
                        " (string _op) ({0} other)\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this); \r\n\t}}\r\n\r\n",
                        TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));
            }*/

            var @params = method.ParameterList.Parameters;



            writer.WriteLine("public static " + returnType + " " + actualMethodName + WriteMethod.GetParameterListAsString(method.ParameterList.Parameters));




            writer.OpenBrace();
            if (method.Body != null)
            {
                foreach (var statement in method.Body.Statements)
                    Core.Write(writer, statement);

                TriviaProcessor.ProcessTrivias(writer, method.Body.DescendantTrivia());
            }

            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++;
            }
        }
Ejemplo n.º 13
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();
        }
Ejemplo n.º 14
0
        public static void Go(OutputWriter writer, ForStatementSyntax forStatement)
        {
            //   writer.WriteLine(); // Beautify the code ...

            var tempWriter = new TempWriter();

            tempWriter.WriteIndent();
            tempWriter.Write("for (");

            foreach (var init in forStatement.Initializers)
            {
                Core.Write(tempWriter, init);
                if (init != forStatement.Initializers.Last())
                {
                    tempWriter.Write(",");
                }
            }

            if (forStatement.Declaration != null)
            {
                var variables = forStatement.Declaration.Variables;
                foreach (var variable in variables)
                {
                    //                    writer.WriteIndent();
                    tempWriter.Write(TypeProcessor.ConvertType(forStatement.Declaration.Type) + " ");
                    tempWriter.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.ValueText));

                    if (variable.Initializer != null)
                    {
                        tempWriter.Write(" = ");
                        Core.Write(tempWriter, variable.Initializer.Value);
                    }

                    if (variable != variables.LastOrDefault())
                    {
                        tempWriter.Write(",");
                    }
                }
            }

            tempWriter.Write(";");

            if (forStatement.Condition == null)
            {
                tempWriter.Write("true");
            }
            else
            {
                Core.Write(tempWriter, forStatement.Condition);
            }

            tempWriter.Write(";");

            foreach (var iterator in forStatement.Incrementors)
            {
                Core.Write(tempWriter, iterator);

                if (iterator != forStatement.Incrementors.LastOrDefault())
                {
                    tempWriter.Write(",");
                }
            }

            tempWriter.Write(")");

            writer.WriteLine(tempWriter.ToString());
            writer.OpenBrace();
            Core.WriteStatementAsBlock(writer, forStatement.Statement, false);
            writer.CloseBrace();

            //  writer.WriteLine(); // Beautify the code ...
        }
Ejemplo n.º 15
0
        //TODO should enum be light class of static members ? or just a plain enum ? (using plain enum for now)
        public static void Go(OutputWriter writer, IEnumerable<EnumMemberDeclarationSyntax> allChildren)
        {
            //            writer.IsInterface = true;
            writer.Write("struct ");
            writer.Write(WriteType.TypeName(Context.Instance.Type, false) + "// Enum");

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

            //TODO: Find a better fix for this, casting integers to e.g. enum of ubyte gives lots of issues
            // writer.Write(":" + TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType));
            writer.Write("\r\n");





            writer.OpenBrace();

            writer.WriteLine("public " + TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType) + " __Value;");
            writer.WriteLine("alias __Value this;");

            writer.WriteLine("public enum __IsEnum = true; // Identifies struct as enum");

            string flagsvalue = "false";

            if (Context.Instance.Type.GetAttributes().Any(k => k.AttributeClass != null && k.AttributeClass.Name == "FlagsAttribute"))
            {
                flagsvalue = "true";
            }

            writer.WriteLine("public enum __HasFlags = {0}; // Identifies struct as enum", flagsvalue);




            writer.WriteLine(string.Format("public this({0} value)", TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType)));
            writer.OpenBrace();
            writer.WriteLine("__Value = value;");
            writer.CloseBrace();


            writer.WriteLine();
            writer.WriteLine("public Type GetType()");
            writer.OpenBrace();
            writer.WriteLine("return __TypeOf!(typeof(this));");
            writer.CloseBrace();


            long lastEnumValue = 0;
            var children = allChildren.ToArray();
            var values =
                children.Select(
                    o => new { Syntax = o, Value = o.EqualsValue != null ? o.EqualsValue.Value : null })
                    .ToList();

            var actualValues = new List<string>();

            for (int index = 0; index < values.Count; index++)
            {
                var value = values[index];
                var text = "";

                text = "public enum " + WriteType.TypeName(Context.Instance.Type, false) + " "
                       + WriteIdentifierName.TransformIdentifier(value.Syntax.Identifier.Text);
                var expressionSyntax = value.Value;
                var expression = expressionSyntax;

                //lets try parsing the value so we can evaluate it
                if (expression != null)
                {
                    var type = TypeProcessor.GetTypeInfo(expression);

                    var tempw = new TempWriter();

                    Core.Write(tempw, expression);

                    var temp = tempw.ToString();

                    if (type.Type != Context.Instance.Type.EnumUnderlyingType)
                    {
                        //TODO: only int enums are supported properly ... should we change them to static structs with constants ?
                        //						temp = "cast(" + TypeProcessor.ConvertType (Context.Instance.Type.EnumUnderlyingType) + ")" + temp;
                        temp = "cast(" + TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType) + ")" +
                               temp;
                    }

                    actualValues.Add(temp);
                    text += " = " + temp;
                    tempw.Dispose();
                    ;
                }
                else
                {
                    if (expressionSyntax != null && expressionSyntax.ToFullString().Trim() != "")
                        text += expressionSyntax;
                    else
                    {
                        if (index > 0)
                        {
                            var temp =
                                WriteIdentifierName.TransformIdentifier(values[index - 1].Syntax.Identifier.Text) + " + 1";
                            text += " = " +
                                temp;
                            actualValues.Add(temp);

                        }
                        else
                        {
                            text += " = 0";
                            actualValues.Add("0");
                        }

                    }
                }

                writer.WriteLine(text + ";");
            }

            //TODO: Need Fix
            var list = new List<string>();
            for (int index = 0; index < values.Count; index++)
            {
                var item = actualValues[index];
                for (int i = 0; i < values.Count ; i++)
                {
                    var value = values[i];
                    if ((value.Value is LiteralExpressionSyntax)||value.Value == null)
                    {
                        item =
                            item.Replace(
                                TypeProcessor.ConvertType(Context.Instance.Type, true, false, false) + "." +
                                value.Syntax.Identifier.Text, actualValues[i]);
                        actualValues[i] = item;
                    }
                }
                list.Add(item);
            }

            writer.WriteLine("public enum __values =[" + list.Aggregate((a, b) => a + "," + b) + "];");
            writer.WriteLine("public enum __names =[" + values.Select(j => "\"" + WriteIdentifierName.TransformIdentifier(j.Syntax.Identifier.Text) + "\"").Aggregate((a, b) => a + "," + b) + "];");


            writer.WriteLine();
            var typeName = WriteType.TypeName(Context.Instance.Type, false);

            var baseString = "";


            writer.WriteLine();

            writer.WriteLine("{0} opBinary(string op)({0} rhs)", typeName);
            writer.OpenBrace();
            writer.WriteLine("return mixin(\"{0}(__Value \"~op~\" rhs.__Value)\");", typeName);
            writer.CloseBrace();

            writer.WriteLine("bool opEquals(const {0} a)", typeName);
            writer.OpenBrace();
            writer.WriteLine("return a.__Value == this.__Value;", typeName);
            writer.CloseBrace();

            writer.WriteLine("bool opEquals(const {0} a)", TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType));
            writer.OpenBrace();
            writer.WriteLine("return a == this.__Value;", typeName);
            writer.CloseBrace();


            writer.WriteLine("public string toString()");
            writer.OpenBrace();
            /*  foreach (var membername in values)
              {
                  var name = WriteIdentifierName.TransformIdentifier(membername.Syntax.Identifier.Text);
                  writer.WriteLine("if (this == {0}.__Value)", name);
                  writer.OpenBrace();
                  writer.WriteLine("return \"{0}\";", name);
                  writer.CloseBrace();
              }
              writer.WriteLine("return std.conv.to!string(BOX(this.__Value).ToString().Text);");*/
            writer.WriteLine("return __ConvertEnumToString(this);");

            writer.CloseBrace();

            //Not needed for enum ... all enum should have a ToString function ...
            //            writer.WriteLine("public static class __Boxed_" + " " +
            //                                 //(genericArgs.Any() ? ("( " + (string.Join(" , ", genericArgs.Select(o => o)) + " )")) : "") +//Internal boxed should not be generic
            //                                 ": Boxed!(" + typeName + ")" + baseString);
            //
            //            writer.OpenBrace();
            //
            //
            //
            //            writer.WriteLine("import std.traits;");
            //
            //            var members = new List<ISymbol>();
            //
            //           
            //
            //            //  foreach (var baseType in bases.Where(o => o.TypeKind == TypeKind.Interface))
            //            //{
            //
            //            var ifacemembers = members.DistinctBy(k => k);//Utility.GetAllMembers(Context.Instance.Type);
            //
            //            foreach (var member in ifacemembers)
            //            {
            //                var ifacemethod =
            //                    Context.Instance.Type.FindImplementationForInterfaceMember(member)
            //                        .DeclaringSyntaxReferences.First()
            //                        .GetSyntax();
            //
            //                var syntax = ifacemethod as MethodDeclarationSyntax;
            //                if (syntax != null)
            //                    WriteMethod.WriteIt(writer, syntax);
            //
            //                var property = ifacemethod as PropertyDeclarationSyntax;
            //                if (property != null)
            //                    WriteProperty.Go(writer, property, true);
            //
            //            }
            //            //}
            //
            //            //This is required to be able to create an instance at runtime / reflection
            //            //					this()
            //            //					{
            //            //						super(SimpleStruct.init);
            //            //					}
            //
            //            writer.WriteLine();
            //            writer.WriteLine("this()");
            //            writer.OpenBrace();
            //            writer.WriteLine("super(__TypeNew!({0})());", typeName);
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("public override Type GetType()");
            //            writer.OpenBrace();
            //            writer.WriteLine("return __TypeOf!(typeof(__Value));");
            //            writer.CloseBrace();
            //
            //
            //            if (Context.Instance.Type.GetMembers("ToString").Any()) // Use better matching ?
            //            {
            //                //					writer.WriteLine ();
            //                writer.WriteLine("override String ToString()");
            //                writer.OpenBrace();
            //                writer.WriteLine("return Value.ToString();");
            //                writer.CloseBrace();
            //            }
            //
            //            writer.WriteLine();
            //            writer.WriteLine("this(ref " + typeName + " value)");
            //            writer.OpenBrace();
            //            writer.WriteLine("super(value);");
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("U opCast(U)()");
            //            writer.WriteLine("if(is(U:{0}))", typeName);
            //            writer.OpenBrace();
            //            writer.WriteLine("return Value;");
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("U opCast(U)()");
            //            writer.WriteLine("if(!is(U:{0}))", typeName);
            //            writer.OpenBrace();
            //            writer.WriteLine("return this;");
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("auto opDispatch(string op, Args...)(Args args)");
            //            writer.OpenBrace();
            //            writer.WriteLine("enum name = op;");
            //            writer.WriteLine("return __traits(getMember, Value, name)(args);");
            //            writer.CloseBrace();

            //            writer.WriteLine();
            //            writer.WriteLine("public override Type GetType()");
            //            writer.OpenBrace();
            //            writer.WriteLine("return __Value.GetType();");
            //            writer.CloseBrace();


            //            writer.CloseBrace();

            writer.CloseBrace();
            //            writer.Write(";");
        }
Ejemplo n.º 16
0
        public static string GetParameterListAsString(ImmutableArray<IParameterSymbol> parameters, bool includeTypes = true, ITypeSymbol iface = null, bool writebraces = true)
        {

            var writer = new TempWriter(); // Temp Writer
            if (writebraces)
                writer.Write("(");
            var firstParam = true;
            foreach (var parameter in parameters)
            {
                var refKeyword = "";

                if (parameter.RefKind==RefKind.Ref)
                    refKeyword = " ref ";

                if (parameter.RefKind==RefKind.Out)
                    refKeyword = " out ";

             //   if (parameter.RefKind==RefKind.None) //????
               //     refKeyword = " in ";

                bool isRef = parameter.RefKind == RefKind.Ref || parameter.RefKind == RefKind.Out;// parameter.Modifiers.Any(SyntaxKind.OutKeyword) ||
                           //  parameter.Modifiers.Any(SyntaxKind.RefKeyword);
                // || parameter.Modifiers.Any (SyntaxKind.InKeyword);
                if (firstParam)
                    firstParam = false;
                else
                    writer.Write(", ");

                var isParams = parameter.IsParams;//.Any(SyntaxKind.ParamsKeyword);

                //if (!isParams)
                {
                    var s = refKeyword + TypeProcessor.ConvertType(parameter.Type) + " ";
                    if (includeTypes)
                        writer.Write(s);
                }
                /* else //Framework depends too much on managed arrays even for params
                 {
                     var type = (TypeProcessor.GetTypeInfo(parameter.Type).Type ?? TypeProcessor.GetTypeInfo(parameter.Type).ConvertedType) as IArrayTypeSymbol;
                     var s = refKeyword + TypeProcessor.ConvertType(type.ElementType) + "[]";

                     if (includeTypes)
                         writer.Write(s);

                 }*/

                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Name));
                if (!parameter.HasExplicitDefaultValue)
                    continue;
                writer.Write(" = ");
                if (parameter.ExplicitDefaultValue is SyntaxNode)
                {
                    Core.Write(writer, (SyntaxNode) (parameter.ExplicitDefaultValue)); //TODO ??
                }
                else
                {
                    if(parameter.ExplicitDefaultValue is string)
                        writer.Write("_S(\""+parameter.ExplicitDefaultValue.ToString()+"\")");
                    else
                    {
                        writer.Write(parameter.ExplicitDefaultValue.ToString());

                    }

                }
               
            }
            if (iface != null)
            {
                if (firstParam)
                    firstParam = false;
                else
                    writer.Write(", ");

                writer.Write(TypeProcessor.ConvertType(iface) + " __j = null");
            }
            if (writebraces)
                writer.Write(")");
            return writer.ToString();
        }
Ejemplo n.º 17
0
        public static string GetParameterListAsString(ImmutableArray <IParameterSymbol> parameters, bool includeTypes = true, ITypeSymbol iface = null, bool writebraces = true)
        {
            var writer = new TempWriter(); // Temp Writer

            if (writebraces)
            {
                writer.Write("(");
            }
            var firstParam = true;

            foreach (var parameter in parameters)
            {
                var refKeyword = "";

                if (parameter.RefKind == RefKind.Ref)
                {
                    refKeyword = " ref ";
                }

                if (parameter.RefKind == RefKind.Out)
                {
                    refKeyword = " out ";
                }

                //   if (parameter.RefKind==RefKind.None) //????
                //     refKeyword = " in ";

                bool isRef = parameter.RefKind == RefKind.Ref || parameter.RefKind == RefKind.Out;// parameter.Modifiers.Any(SyntaxKind.OutKeyword) ||
                //  parameter.Modifiers.Any(SyntaxKind.RefKeyword);
                // || parameter.Modifiers.Any (SyntaxKind.InKeyword);
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    writer.Write(", ");
                }

                var isParams = parameter.IsParams;//.Any(SyntaxKind.ParamsKeyword);

                //if (!isParams)
                {
                    var s = refKeyword + TypeProcessor.ConvertType(parameter.Type) + " ";
                    if (includeTypes)
                    {
                        writer.Write(s);
                    }
                }

                /* else //Framework depends too much on managed arrays even for params
                 * {
                 *   var type = (TypeProcessor.GetTypeInfo(parameter.Type).Type ?? TypeProcessor.GetTypeInfo(parameter.Type).ConvertedType) as IArrayTypeSymbol;
                 *   var s = refKeyword + TypeProcessor.ConvertType(type.ElementType) + "[]";
                 *
                 *   if (includeTypes)
                 *       writer.Write(s);
                 *
                 * }*/

                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Name));
                if (!parameter.HasExplicitDefaultValue)
                {
                    continue;
                }
                writer.Write(" = ");
                if (parameter.ExplicitDefaultValue is SyntaxNode)
                {
                    Core.Write(writer, (SyntaxNode)(parameter.ExplicitDefaultValue));  //TODO ??
                }
                else
                {
                    if (parameter.ExplicitDefaultValue is string)
                    {
                        writer.Write("_S(\"" + parameter.ExplicitDefaultValue.ToString() + "\")");
                    }
                    else
                    {
                        writer.Write(parameter.ExplicitDefaultValue.ToString());
                    }
                }
            }
            if (iface != null)
            {
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    writer.Write(", ");
                }

                writer.Write(TypeProcessor.ConvertType(iface) + " __j = null");
            }
            if (writebraces)
            {
                writer.Write(")");
            }
            return(writer.ToString());
        }
Ejemplo n.º 18
0
        public static void Go(OutputWriter writer, OperatorDeclarationSyntax method)
        {
            var methodSymbol     = (IMethodSymbol)TypeProcessor.GetDeclaredSymbol(method);
            var actualMethodName = OverloadResolver.MethodName(methodSymbol);

            writer.Write("\n");


            var returnType = "";

            if (method.ReturnType.ToString() == "void")
            {
                returnType = ("void ");
            }
            else
            {
                returnType = TypeProcessor.ConvertType(method.ReturnType) + " ";

                //                writer.Write(returnType);
            }

            var methodName = "";

            if (BinaryOperators.ContainsKey(actualMethodName))
            {
                methodName = "opBinary";
                var typeSymbolParam0 = TypeProcessor.GetTypeInfo(method.ParameterList.Parameters[0].Type);

                var typeSymbolParent = (methodSymbol.ContainingType);

                if (typeSymbolParam0.Type != typeSymbolParent)
                {
                    methodName += "Right";
                }
            }

            if (UnaryOperators.ContainsKey(actualMethodName))
            {
                methodName = "opUnary";
            }

            if (EqualsOperators.ContainsKey(actualMethodName))
            {
                methodName = "opEquals";
            }

            if (CmpOperators.ContainsKey(actualMethodName))
            {
                methodName = "opCmp";
            }

            if (AssignOperators.ContainsKey(actualMethodName))
            {
                methodName = "opAssign";
            }

            if (AssignOpOperators.ContainsKey(actualMethodName))
            {
                methodName = "opOpAssign"; // need to remove = from the name
            }
            var paramType = method.ParameterList.Parameters[0];

            if (method.ParameterList.Parameters.Count == 2)
            {
                if (methodName.EndsWith("Right"))
                {
                    paramType = method.ParameterList.Parameters[0];
                }
                else
                {
                    paramType = method.ParameterList.Parameters[1];
                }
            }

            var token = method.OperatorToken.Text;

            var methodBody = "";

            var temp = new TempWriter();

            foreach (var statement in method.Body.Statements)
            {
                Core.Write(temp, statement);
            }

            TriviaProcessor.ProcessTrivias(temp, method.Body.DescendantTrivia());

            methodBody = temp.ToString();


            if (methodName == "opOpAssign")
            {
                token = token.Substring(0, 1);
            }

            //We are going to have to rewrite this bit later ... for now all overloads are called directly

            /*    if (methodName == "opBinary")
             *  {
             *
             *      writer.WriteLine("public final " + returnType + " " + methodName +
             *      String.Format(
             *          " (string _op) ({0} other)\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this,other); \r\n\t}}\r\n\r\n",
             *          TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));
             *
             *      //Add Assignment operator if it doesn't exist
             *      if (!methodSymbol.ContainingType.GetMembers(AssignOpOperators.FirstOrDefault(k => k.Value == token + "=").Key).Any())
             *      {
             *          writer.WriteLine("public final " + returnType + " opOpAssign" +
             *      String.Format(
             *          " (string _op) ({0} other)\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this,other); \r\n\t}}\r\n\r\n",
             *          TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));
             *      }
             *  }
             *  else if (methodName == "opUnary")//TODO unary operators are mostly going to be direct methodCalls
             *  {
             *
             *      writer.WriteLine("public final " + returnType + " " + methodName +
             *          String.Format(
             *              " (string _op) ()\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this); \r\n\t}}\r\n\r\n",
             *              TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));
             *      //				writer.WriteLine ("public final ref " + returnType + " " + methodName +
             *      //					String.Format (
             *      //						" (string _op) ()\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\t{3}\r\n\t}}\r\n\r\n",
             *      //TypeProcessor.ConvertType (paramType.Type), actualMethodName, token, methodBody.Replace(method.ParameterList.Parameters[0].Identifier.ValueText,"this")));
             *  }
             *  else
             *  {
             *      writer.WriteLine("public final " + returnType + " " + methodName +
             *          String.Format(
             *              " (string _op) ({0} other)\r\n\tif(_op==\"{2}\")\r\n\t{{ \r\n\t\treturn {1}(this); \r\n\t}}\r\n\r\n",
             *              TypeProcessor.ConvertType(paramType.Type), actualMethodName, token));
             *  }*/

            var @params = method.ParameterList.Parameters;



            writer.WriteLine("public static " + returnType + " " + actualMethodName + WriteMethod.GetParameterListAsString(method.ParameterList.Parameters));



            writer.OpenBrace();
            if (method.Body != null)
            {
                foreach (var statement in method.Body.Statements)
                {
                    Core.Write(writer, statement);
                }

                TriviaProcessor.ProcessTrivias(writer, method.Body.DescendantTrivia());
            }

            writer.CloseBrace();
        }
Ejemplo n.º 19
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();
        }
Ejemplo n.º 20
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++;
            }
        }
Ejemplo n.º 21
0
        public static string WriteBlock(BlockSyntax block, bool writeBraces = true, int indent=0)
        {
            var writer = new TempWriter();
            writer.Indent = indent;
            if (writeBraces)
                writer.OpenBrace();

            //writer.Indent++;
            foreach (var statement in block.Statements)
            {
                // writer.WriteIndent();
                Write(writer, statement);
            }

            TriviaProcessor.ProcessTrivias(writer, block.DescendantTrivia());
            // writer.Indent--;

            if (writeBraces)
                writer.CloseBrace();

            return writer.ToString();
        }
Ejemplo n.º 22
0
        public static string GetParameterListAsString(SeparatedSyntaxList<ParameterSyntax> parameters,  bool includeTypes = true, ITypeSymbol iface=null, bool writebraces = true, ITypeSymbol genericClass = null)
        {
           
            var writer = new TempWriter(); // Temp Writer
            if(writebraces)
            writer.Write("(");
            var firstParam = true;
                foreach (var parameter in parameters)
            {
                var refKeyword = "";

                if (parameter.Modifiers.Any(SyntaxKind.RefKeyword))
                    refKeyword = " ref ";

                if (parameter.Modifiers.Any(SyntaxKind.OutKeyword))
                    refKeyword = " out ";

                if (parameter.Modifiers.Any(SyntaxKind.InKeyword))
                    refKeyword = " in ";

                bool isRef = parameter.Modifiers.Any(SyntaxKind.OutKeyword) ||
                             parameter.Modifiers.Any(SyntaxKind.RefKeyword);
                    // || parameter.Modifiers.Any (SyntaxKind.InKeyword);
                if (firstParam)
                    firstParam = false;
                else
                    writer.Write(", ");

                var isParams = parameter.Modifiers.Any(SyntaxKind.ParamsKeyword);

                //if (!isParams)
                {
                    var s = refKeyword + TypeProcessor.ConvertType(parameter.Type) + " ";
                    if (includeTypes)
                        writer.Write(s);
                }
               /* else //Framework depends too much on managed arrays even for params
                {
                    var type = (TypeProcessor.GetTypeInfo(parameter.Type).Type ?? TypeProcessor.GetTypeInfo(parameter.Type).ConvertedType) as IArrayTypeSymbol;
                    var s = refKeyword + TypeProcessor.ConvertType(type.ElementType) + "[]";

                    if (includeTypes)
                        writer.Write(s);

                }*/

                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Identifier.Text));
                if (parameter.Default == null)
                    continue;
                writer.Write(" = ");
                Core.Write(writer, parameter.Default.Value);
            }

            if (genericClass!=null)
            {

                writer.Write(TypeProcessor.ConvertType(genericClass) + " __obj");

                if (firstParam)
                    firstParam = false;
                else
                    writer.Write(", ");
            }
            else
            if (iface != null)
            {
                if (firstParam)
                    firstParam = false;
                else
                    writer.Write(", ");
               
                writer.Write(TypeProcessor.ConvertType(iface) + " __j = null");
            }
            if (writebraces)
                writer.Write(")");
            return writer.ToString();
        }
Ejemplo n.º 23
0
        public static void Go(OutputWriter writer, ForStatementSyntax forStatement)
        {
            //   writer.WriteLine(); // Beautify the code ...

            var tempWriter = new TempWriter();
            tempWriter.Indent = writer.Indent;

            var initializers = forStatement.Initializers;
            var initCount = initializers.Count + (forStatement.Declaration!=null?forStatement.Declaration.Variables.Count :0);
            if (initCount > 1)
            {
                tempWriter.WriteLine("//For loop");
                tempWriter.OpenBrace();
                foreach (var init in initializers)
                {
                    tempWriter.WriteLine(Core.WriteString(init, false, tempWriter.Indent) + ";");
                }

                if (forStatement.Declaration != null)
                {
                    var variables = forStatement.Declaration.Variables;
                    foreach (var variable in variables)
                    {
                        var vardec = (TypeProcessor.ConvertType(forStatement.Declaration.Type) + " ");
                        vardec +=(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));

                        if (variable.Initializer != null)
                        {
                            vardec+=(" = ");
                            vardec += Core.WriteString(variable.Initializer.Value,false,tempWriter.Indent);
                        }

                   
                        tempWriter.WriteLine(vardec + ";");

                    }
                }
               
            }
           
            tempWriter.Write("\r\n");
            tempWriter.WriteIndent();
            tempWriter.Write("for (");

            if (initCount == 1)
            {
                foreach (var init in initializers)
                {
                    Core.Write(tempWriter, init);
                    if (init != initializers.Last())
                        tempWriter.Write(",");
                }

                if (forStatement.Declaration != null)
                {
                    var variables = forStatement.Declaration.Variables;
                    foreach (var variable in variables)
                    {
                        //                    writer.WriteIndent();
                        tempWriter.Write(TypeProcessor.ConvertType(forStatement.Declaration.Type) + " ");
                        tempWriter.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));

                        if (variable.Initializer != null)
                        {
                            tempWriter.Write(" = ");
                            Core.Write(tempWriter, variable.Initializer.Value);
                        }

                        if (variable != variables.LastOrDefault())
                            tempWriter.Write(",");
                    }
                }
            }
            

            tempWriter.Write(";");

            if (forStatement.Condition == null)
                tempWriter.Write("true");
            else
                Core.Write(tempWriter, forStatement.Condition);

            tempWriter.Write(";");

            foreach (var iterator in forStatement.Incrementors)
            {
                Core.Write(tempWriter, iterator);

                if (iterator != forStatement.Incrementors.LastOrDefault())
                    tempWriter.Write(",");
            }

            tempWriter.Write(")");

            writer.WriteLine(tempWriter.ToString());
            writer.OpenBrace();
            Core.WriteStatementAsBlock(writer, forStatement.Statement, false);
            writer.CloseBrace();

            if (initCount > 1)
            {
                writer.CloseBrace();
                writer.WriteLine("//End of for loop");
            }
            //  writer.WriteLine(); // Beautify the code ...
        }
        public static void Go(OutputWriter writer, string methodName, IMethodSymbol methodSymbol,
            AttributeSyntax pinvokeAttributes)
        {
            //Do Pinvoke stuff
            //PInvokeFunction < int (int, double)> foo(library, "foo");
            //int i = foo(42, 2.0);
           
//			var methodParams = methodSymbol.Parameters.Any () ? methodSymbol.Parameters.Select (h => ConvertPInvokeType (h.Type)).Aggregate ((k, y) => (k) + " ," + y) : "";
            var returnString = ConvertPInvokeType(methodSymbol.ReturnType);

            if (pinvokeAttributes != null)
            {
                var attributeArgumentSyntax = pinvokeAttributes.ArgumentList.Arguments.FirstOrDefault(k => k.Expression != null);
                string dllImport = attributeArgumentSyntax.ToFullString();
//                AttributeSyntax import =
//                    Context.Instance.DllImports.FirstOrDefault(
//                        d =>
//                            d.ArgumentList.Arguments.FirstOrDefault(
//                                k =>
//                                    k.Expression != null &&
//                                    k.Expression.ToString() ==
//                                    pinvokeAttributes.ArgumentList.Arguments.FirstOrDefault(g => g.Expression != null)
//                                        .Expression.ToString()) != null);
//                if (import != null)
//                    dllImportId = Context.Instance.DllImports.IndexOf(import);
//
//                if (dllImportId == -1)
//                {
//                    Context.Instance.DllImports.Add(pinvokeAttributes);
//                    dllImportId = Context.Instance.DllImports.IndexOf(pinvokeAttributes);
//                }

                var functionCall = String.Format("extern (C) {0} function ({1})", returnString,
                    GetParameterList(methodSymbol.Parameters));
                writer.WriteLine("alias " + functionCall + " " + methodName + "_func_alias;");
                var convertedParameters = ConvertParameters(methodSymbol.Parameters);

                if (attributeArgumentSyntax.Expression is IdentifierNameSyntax)
                {
                    writer.WriteLine(
                        String.Format("auto {1} = cast({2}) __LoadLibraryFunc(__DllImportMap[{0}.text], \"{1}\");",
                            dllImport, methodName, methodName + "_func_alias"));
                }
                else
                {
                    writer.WriteLine(
                       String.Format("auto {1} = cast({2}) __LoadLibraryFunc(__DllImportMap[{0}], \"{1}\");",
                           dllImport, methodName, methodName + "_func_alias"));
                }

                writer.WriteLine(String.Format((returnString != "void" ? "return " : "") + "{0}({1});", methodName,
                    convertedParameters.Count > 0
                        ? convertedParameters.Select(h => h).Aggregate((k, y) => (k) + " ," + y)
                        : ""));


                if (dllImport != null && !Context.Instance.DllImports.Contains(dllImport))
                {
                             
                    var staticWriter = new TempWriter();

                    if (attributeArgumentSyntax.Expression is IdentifierNameSyntax)
                        staticWriter.WriteLine("__SetupDllImport({0}.text);", dllImport);
                    else
                        staticWriter.WriteLine("__SetupDllImport({0});", dllImport);

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

                    Context.Instance.DllImports.Add(dllImport);
                }

            }
            else
            {
               
                var convertedParameters = ConvertParameters(methodSymbol.Parameters);
               writer.WriteLine("//Extern (Internal) Method Call");
                var methodInternalName = TypeProcessor.ConvertType(methodSymbol.ContainingType,false).Replace(".Namespace.","_").Replace(".","_")+ "_" + methodName;

                writer.WriteLine(String.Format((returnString != "void" ? "return " : "") + "{0}({1});", methodInternalName,
                    convertedParameters.Count > 0
                        ? convertedParameters.Select(h => h).Aggregate((k, y) => (k) + " ," + y)
                        : ""));
            }
        }
Ejemplo n.º 25
0
        //TODO should enum be light class of static members ? or just a plain enum ? (using plain enum for now)
        public static void Go(OutputWriter writer, IEnumerable <EnumMemberDeclarationSyntax> allChildren)
        {
            //            writer.IsInterface = true;
            writer.Write("struct ");
            writer.Write(WriteType.TypeName(Context.Instance.Type, false) + "// Enum");

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

            //TODO: Find a better fix for this, casting integers to e.g. enum of ubyte gives lots of issues
            // writer.Write(":" + TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType));
            writer.Write("\r\n");



            writer.OpenBrace();

            writer.WriteLine("public " + TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType) + " __Value;");
            writer.WriteLine("alias __Value this;");

            writer.WriteLine("public enum __IsEnum = true; // Identifies struct as enum");

            string flagsvalue = "false";

            if (Context.Instance.Type.GetAttributes().Any(k => k.AttributeClass != null && k.AttributeClass.Name == "FlagsAttribute"))
            {
                flagsvalue = "true";
            }

            writer.WriteLine("public enum __HasFlags = {0}; // Identifies struct as enum", flagsvalue);



            writer.WriteLine(string.Format("public this({0} value)", TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType)));
            writer.OpenBrace();
            writer.WriteLine("__Value = value;");
            writer.CloseBrace();


            writer.WriteLine();
            writer.WriteLine("public Type GetType()");
            writer.OpenBrace();
            writer.WriteLine("return __TypeOf!(typeof(this));");
            writer.CloseBrace();


            long lastEnumValue = 0;
            var  children      = allChildren.ToArray();
            var  values        =
                children.Select(
                    o => new { Syntax = o, Value = o.EqualsValue != null ? o.EqualsValue.Value : null })
                .ToList();

            var actualValues = new List <string>();

            for (int index = 0; index < values.Count; index++)
            {
                var value = values[index];
                var text  = "";

                text = "public enum " + WriteType.TypeName(Context.Instance.Type, false) + " "
                       + WriteIdentifierName.TransformIdentifier(value.Syntax.Identifier.Text);
                var expressionSyntax = value.Value;
                var expression       = expressionSyntax;

                //lets try parsing the value so we can evaluate it
                if (expression != null)
                {
                    var type = TypeProcessor.GetTypeInfo(expression);

                    var tempw = new TempWriter();

                    Core.Write(tempw, expression);

                    var temp = tempw.ToString();

                    if (type.Type != Context.Instance.Type.EnumUnderlyingType)
                    {
                        //TODO: only int enums are supported properly ... should we change them to static structs with constants ?
                        //						temp = "cast(" + TypeProcessor.ConvertType (Context.Instance.Type.EnumUnderlyingType) + ")" + temp;
                        temp = "cast(" + TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType) + ")" +
                               temp;
                    }

                    actualValues.Add(temp);
                    text += " = " + temp;
                    tempw.Dispose();
                    ;
                }
                else
                {
                    if (expressionSyntax != null && expressionSyntax.ToFullString().Trim() != "")
                    {
                        text += expressionSyntax;
                    }
                    else
                    {
                        if (index > 0)
                        {
                            var temp =
                                WriteIdentifierName.TransformIdentifier(values[index - 1].Syntax.Identifier.Text) + " + 1";
                            text += " = " +
                                    temp;
                            actualValues.Add(temp);
                        }
                        else
                        {
                            text += " = 0";
                            actualValues.Add("0");
                        }
                    }
                }

                writer.WriteLine(text + ";");
            }

            //TODO: Need Fix
            var list = new List <string>();

            for (int index = 0; index < values.Count; index++)
            {
                var item = actualValues[index];
                for (int i = 0; i < values.Count; i++)
                {
                    var value = values[i];
                    if ((value.Value is LiteralExpressionSyntax) || value.Value == null)
                    {
                        item =
                            item.Replace(
                                TypeProcessor.ConvertType(Context.Instance.Type, true, false, false) + "." +
                                value.Syntax.Identifier.Text, actualValues[i]);
                        actualValues[i] = item;
                    }
                }
                list.Add(item);
            }

            writer.WriteLine("public enum __values =[" + list.Aggregate((a, b) => a + "," + b) + "];");
            writer.WriteLine("public enum __names =[" + values.Select(j => "\"" + WriteIdentifierName.TransformIdentifier(j.Syntax.Identifier.Text) + "\"").Aggregate((a, b) => a + "," + b) + "];");


            writer.WriteLine();
            var typeName = WriteType.TypeName(Context.Instance.Type, false);

            var baseString = "";


            writer.WriteLine();

            writer.WriteLine("{0} opBinary(string op)({0} rhs)", typeName);
            writer.OpenBrace();
            writer.WriteLine("return mixin(\"{0}(__Value \"~op~\" rhs.__Value)\");", typeName);
            writer.CloseBrace();

            writer.WriteLine("bool opEquals(const {0} a)", typeName);
            writer.OpenBrace();
            writer.WriteLine("return a.__Value == this.__Value;", typeName);
            writer.CloseBrace();

            writer.WriteLine("bool opEquals(const {0} a)", TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType));
            writer.OpenBrace();
            writer.WriteLine("return a == this.__Value;", typeName);
            writer.CloseBrace();


            writer.WriteLine("public string toString()");
            writer.OpenBrace();

            /*  foreach (var membername in values)
             * {
             *    var name = WriteIdentifierName.TransformIdentifier(membername.Syntax.Identifier.Text);
             *    writer.WriteLine("if (this == {0}.__Value)", name);
             *    writer.OpenBrace();
             *    writer.WriteLine("return \"{0}\";", name);
             *    writer.CloseBrace();
             * }
             * writer.WriteLine("return std.conv.to!string(BOX(this.__Value).ToString().Text);");*/
            writer.WriteLine("return __ConvertEnumToString(this);");

            writer.CloseBrace();

            //Not needed for enum ... all enum should have a ToString function ...
            //            writer.WriteLine("public static class __Boxed_" + " " +
            //                                 //(genericArgs.Any() ? ("( " + (string.Join(" , ", genericArgs.Select(o => o)) + " )")) : "") +//Internal boxed should not be generic
            //                                 ": Boxed!(" + typeName + ")" + baseString);
            //
            //            writer.OpenBrace();
            //
            //
            //
            //            writer.WriteLine("import std.traits;");
            //
            //            var members = new List<ISymbol>();
            //
            //
            //
            //            //  foreach (var baseType in bases.Where(o => o.TypeKind == TypeKind.Interface))
            //            //{
            //
            //            var ifacemembers = members.DistinctBy(k => k);//Utility.GetAllMembers(Context.Instance.Type);
            //
            //            foreach (var member in ifacemembers)
            //            {
            //                var ifacemethod =
            //                    Context.Instance.Type.FindImplementationForInterfaceMember(member)
            //                        .DeclaringSyntaxReferences.First()
            //                        .GetSyntax();
            //
            //                var syntax = ifacemethod as MethodDeclarationSyntax;
            //                if (syntax != null)
            //                    WriteMethod.WriteIt(writer, syntax);
            //
            //                var property = ifacemethod as PropertyDeclarationSyntax;
            //                if (property != null)
            //                    WriteProperty.Go(writer, property, true);
            //
            //            }
            //            //}
            //
            //            //This is required to be able to create an instance at runtime / reflection
            //            //					this()
            //            //					{
            //            //						super(SimpleStruct.init);
            //            //					}
            //
            //            writer.WriteLine();
            //            writer.WriteLine("this()");
            //            writer.OpenBrace();
            //            writer.WriteLine("super(__TypeNew!({0})());", typeName);
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("public override Type GetType()");
            //            writer.OpenBrace();
            //            writer.WriteLine("return __TypeOf!(typeof(__Value));");
            //            writer.CloseBrace();
            //
            //
            //            if (Context.Instance.Type.GetMembers("ToString").Any()) // Use better matching ?
            //            {
            //                //					writer.WriteLine ();
            //                writer.WriteLine("override String ToString()");
            //                writer.OpenBrace();
            //                writer.WriteLine("return Value.ToString();");
            //                writer.CloseBrace();
            //            }
            //
            //            writer.WriteLine();
            //            writer.WriteLine("this(ref " + typeName + " value)");
            //            writer.OpenBrace();
            //            writer.WriteLine("super(value);");
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("U opCast(U)()");
            //            writer.WriteLine("if(is(U:{0}))", typeName);
            //            writer.OpenBrace();
            //            writer.WriteLine("return Value;");
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("U opCast(U)()");
            //            writer.WriteLine("if(!is(U:{0}))", typeName);
            //            writer.OpenBrace();
            //            writer.WriteLine("return this;");
            //            writer.CloseBrace();
            //
            //            writer.WriteLine();
            //            writer.WriteLine("auto opDispatch(string op, Args...)(Args args)");
            //            writer.OpenBrace();
            //            writer.WriteLine("enum name = op;");
            //            writer.WriteLine("return __traits(getMember, Value, name)(args);");
            //            writer.CloseBrace();

            //            writer.WriteLine();
            //            writer.WriteLine("public override Type GetType()");
            //            writer.OpenBrace();
            //            writer.WriteLine("return __Value.GetType();");
            //            writer.CloseBrace();


            //            writer.CloseBrace();

            writer.CloseBrace();
            //            writer.Write(";");
        }
Ejemplo n.º 26
0
        public static string GetParameterListAsString(SeparatedSyntaxList <ParameterSyntax> parameters, bool includeTypes = true, ITypeSymbol iface = null, bool writebraces = true, ITypeSymbol genericClass = null)
        {
            var writer = new TempWriter(); // Temp Writer

            if (writebraces)
            {
                writer.Write("(");
            }
            var firstParam = true;

            foreach (var parameter in parameters)
            {
                var refKeyword = "";

                if (parameter.Modifiers.Any(SyntaxKind.RefKeyword))
                {
                    refKeyword = " ref ";
                }

                if (parameter.Modifiers.Any(SyntaxKind.OutKeyword))
                {
                    refKeyword = " out ";
                }

                if (parameter.Modifiers.Any(SyntaxKind.InKeyword))
                {
                    refKeyword = " in ";
                }

                bool isRef = parameter.Modifiers.Any(SyntaxKind.OutKeyword) ||
                             parameter.Modifiers.Any(SyntaxKind.RefKeyword);
                // || parameter.Modifiers.Any (SyntaxKind.InKeyword);
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    writer.Write(", ");
                }

                var isParams = parameter.Modifiers.Any(SyntaxKind.ParamsKeyword);

                //if (!isParams)
                {
                    var s = refKeyword + TypeProcessor.ConvertType(parameter.Type) + " ";
                    if (includeTypes)
                    {
                        writer.Write(s);
                    }
                }

                /* else //Framework depends too much on managed arrays even for params
                 * {
                 *   var type = (TypeProcessor.GetTypeInfo(parameter.Type).Type ?? TypeProcessor.GetTypeInfo(parameter.Type).ConvertedType) as IArrayTypeSymbol;
                 *   var s = refKeyword + TypeProcessor.ConvertType(type.ElementType) + "[]";
                 *
                 *   if (includeTypes)
                 *       writer.Write(s);
                 *
                 * }*/

                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Identifier.Text));
                if (parameter.Default == null)
                {
                    continue;
                }
                writer.Write(" = ");
                Core.Write(writer, parameter.Default.Value);
            }

            if (genericClass != null)
            {
                writer.Write(TypeProcessor.ConvertType(genericClass) + " __obj");

                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    writer.Write(", ");
                }
            }
            else
            if (iface != null)
            {
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    writer.Write(", ");
                }

                writer.Write(TypeProcessor.ConvertType(iface) + " __j = null");
            }
            if (writebraces)
            {
                writer.Write(")");
            }
            return(writer.ToString());
        }
Ejemplo n.º 27
0
        public static void Go(OutputWriter writer, string methodName, IMethodSymbol methodSymbol,
                              AttributeSyntax pinvokeAttributes)
        {
            //Do Pinvoke stuff
            //PInvokeFunction < int (int, double)> foo(library, "foo");
            //int i = foo(42, 2.0);

//			var methodParams = methodSymbol.Parameters.Any () ? methodSymbol.Parameters.Select (h => ConvertPInvokeType (h.Type)).Aggregate ((k, y) => (k) + " ," + y) : "";
            var returnString = ConvertPInvokeType(methodSymbol.ReturnType);

            if (pinvokeAttributes != null)
            {
                var    attributeArgumentSyntax = pinvokeAttributes.ArgumentList.Arguments.FirstOrDefault(k => k.Expression != null);
                string dllImport = attributeArgumentSyntax.ToFullString();
//                AttributeSyntax import =
//                    Context.Instance.DllImports.FirstOrDefault(
//                        d =>
//                            d.ArgumentList.Arguments.FirstOrDefault(
//                                k =>
//                                    k.Expression != null &&
//                                    k.Expression.ToString() ==
//                                    pinvokeAttributes.ArgumentList.Arguments.FirstOrDefault(g => g.Expression != null)
//                                        .Expression.ToString()) != null);
//                if (import != null)
//                    dllImportId = Context.Instance.DllImports.IndexOf(import);
//
//                if (dllImportId == -1)
//                {
//                    Context.Instance.DllImports.Add(pinvokeAttributes);
//                    dllImportId = Context.Instance.DllImports.IndexOf(pinvokeAttributes);
//                }

                var functionCall = String.Format("extern (C) {0} function ({1})", returnString,
                                                 GetParameterList(methodSymbol.Parameters));
                writer.WriteLine("alias " + functionCall + " " + methodName + "_func_alias;");
                var convertedParameters = ConvertParameters(methodSymbol.Parameters);

                if (attributeArgumentSyntax.Expression is IdentifierNameSyntax)
                {
                    writer.WriteLine(
                        String.Format("auto {1} = cast({2}) __LoadLibraryFunc(__DllImportMap[{0}.text], \"{1}\");",
                                      dllImport, methodName, methodName + "_func_alias"));
                }
                else
                {
                    writer.WriteLine(
                        String.Format("auto {1} = cast({2}) __LoadLibraryFunc(__DllImportMap[{0}], \"{1}\");",
                                      dllImport, methodName, methodName + "_func_alias"));
                }

                writer.WriteLine(String.Format((returnString != "void" ? "return " : "") + "{0}({1});", methodName,
                                               convertedParameters.Count > 0
                        ? convertedParameters.Select(h => h).Aggregate((k, y) => (k) + " ," + y)
                        : ""));


                if (dllImport != null && !Context.Instance.DllImports.Contains(dllImport))
                {
                    var staticWriter = new TempWriter();

                    if (attributeArgumentSyntax.Expression is IdentifierNameSyntax)
                    {
                        staticWriter.WriteLine("__SetupDllImport({0}.text);", dllImport);
                    }
                    else
                    {
                        staticWriter.WriteLine("__SetupDllImport({0});", dllImport);
                    }

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

                    Context.Instance.DllImports.Add(dllImport);
                }
            }
            else
            {
                var convertedParameters = ConvertParameters(methodSymbol.Parameters);
                writer.WriteLine("//Extern (Internal) Method Call");
                var methodInternalName = TypeProcessor.ConvertType(methodSymbol.ContainingType, false).Replace(".Namespace.", "_").Replace(".", "_") + "_" + methodName;

                writer.WriteLine(String.Format((returnString != "void" ? "return " : "") + "{0}({1});", methodInternalName,
                                               convertedParameters.Count > 0
                        ? convertedParameters.Select(h => h).Aggregate((k, y) => (k) + " ," + y)
                        : ""));
            }
        }