Esempio n. 1
0
        private static string GetMethodConstraints(MethodDeclarationSyntax 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)
                    {
                        string dlangCondition = condition.ToString();

                        if (dlangCondition == "new()") // haven't got around to this yet
                        {
                            continue;
                        }
                        if (dlangCondition == "class") // TODO: is there a better way to do this ?
                        {
                            dlangCondition = "NObject";
                        }

                        if (dlangCondition == "struct")
                        {
                            constraints += ((isFirst ? "" : "&&") + " !is(" + constraint.Name + " : NObject)");
                        }
                        else
                        {
                            var constraintName = WriteIdentifierName.TransformIdentifier(constraint.Name.Identifier.Text);

                            if (condition is TypeConstraintSyntax)
                            {
                                var type = TypeProcessor.GetTypeInfo((condition as TypeConstraintSyntax).Type).Type;
                                if (type.TypeKind == TypeKind.Interface)
                                {
                                    constraintName = "__BoxesTo!(" + constraintName + ")";
                                }

                                constraints += ((isFirst ? "" : "&&") + " is(" + constraintName + " : " + TypeProcessor.ConvertType(type, true, true, true) +
                                                ")");
                            }
                            else
                            {
                                //TODO: fix this up better
                                constraints += ((isFirst ? "" : "&&") + " is(" + constraintName + " : " + dlangCondition.Replace("<", "!(").Replace(">", ")") +
                                                ")");
                            }
                        }

                        isFirst = false;

                        //								Console.WriteLine (condition);
                    }
                }

                constraints += (")");
            }
            return(constraints);
        }
        /// <summary>
        ///     calls to Enum.Parse get re-written as calls to our special Parse methods on each enum.  We assume the first
        ///     parameter to Enum.Parse is a a typeof()
        /// </summary>
        private static void WriteEnumParse(OutputWriter writer, InvocationExpressionSyntax invocationExpression)
        {
            var args = invocationExpression.ArgumentList.Arguments;

            if (args.Count < 2 || args.Count > 3)
            {
                throw new Exception("Expected 2-3 args to Enum.Parse");
            }

            if (args.Count == 3 &&
                (!(args[2].Expression is LiteralExpressionSyntax) ||
                 args[2].Expression.As <LiteralExpressionSyntax>().ToString() != "false"))
            {
                throw new NotImplementedException("Case-insensitive Enum.Parse is not supported " +
                                                  Utility.Descriptor(invocationExpression));
            }

            if (!(args[0].Expression is TypeOfExpressionSyntax))
            {
                throw new Exception("Expected a typeof() expression as the first parameter of Enum.Parse " +
                                    Utility.Descriptor(invocationExpression));
            }

            var type = TypeProcessor.GetTypeInfo(args[0].Expression.As <TypeOfExpressionSyntax>().Type).Type;

            //ModelExtensions.GetTypeInfo(Program.GetModel(invocationExpression), args[0].Expression.As<TypeOfExpressionSyntax>().Type).Type;
            writer.Write(type.ContainingNamespace.FullNameWithDot());
            writer.Write(WriteType.TypeName((INamedTypeSymbol)type));
            writer.Write(".Parse(");
            Core.Write(writer, args[1].Expression);
            writer.Write(")");
        }
Esempio n. 3
0
        private static bool ReturnsVoid(SyntaxNode node)
        {
            while (node != null)
            {
                var method = node as MethodDeclarationSyntax;
                if (method != null)
                {
                    return(method.ReturnType.ToString() == "void");
                }

                var prop = node as PropertyDeclarationSyntax;
                if (prop != null)
                {
                    return(prop.Type.ToString() == "void");
                }

                var lambda1 = node as ParenthesizedLambdaExpressionSyntax;
                var lambda2 = node as SimpleLambdaExpressionSyntax;
                if (lambda1 != null || lambda2 != null)
                {
                    var lambda       = lambda1 == null ? lambda2 : (ExpressionSyntax)lambda1;
                    var methodSymbol =
                        TypeProcessor.GetTypeInfo(lambda)
                        .ConvertedType.As <INamedTypeSymbol>()
                        .DelegateInvokeMethod.As <IMethodSymbol>();

                    return(methodSymbol.ReturnsVoid);
                }

                node = node.Parent;
            }

            throw new Exception("Node not in a body");
        }
Esempio n. 4
0
        public static void Go(OutputWriter writer, SizeOfExpressionSyntax expression)
        {
            var type = TypeProcessor.GetTypeInfo(expression.Type);

            //Use dTypes
            writer.Write("" + TypeProcessor.ConvertType(type.Type) + ".sizeof");
            //  writer.Write(SizeOf(type.Type).ToString());
        }
Esempio n. 5
0
        public static void WriteIt(OutputWriter writer, SyntaxToken operatorToken, CSharpSyntaxNode rightExpression,
                                   CSharpSyntaxNode leftExpression)
        {
            if (operatorToken.IsKind(SyntaxKind.AsKeyword))
            {
                writer.Write("AsCast!(");
                writer.Write(TypeProcessor.ConvertType(rightExpression));
                writer.Write(")(");
                Core.Write(writer, leftExpression);
                writer.Write(")");
            }
            else if (operatorToken.IsKind(SyntaxKind.IsKeyword)) // isCast
            {
                var leftSymbolType  = TypeProcessor.GetTypeInfo(leftExpression);
                var rightSymbolType = TypeProcessor.GetTypeInfo(rightExpression);

                if (leftSymbolType.Type.IsValueType)
                {
                    writer.Write("IsCast!(Boxed!(");
                    writer.Write(TypeProcessor.ConvertType(rightExpression));
                    writer.Write("))");
                    writer.Write("(");
                    Core.Write(writer, leftExpression);
                    writer.Write(")");
                }
                else if (rightSymbolType.Type.IsValueType)
                {
                    writer.Write("IsCast!(Boxed!(");
                    writer.Write(TypeProcessor.ConvertType(rightExpression));
                    writer.Write("))");
                    writer.Write("(");
                    Core.Write(writer, leftExpression);
                    writer.Write(")");
                }
                else
                {
                    writer.Write("(IsCast!(");
                    writer.Write(TypeProcessor.ConvertType(rightExpression));
                    writer.Write(")(");
                    Core.Write(writer, leftExpression);
                    writer.Write("))");
                }
            }
            else if (operatorToken.IsKind(SyntaxKind.QuestionQuestionToken))
            {
                writer.Write("((");
                Core.Write(writer, leftExpression);
                writer.Write(")!is null?(");
                Core.Write(writer, leftExpression);
                writer.Write("):(");
                Core.Write(writer, rightExpression);
                writer.Write("))");
            }
            else
            {
                ProcessExpression(writer, operatorToken, rightExpression, leftExpression);
            }
        }
Esempio n. 6
0
 public static void Go(OutputWriter writer, AnonymousMethodExpressionSyntax expression)
 {
     if (expression.ParameterList != null)
     {
         Go(writer, expression.ParameterList.Parameters, expression.Block, TypeProcessor.GetTypeInfo(expression));
     }
     else
     {
         Go(writer, new SeparatedSyntaxList <ParameterSyntax>(), expression.Block, TypeProcessor.GetTypeInfo(expression));
     }
 }
Esempio n. 7
0
        public void Write(OutputWriter writer)
        {
            if (StringOpt != null)
            {
                writer.Write(StringOpt);
            }
            else
            {
                if (ArgumentOpt.NameColon != null)
                {
                    Core.Write(writer, ArgumentOpt.NameColon.Name);
                    writer.Write(" = ");
                }

                var symbol = TypeProcessor.GetSymbolInfo(ArgumentOpt.Expression);
                var type   = TypeProcessor.GetTypeInfo(ArgumentOpt.Expression);

                if (symbol.Symbol != null && type.ConvertedType != null && symbol.Symbol.Kind == SymbolKind.Method &&
                    type.ConvertedType.TypeKind == TypeKind.Delegate)
                {
                    var typeString = TypeProcessor.ConvertType(type.ConvertedType);

                    var createNew = !(ArgumentOpt.Parent.Parent is ObjectCreationExpressionSyntax); //Ugly hack

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

                    var isStatic = symbol.Symbol.IsStatic;
//                    if (isStatic) //Not Needed, delegate class now supports functions directly
//                        writer.Write("__ToDelegate(");
                    MemberUtilities.WriteMethodPointer(writer, ArgumentOpt.Expression);
//                    if (isStatic)
//                        writer.Write(")");

                    if (createNew)
                    {
                        writer.Write(")");
                    }
                    return;
                }

                Core.Write(writer, ArgumentOpt.Expression);
            }
        }
        public static void Go(OutputWriter writer, StackAllocArrayCreationExpressionSyntax @as)
        {
            //import core.stdc.stdlib;
            //@as.Type;
            //auto ptr = cast(wchar*)alloca(wchar.sizeof * len);
            var arrayType       = TypeProcessor.GetTypeInfo(@as.Type);
            var elementType     = TypeProcessor.GetTypeInfo(((ArrayTypeSyntax)@as.Type).ElementType);
            var elementTypeName = TypeProcessor.ConvertType(elementType.Type);
            var size            = Core.WriteString(((ArrayTypeSyntax)@as.Type).RankSpecifiers[0].Sizes[0]);

            writer.Write("cast(" + elementTypeName + "*) core.stdc.stdlib.alloca(" + elementTypeName + ".sizeof * " + size + ")");
        }
Esempio n. 9
0
        public static void Go(OutputWriter writer, UsingStatementSyntax usingStatement)
        {
            var expression = usingStatement.Expression;

            writer.WriteLine("//using block ... " + usingStatement.Declaration);
            writer.OpenBrace();
            //Ensure the using statement is a local variable - we can't deal with things we can't reliably repeat in the finally block
            var resource = Utility.TryGetIdentifier(expression);
//            if (resource == null)
//                throw new Exception("Using statements must reference a local variable. " + Utility.Descriptor(usingStatement));

            var variables = new SeparatedSyntaxList <VariableDeclaratorSyntax>();//.Select(o => o.Identifier.ValueText);

            if (usingStatement.Declaration != null)
            {
                Core.Write(writer, usingStatement.Declaration);
                variables = usingStatement.Declaration.Variables;
            }

            writer.WriteLine("try");
            Core.WriteStatementAsBlock(writer, usingStatement.Statement);
            writer.WriteLine("finally");
            writer.OpenBrace();
            foreach (var variable in variables)
            {
                var typeInfo = TypeProcessor.GetTypeInfo(usingStatement.Declaration.Type);
                if (!typeInfo.Type.IsValueType)
                {
                    writer.WriteLine("if(" + variable.Identifier.Text + " !is null)");
                }
                else if (typeInfo.Type.Name == "Nullable")
                {
                    writer.WriteLine("if(" + variable.Identifier.Text + ".HasValue)");
                }


                writer.WriteLine(variable.Identifier.Text + ".Dispose(cast(IDisposable)null);");
            }
            if (resource != null)
            {
                writer.WriteLine("if(" + resource + " !is null)");
                writer.WriteLine(resource + ".Dispose(cast(IDisposable)null);");
            }
            writer.CloseBrace();
            writer.CloseBrace();
        }
        private static void WriteEnumGetValues(OutputWriter writer, InvocationExpressionSyntax invocationExpression)
        {
            if (!(invocationExpression.ArgumentList.Arguments[0].Expression is TypeOfExpressionSyntax))
            {
                throw new Exception("Expected a typeof() expression as the first parameter of Enum.GetValues " +
                                    Utility.Descriptor(invocationExpression));
            }

            //            var type = ModelExtensions.GetTypeInfo(Program.GetModel(invocationExpression), invocationExpression.ArgumentList.Arguments[0].Expression.As<TypeOfExpressionSyntax>().Type).Type;
            var type =
                TypeProcessor.GetTypeInfo(
                    invocationExpression.ArgumentList.Arguments[0].Expression.As <TypeOfExpressionSyntax>().Type).Type;

            writer.Write(type.ContainingNamespace.FullNameWithDot());
            writer.Write(WriteType.TypeName((INamedTypeSymbol)type));
            writer.Write(".Values");
        }
Esempio n. 11
0
        public static void Go(OutputWriter writer, ImplicitArrayCreationExpressionSyntax array)
        {
            var t           = TypeProcessor.GetTypeInfo(array).Type;
            var ptr         = !t.As <IArrayTypeSymbol>().ElementType.IsValueType; // ? "" : "";
            var elementType = t.As <IArrayTypeSymbol>().ElementType;
            var type        = TypeProcessor.ConvertType(elementType);
            var typeString  = "Array_T!(" + type + ")";

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

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

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

//			array.Initializer.WriteArrayInitializer(writer,);
//            bool first = true;
//            foreach (var expression in array.Initializer.Expressions)
//            {
//                if (first)
//                    first = false;
//                else
//                    writer.Write(",");
//
//                Core.Write(writer, expression);
//            }

            writer.Write(")");
        }
Esempio n. 12
0
        public static void WriteParameterList(OutputWriter writer, ParameterListSyntax list)
        {
            writer.Write("(");
            var firstParam = true;

            foreach (var parameter in list.Parameters)
            {
                bool isRef = parameter.Modifiers.Any(SyntaxKind.OutKeyword) ||
                             parameter.Modifiers.Any(SyntaxKind.RefKeyword);
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    writer.Write(", ");
                }
                var localSymbol = TypeProcessor.GetTypeInfo(parameter.Type);
                var ptr         = (localSymbol.Type != null &&
                                   !(localSymbol.Type.IsValueType || localSymbol.Type.TypeKind == TypeKind.TypeParameter));
                if (!isRef)
                {
                    //  var s = TypeProcessor.ConvertType(parameter.Type) + " " + ptr;
                    var s = TypeProcessor.ConvertType(parameter.Type) + " ";
                    writer.Write(s);
                }
                else
                {
                    //                    var s = "" + TypeProcessor.ConvertType(parameter.Type) + ptr + "& ";
                    var s = " ref " + TypeProcessor.ConvertType(parameter.Type) + " ";
                    writer.Write(s);
                    Program.RefOutSymbols.TryAdd(TypeProcessor.GetDeclaredSymbol(parameter), null);
                }
                writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Identifier.ValueText));
                if (parameter.Default != null)
                {
                    writer.Write(" = ");
                    Core.Write(writer, parameter.Default.Value);
                }
            }
            writer.Write(") ");
        }
Esempio n. 13
0
//        private static long DetermineEnumValue(EnumMemberDeclarationSyntax syntax, ref long lastEnumValue) //Not necessary D and C# enums are equivalent
//        {
//            if (syntax.EqualsValue == null)
//                return ++lastEnumValue;
//
//			var value = syntax.EqualsValue.Value.ToString ();
//
//			if (value.StartsWith ("0x") || value.StartsWith ("0x")) {
//			//probably hex number
//
//			}
//
//			value = value.Replace ("0x","X").Replace("0X","X");  //Int.parse cannot process 0x :(
//
//			if (!long.TryParse(value,  out lastEnumValue))
//                throw new Exception("Enums must be assigned with an integer " + Utility.Descriptor(syntax));
//
//            return lastEnumValue;
//        }


        public static void Check(SyntaxNode node)
        {
            //Check for enums being converted to objects.  There are common methods in .net that accept objects just to call .ToString() on them, such as Console.WriteLine and HttpResponse.Write.  In these cases, we would miss our enum-to-string conversion that ensures the strings are used instead of the number.  To work around this, you should call .ToString() on the enum before passing it in.  It's a good idea to do this anyway for performance, so we just fail instead of doing the conversion automatically.  This check is a bit overzealous, as there are also legitimate reasons to conver enums to objects, but we'd rather be safe and reject a legitimate use than have code behave incorrectly.

            var expression = node as ExpressionSyntax;

            if (expression == null)
            {
                return;
            }

            var typeInfo = TypeProcessor.GetTypeInfo(expression);

            if (typeInfo.Type == null || typeInfo.ConvertedType == null || typeInfo.Type == typeInfo.ConvertedType ||
                typeInfo.Type.BaseType == null)
            {
                return;
            }
            if (typeInfo.ConvertedType.SpecialType != SpecialType.System_Object)
            {
                return;
            }

            if (typeInfo.Type.BaseType.SpecialType != SpecialType.System_Enum)
            {
                if (typeInfo.Type.Name != "Nullable" || typeInfo.Type.ContainingNamespace.FullName() != "System")
                {
                    return;
                }

                var nullableType = typeInfo.Type.As <INamedTypeSymbol>().TypeArguments.Single();

                if (nullableType.BaseType.SpecialType != SpecialType.System_Enum)
                {
                    return;
                }
            }

            throw new Exception(
                      "Enums cannot convert to objects.  Use .ToString() if you're using the enum as a string. " +
                      Utility.Descriptor(node) + ", expr=" + expression);
        }
        public static void Go(OutputWriter writer, LiteralExpressionSyntax expression, bool isConst)
        {
            var str = expression.ToString();

            if (str.StartsWith("@"))
            {
                str = "\"" +
                      str.RemoveFromStartOfString("@\"")
                      .RemoveFromEndOfString("\"")
                      .Replace("\\", "\\\\")
                      .Replace("\"\"", "\\\"")
                      .Replace("\r\n", "\\n") + "\"";
            }

            var typeInfo = TypeProcessor.GetTypeInfo(expression);
            var type     = typeInfo.Type;

            if (type == null)
            {
                type = typeInfo.ConvertedType;
            }

            if (type != null && type.SpecialType == SpecialType.System_String)
            {
                writer.Write("_S(" + str + ")");
            }
            else
            {
                writer.Write(str);
            }

            //TODO: will handle these separately
//            if (typeInfo.Type != null && typeInfo.ConvertedType != null)
//            {
//                if (isConst == false && typeInfo.ConvertedType.SpecialType ==SpecialType.System_Byte && typeInfo.Type.SpecialType == SpecialType.System_Int32)
//                    writer.Write(".toByte");
//            }
        }
        public static void Go(OutputWriter writer, ElementAccessExpressionSyntax expression)
        {
            var type    = TypeProcessor.GetTypeInfo(expression.Expression).Type;
            var typeStr = TypeProcessor.GenericTypeName(type);

            //Todo if we are using unsafe / fast mode, just use array->Data()[i] should bypass bounds check and indirection also should be as fast as pure c++ arrays
            //though fixed syntax could fix this too ??
//            writer.Write("(*");

            Core.Write(writer, expression.Expression);

            if (type.SpecialType == SpecialType.System_Array)
            {
//            writer.Write(")");
                writer.Write(".Items["); //TODO test this thoroughly
            }
            else
            {
                writer.Write("["); //TODO test this thoroughly
            }
            var first = true;

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

                Core.Write(writer, argument.Expression);
            }
            writer.Write("]");
        }
Esempio n. 16
0
        public static void Go(OutputWriter writer, SwitchStatementSyntax switchStatement)
        {
            //  writer.WriteIndent();
            var isStringSwitch = false;
            var isEnumSwitch   = false;

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

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

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

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

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

                writer.OpenBrace(false);

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

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

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

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

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

            writer.CloseBrace();
        }
Esempio n. 17
0
        public static void WriteArrayInitializer(this InitializerExpressionSyntax initializer, OutputWriter writer,
                                                 TypeSyntax type = null)
        {
            bool            first     = true;
            ArrayTypeSyntax arrayType = null;

            ExpressionSyntax[] fullDimension    = null;
            var              inferredDimensions = new Dictionary <int, int>();
            ITypeSymbol      aType  = null;
            IArrayTypeSymbol _aType = null;

            if (type != null)
            {
                arrayType = type as ArrayTypeSyntax;

                if (arrayType != null)
                {
                    aType = TypeProcessor.GetTypeInfo(arrayType).Type as IArrayTypeSymbol;
                }
                else
                {
                    aType = (ITypeSymbol)TypeProcessor.GetTypeInfo(type).Type;
                }

                _aType = aType as IArrayTypeSymbol;
            }
            //For ommitedsizes, lets just count manually
            List <int> inferredSizes = new List <int>();

            if (initializer != null)
            {
                if (initializer.Expressions.Count > 0)
                {
                    if (_aType != null)
                    {
                        writer.Write("__CC!(" + TypeProcessor.ConvertType(_aType.ElementType)
                                     /*+ Enumerable.Range (0, _aType.Rank).Select (l => "[]").Aggregate ((a, b) => a + b).ToString ()*/ +
                                     "[])(");
                    }

                    if (_aType.Rank == 1)
                    {
                        first = WriteArrayElements(initializer, writer, inferredDimensions, 0);
                    }
                    else //multi
                    {
                        writer.Write("[");
                        first = WriteArrayElements(initializer, writer, inferredDimensions, 0, true);
                        writer.Write("]");
                    }
                    //inferredDimensions = inferredDimensions.Take (_aType.Rank).ToList();
                    inferredSizes = inferredDimensions.Select(k => k.Value).ToList();
                    if (_aType != null)
                    {
                        writer.Write(")");
                    }
                }
            }

            if (type != null)
            {
                if (arrayType != null && _aType != null)
                {
                    //Don't do this for jagged arrays ...rank = 1 and .GetLength(>0) throws exception
                    //	if(aType.Rank > 1)
                    {
                        fullDimension =
                            arrayType.RankSpecifiers.Select(o => o.Sizes).SelectMany(j => j).ToArray();

                        if (_aType.Rank > 1)
                        {
                            //If we have a multi-array, we have to have dimensions
                            if (!fullDimension.Any(l => l is OmittedArraySizeExpressionSyntax))
                            {
                                for (int i = 0, fullDimensionLength = fullDimension.Length;
                                     i < fullDimensionLength;
                                     i++)
                                {
                                    var dimensions = fullDimension[i];
                                    if (dimensions is OmittedArraySizeExpressionSyntax)
                                    {
                                        continue;
                                    }
                                    if (first)
                                    {
                                        first = false;
                                    }
                                    else
                                    {
                                        writer.Write(" , ");
                                    }
                                    // MultidimArray
                                    Core.Write(writer, dimensions);
                                }
                            }
                            else
                            {
                                for (int i = 0, fullDimensionLength = inferredSizes.Count; i < fullDimensionLength; i++)
                                {
                                    var dimensions = inferredSizes[i];

                                    if (first)
                                    {
                                        first = false;
                                    }
                                    else
                                    {
                                        writer.Write(" , ");
                                    }
                                    // MultidimArray
                                    writer.Write(dimensions.ToString());
                                }
                            }
                        }
                        else
                        {
                            var dimensions = fullDimension[0];

                            if (!(dimensions is OmittedArraySizeExpressionSyntax))
                            {
                                if (first)
                                {
                                    first = false;
                                }
                                else
                                {
                                    writer.Write(" , ");
                                }

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

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

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

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

            ITypeSymbol interfaceImplemented;

            ISymbol[] proxies;
            ;

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

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

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

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

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

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


                writer.Write("void ");



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

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

                writer.Write(" )");

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

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

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

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

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

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

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



                var IsStatic = "";

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

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

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

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

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

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

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

                    staticWriter.Write(name);

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

                    staticWriter.Write(";");

                    staticWriter.WriteLine();

                    Context.Instance.StaticInits.Add(staticWriter.ToString());
                }
            }
        }
Esempio n. 19
0
        public static void Go(OutputWriter writer, MemberAccessExpressionSyntax expression)
        {
            var memberName = expression.Name.Identifier.ValueText;
            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);

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

                if (directInvocationOnBasics)
                {
//						var extensionNamespace =  symbolInfo.Symbol.ContainingNamespace.FullNameWithDot() + symbolInfo.Symbol.ContainingType.FullName(); //null means it's not an extension method, non-null means it is

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

                    var extensionNamespace = type.ContainingNamespace.FullName() + "." + type.Name;
                    //memberType.ContainingNamespace.FullName() +"."+ memberType.Name;

                    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 (symbolInfo.Symbol != null && symbolInfo.Symbol.Kind == SymbolKind.Property)
            {
                if (symbolInfo.Symbol.ContainingType.TypeKind == TypeKind.Interface ||
                    Equals(symbolInfo.Symbol.ContainingType.FindImplementationForInterfaceMember(symbolInfo.Symbol),
                           symbolInfo.Symbol))
                {
                    memberName =
                        Regex.Replace(
                            TypeProcessor.ConvertType(symbolInfo.Symbol.ContainingType.OriginalDefinition)
                            .RemoveFromStartOfString(symbolInfo.Symbol.ContainingNamespace + ".Namespace.") +
                            "_" + memberName,
                            @" ?!\(.*?\)", string.Empty);
                }

                var interfaceMethods =
                    symbolInfo.Symbol.ContainingType.AllInterfaces.SelectMany(
                        u =>
                        u.GetMembers(memberName)).ToArray();

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

                if (interfaceMethod != null)

                {
//This is an interface method //TO
                    if (symbolInfo.Symbol.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 (!symbolInfo.Symbol.ContainingType.IsAnonymousType &&
                    (symbolInfo.Symbol.DeclaringSyntaxReferences.Any() &&
                     symbolInfo.Symbol.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 (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(" )");
            }
        }
Esempio n. 20
0
        private static void ProcessInitializer(OutputWriter writer, LocalDeclarationStatementSyntax declaration,
                                               VariableDeclaratorSyntax variable)
        {
            var initializer = variable.Initializer;

            if (initializer != null)
            {
                if (initializer.Value.CSharpKind() == SyntaxKind.CollectionInitializerExpression)
                {
                    return;
                }

                var value                  = initializer.Value;
                var initializerType        = TypeProcessor.GetTypeInfo(value);
                var memberaccessexpression = value as MemberAccessExpressionSyntax;
                var nameexpression         = value as NameSyntax;
                var nullAssignment         = value.ToFullString().Trim() == "null";
                var convertedType          = initializerType.ConvertedType;
                var type = initializerType.Type;
                if (type == null && convertedType == null) //TODO: Rare Case (Compiling csnative corlib... need to find a solution, for now just write it out
                {
                    Core.Write(writer, value);
                    return;
                }

                var shouldBox = type != null && (type.IsValueType) &&
                                !convertedType.IsValueType;
                var shouldUnBox = type != null && !type.IsValueType &&
                                  convertedType.IsValueType;
                var isname             = value is NameSyntax;
                var ismemberexpression = value is MemberAccessExpressionSyntax ||
                                         (isname &&
                                          TypeProcessor.GetSymbolInfo(value as NameSyntax).Symbol.Kind ==
                                          SymbolKind.Method);


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

                //Do we have an implicit converter, if so, use it
                if (shouldBox || shouldUnBox)
                {
                    if (WriteConverter(writer, type, convertedType, value))
                    {
                        return;
                    }
                }

                if (nullAssignment)
                {
                    if (convertedType != null) //Nullable Support
                    {
                        if (convertedType.Name == "Nullable")
                        {
                            var atype = TypeProcessor.ConvertType(convertedType);
                            writer.Write(atype + "()");
                        }
                        else
                        {
                            writer.Write("null");
                        }
                    }
                    return;
                }
                if (shouldBox)
                {
                    WriteBox(writer, type, value);
                    return;
                }
                if (shouldUnBox)
                {
                    WriteUnbox(writer, type, value);
                    return;
                }

                if (isdelegateassignment)
                {
                    WriteDelegateAssignment(writer, convertedType, isstaticdelegate, value);
                    return;
                }

//                if (type == null && convertedType == null)
//                {
//                    writer.Write("null");
//                    return;
//                }

                //CTFE

                /* var aVal =  EvaluateValue(value);
                 * if (String.IsNullOrEmpty(aVal))
                 * {
                 *    writer.Write(aVal);
                 * }
                 * else*/
                Core.Write(writer, value);
            }
            else
            {
                writer.Write(TypeProcessor.DefaultValue(declaration.Declaration.Type));
            }
        }
 public static void Go(OutputWriter writer, AnonymousMethodExpressionSyntax expression)
 {
     Go(writer, expression.ParameterList.Parameters, expression.Block, TypeProcessor.GetTypeInfo(expression));
 }
Esempio n. 22
0
        public static void Go(OutputWriter writer, InitializerExpressionSyntax method)
        {
            var array = TypeProcessor.GetTypeInfo(method).ConvertedType as IArrayTypeSymbol;

            //            //TODO: does this info just get discarded ?
            //               if (array.Type.RankSpecifiers.Count > 1 || array.Type.RankSpecifiers.Single().Sizes.Count > 1)
            //                 throw new Exception("Multi-dimensional arrays are not supported " + Utility.Descriptor(array));
            //
            //            var arrayInit = array as ArrayCreationExpressionSyntax;
            //            var rankExpression = array.Type.RankSpecifiers.FirstOrDefault().Sizes.Single();
            //            IEnumerable<ExpressionSyntax> fullDimension =
            //                array.Type.RankSpecifiers.Select(o => o.Sizes).SelectMany(j => j);
            //
            //
            //            if (array.Initializer != null)
            //            {
            //                //                writer.Write("new ");
            //                //                writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
            //                //                writer.Write("[]{");
            //
            //                writer.Write(" new ");
            //
            //                var rCount = array.Type.RankSpecifiers.Count;
            //                for (int i = 0; i < rCount; i++)
            //                {
            //                    writer.Write("Array_T<");
            //
            //                    var typeInfo = TypeProcessor.GetTypeInfo(array.Type.ElementType);
            //
            //                    if ((i + 1) == rCount)
            //                    {
            //                        if (typeInfo.Type != null && (typeInfo.Type.IsValueType == false))
            //                            writer.Write("");
            //                        // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
            //
            //                        writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
            //
            //
            //                    }
            //
            //                }
            //                for (int i = 0; i < rCount; i++)
            //                {
            //                    if ((i > 0) && rCount > 1)
            //                        writer.Write("");
            //                    writer.Write(">");
            //
            //
            //                }
            //
            //                writer.Write("(");
            //                writer.Write("{");
            //                bool first = true;
            //                foreach (var expression in array.Initializer.Expressions)
            //                {
            //                    if (first)
            //                        first = false;
            //                    else
            //                        writer.Write(", ");
            //
            //                    Core.Write(writer, expression);
            //                }
            //
            //                writer.Write("})");
            //            }
            //            else
            //            {
            //
            //
            //
            //
            //
            //
            //                // int.TryParse(rankExpression != null ? rankExpression.ToString() : "0", out sizeInteger);
            //
            //
            //                writer.Write(" new ");
            //
            //                var rCount = array.Type.RankSpecifiers.Count;
            //                for (int i = 0; i < rCount; i++)
            //                {
            //                    writer.Write("Array_T<");
            //
            //                    var type = TypeProcessor.GetTypeInfo(array.Type.ElementType);
            //
            //                    if ((i + 1) == rCount)
            //                    {
            //                        if (type.Type != null && (type.Type.IsValueType == false))
            //                            writer.Write("");
            //                        // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
            //
            //                        writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
            //
            //
            //                    }
            //
            //                }
            //                for (int i = 0; i < rCount; i++)
            //                {
            //                    if ((i > 0) && rCount > 1)
            //                        writer.Write("");
            //                    writer.Write(">");
            //
            //
            //                }
            //
            //
            //
            //
            //                writer.Write("(");
            //
            //                var first = true;
            //                foreach (var dimensions in fullDimension)
            //                {
            //                    if (dimensions is OmittedArraySizeExpressionSyntax)
            //                        continue;
            //                    if (first)
            //                        first = false;
            //                    else
            //                        writer.Write(" + ");
            //
            //                    Core.Write(writer, dimensions);
            //                }
            //
            //                writer.Write(")");
            //
            //                //                writer.Write("new Array_T<");
            //                //
            //                //
            //                //
            //                //                var symbol =Program.GetModel(array).GetDeclaredSymbol(array.Type.ElementType);
            //                //
            //                //                var lsymbol = symbol as ILocalSymbol;
            //                //
            //                //                if (lsymbol != null && (lsymbol.Type.IsValueType == false))
            //                //                    writer.Write(""); // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
            //                //
            //                //                writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
            //                //                                writer.Write(">("+fullDimension+")");
            //
            //                // Core.Write(writer, array.Type.RankSpecifiers.Single().Sizes.Single());
            //                // writer.Write(")");
            //
            //                //  if (array.Initializer != null)
            //                //    throw new Exception("Initalizers along with array sizes are not supported - please use a size or an initializer " + Utility.Descriptor(array));
            //
            //
            //
            //                //                writer.Write("new ");
            //                //                writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
            //                //                writer.Write("[]{");
            //                //                Core.Write(writer, array.Type.RankSpecifiers.Single().Sizes.Single());
            //                //                writer.Write("}");
            //            }
        }
Esempio n. 23
0
 public static void Go(OutputWriter writer, SimpleLambdaExpressionSyntax expression)
 {
     Go(writer, new[] { expression.Parameter }, expression.Body, TypeProcessor.GetTypeInfo(expression));
 }
Esempio n. 24
0
        private static void ProcessInitializer(OutputWriter writer, LocalDeclarationStatementSyntax declaration,
                                               VariableDeclaratorSyntax variable)
        {
            var initializer = variable.Initializer;

            if (initializer != null)
            {
                if (initializer.Value.CSharpKind() == SyntaxKind.CollectionInitializerExpression)
                {
                    return;
                }

                var value                  = initializer.Value;
                var initializerType        = TypeProcessor.GetTypeInfo(value);
                var memberaccessexpression = value as MemberAccessExpressionSyntax;
                var nameexpression         = value as NameSyntax;
                var nullAssignment         = value.ToFullString().Trim() == "null";
                var shouldBox              = initializerType.Type != null && initializerType.Type.IsValueType &&
                                             !initializerType.ConvertedType.IsValueType;
                var shouldUnBox = initializerType.Type != null && !initializerType.Type.IsValueType &&
                                  initializerType.ConvertedType.IsValueType;
                var isname             = value is NameSyntax;
                var ismemberexpression = value is MemberAccessExpressionSyntax ||
                                         (isname &&
                                          TypeProcessor.GetSymbolInfo(value as NameSyntax).Symbol.Kind ==
                                          SymbolKind.Method);
                var isdelegateassignment = ismemberexpression &&
                                           initializerType.ConvertedType.TypeKind == TypeKind.Delegate;
                var isstaticdelegate = isdelegateassignment &&
                                       ((memberaccessexpression != null &&
                                         TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) ||
                                        (isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic));

                //Do we have an implicit converter, if so, use it
                if (shouldBox || shouldUnBox)
                {
//			        if (shouldUnBox)
//			        {
//			            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 = initializerType.Type.GetImplicitCoversionOp(initializerType.Type,initializerType.ConvertedType);
////                            initializerType.Type.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType);
//
//			            if (correctConverter == null)
//			            {
//			                useType = false;
//                            correctConverter =
//                            initializerType.ConvertedType.GetImplicitCoversionOp(initializerType.Type, initializerType.ConvertedType); //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType);
//                        }
//
//			            if (correctConverter != null)
//			            {
//                            if(useType)
//			                writer.Write(TypeProcessor.ConvertType(initializerType.Type) +"."+ "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType));
//                            else
//                            {
//			                writer.Write(TypeProcessor.ConvertType(initializerType.ConvertedType) +"."+ "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType));
//
//                            }
//                            writer.Write("(");
//                            Core.Write(writer, value);
//                            writer.Write(")");
//                            return;
//                        }
//                    }
//			        if (shouldBox)
                    {
                        bool useType          = true;
                        var  correctConverter =
                            initializerType.Type.GetImplicitCoversionOp(initializerType.ConvertedType,
                                                                        initializerType.Type);
                        //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.ConvertedType && h.Parameters[0].Type == initializerType.Type);

                        if (correctConverter == null)
                        {
                            useType          = false;
                            correctConverter =
                                initializerType.ConvertedType.GetImplicitCoversionOp(initializerType.ConvertedType,
                                                                                     initializerType.Type);
                            //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.ConvertedType && h.Parameters[0].Type == initializerType.Type);
                        }

                        if (correctConverter != null)
                        {
                            if (useType)
                            {
                                writer.Write(TypeProcessor.ConvertType(initializerType.Type) + "." + "op_Implicit_" +
                                             TypeProcessor.ConvertType(correctConverter.ReturnType));
                            }
                            else
                            {
                                writer.Write(TypeProcessor.ConvertType(initializerType.ConvertedType) + "." +
                                             "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType));
                            }
                            writer.Write("(");
                            Core.Write(writer, value);
                            writer.Write(")");
                            return;
                        }
                    }
                }

                if (nullAssignment)
                {
                    writer.Write("null");
                    return;
                }
                if (shouldBox)
                {
                    //Box
                    writer.Write("BOX!(" + TypeProcessor.ConvertType(initializerType.Type) + ")(");
                    //When passing an argument by ref or out, leave off the .Value suffix
                    Core.Write(writer, value);
                    writer.Write(")");
                    return;
                }
                if (shouldUnBox)
                {
                    //UnBox
                    writer.Write("cast!(" + TypeProcessor.ConvertType(initializerType.Type) + ")(");
                    Core.Write(writer, value);
                    writer.Write(")");
                }
                if (isdelegateassignment)
                {
                    var createNew  = !(value is ObjectCreationExpressionSyntax);
                    var typeString = TypeProcessor.ConvertType(initializerType.ConvertedType);

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

                    var isStatic = isstaticdelegate;
                    if (isStatic)
                    {
                        writer.Write("__ToDelegate(");
                    }
                    writer.Write("&");

                    Core.Write(writer, value);
                    if (isStatic)
                    {
                        writer.Write(")");
                    }

                    if (createNew)
                    {
                        writer.Write(")");
                    }
                    return;
                }
                if (initializerType.Type == null && initializerType.ConvertedType == null)
                {
                    writer.Write("null");
                    return;
                }
                Core.Write(writer, value);
            }
            else
            {
                writer.Write(TypeProcessor.DefaultValue(declaration.Declaration.Type));
            }
        }
Esempio n. 25
0
        public static void Go(OutputWriter writer, ArrayCreationExpressionSyntax array)
        {
            //TODO: does this info just get discarded ?
            //   if (array.Type.RankSpecifiers.Count > 1 || array.Type.RankSpecifiers.Single().Sizes.Count > 1)
            //     throw new Exception("Multi-dimensional arrays are not supported " + Utility.Descriptor(array));

            //  var rankExpression = array.Type.RankSpecifiers.FirstOrDefault().Sizes.Single();
//            IEnumerable<ExpressionSyntax> fullDimension =
//                array.Type.RankSpecifiers.Select(o => o.Sizes).SelectMany(j=>j);

            if (array.Initializer != null)
            {
                var aType = TypeProcessor.GetTypeInfo(array).Type as IArrayTypeSymbol;
                //                writer.Write("new ");
                //                writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
                //                writer.Write("[]{");

                //                var statement = " new (smGC) ";
                // writer.Write(" new ");
                var type = "";

                if (aType.Rank == 1) // Jagged
                {
                    var rCount = array.Type.RankSpecifiers.Count;

                    for (int i = 0; i < rCount; i++)
                    {
                        type += ("Array_T!(");

                        var typeInfo = TypeProcessor.GetTypeInfo(array.Type.ElementType);

                        if ((i + 1) == rCount)
                        {
                            var isPtr      = typeInfo.Type != null && typeInfo.Type.IsValueType; // ? "" : "";
                            var typeString = TypeProcessor.ConvertType(typeInfo.Type) + " ";

                            // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack

                            //writer.Write(typeString);
                            type += typeString;
                        }
                    }
                    for (int i = 0; i < rCount; i++)
                    {
                        if ((i > 0) && rCount > 1)
                        {
                            type = type;
                        }
                        type += (")");
                    }
                }
                else
                {
                    type += "Array_T!(" + TypeProcessor.ConvertType(array.Type.ElementType)
                            /* + Enumerable.Range (0, aType.Rank-1).Select (l => "[]").Aggregate ((a, b) => a + b).ToString () */ +
                            ")";

//					var typeInfo = TypeProcessor.GetTypeInfo (array.Type.ElementType);
                }
//				if (type.ConvertedType.TypeKind == Microsoft.CodeAnalysis.TypeKind.TypeParameter)
//					writer.Write (" __TypeNew!(" + type + ")([");
//				else
                //{
                writer.Write("new  " + type);

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

                array.Initializer.WriteArrayInitializer(writer, array.Type);

                writer.Write(")");
            }
            else
            {
                // int.TryParse(rankExpression != null ? rankExpression.ToString() : "0", out sizeInteger);

                //  writer.Write(" new ");
                var typeStr = "";

                var rCount = array.Type.RankSpecifiers.Count;
                for (int i = 0; i < rCount; i++)
                {
                    typeStr += ("Array_T!(");

                    var type = TypeProcessor.GetTypeInfo(array.Type.ElementType);

                    if ((i + 1) == rCount)
                    {
//                    if (type.Type != null && (type.Type.IsValueType == false))
//                            typeStr += ("");
                        // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack

                        typeStr += (TypeProcessor.ConvertType(array.Type.ElementType));
                    }
                }
                for (int i = 0; i < rCount; i++)
                {
//                    if ((i > 0) && rCount > 1)
//                        typeStr+=("");
                    typeStr += (")");
                }

                writer.Write("new " + typeStr);
                writer.Write("(");

                array.Initializer.WriteArrayInitializer(writer, array.Type);

                writer.Write(")");

                //                writer.Write("new Array_T!(");
                //
                //
                //
                //                var symbol =Program.GetModel(array).GetDeclaredSymbol(array.Type.ElementType);
                //
                //                var lsymbol = symbol as ILocalSymbol;
                //
                //                if (lsymbol != null && (lsymbol.Type.IsValueType == false))
                //                    writer.Write(""); // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
                //
                //                writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
                //                                writer.Write(">("+fullDimension+")");

                // Core.Write(writer, array.Type.RankSpecifiers.Single().Sizes.Single());
                // writer.Write(")");

                //  if (array.Initializer != null)
                //    throw new Exception("Initalizers along with array sizes are not supported - please use a size or an initializer " + Utility.Descriptor(array));

                //                writer.Write("new ");
                //                writer.Write(TypeProcessor.ConvertType(array.Type.ElementType));
                //                writer.Write("[]{");
                //                Core.Write(writer, array.Type.RankSpecifiers.Single().Sizes.Single());
                //                writer.Write("}");
            }
        }
Esempio n. 26
0
        public static void WritePrefix(OutputWriter writer, PrefixUnaryExpressionSyntax expression)
        {
            var isProperty = false;

            var symbol = TypeProcessor.GetSymbolInfo(expression.Operand);

            if (symbol.Symbol is IPropertySymbol)
            {
                isProperty = true;
            }


            if (isProperty)
            {
                var symbolName = Core.WriteString(expression.Operand).ToString().Trim();
                switch (expression.OperatorToken.RawKind)
                {
                case (int)SyntaxKind.MinusMinusToken:
                    if ((symbol.Symbol as IPropertySymbol).IsIndexer)
                    {
                        writer.Write(String.Format("/*--{0}*/((){{ auto v = {0};{0}=(--v);return v;}})()", symbolName));
                    }
                    else
                    {
                        writer.Write(String.Format("/*--{0}*/((){{ auto v = {0};{0}(--v);return v;}})()", symbolName));
                    }
                    break;

                case (int)SyntaxKind.PlusPlusToken:
                    if ((symbol.Symbol as IPropertySymbol).IsIndexer)
                    {
                        writer.Write(String.Format("/*++{0}*/((){{ auto v = {0};{0}=(++v);return v;}})()", symbolName));
                    }
                    else
                    {
                        writer.Write(String.Format("/*++{0}*/((){{ auto v = {0};{0}(++v);return v;}})()", symbolName));
                    }

                    break;

                default:
                    writer.Write(expression.OperatorToken.Text);

                    Core.Write(writer, expression.Operand);


                    break;
                }
            }
            else
            {
                //			Console.WriteLine (expression.ToFullString());
                //				if (expression.OperatorToken.RawKind == (decimal)SyntaxKind.MinusMinusToken)
                //				{
                //
                //					writer.Write ("--");
                //					Core.Write (writer, expression.Operand);
                //				}
                //				else if (expression.OperatorToken.RawKind == (decimal)SyntaxKind.PlusPlusToken)
                //				{
                //					writer.Write ("++");
                //					Core.Write (writer, expression.Operand);
                //				}
                //				else
                //				{
                //					//TODO: cannot take addresses of structs in 32/64-bit mode and subtract them ... really weird d-bug ... leads to wrong math ... should we do a shift ?
                ////				if (expression.OperatorToken.CSharpKind () == SyntaxKind.AmpersandToken) // Take address
                ////				{
                ////					var memberAccess = expression.Operand as MemberAccessExpressionSyntax;
                ////					var simpleName = expression.Operand as NameSyntax;
                ////
                ////					TypeInfo typeOperand;
                ////
                ////					if (memberAccess != null)
                ////						typeOperand = TypeProcessor.GetTypeInfo (memberAccess.Expression);
                ////					if (simpleName != null)
                ////						typeOperand = TypeProcessor.GetTypeInfo (simpleName);
                ////
                ////					var failed = true;
                //
                ////					if (memberAccess != null)
                ////					{
                ////						 failed = false;
                ////						if (typeOperand.Type.TypeKind == TypeKind.Struct)
                ////						{
                ////							var sNAme = (memberAccess.Expression as SimpleNameSyntax).Identifier;
                ////
                ////							writer.Write ("(cast(ulong)(&" + sNAme.ToFullString () + ") + (");
                ////							Core.Write (writer, expression.Operand);
                ////							writer.Write (".offsetof))");
                ////						}
                ////						else
                ////							failed = true;
                ////					}
                ////					else if (simpleName != null)
                ////					{
                ////						failed = false;
                ////
                ////						if (typeOperand.Type.TypeKind == TypeKind.Struct)
                ////						{
                ////							writer.Write ("(&" + simpleName.ToFullString () + " + (");
                ////							Core.Write (writer, expression.Operand);
                ////							writer.Write (".offsetof))");
                ////						}
                ////						else
                ////							failed = true;
                ////					}
                ////
                ////					if(failed)
                ////					{
                ////						writer.Write (expression.OperatorToken.ToString ());
                ////						Core.Write (writer, expression.Operand);
                ////					}
                ////
                ////				}
                ////				else
                //					{
                //						writer.Write (expression.OperatorToken.ToString ());
                //						Core.Write (writer, expression.Operand);
                //					}
                //				}

                //D's unary operators are a bit different from C# .. i.e. not static
                bool hasOpIncrement = false;
                bool hasOpDecrement = false;

                var typeSymbol = TypeProcessor.GetTypeInfo(expression.Operand).Type;
                if (typeSymbol != null)
                {
                    hasOpIncrement = typeSymbol.GetMembers("op_Increment").Any();

                    hasOpDecrement = typeSymbol.GetMembers("op_Decrement").Any();
                }

                switch (expression.OperatorToken.RawKind)
                {
                case (int)SyntaxKind.MinusMinusToken:
                    if (hasOpDecrement)
                    {
                        var texpression = Core.WriteString(expression.Operand);

                        writer.Write(String.Format("/*--{0}*/((){{ auto v = {0};{0}={0}.op_Decrement({0});return v;}})()", texpression));
                    }
                    else
                    {
                        writer.Write("--");
                        Core.Write(writer, expression.Operand);
                    }
                    break;

                case (int)SyntaxKind.PlusPlusToken:
                    if (hasOpIncrement)
                    {
                        var texpression = Core.WriteString(expression.Operand);

                        writer.Write(String.Format("/*++{0}*/((){{ auto v = {0};{0}={0}.op_Increment({0});return v;}})()", texpression));
                    }
                    else
                    {
                        writer.Write("++");
                        Core.Write(writer, expression.Operand);
                    }
                    break;

                default:
                    writer.Write(expression.OperatorToken.Text);

                    Core.Write(writer, expression.Operand);

                    // throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " +
                    //Utility.Descriptor(expression));
                    break;
                }
            }
        }
Esempio n. 27
0
 public static void Go(OutputWriter writer, ParenthesizedLambdaExpressionSyntax expression)
 {
     Go(writer, expression.ParameterList.Parameters, expression.Body, TypeProcessor.GetTypeInfo(expression));
 }
Esempio n. 28
0
        public static void WriteIt(OutputWriter writer, MethodDeclarationSyntax method, bool isProxy = true)
        {
            writer.WriteLine();
            var methodSymbol = (IMethodSymbol)TypeProcessor.GetDeclaredSymbol(method);
            var methodName   = OverloadResolver.MethodName(methodSymbol);

            var pinvokeAttributes = method.GetAttribute(Context.DllImport);

            // Fix this to actually look for the type, not just by name ...

            //TODO: Improve partial class / method support -- partials classes work, methods need minor work ...
            if (method.Modifiers.Any(SyntaxKind.PartialKeyword) && method.Body == null)
            {
                //We only want to render out one of the two partial methods.  If there's another, skip this one.
                if (Context.Instance.Partials.SelectMany(o => o.Syntax.As <ClassDeclarationSyntax>().Members)
                    .OfType <MethodDeclarationSyntax>()
                    .Except(method).Any(o => o.Identifier.ValueText == method.Identifier.ValueText))
                {
                    return;
                }
            }

            bool isoverride = ShouldUseOverrideKeyword(method, methodSymbol);

            var accessString = "";

            if (isoverride)
            {
                accessString += (" override ");
            }

            var isInterface = method.Parent is InterfaceDeclarationSyntax;

            if (methodName == "Main" /*&& method.Modifiers.Any(SyntaxKind.PublicKeyword)*/ &&
                method.Modifiers.Any(SyntaxKind.StaticKeyword))
            {
                accessString = ("public ");

                accessString += ("static ");

                var methodCall = methodSymbol.ContainingNamespace.FullName() + "." +
                                 methodSymbol.ContainingType.FullName() +
                                 "." + methodName + (method.ParameterList.Parameters.Count < 1 ? "();" : "(null);");
                //: "(new Array_T!(String)(args));"); // for now args not supported
                Context.Instance.EntryMethod = methodCall;
            }

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

                if (method.Modifiers.Any(SyntaxKind.PrivateKeyword))
                {
                    accessString += ("private ");
                }

                //	            if (method.Modifiers.Any(SyntaxKind.VirtualKeyword) || isInterface)
                //	                writer.Write("virtual ");

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

                if (method.Modifiers.Any(SyntaxKind.AbstractKeyword))
                {
                    accessString += (" abstract ");
                }

                if (method.Modifiers.Any(SyntaxKind.StaticKeyword))
                {
                    accessString += ("static ");
                }
            }

            //	        if (isInterface)
            //	        {
            //                writer.IsInterface = true;
            //	        }

            var returnTypeString      = TypeProcessor.ConvertType(method.ReturnType) + " ";
            var methodSignatureString = "";

            if (method.ReturnType.ToString() == "void")
            {
                returnTypeString = ("void ");
            }
            else
            //  bool returnsVoid = method.ReturnType.ToString() == "void";
            //if (!returnsVoid)
            {
                var typeSymbol = TypeProcessor.GetTypeInfo(method.ReturnType).Type;

                //   var isPtr = typeSymbol != null && (typeSymbol.IsValueType || typeSymbol.TypeKind == TypeKind.TypeParameter) ? "" : "";
                //     var typeString = TypeProcessor.ConvertType(method.ReturnType) + isPtr + " ";

                //	            writer.Write(typeString);
                //	            writer.HeaderWriter.Write(typeString);

                var isPtr = typeSymbol != null &&
                            (!typeSymbol.IsValueType || typeSymbol.TypeKind == TypeKind.TypeParameter);
            }

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

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

            //			var typenameI = Regex.Replace (TypeProcessor.ConvertType (interfaceMethod.ContainingType), @" ?!\(.*?\)", string.Empty);

            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)
                {
                    methodSignatureString += ("");
                }
                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('.');
                    }
                    methodName = (typenameI + "_") + methodName;
                }
            }

            //            var explicitHeaderNAme = "";
            //FIX ME: To support explicits, all method calls are going to be prequalified with the interface name, lets just hope we dont have similar interfaces
            //
            // if (methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation)
            //	        {
            //	           // var implementations = methodSymbol.ExplicitInterfaceImplementations[0];
            //	            if (implementations != null)
            //	            {
            //	              //  explicitHeaderNAme = implementations.Name;
            //                     methodName = TypeProcessor.ConvertType(implementations.ReceiverType) + "_" +implementations.Name; //Explicit fix ?
            //
            //	                //			writer.Write(methodSymbol.ContainingType + "." + methodName);
            //	                //Looks like internal classes are not handled properly here ...
            //	            }
            //	        }
            // methodName = methodName.Replace(methodSymbol.ContainingNamespace.FullName() + ".", methodSymbol.ContainingNamespace.FullName().Replace(".", "::") + "::");
            //           (methodSymbol as).Is
            //	        (methodSymbol as Microsoft.CodeAnalysis.CSharp.Symbols.SourceMethodSymbol);
            if (method.Modifiers.Any(SyntaxKind.NewKeyword))
            {
                methodName += "_";
            }

            //            writer.Write( TypeProcessor.ConvertType(methodSymbol.ContainingType)+ "." + methodName); //Dealting with explicit VMT7
            // writer.Write(!String.IsNullOrEmpty(explicitHeaderNAme)? explicitHeaderNAme : methodName);
            //            writer.Write(methodName);
            methodSignatureString += methodName;

            if (method.TypeParameterList != null)
            {
                var genericArgs = method.TypeParameterList.Parameters.ToList();

                //				if (genericArgs.Count > 0)
                //				{
                //					writer.Write("( ");
                //					writer.Write(string.Join(" , ", genericArgs.Select(o => " " + o)));
                //					writer.Write(" )\r\n");
                //				}

                if (genericArgs.Count > 0) // && !methodSymbol.ContainingType.IsGenericType) // doesnt matter
                {
                    methodSignatureString += ("(");
                    methodSignatureString += (string.Join(",", genericArgs.Select(o => " " + o)));
                    methodSignatureString += (")");
                }
            }

            var @params = GetParameterListAsString(method.ParameterList);

            var constraints = "";

            if (method.ConstraintClauses.Count > 0)
            {
                constraints += (" if (");
                bool isFirst = true;
                foreach (var constraint in method.ConstraintClauses)
                {
                    foreach (var condition in constraint.Constraints)
                    {
                        string dlangCondition = condition.ToString();

                        if (dlangCondition == "new()")
                        {
                            continue;
                        }
                        if (dlangCondition == "class") // TODO: is there a better way to do this ?
                        {
                            dlangCondition = "NObject";
                        }

                        if (dlangCondition == "struct")
                        {
                            constraints += ((isFirst ? "" : "&&") + " !is(" + constraint.Name + " : NObject)");
                        }
                        else
                        {
                            constraints += ((isFirst ? "" : "&&") + " is(" + constraint.Name + " : " + dlangCondition +
                                            ")");
                        }

                        isFirst = false;

                        //								Console.WriteLine (condition);
                    }
                }

                constraints += (")");
            }

            if (isInterface || method.Modifiers.Any(SyntaxKind.AbstractKeyword))
            {
                writer.WriteLine(accessString + returnTypeString + methodSignatureString + @params + constraints + ";");

                return;
            }

            writer.WriteLine(accessString + returnTypeString + methodSignatureString + @params + constraints);

            writer.OpenBrace();

            if (isProxy)
            {
                @params = GetParameterListAsString(method.ParameterList, false);

                if (method.ReturnType.ToString() == "void")
                {
                    writer.WriteLine("Value." + methodName + @params + ";");
                }
                else
                {
                    writer.WriteLine("return Value." + methodName + @params + ";");
                }
            }
            else
            {
                if (method.Body != null)
                {
                    foreach (var statement in method.Body.Statements)
                    {
                        Core.Write(writer, statement);
                    }

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

                if (pinvokeAttributes != null)
                {
                    WritePInvokeMethodBody.Go(writer, methodName, methodSymbol, pinvokeAttributes);
                }
            }

            writer.CloseBrace();
        }
        private static void ProcessInitializer(OutputWriter writer, VariableDeclarationSyntax declaration,
                                               VariableDeclaratorSyntax variable)
        {
            var initializer = variable.Initializer;

            if (initializer != null)
            {
                if (CSharpExtensions.CSharpKind(initializer.Value) == SyntaxKind.CollectionInitializerExpression)
                {
                    return;
                }
                var value                  = initializer.Value;
                var initializerType        = TypeProcessor.GetTypeInfo(value);
                var memberaccessexpression = value as MemberAccessExpressionSyntax;
                var nameexpression         = value as NameSyntax;
                var nullAssignment         = value.ToFullString().Trim() == "null";
                var shouldBox              = initializerType.Type != null && (initializerType.Type.IsValueType) &&
                                             !initializerType.ConvertedType.IsValueType;
                var shouldUnBox = initializerType.Type != null && !initializerType.Type.IsValueType &&
                                  initializerType.ConvertedType.IsValueType;
                var isname             = value is NameSyntax;
                var ismemberexpression = value is MemberAccessExpressionSyntax ||
                                         (isname &&
                                          TypeProcessor.GetSymbolInfo(value as NameSyntax).Symbol.Kind ==
                                          SymbolKind.Method);
                var isdelegateassignment = ismemberexpression &&
                                           initializerType.ConvertedType.TypeKind == TypeKind.Delegate;
                var isstaticdelegate = isdelegateassignment &&
                                       ((memberaccessexpression != null &&
                                         TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) ||
                                        (isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic));
                var shouldCast = initializerType.Type != initializerType.ConvertedType &&
                                 initializerType.ConvertedType != null;

                if (nullAssignment)
                {
                    if (initializerType.Type != null) //Nullable Support
                    {
                        if (initializerType.Type.Name == "Nullable")
                        {
                            var atype = TypeProcessor.ConvertType(initializerType.Type);
                            writer.Write(atype + "()");
                        }
                    }
                    else
                    {
                        writer.Write("null");
                    }

                    return;
                }
                if (shouldBox)
                {
//Box
                    writer.Write("BOX!(" + TypeProcessor.ConvertType(initializerType.Type) + ")(");
//When passing an argument by ref or out, leave off the .Value suffix
                    Core.Write(writer, value);
                    writer.Write(")");
                    return;
                }
                if (shouldUnBox)
                {
                    writer.Write("cast(" + TypeProcessor.ConvertType(initializerType.Type) + ")(");
                    Core.Write(writer, value);
                    writer.Write(")");
                    return;
                }
                if (initializer.Parent.Parent.Parent is FixedStatementSyntax) // Fixed is a bit special
                {
//TODO write a better fix
                    var type = TypeProcessor.GetTypeInfo(declaration.Type);

                    writer.Write("cast(" + TypeProcessor.ConvertType(type.Type) + ")(");
                    Core.Write(writer, value);
                    writer.Write(")");
                    return;
                }
                if (isdelegateassignment)
                {
                    var typeString = TypeProcessor.ConvertType(initializerType.ConvertedType);

                    var createNew = !(value is ObjectCreationExpressionSyntax);

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

                    var isStatic = isstaticdelegate;
                    //                    if (isStatic)
                    //                        writer.Write("__ToDelegate(");
                    MemberUtilities.WriteMethodPointer(writer, value);
                    //                    if (isStatic)
                    //                        writer.Write(")");

                    if (createNew)
                    {
                        writer.Write(")");
                    }
                    return;
                }
                if (initializerType.Type == null && initializerType.ConvertedType == null)
                {
                    writer.Write("null");
                    return;
                }
                Core.Write(writer, value);
            }
            else
            {
                writer.Write(TypeProcessor.DefaultValue(declaration.Type));
            }
        }
Esempio n. 30
0
        public static void WritePostfix(OutputWriter writer, PostfixUnaryExpressionSyntax expression)
        {
            var isProperty = false;

            var symbol = TypeProcessor.GetSymbolInfo(expression.Operand);

            if (symbol.Symbol is IPropertySymbol)
            {
                isProperty = true;
            }


            if (isProperty)
            {
                var symbolName = Core.WriteString(expression.Operand);
                switch (expression.OperatorToken.RawKind)
                {
                case (int)SyntaxKind.MinusMinusToken:
                    if ((symbol.Symbol as IPropertySymbol).IsIndexer)
                    {
                        writer.Write(String.Format("/*{0}--*/((){{auto v={0};auto y=v;{0}=(--y);return v;}})()", symbolName));
                    }
                    else
                    {
                        writer.Write(String.Format("/*{0}--*/((){{auto v={0};auto y=v;{0}(--y);return v;}})()", symbolName));
                    }

                    break;

                case (int)SyntaxKind.PlusPlusToken:
                    if ((symbol.Symbol as IPropertySymbol).IsIndexer)
                    {
                        writer.Write(String.Format("/*{0}++*/((){{auto v={0},y={0};{0}=(++y);return v;}})()", symbolName));
                    }
                    else
                    {
                        writer.Write(String.Format("/*{0}++*/((){{auto v={0},y={0};{0}(++y);return v;}})()", symbolName));
                    }

                    break;

                default:
                    Core.Write(writer, expression.Operand);
                    writer.Write(expression.OperatorToken.Text);
                    break;
                }
            }
            else
            {
                //            if (expression.Operand is MemberAccessExpressionSyntax)
                //            {
                //                var memberAccess = expression.Operand as MemberAccessExpressionSyntax;
                //                var typeInfo = TypeProcessor.GetSymbolInfo(memberAccess.Name);

                //                if (typeInfo.Symbol.Kind == SymbolKind.Property)
                //                {
                //                    switch (expression.OperatorToken.RawKind)
                //                    {
                //                        case (int)SyntaxKind.MinusMinusToken:
                //                          var refactored=  SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression,
                //                                expression.Operand,
                //                                SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, expression.Operand,
                //                                    SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,SyntaxFactory.Literal(-1)))
                //                                ).NormalizeWhitespace();
                //                            Core.Write(writer,refactored);
                //                            break;
                //                        case (int)SyntaxKind.PlusPlusToken:
                //                            var refactored1 = SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression,
                //                                 expression.Operand,
                //                                 SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, expression.Operand,
                //                                     SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(+1)))
                //                                 ).NormalizeWhitespace();
                //                            Core.Write(writer, refactored1);
                //                            break;
                //                        default:
                //                            throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " +
                //                                                Utility.Descriptor(expression));
                //                    }
                //                }
                //                else
                //                {
                //                    switch (expression.OperatorToken.RawKind)
                //                    {
                //                        case (int)SyntaxKind.MinusMinusToken:
                //                            Core.Write(writer, expression.Operand);
                //                            writer.Write("--");
                //                            break;
                //                        case (int)SyntaxKind.PlusPlusToken:
                //                            Core.Write(writer, expression.Operand);
                //                            writer.Write("++");
                //                            break;
                //                        default:
                //                            throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " +
                //                                                Utility.Descriptor(expression));
                //                    }
                //                }
                //
                //            }
                //            else
                //            {
                //D's unary operators are a bit different from C# .. i.e. not static
                bool hasOpIncrement = false;
                bool hasOpDecrement = false;

                var typeSymbol = TypeProcessor.GetTypeInfo(expression.Operand).Type;
                if (typeSymbol != null)
                {
                    hasOpIncrement = typeSymbol.GetMembers("op_Increment").Any();

                    hasOpDecrement = typeSymbol.GetMembers("op_Decrement").Any();
                }

                switch (expression.OperatorToken.RawKind)
                {
                case (int)SyntaxKind.MinusMinusToken:
                    if (hasOpDecrement)
                    {
                        var texpression = Core.WriteString(expression.Operand);

                        writer.Write(String.Format("/*{0}--*/({0}={0}.op_Decrement({0}))", texpression));
                    }
                    else
                    {
                        Core.Write(writer, expression.Operand);
                        writer.Write("--");
                    }
                    break;

                case (int)SyntaxKind.PlusPlusToken:
                    if (hasOpIncrement)
                    {
                        var texpression = Core.WriteString(expression.Operand);

                        writer.Write(String.Format("/*{0}--*/({0}={0}.op_Increment({0}))", texpression));
                    }
                    else
                    {
                        Core.Write(writer, expression.Operand);
                        writer.Write("++");
                    }
                    break;

                default:
                    throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " +
                                        Utility.Descriptor(expression));
                }
            }
//            }
        }