public static void Go(OutputWriter writer, TypeOfExpressionSyntax expression) { writer.Write("__TypeOf!("); TypeProcessor.AddUsedType(TypeProcessor.GetTypeInfo(expression.Type).Type); writer.Write(TypeProcessor.ConvertType(expression.Type)); writer.Write(")"); }
public static void Go(OutputWriter writer, SizeOfExpressionSyntax expression) { var type = TypeProcessor.GetTypeInfo(expression.Type); //Use dTypes writer.Write("(" + TypeProcessor.ConvertType(type.Type) + ").sizeof"); // writer.Write(SizeOf(type.Type).ToString()); }
public static void Go(OutputWriter writer, ConstructorInitializerSyntax method) { writer.WriteIndent(); // var symbl = TypeProcessor.GetSymbolInfo(method); // var mysymbl = TypeProcessor.GetSymbolInfo(method.Parent); // var className = symbl.Symbol.ContainingType; if (method.ThisOrBaseKeyword.RawKind == (int) SyntaxKind.ThisKeyword) writer.Write("this"); else writer.Write("super"); // writer.Write(TypeProcessor.ConvertType(className)); writer.Write("("); bool first = true; foreach (var expression in method.ArgumentList.Arguments) { if (first) first = false; else writer.Write(", "); Core.Write(writer, expression.Expression); } writer.Write(")"); }
public static void Go(OutputWriter writer, VariableDeclarationSyntax declaration) { foreach (var variable in declaration.Variables) { ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable); var isRef = false; //UsedAsRef(variable, symbol); writer.WriteIndent(); // writer.Write("var "); // if (isRef) //Not needed c++ can passby ref // { // // var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type); // // var localSymbol = symbol as ILocalSymbol; // var ptr = localSymbol != null && !localSymbol.Type.IsValueType?"*" : ""; // writer.Write("gc::gc_ptr < " + typeStr+ ptr + " >"); // writer.Write("" + typeStr + ptr + ""); // // writer.Write(" "); // writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text)); // // Program.RefOutSymbols.TryAdd(symbol, null); // // writer.Write(" = std::make_shared < "); // writer.Write(typeStr + ptr); // writer.Write(" >("); // // WriteInitializer(writer, declaration, variable); // // writer.Write(")"); // } // else { var lsymbol = symbol as ILocalSymbol; if (lsymbol != null && lsymbol.Type.IsValueType == false) { writer.Write(" "); // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack } writer.Write(TypeProcessor.ConvertType(declaration.Type)); if (lsymbol != null && lsymbol.Type.IsValueType == false) writer.Write(" "); writer.Write(" "); writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text)); writer.Write(" = "); WriteInitializer(writer, declaration, variable); } writer.Write(";\r\n"); } }
public static void WriteIt(OutputWriter writer, SyntaxToken operatorToken, CSharpSyntaxNode rightExpression, CSharpSyntaxNode leftExpression) { if (operatorToken.IsKind(SyntaxKind.AsKeyword)) { writer.Write("AsCast!("); writer.Write(TypeProcessor.ConvertType(rightExpression)); writer.Write(")("); Core.Write(writer, leftExpression); writer.Write(")"); } else if (operatorToken.IsKind(SyntaxKind.IsKeyword)) // isCast { var leftSymbolType = TypeProcessor.GetTypeInfo(leftExpression); var rightSymbolType = TypeProcessor.GetTypeInfo(rightExpression); if (leftSymbolType.Type.IsValueType) { writer.Write("IsCast!(Boxed!("); writer.Write(TypeProcessor.ConvertType(rightExpression)); writer.Write("))"); writer.Write("("); Core.Write(writer, leftExpression); writer.Write(")"); } else if (rightSymbolType.Type.IsValueType) { writer.Write("IsCast!(Boxed!("); writer.Write(TypeProcessor.ConvertType(rightExpression)); writer.Write("))"); writer.Write("("); Core.Write(writer, leftExpression); writer.Write(")"); } else { writer.Write("(IsCast!("); writer.Write(TypeProcessor.ConvertType(rightExpression)); writer.Write(")("); Core.Write(writer, leftExpression); writer.Write("))"); } } else if (operatorToken.IsKind(SyntaxKind.QuestionQuestionToken)) { writer.Write("(("); Core.Write(writer, leftExpression); writer.Write(")!is null?("); Core.Write(writer, leftExpression); writer.Write("):("); Core.Write(writer, rightExpression); writer.Write("))"); } else { ProcessExpression(writer, operatorToken, rightExpression, leftExpression); } }
public static void Go(OutputWriter writer, AnonymousMethodExpressionSyntax expression) { if (expression.ParameterList != null) Go(writer, expression.ParameterList.Parameters, expression.Block, TypeProcessor.GetTypeInfo(expression)); else Go(writer, new SeparatedSyntaxList<ParameterSyntax>(), expression.Block, TypeProcessor.GetTypeInfo(expression)); }
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, ConstructorDeclarationSyntax constructor) { //Only write out static constructors here. If we encounter an instance constructor, we can ignore it since it's already written out by WriteType if (constructor.Modifiers.Any(SyntaxKind.StaticKeyword)) WriteStaticConstructor(writer, constructor, null); else WriteInstanceConstructor(writer, constructor,null); }
public static void Go(OutputWriter writer, ElementAccessExpressionSyntax expression) { var type = TypeProcessor.GetTypeInfo(expression.Expression).Type; var typeStr = TypeProcessor.GenericTypeName(type); var additionalParam = ""; var symbol = TypeProcessor.GetSymbolInfo(expression); //This could be null if (symbol.Symbol != null) { var methodSymbol = symbol.Symbol as IPropertySymbol; //Lets find out if this is an interface implementation if (methodSymbol != null) { IEnumerable<ISymbol> interfaceMethods = methodSymbol.ContainingType.AllInterfaces.SelectMany( u => u.GetMembers(methodSymbol.Name)); interfaceMethods = interfaceMethods.Where( o => Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(o), methodSymbol)); if (interfaceMethods.Any()) { //Lets get the best match var interfaceMethod = interfaceMethods.FirstOrDefault(); additionalParam = "cast("+ TypeProcessor.ConvertType(interfaceMethod.ContainingType)+")null"; } } } //type.GetMembers("this[]") //Todo if we are using unsafe / fast mode, just use array->Data()[i] should bypass bounds check and indirection also should be as fast as pure c++ arrays //though fixed syntax could fix this too ?? // writer.Write("(*"); Core.Write(writer, expression.Expression); if (type.SpecialType == SpecialType.System_Array) // writer.Write(")"); writer.Write(".Items["); //TODO test this thoroughly else writer.Write("["); //TODO test this thoroughly var first = true; foreach (var argument in expression.ArgumentList.Arguments) { if (first) first = false; else writer.Write(", "); Core.Write(writer, argument.Expression); } if(additionalParam!="") writer.Write("," + additionalParam); writer.Write("]"); }
public static void Go(OutputWriter writer, InitializerExpressionSyntax initializer) { writer.WriteIndent(); var isCollectionInit = false; if (CSharpExtensions.CSharpKind(initializer) == SyntaxKind.CollectionInitializerExpression || CSharpExtensions.CSharpKind(initializer) == SyntaxKind.ArrayInitializerExpression) { var tx = TypeProcessor.GetTypeInfo(initializer); var t = tx.Type; if (t == null) t = tx.ConvertedType; if (t != null) // Initializer within initializer { var elementType = t.As<IArrayTypeSymbol>().ElementType; var ptr = !elementType.IsValueType; // ? "" : ""; var type = TypeProcessor.ConvertType(elementType); var typeString = "Array_T!(" + type + ")"; if (elementType.TypeKind == TypeKind.TypeParameter) writer.Write(" __TypeNew!(" + typeString + ")("); else writer.Write("new " + typeString + "("); } var variableDeclarationSyntax = initializer.Parent.Parent.Parent as VariableDeclarationSyntax; if (variableDeclarationSyntax != null) { var atype = variableDeclarationSyntax.Type; initializer.WriteArrayInitializer(writer, atype); } else initializer.WriteArrayInitializer(writer,t); if (t != null) writer.Write(")"); } else { // writer.Write("goto "); // foreach (var expressionSyntax in method.Expressions) // { // Core.Write(writer, expressionSyntax); // } bool first = true; foreach (var expression in initializer.Expressions) { if (first) first = false; else writer.Write(", "); Core.Write(writer, expression); } } // writer.Write(";"); }
public static void Go(OutputWriter writer, BinaryExpressionSyntax expression) { var leftExpression = expression.Left; var rightExpression = expression.Right; var operatorToken = expression.OperatorToken; WriteIt(writer, operatorToken, rightExpression, leftExpression); }
public static void Go(OutputWriter writer, ConditionalExpressionSyntax expression) { writer.Write("("); Core.Write(writer, expression.Condition); writer.Write(") ? ("); Core.Write(writer, expression.WhenTrue); writer.Write(") : ("); Core.Write(writer, expression.WhenFalse); writer.Write(")"); }
public static void Go(OutputWriter writer, EventFieldDeclarationSyntax field) { foreach (var declaration in field.Declaration.Variables) { Go(writer, field, field.Modifiers, WriteIdentifierName.TransformIdentifier(declaration.Identifier.Text), field.Declaration.Type, declaration.Initializer,field.IsThreadStatic()); } }
public static void Go(OutputWriter writer, StackAllocArrayCreationExpressionSyntax @as) { //import core.stdc.stdlib; //@as.Type; //auto ptr = cast(wchar*)alloca(wchar.sizeof * len); var arrayType = TypeProcessor.GetTypeInfo(@as.Type); var elementType = TypeProcessor.GetTypeInfo(((ArrayTypeSyntax) @as.Type).ElementType); var elementTypeName = TypeProcessor.ConvertType(elementType.Type); var size = Core.WriteString(((ArrayTypeSyntax)@as.Type).RankSpecifiers[0].Sizes[0]); writer.Write("cast("+ elementTypeName + "*) core.stdc.stdlib.alloca("+ elementTypeName + ".sizeof * "+ size + ")"); }
public static void Go(OutputWriter writer, ImplicitArrayCreationExpressionSyntax array) { var ti = TypeProcessor.GetTypeInfo(array); var t = ti.Type; if (ti.ConvertedType!=null && !(ti.ConvertedType == t)) // Alot of times we are using covariance here { t = ti.ConvertedType; } var ptr = !t.As<IArrayTypeSymbol>().ElementType.IsValueType; // ? "" : ""; var elementType = t.As<IArrayTypeSymbol>().ElementType; var type = TypeProcessor.ConvertType(elementType); var typeString = "Array_T!(" + type + ")"; var tempWriter = new TempWriter(); tempWriter.Indent = writer.Indent; if (elementType.TypeKind == TypeKind.TypeParameter) tempWriter.Write(" __TypeNew!(" + typeString + ")(["); else { tempWriter.Write("new " + typeString + "("); } //__ARRAY var variableDeclarationSyntax = array.Parent.Parent.Parent as VariableDeclarationSyntax; // var argumentSyntax = array.Parent as ArgumentSyntax; if (variableDeclarationSyntax != null) { var atype = variableDeclarationSyntax.Type; array.Initializer.WriteArrayInitializer(tempWriter, atype); } else array.Initializer.WriteArrayInitializer(tempWriter,t); tempWriter.Write(")"); var tempString = tempWriter.ToString(); var oldString = tempString; tempString = tempString.Replace("new " + typeString + "(__CC!(" + type + "[])(", "__ARRAY!(" + type + ")("); if (tempString != oldString) tempString = tempString.RemoveFromEndOfString(")"); writer.Write(tempString); }
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();"); } }
public static void Go(OutputWriter outputWriter = null) { var partials = Context.Instance.Partials; var first = partials.First(); bool fileExists = false; foreach (var @partial in partials.GroupBy(o => o.Symbol)) { Context.Instance.Namespace = @partial.First().Symbol.ContainingNamespace.FullName(); Context.Instance.Type = @partial.First().Symbol; WriteOutOneType(outputWriter, @partial.ToArray(), fileExists); fileExists = true; } }
public static void Go(OutputWriter writer, WhileStatementSyntax whileStatement) { var info = new LoopInfo(whileStatement); writer.WriteIndent(); writer.Write("while ("); Core.Write(writer, whileStatement.Condition); writer.Write(")\r\n"); writer.OpenBrace(); Core.WriteStatementAsBlock(writer, whileStatement.Statement, false); writer.CloseBrace(); }
/* template Action(T) { alias void delegate(T obj) Action; } */ public static void Go(OutputWriter outputWriter = null) { var partials = Context.Instance.DelegatePartials; var first = partials.First(); bool fileExists = false; foreach (var @partial in partials) { Context.Instance.Namespace = @partial.Symbol.ContainingNamespace.FullName(); Context.Instance.Type = @partial.Symbol; WriteOneDelegate(outputWriter, @partial, fileExists); fileExists = true; } }
public static void Go(OutputWriter writer, CheckedExpressionSyntax checkedExpressionSyntax) { Core.Write(writer, checkedExpressionSyntax.Expression); // var block = checkedExpressionSyntax. // if (writeBraces) // writer.WriteOpenBrace(); // foreach (var statement in block.Statements) // Write(writer, statement); // TriviaProcessor.ProcessTrivias(writer, block.DescendantTrivia()); // if (writeBraces) // writer.WriteCloseBrace(); }
public static void Write(OutputWriter writer, SyntaxNode node, bool isConst = false) { Context.LastNode = node; //Helps with debugging //Write Leading Trivia TriviaProcessor.WriteLeadingTrivia(writer, node); TriviaProcessor.ProcessNode(writer, node); if (Program.DoNotWrite.ContainsKey(node)) return; Factory(writer, node, isConst); TriviaProcessor.WriteTrailingTrivia(writer, node); }
public static void Go(OutputWriter writer, GotoStatementSyntax method) { writer.WriteIndent(); writer.Write("goto "); writer.Write((method.CaseOrDefaultKeyword != default(SyntaxToken)) ? method.CaseOrDefaultKeyword.Text : ""); writer.Write(" "); if (method.Expression != null) if (method.Expression.ToString ().Trim() == "null") writer.Write("-1"); else Core.Write(writer, method.Expression); writer.Write(";\r\n"); }
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, GenericNameSyntax name) { writer.Write(WriteIdentifierName.TransformIdentifier(name.Identifier.Text)); writer.Write("!("); bool first = true; foreach (var type in name.TypeArgumentList.Arguments) { if (first) first = false; else writer.Write(", "); writer.Write(TypeProcessor.ConvertType(type)); } writer.Write(")"); }
public void Write(OutputWriter writer) { if (StringOpt != null) writer.Write(StringOpt); else { if (ArgumentOpt.NameColon != null) { Core.Write(writer, ArgumentOpt.NameColon.Name); writer.Write(" = "); } var symbol = TypeProcessor.GetSymbolInfo(ArgumentOpt.Expression); var type = TypeProcessor.GetTypeInfo(ArgumentOpt.Expression); if (symbol.Symbol != null && type.ConvertedType != null && symbol.Symbol.Kind == SymbolKind.Method && type.ConvertedType.TypeKind == TypeKind.Delegate) { var typeString = TypeProcessor.ConvertType(type.ConvertedType); var createNew = !(ArgumentOpt.Parent.Parent is ObjectCreationExpressionSyntax); //Ugly hack if (createNew) { if (type.ConvertedType.TypeKind == TypeKind.TypeParameter) writer.Write(" __TypeNew!(" + typeString + ")("); else writer.Write("new " + typeString + "("); } var isStatic = symbol.Symbol.IsStatic; // if (isStatic) //Not Needed, delegate class now supports functions directly // writer.Write("__ToDelegate("); MemberUtilities.WriteMethodPointer(writer, ArgumentOpt.Expression); // if (isStatic) // writer.Write(")"); if (createNew) writer.Write(")"); return; } Core.Write(writer, ArgumentOpt.Expression); } }
public static void Go(OutputWriter writer, 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, 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 ProcessTrivias(OutputWriter writer, IEnumerable<SyntaxTrivia> trivias) { bool literalCode = false; //if we encounter a #if SharpNative, we set this to true, which indicates that the next DisabledTextTrivia should be written as pure code. foreach (var trivia in trivias) { if (_triviaProcessed.Add(trivia)) //ensure we don't look at the same trivia multiple times { if (trivia.RawKind == (decimal)SyntaxKind.IfDirectiveTrivia) literalCode |= GetConditions(trivia, "#if ").Contains("SharpNative"); else if (trivia.RawKind == (decimal)SyntaxKind.DisabledTextTrivia && literalCode) { writer.Write(trivia.ToString()); literalCode = false; } } } }
public static void Go(OutputWriter writer, AnonymousObjectCreationExpressionSyntax expression) { writer.Write("new "); writer.Write(TypeName(expression)); writer.Write("("); bool first = true; foreach (var field in expression.Initializers.OrderBy(o => o.Name())) { if (first) first = false; else writer.Write(", "); Core.Write(writer, field.Expression); } writer.Write(")"); }
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 WriteBlock(OutputWriter writer, BlockSyntax block, bool writeBraces = true) { if (writeBraces) { writer.OpenBrace(); } //writer.Indent++; foreach (var statement in block.Statements) { // writer.WriteIndent(); Write(writer, statement); } TriviaProcessor.ProcessTrivias(writer, block.DescendantTrivia()); // writer.Indent--; if (writeBraces) { writer.CloseBrace(); } }
public static void Go(OutputWriter writer, GenericNameSyntax name) { writer.Write(WriteIdentifierName.TransformIdentifier(name.Identifier.Text)); writer.Write("!("); bool first = true; foreach (var type in name.TypeArgumentList.Arguments) { if (first) { first = false; } else { writer.Write(", "); } writer.Write(TypeProcessor.ConvertType(type)); } writer.Write(")"); }
public static void WriteStatementAsBlock(OutputWriter writer, StatementSyntax statement, bool writeBraces = true) { if (statement is BlockSyntax) { WriteBlock(writer, statement.As <BlockSyntax>(), writeBraces); } else { if (writeBraces) { writer.OpenBrace(); } Write(writer, statement); TriviaProcessor.ProcessTrivias(writer, statement.DescendantTrivia()); if (writeBraces) { writer.CloseBrace(); } } }
public static void Go(OutputWriter writer, LiteralExpressionSyntax expression, bool isConst) { var str = expression.ToString(); if (str.StartsWith("@")) { str = "\"" + str.RemoveFromStartOfString("@\"") .RemoveFromEndOfString("\"") .Replace("\\", "\\\\") .Replace("\"\"", "\\\"") .Replace("\r\n", "\\n") + "\""; } var typeInfo = TypeProcessor.GetTypeInfo(expression); var type = typeInfo.Type; if (type == null) { type = typeInfo.ConvertedType; } if (type != null && type.SpecialType == SpecialType.System_String) { writer.Write("_S(" + str + ")"); } else { writer.Write(str); } //TODO: will handle these separately // if (typeInfo.Type != null && typeInfo.ConvertedType != null) // { // if (isConst == false && typeInfo.ConvertedType.SpecialType ==SpecialType.System_Byte && typeInfo.Type.SpecialType == SpecialType.System_Int32) // writer.Write(".toByte"); // } }
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, ElementAccessExpressionSyntax expression) { var type = TypeProcessor.GetTypeInfo(expression.Expression).Type; var typeStr = TypeProcessor.GenericTypeName(type); //Todo if we are using unsafe / fast mode, just use array->Data()[i] should bypass bounds check and indirection also should be as fast as pure c++ arrays //though fixed syntax could fix this too ?? // writer.Write("(*"); Core.Write(writer, expression.Expression); if (type.SpecialType == SpecialType.System_Array) { // writer.Write(")"); writer.Write(".Items["); //TODO test this thoroughly } else { writer.Write("["); //TODO test this thoroughly } var first = true; foreach (var argument in expression.ArgumentList.Arguments) { if (first) { first = false; } else { writer.Write(", "); } Core.Write(writer, argument.Expression); } writer.Write("]"); }
public static void Go(OutputWriter writer, LocalDeclarationStatementSyntax declaration) { foreach (var variable in declaration.Declaration.Variables) { writer.WriteIndent(); { try { var str = TypeProcessor.ConvertType(declaration.Declaration.Type); //This fails sometimes // if (str == "NObject") // Dlangs casting is slow // Looks harmless but is actually a performance optimization ... makes CastTest improve by a whole lot // writer.Write("auto ");//Kills BoxingTest unfortunately as boxed types are also used to make unbound generics work :( //else writer.Write(str); } catch (Exception ex) { writer.Write("auto"); } writer.Write(" "); writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text)); writer.Write(" = "); WriteInitializer(writer, declaration, variable); } writer.Write(";\r\n"); } }
public static void Go(OutputWriter writer, AnonymousObjectCreationExpressionSyntax expression) { writer.Write("new "); writer.Write(TypeName(expression)); writer.Write("("); bool first = true; foreach (var field in expression.Initializers.OrderBy(o => o.Name())) { if (first) { first = false; } else { writer.Write(", "); } Core.Write(writer, field.Expression); } writer.Write(")"); }
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, 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(); }
public static void Go(OutputWriter writer, DefaultExpressionSyntax node) { //Need to fix this writer.Write("null"); }
public static void WritePostfix(OutputWriter writer, PostfixUnaryExpressionSyntax expression) { var isProperty = false; var symbol = TypeProcessor.GetSymbolInfo(expression.Operand); if (symbol.Symbol is IPropertySymbol) { isProperty = true; } if (isProperty) { var symbolName = Core.WriteString(expression.Operand); switch (expression.OperatorToken.RawKind) { case (int)SyntaxKind.MinusMinusToken: if ((symbol.Symbol as IPropertySymbol).IsIndexer) { writer.Write(String.Format("/*{0}--*/((){{auto v={0};auto y=v;{0}=(--y);return v;}})()", symbolName)); } else { writer.Write(String.Format("/*{0}--*/((){{auto v={0};auto y=v;{0}(--y);return v;}})()", symbolName)); } break; case (int)SyntaxKind.PlusPlusToken: if ((symbol.Symbol as IPropertySymbol).IsIndexer) { writer.Write(String.Format("/*{0}++*/((){{auto v={0},y={0};{0}=(++y);return v;}})()", symbolName)); } else { writer.Write(String.Format("/*{0}++*/((){{auto v={0},y={0};{0}(++y);return v;}})()", symbolName)); } break; default: Core.Write(writer, expression.Operand); writer.Write(expression.OperatorToken.Text); break; } } else { // if (expression.Operand is MemberAccessExpressionSyntax) // { // var memberAccess = expression.Operand as MemberAccessExpressionSyntax; // var typeInfo = TypeProcessor.GetSymbolInfo(memberAccess.Name); // if (typeInfo.Symbol.Kind == SymbolKind.Property) // { // switch (expression.OperatorToken.RawKind) // { // case (int)SyntaxKind.MinusMinusToken: // var refactored= SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, // expression.Operand, // SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, expression.Operand, // SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,SyntaxFactory.Literal(-1))) // ).NormalizeWhitespace(); // Core.Write(writer,refactored); // break; // case (int)SyntaxKind.PlusPlusToken: // var refactored1 = SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, // expression.Operand, // SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, expression.Operand, // SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(+1))) // ).NormalizeWhitespace(); // Core.Write(writer, refactored1); // break; // default: // throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " + // Utility.Descriptor(expression)); // } // } // else // { // switch (expression.OperatorToken.RawKind) // { // case (int)SyntaxKind.MinusMinusToken: // Core.Write(writer, expression.Operand); // writer.Write("--"); // break; // case (int)SyntaxKind.PlusPlusToken: // Core.Write(writer, expression.Operand); // writer.Write("++"); // break; // default: // throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " + // Utility.Descriptor(expression)); // } // } // // } // else // { //D's unary operators are a bit different from C# .. i.e. not static bool hasOpIncrement = false; bool hasOpDecrement = false; var typeSymbol = TypeProcessor.GetTypeInfo(expression.Operand).Type; if (typeSymbol != null) { hasOpIncrement = typeSymbol.GetMembers("op_Increment").Any(); hasOpDecrement = typeSymbol.GetMembers("op_Decrement").Any(); } switch (expression.OperatorToken.RawKind) { case (int)SyntaxKind.MinusMinusToken: if (hasOpDecrement) { var texpression = Core.WriteString(expression.Operand); writer.Write(String.Format("/*{0}--*/({0}={0}.op_Decrement({0}))", texpression)); } else { Core.Write(writer, expression.Operand); writer.Write("--"); } break; case (int)SyntaxKind.PlusPlusToken: if (hasOpIncrement) { var texpression = Core.WriteString(expression.Operand); writer.Write(String.Format("/*{0}--*/({0}={0}.op_Increment({0}))", texpression)); } else { Core.Write(writer, expression.Operand); writer.Write("++"); } break; default: throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " + Utility.Descriptor(expression)); } } // } }
public static void WriteStatement(OutputWriter writer, ExpressionStatementSyntax statement) { writer.WriteIndent(); Write(writer, statement.Expression); writer.Write(";\r\n"); }
public static void Go(OutputWriter writer, SimpleLambdaExpressionSyntax expression) { Go(writer, new[] { expression.Parameter }, expression.Body, TypeProcessor.GetTypeInfo(expression)); }
public static void Go(OutputWriter writer, VariableDeclarationSyntax declaration) { foreach (var variable in declaration.Variables) { ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable); var isRef = false; //UsedAsRef(variable, symbol); writer.WriteIndent(); // writer.Write("var "); // if (isRef) //Not needed c++ can passby ref // { // // var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type); // // var localSymbol = symbol as ILocalSymbol; // var ptr = localSymbol != null && !localSymbol.Type.IsValueType?"*" : ""; // writer.Write("gc::gc_ptr < " + typeStr+ ptr + " >"); // writer.Write("" + typeStr + ptr + ""); // // writer.Write(" "); // writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text)); // // Program.RefOutSymbols.TryAdd(symbol, null); // // writer.Write(" = std::make_shared < "); // writer.Write(typeStr + ptr); // writer.Write(" >("); // // WriteInitializer(writer, declaration, variable); // // writer.Write(")"); // } // else { var lsymbol = symbol as ILocalSymbol; if (lsymbol != null && lsymbol.Type.IsValueType == false) { writer.Write(" "); // Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack } writer.Write(TypeProcessor.ConvertType(declaration.Type)); if (lsymbol != null && lsymbol.Type.IsValueType == false) { writer.Write(" "); } writer.Write(" "); writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text)); writer.Write(" = "); WriteInitializer(writer, declaration, variable); } writer.Write(";\r\n"); } }
private static void ProcessInitializer(OutputWriter writer, LocalDeclarationStatementSyntax declaration, VariableDeclaratorSyntax variable) { var initializer = variable.Initializer; if (initializer != null) { if (initializer.Value.CSharpKind() == SyntaxKind.CollectionInitializerExpression) { return; } var value = initializer.Value; var initializerType = TypeProcessor.GetTypeInfo(value); var memberaccessexpression = value as MemberAccessExpressionSyntax; var nameexpression = value as NameSyntax; var nullAssignment = value.ToFullString().Trim() == "null"; var convertedType = initializerType.ConvertedType; var type = initializerType.Type; if (type == null && convertedType == null) //TODO: Rare Case (Compiling csnative corlib... need to find a solution, for now just write it out { Core.Write(writer, value); return; } var shouldBox = type != null && (type.IsValueType) && !convertedType.IsValueType; var shouldUnBox = type != null && !type.IsValueType && convertedType.IsValueType; var isname = value is NameSyntax; var ismemberexpression = value is MemberAccessExpressionSyntax || (isname && TypeProcessor.GetSymbolInfo(value as NameSyntax).Symbol.Kind == SymbolKind.Method); var isdelegateassignment = ismemberexpression && convertedType.TypeKind == TypeKind.Delegate; var isstaticdelegate = isdelegateassignment && ((memberaccessexpression != null && TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) || (isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic)); //Do we have an implicit converter, if so, use it if (shouldBox || shouldUnBox) { if (WriteConverter(writer, type, convertedType, value)) { return; } } if (nullAssignment) { if (convertedType != null) //Nullable Support { if (convertedType.Name == "Nullable") { var atype = TypeProcessor.ConvertType(convertedType); writer.Write(atype + "()"); } else { writer.Write("null"); } } return; } if (shouldBox) { WriteBox(writer, type, value); return; } if (shouldUnBox) { WriteUnbox(writer, type, value); return; } if (isdelegateassignment) { WriteDelegateAssignment(writer, convertedType, isstaticdelegate, value); return; } // if (type == null && convertedType == null) // { // writer.Write("null"); // return; // } //CTFE /* var aVal = EvaluateValue(value); * if (String.IsNullOrEmpty(aVal)) * { * writer.Write(aVal); * } * else*/ Core.Write(writer, value); } else { writer.Write(TypeProcessor.DefaultValue(declaration.Declaration.Type)); } }
private static void WriteUnbox(OutputWriter writer, ITypeSymbol type, ExpressionSyntax value) { writer.Write("Cast!(" + TypeProcessor.ConvertType(type) + ")("); Core.Write(writer, value); writer.Write(")"); }
public static void Go(OutputWriter writer, AnonymousMethodExpressionSyntax expression) { Go(writer, expression.ParameterList.Parameters, expression.Block, TypeProcessor.GetTypeInfo(expression)); }
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 ... }
public static void Go(OutputWriter writer, ContinueStatementSyntax statement) { writer.WriteLine("continue;"); }
public static void Go(OutputWriter writer, ParenthesizedLambdaExpressionSyntax expression) { Go(writer, expression.ParameterList.Parameters, expression.Body, TypeProcessor.GetTypeInfo(expression)); }
private static void ProcessInitializer(OutputWriter writer, VariableDeclarationSyntax declaration, VariableDeclaratorSyntax variable) { var initializer = variable.Initializer; if (initializer != null) { if (CSharpExtensions.CSharpKind(initializer.Value) == SyntaxKind.CollectionInitializerExpression) { return; } var value = initializer.Value; var initializerType = TypeProcessor.GetTypeInfo(value); var memberaccessexpression = value as MemberAccessExpressionSyntax; var nameexpression = value as NameSyntax; var nullAssignment = value.ToFullString().Trim() == "null"; var shouldBox = initializerType.Type != null && (initializerType.Type.IsValueType) && !initializerType.ConvertedType.IsValueType; var shouldUnBox = initializerType.Type != null && !initializerType.Type.IsValueType && initializerType.ConvertedType.IsValueType; var isname = value is NameSyntax; var ismemberexpression = value is MemberAccessExpressionSyntax || (isname && TypeProcessor.GetSymbolInfo(value as NameSyntax).Symbol.Kind == SymbolKind.Method); var isdelegateassignment = ismemberexpression && initializerType.ConvertedType.TypeKind == TypeKind.Delegate; var isstaticdelegate = isdelegateassignment && ((memberaccessexpression != null && TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) || (isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic)); var shouldCast = initializerType.Type != initializerType.ConvertedType && initializerType.ConvertedType != null; if (nullAssignment) { if (initializerType.Type != null) //Nullable Support { if (initializerType.Type.Name == "Nullable") { var atype = TypeProcessor.ConvertType(initializerType.Type); writer.Write(atype + "()"); } } else { writer.Write("null"); } return; } if (shouldBox) { //Box writer.Write("BOX!(" + TypeProcessor.ConvertType(initializerType.Type) + ")("); //When passing an argument by ref or out, leave off the .Value suffix Core.Write(writer, value); writer.Write(")"); return; } if (shouldUnBox) { writer.Write("cast(" + TypeProcessor.ConvertType(initializerType.Type) + ")("); Core.Write(writer, value); writer.Write(")"); return; } if (initializer.Parent.Parent.Parent is FixedStatementSyntax) // Fixed is a bit special { //TODO write a better fix var type = TypeProcessor.GetTypeInfo(declaration.Type); writer.Write("cast(" + TypeProcessor.ConvertType(type.Type) + ")("); Core.Write(writer, value); writer.Write(")"); return; } if (isdelegateassignment) { var typeString = TypeProcessor.ConvertType(initializerType.ConvertedType); var createNew = !(value is ObjectCreationExpressionSyntax); if (createNew) { if (initializerType.ConvertedType.TypeKind == TypeKind.TypeParameter) { writer.Write(" __TypeNew!(" + typeString + ")("); } else { writer.Write("new " + typeString + "("); } } var isStatic = isstaticdelegate; // if (isStatic) // writer.Write("__ToDelegate("); MemberUtilities.WriteMethodPointer(writer, value); // if (isStatic) // writer.Write(")"); if (createNew) { writer.Write(")"); } return; } if (initializerType.Type == null && initializerType.ConvertedType == null) { writer.Write("null"); return; } Core.Write(writer, value); } else { writer.Write(TypeProcessor.DefaultValue(declaration.Type)); } }
private static void Go(OutputWriter writer, IEnumerable <ParameterSyntax> parameters, SyntaxNode body, TypeInfo type) { var methodSymbol = type.ConvertedType.As <INamedTypeSymbol>().DelegateInvokeMethod.As <IMethodSymbol>(); var typeStringNoPtr = TypeProcessor.ConvertType(type.ConvertedType); if (type.ConvertedType.TypeKind == TypeKind.TypeParameter) { writer.Write(" __TypeNew!(" + typeStringNoPtr + ")("); } else { writer.Write("new " + typeStringNoPtr + "("); } writer.Write("("); var parameterSyntaxs = parameters as ParameterSyntax[] ?? parameters.ToArray(); for (int pi = 0; pi < parameterSyntaxs.Count(); pi++) { var parameter = parameterSyntaxs.ElementAt(pi); if (pi > 0) { writer.Write(", "); } if (parameter.Type != null) { writer.Write(TypeProcessor.ConvertType(parameter.Type) + " "); } else { writer.Write(TypeProcessor.ConvertType(methodSymbol.Parameters[pi].Type) + " "); } writer.Write(WriteIdentifierName.TransformIdentifier(parameter.Identifier.Text)); } writer.Write(")"); bool returnsVoid = methodSymbol.ReturnType.ToString() == "void"; if (body is BlockSyntax) { writer.Write("\r\n"); writer.OpenBrace(); var statements = body.As <BlockSyntax>().Statements; var lastStatement = statements.LastOrDefault() as ReturnStatementSyntax; var returnStatements = FindReturnStatements(body); { foreach (var statement in statements) { if (statement == lastStatement) { writer.WriteIndent(); Core.Write(writer, lastStatement); // writer.Write(";\r\n"); } else { Core.Write(writer, statement); } } } writer.Indent--; writer.WriteIndent(); writer.Write("}"); } else { if (!returnsVoid) { writer.Write("=> "); Core.Write(writer, body); } else { writer.Write(" { "); Core.Write(writer, body); writer.Write("; }"); } //writer.Write(" { "); //if (!returnsVoid) // writer.Write ("return "); // writer.Write("; }"); } // if (!returnsVoid) // writer.Write(TypeProcessor.ConvertTypeWithColon(methodSymbol.ReturnType)); writer.Write(")"); }
private static void Factory(OutputWriter writer, SyntaxNode node, bool isConst) { if (node is ConstructorInitializerSyntax) { WriteConstructorInitializer.Go(writer, node.As <ConstructorInitializerSyntax>()); } else if (node is CheckedExpressionSyntax) { WriteChecked.Go(writer, node.As <CheckedExpressionSyntax>()); } else if (node is CheckedStatementSyntax) { WriteChecked.Go(writer, node.As <CheckedStatementSyntax>()); } else if (node is UnsafeStatementSyntax) { WriteUnsafeStatement.Go(writer, node.As <UnsafeStatementSyntax>()); } else if (node is InitializerExpressionSyntax) { WriteInitializer.Go(writer, node.As <InitializerExpressionSyntax>()); } else if (node is GotoStatementSyntax) { WriteGoto.Go(writer, node.As <GotoStatementSyntax>()); } else if (node is CaseSwitchLabelSyntax) { WriteLabel.Go(writer, node.As <CaseSwitchLabelSyntax>()); } else if (node is LabeledStatementSyntax) { WriteLabel.Go(writer, node.As <LabeledStatementSyntax>()); } else if (node is OperatorDeclarationSyntax) { WriteOperatorDeclaration.Go(writer, node.As <OperatorDeclarationSyntax>()); } else if (node is MethodDeclarationSyntax) { WriteMethod.Go(writer, node.As <MethodDeclarationSyntax>()); } else if (node is PropertyDeclarationSyntax) { WriteProperty.Go(writer, node.As <PropertyDeclarationSyntax>()); } else if (node is EventDeclarationSyntax) { WriteEvent.Go(writer, node.As <EventDeclarationSyntax>()); } else if (node is FieldDeclarationSyntax) { WriteField.Go(writer, node.As <FieldDeclarationSyntax>()); } else if (node is EventFieldDeclarationSyntax) { WriteField.Go(writer, node.As <EventFieldDeclarationSyntax>()); } else if (node is ConstructorDeclarationSyntax) { WriteConstructorBody.Go(writer, node.As <ConstructorDeclarationSyntax>()); } else if (node is ExpressionStatementSyntax) { WriteStatement(writer, node.As <ExpressionStatementSyntax>()); } else if (node is FixedStatementSyntax) { WriteFixedStatement(writer, node.As <FixedStatementSyntax>()); } else if (node is LocalDeclarationStatementSyntax) { WriteLocalDeclaration.Go(writer, node.As <LocalDeclarationStatementSyntax>()); } else if (node is VariableDeclarationSyntax) { WriteVariableDeclaration.Go(writer, node.As <VariableDeclarationSyntax>()); } else if (node is BlockSyntax) { WriteBlock(writer, node.As <BlockSyntax>()); } else if (node is InvocationExpressionSyntax) { WriteInvocationExpression.Go(writer, node.As <InvocationExpressionSyntax>()); } else if (node is LiteralExpressionSyntax) { WriteLiteralExpression.Go(writer, node.As <LiteralExpressionSyntax>(), isConst); } else if (node is IdentifierNameSyntax) { WriteIdentifierName.Go(writer, node.As <IdentifierNameSyntax>()); } else if (node is ImplicitArrayCreationExpressionSyntax) { WriteArrayCreationExpression.Go(writer, node.As <ImplicitArrayCreationExpressionSyntax>()); } else if (node is ArrayCreationExpressionSyntax) { WriteArrayCreationExpression.Go(writer, node.As <ArrayCreationExpressionSyntax>()); } else if (node is MemberAccessExpressionSyntax) { WriteMemberAccessExpression.Go(writer, node.As <MemberAccessExpressionSyntax>()); } else if (node is ParenthesizedLambdaExpressionSyntax) { WriteLambdaExpression.Go(writer, node.As <ParenthesizedLambdaExpressionSyntax>()); } else if (node is SimpleLambdaExpressionSyntax) { WriteLambdaExpression.Go(writer, node.As <SimpleLambdaExpressionSyntax>()); } else if (node is AnonymousMethodExpressionSyntax) { WriteLambdaExpression.Go(writer, node.As <AnonymousMethodExpressionSyntax>()); } else if (node is ReturnStatementSyntax) { WriteReturnStatement.Go(writer, node.As <ReturnStatementSyntax>()); } else if (node is ObjectCreationExpressionSyntax) { WriteObjectCreationExpression.Go(writer, node.As <ObjectCreationExpressionSyntax>()); } else if (node is ElementAccessExpressionSyntax) { WriteElementAccessExpression.Go(writer, node.As <ElementAccessExpressionSyntax>()); } else if (node is ForEachStatementSyntax) { WriteForEachStatement.Go(writer, node.As <ForEachStatementSyntax>()); } else if (node is IfStatementSyntax) { WriteIfStatement.Go(writer, node.As <IfStatementSyntax>()); } else if (node is BinaryExpressionSyntax) { WriteBinaryExpression.Go(writer, node.As <BinaryExpressionSyntax>()); } else if (node is AssignmentExpressionSyntax) { WriteAssignmentExpression.Go(writer, node.As <AssignmentExpressionSyntax>()); } else if (node is ConditionalExpressionSyntax) { WriteConditionalExpression.Go(writer, node.As <ConditionalExpressionSyntax>()); } else if (node is BaseExpressionSyntax) { WriteBaseExpression.Go(writer, node.As <BaseExpressionSyntax>()); } else if (node is ThisExpressionSyntax) { WriteThisExpression.Go(writer, node.As <ThisExpressionSyntax>()); } else if (node is CastExpressionSyntax) { WriteCastExpression.Go(writer, node.As <CastExpressionSyntax>()); } else if (node is ThrowStatementSyntax) { WriteThrowStatement.Go(writer, node.As <ThrowStatementSyntax>()); } else if (node is EqualsValueClauseSyntax) { WriteEqualsValueClause.Go(writer, node.As <EqualsValueClauseSyntax>()); } else if (node is ForStatementSyntax) { WriteForStatement.Go(writer, node.As <ForStatementSyntax>()); } else if (node is WhileStatementSyntax) { WriteWhileStatement.Go(writer, node.As <WhileStatementSyntax>()); } else if (node is BreakStatementSyntax) { WriteBreakStatement.Go(writer, node.As <BreakStatementSyntax>()); } else if (node is ContinueStatementSyntax) { WriteContinueStatement.Go(writer, node.As <ContinueStatementSyntax>()); } else if (node is DoStatementSyntax) { WriteDoStatement.Go(writer, node.As <DoStatementSyntax>()); } else if (node is SwitchStatementSyntax) { WriteSwitchStatement.Go(writer, node.As <SwitchStatementSyntax>()); } else if (node is TryStatementSyntax) { WriteTryStatement.Go(writer, node.As <TryStatementSyntax>()); } else if (node is UsingStatementSyntax) { WriteUsingStatement.Go(writer, node.As <UsingStatementSyntax>()); } else if (node is ParenthesizedExpressionSyntax) { WriteParenthesizedExpression.Go(writer, node.As <ParenthesizedExpressionSyntax>()); } else if (node is LockStatementSyntax) { WriteLockStatement.Go(writer, node.As <LockStatementSyntax>()); } else if (node is TypeOfExpressionSyntax) { WriteTypeOfExpression.Go(writer, node.As <TypeOfExpressionSyntax>()); } else if (node is AnonymousObjectCreationExpressionSyntax) { WriteAnonymousObjectCreationExpression.Go(writer, node.As <AnonymousObjectCreationExpressionSyntax>()); } else if (node is EmptyStatementSyntax) { return; //ignore empty statements } else if (node is DelegateDeclarationSyntax) { return; //don't write delegates - TypeProcessor converts them to function types directly } else if (node is DefaultExpressionSyntax) { WriteDefaultExpression.Go(writer, node.As <DefaultExpressionSyntax>()); } else if (node is GenericNameSyntax) { WriteGenericName.Go(writer, node.As <GenericNameSyntax>()); } else if (node is ConversionOperatorDeclarationSyntax) { WriteConversionOperatorDeclaration.Go(writer, node.As <ConversionOperatorDeclarationSyntax>()); } else if (node is PrefixUnaryExpressionSyntax) { WriteUnaryExpression.WritePrefix(writer, node.As <PrefixUnaryExpressionSyntax>()); } else if (node is PostfixUnaryExpressionSyntax) { WriteUnaryExpression.WritePostfix(writer, node.As <PostfixUnaryExpressionSyntax>()); } else if (node is SizeOfExpressionSyntax) { WriteSizeOfExpression.Go(writer, node.As <SizeOfExpressionSyntax>()); } else if (node is DestructorDeclarationSyntax) { WriteDestructorBody.WriteDestructor(writer, node.As <DestructorDeclarationSyntax>()); } else if (node is IndexerDeclarationSyntax) { WriteIndexer.Go(writer, node.As <IndexerDeclarationSyntax>()); } else if (node is StackAllocArrayCreationExpressionSyntax) { WriteStackArrayCreation.Go(writer, node.As <StackAllocArrayCreationExpressionSyntax>()); } // writer.Write(node.ToFullString() + "//TODO: StackAlloc not supported yet"); else if (node is YieldStatementSyntax) { WriteYieldStatement.Go(writer, node.As <YieldStatementSyntax>()); } else { throw new NotImplementedException(node.GetType().Name + " is not supported. " + Utility.Descriptor(node)); } }
public static void Go(OutputWriter writer, ThisExpressionSyntax expression) { writer.Write("this"); }
private static void ProcessInitializer(OutputWriter writer, LocalDeclarationStatementSyntax declaration, VariableDeclaratorSyntax variable) { var initializer = variable.Initializer; if (initializer != null) { if (initializer.Value.CSharpKind() == SyntaxKind.CollectionInitializerExpression) { return; } var value = initializer.Value; var initializerType = TypeProcessor.GetTypeInfo(value); var memberaccessexpression = value as MemberAccessExpressionSyntax; var nameexpression = value as NameSyntax; var nullAssignment = value.ToFullString().Trim() == "null"; var shouldBox = initializerType.Type != null && initializerType.Type.IsValueType && !initializerType.ConvertedType.IsValueType; var shouldUnBox = initializerType.Type != null && !initializerType.Type.IsValueType && initializerType.ConvertedType.IsValueType; var isname = value is NameSyntax; var ismemberexpression = value is MemberAccessExpressionSyntax || (isname && TypeProcessor.GetSymbolInfo(value as NameSyntax).Symbol.Kind == SymbolKind.Method); var isdelegateassignment = ismemberexpression && initializerType.ConvertedType.TypeKind == TypeKind.Delegate; var isstaticdelegate = isdelegateassignment && ((memberaccessexpression != null && TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) || (isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic)); //Do we have an implicit converter, if so, use it if (shouldBox || shouldUnBox) { // if (shouldUnBox) // { // bool useType = true; // // //We should start with exact converters and then move to more generic convertors i.e. base class or integers which are implicitly convertible // var correctConverter = initializerType.Type.GetImplicitCoversionOp(initializerType.Type,initializerType.ConvertedType); //// initializerType.Type.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType); // // if (correctConverter == null) // { // useType = false; // correctConverter = // initializerType.ConvertedType.GetImplicitCoversionOp(initializerType.Type, initializerType.ConvertedType); //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType); // } // // if (correctConverter != null) // { // if(useType) // writer.Write(TypeProcessor.ConvertType(initializerType.Type) +"."+ "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType)); // else // { // writer.Write(TypeProcessor.ConvertType(initializerType.ConvertedType) +"."+ "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType)); // // } // writer.Write("("); // Core.Write(writer, value); // writer.Write(")"); // return; // } // } // if (shouldBox) { bool useType = true; var correctConverter = initializerType.Type.GetImplicitCoversionOp(initializerType.ConvertedType, initializerType.Type); //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.ConvertedType && h.Parameters[0].Type == initializerType.Type); if (correctConverter == null) { useType = false; correctConverter = initializerType.ConvertedType.GetImplicitCoversionOp(initializerType.ConvertedType, initializerType.Type); //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.ConvertedType && h.Parameters[0].Type == initializerType.Type); } if (correctConverter != null) { if (useType) { writer.Write(TypeProcessor.ConvertType(initializerType.Type) + "." + "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType)); } else { writer.Write(TypeProcessor.ConvertType(initializerType.ConvertedType) + "." + "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType)); } writer.Write("("); Core.Write(writer, value); writer.Write(")"); return; } } } if (nullAssignment) { writer.Write("null"); return; } if (shouldBox) { //Box writer.Write("BOX!(" + TypeProcessor.ConvertType(initializerType.Type) + ")("); //When passing an argument by ref or out, leave off the .Value suffix Core.Write(writer, value); writer.Write(")"); return; } if (shouldUnBox) { //UnBox writer.Write("cast!(" + TypeProcessor.ConvertType(initializerType.Type) + ")("); Core.Write(writer, value); writer.Write(")"); } if (isdelegateassignment) { var createNew = !(value is ObjectCreationExpressionSyntax); var typeString = TypeProcessor.ConvertType(initializerType.ConvertedType); if (createNew) { if (initializerType.ConvertedType.TypeKind == TypeKind.TypeParameter) { writer.Write(" __TypeNew!(" + typeString + ")("); } else { writer.Write("new " + typeString + "("); } } var isStatic = isstaticdelegate; if (isStatic) { writer.Write("__ToDelegate("); } writer.Write("&"); Core.Write(writer, value); if (isStatic) { writer.Write(")"); } if (createNew) { writer.Write(")"); } return; } if (initializerType.Type == null && initializerType.ConvertedType == null) { writer.Write("null"); return; } Core.Write(writer, value); } else { writer.Write(TypeProcessor.DefaultValue(declaration.Declaration.Type)); } }
private static void WriteInitializer(OutputWriter writer, VariableDeclarationSyntax declaration, VariableDeclaratorSyntax variable) { ProcessInitializer(writer, declaration, variable); }
private static bool WriteArrayElements(InitializerExpressionSyntax initializer, OutputWriter writer, Dictionary <int, int> inferred, int level, bool omitbraces = false) { level++; if (!omitbraces) { writer.Write("["); } bool first = true; if (!inferred.ContainsKey(level)) { inferred.Add(level, initializer.Expressions.Count); } foreach (var iexpression in initializer.Expressions) { if (first) { first = false; } else { writer.Write(","); } if (iexpression is InitializerExpressionSyntax) { WriteArrayElements(iexpression as InitializerExpressionSyntax, writer, inferred, level, omitbraces); } else { Core.Write(writer, iexpression); } } if (!omitbraces) { writer.Write("]"); } return(first); }
public static void WritePrefix(OutputWriter writer, PrefixUnaryExpressionSyntax expression) { var isProperty = false; var symbol = TypeProcessor.GetSymbolInfo(expression.Operand); if (symbol.Symbol is IPropertySymbol) { isProperty = true; } if (isProperty) { var symbolName = Core.WriteString(expression.Operand).ToString().Trim(); switch (expression.OperatorToken.RawKind) { case (int)SyntaxKind.MinusMinusToken: if ((symbol.Symbol as IPropertySymbol).IsIndexer) { writer.Write(String.Format("/*--{0}*/((){{ auto v = {0};{0}=(--v);return v;}})()", symbolName)); } else { writer.Write(String.Format("/*--{0}*/((){{ auto v = {0};{0}(--v);return v;}})()", symbolName)); } break; case (int)SyntaxKind.PlusPlusToken: if ((symbol.Symbol as IPropertySymbol).IsIndexer) { writer.Write(String.Format("/*++{0}*/((){{ auto v = {0};{0}=(++v);return v;}})()", symbolName)); } else { writer.Write(String.Format("/*++{0}*/((){{ auto v = {0};{0}(++v);return v;}})()", symbolName)); } break; default: writer.Write(expression.OperatorToken.Text); Core.Write(writer, expression.Operand); break; } } else { // Console.WriteLine (expression.ToFullString()); // if (expression.OperatorToken.RawKind == (decimal)SyntaxKind.MinusMinusToken) // { // // writer.Write ("--"); // Core.Write (writer, expression.Operand); // } // else if (expression.OperatorToken.RawKind == (decimal)SyntaxKind.PlusPlusToken) // { // writer.Write ("++"); // Core.Write (writer, expression.Operand); // } // else // { // //TODO: cannot take addresses of structs in 32/64-bit mode and subtract them ... really weird d-bug ... leads to wrong math ... should we do a shift ? //// if (expression.OperatorToken.CSharpKind () == SyntaxKind.AmpersandToken) // Take address //// { //// var memberAccess = expression.Operand as MemberAccessExpressionSyntax; //// var simpleName = expression.Operand as NameSyntax; //// //// TypeInfo typeOperand; //// //// if (memberAccess != null) //// typeOperand = TypeProcessor.GetTypeInfo (memberAccess.Expression); //// if (simpleName != null) //// typeOperand = TypeProcessor.GetTypeInfo (simpleName); //// //// var failed = true; // //// if (memberAccess != null) //// { //// failed = false; //// if (typeOperand.Type.TypeKind == TypeKind.Struct) //// { //// var sNAme = (memberAccess.Expression as SimpleNameSyntax).Identifier; //// //// writer.Write ("(cast(ulong)(&" + sNAme.ToFullString () + ") + ("); //// Core.Write (writer, expression.Operand); //// writer.Write (".offsetof))"); //// } //// else //// failed = true; //// } //// else if (simpleName != null) //// { //// failed = false; //// //// if (typeOperand.Type.TypeKind == TypeKind.Struct) //// { //// writer.Write ("(&" + simpleName.ToFullString () + " + ("); //// Core.Write (writer, expression.Operand); //// writer.Write (".offsetof))"); //// } //// else //// failed = true; //// } //// //// if(failed) //// { //// writer.Write (expression.OperatorToken.ToString ()); //// Core.Write (writer, expression.Operand); //// } //// //// } //// else // { // writer.Write (expression.OperatorToken.ToString ()); // Core.Write (writer, expression.Operand); // } // } //D's unary operators are a bit different from C# .. i.e. not static bool hasOpIncrement = false; bool hasOpDecrement = false; var typeSymbol = TypeProcessor.GetTypeInfo(expression.Operand).Type; if (typeSymbol != null) { hasOpIncrement = typeSymbol.GetMembers("op_Increment").Any(); hasOpDecrement = typeSymbol.GetMembers("op_Decrement").Any(); } switch (expression.OperatorToken.RawKind) { case (int)SyntaxKind.MinusMinusToken: if (hasOpDecrement) { var texpression = Core.WriteString(expression.Operand); writer.Write(String.Format("/*--{0}*/((){{ auto v = {0};{0}={0}.op_Decrement({0});return v;}})()", texpression)); } else { writer.Write("--"); Core.Write(writer, expression.Operand); } break; case (int)SyntaxKind.PlusPlusToken: if (hasOpIncrement) { var texpression = Core.WriteString(expression.Operand); writer.Write(String.Format("/*++{0}*/((){{ auto v = {0};{0}={0}.op_Increment({0});return v;}})()", texpression)); } else { writer.Write("++"); Core.Write(writer, expression.Operand); } break; default: writer.Write(expression.OperatorToken.Text); Core.Write(writer, expression.Operand); // throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " + //Utility.Descriptor(expression)); break; } } }
public static void WriteArrayInitializer(this InitializerExpressionSyntax initializer, OutputWriter writer, TypeSyntax type = null) { bool first = true; ArrayTypeSyntax arrayType = null; ExpressionSyntax[] fullDimension = null; var inferredDimensions = new Dictionary <int, int>(); ITypeSymbol aType = null; IArrayTypeSymbol _aType = null; if (type != null) { arrayType = type as ArrayTypeSyntax; if (arrayType != null) { aType = TypeProcessor.GetTypeInfo(arrayType).Type as IArrayTypeSymbol; } else { aType = (ITypeSymbol)TypeProcessor.GetTypeInfo(type).Type; } _aType = aType as IArrayTypeSymbol; } //For ommitedsizes, lets just count manually List <int> inferredSizes = new List <int>(); if (initializer != null) { if (initializer.Expressions.Count > 0) { if (_aType != null) { writer.Write("__CC!(" + TypeProcessor.ConvertType(_aType.ElementType) /*+ Enumerable.Range (0, _aType.Rank).Select (l => "[]").Aggregate ((a, b) => a + b).ToString ()*/ + "[])("); } if (_aType.Rank == 1) { first = WriteArrayElements(initializer, writer, inferredDimensions, 0); } else //multi { writer.Write("["); first = WriteArrayElements(initializer, writer, inferredDimensions, 0, true); writer.Write("]"); } //inferredDimensions = inferredDimensions.Take (_aType.Rank).ToList(); inferredSizes = inferredDimensions.Select(k => k.Value).ToList(); if (_aType != null) { writer.Write(")"); } } } if (type != null) { if (arrayType != null && _aType != null) { //Don't do this for jagged arrays ...rank = 1 and .GetLength(>0) throws exception // if(aType.Rank > 1) { fullDimension = arrayType.RankSpecifiers.Select(o => o.Sizes).SelectMany(j => j).ToArray(); if (_aType.Rank > 1) { //If we have a multi-array, we have to have dimensions if (!fullDimension.Any(l => l is OmittedArraySizeExpressionSyntax)) { for (int i = 0, fullDimensionLength = fullDimension.Length; i < fullDimensionLength; i++) { var dimensions = fullDimension[i]; if (dimensions is OmittedArraySizeExpressionSyntax) { continue; } if (first) { first = false; } else { writer.Write(" , "); } // MultidimArray Core.Write(writer, dimensions); } } else { for (int i = 0, fullDimensionLength = inferredSizes.Count; i < fullDimensionLength; i++) { var dimensions = inferredSizes[i]; if (first) { first = false; } else { writer.Write(" , "); } // MultidimArray writer.Write(dimensions.ToString()); } } } else { var dimensions = fullDimension[0]; if (!(dimensions is OmittedArraySizeExpressionSyntax)) { if (first) { first = false; } else { writer.Write(" , "); } Core.Write(writer, dimensions); } } } } } }