public static void Go(OutputWriter writer, YieldStatementSyntax yieldStatementSyntax) { if (yieldStatementSyntax.ReturnOrBreakKeyword.IsKind(SyntaxKind.ReturnKeyword)) { writer.WriteLine("__iter.yieldReturn({0});", Core.WriteString(yieldStatementSyntax.Expression)); } else { writer.WriteLine("__iter.yieldBreak();"); } }
//TODO should enum be light class of static members ? or just a plain enum ? (using plain enum for now) public static void Go(OutputWriter writer, IEnumerable <EnumMemberDeclarationSyntax> allChildren) { // writer.IsInterface = true; writer.Write("enum "); writer.Write(Context.Instance.TypeName); writer.Write(":" + TypeProcessor.ConvertType(Context.Instance.Type.EnumUnderlyingType) + "\r\n"); writer.OpenBrace(); long lastEnumValue = 0; var children = allChildren.ToArray(); var values = children.Select( o => new { Syntax = o, Value = o.EqualsValue != null ? o.EqualsValue.Value.ToString() : null }) .ToList(); foreach (var value in values) { writer.WriteLine( WriteIdentifierName.TransformIdentifier(value.Syntax.Identifier.ValueText) + (value.Value != null ? " = " + value.Value : "") + ","); } // 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.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 + "\" => " + value.Value + ";"); // // 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.CloseBrace(); writer.Write(";"); }
public static void Go(OutputWriter writer, LockStatementSyntax statement) { //All d objects implement a lock writer.WriteLine("synchronized(" + Core.WriteString(statement.Expression) + ")"); writer.OpenBrace(); Core.WriteStatementAsBlock(writer, statement.Statement, false); writer.CloseBrace(); }
public static void Go(OutputWriter writer, LockStatementSyntax statement) { //All d objects implement a lock writer.WriteLine("synchronized(" + Core.WriteString(statement.Expression)+")"); writer.OpenBrace(); Core.WriteStatementAsBlock(writer, statement.Statement, false); writer.CloseBrace(); }
public static void Go(OutputWriter writer, UsingStatementSyntax usingStatement) { var expression = usingStatement.Expression; //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)); writer.WriteLine("try"); Core.WriteStatementAsBlock(writer, usingStatement.Statement); writer.WriteLine("finally"); writer.OpenBrace(); writer.WriteLine(resource + ".IDisposable_Dispose();"); writer.CloseBrace(); }
public static void Go(OutputWriter 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) { foreach (var catchClause in catches) { if (catchClause.Declaration == null) { writer.WriteLine("catch(Exception __ex)"); } else { writer.WriteLine("catch(" + TypeProcessor.ConvertType(catchClause.Declaration.Type) + " " + (string.IsNullOrWhiteSpace(catchClause.Declaration.Identifier.Text) ? "__ex" : WriteIdentifierName.TransformIdentifier( catchClause.Declaration.Identifier.Text)) + ")"); } writer.OpenBrace(); Core.WriteBlock(writer, catchClause.Block, false); // foreach (var statement in catchClause.Block.Statements) // Core.Write(writer, statement); writer.CloseBrace(); } } if (tryStatement.Finally != null) { writer.WriteLine("finally"); // Core.Write(writer, tryStatement.Finally.Block); writer.OpenBrace(); Core.WriteBlock(writer, tryStatement.Finally.Block, false); // foreach (var statement in catchClause.Block.Statements) // Core.Write(writer, statement); writer.CloseBrace(); } }
private static void WriteEntryMethod(OutputWriter writer) { if (Context.Instance.EntryMethod != null) { //TODO: DllImports should be centralized // writer.WriteLine(); writer.WriteLine("void main(string[] args)"); writer.OpenBrace(); writer.WriteLine("__SetupSystem();"); writer.WriteLine(Context.Instance.EntryMethod); writer.WriteLine("__EndSystem();"); writer.CloseBrace(); } }
public static void Go(OutputWriter 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) { foreach (var catchClause in catches) { if (catchClause.Declaration == null) writer.WriteLine("catch(Exception __ex)"); else { writer.WriteLine("catch(" + TypeProcessor.ConvertType(catchClause.Declaration.Type) + " " + (string.IsNullOrWhiteSpace(catchClause.Declaration.Identifier.Text) ? "__ex" : WriteIdentifierName.TransformIdentifier( catchClause.Declaration.Identifier.Text)) + ")"); } writer.OpenBrace(); Core.WriteBlock(writer, catchClause.Block, false); // foreach (var statement in catchClause.Block.Statements) // Core.Write(writer, statement); writer.CloseBrace(); } } if (tryStatement.Finally != null) { writer.WriteLine("finally"); // Core.Write(writer, tryStatement.Finally.Block); writer.OpenBrace(); Core.WriteBlock(writer, tryStatement.Finally.Block, false); // foreach (var statement in catchClause.Block.Statements) // Core.Write(writer, statement); writer.CloseBrace(); } }
public static void Go(OutputWriter writer, string methodName, IMethodSymbol methodSymbol, AttributeSyntax pinvokeAttributes) { //Do Pinvoke stuff //PInvokeFunction < int (int, double)> foo(library, "foo"); //int i = foo(42, 2.0); int dllImportId = -1; AttributeSyntax import = Context.Instance.DllImports.FirstOrDefault( d => d.ArgumentList.Arguments.FirstOrDefault( k => k.Expression != null && k.Expression.ToString() == pinvokeAttributes.ArgumentList.Arguments.FirstOrDefault(g => g.Expression != null) .Expression.ToString()) != null); if (import != null) { dllImportId = Context.Instance.DllImports.IndexOf(import); } if (dllImportId == -1) { Context.Instance.DllImports.Add(pinvokeAttributes); dllImportId = Context.Instance.DllImports.IndexOf(pinvokeAttributes); } // var methodParams = methodSymbol.Parameters.Any () ? methodSymbol.Parameters.Select (h => ConvertPInvokeType (h.Type)).Aggregate ((k, y) => (k) + " ," + y) : ""; var returnString = ConvertPInvokeType(methodSymbol.ReturnType); var functionCall = String.Format("extern (C) {0} function ({1})", returnString, GetParameterList(methodSymbol.Parameters)); writer.WriteLine("alias " + functionCall + " " + methodName + "_func_alias;"); var convertedParameters = ConvertParameters(methodSymbol.Parameters); writer.WriteLine(String.Format("auto {1} = cast({2}) LoadLibraryFunc(__DllImportMap[{0}], \"{1}\");", dllImportId, methodName, methodName + "_func_alias")); writer.WriteLine(String.Format((returnString != "void" ? "return " : "") + "{0}({1});", methodName, convertedParameters.Count > 0 ? convertedParameters.Select(h => h).Aggregate((k, y) => (k) + " ," + y) : "")); }
public static void WriteFixedStatement(OutputWriter writer, FixedStatementSyntax statement) { // writer.WriteIndent(); writer.WriteLine("//fixed() Scope"); writer.OpenBrace(); Write(writer, statement.Declaration); Write(writer, statement.Statement); writer.CloseBrace(); // writer.Write(";\r\n"); }
private static void WriteNamespaces() { //For now ignore system namespace to prevent conflicts, later we should just check if the module is defined in our sources foreach (var @namespace in Context.Namespaces) { if ([email protected]("System")) { // TODO: this should write nses for only types defined in binary, this should be a switch, we could be compiling corlib using (var writer = new OutputWriter(@namespace.Key, @namespace.Key) { IsNamespace = true }) { writer.WriteLine("module " + @namespace.Key + ";"); foreach (var type in @namespace.Value) { var className = type.RemoveFromStartOfString(@namespace.Key + "."); var properClassName = @namespace.Key.RemoveFromEndOfString(".Namespace") + "." + className + "." + className; if (className.EndsWith("Namespace")) { continue; } if (className.StartsWith("__Boxed_")) //TODO: need a better system for this { properClassName = @namespace.Key.RemoveFromEndOfString(".Namespace") + "." + className.RemoveFromStartOfString("__Boxed_") + "." + className; writer.WriteLine("alias " + properClassName + " " + className + ";"); } else { writer.WriteLine("alias " + properClassName + " " + className + ";"); } } } } } }
private const string _set = ""; //"set"; static void WriteRegion(bool get, string body, ITypeSymbol iface, OutputWriter writer, string typeString, string name, SyntaxTokenList modifiers, string parameters, bool isindexer, bool hasGetter) { //no inline in D // if (get) writer.Write((get ? (typeString) : (hasGetter ? typeString : "void")) + " "); // else // writer.Write("void "); if (!isindexer) { writer.Write((get?(_get + name):(_set + (name))) + (get ? "(" + (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : "") + ")" : "(" + typeString + " value " + (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : "") + ")") + " "); } else { writer.Write((name) + (get ? "(" + parameters + ")" : "(" + typeString + " value, " + parameters + ")") + ""); } if (modifiers.Any(SyntaxKind.AbstractKeyword) || body == null) { writer.Write(";\r\n"); } else { writer.WriteLine(); writer.OpenBrace(); writer.WriteLine(body); writer.CloseBrace(); writer.WriteLine(); } }
private const string _set = "";//"set"; static void WriteRegion(bool get, string body, ITypeSymbol iface, OutputWriter writer, string typeString, string name, SyntaxTokenList modifiers, string parameters, bool isindexer, bool hasGetter) { //no inline in D // if (get) writer.Write((get ? (typeString) : (hasGetter ? typeString : "void")) + " "); // else // writer.Write("void "); if (!isindexer) { writer.Write( (get?(_get+name):(_set+(name))) + (get ? "(" + (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : "") + ")" : "(" + typeString + " value " + (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : "") + ")") + " "); } else { writer.Write((name) + (get ? "(" + parameters + ")" : "(" + typeString + " value, " + parameters + ")") + ""); } if (modifiers.Any(SyntaxKind.AbstractKeyword) || body == null) writer.Write(";\r\n"); else { writer.WriteLine(); writer.OpenBrace(); writer.WriteLine(body); writer.CloseBrace(); writer.WriteLine(); } }
public static void WriteStaticConstructor(OutputWriter writer, ConstructorDeclarationSyntax staticConstructor, List <string> otherStatics) { if (staticConstructor.Body == null && (otherStatics == null || otherStatics.Count == 0)) { return; } writer.WriteLine(); writer.WriteLine("static this()"); writer.OpenBrace(); if (otherStatics != null) //We need to write the static initializers before anything else { foreach (var statement in otherStatics) { var nodeString = statement; if (nodeString != null) { writer.WriteLine(nodeString); } } } if (staticConstructor.Body != null) { foreach (var statement in staticConstructor.Body.As <BlockSyntax>().Statements) { Core.Write(writer, statement); } } writer.CloseBrace(); StaticConstructors.Add(Context.Instance.Partials.First().Symbol.ContainingNamespace.FullNameWithDot() + Context.Instance.TypeName); }
public static void Go(OutputWriter writer, ConversionOperatorDeclarationSyntax method) { //TODO: Need to find a way of dealing with this ... Quickly moving towards the idea of compile/decompile using ILSPY // if (method.ImplicitOrExplicitKeyword.RawKind != (decimal) SyntaxKind.ExplicitKeyword) // throw new Exception("Implicit cast operators are not supported " + Utility.Descriptor(method)); var temp = new TempWriter(); // temp.WriteIndent(); temp.Write("public static " + TypeProcessor.ConvertType(method.Type)); temp.Write(" " + ((method.ImplicitOrExplicitKeyword.RawKind != (decimal)SyntaxKind.ExplicitKeyword) ? ("op_Implicit_" + TypeProcessor.ConvertType(method.Type, false, true, false).Replace(".", "_")) : "op_Explicit")); //writer.Write(" op_Explicit"); // writer.Write(TypeProcessor.ConvertType(method.Type)); temp.Write("("); bool firstParam = true; foreach (var param in method.ParameterList.Parameters) { if (firstParam) { firstParam = false; } else { temp.Write(", "); } temp.Write(TypeProcessor.ConvertType(param.Type) + " "); temp.Write(WriteIdentifierName.TransformIdentifier(param.Identifier.Text)); } temp.Write(")"); writer.WriteLine(temp.ToString()); writer.OpenBrace(); foreach (var statement in method.Body.Statements) { Core.Write(writer, statement); } writer.CloseBrace(); }
public static void Go(OutputWriter writer, DoStatementSyntax statement) { var info = new LoopInfo(statement); writer.WriteLine("do"); writer.OpenBrace(); Core.WriteStatementAsBlock(writer, statement.Statement, false); writer.CloseBrace(); writer.WriteIndent(); writer.Write("while ("); Core.Write(writer, statement.Condition); writer.Write(");\r\n"); }
public static void WriteStaticConstructor(OutputWriter writer, ConstructorDeclarationSyntax staticConstructor, List <string> otherStatics) { if (staticConstructor.Body == null && (otherStatics == null || otherStatics.Count == 0)) { return; } writer.WriteLine(); writer.WriteLine("static this()"); writer.OpenBrace(); if (staticConstructor.Body != null) { foreach (var statement in staticConstructor.Body.As <BlockSyntax>().Statements) { Core.Write(writer, statement); } } if (otherStatics != null) { foreach (var statement in otherStatics) { var nodeString = statement; // if (nodeString.EndsWith (" SharpNative;\n")) { // nodeString = nodeString.RemoveFromEndOfString(" SharpNative;\n")+";\n"; // } writer.WriteLine(nodeString); } } writer.CloseBrace(); StaticConstructors.Add(Context.Instance.Partials.First().Symbol.ContainingNamespace.FullNameWithDot() + Context.Instance.TypeName); }
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(); }
public static void WriteLeadingTrivia(OutputWriter writer, SyntaxNode node) { var triviaList = node.GetLeadingTrivia(); foreach (var trivia in triviaList) { if (trivia.CSharpKind() == SyntaxKind.SingleLineCommentTrivia || trivia.CSharpKind() == SyntaxKind.MultiLineCommentTrivia || trivia.CSharpKind() == SyntaxKind.SingleLineDocumentationCommentTrivia || trivia.CSharpKind() == SyntaxKind.MultiLineDocumentationCommentTrivia || trivia.CSharpKind() == SyntaxKind.WhitespaceTrivia) { if (trivia.CSharpKind() == SyntaxKind.WhitespaceTrivia) { if (trivia.ToFullString().EndsWith("\n")) { writer.WriteLine(); writer.WriteIndent(); } } else writer.WriteLine(trivia.ToFullString()); } } }
private static void WriteSetter(OutputWriter writer, bool isProxy, bool hasSetter, string acccessmodifiers, string name, string typeString, ITypeSymbol iface, string isOverride, bool setterHasBody, SyntaxTokenList modifiers, bool isInterface, string fieldName, string setterbody, string parameters, bool isindexer, bool hasGetter) { if (isindexer) { name = "opIndexAssign"; } var args = _set; if (hasSetter && isProxy) { if (!isindexer) { writer.WriteLine(string.Format("{0} {2} {5}{1}({2} value{3}{4}){4} {{ __Value.{1} = value; return value;}}", acccessmodifiers, name, hasGetter ? typeString : "void", (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : ""), isOverride, args)); } else { writer.WriteLine(string.Format("{0} {2} {1}({2} value,{3}{4}) {4} {{ __Value.{1} = value;return value;}}", acccessmodifiers, name, typeString, parameters, isOverride)); } } else if (hasSetter && !setterHasBody) //Setter { if (modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) { if (!isindexer) { writer.WriteLine(string.Format("{0} {2} {5}{1}({2} value{3}{4});", acccessmodifiers, name, hasGetter ? typeString : "void", (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : ""), isOverride, args)); } else { writer.WriteLine(string.Format("{0} {2} {1}({2} value,{3}{4});", acccessmodifiers, name, typeString, parameters, isOverride)); } } else { if (!isindexer) { var returnValue = hasGetter ? writer.WriteIndentToString() + "return value;" :""; writer.WriteLine(string.Format("{0} {2} {6}{1}({2} value{3}){4} {{{5} = value;{7}}}", acccessmodifiers, name, hasGetter?typeString :"void", (iface != null ? ("," + TypeProcessor.ConvertType(iface) + " __ig=null") : ""), isOverride, fieldName, args, returnValue)); } else { var returnValue = hasGetter ? writer.WriteIndentToString() + "return value;" : ""; writer.WriteLine(string.Format("{0} {2} {1}({2} value,{3}){4} {{{5} = value;{6}}}", acccessmodifiers, name, typeString, parameters, isOverride, fieldName, returnValue)); } } } else if (hasSetter) { writer.WriteIndent(); writer.Write(acccessmodifiers); WriteRegion(false, setterbody, iface, writer, typeString, name, modifiers, parameters, isindexer, hasGetter); } }
public static void WriteDestructor(OutputWriter writer, DestructorDeclarationSyntax destructor) { if (destructor.Body == null) return; writer.WriteLine("~this()"); writer.OpenBrace(); if (destructor.Body != null) { foreach (var statement in destructor.Body.As<BlockSyntax>().Statements) Core.Write(writer, statement); } writer.CloseBrace(); }
public static void Go(OutputWriter writer, LockStatementSyntax statement) { // if (statement.DescendantNodes().OfType<ReturnStatementSyntax>().Any()) // throw new Exception("Cannot return from within a lock statement " + Utility.Descriptor(statement)); //synchronized writer.WriteIndent(); writer.Write("synchronized("); //All d object implement a lock Core.Write(writer, statement.Expression); writer.Write(")"); //, () =>\r\n"); writer.OpenBrace(); Core.WriteStatementAsBlock(writer, statement.Statement, false); writer.Indent--; writer.WriteIndent(); writer.CloseBrace(); writer.WriteLine(); // writer.Write("};\r\n"); }
private static void WriteGetter(OutputWriter writer, bool isProxy, bool hasGetter, string acccessmodifiers, string typeString, string name, ITypeSymbol iface, bool getterHasBody, SyntaxTokenList modifiers, bool isInterface, string fieldName, string getterbody, string parameters, bool isindexer) { if (isindexer) { name = "opIndex"; } var args = _get; if (hasGetter && isProxy) { if (!isindexer) { writer.WriteLine(string.Format("{0}{1} {4}{2}({3}) {{ return __Value.{2};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : ""), args)); } else { writer.WriteLine(string.Format("{0}{1} {2}({3}) {{ return __Value.{2};}}", acccessmodifiers, typeString, name, parameters)); } } else if (hasGetter && !getterHasBody) //Getter { if (modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) { if (!isindexer) { writer.WriteLine(string.Format("{0}{1} {4}{2}({3});", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : ""), args)); } else { writer.WriteLine(string.Format("{0}{1} {2}({3});", acccessmodifiers, typeString, name, parameters)); } } else { if (!isindexer) { writer.WriteLine(string.Format("{0}{1} {5}{2}({3}) {{ return {4};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType(iface) + " __ig=null") : ""), fieldName, args)); } else { writer.WriteLine(string.Format("{0}{1} {2}({3}) {{ return {4};}}", acccessmodifiers, typeString, name, parameters, fieldName)); } } } else if (hasGetter) { writer.WriteIndent(); writer.Write(acccessmodifiers); WriteRegion(true, getterbody, iface, writer, typeString, name, modifiers, parameters, isindexer, hasGetter); } }
public static void Go(OutputWriter writer, 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(); }
public static void Go(OutputWriter writer, ConversionOperatorDeclarationSyntax method) { //TODO: Need to find a way of dealing with this ... Quickly moving towards the idea of compile/decompile using ILSPY // if (method.ImplicitOrExplicitKeyword.RawKind != (decimal) SyntaxKind.ExplicitKeyword) // throw new Exception("Implicit cast operators are not supported " + Utility.Descriptor(method)); var temp = new TempWriter(); // temp.WriteIndent(); temp.Write("public static " + TypeProcessor.ConvertType(method.Type)); temp.Write(" " + ((method.ImplicitOrExplicitKeyword.RawKind != (decimal) SyntaxKind.ExplicitKeyword) ? ("op_Implicit_" + TypeProcessor.ConvertType(method.Type,false,true,false).Replace(".", "_")) : "op_Explicit")); //writer.Write(" op_Explicit"); // writer.Write(TypeProcessor.ConvertType(method.Type)); temp.Write("("); bool firstParam = true; foreach (var param in method.ParameterList.Parameters) { if (firstParam) firstParam = false; else temp.Write(", "); temp.Write(TypeProcessor.ConvertType(param.Type) + " "); temp.Write(WriteIdentifierName.TransformIdentifier(param.Identifier.Text)); } temp.Write(")"); writer.WriteLine(temp.ToString()); writer.OpenBrace(); foreach (var statement in method.Body.Statements) Core.Write(writer, statement); writer.CloseBrace(); }
public static void Go(OutputWriter writer, IfStatementSyntax ifStatement, bool indent = true) { // writer.WriteLine(); var tempWriter = new TempWriter(); if (indent) { tempWriter.WriteIndent(); } tempWriter.Write("if("); Core.Write(tempWriter, ifStatement.Condition); tempWriter.Write(")"); writer.WriteLine(tempWriter.ToString()); Core.WriteStatementAsBlock(writer, ifStatement.Statement); if (ifStatement.Else == null) { return; } writer.WriteIndent(); writer.Write("else"); if (ifStatement.Else.Statement is BlockSyntax) { writer.Write("\r\n"); Core.WriteBlock(writer, ifStatement.Else.Statement.As <BlockSyntax>()); } else if (ifStatement.Else.Statement is IfStatementSyntax) { writer.Write(" "); Go(writer, ifStatement.Else.Statement.As <IfStatementSyntax>(), false); } else { writer.Write("\r\n"); Core.WriteStatementAsBlock(writer, ifStatement.Else.Statement); } }
public static void WriteDestructor(OutputWriter writer, DestructorDeclarationSyntax destructor) { if (destructor.Body == null) { return; } writer.WriteLine("~this()"); writer.OpenBrace(); if (destructor.Body != null) { foreach (var statement in destructor.Body.As <BlockSyntax>().Statements) { Core.Write(writer, statement); } } writer.CloseBrace(); }
private static string WriteAutoFieldName(OutputWriter writer, string name, SyntaxTokenList modifiers, bool isInterface, bool hasGetter, bool getterHasBody, bool hasSetter, bool setterHasBody, string typeString, out string isOverride, bool isIndexer = false) { //Auto Property var fieldName = "__prop_" + name; isOverride = (modifiers.Any(SyntaxKind.NewKeyword) || modifiers.Any(SyntaxKind.OverrideKeyword)) && !isInterface ? " override " : ""; var isStatic = modifiers.Any(SyntaxKind.StaticKeyword); if (!isInterface && !isIndexer) // Auto property { if ((hasGetter && !getterHasBody) && (hasSetter && !setterHasBody) && (!modifiers.Any(SyntaxKind.AbstractKeyword))) { writer.WriteLine("private " + (isStatic?"static " :"") + typeString + " " + fieldName + ";"); } } return(fieldName); }
public static void Go(OutputWriter writer, IfStatementSyntax ifStatement, bool indent = true) { // writer.WriteLine(); var tempWriter = new TempWriter(); if (indent) tempWriter.WriteIndent(); tempWriter.Write("if("); Core.Write(tempWriter, ifStatement.Condition); tempWriter.Write(")"); writer.WriteLine(tempWriter.ToString()); Core.WriteStatementAsBlock(writer, ifStatement.Statement); if (ifStatement.Else == null) return; writer.WriteIndent(); writer.Write("else"); if (ifStatement.Else.Statement is BlockSyntax) { writer.Write("\r\n"); Core.WriteBlock(writer, ifStatement.Else.Statement.As<BlockSyntax>()); } else if (ifStatement.Else.Statement is IfStatementSyntax) { writer.Write(" "); Go(writer, ifStatement.Else.Statement.As<IfStatementSyntax>(), false); } else { writer.Write("\r\n"); Core.WriteStatementAsBlock(writer, ifStatement.Else.Statement); } }
public static void Go(OutputWriter writer, ForEachStatementSyntax foreachStatement) { var info = new LoopInfo(foreachStatement); var types = TypeProcessor.GetTypeInfo(foreachStatement.Expression); var typeStr = TypeProcessor.GenericTypeName(types.Type); writer.WriteLine(""); // writer.WriteOpenBrace(); // writer.WriteIndent(); var typeinfo = TypeProcessor.GetTypeInfo(foreachStatement.Expression); // var isPtr = typeinfo.Type != null && typeinfo.Type.IsValueType ? "" : ""; var typeString = TypeProcessor.ConvertType(foreachStatement.Type) + " "; var foreachCount = Context.Instance.ForeachCount++; var isListT = types.Type.OriginalDefinition == Context.ListT; var isArray = types.Type is IArrayTypeSymbol; if (isArray || isListT) {//Lets just for through the array, iterators are slow ... really slow var forIter = "__for" + foreachCount; var forArray = "__varfor" + foreachCount; var temp = new TempWriter(); Core.Write(temp, foreachStatement.Expression); var expressiono = temp.ToString(); // writer.WriteIndent(); writer.WriteLine("auto {0} = {1};", forArray, expressiono); writer.WriteLine("for (int {0}=0;{0} < {2}.{3}; {0}++)", forIter, //Special case to support iterating "params" array WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), forArray, isListT?"Count" :"length"); writer.OpenBrace(); writer.WriteLine("auto {0} = {1}[{2}];", WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), forArray, forIter); Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false); writer.CloseBrace(); return; } //It's faster to "while" through arrays than "for" through them var foreachIter = "__foreachIter" + foreachCount; if (typeinfo.Type.AllInterfaces.OfType<INamedTypeSymbol>().Any(j => j.MetadataName == "IEnumerable`1") || typeinfo.Type.MetadataName == "IEnumerable`1") { var collections = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Collections.Generic")); Context.Instance.UsingDeclarations = Context.Instance.UsingDeclarations .Union(new[] { collections }).ToArray(); writer.WriteLine("//ForEach"); // writer.OpenBrace (); writer.WriteIndent(); writer.Write(string.Format("auto {0} = ", foreachIter)); Core.Write(writer, foreachStatement.Expression); writer.Write(String.Format(".GetEnumerator(cast(IEnumerable__G!({0}))null);\r\n",typeString)); writer.WriteLine(string.Format("while({0}.MoveNext())", foreachIter)); writer.OpenBrace(); writer.WriteLine(string.Format("{0}{1} = {2}.Current(cast(IEnumerator__G!({0}))null);", typeString, WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), foreachIter)); Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false); writer.CloseBrace(); writer.WriteLine(""); // writer.CloseBrace (); foreachCount++; } else { var collections = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Collections")); Context.Instance.UsingDeclarations = Context.Instance.UsingDeclarations .Union(new[] { collections }).ToArray(); writer.WriteLine("//ForEach"); writer.WriteIndent(); writer.Write(string.Format("auto {0} = ", foreachIter)); Core.Write(writer, foreachStatement.Expression); writer.Write(".GetEnumerator();\r\n"); writer.WriteLine(string.Format("while({0}.MoveNext())", foreachIter)); writer.OpenBrace(); writer.WriteLine(string.Format("{0}{1} = UNBOX!({0})({2}.Current);", typeString, WriteIdentifierName.TransformIdentifier(foreachStatement.Identifier.Text), foreachIter)); Core.WriteStatementAsBlock(writer, foreachStatement.Statement, false); writer.CloseBrace(); writer.WriteLine(""); foreachCount++; } }
public static void Go(OutputWriter writer, MemberDeclarationSyntax field, SyntaxTokenList modifiers, string name, TypeSyntax type, EqualsValueClauseSyntax initializerOpt = null, bool isThreadStatic =false) { writer.WriteIndent(); var typeinfo = TypeProcessor.GetTypeInfo(type); // var isPtr = typeinfo.Type != null && (typeinfo.Type.IsValueType || typeinfo.Type.TypeKind==TypeKind.TypeParameter) ? "" : ""; var typeStringNoPtr = TypeProcessor.ConvertType(type); var typeString = typeStringNoPtr + " "; var isConst = IsConst(modifiers, initializerOpt, type); var isStatic = isConst; //Handle Auto Properties // if (modifiers.Any(SyntaxKind.PrivateKeyword)) // Reflection cannot work with this, cant get address or set value // writer.Write("private "); if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword)) writer.Write("public "); if (isThreadStatic) { writer.Write("static "); } if (modifiers.Any(SyntaxKind.StaticKeyword) || modifiers.Any(SyntaxKind.ConstKeyword)) { isStatic = true; writer.Write("__gshared "); } if (isConst && typeinfo.Type.IsPrimitive()) { writer.Write("const "); //const has interesting semantics in Dlang } var @event = field is EventFieldDeclarationSyntax; ITypeSymbol iface; ISymbol[] proxies; bool isInterface =false; // var ename = MemberUtilities.GetMethodName(field, ref isInterface, out iface, out proxies); if (@event) { typeString = ("__Event!(" + typeString + ")"); if (field.Parent is InterfaceDeclarationSyntax) { //writer.Write(typeString); writer.WriteLine(typeString + " " + name + "(" + TypeProcessor.ConvertType(field.Parent) +" __ij)" + "@property;"); return; } } writer.Write(typeString); // if (isStatic) // writer.Write(typeString); writer.Write(name); if (isStatic) { // var fieldInfo = TypeProcessor.GetDeclaredSymbol(field.Parent); // if (fieldInfo != null) // writer.Write((!string.IsNullOrEmpty(fieldInfo.ContainingNamespace.FullName())?(fieldInfo.ContainingNamespace.FullName()+".") :"") + fieldInfo.Name+"."+name); // writer.Write(name); } if (!isStatic || isConst) { if (initializerOpt != null) { writer.Write(String.Format(" = cast({0})", typeString)); if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression) { // writer.Write("gc::gc_ptr< " + typeStringNoPtr + " >("); writer.Write(" new " + typeString + " ("); var intializer = initializerOpt.Value as InitializerExpressionSyntax; intializer.WriteArrayInitializer(writer, type); writer.Write(")"); } else Core.Write(writer, initializerOpt.Value); } else { // if (typeinfo.Type.TypeKind != TypeKind.Struct) { writer.Write(" = "); if (typeinfo.Type.TypeKind == TypeKind.Delegate) writer.Write("new " + typeString + "()"); else writer.Write(TypeProcessor.DefaultValue(type)); } } } else { var staticWriter = new TempWriter(); if (initializerOpt != null) { staticWriter.Write(name); staticWriter.Write(" = "); if (CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind(initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression) { staticWriter.Write("new " + typeStringNoPtr + " ("); var intializer = initializerOpt.Value as InitializerExpressionSyntax; intializer.WriteArrayInitializer(staticWriter, type); staticWriter.Write(")"); } else Core.Write(staticWriter, initializerOpt.Value); staticWriter.Write(";"); staticWriter.WriteLine(); Context.Instance.StaticInits.Add(staticWriter.ToString()); } else if (typeinfo.Type.TypeKind != TypeKind.Struct) { staticWriter.Write(name); staticWriter.Write(" = "); if (typeinfo.Type.TypeKind == TypeKind.Delegate) staticWriter.Write("new " + typeString + "()"); else staticWriter.Write(TypeProcessor.DefaultValue(type)); staticWriter.Write(";"); staticWriter.WriteLine(); Context.Instance.StaticInits.Add(staticWriter.ToString()); } } writer.Write(";"); writer.WriteLine(); }
public static void Go(OutputWriter writer, ForStatementSyntax forStatement) { // writer.WriteLine(); // Beautify the code ... var tempWriter = new TempWriter(); tempWriter.WriteIndent(); tempWriter.Write("for ("); foreach (var init in forStatement.Initializers) { Core.Write(tempWriter, init); if (init != forStatement.Initializers.Last()) { tempWriter.Write(","); } } if (forStatement.Declaration != null) { var variables = forStatement.Declaration.Variables; foreach (var variable in variables) { // writer.WriteIndent(); tempWriter.Write(TypeProcessor.ConvertType(forStatement.Declaration.Type) + " "); tempWriter.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.ValueText)); if (variable.Initializer != null) { tempWriter.Write(" = "); Core.Write(tempWriter, variable.Initializer.Value); } if (variable != variables.LastOrDefault()) { tempWriter.Write(","); } } } tempWriter.Write(";"); if (forStatement.Condition == null) { tempWriter.Write("true"); } else { Core.Write(tempWriter, forStatement.Condition); } tempWriter.Write(";"); foreach (var iterator in forStatement.Incrementors) { Core.Write(tempWriter, iterator); if (iterator != forStatement.Incrementors.LastOrDefault()) { tempWriter.Write(","); } } tempWriter.Write(")"); writer.WriteLine(tempWriter.ToString()); writer.OpenBrace(); Core.WriteStatementAsBlock(writer, forStatement.Statement, false); writer.CloseBrace(); // writer.WriteLine(); // Beautify the code ... }
private static void WriteOneDelegate(OutputWriter outputWriter, Context.DelegateSyntaxAndSymbol first, bool fileExists) { Context.Instance.Namespace = first.Symbol.ContainingNamespace.FullName(); Context.Instance.Type = first.Symbol; TypeProcessor.ClearUsedTypes(); var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace"); // + "." + TypeState.Instance.TypeName; var myUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace)); var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")); // Required as certain functions like boxing are in this namespace Context.Instance.UsingDeclarations = first.Syntax.Parent.DescendantNodes().OfType<UsingDirectiveSyntax>().ToArray() .Union(new[] { myUsingDirective, SystemUsingDirective }).ToArray(); OutputWriter writer = null; using ( writer = outputWriter == null ? new OutputWriter(Context.Instance.Namespace, Context.Instance.TypeName) : new TempWriter()) { if (outputWriter != null) { writer.WriteLine(); writer.Indent = outputWriter.Indent + 2; writer.WriteIndent(); } writer.FileExists = fileExists; WriteBcl.Go(writer); WriteStandardIncludes.Go(writer); //Look for generic arguments { List<TypeParameterSyntax> genericArgs = new List<TypeParameterSyntax>(); if (first.Syntax.TypeParameterList != null) genericArgs = first.Syntax.TypeParameterList.Parameters.ToList(); var name = WriteType.TypeName(Context.Instance.Type, false); //Context.Instance.TypeName; if (genericArgs.Count > 0) { name = "template " + name; name += ("("); name += (string.Join(" , ", genericArgs.Select(o => o))); name += (")"); writer.WriteLine(name); writer.OpenBrace(); writer.WriteLine("alias __Delegate!(" + TypeProcessor.ConvertType(first.Syntax.ReturnType) + " delegate" + WriteMethod.GetParameterListAsString(first.Syntax.ParameterList.Parameters) + ") " + WriteType.TypeName(Context.Instance.Type, false) + ";"); writer.CloseBrace(); } else { //Non-generic writer.WriteLine("alias __Delegate!(" + TypeProcessor.ConvertType(first.Syntax.ReturnType) + " delegate" + WriteMethod.GetParameterListAsString(first.Syntax.ParameterList.Parameters) + ") " + WriteType.TypeName(Context.Instance.Type, false) + ";"); } } if (outputWriter != null) outputWriter.WriteLine(writer.ToString()); } }
public static void Go(OutputWriter writer, InvocationExpressionSyntax invocationExpression) { var symbolInfo = TypeProcessor.GetSymbolInfo(invocationExpression); var expressionSymbol = TypeProcessor.GetSymbolInfo(invocationExpression.Expression); var symbol = symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(); // Resolution error if (symbol == null) { writer.WriteLine("/*" + invocationExpression.ToFullString() +" //SharpNative Failed To Get Symbol */"); } var methodSymbol = symbol.OriginalDefinition.As<IMethodSymbol>().UnReduce(); var memberReferenceExpressionOpt = invocationExpression.Expression as MemberAccessExpressionSyntax; var firstParameter = true; var extensionNamespace = methodSymbol.IsExtensionMethod ? methodSymbol.ContainingNamespace.FullNameWithDot() + methodSymbol.ContainingType.FullName() : null; //null means it's not an extension method, non-null means it is string methodName; string typeParameters = null; ExpressionSyntax subExpressionOpt; if (expressionSymbol.Symbol is IEventSymbol) { methodName = "Invoke"; } else if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) methodName = null; else methodName = OverloadResolver.MethodName(methodSymbol); if (methodSymbol.ContainingType.TypeKind == TypeKind.Interface || Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(methodSymbol), methodSymbol)) { /* methodName = Regex.Replace(TypeProcessor.ConvertType(methodSymbol.ContainingType.OriginalDefinition) .RemoveFromStartOfString(methodSymbol.ContainingNamespace + ".Namespace.") + "_" + methodName, @" ?!\(.*?\)", string.Empty);*/ if (methodSymbol.ContainingType.ContainingType != null) methodName = methodName.RemoveFromStartOfString(methodSymbol.ContainingType.ContainingType.Name + "."); } var interfaceMethods = methodSymbol.ContainingType.AllInterfaces.SelectMany( u => u.GetMembers(methodName)).ToArray(); ISymbol interfaceMethod = interfaceMethods.FirstOrDefault( o => methodSymbol.ContainingType.FindImplementationForInterfaceMember(o) == methodSymbol); // if (interfaceMethod == null) // { // //TODO: fix this for virtual method test 7, seems roslyn cannot deal with virtual // // overrides of interface methods ... so i'll provide a kludge // if (!method.Modifiers.Any(SyntaxKind.NewKeyword)) // interfaceMethod = interfaceMethods.FirstOrDefault(k => CompareMethods(k as IMethodSymbol, methodSymbol)); // } if (interfaceMethod != null) // && CompareMethods(interfaceMethod ,methodSymbol)) { { //This is an interface method //TO if (methodSymbol.ContainingType.SpecialType == SpecialType.System_Array) writer.Write(""); else { /* var typenameI = Regex.Replace( TypeProcessor.ConvertType(interfaceMethod.ContainingType.ConstructedFrom, true), @" ?!\(.*?\)", string.Empty); //TODO: we should be able to get the original interface name, or just remove all generics from this if (typenameI.Contains('.')) typenameI = typenameI.SubstringAfterLast('.'); writer.Write(typenameI + "_");*/ } } var containingType = interfaceMethod == null ? methodSymbol.ContainingType : interfaceMethod.ContainingType; bool isVirtualGeneric = methodSymbol.IsGenericMethod && (methodSymbol.IsVirtual || methodSymbol.ContainingType.TypeKind == TypeKind.Interface) && !containingType.IsAssignableFrom(Context.Instance.Type);// !(invocationExpression.Expression is BaseExpressionSyntax); if (isVirtualGeneric) methodName = TypeProcessor.ConvertType(containingType,false,false,false).Replace(".", "_") + "_" + methodName; if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) subExpressionOpt = invocationExpression.Expression; else if (memberReferenceExpressionOpt != null) { if (memberReferenceExpressionOpt.Expression is PredefinedTypeSyntax) subExpressionOpt = null; else subExpressionOpt = memberReferenceExpressionOpt.Expression; } else subExpressionOpt = null; //When the code specifically names generic arguments, include them in the method name ... dmd needs help with inference, so we give it the types anyway if (methodSymbol.IsGenericMethod) { //return TryConvertType(named) + (named.TypeKind == TypeKind.Struct && o.ConstraintTypes.Any(k => k.TypeKind == //TypeKind.Interface) ? ".__Boxed_" : ""); var named = ((IMethodSymbol)symbol); typeParameters = "!(" + named.TypeArguments.Select(o => TypeProcessor.GetGenericParameterType(named.TypeParameters[named.TypeArguments.IndexOf(o)], o)).Aggregate((a, b) => a + ", " + b) + ")"; // typeParameters = "!( " + // string.Join(", ", // ((IMethodSymbol) symbol).TypeArguments.Select(r => TypeProcessor.ConvertType(r) )) + // " )"; } //Determine if it's an extension method called in a non-extension way. In this case, just pretend it's not an extension method if (extensionNamespace != null && subExpressionOpt != null && TypeProcessor.GetTypeInfo(subExpressionOpt).ConvertedType.ToString() == methodSymbol.ContainingNamespace.FullName() + "." + methodSymbol.ContainingType.FullName()) extensionNamespace = null; var memberType = memberReferenceExpressionOpt == null ? null : TypeProcessor.GetTypeInfo(memberReferenceExpressionOpt.Expression).Type; var isNullableEnum = memberType != null && (memberType.Name == "Nullable" && memberType.ContainingNamespace.FullName() == "System") && memberType.As<INamedTypeSymbol>().TypeArguments.Single().TypeKind == TypeKind.Enum; // if (isNullableEnum && methodSymbol.Name == "ToString") // { // extensionNamespace = null; //override Translations.xml for nullable enums. We want them to convert to the enum's ToString method // methodName = "toString"; // } //Invocation on basics should come from boxing the basic then calling on the boxed type, unless static var directInvocationOnBasics = methodSymbol.ContainingType.IsBasicType() && methodSymbol.IsStatic; //&& methodSymbol.ContainingType!=Context.Instance.Type; //If we are currently working on a basic type e.g. in corlib, don't alter the code //Extension methods in Dlang are straightforward, although this could lead to clashes without qualification string instanceName =null; if (extensionNamespace != null || directInvocationOnBasics) { if (extensionNamespace == null) { extensionNamespace = TypeProcessor.ConvertType(methodSymbol.ContainingType, true, false); // methodSymbol.ContainingNamespace.FullName() + "." + methodSymbol.ContainingType.Name; //memberType.ContainingNamespace.FullName() +"."+ memberType.Name; } if (!isVirtualGeneric) { writer.Write(extensionNamespace); if (methodName != null) { methodName = WriteIdentifierName.TransformIdentifier(methodName); // if (symbolInfo.Symbol.ContainingType != Context.Instance.Type) writer.Write("."); writer.Write(methodName); } } else { writer.Write(methodName); } WriteTypeParameters(writer, typeParameters, invocationExpression); writer.Write("("); if (subExpressionOpt != null) { firstParameter = false; Core.Write(writer, subExpressionOpt); } } else { if (memberReferenceExpressionOpt != null) { } if (subExpressionOpt != null) { if (!isVirtualGeneric) { WriteMemberAccessExpression.WriteMember(writer, subExpressionOpt); // if (!(subExpressionOpt is BaseExpressionSyntax)) // { // if (methodName != null && methodSymbol.IsStatic) // writer.Write("."); // else // { if (methodSymbol.MethodKind != MethodKind.DelegateInvoke) writer.Write("."); } else { instanceName = WriteMemberAccessExpression.WriteMemberToString(subExpressionOpt); } // } // } // writer.Write("."); } else if (methodSymbol.IsStatic && extensionNamespace == null) { if (methodSymbol.ContainingType != Context.Instance.Type) { var str = TypeProcessor.ConvertType(methodSymbol.ContainingType); if (str == "Array_T") // Array is the only special case, otherwise generics have to be specialized to access static members str = "Array"; writer.Write(str); // writer.Write(methodSymbol.ContainingNamespace.FullNameWithDot()); // writer.Write(WriteType.TypeName(methodSymbol.ContainingType)); writer.Write("."); } } if (methodSymbol.MethodKind != MethodKind.DelegateInvoke) { var declaringSyntaxReferences = methodSymbol.DeclaringSyntaxReferences.Select(j => j.GetSyntax()) .OfType<MethodDeclarationSyntax>(); var methodDeclarationSyntaxs = declaringSyntaxReferences as MethodDeclarationSyntax[] ?? declaringSyntaxReferences.ToArray(); var any = methodDeclarationSyntaxs.Any(); if (any && methodDeclarationSyntaxs.FirstOrDefault() .As<MethodDeclarationSyntax>() .Modifiers.Any(SyntaxKind.NewKeyword)) { //TODO: this means that new is not supported on external libraries // //why doesnt roslyn give me this information ? //methodName += "_"; //Not needed anymore :) } if (any && methodDeclarationSyntaxs.FirstOrDefault() .As<MethodDeclarationSyntax>() .Modifiers.Any(SyntaxKind.NewKeyword)) { // if (symbolInfo.Symbol.ContainingType != Context.Instance.Type) writer.Write(WriteIdentifierName.TransformIdentifier(methodSymbol.ContainingType.Name,methodSymbol.ContainingType) + "."); } methodName = WriteIdentifierName.TransformIdentifier(methodName); writer.Write(methodName); } WriteTypeParameters(writer, typeParameters, invocationExpression); writer.Write("("); } bool inParams = false; bool foundParamsArray = false; var arguments = invocationExpression.ArgumentList.Arguments; ITypeSymbol typeSymbol = null; bool isOverloaded = methodSymbol.ContainingType.GetMembers(methodSymbol.Name).OfType<IMethodSymbol>().Any(j => j.TypeParameters == methodSymbol.TypeParameters && ParameterMatchesWithRefOutIn(methodSymbol, j)); WriteArguments(writer, invocationExpression, arguments, firstParameter, inParams, methodSymbol, foundParamsArray, typeSymbol, isOverloaded, symbol,instanceName); }
public static void WriteInstanceConstructor(OutputWriter writer, ConstructorDeclarationSyntax method, List <string> otherInits) { writer.WriteLine(); var accessmodifiers = ""; var isInterface = method.Parent is InterfaceDeclarationSyntax; if (method.Modifiers.Any(SyntaxKind.PublicKeyword) || method.Modifiers.Any(SyntaxKind.InternalKeyword) || method.Modifiers.Any(SyntaxKind.ProtectedKeyword) || method.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) { accessmodifiers += ("public "); } // Reflection cannot work with this, cant get address or set value //if (method.Modifiers.Any(SyntaxKind.PrivateKeyword)) // accessmodifiers += ("private "); if (method.Modifiers.Any(SyntaxKind.StaticKeyword)) { accessmodifiers += ("static "); } var constructorName = "this"; if (Context.Instance.Type.TypeKind == TypeKind.Struct) // Struct { constructorName = " void __init"; } writer.WriteLine(accessmodifiers + constructorName + WriteMethod.GetParameterListAsString(method.ParameterList.Parameters)); if (isInterface || method.Modifiers.Any(SyntaxKind.AbstractKeyword)) { writer.Write(" = 0;\r\n"); return; } //if (!returnsVoid) // writer.Write(" ="); // writer.Write("\r\n"); writer.OpenBrace(); if (otherInits != null) //We need to write the static initializers before anything else { foreach (var statement in otherInits) { var nodeString = statement; if (nodeString != null) { writer.WriteLine(nodeString); } } } if (method.Initializer != null) { //writer.Write(":"); Core.Write(writer, method.Initializer); writer.Write(";"); writer.WriteLine(); //";\r\n"); } if (method.Body != null) { foreach (var statement in method.Body.Statements) { Core.Write(writer, statement); } TriviaProcessor.ProcessTrivias(writer, method.Body.DescendantTrivia()); } writer.CloseBrace(); }
public static void WriteAnonymousType(AnonymousObjectCreationExpressionSyntax syntax) { var type = TypeProcessor.GetTypeInfo(syntax).Type.As<INamedTypeSymbol>(); Context.Instance.Type = type; TypeProcessor.ClearUsedTypes(); var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace"); // + "." + TypeState.Instance.TypeName; Context.Instance.Namespace = mynamespace; var myUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace)); var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")); // Required as certain functions like boxing are in this namespace Context.Instance.UsingDeclarations = syntax.Parent.DescendantNodes().OfType<UsingDirectiveSyntax>().ToArray() .Union(new[] { myUsingDirective, SystemUsingDirective }).ToArray(); //using (var writer = new CppWriter (TypeState.Instance.Namespace, )) { //Ty var anonName = TypeName(type); using (var writer = new OutputWriter(Context.Instance.Namespace, StripGeneric(anonName))) { var fields = type.GetMembers().OfType<IPropertySymbol>().OrderBy(o => o.Name).ToList(); // writer.WriteLine("namespace anonymoustypes {"); WriteStandardIncludes.Go(writer); writer.WriteIndent(); writer.Write("class "); writer.Write(anonName); writer.OpenBrace(); foreach (var field in fields) { writer.WriteIndent(); writer.Write("public "); writer.Write(TypeProcessor.ConvertType(field.Type) + " "); writer.Write(WriteIdentifierName.TransformIdentifier(field.Name)); writer.Write(" = " + TypeProcessor.DefaultValue(field.Type)); writer.Write(";\r\n"); } //Must Write a constructor here ... writer.Write("\r\nthis ("); bool first = true; foreach (var field in fields) { if (first) first = false; else writer.Write(", "); writer.Write(TypeProcessor.ConvertType(field.Type) + " "); writer.Write("_" + WriteIdentifierName.TransformIdentifier(field.Name)); } writer.Write(")\r\n"); writer.OpenBrace(); writer.Indent++; foreach (var field in fields) { var fieldNAme = WriteIdentifierName.TransformIdentifier(field.Name); writer.WriteLine(fieldNAme + " = _" + fieldNAme + ";"); } writer.Indent--; writer.CloseBrace(); writer.CloseBrace(); // writer.Write("};"); // writer.Write("}"); } }
public static void Go(OutputWriter writer, UnsafeStatementSyntax checkedExpressionSyntax) { writer.WriteLine("//Unsafe"); Core.Write(writer, checkedExpressionSyntax.Block); }
public static void WriteStaticConstructor(OutputWriter writer, ConstructorDeclarationSyntax staticConstructor, List<string> otherStatics) { if (staticConstructor.Body == null && (otherStatics == null || otherStatics.Count == 0)) return; writer.WriteLine(); writer.WriteLine("static this()"); writer.OpenBrace(); if (otherStatics != null) //We need to write the static initializers before anything else { foreach (var statement in otherStatics) { var nodeString = statement; if (nodeString != null) writer.WriteLine(nodeString); } } if (staticConstructor.Body != null) { foreach (var statement in staticConstructor.Body.As<BlockSyntax>().Statements) Core.Write(writer, statement); } writer.CloseBrace(); StaticConstructors.Add(Context.Instance.Partials.First().Symbol.ContainingNamespace.FullNameWithDot() + Context.Instance.TypeName); }
public static void Go(OutputWriter writer, EventDeclarationSyntax property) { writer.WriteLine("\r\n"); var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c# var isInterface = property.Parent is InterfaceDeclarationSyntax; var add = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal)SyntaxKind.AddKeyword); var remove = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal)SyntaxKind.RemoveKeyword); var methodSymbol = (TypeProcessor.GetDeclaredSymbol(add) ?? TypeProcessor.GetDeclaredSymbol(remove)) as IMethodSymbol; Action <AccessorDeclarationSyntax, bool> writeRegion = (region, get) => { writer.WriteIndent(); // if (property.Modifiers.Any(SyntaxKind.PrivateKeyword)) // writer.HeaderWriter.Write("private:\n"); // // if (property.Modifiers.Any(SyntaxKind.PublicKeyword) || property.Modifiers.Any(SyntaxKind.InternalKeyword)) // writer.HeaderWriter.Write("public "); var typeinfo = TypeProcessor.GetTypeInfo(property.Type); var isPtr = ""; var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " "; if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null) { writer.Write(" abstract "); } if (property.Modifiers.Any(SyntaxKind.OverrideKeyword)) { writer.Write(" override "); } //TODO: look at final and other optimizations // if (!(property.Modifiers.Any (SyntaxKind.VirtualKeyword) || (property.Modifiers.Any (SyntaxKind.AbstractKeyword)) || isInterface || property.Modifiers.Any(SyntaxKind.OverrideKeyword)) ) { // writer.Write(" final "); // } //no inline in D // if (get) // { // writer.Write(" " + rEf+ typeString + " "); // writer.Write(typeString + " "); // } // else // { // writer.Write("_=(value"); // writer.Write(TypeProcessor.ConvertTypeWithColon(property.Type)); // writer.Write(")"); writer.Write("void "); // writer.Write(" " + "void "); // } //not needed for Dlang var methodName = (get ? "" : "") + WriteIdentifierName.TransformIdentifier(property.Identifier.ValueText); var explicitHeaderNAme = ""; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation) { var implementations = methodSymbol.ExplicitInterfaceImplementations[0]; if (implementations != null) { explicitHeaderNAme = implementations.Name; methodName = //implementations.ReceiverType.FullName() + "." + implementations.Name; //Explicit fix ? // writer.Write(methodSymbol.ContainingType + "." + methodName); //Looks like internal classes are not handled properly here ... } } if (methodSymbol != null) { // methodName = methodName.Replace(methodSymbol.ContainingNamespace.FullName() + ".", methodSymbol.ContainingNamespace.FullName() + "."); // writer.Write((methodSymbol.ContainingType.FullName() + "." + methodName) + (get ? "()" : "( " + typeString + " value )")); //Dealing with explicit VMT7 } if (property.Modifiers.Any(SyntaxKind.NewKeyword)) { methodName += "_"; } writer.Write( //(!String.IsNullOrEmpty(explicitHeaderNAme) ? explicitHeaderNAme : methodName) (get ? "Add_" : "Remove_") + methodName + "( " + typeString + " value )"); if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null) { writer.Write(";\r\n"); } else { // writer.Write(";\r\n"); writer.OpenBrace(); // writer.Write(" =\r\n"); Core.WriteBlock(writer, region.Body.As <BlockSyntax>()); writer.CloseBrace(); writer.Write("\r\n"); } }; if (add == null && remove == null) { throw new Exception("Property must have either a get or a set"); } // if (getter != null && setter != null && setter.Body == null && getter.Body == null) { //Both get and set are null, which means this is an automatic property. For our purposes, this is the equivilant of a field//Nope // WriteField.Go(writer,property, property.Modifiers, WriteIdentifierName.TransformIdentifier(property.Identifier.ValueText), property.Type); var name = WriteIdentifierName.TransformIdentifier(property.Identifier.ValueText); var type = property.Type; var typeinfo = TypeProcessor.GetTypeInfo(type); var modifiers = property.Modifiers; var isPtr = typeinfo.Type != null && (typeinfo.Type.IsValueType || typeinfo.Type.TypeKind == TypeKind.TypeParameter) ? "" : ""; var typeString = TypeProcessor.ConvertType(type) + isPtr + " "; var isStatic = false; //Handle Auto Properties var accessors = property.AccessorList.Accessors; //.Where(o=>o.Body==null); var accessString = ""; if (modifiers.Any(SyntaxKind.PrivateKeyword)) { accessString += (" private "); } if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) { accessString += (" public "); } // if (!(property.Modifiers.Any (SyntaxKind.VirtualKeyword) || (property.Modifiers.Any (SyntaxKind.AbstractKeyword)))) { // writer.Write(" final "); // } // if (modifiers.Any(SyntaxKind.PublicKeyword) || method.Modifiers.Any(SyntaxKind.InternalKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword)) // writer.HeaderWriter.WriteLine("public: "); var IsStatic = ""; if (modifiers.Any(SyntaxKind.StaticKeyword)) { isStatic = true; IsStatic = accessString += " static "; // writer.HeaderWriter.Write("static "); } var fieldName = "__evt__" + name; if (!isStatic) { writer.Write("private " + "Event!(" + typeString + ") " + fieldName + ";\r\n"); // Internal Field used for event writer.Write(accessString); writer.WriteLine("Event!(" + typeString + ") " + name + "() @property"); writer.OpenBrace(); writer.WriteLine("if (" + fieldName + " is null)"); writer.OpenBrace(); writer.Write(fieldName + " = new " + "Event!(" + typeString + ")(new Action_T!(" + typeString + ")(&Add_" + name + "),new Action_T!(" + typeString + ")(&Remove_" + name + ") );"); writer.CloseBrace(); writer.Write("return " + fieldName + ";"); writer.CloseBrace(); } else { writer.Write(IsStatic); writer.Write("Event!(" + typeString + ") " + name + ";\r\n"); } // var isOverride = property.Modifiers.Any(SyntaxKind.NewKeyword) || property.Modifiers.Any(SyntaxKind.OverrideKeyword) ? " override " : ""; var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) || property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface ? " abstract " : ""; // if(!isInterface) // if ((add!=null && add.Body == null) || // (remove != null && remove.Body == null) && (!property.Modifiers.Any(SyntaxKind.AbstractKeyword))) // { // // writer.Write (IsStatic); // var initString = "";//isStatic?"":(" = " + TypeProcessor.DefaultValue (type)); // writer.Write (typeString + fieldName + initString + ";\r\n"); // // } //Adder if (add != null && add.Body == null) { writer.Write(IsStatic); //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface) { writer.WriteLine(" " + isVirtual + " void Add_" + name + "(" + typeString + " value)" + isOverride + "" + ";"); } // else // writer.WriteLine(" "+isVirtual + " void Add_" + name + "(" + typeString + " value)" + // isOverride + " {" + fieldName + " = value;}"); } else if (add != null) { writer.Write(IsStatic); writeRegion(add, true); } //Remover if (remove != null && remove.Body == null) { writer.Write(IsStatic); //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface) { writer.WriteLine(" " + isVirtual + " void Remove_" + name + "(" + typeString + " value)" + isOverride + "" + ";"); } //else // writer.WriteLine(" "+isVirtual + " void Remove_" + name + "(" + typeString + " value)" + // isOverride + " {" + fieldName + " = value;}"); } else if (remove != null) { writer.Write(IsStatic); writeRegion(remove, false); } if (isStatic) { var staticWriter = new OutputWriter("", "", false); staticWriter.Write(name); staticWriter.Write(" = new " + "Event!(" + typeString + ")(new Action_T!(" + typeString + ")(__ToDelegate(&Add_" + name + ")),new Action_T!(" + typeString + ")(__ToDelegate(&Remove_" + name + ")) )"); staticWriter.Write(";"); staticWriter.WriteLine(); Context.Instance.StaticInits.Add(staticWriter.ToString()); } else { var staticWriter = new OutputWriter("", "", false); staticWriter.Write(name); staticWriter.Write(" = new " + "Event!(" + typeString + ")(new Action_T!(" + typeString + ")((&Add_" + name + ")),new Action_T!(" + typeString + ")((&Remove_" + name + ")) )"); staticWriter.Write(";"); staticWriter.WriteLine(); Context.Instance.InstanceInits.Add(staticWriter.ToString()); } // if (CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression) // { // // // staticWriter.Write ("new " + typeStringNoPtr + " (["); // // // } // Core.Write (staticWriter, initializerOpt.Value); // if (CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind (initializerOpt.Value) == SyntaxKind.ArrayInitializerExpression) // { // // // staticWriter.Write ("])"); // } } }
public static void Go(OutputWriter writer, BasePropertyDeclarationSyntax property, bool isProxy = false) { writer.WriteLine(); //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c# var isInterface = property.Parent is InterfaceDeclarationSyntax; var getter = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal)SyntaxKind.GetKeyword); var setter = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal)SyntaxKind.SetKeyword); var isYield = getter != null && getter.DescendantNodes().OfType<YieldStatementSyntax>().Any(); var isStatic = property.Modifiers.Any (k=>k.IsKind(SyntaxKind.StaticKeyword)); ITypeSymbol iface; ISymbol[] proxies; var name = MemberUtilities.GetMethodName(property, ref isInterface, out iface, out proxies); var modifiers = property.Modifiers; var propertySymbol = (IPropertySymbol)TypeProcessor.GetDeclaredSymbol(property); var type = propertySymbol.Type; var acccessmodifiers = MemberUtilities.GetAccessModifiers(property, isInterface || propertySymbol.IsAbstract); var typeString = TypeProcessor.ConvertType(type); var hasGetter = getter != null; var getterHasBody = hasGetter && getter.Body != null; var hasSetter = setter != null; var setterHasBody = hasSetter && setter.Body != null; var indexerDeclarationSyntax = property as IndexerDeclarationSyntax; var isindexer = indexerDeclarationSyntax != null; string getterbody = null; if (getterHasBody) { getterbody = Core.WriteBlock(getter.Body, false, writer.Indent + 2); if (!isProxy && isYield) { var namedTypeSymbol = propertySymbol.Type as INamedTypeSymbol; if (namedTypeSymbol != null) { // var iteratortype = namedTypeSymbol.TypeArguments[0]; // getterbody=String.Format("return new __IteratorBlock!({0})(delegate(__IteratorBlock!({0}) __iter){{ {1} }});", // TypeProcessor.ConvertType(iteratortype),getterbody); var className = propertySymbol.GetYieldClassName()+( (((INamedTypeSymbol)propertySymbol.Type).TypeArguments.Any() && ((INamedTypeSymbol)propertySymbol.Type).TypeArguments[0].TypeKind == TypeKind.TypeParameter) ? "__G" : ""); // writer.WriteLine(accessString + returnTypeString + methodSignatureString + @params2 + constraints); //writer.OpenBrace(); if (!propertySymbol.IsStatic) { getterbody = writer.WriteIndentToString() + ("return new " + className + "(this);"); } else { getterbody = writer.WriteIndentToString() + ("return new " + className + "();"); } } } } string setterbody = null; if (setterHasBody) { setterbody = Core.WriteString (setter.Body, false, writer.Indent + 2); if (isindexer) { setterbody += writer.WriteIndentToString()+ "return value;"; } else { if (hasGetter) { setterbody += writer.WriteIndentToString() + "return " + name + ";"; } } } if (getter == null && setter == null) throw new Exception("Property must have either a get or a set"); string isOverride; var fieldName = WriteAutoFieldName(writer, name, modifiers, isInterface, hasGetter, getterHasBody, hasSetter, setterHasBody, typeString, out isOverride, (property is IndexerDeclarationSyntax)); BracketedParameterListSyntax @params = null; if (indexerDeclarationSyntax != null) { @params = indexerDeclarationSyntax.ParameterList; } string parameters = null; if (@params != null) { parameters = WriteMethod.GetParameterListAsString(@params.Parameters, iface: proxies == null ? iface : null, writebraces: false); } WriteGetter(writer, isProxy, hasGetter, acccessmodifiers, typeString, name, proxies == null ? iface : null, getterHasBody, modifiers, isInterface, fieldName, getterbody, parameters, indexerDeclarationSyntax != null); WriteSetter(writer, isProxy, hasSetter, acccessmodifiers, name, typeString, proxies == null ? iface : null, isOverride, setterHasBody, modifiers, isInterface, fieldName, setterbody, parameters, isindexer,hasGetter); // if (!isindexer && !isInterface) //TODO: Find a better solution // { // var fieldacccessmodifiers = acccessmodifiers.Replace ("abstract", "").Replace ("virtual","").Replace("override",""); // // writer.WriteLine(fieldacccessmodifiers + "__Property!(" + typeString + ")" + name + ";"); // if (isStatic) // { // var staticWriter = new TempWriter (); // // staticWriter.WriteLine (name + String.Format (" = __Property!(" + typeString + ")(__ToDelegate(&set{0}), __ToDelegate(&get{0}));", name)); // Context.Instance.StaticInits.Add (staticWriter.ToString ()); // } // else // { // var instanceWriter = new TempWriter (); // // instanceWriter.WriteLine (name + String.Format (" = __Property!(" + typeString + ")((&set{0}), (&get{0}));", name)); // Context.Instance.InstanceInits.Add (instanceWriter.ToString ()); // } // } if (proxies != null) { foreach (var proxy in proxies) { if (indexerDeclarationSyntax == null) { setterbody = writer.WriteIndentToString() + name + "=" + "value" + ";"; getterbody = writer.WriteIndentToString() + "return " + name + ";"; } else { string parameters2=""; if (@params != null) { parameters2 = WriteMethod.GetParameterListAsString(@params.Parameters, iface: null, includeTypes: false,writebraces:false); // parameters2 = WriteMethod.GetParameterListAsString(@params.Parameters, iface: proxies == null ? iface : null, writebraces: false); } setterbody = writer.WriteIndentToString() + "return opIndexAssign(value," + parameters2 + ");";// + "=" + "value" + ";"; getterbody = writer.WriteIndentToString() + "return opIndex(" + parameters2 + ");"; } parameters = null; if (@params != null) { parameters = WriteMethod.GetParameterListAsString(@params.Parameters, iface: proxy.ContainingType, writebraces: false); } WriteGetter(writer, isProxy, hasGetter, acccessmodifiers, typeString, name, proxy.ContainingType, getterHasBody, modifiers, isInterface, fieldName, getterbody, parameters, isindexer); WriteSetter (writer, isProxy, hasSetter, acccessmodifiers, name, typeString, proxy.ContainingType, isOverride, setterHasBody, modifiers, isInterface, fieldName, setterbody, parameters, isindexer,hasGetter); } } }
public static void Go(OutputWriter writer, BreakStatementSyntax statement) { writer.WriteLine("break;"); }
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(); }
public static void Go(OutputWriter writer, string methodName, IMethodSymbol methodSymbol, AttributeSyntax pinvokeAttributes) { //Do Pinvoke stuff //PInvokeFunction < int (int, double)> foo(library, "foo"); //int i = foo(42, 2.0); // var methodParams = methodSymbol.Parameters.Any () ? methodSymbol.Parameters.Select (h => ConvertPInvokeType (h.Type)).Aggregate ((k, y) => (k) + " ," + y) : ""; var returnString = ConvertPInvokeType(methodSymbol.ReturnType); if (pinvokeAttributes != null) { var attributeArgumentSyntax = pinvokeAttributes.ArgumentList.Arguments.FirstOrDefault(k => k.Expression != null); string dllImport = attributeArgumentSyntax.ToFullString(); // AttributeSyntax import = // Context.Instance.DllImports.FirstOrDefault( // d => // d.ArgumentList.Arguments.FirstOrDefault( // k => // k.Expression != null && // k.Expression.ToString() == // pinvokeAttributes.ArgumentList.Arguments.FirstOrDefault(g => g.Expression != null) // .Expression.ToString()) != null); // if (import != null) // dllImportId = Context.Instance.DllImports.IndexOf(import); // // if (dllImportId == -1) // { // Context.Instance.DllImports.Add(pinvokeAttributes); // dllImportId = Context.Instance.DllImports.IndexOf(pinvokeAttributes); // } var functionCall = String.Format("extern (C) {0} function ({1})", returnString, GetParameterList(methodSymbol.Parameters)); writer.WriteLine("alias " + functionCall + " " + methodName + "_func_alias;"); var convertedParameters = ConvertParameters(methodSymbol.Parameters); if (attributeArgumentSyntax.Expression is IdentifierNameSyntax) { writer.WriteLine( String.Format("auto {1} = cast({2}) __LoadLibraryFunc(__DllImportMap[{0}.text], \"{1}\");", dllImport, methodName, methodName + "_func_alias")); } else { writer.WriteLine( String.Format("auto {1} = cast({2}) __LoadLibraryFunc(__DllImportMap[{0}], \"{1}\");", dllImport, methodName, methodName + "_func_alias")); } writer.WriteLine(String.Format((returnString != "void" ? "return " : "") + "{0}({1});", methodName, convertedParameters.Count > 0 ? convertedParameters.Select(h => h).Aggregate((k, y) => (k) + " ," + y) : "")); if (dllImport != null && !Context.Instance.DllImports.Contains(dllImport)) { var staticWriter = new TempWriter(); if (attributeArgumentSyntax.Expression is IdentifierNameSyntax) staticWriter.WriteLine("__SetupDllImport({0}.text);", dllImport); else staticWriter.WriteLine("__SetupDllImport({0});", dllImport); Context.Instance.StaticInits.Add(staticWriter.ToString()); Context.Instance.DllImports.Add(dllImport); } } else { var convertedParameters = ConvertParameters(methodSymbol.Parameters); writer.WriteLine("//Extern (Internal) Method Call"); var methodInternalName = TypeProcessor.ConvertType(methodSymbol.ContainingType,false).Replace(".Namespace.","_").Replace(".","_")+ "_" + methodName; writer.WriteLine(String.Format((returnString != "void" ? "return " : "") + "{0}({1});", methodInternalName, convertedParameters.Count > 0 ? convertedParameters.Select(h => h).Aggregate((k, y) => (k) + " ," + y) : "")); } }
public static void Go(OutputWriter writer, ContinueStatementSyntax statement) { writer.WriteLine("continue;"); }
public static void WriteInstanceConstructor(OutputWriter writer, ConstructorDeclarationSyntax method, List<string> otherInits) { writer.WriteLine(); var accessmodifiers = ""; var isInterface = method.Parent is InterfaceDeclarationSyntax; if (method.Modifiers.Any(SyntaxKind.PublicKeyword) || method.Modifiers.Any(SyntaxKind.InternalKeyword) || method.Modifiers.Any(SyntaxKind.ProtectedKeyword) || method.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) accessmodifiers += ("public "); // Reflection cannot work with this, cant get address or set value //if (method.Modifiers.Any(SyntaxKind.PrivateKeyword)) // accessmodifiers += ("private "); if (method.Modifiers.Any(SyntaxKind.StaticKeyword)) accessmodifiers += ("static "); var constructorName = "this"; if (Context.Instance.Type.TypeKind == TypeKind.Struct) // Struct { constructorName = " void __init"; } writer.WriteLine(accessmodifiers + constructorName + WriteMethod.GetParameterListAsString(method.ParameterList.Parameters)); if (isInterface || method.Modifiers.Any(SyntaxKind.AbstractKeyword)) { writer.Write(" = 0;\r\n"); return; } //if (!returnsVoid) // writer.Write(" ="); // writer.Write("\r\n"); writer.OpenBrace(); if (otherInits != null) //We need to write the static initializers before anything else { foreach (var statement in otherInits) { var nodeString = statement; if (nodeString != null) writer.WriteLine(nodeString); } } if (method.Initializer != null) { //writer.Write(":"); Core.Write(writer, method.Initializer); writer.Write(";"); writer.WriteLine(); //";\r\n"); } if (method.Body != null) { foreach (var statement in method.Body.Statements) Core.Write(writer, statement); TriviaProcessor.ProcessTrivias(writer, method.Body.DescendantTrivia()); } writer.CloseBrace(); }
public static void Go(OutputWriter writer, EventDeclarationSyntax property) { writer.WriteLine("\r\n"); var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c# var isInterface = property.Parent is InterfaceDeclarationSyntax; var add = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal)SyntaxKind.AddKeyword); var remove = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal)SyntaxKind.RemoveKeyword); var eventSymbol = TypeProcessor.GetDeclaredSymbol(property); var methodSymbol = (TypeProcessor.GetDeclaredSymbol(add) ?? TypeProcessor.GetDeclaredSymbol(remove)) as IMethodSymbol; ITypeSymbol interfaceImplemented; ISymbol[] proxies; ; var methodName = WriteIdentifierName.TransformIdentifier(MemberUtilities.GetMethodName(eventSymbol, ref isInterface, out interfaceImplemented, out proxies)); Action <AccessorDeclarationSyntax, bool> writeRegion = (region, get) => { writer.WriteIndent(); // if (property.Modifiers.Any(SyntaxKind.PrivateKeyword)) // writer.HeaderWriter.Write("private:\n"); // // if (property.Modifiers.Any(SyntaxKind.PublicKeyword) || property.Modifiers.Any(SyntaxKind.InternalKeyword)) // writer.HeaderWriter.Write("public "); var typeinfo = TypeProcessor.GetTypeInfo(property.Type); var isPtr = ""; var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " "; if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null) { writer.Write(" abstract "); } if (property.Modifiers.Any(SyntaxKind.OverrideKeyword)) { writer.Write(" override "); } writer.Write("void "); writer.Write( (get ? "Add_" : "Remove_") + methodName + "( " + typeString + " value"); if (isInterface) { writer.WriteLine(" , " + TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null"); } writer.Write(" )"); if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null) { writer.Write(";\r\n"); } else { // writer.Write(";\r\n"); writer.OpenBrace(); // writer.Write(" =\r\n"); Core.WriteBlock(writer, region.Body.As <BlockSyntax>()); writer.CloseBrace(); writer.Write("\r\n"); } }; if (add == null && remove == null) { throw new Exception("Event must have both a add and remove"); } { var name = WriteIdentifierName.TransformIdentifier(property.Identifier.Text); var type = property.Type; var typeinfo = TypeProcessor.GetTypeInfo(type); var modifiers = property.Modifiers; var typeString = TypeProcessor.ConvertType(type) + " "; var isStatic = false; //Handle Auto Properties var accessors = property.AccessorList.Accessors; //.Where(o=>o.Body==null); var accessString = ""; if (modifiers.Any(SyntaxKind.PrivateKeyword)) { accessString += (" private "); } if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) { accessString += (" public "); } var IsStatic = ""; if (modifiers.Any(SyntaxKind.StaticKeyword)) { isStatic = true; IsStatic = accessString += " static "; // writer.HeaderWriter.Write("static "); } var fieldName = "__evt__" + name + (interfaceImplemented != null?TypeProcessor.ConvertType(interfaceImplemented) .Replace("(", "_").Replace("!", "_").Replace(")", "_").Replace(".", "_") :""); if (!(property.Parent is InterfaceDeclarationSyntax)) { if (!isStatic) { writer.Write("private " + "__Event!(" + typeString + ") " + fieldName + ";\r\n"); // Internal Field used for event writer.Write(accessString); writer.WriteLine("__Event!(" + typeString + ") " + name + "(" + (interfaceImplemented != null ? (TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null") :"") + ") @property"); writer.OpenBrace(); writer.WriteLine("if (" + fieldName + " is null)"); writer.OpenBrace(); writer.Write(fieldName + " = new " + "__Event!(" + typeString + ")(new Action__G!(" + typeString + ")(&Add_" + name + "),new Action__G!(" + typeString + ")(&Remove_" + name + ") );"); writer.CloseBrace(); writer.Write("return " + fieldName + ";"); writer.CloseBrace(); } else { writer.Write(IsStatic); writer.Write("__Event!(" + typeString + ") " + name + ";\r\n"); } } // var isOverride = property.Modifiers.Any(SyntaxKind.NewKeyword) || property.Modifiers.Any(SyntaxKind.OverrideKeyword) ? " override " : ""; var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) || property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface ? " abstract " : ""; //Adder if (add != null && add.Body == null) { writer.Write(IsStatic); //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface) { writer.WriteLine(" " + isVirtual + " void Add_" + name + "(" + typeString + " value)" + isOverride + "" + ";"); } // else // writer.WriteLine(" "+isVirtual + " void Add_" + name + "(" + typeString + " value)" + // isOverride + " {" + fieldName + " = value;}"); } else if (add != null) { writer.Write(IsStatic); writeRegion(add, true); } //Remover if (remove != null && remove.Body == null) { writer.Write(IsStatic); //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface) { writer.WriteLine(" " + isVirtual + " void Remove_" + name + "(" + typeString + " value)" + isOverride + "" + ";"); } } else if (remove != null) { writer.Write(IsStatic); writeRegion(remove, false); } if (isStatic) { var staticWriter = new OutputWriter("", "", false); staticWriter.Write(name); staticWriter.Write(" = new " + "__Event!(" + typeString + ")(new Action__G!(" + typeString + ")(&Add_" + name + "),new Action__G!(" + typeString + ")(&Remove_" + name + ") )"); staticWriter.Write(";"); staticWriter.WriteLine(); Context.Instance.StaticInits.Add(staticWriter.ToString()); } } }
public static void Go(OutputWriter writer, SwitchStatementSyntax switchStatement) { writer.WriteIndent(); var isStringSwitch = false; var symbol = TypeProcessor.GetTypeInfo(switchStatement.Expression); if (symbol.Type.SpecialType == SpecialType.System_String) { isStringSwitch = true; } writer.Write("switch( "); Core.Write(writer, switchStatement.Expression); writer.Write(isStringSwitch ? ".Text" : ""); writer.Write(" )\n"); writer.OpenBrace(); //First process all blocks except the section with the default block foreach ( var section in switchStatement.Sections.Where( o => o.Labels.None(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword))) { writer.WriteIndent(); foreach (var label in section.Labels) { //Core.Write(writer, label, true); WriteLabel.Go(writer, (CaseSwitchLabelSyntax)label, isStringSwitch); } // writer.Write(" :\r\n"); writer.Indent++; foreach (var statement in section.Statements) { if (!(statement is BreakStatementSyntax)) { Core.Write(writer, statement); } } writer.WriteLine("break;"); writer.Indent--; } //Now write the default section var defaultSection = switchStatement.Sections.SingleOrDefault( o => o.Labels.Any(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword)); if (defaultSection != null) { // if (defaultSection.Labels.Count > 1) // throw new Exception("Cannot fall-through into or out of the default section of switch statement " + Utility.Descriptor(defaultSection)); writer.WriteLine("default:\r\n"); writer.Indent++; foreach (var statement in defaultSection.Statements) { if (!(statement is BreakStatementSyntax)) { Core.Write(writer, statement); } } writer.WriteLine("break;"); writer.Indent--; } else { writer.WriteLine("default:\r\nbreak;\r\n"); } writer.CloseBrace(); }
private static string WriteAutoFieldName(OutputWriter writer, string name, SyntaxTokenList modifiers, bool isInterface, bool hasGetter, bool getterHasBody, bool hasSetter, bool setterHasBody, string typeString, out string isOverride, bool isIndexer=false) { //Auto Property var fieldName = "__prop_" + name; isOverride = (modifiers.Any(SyntaxKind.NewKeyword) || modifiers.Any(SyntaxKind.OverrideKeyword)) && !isInterface ? " override " : ""; var isStatic = modifiers.Any(SyntaxKind.StaticKeyword); if (!isInterface &&!isIndexer) // Auto property { if ((hasGetter && !getterHasBody) && (hasSetter && !setterHasBody) && (!modifiers.Any(SyntaxKind.AbstractKeyword))) { writer.WriteLine("private " + (isStatic?"static " :"") + typeString + " " + fieldName + ";"); } } return fieldName; }
public static void Go(OutputWriter writer, SwitchStatementSyntax switchStatement) { // writer.WriteIndent(); var isStringSwitch = false; var isEnumSwitch = false; var symbol = TypeProcessor.GetTypeInfo(switchStatement.Expression); if (symbol.Type != null) // Sometimes its null why ? { if (symbol.Type.SpecialType == SpecialType.System_String) { isStringSwitch = true; } if (symbol.Type.TypeKind == TypeKind.Enum) { isEnumSwitch = true; } } if (!(switchStatement.Expression is LiteralExpressionSyntax)) { writer.WriteLine("switch(" + Core.WriteString(switchStatement.Expression) + (isStringSwitch ? ".Hash" : "") + (isEnumSwitch ? ".__Value" : "") + ")"); } else { var typeInfo = TypeProcessor.GetTypeInfo(switchStatement.Expression); if (typeInfo.Type.SpecialType == SpecialType.System_String) { writer.WriteLine("switch("); WriteLiteralExpression.Go(writer, (LiteralExpressionSyntax)switchStatement.Expression, true, true); writer.WriteLine((isStringSwitch ? ".Hash" : "") + ")"); } else { writer.WriteLine("switch(" + Core.WriteString(switchStatement.Expression) + (isStringSwitch ? ".Hash" : "") + (isEnumSwitch ? ".__Value" : "") + ")"); } } writer.OpenBrace(); //First process all blocks except the section with the default block foreach ( var section in switchStatement.Sections.Where( o => o.Labels.None(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword))) { foreach (var label in section.Labels) { writer.WriteIndent(); WriteLabel.Go(writer, (CaseSwitchLabelSyntax)label, isStringSwitch); } writer.OpenBrace(false); foreach (var statement in section.Statements) { if (!(statement is BreakStatementSyntax)) { writer.Write(Core.WriteString(statement, false, writer.Indent + 2)); } } writer.WriteLine("break;\r\n"); writer.CloseBrace(false); } //Now write the default section var defaultSection = switchStatement.Sections.SingleOrDefault( o => o.Labels.Any(z => z.Keyword.RawKind == (decimal)SyntaxKind.DefaultKeyword)); if (defaultSection != null) { foreach (var label in defaultSection.Labels) // Could be more than one label :P { writer.WriteIndent(); if (label is CaseSwitchLabelSyntax) { WriteLabel.Go(writer, (CaseSwitchLabelSyntax)label, isStringSwitch); } else { writer.WriteLine(label.ToFullString().Trim()); } } // writer.WriteLine("default:"); writer.OpenBrace(false); foreach (var statement in defaultSection.Statements) { if (!(statement is BreakStatementSyntax)) { writer.Write(Core.WriteString(statement, false, writer.Indent + 2)); } } writer.WriteLine("break;"); writer.CloseBrace(false); } else { writer.WriteLine("default:"); writer.WriteLine("break;"); } writer.CloseBrace(); }
public static void Go(OutputWriter writer, LabeledStatementSyntax method) { writer.WriteLine(method.Identifier + ":"); Core.Write(writer, method.Statement); }
private static void WriteOneDelegate(OutputWriter outputWriter, Context.DelegateSyntaxAndSymbol first, bool fileExists) { Context.Instance.Namespace = first.Symbol.ContainingNamespace.FullName(); Context.Instance.Type = first.Symbol; TypeProcessor.ClearUsedTypes(); var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace"); // + "." + TypeState.Instance.TypeName; var myUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace)); var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")); // Required as certain functions like boxing are in this namespace Context.Instance.UsingDeclarations = first.Syntax.Parent.DescendantNodes().OfType <UsingDirectiveSyntax>().ToArray() .Union(new[] { myUsingDirective, SystemUsingDirective }).ToArray(); OutputWriter writer = null; using ( writer = outputWriter == null ? new OutputWriter(Context.Instance.Namespace, Context.Instance.TypeName) : new TempWriter()) { if (outputWriter != null) { writer.WriteLine(); writer.Indent = outputWriter.Indent + 2; writer.WriteIndent(); } writer.FileExists = fileExists; WriteBcl.Go(writer); WriteStandardIncludes.Go(writer); //Look for generic arguments { List <TypeParameterSyntax> genericArgs = new List <TypeParameterSyntax>(); if (first.Syntax.TypeParameterList != null) { genericArgs = first.Syntax.TypeParameterList.Parameters.ToList(); } var name = WriteType.TypeName(Context.Instance.Type, false); //Context.Instance.TypeName; if (genericArgs.Count > 0) { name = "template " + name; name += ("("); name += (string.Join(" , ", genericArgs.Select(o => o))); name += (")"); writer.WriteLine(name); writer.OpenBrace(); writer.WriteLine("alias __Delegate!(" + TypeProcessor.ConvertType(first.Syntax.ReturnType) + " delegate" + WriteMethod.GetParameterListAsString(first.Syntax.ParameterList.Parameters) + ") " + WriteType.TypeName(Context.Instance.Type, false) + ";"); writer.CloseBrace(); } else { //Non-generic writer.WriteLine("alias __Delegate!(" + TypeProcessor.ConvertType(first.Syntax.ReturnType) + " delegate" + WriteMethod.GetParameterListAsString(first.Syntax.ParameterList.Parameters) + ") " + WriteType.TypeName(Context.Instance.Type, false) + ";"); } } if (outputWriter != null) { outputWriter.WriteLine(writer.ToString()); } } }
public static void WriteIt(OutputWriter writer, MethodDeclarationSyntax method, bool isProxy = true, IEnumerable<ITypeSymbol> virtualGenericClasses=null) { var methodSymbol = (IMethodSymbol) TypeProcessor.GetDeclaredSymbol(method); var isYield = YieldChecker.HasYield(method);//method.DescendantNodes().OfType<YieldStatementSyntax>().Any(); writer.WriteLine(); var pinvokeAttributes = method.GetAttribute(Context.DllImport); var isInternalPInvoke = pinvokeAttributes == null && method.Modifiers.Any(SyntaxKind.ExternKeyword); //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.Text == method.Identifier.Text)) return; } var accessString = ""; var isInterface = method.Parent is InterfaceDeclarationSyntax; ITypeSymbol iface; ISymbol[] proxies; var methodName = MemberUtilities.GetMethodName(method, ref isInterface, out iface, out proxies); // var originalMethodName = methodName; var containingType = iface == null ? methodSymbol.ContainingType : iface; if (virtualGenericClasses != null) { methodName = TypeProcessor.ConvertType(containingType, false, false, false).Replace(".","_") + "_"+methodName; accessString = "public static final "; } else 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 { accessString = MemberUtilities.GetAccessModifiers(method, isInterface || methodSymbol.IsAbstract); } var returnTypeString = TypeProcessor.ConvertType(method.ReturnType, true) + " "; var methodSignatureString = ""; if (method.ReturnType.ToString() == "void") returnTypeString = ("void "); methodSignatureString += methodName; var genericParameters = ""; 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 { genericParameters += ("("); genericParameters += (string.Join(",", genericArgs.Select(o => o))); genericParameters += (")"); } } methodSignatureString += genericParameters; var @params = GetParameterListAsString(method.ParameterList.Parameters, iface: proxies == null ? iface : null, genericClass: virtualGenericClasses != null ? containingType : null); // if (virtualGenericClasses != null) // { // @params = TypeProcessor.ConvertType() + ", " + @params; // } string constraints = GetMethodConstraints(method); 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.Parameters, includeTypes: false); if (virtualGenericClasses !=null) { /* public final static void Program_IBase_GenericVirtual_Dispatch(T)(Program.IBase aobj) { Object obj = cast(Object) aobj; if((typeid(obj)==typeid(Program.B))) (cast(Program.B)obj).GenericVirtual!(T)(); if((typeid(obj)==typeid(Program.A))) (cast(Program.A)obj).GenericVirtual!(T)(); } */ writer.WriteLine("NObject ___obj = cast(NObject)__obj;"); foreach (var virtualGenericClass in virtualGenericClasses) { var className = TypeProcessor.ConvertType(virtualGenericClass); writer.WriteLine("if(typeid(___obj)==typeid({0}))", className); if (method.ReturnType.ToString() == "void") writer.WriteLine("(cast({0})___obj)." + originalMethodName + "!" + genericParameters + @params + ";", className); else writer.WriteLine("return (cast({0})___obj)." + methodSignatureString + "!" + genericParameters + ";", className); } } else { if (method.ReturnType.ToString() == "void") writer.WriteLine("__Value." + methodName + @params + ";"); else writer.WriteLine("return __Value." + methodName + @params + ";"); } } else { if (!isProxy && isYield) { var namedTypeSymbol = methodSymbol.ReturnType as INamedTypeSymbol; if (namedTypeSymbol != null) { // var iteratortype = namedTypeSymbol.TypeArguments[0]; var className = methodSymbol.GetYieldClassName() +( ( ((INamedTypeSymbol)methodSymbol.ReturnType).TypeArguments.Any() && ((INamedTypeSymbol)methodSymbol.ReturnType).TypeArguments[0].TypeKind==TypeKind.TypeParameter) ? "__G" : ""); methodSignatureString = methodName + genericParameters; if (!String.IsNullOrEmpty(genericParameters)) { className = className + "!" + genericParameters; } var @params2 = GetParameterListAsString(method.ParameterList.Parameters, iface: methodSymbol.ContainingType); var @params3 = GetParameterListAsString(method.ParameterList.Parameters, iface: null, includeTypes: false,writebraces:false); // writer.WriteLine(accessString + returnTypeString + methodSignatureString + @params2 + constraints); //writer.OpenBrace(); if (!methodSymbol.IsStatic) { if(method.ParameterList.Parameters.Count >0) writer.WriteLine("return new " + className + "(this," + @params3 +");"); else { writer.WriteLine("return new " + className + "(this);"); } } else { writer.WriteLine("return new " + className + "(" + @params3 + ");"); } } } 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); if (isInternalPInvoke) WritePInvokeMethodBody.Go(writer, methodName, methodSymbol, null); if (!isProxy && isYield) { //writer.WriteLine("});"); } } writer.CloseBrace(); if (proxies != null) { foreach (var proxy in proxies) { //Need to write proxy signature here ... methodSignatureString = methodName + genericParameters; var @params2 = GetParameterListAsString(method.ParameterList.Parameters, iface: proxy.ContainingType); var @params3 = GetParameterListAsString(method.ParameterList.Parameters, iface: null, includeTypes: false); writer.WriteLine(accessString + returnTypeString + methodSignatureString + @params2 + constraints); writer.OpenBrace(); if (method.ReturnType.ToString() == "void") writer.WriteLine("" + methodName + @params3 + ";"); else writer.WriteLine("return " + methodName + @params3 + ";"); writer.CloseBrace(); } } }
public static void Go(OutputWriter writer, EventDeclarationSyntax property) { writer.WriteLine("\r\n"); var rEf = ""; //" ref ";// ref should be used based on analysis, is the return type a single var or not //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c# var isInterface = property.Parent is InterfaceDeclarationSyntax; var add = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal) SyntaxKind.AddKeyword); var remove = property.AccessorList.Accessors.SingleOrDefault( o => o.Keyword.RawKind == (decimal) SyntaxKind.RemoveKeyword); var eventSymbol = TypeProcessor.GetDeclaredSymbol(property); var methodSymbol = (TypeProcessor.GetDeclaredSymbol(add) ?? TypeProcessor.GetDeclaredSymbol(remove)) as IMethodSymbol; ITypeSymbol interfaceImplemented; ISymbol[] proxies; ; var methodName = WriteIdentifierName.TransformIdentifier(MemberUtilities.GetMethodName(eventSymbol, ref isInterface, out interfaceImplemented, out proxies)); Action<AccessorDeclarationSyntax, bool> writeRegion = (region, get) => { writer.WriteIndent(); // if (property.Modifiers.Any(SyntaxKind.PrivateKeyword)) // writer.HeaderWriter.Write("private:\n"); // // if (property.Modifiers.Any(SyntaxKind.PublicKeyword) || property.Modifiers.Any(SyntaxKind.InternalKeyword)) // writer.HeaderWriter.Write("public "); var typeinfo = TypeProcessor.GetTypeInfo(property.Type); var isPtr = ""; var typeString = TypeProcessor.ConvertType(property.Type) + isPtr + " "; if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null) writer.Write(" abstract "); if (property.Modifiers.Any(SyntaxKind.OverrideKeyword)) writer.Write(" override "); writer.Write("void "); writer.Write( (get ? "Add_" : "Remove_") + methodName + "( " + typeString + " value"); if (isInterface) { writer.WriteLine(" , " + TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null"); } writer.Write(" )"); if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) || region.Body == null) writer.Write(";\r\n"); else { // writer.Write(";\r\n"); writer.OpenBrace(); // writer.Write(" =\r\n"); Core.WriteBlock(writer, region.Body.As<BlockSyntax>()); writer.CloseBrace(); writer.Write("\r\n"); } }; if (add == null && remove == null) throw new Exception("Event must have both a add and remove"); { var name = WriteIdentifierName.TransformIdentifier(property.Identifier.Text); var type = property.Type; var typeinfo = TypeProcessor.GetTypeInfo(type); var modifiers = property.Modifiers; var typeString = TypeProcessor.ConvertType(type) + " "; var isStatic = false; //Handle Auto Properties var accessors = property.AccessorList.Accessors; //.Where(o=>o.Body==null); var accessString = ""; if (modifiers.Any(SyntaxKind.PrivateKeyword)) accessString += (" private "); if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.InternalKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) accessString += (" public "); var IsStatic = ""; if (modifiers.Any(SyntaxKind.StaticKeyword)) { isStatic = true; IsStatic = accessString += " static "; // writer.HeaderWriter.Write("static "); } var fieldName = "__evt__" + name + (interfaceImplemented!=null?TypeProcessor.ConvertType(interfaceImplemented) .Replace("(","_").Replace("!", "_").Replace(")", "_").Replace(".", "_") :""); if (!(property.Parent is InterfaceDeclarationSyntax)) { if (!isStatic) { writer.Write("private " + "__Event!(" + typeString + ") " + fieldName + ";\r\n"); // Internal Field used for event writer.Write(accessString); writer.WriteLine("__Event!(" + typeString + ") " + name + "(" + (interfaceImplemented!=null ? ( TypeProcessor.ConvertType(interfaceImplemented) + " __ij = null") :"")+") @property"); writer.OpenBrace(); writer.WriteLine("if (" + fieldName + " is null)"); writer.OpenBrace(); writer.Write(fieldName + " = new " + "__Event!(" + typeString + ")(new Action__G!(" + typeString + ")(&Add_" + name + "),new Action__G!(" + typeString + ")(&Remove_" + name + ") );"); writer.CloseBrace(); writer.Write("return " + fieldName + ";"); writer.CloseBrace(); } else { writer.Write(IsStatic); writer.Write("__Event!(" + typeString + ") " + name + ";\r\n"); } } // var isOverride = property.Modifiers.Any(SyntaxKind.NewKeyword) || property.Modifiers.Any(SyntaxKind.OverrideKeyword) ? " override " : ""; var isVirtual = //property.Modifiers.Any(SyntaxKind.VirtualKeyword) || property.Modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface ? " abstract " : ""; //Adder if (add != null && add.Body == null) { writer.Write(IsStatic); //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface) { writer.WriteLine(" " + isVirtual + " void Add_" + name + "(" + typeString + " value)" + isOverride + "" + ";"); } // else // writer.WriteLine(" "+isVirtual + " void Add_" + name + "(" + typeString + " value)" + // isOverride + " {" + fieldName + " = value;}"); } else if (add != null) { writer.Write(IsStatic); writeRegion(add, true); } //Remover if (remove != null && remove.Body == null) { writer.Write(IsStatic); //if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)||isInterface) { writer.WriteLine(" " + isVirtual + " void Remove_" + name + "(" + typeString + " value)" + isOverride + "" + ";"); } } else if (remove != null) { writer.Write(IsStatic); writeRegion(remove, false); } if (isStatic) { var staticWriter = new OutputWriter("", "", false); staticWriter.Write(name); staticWriter.Write(" = new " + "__Event!(" + typeString + ")(new Action__G!(" + typeString + ")(&Add_" + name + "),new Action__G!(" + typeString + ")(&Remove_" + name + ") )"); staticWriter.Write(";"); staticWriter.WriteLine(); Context.Instance.StaticInits.Add(staticWriter.ToString()); } } }
public static void Go(OutputWriter writer, 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(); }
private static void WriteReflectionInfo(OutputWriter writer, ITypeSymbol specialization, string genericName) { if (specialization.TypeKind == TypeKind.Interface) { //for now no interfaces in reflection return; } // List<string> imports; // Context.TypeImports.TryGetValue(Context.Instance.Type, out imports); // // if (imports == null) // return; if(specialization.Name.StartsWith("__YieldEnumerator_")) { //Ignore YieldEnumerators / Generated Classes return; } writer.WriteLine(); // foreach (var import in imports) // { // writer.WriteLine("import " + import + ";"); // } /* if (specialization.Name.StartsWith("YieldEnumerator")) { writer.WriteLine("import System.Collections.Namespace;"); writer.WriteLine("import System.Collections.Generic.Namespace;"); } */ writer.WriteLine("__TypeOf!(" + TypeProcessor.ConvertType(specialization,false, false, false) + "" + ")(\"" + genericName + "\")"); writer.WriteLine(".__Setup(" + (specialization.BaseType!=null?("__TypeOf!(" + TypeProcessor.ConvertType(specialization.BaseType, false, false, false)+")") :"null") + "," + (specialization.Interfaces.Length>0? ("[" + specialization.Interfaces.Select( delegate(INamedTypeSymbol k) { return "__TypeOf!(" + TypeProcessor.ConvertType(k, false, false, false) + ")"; }).Aggregate((a,b)=>a + "," + b) +"]") : "null") + ")"); bool writtenGetType = false; foreach (var member in specialization.GetMembers().DistinctBy(l=>l)) { //TODO: Add explicit interface method support if (member.Name.Contains(".")) continue; if (member is IFieldSymbol) { var field = member as IFieldSymbol; if (field.AssociatedSymbol == null) { // Ignore compiler generated backing fields ... for properties etc ... var modifiers = member.DeclaredAccessibility; FieldAttributes attr = FieldAttributes.Public; if (modifiers == Accessibility.Public) attr = FieldAttributes.Public; if (modifiers == Accessibility.Private) attr = FieldAttributes.Private; if (field.IsConst) attr |= (FieldAttributes.Literal | FieldAttributes.HasDefault); if (field.IsStatic) attr |= (FieldAttributes.Static ); var attString = attr.ToString().Split(',') .Select(k=> "FieldAttributes." + k).Aggregate((a,b)=> a +"|"+ b ); writer.WriteLine( !field.IsConst ? ".__Field(\"{0}\", new FieldInfo__G!({1},{2})(function {2} ({1}* _param_{4}){{ return _param_{4}.{3};}},function void ({1}* _param_{4}, {2} _param_{0}){{ _param_{4}.{3} = _param_{0};}}), {5})" : ".__Field(\"{0}\", new FieldInfo__G!({1},{2})(function {2} ({1}* _param_{4}){{ return _param_{4}.{3};}},null),{5})", field.Name, TypeProcessor.ConvertType(field.ContainingType), TypeProcessor.ConvertType(field.Type), WriteIdentifierName.TransformIdentifier(field.Name), field.ContainingType.Name, attString); } } else if (member is IPropertySymbol) { var property = member as IPropertySymbol; bool isiface = false; ITypeSymbol iface; ISymbol[] proxies; var name = MemberUtilities.GetMethodName(property, ref isiface, out iface, out proxies); //TODO... set/specify interfaces if (property.IsAbstract == false) { // Ignore compiler generated backing fields ... for properties etc ... // //.__Property("Counter",new PropertyInfo__G!(Simple,int)(function int (Simple a){ return a.Counter();},function void (Simple a,int _age){ a.Counter(_age);})) // Need to explicitly set the interfaces etc ... if (property.Name != "this[]") { writer.WriteLine( ".__Property(\"{0}\", new PropertyInfo__G!({1},{2})(" + (property.GetMethod != null ? "function {2} ({1}* _param_{4}){{ return _param_{4}.{3}();}}" : "null") + "," + (property.SetMethod != null ? "function void ({1}* _param_{4}, {2} _param_{0}){{ _param_{4}.{3}(_param_{0});}}" : "null") + "))", property.Name, TypeProcessor.ConvertType(property.ContainingType), TypeProcessor.ConvertType(property.Type), WriteIdentifierName.TransformIdentifier(property.Name), property.ContainingType.Name); } else { writer.WriteLine( ".__Property(\"{0}\", new PropertyInfo__G!({1},{2})(" + (property.GetMethod != null ? "function {2} ({1}* _param_{4}){{ return _param_{4}.opIndex();}}" : "null") + "," + (property.SetMethod != null ? "function void ({1}* _param_{4}, {2} _param_{0}){{ _param_{4}.opIndexAssign(_param_{0});}}" : "null") + "))", property.Name, TypeProcessor.ConvertType(property.ContainingType), TypeProcessor.ConvertType(property.Type), WriteIdentifierName.TransformIdentifier(property.Name), property.ContainingType.Name); } } } //Constructors else if (member is IMethodSymbol) { if(specialization.TypeKind==TypeKind.Enum || specialization.TypeKind == TypeKind.Delegate) continue; var method = member as IMethodSymbol; if (method.IsGenericMethod && MemberUtilities.CompareArguments(method.TypeArguments, method.TypeParameters)) { //Add support for unbound generic methods continue; } if (method.Name == "GetType" && method.Parameters == null) writtenGetType = true; bool isiface = false; ITypeSymbol iface; ISymbol[] proxies; var name = MemberUtilities.GetMethodName(method,ref isiface,out iface, out proxies); if (method.AssociatedSymbol == null && method.IsAbstract==false) { if (method.MethodKind == MethodKind.Constructor || method.MethodKind==MethodKind.StaticConstructor) //TODO, need a fix for static constructors { //.__Method("TellEm", new MethodInfo__G!(Simple,void function(Simple,int))(&Simple.TellEm)) // Ignore compiler generated backing fields ... for properties etc ... writer.WriteLine( ".__Constructor(\"{0}\", new ConstructorInfo__G!({1},{2} function({4}))( ({4})=> "+ (specialization.TypeKind==TypeKind.Struct?"" :"new ") +"{1}({5})))" , method.Name, TypeProcessor.ConvertType(method.ContainingType), TypeProcessor.ConvertType(method.ContainingType), "this", //WriteIdentifierName.TransformIdentifier(method.Name), WriteMethod.GetParameterListAsString(method.Parameters, true, null, false), WriteMethod.GetParameterListAsString(method.Parameters, false, null, false) ); } else { if (method.MethodKind == MethodKind.Conversion) { var mname = method.Name; if (method.Name == "op_Implicit") { mname += "_" + TypeProcessor.ConvertType(method.ReturnType, false, true, false) .Replace(".", "_"); } //.__Method("TellEm", new MethodInfo__G!(Simple,void function(Simple,int))(&Simple.TellEm)) // Ignore compiler generated backing fields ... for properties etc ... //&__traits(getOverloads, foo, "func")[1] int overloadindex = GetIndexOfMethod(method); writer.WriteLine( ".__Method(\"{0}\", new MethodInfo__G!({1},{2} function({4}))(&__traits(getOverloads,{1},\"{3}\")[{5}]))" , method.Name, TypeProcessor.ConvertType(method.ContainingType), TypeProcessor.ConvertType(method.ReturnType), WriteIdentifierName.TransformIdentifier(mname), WriteMethod.GetParameterListAsString(method.Parameters, true, iface, false), overloadindex); } else { //.__Method("TellEm", new MethodInfo__G!(Simple,void function(Simple,int))(&Simple.TellEm)) // Ignore compiler generated backing fields ... for properties etc ... int overloadindex = GetIndexOfMethod(method); writer.WriteLine( ".__Method(\"{0}\", new MethodInfo__G!({1},{2} function({4}))(&__traits(getOverloads,{1},\"{3}\")[{5}]))" , method.Name, TypeProcessor.ConvertType(method.ContainingType), TypeProcessor.ConvertType(method.ReturnType), WriteIdentifierName.TransformIdentifier(name), WriteMethod.GetParameterListAsString(method.Parameters, true, iface, false),overloadindex); } } } } } if(!writtenGetType) writer.WriteLine(".__Method(\"GetType\", new MethodInfo__G!({0},System.Namespace.Type function())(&{0}.GetType))", TypeProcessor.ConvertType(specialization, true, true, false)); writer.Write(";"); }
private static void WriteGetter(OutputWriter writer, bool isProxy, bool hasGetter, string acccessmodifiers, string typeString, string name, ITypeSymbol iface, bool getterHasBody, SyntaxTokenList modifiers, bool isInterface, string fieldName, string getterbody, string parameters, bool isindexer) { if (isindexer) name = "opIndex"; var args =_get; if (hasGetter && isProxy) { if (!isindexer) { writer.WriteLine (string.Format ("{0}{1} {4}{2}({3}) {{ return __Value.{2};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType (iface) + " __ig=null") : ""), args)); } else { writer.WriteLine (string.Format ("{0}{1} {2}({3}) {{ return __Value.{2};}}", acccessmodifiers, typeString, name, parameters)); } } else if (hasGetter && !getterHasBody) //Getter { if (modifiers.Any(SyntaxKind.AbstractKeyword) || isInterface) { if (!isindexer) { writer.WriteLine (string.Format ("{0}{1} {4}{2}({3});", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType (iface) + " __ig=null") : ""), args)); } else { writer.WriteLine (string.Format ("{0}{1} {2}({3});", acccessmodifiers, typeString, name, parameters)); } } else { if (!isindexer) { writer.WriteLine (string.Format ("{0}{1} {5}{2}({3}) {{ return {4};}}", acccessmodifiers, typeString, name, (iface != null ? (TypeProcessor.ConvertType (iface) + " __ig=null") : ""), fieldName, args)); } else { writer.WriteLine (string.Format ("{0}{1} {2}({3}) {{ return {4};}}", acccessmodifiers, typeString, name, parameters, fieldName)); } } } else if (hasGetter) { writer.WriteIndent(); writer.Write(acccessmodifiers); WriteRegion(true, getterbody, iface, writer, typeString, name, modifiers,parameters,isindexer,hasGetter); } }
private static void WriteNamespaces() { //We dont need namespace aliases at this point Context.Instance.NamespaceAliases = new Dictionary<INamespaceSymbol, string>(); //For now ignore system namespace to prevent conflicts, later we should just check if the module is defined in our sources var namespaces = Context.Namespaces.ToArray(); foreach (var @namespace in namespaces) { // if ([email protected]("System") && !isCorlib) //For generating corlib, lets get all types in namespace ... var anyExtern = [email protected](); //||@namespace.Key.Name == "System";//.All(o => o.MetadataName != ("__YieldIterator`1")); if (!anyExtern) // This should take care of corlib and external assemblies at once { // TODO: this should write nses for only types defined in binary, this should be a switch, we could be compiling corlib using (var writer = new OutputWriter(@namespace.Key.GetModuleName(), "Namespace") { IsNamespace = true }) { writer.WriteLine("module " + @namespace.Key.GetModuleName(false) + ";"); List<string> addedTypes = new List<string>(); StringBuilder namespaceImports = new StringBuilder(); var alltypes = @namespace.Key.GetTypeMembers().Union(@namespace.Value).DistinctBy(k=>k); // For purposes of reflection ... later this should become opt-out ... just use "version(SharpNativeReflection) foreach (var type in alltypes) { if (type.ContainingType != null) continue; var properClassName = type.GetModuleName(false); if (addedTypes.Contains(properClassName)) continue; var className = type.GetNameD(); if (properClassName.Trim() != String.Empty && className.Trim() != String.Empty) writer.WriteLine("alias " + properClassName + " " + className + ";"); addedTypes.Add(properClassName); } //Reflection Info writer.WriteLine("\n\nimport System.Namespace;"); writer.WriteLine("\n\nimport System.Reflection.Namespace;"); //To be on the safe side, import all namespaces except us... this allows us to create correct reflectioninfo //gtest-053.cs // foreach (var @name in namespaces.DistinctBy(o=>o.Key).Except(@namespace)) //Cant work leads to cycles // { // writer.WriteLine("import {0};", @name.Key.GetModuleName(false)); // } var genericMethods = new List<IMethodSymbol>(); writer.WriteLine("public class __ReflectionInfo"); writer.OpenBrace(); writer.WriteLine("static this()"); writer.OpenBrace(); foreach (var type in alltypes) { if(type.TypeKind==TypeKind.Error) continue; var allgenericVirtualMethods = type.GetMembers().OfType<IMethodSymbol>().Where(k=>k.IsGenericMethod && k.IsVirtual); genericMethods.AddRange(allgenericVirtualMethods); if (((INamedTypeSymbol) type).IsGenericType) { //Get its specializations foreach (var specialization in GetGenericSpecializations(type).DistinctBy(k=> k)) { //TODO fix nested types //if (specialization.ContainingType == null) { /* var allNamespaces = GetAllNamespaces(specialization); foreach (var @name in allNamespaces.DistinctBy(o => o).Where(p=>p!=null).Except(@namespace.Key)) { writer.WriteLine("import {0};", @name.GetModuleName(false)); }*/ var genericName = GetGenericMetadataName(specialization); WriteReflectionInfo(writer, specialization, genericName); } } } else { /*var allNamespaces = GetAllNamespaces((INamedTypeSymbol) type); foreach (var @name in allNamespaces.DistinctBy(o => o).Where(p => p != null).Except(@namespace.Key)) { writer.WriteLine("import {0};", @name.GetModuleName(false)); }*/ var genericName = GetGenericMetadataName((INamedTypeSymbol) type); WriteReflectionInfo(writer, type, genericName); } } writer.CloseBrace(); writer.CloseBrace(); foreach (var genericMethod in genericMethods) { var allClasses = alltypes.Where(type => genericMethod.ContainingType.IsAssignableFrom(type)).ToList(); // Or use a HashSet, for better Contains perf. IEnumerable<ITypeSymbol> firstImplementations = allClasses .Except(allClasses.Where(t => allClasses.Contains(t.BaseType))); // writer.WriteLine("public final static " + TypeProcessor.ConvertType(genericMethod.ReturnType) + WriteIdentifierName.TransformIdentifier(genericMethod.Name) + ); if((firstImplementations.Contains( genericMethod.ContainingType ))) WriteMethod.WriteIt(writer,(MethodDeclarationSyntax) genericMethod.DeclaringSyntaxReferences[0].GetSyntax(),true, allClasses); } } } } }