Example #1
0
        public static void Write(ScalaWriter writer, SyntaxNode node, bool isConst = false)
        {
            TriviaProcessor.ProcessNode(writer, node);

            if (Program.DoNotWrite.ContainsKey(node))
            {
                return;
            }

            var    exprOpt     = node as ExpressionSyntax;
            string postFactory = null;

            if (exprOpt != null)
            {
                var type = Program.GetModel(node).GetTypeInfo(exprOpt);

                if (type.Type != null && type.Type.SpecialType == SpecialType.System_Byte && type.ConvertedType.SpecialType != SpecialType.System_Byte && Utility.IsNumeric(type.ConvertedType))
                {
                    //Bytes are signed in the JVM, so we have to take care when up-converting them
                    writer.Write("System.CsScala.ByteTo");
                    writer.Write(TypeProcessor.ConvertType(type.ConvertedType));
                    writer.Write("(");
                    postFactory = ")";
                }
            }


            Factory(writer, node, isConst);
            writer.Write(postFactory);
        }
        public static void WriteConstructorsHelper(IEnumerable <INamedTypeSymbol> allTypes)
        {
            foreach (var t in allTypes.Select(o => o.ContainingNamespace.FullNameWithDot() + WriteType.TypeName(o)))
            {
                AllTypes.Add(t);
            }

            if (StaticConstructors.Count == 0)
            {
                return; //no need for it.
            }
            using (var writer = new ScalaWriter("CsRoot", "Constructors"))
            {
                writer.WriteLine(@"package CsRoot;
/*
This file lists all the static constructors.  Scala doesn't have the same concept of static constructors as C#, so CsScala generated cctor() methods.  You must call these manually.  If you call Constructors.init(), all static constructors will be called at once and you won't have to worry about calling each one manually.
*/");

                //foreach (var type in AllTypes.OrderBy(o => o))
                //	writer.WriteLine("import " + type + ";");

                writer.WriteLine("object Constructors");
                writer.WriteOpenBrace();

                writer.WriteLine("def init()");
                writer.WriteOpenBrace();
                foreach (var cctor in StaticConstructors.OrderBy(o => o))
                {
                    writer.WriteLine(cctor + ".cctor();");
                }
                writer.WriteCloseBrace();
                writer.WriteCloseBrace();
            }
        }
Example #3
0
        public static void Go(ScalaWriter writer, IfStatementSyntax ifStatement, bool indent = true)
        {
            if (indent)
            {
                writer.WriteIndent();
            }

            writer.Write("if (");
            Core.Write(writer, ifStatement.Condition);
            writer.Write(")\r\n");

            Core.WriteStatementAsBlock(writer, ifStatement.Statement);

            if (ifStatement.Else != null)
            {
                writer.WriteIndent();
                writer.Write("else");

                if (ifStatement.Else.Statement is BlockSyntax)
                {
                    writer.Write("\r\n");
                    Core.WriteBlock(writer, ifStatement.Else.Statement.As <BlockSyntax>());
                }
                else if (ifStatement.Else.Statement is IfStatementSyntax)
                {
                    writer.Write(" ");
                    WriteIfStatement.Go(writer, ifStatement.Else.Statement.As <IfStatementSyntax>(), false);
                }
                else
                {
                    writer.Write("\r\n");
                    Core.WriteStatementAsBlock(writer, ifStatement.Else.Statement);
                }
            }
        }
        public static void Go(ScalaWriter writer, ImplicitArrayCreationExpressionSyntax array)
        {
            writer.Write("Array");

            //var t = Program.GetModel(array).GetTypeInfo(array).Type;

            //if (t is IArrayTypeSymbol)
            //{
            //    writer.Write("[");
            //    writer.Write(TypeProcessor.ConvertType(t.As<IArrayTypeSymbol>().ElementType));
            //    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(")");
        }
Example #5
0
        public static void Go(ScalaWriter writer, SyntaxTokenList modifiers, string name, TypeSyntax type, EqualsValueClauseSyntax initializerOpt = null)
        {
            writer.WriteIndent();

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

            WriteFieldModifiers(writer, modifiers);
            if (isConst)
            {
                writer.Write("final val ");
            }
            else
            {
                writer.Write("var ");
            }

            writer.Write(name);
            writer.Write(TypeProcessor.ConvertTypeWithColon(type));
            writer.Write(" = ");

            if (initializerOpt != null)
            {
                Core.Write(writer, initializerOpt.Value);
            }
            else
            {
                writer.Write(TypeProcessor.DefaultValue(type));
            }

            writer.Write(";");
            writer.WriteLine();
        }
Example #6
0
 public static void WriteFieldModifiers(ScalaWriter writer, SyntaxTokenList modifiers)
 {
     if (modifiers.Any(SyntaxKind.PrivateKeyword))
     {
         writer.Write("private ");
     }
 }
Example #7
0
        public static void Go(ScalaWriter writer, ElementAccessExpressionSyntax expression)
        {
            var typeStr = TypeProcessor.GenericTypeName(Program.GetModel(expression).GetTypeInfo(expression.Expression).Type);
            var trans   = ElementAccessTranslation.Get(typeStr);

            Core.Write(writer, expression.Expression);

            if (trans != null)
            {
                writer.Write(".");
                writer.Write(trans.ReplaceGet);
            }

            writer.Write("(");

            bool first = true;

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

                Core.Write(writer, argument.Expression);
            }
            writer.Write(")");
        }
Example #8
0
        /// <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(ScalaWriter 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 = Program.GetModel(invocationExpression).GetTypeInfo(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(")");
        }
Example #9
0
        public static void Go(ScalaWriter writer, ReturnStatementSyntax statement)
        {
            if (TypeState.Instance.InLambdaBreakable > 0)
            {
                if (statement.Expression != null)
                {
                    writer.WriteIndent();
                    writer.Write("__lambdareturn = ");
                    Core.Write(writer, statement.Expression);
                    writer.Write(";\r\n");
                }

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

                if (statement.Expression != null)
                {
                    writer.Write(" ");
                    Core.Write(writer, statement.Expression);
                }
                writer.Write(";\r\n");
            }
        }
Example #10
0
 public void WriteLoopClosing(ScalaWriter writer)
 {
     if (HasContinue)
     {
         writer.WriteCloseBrace();
     }
 }
Example #11
0
 public void WritePostLoop(ScalaWriter writer)
 {
     if (HasBreak)
     {
         writer.WriteCloseBrace();
     }
 }
Example #12
0
        public static void Go(ScalaWriter writer, IEnumerable <EnumMemberDeclarationSyntax> allChildren)
        {
            writer.Write("object ");
            writer.Write(TypeState.Instance.TypeName);
            writer.Write("\r\n");
            writer.WriteOpenBrace();

            int lastEnumValue = -1;

            var values = allChildren.Select(o => new { Syntax = o, Value = DetermineEnumValue(o, ref lastEnumValue) }).ToList();

            foreach (var value in values)
            {
                writer.WriteLine("final val " + WriteIdentifierName.TransformIdentifier(value.Syntax.Identifier.ValueText) + ":Int = " + value.Value + ";");
            }

            writer.WriteLine();
            writer.WriteLine(@"def ToString(n:java.lang.Integer):String = if (n == null) """" else ToString(n.intValue());");

            writer.WriteLine("def ToString(e:Int):String =");
            writer.WriteOpenBrace();
            writer.WriteLine("return e match");
            writer.WriteOpenBrace();

            foreach (var value in values)
            {
                writer.WriteLine("case " + value.Value + " => \"" + value.Syntax.Identifier.ValueText + "\";");
            }

            writer.WriteLine("case u => u.toString;");

            writer.WriteCloseBrace();
            writer.WriteCloseBrace();

            writer.WriteLine();
            writer.WriteLine("def Parse(s:String):Int =");
            writer.WriteOpenBrace();
            writer.WriteLine("return s match");
            writer.WriteOpenBrace();

            foreach (var value in values)
            {
                writer.WriteLine("case \"" + value.Syntax.Identifier.ValueText + "\" => " + value.Value + ";");
            }

            writer.WriteLine("case u => u.toInt;");

            writer.WriteCloseBrace();
            writer.WriteCloseBrace();

            writer.WriteLine();
            writer.WriteIndent();
            writer.Write("final val Values:Array[Int] = Array(");
            writer.Write(string.Join(", ", values.Select(o => o.Value.ToString())));
            writer.Write(");\r\n");


            writer.WriteCloseBrace();
        }
Example #13
0
        public static void Go(ScalaWriter writer, CastExpressionSyntax expression)
        {
            var model = Program.GetModel(expression);

            var symbol = model.GetSymbolInfo(expression);

            var castingFrom = model.GetTypeInfo(expression.Expression).Type;

            if (castingFrom == null)
            {
                castingFrom = model.GetTypeInfo(expression).Type;
            }

            var srcTypeScala  = TypeProcessor.ConvertType((ITypeSymbol)castingFrom);
            var destType      = model.GetTypeInfo(expression.Type).Type;
            var destTypeScala = TypeProcessor.TryConvertType(expression.Type);

            if (destTypeScala == srcTypeScala)
            {
                //Eat casts where the types are identical.  Enums getting casted to int fall here, and since we use ints to represent enums anyway, it's not necessary.
                Core.Write(writer, expression.Expression);
            }
            else if (symbol.Symbol != null && srcTypeScala != "Int" && srcTypeScala != "String" && srcTypeScala != "Bool")
            {
                //when the symbol is non-null, this indicates we're calling a cast operator function
                writer.Write(TypeProcessor.ConvertType(symbol.Symbol.ContainingType));
                writer.Write(".op_Explicit_");
                writer.Write(destTypeScala.TrySubstringBeforeFirst('[').Replace('.', '_'));
                writer.Write("(");
                Core.Write(writer, expression.Expression);
                writer.Write(")");
            }
            else if (TypeProcessor.IsPrimitiveType(srcTypeScala) && TypeProcessor.IsPrimitiveType(destTypeScala))
            {
                if (srcTypeScala == "Byte")
                {
                    //JVM's bytes are signed, so we must take care when upcasting
                    writer.Write("System.CsScala.ByteTo");
                    writer.Write(destTypeScala);
                    writer.Write("(");
                    Core.Write(writer, expression.Expression);
                    writer.Write(")");
                }
                else
                {
                    //Casting between primitives is handled in scala bo the .toXX functions
                    Core.Write(writer, expression.Expression);
                    writer.Write(".to");
                    writer.Write(destTypeScala);
                }
            }
            else
            {
                Core.Write(writer, expression.Expression);
                writer.Write(".asInstanceOf[");
                writer.Write(destTypeScala);
                writer.Write("]");
            }
        }
Example #14
0
 public void WriteLoopOpening(ScalaWriter writer)
 {
     if (HasContinue)
     {
         writer.WriteLine("CsScala.cscontinue.breakable");
         writer.WriteOpenBrace();
     }
 }
Example #15
0
 public static void Go(ScalaWriter writer, ConstructorDeclarationSyntax constructor)
 {
     //Only write out static constructors here.  If we encounter an instance constructor, we can ignore it since it's already written out by WriteType
     if (constructor.Modifiers.Any(SyntaxKind.StaticKeyword))
     {
         WriteStaticConstructor(writer, constructor);
     }
 }
Example #16
0
 public void WritePreLoop(ScalaWriter writer)
 {
     if (HasBreak)
     {
         writer.WriteLine("CsScala.csbreak.breakable");
         writer.WriteOpenBrace();
     }
 }
Example #17
0
        public static void Go(ScalaWriter writer, TryStatementSyntax tryStatement)
        {
            writer.WriteLine("try");
            Core.Write(writer, tryStatement.Block);

            var catches = tryStatement.Catches.Where(o => Program.DoNotWrite.ContainsKey(o) == false).ToList();

            if (catches.Count > 0)
            {
                writer.WriteLine("catch");
                writer.WriteOpenBrace();

                foreach (var catchClause in catches)
                {
                    writer.WriteIndent();

                    //In C#, the base exception type is Exception, but on the JVM it is Throwable.  Normally, JVM programs should not catch throwable, so we map the C# Exception type to the JVM Exception type by default.  We attempted to change Exception to map to Throwable but ran into issues with things getting caught that shouldn't, such as Scala's "BreakControl" that's used on break statements.
                    //if C# code really wants to catch all throwables, catch Exception and name the variable "allThrowables".  This is a signal to CSScala that all throwables should be caught.  However, use it with care, as it can cause complications.
                    if (catchClause.Declaration == null)
                    {
                        writer.Write("case __ex: java.lang.Exception => ");
                    }
                    else
                    {
                        writer.Write("case ");
                        writer.Write(string.IsNullOrWhiteSpace(catchClause.Declaration.Identifier.ValueText) ? "__ex" : WriteIdentifierName.TransformIdentifier(catchClause.Declaration.Identifier.ValueText));
                        writer.Write(": ");


                        if (catchClause.Declaration.Identifier.ValueText == "allThrowables")
                        {
                            writer.Write("java.lang.Throwable");
                        }
                        else
                        {
                            writer.Write(TypeProcessor.ConvertType(catchClause.Declaration.Type));
                        }

                        writer.Write(" =>\r\n");
                    }

                    writer.Indent++;
                    foreach (var statement in catchClause.Block.Statements)
                    {
                        Core.Write(writer, statement);
                    }
                    writer.Indent--;
                }

                writer.WriteCloseBrace();
            }

            if (tryStatement.Finally != null)
            {
                writer.WriteLine("finally");
                Core.Write(writer, tryStatement.Finally.Block);
            }
        }
Example #18
0
 public static void Go(ScalaWriter writer, ConditionalExpressionSyntax expression)
 {
     writer.Write("(if (");
     Core.Write(writer, expression.Condition);
     writer.Write(") ");
     Core.Write(writer, expression.WhenTrue);
     writer.Write(" else ");
     Core.Write(writer, expression.WhenFalse);
     writer.Write(")");
 }
        public static void Go(ScalaWriter writer, LocalDeclarationStatementSyntax declaration)
        {
            foreach (var variable in declaration.Declaration.Variables)
            {
                var symbol = Program.GetModel(declaration).GetDeclaredSymbol(variable);

                var isRef = UsedAsRef(variable, symbol);

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

                if (isRef)
                {
                    var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type);

                    writer.Write(":CsRef[");
                    writer.Write(typeStr);
                    writer.Write("]");

                    Program.RefOutSymbols.TryAdd(symbol, null);

                    writer.Write(" = new CsRef[");
                    writer.Write(typeStr);
                    writer.Write("](");

                    if (variable.Initializer == null)
                    {
                        writer.Write(TypeProcessor.DefaultValue(declaration.Declaration.Type));
                    }
                    else
                    {
                        Core.Write(writer, variable.Initializer.As <EqualsValueClauseSyntax>().Value);
                    }

                    writer.Write(")");
                }
                else
                {
                    writer.Write(TypeProcessor.ConvertTypeWithColon(declaration.Declaration.Type));
                    writer.Write(" = ");

                    if (variable.Initializer != null)
                    {
                        Core.Write(writer, variable.Initializer.As <EqualsValueClauseSyntax>().Value);
                    }
                    else
                    {
                        writer.Write(TypeProcessor.DefaultValue(declaration.Declaration.Type));
                    }
                }

                writer.Write(";\r\n");
            }
        }
Example #20
0
        public static void WriteAnonymousType(AnonymousObjectCreationExpressionSyntax syntax)
        {
            var type     = Program.GetModel(syntax).GetTypeInfo(syntax).Type.As <INamedTypeSymbol>();
            var anonName = TypeName(type);

            using (var writer = new ScalaWriter("anonymoustypes", StripGeneric(anonName)))
            {
                var fields = type.GetMembers().OfType <IPropertySymbol>().OrderBy(o => o.Name).ToList();

                writer.WriteLine("package anonymoustypes;");
                WriteImports.Go(writer);

                writer.WriteIndent();
                writer.Write("class ");
                writer.Write(anonName);
                writer.Write("(");
                bool first = true;
                foreach (var field in fields)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        writer.Write(", ");
                    }

                    writer.Write("_");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(TypeProcessor.ConvertTypeWithColon(field.Type));
                }
                writer.Write(")\r\n");


                writer.WriteOpenBrace();



                foreach (var field in fields)
                {
                    writer.WriteIndent();
                    writer.Write("final var ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(TypeProcessor.ConvertTypeWithColon(field.Type));
                    writer.Write(" = _");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(";\r\n");
                }



                writer.WriteCloseBrace();
            }
        }
Example #21
0
        //public static void WriteInstanceConstructor(ScalaWriter writer, ConstructorDeclarationSyntax ctor)
        //{


        //	foreach (var field in TypeState.Instance.AllMembers
        //				.OfType<BaseFieldDeclarationSyntax>()
        //				.Where(o => !o.Modifiers.Any(SyntaxKind.StaticKeyword))
        //				.SelectMany(o => o.Declaration.Variables)
        //				.Where(o =>
        //					(o.Initializer != null && !WriteField.IsConst(o.Parent.Parent.As<BaseFieldDeclarationSyntax>().Modifiers, o.Initializer, o.Parent.As<VariableDeclarationSyntax>().Type))
        //					||
        //					(o.Initializer == null && TypeProcessor.ValueToReference(o.Parent.As<VariableDeclarationSyntax>().Type))
        //					||
        //					o.Parent.Parent is EventFieldDeclarationSyntax))
        //	{
        //		writer.WriteIndent();
        //		writer.Write(field.Identifier.ValueText);
        //		writer.Write(" = ");

        //		if (field.Initializer == null)
        //		{
        //			//The only way to get here with a null initializer is for a TypeProcess.ValueToReference field.
        //			writer.Write("new ");
        //			writer.Write(TypeProcessor.ConvertType(field.Parent.As<VariableDeclarationSyntax>().Type));
        //			writer.Write("()");
        //		}
        //		else
        //		{
        //			Core.Write(writer, field.Initializer.Value);
        //		}

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

        //}



        public static void WriteStaticConstructor(ScalaWriter writer, ConstructorDeclarationSyntax staticConstructor)
        {
            //var staticFieldsNeedingInitialization = TypeState.Instance.AllMembers
            //	.OfType<BaseFieldDeclarationSyntax>()
            //	.Where(o => o.Modifiers.Any(SyntaxKind.StaticKeyword))
            //	.SelectMany(o => o.Declaration.Variables)
            //	.Where(o =>
            //		(o.Initializer != null && !WriteField.IsConst(o.Parent.Parent.As<BaseFieldDeclarationSyntax>().Modifiers, o.Initializer, o.Parent.As<VariableDeclarationSyntax>().Type))
            //		||
            //		(o.Initializer == null && TypeProcessor.ValueToReference(o.Parent.As<VariableDeclarationSyntax>().Type))
            //		||
            //		o.Parent.Parent is EventFieldDeclarationSyntax)
            //	.ToList();

            if (staticConstructor.Body == null)
            {
                return;
            }


            writer.WriteLine("def cctor()");
            writer.WriteOpenBrace();

            //foreach (var field in staticFieldsNeedingInitialization)
            //{
            //	writer.WriteIndent();
            //	writer.Write(field.Identifier.ValueText);
            //	writer.Write(" = ");

            //	if (field.Initializer == null)
            //	{
            //		//The only way to get here without an initializer is if it's a TypeProcessor.ValueToReference.
            //		writer.Write("new ");
            //		writer.Write(TypeProcessor.ConvertType(field.Parent.As<VariableDeclarationSyntax>().Type));
            //		writer.Write("()");
            //	}
            //	else
            //	{
            //		Core.Write(writer, field.Initializer.As<EqualsValueClauseSyntax>().Value);
            //	}
            //	writer.Write(";\r\n");
            //}



            foreach (var statement in staticConstructor.Body.As <BlockSyntax>().Statements)
            {
                Core.Write(writer, statement);
            }

            writer.WriteCloseBrace();

            StaticConstructors.Add(TypeState.Instance.Partials.First().Symbol.ContainingNamespace.FullNameWithDot() + TypeState.Instance.TypeName);
        }
Example #22
0
        public static void Go(ScalaWriter writer, LiteralExpressionSyntax expression, bool isConst)
        {
            var str = expression.ToString();

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


            if (str.Length > 65000)
            {
                //Big strings have to be broken up, scala can't render big string constants, even when concatenated.  So we have to pass them to a function to concat at runtime
                writer.Write("System.CsScala.JoinConstants(");
                var raw = str.RemoveFromStartOfString("\"").RemoveFromEndOfString("\"");

                var subLength = 65000;
                for (int i = 0; i < raw.Length; i += subLength)
                {
                    var sub = raw.SubstringSafe(i, subLength);
                    //Make sure we never break in the middle of a backslash sequence.  TODO: This assumes backslash sequences are only ever two characters long, we could break on longer ones.
                    if (sub[sub.Length - 1] == '\\' && sub[sub.Length - 2] != '\\')
                    {
                        sub += raw[i + subLength];
                        i++;
                    }

                    writer.Write("\"");
                    writer.Write(sub);
                    writer.Write("\"");
                    if (i + subLength < raw.Length)
                    {
                        writer.Write(", ");
                    }
                }
                writer.Write(")");
            }
            else
            {
                writer.Write(str);
            }

            var typeInfo = Program.GetModel(expression).GetTypeInfo(expression);

            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");
                }
            }
        }
Example #23
0
        private static void WriteEnumGetValues(ScalaWriter 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 = Program.GetModel(invocationExpression).GetTypeInfo(invocationExpression.ArgumentList.Arguments[0].Expression.As <TypeOfExpressionSyntax>().Type).Type;

            writer.Write(type.ContainingNamespace.FullNameWithDot());
            writer.Write(WriteType.TypeName((INamedTypeSymbol)type));
            writer.Write(".Values");
        }
Example #24
0
 public static void Go(ScalaWriter writer, FieldDeclarationSyntax field)
 {
     foreach (var declaration in field.Declaration.Variables)
     {
         if (field.AttributeLists.Any(l => l.Attributes.Any(a => a.Name.As <IdentifierNameSyntax>().Identifier.ValueText == "ThreadStatic")))
         {
             WriteThreadStatic(writer, declaration, field);
         }
         else
         {
             Go(writer, field.Modifiers, WriteIdentifierName.TransformIdentifier(declaration.Identifier.ValueText), field.Declaration.Type, declaration.Initializer);
         }
     }
 }
Example #25
0
        private static void WriteGetEnumeratorFunction(ScalaWriter writer, MethodDeclarationSyntax method, IMethodSymbol methodSymbol)
        {
            var returnType = TypeProcessor.ConvertType(methodSymbol.ReturnType);

            if (!returnType.StartsWith("System.Collections.Generic.IEnumerator["))
            {
                return; //we only support the generic IEnumerator form of GetEnumerator.  Anything else, just don't write out the method.
            }
            var enumerableType = returnType.RemoveFromStartOfString("System.Collections.Generic.IEnumerator[").RemoveFromEndOfString("]");

            //We only support very simple GetEnumerator functions that pass on their call to some other collection.  The body should be like "return <expr>.GetEnumerator();", otherwise don't write out the function at all.
            if (method.Body == null)
            {
                return;
            }
            if (method.Body.Statements.Count > 1)
            {
                return;
            }
            var returnStatement = method.Body.Statements.Single() as ReturnStatementSyntax;

            if (returnStatement == null)
            {
                return;
            }
            var invocation = returnStatement.Expression as InvocationExpressionSyntax;

            if (invocation == null)
            {
                return;
            }
            var member = invocation.Expression as MemberAccessExpressionSyntax;

            if (member == null)
            {
                return;
            }

            writer.WriteIndent();
            writer.Write("def foreach[U](fn: ");
            writer.Write(enumerableType);
            writer.Write(" => U)\r\n");
            writer.WriteOpenBrace();

            writer.WriteIndent();
            Core.Write(writer, member.Expression);
            writer.Write(".foreach(fn);\r\n");
            writer.WriteCloseBrace();
        }
Example #26
0
        private static void WriteTypeParameters(ScalaWriter writer, MethodTranslation translateOpt, string typeParameters, InvocationExpressionSyntax invoke)
        {
            if (translateOpt != null)
            {
                if (translateOpt.WriteTypeParameters(writer, invoke))
                {
                    return;
                }
            }

            if (typeParameters != null)
            {
                writer.Write(typeParameters);
            }
        }
Example #27
0
        private static void WriteThreadStatic(ScalaWriter writer, VariableDeclaratorSyntax declaration, FieldDeclarationSyntax field)
        {
            /*val __Init = new ThreadLocal[String]()
             * { override def initialValue():String = ""initval""; };
             * def Init:String = __Init.get();
             * def Init_=(value:String) = __Init.set(value);*/

            var type = TypeProcessor.ConvertType(field.Declaration.Type);

            writer.WriteIndent();
            writer.Write("final val __");
            writer.Write(declaration.Identifier.ValueText);
            writer.Write(" = new ThreadLocal[");
            writer.Write(type);
            writer.Write("]()");

            if (declaration.Initializer != null)
            {
                writer.Write("\r\n");
                writer.WriteIndent();
                writer.Write("{ override def initialValue():");
                writer.Write(type);
                writer.Write(" = ");
                Core.Write(writer, declaration.Initializer.Value);
                writer.Write("; }");
            }

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

            writer.WriteIndent();
            writer.Write("def ");
            writer.Write(declaration.Identifier.ValueText);
            writer.Write(":");
            writer.Write(type);
            writer.Write(" = __");
            writer.Write(declaration.Identifier.ValueText);
            writer.Write(".get();\r\n");

            writer.WriteIndent();
            writer.Write("def ");
            writer.Write(declaration.Identifier.ValueText);
            writer.Write("_=(value:");
            writer.Write(type);
            writer.Write(") = __");
            writer.Write(declaration.Identifier.ValueText);
            writer.Write(".set(value);\r\n");
        }
Example #28
0
        public static void Go(ScalaWriter writer, BreakStatementSyntax statement)
        {
            //Traverse up to figure out what we're breaking from.  If we're breaking from a loop, it's fine.  However, if we're breaking from a switch statement, throw an error as we don't allow this except directly inside of a case block.
            var breakingFrom = statement.Parent;

            while (!(breakingFrom is WhileStatementSyntax || breakingFrom is ForStatementSyntax || breakingFrom is DoStatementSyntax || breakingFrom is ForEachStatementSyntax))
            {
                if (breakingFrom is SwitchStatementSyntax)
                {
                    throw new Exception("Cannot \"break\" from within a switch statement except directly inside of a case statement. " + Utility.Descriptor(statement));
                }

                breakingFrom = breakingFrom.Parent;
            }

            writer.WriteLine("CsScala.csbreak.break;");
        }
Example #29
0
        public static void Go(ScalaWriter writer, WhileStatementSyntax whileStatement)
        {
            var info = new LoopInfo(whileStatement);

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

            writer.WriteOpenBrace();
            info.WriteLoopOpening(writer);
            Core.WriteStatementAsBlock(writer, whileStatement.Statement, false);
            info.WriteLoopClosing(writer);
            writer.WriteCloseBrace();
            info.WritePostLoop(writer);
        }
 public static void WritePostfix(ScalaWriter writer, PostfixUnaryExpressionSyntax expression)
 {
     if (expression.OperatorToken.Kind() == SyntaxKind.MinusMinusToken)
     {
         Core.Write(writer, expression.Operand);
         writer.Write(" -= 1");
     }
     else if (expression.OperatorToken.Kind() == SyntaxKind.PlusPlusToken)
     {
         Core.Write(writer, expression.Operand);
         writer.Write(" += 1");
     }
     else
     {
         throw new Exception("No support for " + expression.OperatorToken.Kind() + " at " + Utility.Descriptor(expression));
     }
 }