public static void Go(OutputWriter writer, InvocationExpressionSyntax invocationExpression)
        {
            var symbolInfo       = TypeProcessor.GetSymbolInfo(invocationExpression);
            var expressionSymbol = TypeProcessor.GetSymbolInfo(invocationExpression.Expression);

            var symbol = symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(); // Resolution error

            if (symbol == null)
            {
                writer.WriteLine("/*" + invocationExpression.ToFullString() + "  //SharpNative Failed To Get Symbol */");
            }
            var methodSymbol = symbol.OriginalDefinition.As <IMethodSymbol>().UnReduce();

            var memberReferenceExpressionOpt = invocationExpression.Expression as MemberAccessExpressionSyntax;
            var firstParameter = true;

            var extensionNamespace = methodSymbol.IsExtensionMethod
                ? methodSymbol.ContainingNamespace.FullNameWithDot() + methodSymbol.ContainingType.FullName()
                : null; //null means it's not an extension method, non-null means it is
            string           methodName;
            string           typeParameters = null;
            ExpressionSyntax subExpressionOpt;

            if (expressionSymbol.Symbol is IEventSymbol)
            {
                methodName = "Invoke";
            }
            else if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
            {
                methodName = null;
            }
            else
            {
                methodName = OverloadResolver.MethodName(methodSymbol);
            }

            if (methodSymbol.ContainingType.TypeKind == TypeKind.Interface ||
                Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(methodSymbol),
                       methodSymbol))
            {
                /*    methodName =
                 *  Regex.Replace(TypeProcessor.ConvertType(methodSymbol.ContainingType.OriginalDefinition)
                 *          .RemoveFromStartOfString(methodSymbol.ContainingNamespace + ".Namespace.") + "_" +
                 *      methodName,
                 *      @" ?!\(.*?\)", string.Empty);*/
                if (methodSymbol.ContainingType.ContainingType != null)
                {
                    methodName = methodName.RemoveFromStartOfString(methodSymbol.ContainingType.ContainingType.Name + ".");
                }
            }

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

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

            //                    if (interfaceMethod == null)
            //                    {
            //                        //TODO: fix this for virtual method test 7, seems roslyn cannot deal with virtual
            //                        // overrides of interface methods ... so i'll provide a kludge
            //                        if (!method.Modifiers.Any(SyntaxKind.NewKeyword))
            //                            interfaceMethod = interfaceMethods.FirstOrDefault(k => CompareMethods(k as IMethodSymbol, methodSymbol));
            //                    }

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

            var containingType = interfaceMethod == null ? methodSymbol.ContainingType : interfaceMethod.ContainingType;

            bool isVirtualGeneric = methodSymbol.IsGenericMethod &&
                                    (methodSymbol.IsVirtual ||
                                     methodSymbol.ContainingType.TypeKind == TypeKind.Interface) &&
                                    !containingType.IsAssignableFrom(Context.Instance.Type);   // !(invocationExpression.Expression is BaseExpressionSyntax);



            if (isVirtualGeneric)
            {
                methodName = TypeProcessor.ConvertType(containingType, false, false, false).Replace(".", "_") + "_" + methodName;
            }

            if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
            {
                subExpressionOpt = invocationExpression.Expression;
            }
            else if (memberReferenceExpressionOpt != null)
            {
                if (memberReferenceExpressionOpt.Expression is PredefinedTypeSyntax)
                {
                    subExpressionOpt = null;
                }
                else
                {
                    subExpressionOpt = memberReferenceExpressionOpt.Expression;
                }
            }
            else
            {
                subExpressionOpt = null;
            }

            //When the code specifically names generic arguments, include them in the method name ... dmd needs help with inference, so we give it the types anyway
            if (methodSymbol.IsGenericMethod)
            {
                //return TryConvertType(named) + (named.TypeKind == TypeKind.Struct && o.ConstraintTypes.Any(k => k.TypeKind == //TypeKind.Interface) ? ".__Boxed_" : "");

                var named = ((IMethodSymbol)symbol);
                typeParameters = "!(" +
                                 named.TypeArguments.Select(o => TypeProcessor.GetGenericParameterType(named.TypeParameters[named.TypeArguments.IndexOf(o)], o)).Aggregate((a, b) => a + ", " + b)
                                 + ")";

//                typeParameters = "!( " +
//                                 string.Join(", ",
//                                     ((IMethodSymbol) symbol).TypeArguments.Select(r => TypeProcessor.ConvertType(r)  )) +
//                                 " )";
            }

            //Determine if it's an extension method called in a non-extension way.  In this case, just pretend it's not an extension method
            if (extensionNamespace != null && subExpressionOpt != null &&
                TypeProcessor.GetTypeInfo(subExpressionOpt).ConvertedType.ToString() ==
                methodSymbol.ContainingNamespace.FullName() + "." + methodSymbol.ContainingType.FullName())
            {
                extensionNamespace = null;
            }

            var memberType = memberReferenceExpressionOpt == null
                ? null
                : TypeProcessor.GetTypeInfo(memberReferenceExpressionOpt.Expression).Type;
            var isNullableEnum = memberType != null &&
                                 (memberType.Name == "Nullable" && memberType.ContainingNamespace.FullName() == "System") &&
                                 memberType.As <INamedTypeSymbol>().TypeArguments.Single().TypeKind == TypeKind.Enum;
            //          if (isNullableEnum && methodSymbol.Name == "ToString")
            //          {
            //              extensionNamespace = null; //override Translations.xml for nullable enums. We want them to convert to the enum's ToString method
            //              methodName = "toString";
            //          }

            //Invocation on basics should come from boxing the basic then calling on the boxed type, unless static
            var directInvocationOnBasics = methodSymbol.ContainingType.IsBasicType() && methodSymbol.IsStatic;
            //&& methodSymbol.ContainingType!=Context.Instance.Type; //If we are currently working on a basic type e.g. in corlib, don't alter the code

            //Extension methods in Dlang are straightforward, although this could lead to clashes without qualification

            string instanceName = null;

            if (extensionNamespace != null || directInvocationOnBasics)
            {
                if (extensionNamespace == null)
                {
                    extensionNamespace = TypeProcessor.ConvertType(methodSymbol.ContainingType, true, false);
                    // methodSymbol.ContainingNamespace.FullName() + "." + methodSymbol.ContainingType.Name;
                    //memberType.ContainingNamespace.FullName() +"."+ memberType.Name;
                }

                if (!isVirtualGeneric)
                {
                    writer.Write(extensionNamespace);

                    if (methodName != null)
                    {
                        methodName = WriteIdentifierName.TransformIdentifier(methodName);
                        //                    if (symbolInfo.Symbol.ContainingType != Context.Instance.Type)
                        writer.Write(".");
                        writer.Write(methodName);
                    }
                }
                else
                {
                    writer.Write(methodName);
                }

                WriteTypeParameters(writer, typeParameters, invocationExpression);

                writer.Write("(");

                if (subExpressionOpt != null)
                {
                    firstParameter = false;
                    Core.Write(writer, subExpressionOpt);
                }
            }
            else
            {
                if (memberReferenceExpressionOpt != null)
                {
                }

                if (subExpressionOpt != null)
                {
                    if (!isVirtualGeneric)
                    {
                        WriteMemberAccessExpression.WriteMember(writer, subExpressionOpt);

                        //                    if (!(subExpressionOpt is BaseExpressionSyntax))
                        //                    {
                        //                        if (methodName != null && methodSymbol.IsStatic)
                        //                            writer.Write(".");
                        //                        else
                        //                      {
                        if (methodSymbol.MethodKind != MethodKind.DelegateInvoke)
                        {
                            writer.Write(".");
                        }
                    }
                    else
                    {
                        instanceName = WriteMemberAccessExpression.WriteMemberToString(subExpressionOpt);
                    }
                    //                        }
                    //                    }
                    //                  writer.Write(".");
                }
                else if (methodSymbol.IsStatic && extensionNamespace == null)
                {
                    if (methodSymbol.ContainingType != Context.Instance.Type)
                    {
                        var str = TypeProcessor.ConvertType(methodSymbol.ContainingType);
                        if (str == "Array_T")
                        {
                            // Array is the only special case, otherwise generics have to be specialized to access static members
                            str = "Array";
                        }

                        writer.Write(str);
                        //                    writer.Write(methodSymbol.ContainingNamespace.FullNameWithDot());
                        //                    writer.Write(WriteType.TypeName(methodSymbol.ContainingType));
                        writer.Write(".");
                    }
                }

                if (methodSymbol.MethodKind != MethodKind.DelegateInvoke)
                {
                    var declaringSyntaxReferences =
                        methodSymbol.DeclaringSyntaxReferences.Select(j => j.GetSyntax())
                        .OfType <MethodDeclarationSyntax>();
                    var methodDeclarationSyntaxs = declaringSyntaxReferences as MethodDeclarationSyntax[] ?? declaringSyntaxReferences.ToArray();
                    var any = methodDeclarationSyntaxs.Any();
                    if (any &&
                        methodDeclarationSyntaxs.FirstOrDefault()
                        .As <MethodDeclarationSyntax>()
                        .Modifiers.Any(SyntaxKind.NewKeyword))
                    {
                        //TODO: this means that new is not supported on external libraries
                        //                  //why doesnt roslyn give me this information ?
                        //methodName += "_"; //Not needed anymore :)
                    }

                    if (any &&
                        methodDeclarationSyntaxs.FirstOrDefault()
                        .As <MethodDeclarationSyntax>()
                        .Modifiers.Any(SyntaxKind.NewKeyword))
                    {
//                        if (symbolInfo.Symbol.ContainingType != Context.Instance.Type)
                        writer.Write(WriteIdentifierName.TransformIdentifier(methodSymbol.ContainingType.Name, methodSymbol.ContainingType) + ".");
                    }



                    methodName = WriteIdentifierName.TransformIdentifier(methodName);

                    writer.Write(methodName);
                }
                WriteTypeParameters(writer, typeParameters, invocationExpression);
                writer.Write("(");
            }

            bool inParams         = false;
            bool foundParamsArray = false;

            var arguments = invocationExpression.ArgumentList.Arguments;

            ITypeSymbol typeSymbol = null;

            bool isOverloaded = methodSymbol.ContainingType.GetMembers(methodSymbol.Name).OfType <IMethodSymbol>().Any(j => j.TypeParameters == methodSymbol.TypeParameters && ParameterMatchesWithRefOutIn(methodSymbol, j));

            WriteArguments(writer, invocationExpression, arguments, firstParameter, inParams, methodSymbol, foundParamsArray, typeSymbol, isOverloaded, symbol, instanceName);
        }
Exemple #2
0
        public static void Go(OutputWriter writer, EventDeclarationSyntax property)
        {
            writer.WriteLine("\r\n");
            var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                var IsStatic = "";

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

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

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

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

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

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

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

                    staticWriter.Write(name);

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

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

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

                    staticWriter.Write(name);

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

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.InstanceInits.Add(staticWriter.ToString());
                }
//						if (CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
//						{
//
//
//							staticWriter.Write ("new " + typeStringNoPtr + " ([");
//
//
//						}
//						Core.Write (staticWriter, initializerOpt.Value);
//						if (CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression)
//						{
//
//
//							staticWriter.Write ("])");
//						}
            }
        }
Exemple #3
0
        public static void Go(OutputWriter writer, PropertyDeclarationSyntax property, bool isProxy = false)
        {
            writer.WriteLine();
            //var rEf = "";//" ref ";// ref should be used based on analysis, is the return type a single var or not
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                var acccessmodifiers = "";

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

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

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

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

                //TODO: look at final and other optimizations

                var IsStatic = "";

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

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

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

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

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

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

                if (setter != null && isProxy)
                {
                    writer.WriteLine(acccessmodifiers + " void " + name + "(" + typeString + " value) @property" +
                                     isOverride + " {  Value." + name + " = value;}");
                }
                else
                //Setter
                if (setter != null && setter.Body == null)
                {
                    if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface)
                    {
                        writer.WriteLine(acccessmodifiers + " void " + name + "(" + typeString + " value)" +
                                         isOverride + "" + " @property;");
                    }
                    else
                    {
                        writer.WriteLine(acccessmodifiers + " void " + name + "(" + typeString + " value) @property" +
                                         isOverride + " {" + fieldName + " = value;}");
                    }
                }
                else if (setter != null)
                {
                    writer.WriteIndent();
                    writer.Write(acccessmodifiers);
                    writeRegion(setter, false);
                }
            }
        }
Exemple #4
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++;
            }
        }
        public static void WriteAnonymousType(AnonymousObjectCreationExpressionSyntax syntax)
        {
            var type = TypeProcessor.GetTypeInfo(syntax).Type.As <INamedTypeSymbol>();

            Context.Instance.Type = type;

            TypeProcessor.ClearUsedTypes();

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

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

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

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

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

            //Ty

            var anonName = TypeName(type);

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

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

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

                writer.OpenBrace();

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

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

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

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

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

                writer.CloseBrace();

                writer.CloseBrace();
//                writer.Write("};");
//                writer.Write("}");
            }
        }
Exemple #6
0
        public static void Go(OutputWriter writer, ForEachStatementSyntax foreachStatement)
        {
            var info = new LoopInfo(foreachStatement);

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

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

//                writer.WriteIndent();

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

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

            var foreachIter = "__foreachIter" + foreachCount;

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

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

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

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

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

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

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

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

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

            //    writer.WriteCloseBrace();
//            }
//            else if (typeStr == "System.Collections.Generic.List<>"
//                //|| typeStr == "System.Collections.Generic.Dictionary<,>"
//                || typeStr == "System.Collections.Generic.Dictionary<,>.KeyCollection"
//                || typeStr == "System.Collections.Generic.Dictionary<,>.ValueCollection")
//            {
//                //It's faster to "while" over a list's iterator than to "for" through it
//                writer.WriteOpenBrace();
//                info.WritePreLoop(writer);
//
//                writer.WriteIndent();
//                writer.Write("val __foreachiterator = ");
//                Core.Write(writer, foreachStatement.Expression);
//                writer.Write(".iterator();\r\n");
//
//
//                writer.WriteLine("while (__foreachiterator.hasNext())");
//                writer.WriteOpenBrace();
//
//                writer.WriteIndent();
//                writer.Write("val ");
//                writer.Write(WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.ValueText));
//                writer.Write(" = __foreachiterator.next();\r\n");
//
//                info.WriteLoopOpening(writer);
//                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);
//                info.WriteLoopClosing(writer);
//                writer.WriteCloseBrace();
//
//                info.WritePostLoop(writer);
//                writer.WriteCloseBrace();
//            }
//            else
//            {
//
//                info.WritePreLoop(writer);
//                writer.WriteIndent();
//                writer.Write("for (");
//                writer.Write(WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.ValueText));
//                writer.Write(" = ");
//                Core.Write(writer, foreachStatement.Expression);
//                writer.Write(")\r\n");
//                writer.WriteOpenBrace();
//                info.WriteLoopOpening(writer);
//                Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false);
//                info.WriteLoopClosing(writer);
//                writer.WriteCloseBrace();
//                info.WritePostLoop(writer);
//            }
        }
Exemple #7
0
        private static void ProcessExpression(OutputWriter writer, SyntaxToken operatorToken, CSharpSyntaxNode rightExpression,
                                              CSharpSyntaxNode leftExpression)
        {
            TypeInfo leftExpressionType = TypeProcessor.GetTypeInfo(leftExpression ?? rightExpression);

            var rightExpressionType = TypeProcessor.GetTypeInfo(rightExpression);

            var boxLeft = leftExpressionType.Type != null && (leftExpressionType.Type != leftExpressionType.ConvertedType) &&
                          ((leftExpressionType.Type.IsValueType || leftExpressionType.Type.TypeKind == TypeKind.TypeParameter) &&
                           (leftExpressionType.ConvertedType.IsReferenceType));

            var boxRight = (rightExpressionType.ConvertedType != null &&
                            (rightExpressionType.Type != null &&
                             ((rightExpressionType.Type.IsValueType ||
                               rightExpressionType.Type.TypeKind == TypeKind.TypeParameter) &&
                              (rightExpressionType.ConvertedType.IsReferenceType))))
                           ||
                           (rightExpressionType.Type != null && rightExpressionType.Type.IsValueType &&
                            leftExpressionType.Type != null && leftExpressionType.Type.TypeKind == TypeKind.Error);
            //Fix for yield ... why does it give errortypes ?

            var unboxRight = rightExpressionType.ConvertedType != null &&
                             (rightExpressionType.Type != null && (rightExpressionType.Type.IsReferenceType &&
                                                                   (rightExpressionType.ConvertedType.IsValueType)));

            var rightnull = rightExpression != null && rightExpression.ToFullString().Trim() == "null";
            var leftnull  = leftExpression != null && leftExpression.ToFullString().Trim() == "null";

            var nullAssignment = (rightnull || leftnull);

            var val = WriteOperatorDeclaration.AllBinaryOperators.FirstOrDefault(k => k.Value == operatorToken.Text);

            //Matching Binary Operator Overload
            if (!String.IsNullOrEmpty(val.Value))
            {
                //Try Left
                IEnumerable <ISymbol> members = new List <ISymbol>();
                if (leftExpressionType.Type != null)
                {
                    members = leftExpressionType.Type.GetMembers(val.Key);
                }
                if (rightExpressionType.Type != null)
                {
                    members = members.
                              Union(rightExpressionType.Type.GetMembers(val.Key));
                }

                var leftExpressionString = Core.WriteString(leftExpression);
                if (members != null && members.Any())
                {
                    if (!(leftExpressionType.Type.IsPrimitive() && rightExpressionType.Type.IsPrimitive()))
                    {
                        var correctOverload =
                            members.OfType <IMethodSymbol>()
                            .FirstOrDefault(
                                u =>
                                u.Parameters[0].Type == leftExpressionType.Type &&
                                u.Parameters[1].Type == rightExpressionType.Type);

                        if (correctOverload != null)
                        {
                            var name =
                                WriteIdentifierName.TransformIdentifier(OverloadResolver.MethodName(correctOverload));
                            writer.Write(TypeProcessor.ConvertType(correctOverload.ContainingType) + "." + name +
                                         "(" +
                                         leftExpressionString + "," + Core.WriteString(rightExpression)
                                         + ")");
                            return;
                        }
                    }
                }
                else
                {
                    if (WriteOperatorDeclaration.AssignOpOperators.ContainsKey(val.Key))
                    {
                        var methodName =
                            WriteOperatorDeclaration.AllBinaryOperators.FirstOrDefault(
                                k => k.Value == val.Value.Substring(0, 1));
                        // emulate c# facility to use the lower op ...
                        //Try Left
                        members = null;
                        if (leftExpressionType.Type != null)
                        {
                            members = leftExpressionType.Type.GetMembers(methodName.Key);
                        }
                        if (rightExpressionType.Type != null)
                        {
                            members = members.
                                      Union(rightExpressionType.Type.GetMembers(methodName.Key));
                        }

                        if (members != null && members.Any())
                        {
                            if (!(leftExpressionType.Type.IsPrimitive() && rightExpressionType.Type.IsPrimitive()))
                            {
                                var correctOverload =
                                    members.OfType <IMethodSymbol>()
                                    .FirstOrDefault(
                                        u =>
                                        u.Parameters[0].Type == leftExpressionType.Type &&
                                        u.Parameters[1].Type == rightExpressionType.Type);

                                if (correctOverload != null)
                                {
                                    var name =
                                        WriteIdentifierName.TransformIdentifier(
                                            OverloadResolver.MethodName(correctOverload));
                                    writer.Write(leftExpressionString + " = " +
                                                 TypeProcessor.ConvertType(correctOverload.ContainingType) + "." +
                                                 name +
                                                 "(" +
                                                 leftExpressionString + "," + Core.WriteString(rightExpression)
                                                 + ")");
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            //Property calls will be fixed in a preprocessor step ... i.e. just call them
            if (nullAssignment)
            {
                if (rightnull)
                {
                    switch (operatorToken.CSharpKind())
                    {
                    case SyntaxKind.EqualsEqualsToken:
                        writer.Write("");
                        break;

                    case SyntaxKind.NotEqualsExpression:
                    case SyntaxKind.ExclamationEqualsToken:
                        writer.Write("!");
                        break;

                    default:
                        writer.Write(operatorToken.ToString());
                        break;
                    }


                    writer.Write("__IsNull(");
                    Core.Write(writer, leftExpression);
                    writer.Write(")");
                    return;
                }

                if (leftnull)
                {
                    //                    writer.Write("null");
                    //
                    //                    switch (operatorToken.CSharpKind())
                    //                    {
                    //                        case SyntaxKind.EqualsEqualsToken:
                    //                            writer.Write(" is ");
                    //                            break;
                    //                        case SyntaxKind.NotEqualsExpression:
                    //                        case SyntaxKind.ExclamationEqualsToken:
                    //                            writer.Write(" !is ");
                    //                            break;
                    //                        default:
                    //                            writer.Write(operatorToken.ToString());
                    //                            break;
                    //                    }
                    //
                    //                    Core.Write(writer, rightExpression);
                    //
                    //                    return;
                    switch (operatorToken.CSharpKind())
                    {
                    case SyntaxKind.EqualsEqualsToken:
                        writer.Write("");
                        break;

                    case SyntaxKind.NotEqualsExpression:
                    case SyntaxKind.ExclamationEqualsToken:
                        writer.Write("!");
                        break;

                    default:
                        writer.Write(operatorToken.ToString());
                        break;
                    }


                    writer.Write("__IsNull(");
                    Core.Write(writer, rightExpression);
                    writer.Write(")");
                    return;
                }
            }

            //Do we have an implicit converter, if so, use it
            if (leftExpressionType.Type != rightExpressionType.Type && rightExpressionType.Type != null)
            {
                bool useType = true;

                //We should start with exact converters and then move to more generic convertors i.e. base class or integers which are implicitly convertible
                var correctConverter = leftExpressionType.Type.GetImplicitCoversionOp(leftExpressionType.Type,
                                                                                      rightExpressionType.Type, true);

                if (correctConverter == null)
                {
                    useType          = false;
                    correctConverter =
                        rightExpressionType.Type.GetImplicitCoversionOp(leftExpressionType.Type,
                                                                        rightExpressionType.Type, true);
                }

                if (correctConverter != null)
                {
                    Core.Write(writer, leftExpression);
                    writer.Write(operatorToken.ToString());
                    if (useType)
                    {
                        writer.Write(TypeProcessor.ConvertType(leftExpressionType.Type) + "." + "op_Implicit_" +
                                     TypeProcessor.ConvertType(correctConverter.ReturnType, false, true, false).Replace(".", "_"));
                    }
                    else
                    {
                        writer.Write(TypeProcessor.ConvertType(rightExpressionType.Type) + "." + "op_Implicit_" +
                                     TypeProcessor.ConvertType(correctConverter.ReturnType, false, true, false).Replace(".", "_"));
                    }
                    writer.Write("(");
                    Core.Write(writer, rightExpression);
                    writer.Write(")");
                    return;
                }
            }

            if (operatorToken.CSharpKind() == SyntaxKind.PlusEqualsToken ||
                operatorToken.CSharpKind() == SyntaxKind.MinusEqualsToken)
            {
                var isname = rightExpression is NameSyntax;

                var nameexpression = rightExpression as NameSyntax;

                var ismemberexpression = rightExpression is MemberAccessExpressionSyntax ||
                                         (isname &&
                                          TypeProcessor.GetSymbolInfo(rightExpression as NameSyntax).Symbol.Kind ==
                                          SymbolKind.Method);

                var isdelegateassignment = rightExpressionType.ConvertedType != null && (ismemberexpression &&
                                                                                         rightExpressionType.ConvertedType
                                                                                         .TypeKind == TypeKind.Delegate);

                var memberaccessexpression = rightExpression as MemberAccessExpressionSyntax;

                var isstaticdelegate = isdelegateassignment &&
                                       ((memberaccessexpression != null &&
                                         TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) ||
                                        (isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic));

                if (isdelegateassignment)
                {
                    Core.Write(writer, leftExpression);

                    writer.Write(operatorToken.ToString());

                    var typeString = TypeProcessor.ConvertType(rightExpressionType.ConvertedType);

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

                    var isStatic = isstaticdelegate;
                    //                        if (isStatic)
                    //                            writer.Write("__ToDelegate(");

                    MemberUtilities.WriteMethodPointer(writer, rightExpression);
                    //                        if (isStatic)
                    //                            writer.Write(")");

                    writer.Write(")");
                    return;
                }
            }
            if (leftExpressionType.Type == null || (rightExpressionType.Type == null && rightExpression != null))
            {
                // seems we have a null here obj==null or null==obj
                if ((rightExpressionType.Type != null && rightExpressionType.Type.IsValueType) ||
                    (leftExpressionType.Type != null && leftExpressionType.Type.IsValueType))
                {
                    writer.Write("/*value type cannot be null*/");
                    Core.Write(writer, leftExpression);
                    switch (operatorToken.CSharpKind())
                    {
                    case SyntaxKind.EqualsEqualsToken:
                        writer.Write("!=");
                        break;

                    case SyntaxKind.NotEqualsExpression:
                        writer.Write("==");
                        break;

                    default:
                        writer.Write(operatorToken.ToString());
                        break;
                    }

                    Core.Write(writer, rightExpression);
                }
                else
                {
                    Core.Write(writer, leftExpression);
                    if (operatorToken.CSharpKind() == SyntaxKind.EqualsEqualsToken)
                    {
                        writer.Write(" is ");
                    }
                    else if (operatorToken.CSharpKind() == SyntaxKind.ExclamationEqualsToken)
                    {
                        writer.Write(" !is ");
                    }
                    else
                    {
                        writer.Write(operatorToken.ToString());
                    }
                    if (rightExpression != null)
                    {
                        Core.Write(writer, rightExpression);
                    }
                }
            }
            else
            {
                writer.Write(boxLeft ? "BOX!(" + TypeProcessor.ConvertType(leftExpressionType.Type) + ")(" : "");
                Core.Write(writer, leftExpression);
                writer.Write(boxLeft ? ")" : "");
                writer.Write(operatorToken.ToString());
                if (rightExpression != null)
                {
                    writer.Write(unboxRight
                        ? "UNBOX!(" + TypeProcessor.ConvertType(rightExpressionType.ConvertedType) + ")("
                        : "");
                    writer.Write(boxRight ? "BOX!(" + TypeProcessor.ConvertType(rightExpressionType.Type) + ")(" : "");
                    Core.Write(writer, rightExpression);
                    writer.Write(boxRight ? ")" : "");
                    writer.Write(unboxRight ? ")" : "");
                }
            }
        }
Exemple #8
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());
        }
        public static void Go(OutputWriter writer, MemberAccessExpressionSyntax expression)
        {
            var memberName = expression.Name.Identifier.Text;
            var type       = TypeProcessor.GetTypeInfo(expression.Expression).ConvertedType;
            var typeStr    = TypeProcessor.GenericTypeName(type);

            var isLiteral = expression.Expression is LiteralExpressionSyntax;

            var isStringLiteral = false;

            if (isLiteral)
            {
                var literal = expression.Expression as LiteralExpressionSyntax;

                if (literal.RawKind == (decimal)SyntaxKind.StringLiteralExpression)
                {
                    isStringLiteral = true;
                    // writer.Write("((System.String)"); Not needed for strings at all
                }
            }

            memberName = WriteIdentifierName.TransformIdentifier(memberName);

            var typeInfo     = TypeProcessor.GetTypeInfo(expression.Expression);
            var symbolInfo   = TypeProcessor.GetSymbolInfo(expression);
            var methodSymbol = symbolInfo.Symbol;

            if (methodSymbol == null)
            {
                symbolInfo = TypeProcessor.GetSymbolInfo(expression.Expression);
            }
            if (type != null && methodSymbol != null)
            //if type is null, then we're just a namespace.  We can ignore these.
            {
                var directInvocationOnBasics = methodSymbol.ContainingType.IsBasicType() && methodSymbol.IsStatic;

                if (directInvocationOnBasics)
                {
                    //Extension methods in Dlang are straightforward, although this could lead to clashes without qualification
                    if (methodSymbol.ContainingType != Context.Instance.Type)
                    {
                        var extensionNamespace = TypeProcessor.ConvertType(type, true, false);

                        writer.Write(extensionNamespace);
                    }
                }
                else
                {
                    WriteMember(writer, expression.Expression);
                }

                if (isLiteral && !isStringLiteral)
                {
                    writer.Write(")"); //Not needed for strings at all
                }
                writer.Write(".");
                // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
            }

            if (methodSymbol != null && methodSymbol.Kind == SymbolKind.Property)
            {
                if (methodSymbol.ContainingType.TypeKind == TypeKind.Interface ||
                    Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(methodSymbol),
                           methodSymbol))
                {
                    /* memberName =
                     *   Regex.Replace(
                     *       TypeProcessor.ConvertType(methodSymbol.ContainingType.OriginalDefinition)
                     *           .RemoveFromStartOfString(methodSymbol.ContainingNamespace + ".Namespace.") +
                     *       "_" + memberName,
                     *       @" ?!\(.*?\)", string.Empty);*/
                    if (methodSymbol.ContainingType.ContainingType != null)
                    {
                        memberName = memberName.RemoveFromStartOfString(methodSymbol.ContainingType.ContainingType.Name + ".");
                    }
                }

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

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

                if (interfaceMethod != null)

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

                /*  if (!methodSymbol.ContainingType.IsAnonymousType &&
                 *    (methodSymbol.DeclaringSyntaxReferences.Any() &&
                 *     methodSymbol.DeclaringSyntaxReferences.FirstOrDefault()
                 *         .GetSyntax()
                 *         .As<PropertyDeclarationSyntax>()
                 *         .Modifiers.Any(SyntaxKind.NewKeyword)))
                 * {
                 *    //TODO: this means that new is not supported on external libraries, anonymous types cannot be extended
                 *    //					//why doesnt roslyn give me this information ?
                 *    memberName += "_";
                 * }*/
            }

            var isGet = false;

            writer.Write(memberName);

//            if (methodSymbol is IMethodSymbol) //Lets specialize it
//            {
//                //                //Type inference for delegates
//                var mmethodSymbol = methodSymbol as IMethodSymbol;
//
//                var specialization =
//                                        (mmethodSymbol.TypeArguments.Any() ? ("!(" +
//                                        mmethodSymbol.TypeArguments.Select(k => TypeProcessor.ConvertType(k))
//                                            .Aggregate((a, b) => a + "," + b) + ")") : "");
//                writer.Write(specialization);
//            }

            /* if (expression.Name is GenericNameSyntax)
             * {
             *   var gen = expression.Name.As<GenericNameSyntax>();
             *
             *   writer.Write("!(");
             *
             *   bool first = true;
             *   foreach (var g in gen.TypeArgumentList.Arguments)
             *   {
             *       if (first)
             *           first = false;
             *       else
             *           writer.Write(", ");
             *
             *       writer.Write(TypeProcessor.ConvertType(g));
             *   }
             *
             *   writer.Write(")");
             * }*/
        }
Exemple #10
0
        public static string GetMethodName(MemberDeclarationSyntax member, ref bool isInterface, out ITypeSymbol interfaceImplemented, out ISymbol[] proxies)
        {
            interfaceImplemented = null;
            proxies = null;
            var methodSymbol = TypeProcessor.GetDeclaredSymbol(member);
            var name         = WriteIdentifierName.TransformIdentifier(OverloadResolver.MethodName(methodSymbol));

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



            var isinterfacemethod = Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(methodSymbol),
                                           methodSymbol);

            if (!isinterfacemethod && methodSymbol.IsOverride)
            {
                isinterfacemethod = Equals(methodSymbol.ContainingType.BaseType.FindImplementationForInterfaceMember(methodSymbol),
                                           methodSymbol);
            }

            if (methodSymbol.ContainingType.TypeKind == TypeKind.Interface ||
                (isinterfacemethod && methodSymbol.IsOverride))
            {
                /* name = Regex.Replace(
                 *  TypeProcessor.ConvertType(methodSymbol.ContainingType.ConstructedFrom) + "_" + name,
                 *  @" ?!\(.*?\)", String.Empty);*/

                interfaceImplemented = methodSymbol.ContainingType.ConstructedFrom;

                if (methodSymbol.ContainingType.ContainingType != null)
                {
                    name = name.RemoveFromStartOfString(methodSymbol.ContainingType.ContainingType.Name + ".");
                }
            }

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

            var name1 = name;

            IEnumerable <ISymbol> interfaceMethods = null;

            if (methodSymbol.IsOverride && (interfaceMethods == null || !interfaceMethods.Any()))
            {
                interfaceMethods =
                    methodSymbol.ContainingType.BaseType.AllInterfaces.SelectMany(
                        u =>
                        u.GetMembers(name1));

                if ((interfaceMethods == null || !interfaceMethods.Any()))
                {
                    interfaceMethods =
                        interfaceMethods.Where(
                            o => Equals(methodSymbol.ContainingType.BaseType.FindImplementationForInterfaceMember(o), methodSymbol));
                }
            }
            else
            {
                interfaceMethods =
                    methodSymbol.ContainingType.AllInterfaces.SelectMany(
                        u =>
                        u.GetMembers(name1));
                interfaceMethods =
                    interfaceMethods.Where(
                        o => Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(o), methodSymbol));
            }

            var enumerable      = interfaceMethods as ISymbol[] ?? interfaceMethods.ToArray();
            var interfaceMethod = enumerable.FirstOrDefault();

            if (interfaceMethods.Count() > 1)
            {
                proxies = interfaceMethods.ToArray();
            }

            if (interfaceMethod != null)
            {
                //TODO: fix this for virtual method test 7, seems roslyn cannot deal with virtual
                // overrides of interface methods ... so i'll provide a kludge
                //                if (!member.GetModifiers().Any(SyntaxKind.NewKeyword) && methodSymbol is IMethodSymbol) // This is not neccessary for properties
                //                {
                //                    interfaceMethod =
                //                        enumerable.FirstOrDefault(k => CompareMethods(k as IMethodSymbol, (IMethodSymbol) methodSymbol));
                //                }
            }

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

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

            //            if (member.GetModifiers().Any(SyntaxKind.NewKeyword) && methodSymbol.OriginalDefinition.ContainingType.TypeKind != TypeKind.Interface) //Take care of new
            //                name += "_";
            if (methodSymbol.IsNew())
            {
                // name += "_";
                interfaceImplemented = methodSymbol.OriginalDefinition.ContainingType;
            }

            GetExplicitInterface(ref interfaceImplemented, methodSymbol);

            //            if (interfaceMethods.Count() >= 1 && interfaceMethod!=null)
            //                proxies = interfaceMethods.ToArray();

            return(name);
        }
Exemple #11
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(";");
        }
Exemple #12
0
        public static string GetCSharpName(this MemberDeclarationSyntax member)
        {
            var method      = member as MethodDeclarationSyntax;
            var field       = member as FieldDeclarationSyntax;
            var property    = member as PropertyDeclarationSyntax;
            var _eventField = member as EventFieldDeclarationSyntax;
            var _event      = member as EventDeclarationSyntax;

            var _operator     = member as OperatorDeclarationSyntax;
            var _convoperator = member as ConversionOperatorDeclarationSyntax;
            var indexer       = member as IndexerDeclarationSyntax;
            var destructor    = member as DestructorDeclarationSyntax;
            var constructor   = member as ConstructorDeclarationSyntax;



            //TODO: might have to add support for parameters


            if (method != null)
            {
                return(WriteIdentifierName.TransformIdentifier(method.Identifier.Text));
            }

            if (field != null)
            {
                return(field.Declaration.Variables.Select(j => WriteIdentifierName.TransformIdentifier(j.Identifier.Text)).Aggregate((a, b) => a + "," + b));
            }

            if (property != null)
            {
                return(WriteIdentifierName.TransformIdentifier(property.Identifier.Text));
            }

            if (_eventField != null)
            {
                return(_eventField.Declaration.Variables.Select(j => WriteIdentifierName.TransformIdentifier(j.Identifier.Text)).Aggregate((a, b) => a + "," + b));
            }

            if (_event != null)
            {
                return(WriteIdentifierName.TransformIdentifier(_event.Identifier.Text));
            }

            if (_operator != null)
            {
                return("operator" + _operator.OperatorToken);
            }

            if (_convoperator != null)
            {
                return("operator");
            }

            if (indexer != null)
            {
                return("[]");
            }

            if (destructor != null)
            {
                return("~this()"); //destructor.Identifier.Text;
            }

            if (constructor != null)
            {
                return("this()"); //destructor.Identifier.Text;
            }



            throw new NotImplementedException(member.ToFullString());
        }
Exemple #13
0
        private static string ConvertTypeUncached(ITypeSymbol typeSymbol)
        {
            if (typeSymbol.IsAnonymousType)
            {
                return(WriteAnonymousObjectCreationExpression.TypeName(typeSymbol.As <INamedTypeSymbol>()));
            }

            var array = typeSymbol as IArrayTypeSymbol;

            if (array != null)
            {
                var typeString = TryConvertType(array.ElementType, false);
//                if (localize)
//                {
//                    var name =
//                        Context.Instance.UsingDeclarations.FirstOrDefault(
//                            k => typeString.StartsWith(k.Name.ToFullString() + ".Namespace.", StringComparison.Ordinal));
//
//                    if (name != null)
//                        typeString = typeString.RemoveFromStartOfString(name.Name.ToFullString() + ".Namespace.");
//                }
                return("Array_T!(" + typeString + ")");
            }

            if (typeSymbol.TypeKind == TypeKind.PointerType)
            {
                var pointer = typeSymbol as IPointerTypeSymbol;
                return(ConvertType(pointer.PointedAtType) + "*");
            }

            var typeInfoStr = typeSymbol.ToString();

            var named = typeSymbol as INamedTypeSymbol;

            if (typeSymbol.TypeKind == TypeKind.TypeParameter)
            {
                return(WriteIdentifierName.TransformIdentifier(typeSymbol.Name, typeSymbol));
            }


            if (named != null && (named.ContainingNamespace.ToString() == "System" && named.Name == "Exception"))
            {
                return("System.Namespace.NException");
            }

            //TODO: Add explicit support for Nullable
            if (named != null && (named.Name == "Nullable" && named.ContainingNamespace.ToString() == "System"))
            {
                //Nullable types
                if (named.TypeArguments.Any())
                {
                    string convertedType = "";

                    if (named.TypeArguments.FirstOrDefault() is IErrorTypeSymbol)
                    {
                        //unbound generic
                        convertedType = "__UNBOUND";
                    }
                    else
                    {
                        convertedType = TryConvertType(named.TypeArguments.FirstOrDefault(), false);
                    }


                    return("Nullable__G!(" + convertedType + ")");
                }
            }

            var typeStr = GenericTypeName(typeSymbol);

            if (named != null && named.IsGenericType)
            {
                if (!named.IsUnboundGenericType && TypeArguments(named).Any())
                {
                    return(GetFullGenericName(named));
                }
                else
                {
                    return(GetFullGenericName(named.OriginalDefinition));
                }
            }


            switch (typeStr)
            {
            case "System.Namespace.Void":
                return("void");

            case "System.Namespace.Boolean":
                return("bool");

            case "System.Object":
            case "System.Namespace.Object":
                return("NObject");

            case "System.Namespace.UInt64":
                return("ulong");

            case "System.Namespace.Double":
                return("double");

            case "System.Namespace.Single":
                return("float");

            case "System.Namespace.String":
                return("String");

            case "System.Namespace.Int32":
                return("int");

            case "System.Namespace.UInt16":
                return("ushort");

            case "System.Namespace.Int64":
                return("long");

            case "System.Namespace.UInt32":
                return("uint");    // /TODO: Looks like d's uint32 is smaller than C#'s

            case "System.Namespace.Byte":
                return("ubyte");

            case "System.Namespace.SByte":
                return("byte");

            case "System.Namespace.Int16":
                return("short");

            case "System.Namespace.Char":
                return("wchar");

            case "System.Namespace.Array":
                return("Array");    //All template (generic) classes have atleast one "_T" appended

            default:

                if (named != null)
                {
                    return(typeSymbol.ContainingNamespace.FullNameWithDot(true, false) + WriteType.TypeName(named));
                }

                //This type does not get translated and gets used as-is
                return(typeSymbol.ContainingNamespace.FullNameWithDot(true, false) + WriteIdentifierName.TransformIdentifier(typeSymbol.Name));
            }
        }
Exemple #14
0
        public static void Go(OutputWriter writer, LocalDeclarationStatementSyntax declaration)
        {
            foreach (var variable in declaration.Declaration.Variables)
            {
                ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable);

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

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

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

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

                    var str = TypeProcessor.ConvertType(declaration.Declaration.Type);
                    if (str == "NObject")
                    {
                        // Looks harmless but is actually a performance optimization ... makes CastTest improve by a whole lot
                        writer.Write("auto ");
                    }
                    else
                    {
                        writer.Write(str);
                    }

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

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

                    WriteInitializer(writer, declaration, variable);
                }

                writer.Write(";\r\n");
            }
        }
Exemple #15
0
        private static string GetTypeConstraints(TypeDeclarationSyntax method)
        {
            string constraints = "";

            if (method.ConstraintClauses.Count > 0)
            {
                constraints += (" if (");
                bool isFirst = true;
                foreach (var constraint in method.ConstraintClauses)
                {
                    foreach (var condition in constraint.Constraints)
                    {
                        if (condition is TypeConstraintSyntax)
                        {
                            var type = (condition as TypeConstraintSyntax).Type;
                            constraints += (isFirst ? "" : "&&") + "is(" + WriteIdentifierName.TransformIdentifier(constraint.Name.ToFullString()) + ":" + TypeProcessor.ConvertType(type) + ")";
                        }

                        if (condition is ConstructorConstraintSyntax)
                        {
                            constraints += (isFirst ? "" : "&&") + "__isNewwable!(" + WriteIdentifierName.TransformIdentifier(constraint.Name.ToFullString()) + ")";
                        }

                        if (condition is ClassOrStructConstraintSyntax)
                        {
                            var properConstraint = condition as ClassOrStructConstraintSyntax;
                            if (properConstraint.ClassOrStructKeyword.RawKind == (decimal)SyntaxKind.StructKeyword)
                            {
                                constraints += (isFirst ? "" : "&&") + "__isCSStruct!(" + WriteIdentifierName.TransformIdentifier(constraint.Name.ToFullString()) + ")";
                            }
                            else
                            {
                                constraints += (isFirst ? "" : "&&") + "__isClass!(" + WriteIdentifierName.TransformIdentifier(constraint.Name.ToFullString()) + ")";
                            }
                        }

                        /*  string dlangCondition = condition.ToString();
                         *
                         * if (dlangCondition == "new()") // haven't got around to this yet
                         *    // constraints += " __traits(compiles, {0}())";//Fix this
                         *    dlangCondition = "";
                         * if (dlangCondition == "class") // TODO: is there a better way to do this ?
                         *    dlangCondition = "NObject";
                         *
                         * if (dlangCondition == "struct")
                         *    constraints += ((isFirst ? "" : "&&") + " !is(" + constraint.Name + " : NObject)");
                         * else
                         * {
                         *    //TODO: fix this up better
                         *    constraints += ((isFirst ? "" : "&&") + " is(" + constraint.Name + " : " + dlangCondition.Replace("<", "!(").Replace(">", ")") +
                         *                    ")");
                         * }*/

                        isFirst = false;

                        //								Console.WriteLine (condition);
                    }
                }

                constraints += (")");
            }
            return(constraints);
        }
        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 ...
        }
Exemple #17
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());
        }