From 042f756070c3cac0b5c79d6f4e1e837a2f65da07 Mon Sep 17 00:00:00 2001 From: marc hoffman Date: Fri, 10 Feb 2017 16:19:56 -0400 Subject: [PATCH] Updated to use RTL2 instead of Sugar, part one --- Base.swift | 19 +- CGCPlusPlusCPPCodeGenerator.swift | 40 +- CGCPlusPlusCodeGenerator.swift | 420 ++++++------ CGCPlusPlusHCodeGenerator.swift | 171 +++-- CGCSharpCodeGenerator.swift | 10 +- CGCStyleCodeGenerator.swift | 41 +- CGCodeGenerator.swift | 5 +- CGDelphiCodeGenerator.swift | 164 +++-- CGJavaCodeGenerator.swift | 19 +- CGJavaScriptCodeGenerator.swift | 7 +- CGObjectiveCCodeGenerator.swift | 98 ++- CGObjectiveCHCodeGenerator.swift | 45 +- CGObjectiveCMCodeGenerator.swift | 30 +- CGOxygeneCodeGenerator.swift | 130 ++-- CGPascalCodeGenerator.swift | 92 ++- CGSkeletonCodeGenerator.swift | 85 ++- CGSwiftCodeGenerator.swift | 180 +++--- CGVisualBasicNetCodeGenerator.swift | 129 ++-- CodeDomToCG4.swift | 240 +++---- Expressions.swift | 82 ++- Extensions.swift | 26 +- Statements.swift | 690 ++++++++++---------- TypeDefinitions.swift | 972 ++++++++++++++-------------- TypeReferences.swift | 44 +- 24 files changed, 1828 insertions(+), 1911 deletions(-) diff --git a/Base.swift b/Base.swift index 4fd2a48..6de81a2 100644 --- a/Base.swift +++ b/Base.swift @@ -1,7 +1,4 @@ -import Sugar -import Sugar.Collections - -public enum CGPlatform { +public enum CGPlatform { case Echoes case Cooper case Toffee @@ -22,7 +19,7 @@ public __abstract class CGEntity { } public class CGCodeUnit { - + public var FileName: String? public var Namespace: CGNamespaceReference? public var HeaderComment = CGCommentStatement() @@ -31,7 +28,7 @@ public class CGCodeUnit { public var FileImports = List() public var Types = List() public var Globals = List() - + public var ImplementationDirectives = List() /* Pascal only */ public var ImplementationImports = List() /* Pascal only */ public var Initialization: List? /* Delphi only */ @@ -50,7 +47,7 @@ public class CGCodeUnit { public class CGCompilerDirective { public var Directive: String /* will not be language agnostic */ public var Condition: CGConditionalDefine? - + public init(_ directive: String) { Directive = directive } @@ -63,7 +60,7 @@ public class CGCompilerDirective { public class CGImport { public var Namespace: CGNamespaceReference? public var StaticClass: CGNamedTypeReference? - + public var Name: String! { if let ns = Namespace { return ns.Name @@ -100,7 +97,7 @@ public class CGConditionalDefine { } public convenience init(_ define: String) { - init(CGNamedIdentifierExpression(define)) + init(CGNamedIdentifierExpression(define)) } public init(_ define: String, inverted: Boolean) { @@ -125,8 +122,8 @@ public class CGGlobalFunctionDefinition : CGGlobalDefinition { public class CGGlobalVariableDefinition : CGGlobalDefinition { public var Variable: CGFieldDefinition - + public init(_ variable: CGFieldDefinition) { Variable = variable } -} +} \ No newline at end of file diff --git a/CGCPlusPlusCPPCodeGenerator.swift b/CGCPlusPlusCPPCodeGenerator.swift index 6debd34..cd1ca41 100644 --- a/CGCPlusPlusCPPCodeGenerator.swift +++ b/CGCPlusPlusCPPCodeGenerator.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.IO - -public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { +public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { public override var defaultFileExtension: String { return "cpp" } public var UseHdrStop: Boolean = true @@ -23,14 +19,14 @@ public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { var lastGlobal: CGGlobalDefinition? = nil for g in currentUnit.Globals { var visibility: CGMemberVisibilityKind = .Unspecified; - if let method = g as? CGGlobalFunctionDefinition { + if let method = g as? CGGlobalFunctionDefinition { visibility = .Unit; } - if let variable = g as? CGGlobalVariableDefinition { + if let variable = g as? CGGlobalVariableDefinition { visibility = variable.Variable.Visibility; } // generate only .Unit & .Private visibility - if ((visibility == .Unit)||(visibility == .Private)){ + if ((visibility == .Unit)||(visibility == .Private)){ if let lastGlobal = lastGlobal, globalNeedsSpace(g, afterGlobal: lastGlobal) { AppendLine() } @@ -56,7 +52,7 @@ public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { AppendLine("#include \"\(Path.ChangeExtension(fileName, ".h"))\"") } } - + override func generateFooter(){ var lnamespace = currentUnit.FileName; if isCBuilder() { @@ -102,26 +98,26 @@ public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { // // Types // - + override func generateStructType(_ type: CGStructTypeDefinition) { // structs don't appear in .m } - + override func generateInterfaceType(_ type: CGInterfaceTypeDefinition) { // protocols don't appear in .m } - + // // Type Members // - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { cppGenerateMethodDefinitionHeader(method, type: type, header: false) AppendLine() AppendLine("{") incIndent() // process local variables - if let localVariables = method.LocalVariables, localVariables.Count > 0 { + if let localVariables = method.LocalVariables, localVariables.Count > 0 { for v in localVariables { generateVariableDeclarationStatement(v); } @@ -134,25 +130,25 @@ public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { if let getStatements = property.GetStatements, let method = property.GetterMethodDefinition() { method.Name = "get__" + property.Name - if isCBuilder() { + if isCBuilder() { method.CallingConvention = .Register } generateMethodDefinition(method, type: type) } if let setStatements = property.SetStatements, let method = property.SetterMethodDefinition() { method.Name = "set__" + uppercaseFirstLetter(property.Name) - if isCBuilder() { + if isCBuilder() { method.CallingConvention = .Register } generateMethodDefinition(method, type: type) } } - + override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) { - if type == CGGlobalTypeDefinition.GlobalType { + if type == CGGlobalTypeDefinition.GlobalType { super.generateFieldDefinition(field, type: type) } - } + } override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { cppGenerateMethodDefinitionHeader(ctor, type: type, header: false) @@ -160,7 +156,7 @@ public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { AppendLine("{") incIndent() // process local variables - if let localVariables = ctor.LocalVariables, localVariables.Count > 0 { + if let localVariables = ctor.LocalVariables, localVariables.Count > 0 { for v in localVariables { generateVariableDeclarationStatement(v); } @@ -176,7 +172,7 @@ public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { AppendLine("{") incIndent() // process local variables - if let localVariables = dtor.LocalVariables, localVariables.Count > 0 { + if let localVariables = dtor.LocalVariables, localVariables.Count > 0 { for v in localVariables { generateVariableDeclarationStatement(v); } @@ -187,4 +183,4 @@ public class CGCPlusPlusCPPCodeGenerator : CGCPlusPlusCodeGenerator { } -} +} \ No newline at end of file diff --git a/CGCPlusPlusCodeGenerator.swift b/CGCPlusPlusCodeGenerator.swift index e2b18ca..46883fb 100644 --- a/CGCPlusPlusCodeGenerator.swift +++ b/CGCPlusPlusCodeGenerator.swift @@ -1,11 +1,7 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -public enum CGCPlusPlusCodeGeneratorDialect { +public enum CGCPlusPlusCodeGeneratorDialect { case Standard - case CPlusPlusBuilder //C++Builder - case VCPlusPlus //MS Visual C++ + case CPlusPlusBuilder //C++Builder + case VCPlusPlus //MS Visual C++ } // @@ -20,7 +16,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { func isStandard() -> Boolean{ return Dialect == CGCPlusPlusCodeGeneratorDialect.Standard; } - + func isCBuilder() -> Boolean{ return Dialect == CGCPlusPlusCodeGeneratorDialect.CPlusPlusBuilder; } @@ -32,42 +28,42 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { public init() { super.init() // from http://en.cppreference.com/w/cpp/keyword - keywords = ["alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", - "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "concept", "const", - "const_cast", "constexpr", "continue", "decltype", "default", "define", "defined", "delete", + keywords = ["alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", + "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "concept", "const", + "const_cast", "constexpr", "continue", "decltype", "default", "define", "defined", "delete", "do", "double", "dynamic_cast", "elif", "else", "endif", "enum", "error", "explicit", "export", "extern", "false", "final", "float", "for", "friend", "goto", "if", "ifdef", "ifndef", "include", - "inline", "int", "line", "long", "mutable", "namespace", "new", "noexcept", "not", "not_eq", + "inline", "int", "line", "long", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "override", "pragma", "private", "protected", "public", "register", "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "undef", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq"].ToList() as! List; - // // c++Builder keywords - // keywords = ["__asm", "__automated", "__cdecl", "__classid", "__classmethod", "__closure", "__declspec", - // "__delphirtti", "__dispid", "__except", "__export", "__fastcall", "__finally", "__import", - // "__inline", "__int16", "__int32", "__int64", "__int8", "__msfastcall", "__msreturn", - // "__pascal", "__property", "__published", "__rtti", "__stdcall", "__thread", "__try", "_asm", - // "_Bool", "_cdecl", "_Complex", "_export", "_fastcall", "_Imaginary", "_import", "_pascal", - // "_stdcall", "alignas", "alignof", "and", "and_eq", "asm", "auto", "axiom", "bitand", "bitor", - // "bool", "break", "case", "catch", "cdecl", "char", "char16_t", "char32_t", "class", "compl", - // "concept", "concept_map", "const", "const_cast", "constexpr", "continue", "decltype", "default", - // "define", "defined", "delete", "deprecated", "do", "double", "Dynamic cast", "dynamic_cast", - // "elif", "else", "endif", "enum", "error", "explicit", "export", "extern", "false", "final", - // "float", "for", "friend", "goto", "if", "ifdef", "ifndef", "include", "inline", "int", - // "late_check", "line", "long", "mutable", "namespace", "new", "noexcept", "noreturn", - // "not", "not_eq", "nullptr", "operator", "or", "or_eq", "override", "pascal", "pragma", - // "private", "protected", "public", "register", "reinterpret_cast", "requires", "restrict", - // "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", - // "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", - // "typename", "typeof", "undef", "union", "unsigned", "using", "uuidof", "virtual", "void", - // "volatile", "wchar_t", "while", "xor", "xor_eq"].ToList() as! List; + // // c++Builder keywords + // keywords = ["__asm", "__automated", "__cdecl", "__classid", "__classmethod", "__closure", "__declspec", + // "__delphirtti", "__dispid", "__except", "__export", "__fastcall", "__finally", "__import", + // "__inline", "__int16", "__int32", "__int64", "__int8", "__msfastcall", "__msreturn", + // "__pascal", "__property", "__published", "__rtti", "__stdcall", "__thread", "__try", "_asm", + // "_Bool", "_cdecl", "_Complex", "_export", "_fastcall", "_Imaginary", "_import", "_pascal", + // "_stdcall", "alignas", "alignof", "and", "and_eq", "asm", "auto", "axiom", "bitand", "bitor", + // "bool", "break", "case", "catch", "cdecl", "char", "char16_t", "char32_t", "class", "compl", + // "concept", "concept_map", "const", "const_cast", "constexpr", "continue", "decltype", "default", + // "define", "defined", "delete", "deprecated", "do", "double", "Dynamic cast", "dynamic_cast", + // "elif", "else", "endif", "enum", "error", "explicit", "export", "extern", "false", "final", + // "float", "for", "friend", "goto", "if", "ifdef", "ifndef", "include", "inline", "int", + // "late_check", "line", "long", "mutable", "namespace", "new", "noexcept", "noreturn", + // "not", "not_eq", "nullptr", "operator", "or", "or_eq", "override", "pascal", "pragma", + // "private", "protected", "public", "register", "reinterpret_cast", "requires", "restrict", + // "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", + // "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", + // "typename", "typeof", "undef", "union", "unsigned", "using", "uuidof", "virtual", "void", + // "volatile", "wchar_t", "while", "xor", "xor_eq"].ToList() as! List; } public convenience init(dialect: CGCPlusPlusCodeGeneratorDialect) { init() Dialect = dialect - } + } override func generateAll() { // overriden in .h and .cpp @@ -75,7 +71,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { // // Statements // - + // in C-styleCG Base class /* override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) { @@ -122,14 +118,14 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { // handled in base } */ - + override func generateLockingStatement(_ statement: CGLockingStatement) { assert(false, "generateLockingStatement is not supported in C++") } - + override func generateUsingStatement(_ statement: CGUsingStatement) { assert(false, "generateUsingStatement is not supported in C++") - } + } override func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) { assert(false, "generateAutoReleasePoolStatement is not supported in C++") @@ -143,10 +139,10 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } } // __try { - // try {} - // body - // catch {} - // } + // try {} + // body + // catch {} + // } // __finally {} if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 { AppendLine("__try") @@ -223,7 +219,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { generateTypeReference(type) Append(" ") } else { -// Append("id ") +// Append("id ") } generateIdentifier(statement.Name) if let value = statement.Value { @@ -238,7 +234,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { // handled in base } */ - + override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) { // empty } @@ -268,11 +264,11 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { override func generateTypeOfExpression(_ expression: CGTypeOfExpression) { Append("[") generateExpression(expression.Expression, ignoreNullability: true) -// if let typeReferenceExpression = expression.Expression as? CGTypeReferenceExpression { -// generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true) -// } else { -// generateExpression(expression.Expression) -// } +// if let typeReferenceExpression = expression.Expression as? CGTypeReferenceExpression { +// generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true) +// } else { +// generateExpression(expression.Expression) +// } Append(" class]") } @@ -295,7 +291,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } else { // (MyClass *)ptr Append("(") - generateTypeReference(cast.TargetType) + generateTypeReference(cast.TargetType) Append(")") generateExpression(cast.Expression) } @@ -314,7 +310,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) { - Append(CGPropertyDefinition.MAGIC_VALUE_PARAMETER_NAME) + Append(CGPropertyDefinition.MAGIC_VALUE_PARAMETER_NAME) } override func generateAwaitExpression(_ expression: CGAwaitExpression) { @@ -357,7 +353,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { // handled in base } */ - + /* override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { // handled in base @@ -394,12 +390,12 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { if p > 0 { Append(", ") } - + switch param.Modifier { case .Var: Append(" &") case .Out: Append(" &") - default: - } + default: + } generateExpression(param.Value) } } @@ -413,19 +409,19 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { switch param.Modifier { case .Const: self.Append("const ") case .Var: self.Append("/* var */ ") - case .Out: self.Append("/* out */ ") + case .Out: self.Append("/* out */ ") default: } self.generateTypeReference(param.`Type`) switch param.Modifier { case .Var: self.Append(" &") case .Out: self.Append(" &") - default: + default: } self.Append(" ") - self.generateIdentifier(param.Name) + self.generateIdentifier(param.Name) if header { - if let pv = param.DefaultValue, pv != nil { + if let pv = param.DefaultValue, pv != nil { self.Append(" = ") self.generateExpression(pv) } @@ -457,27 +453,27 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } } - + func cppGenerateAddressing(_ expression: CGMemberAccessExpression) { - if (expression.CallSite != nil) { - switch expression.CallSiteKind{ - case .Instance: Append("."); - case .Reference: Append("->"); - case .Static: Append("::"); - case .Unspecified: + if (expression.CallSite != nil) { + switch expression.CallSiteKind{ + case .Instance: Append("."); + case .Reference: Append("->"); + case .Static: Append("::"); + case .Unspecified: if let typeref = expression.CallSite as? CGTypeReferenceExpression { Append("::") } else if let typeref = expression.CallSite as? CGInheritedExpression { Append("::") - } + } else if let typeref = expression.CallSite as? CGSelfExpression { Append(".") - } - else { + } + else { Append(".") } - } + } } } @@ -515,7 +511,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { // int * a = new int[500]; // delete [] a; Append("delete "); - generateExpression(expression.Instance); + generateExpression(expression.Instance); } override func generatePropertyAccessExpression(_ property: CGPropertyAccessExpression) { @@ -560,17 +556,17 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { */ override func generateArrayLiteralExpression(_ array: CGArrayLiteralExpression) { - if isCBuilder() { - if array.ArrayKind == .Dynamic { + if isCBuilder() { + if array.ArrayKind == .Dynamic { var isOpenArray = false - if let ltype = array.ElementType { + if let ltype = array.ElementType { // open array isOpenArray = true; Append("OPENARRAY(") generateTypeReference(ltype) Append(", (") } - else { + else { // array of const Append("ARRAYOFCONST((") } @@ -579,7 +575,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } Append(")") Append(")") - return; + return; } } Append("[") @@ -621,156 +617,156 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { // default handled in base } */ - -// override func generateSetTypeReference(_ setType: CGSetTypeReference) { -// assert(false, "generateSetTypeReference is not supported in C++") -// } -// -// override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference) { -// assert(false, "generateSequenceTypeReference is not supported in C++") -// } - + +// override func generateSetTypeReference(_ setType: CGSetTypeReference) { +// assert(false, "generateSetTypeReference is not supported in C++") +// } +// +// override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference) { +// assert(false, "generateSequenceTypeReference is not supported in C++") +// } + // // Type Definitions // - + override func generateAttribute(_ attribute: CGAttribute) { // no-op, we dont support attribtes in Objective-C } - + override func generateAliasType(_ type: CGTypeAliasDefinition) { } - + override func generateBlockType(_ type: CGBlockTypeDefinition) { - + } - + override func generateEnumType(_ type: CGEnumTypeDefinition) { // overriden in H } - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { // overriden and H } - + override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { AppendLine() } - -// func cppGenerateFields(_ type: CGTypeDefinition) { -// for m in type.Members { -// if let property = m as? CGPropertyDefinition { -// if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil { -// if let type = property.`Type` { -// generateTypeReference(type) -// Append(" ") -// } else { -// Append("id ") -// } -// Append("__p_") -// generateIdentifier(property.Name, escaped: false) -// AppendLine(";") -// } -// } else if let field = m as? CGFieldDefinition { -// if let type = field.`Type` { -// generateTypeReference(type) -// Append(" ") -// } else { -// Append("id ") -// } -// generateIdentifier(field.Name) -// AppendLine(";") -// } -// } -// } - + +// func cppGenerateFields(_ type: CGTypeDefinition) { +// for m in type.Members { +// if let property = m as? CGPropertyDefinition { +// if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil { +// if let type = property.`Type` { +// generateTypeReference(type) +// Append(" ") +// } else { +// Append("id ") +// } +// Append("__p_") +// generateIdentifier(property.Name, escaped: false) +// AppendLine(";") +// } +// } else if let field = m as? CGFieldDefinition { +// if let type = field.`Type` { +// generateTypeReference(type) +// Append(" ") +// } else { +// Append("id ") +// } +// generateIdentifier(field.Name) +// AppendLine(";") +// } +// } +// } + override func generateStructTypeStart(_ type: CGStructTypeDefinition) { // overriden in H } - + override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { // overriden in H - } - + } + override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { // overriden in H } - + override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { // overriden in H - } - + } + override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { // overriden in M and H } - + override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { AppendLine("@end") - } + } // // Type Members // - func cppGenerateCallingConversion(_ callingConvention: CGCallingConventionKind){ - if isCBuilder() { - switch callingConvention { - case .CDecl: Append("__cdecl ") - case .Pascal: Append("__pascal ") - case .FastCall: Append("__msfastcall ") - case .StdCall: Append("__stdcall ") - case .Register: Append("__fastcall ") + func cppGenerateCallingConversion(_ callingConvention: CGCallingConventionKind){ + if isCBuilder() { + switch callingConvention { + case .CDecl: Append("__cdecl ") + case .Pascal: Append("__pascal ") + case .FastCall: Append("__msfastcall ") + case .StdCall: Append("__stdcall ") + case .Register: Append("__fastcall ") default: } } - else if isVC(){ - switch callingConvention { - case .CDecl: Append("__cdecl ") - case .ClrCall: Append("__clrcall ") - case .StdCall: Append("__stdcall ") - case .FastCall: Append("__fastcall ") - case .ThisCall: Append("__thiscall ") - case .VectorCall: Append("__vectorcall ") + else if isVC(){ + switch callingConvention { + case .CDecl: Append("__cdecl ") + case .ClrCall: Append("__clrcall ") + case .StdCall: Append("__stdcall ") + case .FastCall: Append("__fastcall ") + case .ThisCall: Append("__thiscall ") + case .VectorCall: Append("__vectorcall ") default: } } - else if isStandard() { + else if isStandard() { // only cdecl is used be default; } - } + } func cppGenerateMethodDefinitionHeader(_ method: CGMethodLikeMemberDefinition, type: CGTypeDefinition, header: Boolean) { let isCtor = (method as? CGConstructorDefinition) != nil; let isDtor = (method as? CGDestructorDefinition) != nil; let isInterface = (type as? CGInterfaceTypeDefinition) != nil; - let isGlobal = type == CGGlobalTypeDefinition.GlobalType; + let isGlobal = type == CGGlobalTypeDefinition.GlobalType; if header { if method.Static { - if isCBuilder() { + if isCBuilder() { Append("__classmethod ") } - else + else { Append("static ") - } + } } } if header { - if isInterface && isCBuilder(){ + if isInterface && isCBuilder(){ Append("virtual "); } else if !isGlobal { // virtuality isn't supported for globals switch (method.Virtuality) { - case .Virtual: Append("virtual "); - case .Override: Append("virtual "); + case .Virtual: Append("virtual "); + case .Override: Append("virtual "); case .Reintroduce: if isCBuilder() { Append("HIDESBASE "); } default: // ???? } } } - if !isCtor && !isDtor{ + if !isCtor && !isDtor{ // ctor&dtor have no result if let returnType = method.ReturnType { generateTypeReference(returnType) @@ -780,9 +776,9 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { Append(" ") } if let conversion = method.CallingConvention { - cppGenerateCallingConversion(conversion) + cppGenerateCallingConversion(conversion) } - if isCtor { + if isCtor { if !header { if let namespace = currentUnit.Namespace { generateIdentifier(namespace.Name) @@ -806,7 +802,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } Append("~") generateIdentifier(uppercaseFirstLetter(type.Name)); - } else { + } else { if !header { if !(isGlobal && (method.Visibility == .Private)) { if let namespace = currentUnit.Namespace { @@ -814,7 +810,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { Append("::") } } - if !isGlobal { + if !isGlobal { generateIdentifier(type.Name) Append("::") } @@ -824,12 +820,12 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { Append("(") cppGenerateDefinitionParameters(method.Parameters, header: header) Append(")") - if header && isInterface { + if header && isInterface { Append(" = 0") } if !header && isCtor { - if let classtype = type as? CGClassOrStructTypeDefinition { - if classtype.Ancestors.Count > 0 { + if let classtype = type as? CGClassOrStructTypeDefinition { + if classtype.Ancestors.Count > 0 { AppendLine(); incIndent() Append(": ") @@ -847,7 +843,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { helpGenerateCommaSeparatedList(method.Parameters) { p in self.generateIdentifier(p.Name) } -/* for var p = 0; p < method.Parameters.Count; p++ { +/* for var p = 0; p < method.Parameters.Count; p++ { let param = method.Parameters[p] if p > 0 { Append(", ") @@ -861,11 +857,11 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } } } - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { // overriden in H } - + override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { // overriden in H & CPP } @@ -880,8 +876,8 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) { - // use field as is - if let type = field.`Type` { + // use field as is + if let type = field.`Type` { if field.Constant { Append("const ") } @@ -895,14 +891,14 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { AppendLine(";") } else { // without type, generate as define - Append("#define "); + Append("#define "); generateIdentifier(field.Name) if let value = field.Initializer { Append(" ") generateExpression(value) } AppendLine(); - } + } } override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { @@ -920,7 +916,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { // // Type References // - + override func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNamespace: Boolean, ignoreNullability: Boolean) { if ignoreNamespace { generateIdentifier(type.Name) @@ -936,46 +932,46 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { Append("*") } } - + override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { switch (type.Kind) { - case .Int: Append("int") //+ - case .UInt: Append("unsigned int") //+ - case .Int8: Append("char") //+ - case .UInt8: Append("unsigned char") //+ - case .Int16: Append("short int") //+ - case .UInt16: Append("unsigned short int") //+ - case .Int32: Append("int") //+ - case .UInt32: Append("unsigned int") //+ - case .Int64: if isCBuilder() {Append("__int64")} else {Append("long int")} //+ - case .UInt64: Append("unsigned long int") //+ - case .IntPtr: Append("IntPtr") //??????? - case .UIntPtr: Append("UIntPtr") //??????? - case .Single: Append("float") //+ - case .Double: Append("double") //+ - case .Boolean: Append("bool") //+ - case .String: Append("string") //+ - case .AnsiChar: Append("char") //+ - case .UTF16Char: Append("wchar_t") //+ - case .UTF32Char: Append("wchar_t") //+ - case .Dynamic: Append("{DYNAMIC}") //?????? - case .InstanceType: Append("{INSTANCETYPE}") //?????? - case .Void: Append("void") //+ - case .Object: Append("{OBJECT}") //?????? - case .Class: Append("{CLASS}") //?????? - } + case .Int: Append("int") //+ + case .UInt: Append("unsigned int") //+ + case .Int8: Append("char") //+ + case .UInt8: Append("unsigned char") //+ + case .Int16: Append("short int") //+ + case .UInt16: Append("unsigned short int") //+ + case .Int32: Append("int") //+ + case .UInt32: Append("unsigned int") //+ + case .Int64: if isCBuilder() {Append("__int64")} else {Append("long int")} //+ + case .UInt64: Append("unsigned long int") //+ + case .IntPtr: Append("IntPtr") //??????? + case .UIntPtr: Append("UIntPtr") //??????? + case .Single: Append("float") //+ + case .Double: Append("double") //+ + case .Boolean: Append("bool") //+ + case .String: Append("string") //+ + case .AnsiChar: Append("char") //+ + case .UTF16Char: Append("wchar_t") //+ + case .UTF32Char: Append("wchar_t") //+ + case .Dynamic: Append("{DYNAMIC}") //?????? + case .InstanceType: Append("{INSTANCETYPE}") //?????? + case .Void: Append("void") //+ + case .Object: Append("{OBJECT}") //?????? + case .Class: Append("{CLASS}") //?????? + } } override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { - + let block = type.Block - + if let returnType = block.ReturnType { generateTypeReference(returnType) } else { Append("void") - } - Append("(^)(") + } + Append("(^)(") for p in 0 ..< block.Parameters.Count { if p > 0 { Append(", ") @@ -988,20 +984,20 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { } Append(")") } - - override func generateConstantTypeReference(_ type: CGConstantTypeReference, ignoreNullability: Boolean = false) { + + override func generateConstantTypeReference(_ type: CGConstantTypeReference, ignoreNullability: Boolean = false) { generateTypeReference(type.`Type`) Append(" const") } -// override func generateKindOfTypeReference(_ type: CGKindOfTypeReference) { -// Append("__kindof ") -// generateTypeReference(type.`Type`) -// } - +// override func generateKindOfTypeReference(_ type: CGKindOfTypeReference) { +// Append("__kindof ") +// generateTypeReference(type.`Type`) +// } + override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) { - if isCBuilder() { - if type.ArrayKind == .Dynamic { + if isCBuilder() { + if type.ArrayKind == .Dynamic { Append("DynamicArray<") generateTypeReference(type.`Type`) Append(">") @@ -1017,11 +1013,11 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { Append("[]") } } - + override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { } - + func generatePragma(_ pragma: String){ Append("#pragma "); AppendLine(pragma); @@ -1032,7 +1028,7 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { case .Unspecified: break case .Unit: break case .Assembly: break - case .Public: Append("public ") + case .Public: Append("public ") } } @@ -1040,6 +1036,6 @@ public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator { generateTypeReference(type.`Type`) if type.Reference { Append("&") - } else { - Append("*") } } -} + } else { + Append("*") } } +} \ No newline at end of file diff --git a/CGCPlusPlusHCodeGenerator.swift b/CGCPlusPlusHCodeGenerator.swift index 8135823..e4f7072 100644 --- a/CGCPlusPlusHCodeGenerator.swift +++ b/CGCPlusPlusHCodeGenerator.swift @@ -1,7 +1,4 @@ -import Sugar -import Sugar.Collections - -public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { +public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { public override var defaultFileExtension: String { return "h" } @@ -28,14 +25,14 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { var lastGlobal: CGGlobalDefinition? = nil for g in currentUnit.Globals { var visibility: CGMemberVisibilityKind = .Unspecified; - if let method = g as? CGGlobalFunctionDefinition { + if let method = g as? CGGlobalFunctionDefinition { visibility = method.Function.Visibility; } - if let variable = g as? CGGlobalVariableDefinition { + if let variable = g as? CGGlobalVariableDefinition { visibility = variable.Variable.Visibility; } // skip .Unit & .Private visibility - they will be put into .cpp - if !((visibility == .Unit)||(visibility == .Private)){ + if !((visibility == .Unit)||(visibility == .Private)){ if let lastGlobal = lastGlobal, globalNeedsSpace(g, afterGlobal: lastGlobal) { AppendLine() } @@ -75,12 +72,12 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { if isCBuilder() { generatePragma("delphiheader begin"); generatePragma("option push"); - generatePragma("option -w- // All warnings off"); - generatePragma("option -Vx // Zero-length empty class member functions"); + generatePragma("option -w- // All warnings off"); + generatePragma("option -Vx // Zero-length empty class member functions"); generatePragma("pack(push,8)"); } } - + override func generateFooter(){ var lnamespace = currentUnit.FileName+"H"; if isCBuilder() { @@ -118,7 +115,7 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { } } } - + override func generateImport(_ imp: CGImport) { if imp.StaticClass != nil { @@ -131,7 +128,7 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { // // Types // - + override func generateAliasType(_ type: CGTypeAliasDefinition) { Append("typedef ") generateTypeReference(type.ActualType) @@ -139,18 +136,18 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { generateIdentifier(type.Name) AppendLine(";") } - + override func generateBlockType(_ type: CGBlockTypeDefinition) { - + } - + override func generateEnumType(_ type: CGEnumTypeDefinition) { //#pragma option push -b- //enum TSex { - // TSex_sxMale, - // TSex_sxFemale - // }; + // TSex_sxMale, + // TSex_sxFemale + // }; //#pragma option pop if isCBuilder() { @@ -177,11 +174,11 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { generatePragma("option pop"); } } - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { -// if isCBuilder() { -// AppendLine("class DELPHICLASS \(type.Name);"); -// } +// if isCBuilder() { +// AppendLine("class DELPHICLASS \(type.Name);"); +// } Append("class ") generateIdentifier(type.Name) cppGenerateAncestorList(type) @@ -189,33 +186,33 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { AppendLine("{") incIndent(); if isCBuilder() { - if type.Ancestors.Count > 0 { + if type.Ancestors.Count > 0 { for a in 0 ..< type.Ancestors.Count { if let ancestor = type.Ancestors[a] { Append("typedef "); generateTypeReference(ancestor, ignoreNullability: true); - AppendLine(" inherited;") + AppendLine(" inherited;") } } - + } } -// cppGenerateFields(type) +// cppGenerateFields(type) AppendLine() - if isCBuilder() { + if isCBuilder() { // generate empty "__published:" decIndent(); cppHGenerateMemberVisibilityPrefix(CGMemberVisibilityKind.Published); incIndent(); } } - + override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { decIndent() AppendLine() AppendLine("};") } - + override func generateStructTypeStart(_ type: CGStructTypeDefinition) { Append("struct "); generateIdentifier(type.Name) @@ -224,17 +221,17 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { AppendLine("{") incIndent(); } - + override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { decIndent(); AppendLine() AppendLine("}") - } - + } + override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { -// Append("__interface ") -// generateIdentifier(type.Name) -// AppendLine(";"); +// Append("__interface ") +// generateIdentifier(type.Name) +// AppendLine(";"); Append("__interface ") if isCBuilder() { if let k = type.InterfaceGuid { @@ -247,17 +244,17 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { AppendLine("{") incIndent() } - - override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { + + override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { decIndent() AppendLine() AppendLine("};") - } + } // // Type Members // - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { cppGenerateMethodDefinitionHeader(method, type: type, header: true) AppendLine(";") @@ -272,42 +269,42 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { cppGenerateMethodDefinitionHeader(dtor, type: type, header: true) AppendLine(";") } - + override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { - + if property.Virtuality == CGMemberVirtualityKind.Override || property.Virtuality == CGMemberVirtualityKind.Final { Append("// overriden ") // we don't need to re-emit overriden properties in header? } - + Append("__property ") - - // Append("(") - // if property.Atomic { - // Append("atomic") - // } else { - // Append("nonatomic") - // } - // if let type = property.`Type` { - // if type.IsClassType { - // switch type.StorageModifier { - // case .Strong: Append(", strong") - // case .Weak: Append(", weak") - // case .Unretained: Append(", unsafe_unretained") - // } - // } else { - // //todo? - // } - // } - // if property.ReadOnly { - // Append(", readonly") - // } - // Append(") ") - + + // Append("(") + // if property.Atomic { + // Append("atomic") + // } else { + // Append("nonatomic") + // } + // if let type = property.`Type` { + // if type.IsClassType { + // switch type.StorageModifier { + // case .Strong: Append(", strong") + // case .Weak: Append(", weak") + // case .Unretained: Append(", unsafe_unretained") + // } + // } else { + // //todo? + // } + // } + // if property.ReadOnly { + // Append(", readonly") + // } + // Append(") ") + if let type = property.`Type` { generateTypeReference(type/*, ignoreNullability:true*/) Append(" ") } else { - // Append("id ") + // Append("id ") } generateIdentifier(property.Name) if let parameters = property.Parameters, parameters.Count > 0 { @@ -330,11 +327,11 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { generateExpression(getExpression) } } - + if let setStatements = property.SetStatements, let setterMethod = property.SetterMethodDefinition() { if readerExist { Append(", ") - } + } Append("write=") if !definitionOnly { generateIdentifier(setterMethod.Name) @@ -342,7 +339,7 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { } else if let setExpression = property.SetExpression { if readerExist { Append(", ") - } + } Append("write=") if !definitionOnly { generateExpression(setExpression) @@ -360,7 +357,7 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { decIndent(); cppHGenerateMemberVisibilityPrefix(mVisibility) incIndent(); - } + } } } generateTypeMember(member, type: type); @@ -382,20 +379,20 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { if let type = type as? CGInterfaceTypeDefinition { decIndent(); cppHGenerateMemberVisibilityPrefix(CGMemberVisibilityKind.Public); - incIndent(); + incIndent(); super.generateTypeMembers(type); } else { -// var lastMember: CGMemberDefinition? = nil -// var lastVisibility: CGMemberVisibilityKind = CGMemberVisibilityKind.Unspecified; -// for m in type.Members { -// if let lastMember = lastMember, memberNeedsSpace(m, afterMember: lastMember) && !definitionOnly { -// AppendLine() -// } -// cppHGenerateTypeMember(m, type: type, lastVisibility: lastVisibility); -// lastMember = m; -// lastVisibility = m.Visibility; -// } +// var lastMember: CGMemberDefinition? = nil +// var lastVisibility: CGMemberVisibilityKind = CGMemberVisibilityKind.Unspecified; +// for m in type.Members { +// if let lastMember = lastMember, memberNeedsSpace(m, afterMember: lastMember) && !definitionOnly { +// AppendLine() +// } +// cppHGenerateTypeMember(m, type: type, lastVisibility: lastVisibility); +// lastMember = m; +// lastVisibility = m.Visibility; +// } generateTypeMembers(type, forVisibility: CGMemberVisibilityKind.Unspecified) generateTypeMembers(type, forVisibility: CGMemberVisibilityKind.Private) generateTypeMembers(type, forVisibility: CGMemberVisibilityKind.Unit) @@ -413,14 +410,14 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { func cppGeneratePropertyAccessorDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { if !definitionOnly { if let getStatements = property.GetStatements, let getterMethod = property.GetterMethodDefinition() { - if isCBuilder() { - getterMethod.CallingConvention = .Register + if isCBuilder() { + getterMethod.CallingConvention = .Register } getterMethod.Visibility = .Private generateMethodDefinition(getterMethod, type: type) } if let setStatements = property.SetStatements, let setterMethod = property.SetterMethodDefinition() { - if isCBuilder() { + if isCBuilder() { setterMethod.CallingConvention = .Register } setterMethod.Visibility = .Private @@ -442,7 +439,7 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { if first { decIndent() if visibility != CGMemberVisibilityKind.Unspecified { - cppHGenerateMemberVisibilityPrefix(visibility) + cppHGenerateMemberVisibilityPrefix(visibility) } first = false incIndent() @@ -451,8 +448,8 @@ public class CGCPlusPlusHCodeGenerator: CGCPlusPlusCodeGenerator { } } else { generateTypeMember(m, type: type) - } + } } } -} +} \ No newline at end of file diff --git a/CGCSharpCodeGenerator.swift b/CGCSharpCodeGenerator.swift index 6b5fe8d..47816f5 100644 --- a/CGCSharpCodeGenerator.swift +++ b/CGCSharpCodeGenerator.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -public enum CGCSharpCodeGeneratorDialect { +public enum CGCSharpCodeGeneratorDialect { case Standard case Hydrogene } @@ -664,9 +660,9 @@ public class CGCSharpCodeGenerator : CGCStyleCodeGenerator { override func cStyleEscapeSequenceForCharacter(_ ch: Char) -> String { if ch <= 0xffff { - return "\\u\(Sugar.Convert.ToHexString(Integer(ch), 4))" + return "\\u\(Convert.ToHexString(Integer(ch), 4))" } else { - return "\\U\(Sugar.Convert.ToHexString(Integer(ch), 8))" + return "\\U\(Convert.ToHexString(Integer(ch), 8))" } } diff --git a/CGCStyleCodeGenerator.swift b/CGCStyleCodeGenerator.swift index 4bb4da5..cdb845e 100644 --- a/CGCStyleCodeGenerator.swift +++ b/CGCStyleCodeGenerator.swift @@ -1,7 +1,4 @@ -import Sugar -import Sugar.Collections - -// +// // Abstract base implementation for all C-style languages (C#, Obj-C, Swift, Java, C++) // @@ -16,7 +13,7 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { var comment = comment.Replace("*/", "* /") Append("/* \(comment) */") } - + override func generateConditionStart(_ condition: CGConditionalDefine) { if let name = condition.Expression as? CGNamedIdentifierExpression { Append("#ifdef ") @@ -32,14 +29,14 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { generateExpression(condition.Expression) } } -// generateConditionalDefine(condition) +// generateConditionalDefine(condition) AppendLine() } - + override func generateConditionElse() { AppendLine("#else") } - + override func generateConditionEnd(_ condition: CGConditionalDefine) { AppendLine("#endif") } @@ -73,7 +70,7 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { Append(" = ") generateExpression(statement.StartValue) Append("; ") - + generateIdentifier(statement.LoopVariableName) if statement.Direction == CGLoopDirectionKind.Forward { Append(" <= ") @@ -161,18 +158,18 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { Append(" = ") generateExpression(statement.Value) generateStatementTerminator() - } - + } + // // Expressions // - + override func generateSizeOfExpression(_ expression: CGSizeOfExpression) { Append("sizeof(") generateExpression(expression.Expression) Append(")") } - + override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) { Append("*(") generateExpression(expression.PointerExpression) @@ -188,7 +185,7 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { case .ForceUnwrapNullable: // no-op } } - + override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { switch (`operator`) { case .Concat: fallthrough @@ -212,7 +209,7 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { case .BitwiseAnd: Append("&") case .BitwiseOr: Append("|") case .BitwiseXor: Append("^") - //case .Implies: + //case .Implies: case .Is: Append("is") //case .IsNot: //case .In: @@ -256,20 +253,20 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { case "\0".."\31": result.Append("\\"+Integer(ch).ToString()) // Cannot use the binary operator ".." case "\u{0080}".."\u{ffffffff}": result.Append("\\u{"+Sugar.Cryptography.Utils.ToHexString(Integer(ch), 4)) // Cannot use the binary operator ".." */ - default: + default: if ch < 32 || ch > 0x7f { result.Append(cStyleEscapeSequenceForCharacter(ch)) } else { result.Append(ch) } - + } } return result.ToString() } - + internal func cStyleEscapeSequenceForCharacter(_ ch: Char) -> String { - return "\\U"+Sugar.Convert.ToHexString(Integer(ch), 8) // plain C: always use 8 hex digits with "\U" + return "\\U"+Convert.ToHexString(Integer(ch), 8) // plain C: always use 8 hex digits with "\U" } override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) { @@ -279,7 +276,7 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) { Append("'\(cStyleEscapeCharactersInStringLiteral(expression.Value.ToString()))'") } - + private func cStyleAppendNumberKind(_ numberKind: CGNumberKind?) { if let numberKind = numberKind { switch numberKind { @@ -314,5 +311,5 @@ public __abstract class CGCStyleCodeGenerator : CGCodeGenerator { override func generatePointerTypeReference(_ type: CGPointerTypeReference) { generateTypeReference(type.`Type`) Append("*") - } -} + } +} \ No newline at end of file diff --git a/CGCodeGenerator.swift b/CGCodeGenerator.swift index a72a9fc..123b64f 100644 --- a/CGCodeGenerator.swift +++ b/CGCodeGenerator.swift @@ -1,7 +1,4 @@ -import Sugar -import Sugar.Collections - -public __abstract class CGCodeGenerator { +public __abstract class CGCodeGenerator { internal var currentUnit: CGCodeUnit! internal var tabSize = 2 diff --git a/CGDelphiCodeGenerator.swift b/CGDelphiCodeGenerator.swift index 625dfba..ea81a80 100644 --- a/CGDelphiCodeGenerator.swift +++ b/CGDelphiCodeGenerator.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -public class CGDelphiCodeGenerator : CGPascalCodeGenerator { +public class CGDelphiCodeGenerator : CGPascalCodeGenerator { public init() { super.init() @@ -21,26 +17,26 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { // Delphi Seattle + FPC reserved list // http://docwiki.embarcadero.com/RADStudio/Seattle/en/Fundamental_Syntactic_Elements#Reserved_Words // http://www.freepascal.org/docs-html/ref/refse3.html - keywords = ["absolute", "abstract", "alias", "and", "array", "as", "asm", "assembler", "at", "automated", "begin", - "bitpacked", "break", "case", "cdecl", "class", "const", "constructor", "continue", "cppdecl", "cvar", "default", + keywords = ["absolute", "abstract", "alias", "and", "array", "as", "asm", "assembler", "at", "automated", "begin", + "bitpacked", "break", "case", "cdecl", "class", "const", "constructor", "continue", "cppdecl", "cvar", "default", "deprecated", "destructor", "dispinterface", "dispose", "div", "do", "downto", "dynamic", "else", "end", "enumerator", - "except", "exit", "experimental", "export", "exports", "external", "false", "far", "far16", "file", "finalization", - "finally", "for", "forward", "function", "generic", "goto", "helper", "if", "implementation", "implements", "in", - "index", "inherited", "initialization", "inline", "interface", "interrupt", "iochecks", "is", "label", "library", - "local", "message", "mod", "name", "near", "new", "nil", "nodefault", "noreturn", "nostackframe", "not", "object", - "of", "oldfpccall", "on", "operator", "or", "otherwise", "out", "overload", "override", "packed", "pascal", "platform", - "private", "procedure", "program", "property", "protected", "public", "published", "raise", "read", "record", "register", - "reintroduce", "repeat", "resourcestring", "result", "safecall", "saveregisters", "self", "set", "shl", "shr", "softfloat", - "specialize", "static", "stdcall", "stored", "strict", "string", "then", "threadvar", "to", "true", "try", "type", "unaligned", + "except", "exit", "experimental", "export", "exports", "external", "false", "far", "far16", "file", "finalization", + "finally", "for", "forward", "function", "generic", "goto", "helper", "if", "implementation", "implements", "in", + "index", "inherited", "initialization", "inline", "interface", "interrupt", "iochecks", "is", "label", "library", + "local", "message", "mod", "name", "near", "new", "nil", "nodefault", "noreturn", "nostackframe", "not", "object", + "of", "oldfpccall", "on", "operator", "or", "otherwise", "out", "overload", "override", "packed", "pascal", "platform", + "private", "procedure", "program", "property", "protected", "public", "published", "raise", "read", "record", "register", + "reintroduce", "repeat", "resourcestring", "result", "safecall", "saveregisters", "self", "set", "shl", "shr", "softfloat", + "specialize", "static", "stdcall", "stored", "strict", "string", "then", "threadvar", "to", "true", "try", "type", "unaligned", "unimplemented", "unit", "until", "uses", "var", "varargs", "virtual", "while", "with", "write", "xor"].ToList() as! List } - + public var Version: Integer = 7 public convenience init(version: Integer) { init() Version = version - } + } override func escapeIdentifier(_ name: String) -> String { if Version > 9 { @@ -63,24 +59,24 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { AppendLine() super.generateHeader() } - + internal func generateForwards(_ Types : List) { if Types.Count > 0 { AppendLine("{ Forward declarations }") var t = List() - t.AddRange(Types) + t.Add(Types) if AlphaSortImplementationMembers { t.Sort({return $0.Name.CompareTo/*IgnoreCase*/($1.Name)}) } for type in t { if let type = type as? CGInterfaceTypeDefinition { - AppendLine(type.Name + " = interface;") + AppendLine(type.Name + " = interface;") } } - + for type in t { if let type = type as? CGClassTypeDefinition { - AppendLine(type.Name + " = class;") + AppendLine(type.Name + " = class;") } } AppendLine() @@ -136,15 +132,15 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { } override func pascalGenerateCallingConversion(_ callingConvention: CGCallingConventionKind){ - switch callingConvention { - case .Register: break //default case - case .Pascal: Append(" pascal;") //backward compatibility + switch callingConvention { + case .Register: break //default case + case .Pascal: Append(" pascal;") //backward compatibility case .CDecl: Append(" cdecl;") case .SafeCall: Append(" safecall;") case .StdCall: Append(" stdcall;") default: } - } + } override func generateEnumValueAccessExpression(_ expression: CGEnumValueAccessExpression) { // don't prefix with typename in Delphi (but do in base Pascal/Oxygene) @@ -154,7 +150,7 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { // // Type Definitions // - + override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { generateIdentifier(type.Name) pascalGenerateGenericParameters(type.GenericParameters) @@ -168,7 +164,7 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { AppendLine() incIndent() } - + override func generateAll() { if !definitionOnly { generateHeader() @@ -184,10 +180,10 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { AppendLine("implementation") AppendLine() delphiGenerateImplementationDirectives() - pascalGenerateImports(currentUnit.ImplementationImports) + pascalGenerateImports(currentUnit.ImplementationImports) delphiGenerateGlobalImplementations() delphiGenerateImplementationTypeDefinition() - pascalGenerateTypeImplementations() + pascalGenerateTypeImplementations() generateFooter() } } @@ -201,7 +197,7 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { } } - var needCR: Boolean = false; + var needCR: Boolean = false; final func delphiGenerateGlobalImplementations() { // step1: generate global consts and vars needCR = false; @@ -214,12 +210,12 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { } else if let global = g as? CGGlobalFunctionDefinition { // will be processed at step2 - } + } else { assert(false, "unsupported global found: \(typeOf(g).ToString())") - } + } } - if needCR { AppendLine();} + if needCR { AppendLine();} // step2: generate global methods for g in currentUnit.Globals { if let global = g as? CGGlobalVariableDefinition { @@ -227,11 +223,11 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { } else if let global = g as? CGGlobalFunctionDefinition { pascalGenerateMethodImplementation(global.Function, type: CGGlobalTypeDefinition.GlobalType) - } + } else { assert(false, "unsupported global found: \(typeOf(g).ToString())") - } - } + } + } } final func delphiGenerateGlobalInterfaceVariables() { @@ -246,10 +242,10 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { } else if let global = g as? CGGlobalFunctionDefinition { // will be processed in delphiGenerateGlobalInterfaceMethods - } + } else { assert(false, "unsupported global found: \(typeOf(g).ToString())") - } + } } } @@ -263,12 +259,12 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { if global.Function.Visibility != CGMemberVisibilityKind.Private { generateTypeMember(global.Function, type: CGGlobalTypeDefinition.GlobalType) } - } + } else { assert(false, "unsupported global found: \(typeOf(g).ToString())") - } + } } - + } @@ -435,7 +431,7 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { Append("^") generateTypeReference(type.`Type`) } - + // // Statements // @@ -455,10 +451,10 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { generateExpression(condition.Expression) } } -// generateConditionalDefine(condition) +// generateConditionalDefine(condition) AppendLine("}") } - + override func generateConditionEnd(_ condition: CGConditionalDefine) { if let name = condition.Expression as? CGNamedIdentifierExpression { AppendLine("{$ENDIF}") @@ -474,42 +470,42 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { } -// override func generateIfElseStatement(_ statement: CGIfThenElseStatement) { -// Append("if ") -// generateExpression(statement.Condition) -// Append(" then") -// var b = true; -// if let statement1 = statement.IfStatement as? CGBeginEndBlockStatement { b = false } -// if let elseStatement1 = statement.ElseStatement { b = false; } -// if b { -// /*generate code like -// if Result then -// System.Inc(fCurrentIndex) -// instead of -// if Result then begin -// System.Inc(fCurrentIndex) -// end; -// works only if else statement isn't used -// otherwise need to add global variable and handle it in "generateStatementTerminator" -// */ -// generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.IfStatement) -// } else { -// AppendLine(" begin") -// incIndent() -// generateStatementSkippingOuterBeginEndBlock(statement.IfStatement) -// decIndent() -// Append("end") -// if let elseStatement = statement.ElseStatement { -// AppendLine() -// AppendLine("else begin") -// incIndent() -// generateStatementSkippingOuterBeginEndBlock(elseStatement) -// decIndent() -// Append("end") -// } -// generateStatementTerminator() -// } -// } +// override func generateIfElseStatement(_ statement: CGIfThenElseStatement) { +// Append("if ") +// generateExpression(statement.Condition) +// Append(" then") +// var b = true; +// if let statement1 = statement.IfStatement as? CGBeginEndBlockStatement { b = false } +// if let elseStatement1 = statement.ElseStatement { b = false; } +// if b { +// /*generate code like +// if Result then +// System.Inc(fCurrentIndex) +// instead of +// if Result then begin +// System.Inc(fCurrentIndex) +// end; +// works only if else statement isn't used +// otherwise need to add global variable and handle it in "generateStatementTerminator" +// */ +// generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.IfStatement) +// } else { +// AppendLine(" begin") +// incIndent() +// generateStatementSkippingOuterBeginEndBlock(statement.IfStatement) +// decIndent() +// Append("end") +// if let elseStatement = statement.ElseStatement { +// AppendLine() +// AppendLine("else begin") +// incIndent() +// generateStatementSkippingOuterBeginEndBlock(elseStatement) +// decIndent() +// Append("end") +// } +// generateStatementTerminator() +// } +// } override func generateSwitchStatement(_ statement: CGSwitchStatement) { Append("case ") @@ -522,7 +518,7 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { } Append(": ") var b = false; -// if (c.Statements.Count == 1) && !(c.Statements[0] is CGBeginEndBlockStatement) { b = true} +// if (c.Statements.Count == 1) && !(c.Statements[0] is CGBeginEndBlockStatement) { b = true} if b { /*optimization: generate code like case x of @@ -590,7 +586,7 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { generateTypeReference(type) Append(" do ") var b1 = false; -// if (b.Statements.Count == 1) && !(b.Statements[0] is CGBeginEndBlockStatement) { b1 = true} +// if (b.Statements.Count == 1) && !(b.Statements[0] is CGBeginEndBlockStatement) { b1 = true} if b1 { //optimization AppendLine() @@ -654,4 +650,4 @@ public class CGDelphiCodeGenerator : CGPascalCodeGenerator { super.generateCharacterLiteralExpression(expression); } } -} +} \ No newline at end of file diff --git a/CGJavaCodeGenerator.swift b/CGJavaCodeGenerator.swift index aecff25..29a90ae 100644 --- a/CGJavaCodeGenerator.swift +++ b/CGJavaCodeGenerator.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -public enum CGJavaCodeGeneratorDialect { +public enum CGJavaCodeGeneratorDialect { case Standard case Iodine } @@ -24,7 +20,7 @@ public class CGJavaCodeGenerator : CGCStyleCodeGenerator { public convenience init(dialect: CGJavaCodeGeneratorDialect) { init() Dialect = dialect - } + } public override var defaultFileExtension: String { return "java" } @@ -285,7 +281,7 @@ public class CGJavaCodeGenerator : CGCStyleCodeGenerator { } */ - override func generateTypeOfExpression(_ expression: CGTypeOfExpression) { + override func generateTypeOfExpression(_ expression: CGTypeOfExpression) { generateExpression(expression.Expression) Append(".class") } @@ -745,7 +741,7 @@ public class CGJavaCodeGenerator : CGCStyleCodeGenerator { if method.Virtuality == CGMemberVirtualityKind.Override { generateAttribute(CGAttribute("Override".AsTypeReference())); } - + javaGenerateMemberTypeVisibilityPrefix(method.Visibility) javaGenerateStaticPrefix(method.Static && !type.Static) if method.External { @@ -764,7 +760,7 @@ public class CGJavaCodeGenerator : CGCStyleCodeGenerator { Append("(") javaGenerateDefinitionParameters(method.Parameters) Append(")") - + if let `throws` = method.ThrownExceptions, `throws`.Count > 0 { Append(" throws ") helpGenerateCommaSeparatedList(`throws`) { t in @@ -857,7 +853,7 @@ public class CGJavaCodeGenerator : CGCStyleCodeGenerator { generateIdentifier(property.Name) } AppendLine(";") - + /*if let params = property.Parameters, params.Count > 0 { Append("[") @@ -1037,5 +1033,4 @@ public class CGJavaCodeGenerator : CGCStyleCodeGenerator { override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { } -} - +} \ No newline at end of file diff --git a/CGJavaScriptCodeGenerator.swift b/CGJavaScriptCodeGenerator.swift index 0807b11..9bf7662 100644 --- a/CGJavaScriptCodeGenerator.swift +++ b/CGJavaScriptCodeGenerator.swift @@ -1,8 +1,5 @@ -import Sugar -import Sugar.Collections - -public class CGJavaScriptCodeGenerator : CGCStyleCodeGenerator { +public class CGJavaScriptCodeGenerator : CGCStyleCodeGenerator { public override var defaultFileExtension: String { return "js" } -} +} \ No newline at end of file diff --git a/CGObjectiveCCodeGenerator.swift b/CGObjectiveCCodeGenerator.swift index a2e19a2..ee8165c 100644 --- a/CGObjectiveCCodeGenerator.swift +++ b/CGObjectiveCCodeGenerator.swift @@ -1,24 +1,20 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -// +// // Abstract base implementation for Objective-C. Inherited by specific .m and .h Generators // public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { public init() { - keywords = ["__nonnull", "__null_unspecified", "__nullable", "__strong", "__unsafe_unretained", "__weak", - "id", "in", "self", "super", "auto", "break", "case", "char", "const", "continue", "do", "double", "else", "enum", "extern", - "float", "for", "goto", "if", "return", "int", "long", "register", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", + keywords = ["__nonnull", "__null_unspecified", "__nullable", "__strong", "__unsafe_unretained", "__weak", + "id", "in", "self", "super", "auto", "break", "case", "char", "const", "continue", "do", "double", "else", "enum", "extern", + "float", "for", "goto", "if", "return", "int", "long", "register", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "colatile", "while"].ToList() as! List } // // Statements // - + // in C-styleCG Base class /* override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) { @@ -182,7 +178,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { // handled in base } */ - + override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) { Append("self = [") if let callSite = statement.CallSite { @@ -262,7 +258,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { } override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) { - Append(CGPropertyDefinition.MAGIC_VALUE_PARAMETER_NAME) + Append(CGPropertyDefinition.MAGIC_VALUE_PARAMETER_NAME) } override func generateAwaitExpression(_ expression: CGAwaitExpression) { @@ -300,7 +296,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { // handled in base } */ - + /* override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { // handled in base @@ -334,7 +330,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { func objcGenerateCallParameters(_ parameters: List, skipFirstName: Boolean = false) { for p in 0 ..< parameters.Count { let param = parameters[p] - + if param.EllipsisParameter { if p > 0 { Append(", ") @@ -347,7 +343,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { } if let name = param.Name, p > 0 || !skipFirstName { generateIdentifier(name) - } + } Append(":") } generateExpression(param.Value) @@ -357,10 +353,10 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { func objcGenerateFunctionCallParameters(_ parameters: List) { for p in 0 ..< parameters.Count { let param = parameters[p] - + if p > 0 { Append(", ") - } + } generateExpression(param.Value) } } @@ -383,7 +379,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { switch param.Modifier { case .Var: Append("*") case .Out: Append("*") - default: + default: } Append(")") generateIdentifier(param.Name) @@ -531,44 +527,44 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { // default handled in base } */ - + override func generateSetTypeReference(_ setType: CGSetTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateSetTypeReference is not supported in Objective-C") } - + override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateSequenceTypeReference is not supported in Objective-C") } - + // // Type Definitions // - + override func generateAttribute(_ attribute: CGAttribute) { // no-op, we dont support attribtes in Objective-C } - + override func generateAliasType(_ type: CGTypeAliasDefinition) { } - + override func generateBlockType(_ block: CGBlockTypeDefinition) { - + } - + override func generateEnumType(_ type: CGEnumTypeDefinition) { // overriden in H } - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { // overriden in M and H } - + override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { AppendLine() AppendLine("@end") } - + func objcGenerateFields(_ type: CGTypeDefinition) { var hasFields = false for m in type.Members { @@ -616,42 +612,42 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { AppendLine("}") } } - + override func generateStructTypeStart(_ type: CGStructTypeDefinition) { // overriden in H } - + override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { // overriden in H - } - + } + override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { // overriden in H } - + override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { // overriden in H - } - + } + override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { // overriden in M and H } - + override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { AppendLine("@end") - } + } // // Type Members // - + func generateMethodDefinitionHeader(_ method: CGMethodLikeMemberDefinition, type: CGTypeDefinition) { if method.Static { Append("+ ") } else { Append("- ") } - + if let ctor = method as? CGConstructorDefinition { Append("(instancetype)init") generateIdentifier(uppercaseFirstLetter(ctor.Name)) @@ -667,11 +663,11 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { } objcGenerateDefinitionParameters(method.Parameters) } - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { // overriden in H } - + override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { // overriden in H } @@ -703,7 +699,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { // // Type References // - + internal func objcTypeRefereneIsPointer(_ type: CGTypeReference) -> Boolean { if let type = type as? CGNamedTypeReference { return type.IsClassType @@ -719,7 +715,7 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { Append(" *") } } - + override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { switch (type.Kind) { case .Int: Append("NSInteger") @@ -746,19 +742,19 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { case .Void: Append("void") case .Object: if ignoreNullability { Append("NSObject") } else { Append("NSObject *") } case .Class: Append("Class") - } + } } override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { - + let block = type.Block - + if let returnType = block.ReturnType { generateTypeReference(returnType) } else { Append("void") - } - Append("(^)(") + } + Append("(^)(") for p in 0 ..< block.Parameters.Count { if p > 0 { Append(", ") @@ -771,16 +767,16 @@ public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { } Append(")") } - + override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { Append("__kindof ") generateTypeReference(type.`Type`) } - + override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) { } - + override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { } diff --git a/CGObjectiveCHCodeGenerator.swift b/CGObjectiveCHCodeGenerator.swift index 0630e28..90fbdd2 100644 --- a/CGObjectiveCHCodeGenerator.swift +++ b/CGObjectiveCHCodeGenerator.swift @@ -1,7 +1,4 @@ -import Sugar -import Sugar.Collections - -public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { +public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { public override var defaultFileExtension: String { return "h" } @@ -18,7 +15,7 @@ public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { } } } - + override func generateImport(_ imp: CGImport) { AppendLine("#import <\(imp.Name)/\(imp.Name).h>") } @@ -30,15 +27,15 @@ public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { // // Types // - + override func generateAliasType(_ type: CGTypeAliasDefinition) { } - + override func generateBlockType(_ type: CGBlockTypeDefinition) { - + } - + override func generateEnumType(_ type: CGEnumTypeDefinition) { Append("typedef NS_ENUM(") if let baseType = type.BaseType { @@ -64,7 +61,7 @@ public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { decIndent() AppendLine("};") } - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { Append("@interface ") generateIdentifier(type.Name) @@ -74,20 +71,20 @@ public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { objcGenerateFields(type) AppendLine() } - + /*override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { decIndent() AppendLine(@"end") }*/ - + override func generateStructTypeStart(_ type: CGStructTypeDefinition) { } - + override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { - } - + } + override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { Append("@protocol ") generateIdentifier(type.Name) @@ -95,34 +92,34 @@ public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { AppendLine() AppendLine() } - + override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { AppendLine() AppendLine("@end") - } + } // // Type Members // - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { generateMethodDefinitionHeader(method, type: type) AppendLine(";") } - + override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { generateMethodDefinitionHeader(ctor, type: type) AppendLine(";") } - + override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { - + if property.Virtuality == CGMemberVirtualityKind.Override || property.Virtuality == CGMemberVirtualityKind.Final { Append("// overriden ") // we don't need to re-emit overriden properties in header? } - + Append("@property ") - + Append("(") if property.Atomic { Append("atomic") @@ -144,7 +141,7 @@ public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator { Append(", readonly") } Append(") ") - + if let type = property.`Type` { generateTypeReference(type) if !objcTypeRefereneIsPointer(type) { diff --git a/CGObjectiveCMCodeGenerator.swift b/CGObjectiveCMCodeGenerator.swift index 34f85e3..4fc013f 100644 --- a/CGObjectiveCMCodeGenerator.swift +++ b/CGObjectiveCMCodeGenerator.swift @@ -1,18 +1,14 @@ -import Sugar -import Sugar.Collections -import Sugar.IO - -public class CGObjectiveCMCodeGenerator : CGObjectiveCCodeGenerator { +public class CGObjectiveCMCodeGenerator : CGObjectiveCCodeGenerator { public override var defaultFileExtension: String { return "m" } override func generateHeader() { - + if let fileName = currentUnit.FileName { Append("#import \"\(Path.ChangeExtension(fileName, ".h"))\"") } } - + override func generateImport(_ imp: CGImport) { // ignore imports, they are in the .h } @@ -20,29 +16,29 @@ public class CGObjectiveCMCodeGenerator : CGObjectiveCCodeGenerator { // // Types // - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { Append("@implementation ") generateIdentifier(type.Name) AppendLine() - + //objcGenerateFields(type) - + AppendLine() } override func generateStructType(_ type: CGStructTypeDefinition) { // structs don't appear in .m } - + override func generateInterfaceType(_ type: CGInterfaceTypeDefinition) { // protocols don't appear in .m } - + // // Type Members // - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { generateMethodDefinitionHeader(method, type: type) AppendLine() @@ -63,7 +59,7 @@ public class CGObjectiveCMCodeGenerator : CGObjectiveCCodeGenerator { decIndent() AppendLine("}") } - + override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil { Append("@synthesize ") @@ -83,7 +79,7 @@ public class CGObjectiveCMCodeGenerator : CGObjectiveCCodeGenerator { } } } - + override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) { if field.Static { Append("static ") @@ -92,7 +88,7 @@ public class CGObjectiveCMCodeGenerator : CGObjectiveCCodeGenerator { case .Strong: Append("__strong ") case .Weak: Append("__weak ") case .Unretained: Append("__unsafe_unretained") - } + } generateTypeReference(type) if !objcTypeRefereneIsPointer(type) { Append(" ") @@ -104,5 +100,5 @@ public class CGObjectiveCMCodeGenerator : CGObjectiveCCodeGenerator { AppendLine(";") } // instance fields are generated in TypeStart - } + } } \ No newline at end of file diff --git a/CGOxygeneCodeGenerator.swift b/CGOxygeneCodeGenerator.swift index a2f13d2..62750bb 100644 --- a/CGOxygeneCodeGenerator.swift +++ b/CGOxygeneCodeGenerator.swift @@ -1,14 +1,10 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { +public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { public enum CGOxygeneCodeGeneratorStyle { case Standard case Unified } - + public enum CGOxygeneStringQuoteStyle { case Single case Double @@ -20,49 +16,49 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { super.init() // current as of Elements 8.1 - keywords = ["abstract", "add", "and", "array", "as", "asc", "aspect", "assembly", "async", "autoreleasepool", "await", - "begin", "block", "break", "by", - "case", "class", "const", "constructor", "continue", - "default", "delegate", "deprecated", "desc", "distinct", "div", "do", "downto", "dynamic", - "each", "else", "empty", "end", "ensure", "enum", "equals", "event", "except", "exit", "extension", "external", - "false", "finalizer", "finally", "flags", "for", "from", "function", - "global", "goto", "group", - "has", - "if", "implementation", "implements", "implies", "in", "index", "inherited", "inline", "interface", "invariants", "is", "iterator", - "join", - "lazy", "locked", "locking", "loop", - "mapped", "matching", "method", "mod", "module", "namespace", - "nested", "new", "nil", "not", "notify", "nullable", - "of", "old", "on", "operator", "optional", "or", "order", "out", "override", - "parallel", "param", "params", "partial", "pinned", "private", "procedure", "property", "protected", "public", - "queryable", "raise", "raises", "read", "readonly", "record", "reintroduce", "remove", "repeat", "require", "result", "reverse", "sealed", - "select", "selector -", "self", "sequence", "set", "shl", "shr", "skip", "soft", "static", "step", "strong", - "take", "then", "to", "true", "try", "type", - "union", "unit", "unretained", "unsafe", "until", "uses", "using", - "var", "virtual", - "weak", "where", "while", "with", "write", - "xor", + keywords = ["abstract", "add", "and", "array", "as", "asc", "aspect", "assembly", "async", "autoreleasepool", "await", + "begin", "block", "break", "by", + "case", "class", "const", "constructor", "continue", + "default", "delegate", "deprecated", "desc", "distinct", "div", "do", "downto", "dynamic", + "each", "else", "empty", "end", "ensure", "enum", "equals", "event", "except", "exit", "extension", "external", + "false", "finalizer", "finally", "flags", "for", "from", "function", + "global", "goto", "group", + "has", + "if", "implementation", "implements", "implies", "in", "index", "inherited", "inline", "interface", "invariants", "is", "iterator", + "join", + "lazy", "locked", "locking", "loop", + "mapped", "matching", "method", "mod", "module", "namespace", + "nested", "new", "nil", "not", "notify", "nullable", + "of", "old", "on", "operator", "optional", "or", "order", "out", "override", + "parallel", "param", "params", "partial", "pinned", "private", "procedure", "property", "protected", "public", + "queryable", "raise", "raises", "read", "readonly", "record", "reintroduce", "remove", "repeat", "require", "result", "reverse", "sealed", + "select", "selector -", "self", "sequence", "set", "shl", "shr", "skip", "soft", "static", "step", "strong", + "take", "then", "to", "true", "try", "type", + "union", "unit", "unretained", "unsafe", "until", "uses", "using", + "var", "virtual", + "weak", "where", "while", "with", "write", + "xor", "yield"].ToList() as! List } public var Style: CGOxygeneCodeGeneratorStyle = .Standard public var QuoteStyle: CGOxygeneStringQuoteStyle = .SmartSingle - - override var isUnified: Boolean { return Style == .Unified } + + override var isUnified: Boolean { return Style == .Unified } public convenience init(style: CGOxygeneCodeGeneratorStyle) { init() Style = style - } + } public convenience init(style: CGOxygeneCodeGeneratorStyle, quoteStyle: CGOxygeneStringQuoteStyle) { init() Style = style QuoteStyle = quoteStyle - } + } override func generateHeader() { - + Append("namespace") if let namespace = currentUnit.Namespace { Append(" ") @@ -72,7 +68,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { AppendLine() super.generateHeader() } - + override func generateGlobals() { if let globals = currentUnit.Globals, globals.Count > 0{ AppendLine("{$GLOBALS ON}") @@ -124,7 +120,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { AppendLine("exit;") } } - + override func generateYieldStatement(_ statement: CGYieldStatement) { Append("yield ") generateExpression(statement.Value) @@ -158,7 +154,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { if let name = statement.ConstructorName { Append(" ") Append(name) - } + } Append("(") pascalGenerateCallParameters(statement.Parameters) AppendLine(");") @@ -185,13 +181,13 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { } Append("(") helpGenerateCommaSeparatedList(type.Members) { m in - + self.generateIdentifier(m.Name) self.Append(" := ") if let member = m as? CGAnonymousPropertyMemberDefinition { - + self.generateExpression(member.Value) - + } else if let member = m as? CGAnonymousMethodMemberDefinition { self.Append("method ") @@ -210,7 +206,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { self.decIndent() self.Append("end") } - + } Append(")") } @@ -267,7 +263,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { switch parameters[p].Modifier { case .Out: Append("out ") case .Var: Append("var ") - default: + default: } generateExpression(param.Value) } @@ -279,7 +275,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { case .Const: Append("const ") case .Out: Append("out ") case .Params: Append("params ") - default: + default: } generateIdentifier(param.Name) Append(": ") @@ -306,7 +302,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { } else { param.startLocation = currentLocation } - + generateParameterDefinition(param) param.endLocation = currentLocation } @@ -317,11 +313,11 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { generateExpression(expression.`Type`, ignoreNullability: true) if let bounds = expression.ArrayBounds, bounds.Count > 0 { Append("[") - helpGenerateCommaSeparatedList(bounds) { boundExpression in + helpGenerateCommaSeparatedList(bounds) { boundExpression in self.generateExpression(boundExpression) } Append("]") - } else { + } else { if let name = expression.ConstructorName { Append(" ") generateIdentifier(name) @@ -331,17 +327,17 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { Append(")") } } - + override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) { let SINGLE: Char = "'" - let DOUBLE: Char = "\"" + let DOUBLE: Char = "\"" let quoteChar: Char switch QuoteStyle { case .Single: quoteChar = SINGLE case .Double: quoteChar = DOUBLE case .SmartSingle: quoteChar = expression.Value.Contains(SINGLE) && !expression.Value.Contains(DOUBLE) ? DOUBLE : SINGLE case .SmartDouble: quoteChar = expression.Value.Contains(DOUBLE) && !expression.Value.Contains(SINGLE) ? SINGLE : DOUBLE - } + } Append(pascalEscapeCharactersInStringLiteral(expression.Value, quoteChar: quoteChar)) } @@ -357,7 +353,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { case .Public: Append("public ") } } - + override func pascalGenerateMemberVisibilityKeyword(_ visibility: CGMemberVisibilityKind) { switch visibility { case .Unspecified: break /* no-op */ @@ -373,7 +369,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { case .Public: Append("public") } } - + override func generateBlockType(_ block: CGBlockTypeDefinition) { generateIdentifier(block.Name) pascalGenerateGenericParameters(block.GenericParameters) @@ -411,15 +407,15 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { AppendLine() incIndent() } - + // // Type Members // - + override func pascalKeywordForMethod(_ method: CGMethodDefinition) -> String { - return "method" + return "method" } - + override func pascalGenerateVirtualityModifiders(_ member: CGMemberDefinition) { switch member.Virtuality { //case .None @@ -431,12 +427,12 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { default: } } - + override func pascalGenerateConstructorHeader(_ ctor: CGMethodLikeMemberDefinition, type: CGTypeDefinition, methodKeyword: String, implementation: Boolean, includeVisibility: Boolean = false) { if ctor.Static { Append("class ") } - + Append("constructor") if implementation { Append(" ") @@ -448,7 +444,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { } pascalGenerateSecondHalfOfMethodHeader(ctor, implementation: implementation, includeVisibility: includeVisibility) } - + internal func pascalGenerateFinalizerHeader(_ method: CGMethodLikeMemberDefinition, type: CGTypeDefinition, implementation: Boolean) { Append("finalizer") if implementation { @@ -509,7 +505,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { generateMethodDefinition(event.RaiseMethodDefinition, type: ttpe) }*/ } - + override func pascalGenerateEventImplementation(_ event: CGEventDefinition, type: CGTypeDefinition) { if let addStatements = event.AddStatements { pascalGenerateMethodImplementation(event.AddMethodDefinition()!, type: type) @@ -525,8 +521,8 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { // // Type References // - - + + func pascalGeneratePrefixForNullability(_ type: CGTypeReference) { if (type.Nullability == CGTypeNullabilityKind.NullableUnwrapped && (type.DefaultNullability == CGTypeNullabilityKind.NotNullable || type.DefaultNullability == CGTypeNullabilityKind.Unknown)) || type.Nullability == CGTypeNullabilityKind.NullableNotUnwrapped { Append("nullable ") @@ -534,20 +530,20 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { Append("not nullable ") } } - + override func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNullability: Boolean = false) { if !ignoreNullability { pascalGeneratePrefixForNullability(type) } super.generateNamedTypeReference(type, ignoreNullability: ignoreNullability) } - + override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { - + if !ignoreNullability { pascalGeneratePrefixForNullability(type) } - + switch (type.Kind) { case .Int: Append("NativeInt") case .UInt: Append("NativeUInt") @@ -573,7 +569,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { case .Void: Append("{VOID}") case .Object: Append("Object") case .Class: generateIdentifier("Class") // todo: make platform-specific - } + } } override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { @@ -601,7 +597,7 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { generateTypeReference(type.`Type`) Append(">") } - + override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) { if !ignoreNullability { pascalGeneratePrefixForNullability(type) @@ -623,5 +619,5 @@ public class CGOxygeneCodeGenerator : CGPascalCodeGenerator { Append("sequence of ") generateTypeReference(sequence.`Type`) } - + } \ No newline at end of file diff --git a/CGPascalCodeGenerator.swift b/CGPascalCodeGenerator.swift index de0a26c..f581380 100644 --- a/CGPascalCodeGenerator.swift +++ b/CGPascalCodeGenerator.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -// +// // Abstract base implementation for all Pascal-style languages (Oxygene, Delphi) // @@ -27,8 +23,8 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { } return name } - - internal var isUnified: Boolean { return false } + + internal var isUnified: Boolean { return false } // // Pascal Special for interface/implementation separation @@ -59,16 +55,16 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { pascalGenerateImports(currentUnit.ImplementationImports) pascalGenerateTypeImplementations() pascalGenerateGlobalImplementations() - } - generateFooter() + } + generateFooter() } - + final func pascalGenerateTypeImplementations() { for t in currentUnit.Types { pascalGenerateTypeImplementation(t) } } - + final func pascalGenerateGlobalImplementations() { for g in currentUnit.Globals { pascalGenerateGlobalImplementation(g) @@ -101,7 +97,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { final func pascalGenerateTypeMemberImplementations(_ type: CGTypeDefinition) { if AlphaSortImplementationMembers { var temp = List() - temp.AddRange(type.Members) + temp.Add(type.Members) temp.Sort({return $0.Name.CompareTo/*IgnoreCase*/($1.Name)}) for m in temp { pascalGenerateTypeMemberImplementation(m, type: type) @@ -112,7 +108,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { } } } - + final func pascalGenerateTypeMemberImplementation(_ member: CGMemberDefinition, type: CGTypeDefinition) { if let condition = member.Condition { @@ -142,8 +138,8 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { } } - - + + final func pascalGenerateGlobalImplementation(_ global: CGGlobalDefinition) { if let global = global as? CGGlobalFunctionDefinition { pascalGenerateMethodImplementation(global.Function, type: CGGlobalTypeDefinition.GlobalType) @@ -164,7 +160,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { var comment = comment.Replace("}", "*)") Append("{ \(comment) }") } - + internal func pascalGenerateImports(_ imports: List) { if imports.Count > 0 { AppendLine("uses") @@ -181,7 +177,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { decIndent() } } - + override func generateFooter() { AppendLine("end.") } @@ -189,7 +185,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { // // Statements // - + override func generateConditionStart(_ condition: CGConditionalDefine) { Append("{$IF ") generateConditionalDefine(condition) // Oxygene is easier than plain Pascal here @@ -199,7 +195,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { override func generateConditionElse() { AppendLine("{$ELSE}") } - + override func generateConditionEnd(_ condition: CGConditionalDefine) { AppendLine("{$ENDIF}") } @@ -623,12 +619,12 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { case .In: Append("in") //case .NotIn: case .Assign: Append(":=") - //case .AssignAddition: + //case .AssignAddition: //case .AssignSubtraction: //case .AssignMultiplication: - //case .AssignDivision: - //case .AddEvent: - //case .RemoveEvent: + //case .AssignDivision: + //case .AddEvent: + //case .RemoveEvent: default: Append("{ NOT SUPPORTED }") } } @@ -683,8 +679,8 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { } func pascalGenerateDefinitionParameters(_ parameters: List) { - helpGenerateCommaSeparatedList(parameters, separator: { self.Append("; ") }) { param in - if let exp = param.`Type` as? CGConstantTypeReference { + helpGenerateCommaSeparatedList(parameters, separator: { self.Append("; ") }) { param in + if let exp = param.`Type` as? CGConstantTypeReference { self.Append("const ") } else { @@ -830,11 +826,11 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { internal func pascalEscapeCharactersInStringLiteral(_ string: String, quoteChar: Char) -> String { let result = StringBuilder() let len = string.Length - + if len == 0 { return quoteChar+quoteChar } - + var inQuotes = false for i in 0 ..< len { let ch = string[i] @@ -861,7 +857,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { } return result.ToString() } - + override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) { Append(pascalEscapeCharactersInStringLiteral(expression.Value, quoteChar: "'")) } @@ -977,7 +973,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { Append(" = ") pascalGenerateTypeVisibilityPrefix(type.Visibility) Append("enum (") - + helpGenerateCommaSeparatedList(type.Members) { m in if let member = m as? CGEnumValueDefinition { self.generateIdentifier(member.Name) @@ -987,7 +983,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { } } } - + Append(")") if let baseType = type.BaseType { Append(" of ") @@ -1176,9 +1172,9 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { returnType.endLocation = currentLocation } Append(";") - + if !implementation { - + if isUnified { Append(" ") pascalGenerateMemberVisibilityKeyword(method.Visibility) @@ -1227,7 +1223,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { if method.Overloaded { Append(" overload;") } - if let conversion = method.CallingConvention { + if let conversion = method.CallingConvention { pascalGenerateCallingConversion(conversion); } @@ -1424,7 +1420,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { generateExpression(initializer) } } - + if isUnified { Append("; ") pascalGenerateMemberVisibilityKeyword(variable.Visibility) @@ -1450,7 +1446,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { } // todo: initializer for properties? - + func appendRead() { self.Append(" ") if let v = property.GetterVisibility { @@ -1464,28 +1460,28 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { if let v = property.SetterVisibility { self.pascalGenerateMemberVisibilityKeyword(v) self.Append(" ") - } + } self.Append("write") } - + if property.IsShortcutProperty { if type is CGInterfaceTypeDefinition || property.Virtuality == CGMemberVirtualityKind.Abstract { - + if !property.WriteOnly { Append(" read") } if !property.ReadOnly { Append(" write") } - + } else { - + if !property.ReadOnly && property.GetterVisibility != nil || property.SetterVisibility != nil { appendRead() appendWrite() } - + if let value = property.Initializer { Append(" := ") generateExpression(value) @@ -1494,9 +1490,9 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { Append("; readonly") } } - + } else { - + if let getStatements = property.GetStatements, let getterMethod = property.GetterMethodDefinition() { appendRead() if !definitionOnly { @@ -1510,7 +1506,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { generateExpression(getExpression) } } - + if let setStatements = property.SetStatements, let setterMethod = property.SetterMethodDefinition() { appendWrite() if !definitionOnly { @@ -1607,7 +1603,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { case .Void: Append("{VOID}") case .Object: Append("Object") case .Class: Append("") - } + } } override func generateIntegerRangeTypeReference(_ type: CGIntegerRangeTypeReference, ignoreNullability: Boolean = false) { @@ -1615,7 +1611,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { Append("..") Append(type.End.ToString()) } - + override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateInlineBlockTypeReference is not supported in base Pascal, only Oxygene") } @@ -1633,7 +1629,7 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateKindOfTypeReference is not supported in base Pascal, only Oxygene") } - + override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateTupleTypeReference is not supported in base Pascal, only Oxygene") } @@ -1671,4 +1667,4 @@ public __abstract class CGPascalCodeGenerator : CGCodeGenerator { override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateDictionaryTypeReference is not supported in Pascal") } -} +} \ No newline at end of file diff --git a/CGSkeletonCodeGenerator.swift b/CGSkeletonCodeGenerator.swift index 529ed02..324cab2 100644 --- a/CGSkeletonCodeGenerator.swift +++ b/CGSkeletonCodeGenerator.swift @@ -1,14 +1,11 @@ -import Sugar -import Sugar.Collections - -// +// // An Empty Code Generator with stubs for all methids that usually need implementing // Useful as a starting oint for creating a new codegen, or check for missing implementations via diff // // All concrete implementations should use the same sort order for methods as this class. // // All methods named "generate*" should be overrides. For language-specific generators, add a prefix -// to the method name to indicate the language — see Swift of Pascal codegen implementations for reference. +// to the method name to indicate the language — see Swift of Pascal codegen implementations for reference. // public class CGSkeletonCodeGenerator : CGCodeGenerator { @@ -20,16 +17,16 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { } override func generateHeader() { - + } override func generateFooter() { } - + /*override func generateImports() { }*/ - + override func generateImport(_ imp: CGImport) { } @@ -37,11 +34,11 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { override func generateInlineComment(_ comment: String) { } - + // // Statements // - + override func generateConditionStart(_ condition: CGConditionalDefine) { } @@ -128,8 +125,8 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { override func generateAssignmentStatement(_ statement: CGAssignmentStatement) { - } - + } + override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) { } @@ -209,7 +206,7 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) { } - + override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { } @@ -275,75 +272,75 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { // default handled in base } */ - + override func generateSetTypeReference(_ type: CGSetTypeReference, ignoreNullability: Boolean = false) { } - + override func generateSequenceTypeReference(_ type: CGSequenceTypeReference, ignoreNullability: Boolean = false) { } - + // // Type Definitions // - + override func generateAttribute(_ attribute: CGAttribute) { } - + override func generateAliasType(_ type: CGTypeAliasDefinition) { } - + override func generateBlockType(_ type: CGBlockTypeDefinition) { - + } - + override func generateEnumType(_ type: CGEnumTypeDefinition) { - + } - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { } - + override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { } - + override func generateStructTypeStart(_ type: CGStructTypeDefinition) { } - + override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { - } - + } + override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { } - + override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { - } - + } + override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { } - + override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { - } + } // // Type Members // - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { } - + override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { } @@ -383,7 +380,7 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { override func generateNamedTypeReference(_ type: CGNamedTypeReference) { } - + override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { switch (type.Kind) { case .Int: Append("") @@ -410,7 +407,7 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { case .Void: Append("") case .Object: Append("") case .Class: Append("") - } + } } override func generateIntegerRangeTypeReference(_ type: CGIntegerRangeTypeReference, ignoreNullability: Boolean = false) { @@ -418,28 +415,28 @@ public class CGSkeletonCodeGenerator : CGCodeGenerator { Append("..") Append(type.End.ToString()) } - + override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { } - + override func generatePointerTypeReference(_ type: CGPointerTypeReference) { } - + override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { } - + override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) { } - + override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) { } - + override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { } -} +} \ No newline at end of file diff --git a/CGSwiftCodeGenerator.swift b/CGSwiftCodeGenerator.swift index e8eac51..3144168 100644 --- a/CGSwiftCodeGenerator.swift +++ b/CGSwiftCodeGenerator.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -public enum CGSwiftCodeGeneratorDialect { +public enum CGSwiftCodeGeneratorDialect { case Standard case Silver } @@ -11,9 +7,9 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { public init() { super.init() - + // current as of Elements 8.1 and Swift 1.2 - keywords = ["__abstract", "__await", "__catch", "__event", "__finally", "__mapped", "__out", "__partial", "__throw", "__try", "__using", "__yield", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", + keywords = ["__abstract", "__await", "__catch", "__event", "__finally", "__mapped", "__out", "__partial", "__throw", "__try", "__using", "__yield", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", "as", "associativity", "autoreleasepool", "break", "case", "catch", "class", "continue", "convenience", "default", "defer", "deinit", "didSet", "do", "dynamicType", "else", "enum", "extension", "fallthrough", "false", "final", "for", "func", "get", "guard", "if", "import", "in", "infix", "init", "inout", "internal", "is", "lazy", "left", "let", "mutating", "nil", "none", "nonmutating", "open", "operator", "optional", "override", "postfix", "precedence", "prefix", "private", "protocol", "public", @@ -22,11 +18,11 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } public var Dialect: CGSwiftCodeGeneratorDialect = .Standard - + public convenience init(dialect: CGSwiftCodeGeneratorDialect) { init() Dialect = dialect - } + } public override var defaultFileExtension: String { return "swift" } @@ -43,11 +39,11 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { override func generateStatementTerminator() { AppendLine() // no ; in Swift } - + // // Statements // - + // in C-styleCG Base class /*override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) { }*/ @@ -89,7 +85,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append(" = ") generateExpression(statement.StartValue) Append("; ") - + generateIdentifier(statement.LoopVariableName) if statement.Direction == CGLoopDirectionKind.Forward { Append(" <= ") @@ -172,17 +168,17 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { override func generateUsingStatement(_ statement: CGUsingStatement) { if Dialect == CGSwiftCodeGeneratorDialect.Silver { - + Append("__using let ") generateIdentifier(statement.Name) if let type = statement.`Type` { Append(": ") generateTypeReference(type) - } + } Append(" = ") generateExpression(statement.Value) AppendLine(" {") - + generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement) AppendLine("}") @@ -318,7 +314,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append(")") AppendLine() } - + // // Expressions // @@ -433,15 +429,15 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { AppendLine("{") incIndent() helpGenerateCommaSeparatedList(type.Members, separator: { self.AppendLine() }) { m in - + if let member = m as? CGAnonymousPropertyMemberDefinition { - + self.Append("var ") self.generateIdentifier(m.Name) self.Append(" = ") self.generateExpression(member.Value) self.AppendLine() - + } else if let member = m as? CGAnonymousMethodMemberDefinition { self.Append("func ") @@ -551,11 +547,11 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } switch param.Modifier { case .Out: fallthrough - case .Var: + case .Var: Append("&(") generateExpression(param.Value) Append(")") - default: + default: generateExpression(param.Value) } } @@ -578,18 +574,18 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { override func generateParameterDefinition(_ param: CGParameterDefinition) { swiftGenerateParameterDefinition(param, emitExternal: false) // never emit the _ } - + private func swiftGenerateParameterDefinition(_ param: CGParameterDefinition, emitExternal: Boolean, externalName: String? = nil) { switch param.Modifier { - case .Out: + case .Out: if Dialect == CGSwiftCodeGeneratorDialect.Silver { Append("__out ") } else { fallthrough } - case .Var: + case .Var: Append("inout ") - default: + default: } if emitExternal, let externalName = param.ExternalName ?? externalName { if externalName != param.Name { @@ -613,7 +609,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { let param = parameters[p] if p > 0 { Append(", ") - } + } param.startLocation = currentLocation swiftGenerateParameterDefinition(param, emitExternal: true, externalName: p == 0 ? firstExternalName : nil) param.endLocation = currentLocation @@ -683,15 +679,15 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append("?") } Append("(") - swiftGenerateCallParameters(method.Parameters) + swiftGenerateCallParameters(method.Parameters) Append(")") } - + override func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) { generateExpression(expression.`Type`, ignoreNullability: true) if let bounds = expression.ArrayBounds, bounds.Count > 0 { Append("[](count: ") - helpGenerateCommaSeparatedList(bounds) { boundExpression in + helpGenerateCommaSeparatedList(bounds) { boundExpression in self.generateExpression(boundExpression) } Append(")") @@ -715,9 +711,9 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append("]") } } - + override func cStyleEscapeSequenceForCharacter(_ ch: Char) -> String { - return "\\u{"+Sugar.Convert.ToString(Integer(ch), 16) + return "\\u{"+Convert.ToString(Integer(ch), 16) } /* @@ -792,11 +788,11 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { // default handled in base } */ - + // // Type Definitions // - + override func generateAttribute(_ attribute: CGAttribute) { Append("@") generateTypeReference(attribute.`Type`, ignoreNullability: true) @@ -804,7 +800,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append("(") swiftGenerateAttributeParameters(parameters) Append(")") - } + } if let comment = attribute.Comment { Append(" ") generateSingleLineCommentStatement(comment) @@ -812,7 +808,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { AppendLine() } } - + func swiftGenerateTypeVisibilityPrefix(_ visibility: CGTypeVisibilityKind, sealed: Boolean = false) { switch visibility { case .Unspecified: @@ -832,7 +828,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } } } - + func swiftGenerateMemberTypeVisibilityPrefix(_ visibility: CGMemberVisibilityKind, virtuality: CGMemberVirtualityKind, appendSpace: Boolean = true) { switch visibility { case .Unspecified: break /* no-op */ @@ -859,18 +855,18 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { case .Override: Append(" override") case .Final: Append(" final") case .Reintroduce: break; - } + } if appendSpace { Append(" ") } } - + func swiftGenerateStaticPrefix(_ isStatic: Boolean) { if isStatic { Append("static ") } } - + func swiftGenerateAbstractPrefix(_ isAbstract: Boolean) { if isAbstract && Dialect == CGSwiftCodeGeneratorDialect.Silver { Append("__abstract ") @@ -885,7 +881,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { generateTypeReference(type.ActualType) AppendLine() } - + override func generateBlockType(_ block: CGBlockTypeDefinition) { swiftGenerateTypeVisibilityPrefix(block.Visibility) Append("typealias ") @@ -894,7 +890,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { swiftGenerateInlineBlockType(block) AppendLine() } - + func swiftGenerateInlineBlockType(_ block: CGBlockTypeDefinition) { if block.IsPlainFunctionPointer { Append("@FunctionPointer ") @@ -917,7 +913,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append("()") } } - + override func generateEnumType(_ type: CGEnumTypeDefinition) { swiftGenerateTypeVisibilityPrefix(type.Visibility) Append("enum ") @@ -943,7 +939,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { decIndent() AppendLine("}") } - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { swiftGenerateTypeVisibilityPrefix(type.Visibility, sealed: type.Sealed) swiftGenerateStaticPrefix(type.Static) @@ -955,12 +951,12 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { AppendLine(" { ") incIndent() } - + override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { decIndent() AppendLine("}") } - + override func generateStructTypeStart(_ type: CGStructTypeDefinition) { swiftGenerateTypeVisibilityPrefix(type.Visibility, sealed: type.Sealed) swiftGenerateStaticPrefix(type.Static) @@ -972,12 +968,12 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { AppendLine(" { ") incIndent() } - + override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { decIndent() AppendLine("}") - } - + } + override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { swiftGenerateTypeVisibilityPrefix(type.Visibility, sealed: type.Sealed) Append("protocol ") @@ -987,12 +983,12 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { AppendLine(" { ") incIndent() } - + override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { decIndent() AppendLine("}") - } - + } + override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { swiftGenerateTypeVisibilityPrefix(type.Visibility) Append("extension ") @@ -1001,16 +997,16 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { AppendLine("{ ") incIndent() } - + override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { decIndent() AppendLine("}") - } + } // // Type Members // - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { if type is CGInterfaceTypeDefinition { @@ -1031,23 +1027,23 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append("(") swiftGenerateDefinitionParameters(method.Parameters) Append(")") - + if method.Throws { Append(" throws") } - + if let returnType = method.ReturnType, !returnType.IsVoid { Append(" -> ") returnType.startLocation = currentLocation generateTypeReference(returnType) returnType.endLocation = currentLocation } - + if type is CGInterfaceTypeDefinition || method.External || definitionOnly { AppendLine() return } - + AppendLine(" {") incIndent() generateStatements(method.LocalVariables) @@ -1055,7 +1051,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { decIndent() AppendLine("}") } - + override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { if type is CGInterfaceTypeDefinition { } else { @@ -1065,7 +1061,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { switch ctor.Nullability { case .NullableUnwrapped: Append("!") case .NullableNotUnwrapped: Append("?") - default: + default: } Append("(") if length(ctor.Name) > 0 { @@ -1115,18 +1111,18 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } } Append("func Finalizer()") - + if type is CGInterfaceTypeDefinition || finalizer.External || definitionOnly { AppendLine() return } - + AppendLine(" {") incIndent() generateStatements(finalizer.LocalVariables) generateStatements(finalizer.Statements) decIndent() - AppendLine("}") + AppendLine("}") } override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) { @@ -1161,7 +1157,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } else { swiftGenerateMemberTypeVisibilityPrefix(property.Visibility, virtuality: property.Virtuality) } - + if let v = property.SetterVisibility { swiftGenerateMemberTypeVisibilityPrefix(v, virtuality: property.Virtuality, appendSpace: false) Append("(set) ") @@ -1172,15 +1168,15 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } else { swiftGenerateMemberTypeVisibilityPrefix(property.Visibility, virtuality: property.Virtuality) } - + swiftGenerateStaticPrefix(property.Static && !type.Static) if property.Lazy { Append("lazy ") } swiftGenerateStorageModifierPrefix(property.`Type`) - + if let params = property.Parameters, params.Count > 0 { - + Append("subscript ") generateIdentifier(property.Name) Append("(") @@ -1193,9 +1189,9 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { assert(false, "Swift Subscripts must have a well-defined type.") } assert(property.Initializer == nil, "Swift Subscripts cannot have an initializer.") - + } else { - + if property.ReadOnly && (property.IsShortcutProperty) { Append("let ") } else if property.WriteOnly { @@ -1211,7 +1207,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } if property.IsShortcutProperty { - + if let value = property.Initializer { Append(" = ") generateExpression(value) @@ -1219,13 +1215,13 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { swiftGenerateDefaultInitializerForType(property.`Type`) } AppendLine() - + } else { - + if let value = property.Initializer { assert(false, "Swift Properties cannot have both accessor statements and an initializer") } - + if type is CGInterfaceTypeDefinition || definitionOnly { AppendLine() return @@ -1233,7 +1229,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { AppendLine(" {") incIndent() - + if let getStatements = property.GetStatements { AppendLine("get {") incIndent() @@ -1247,7 +1243,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { decIndent() AppendLine("}") } - + if let setStatements = property.SetStatements { AppendLine("set {") incIndent() @@ -1261,7 +1257,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { decIndent() AppendLine("}") } - + decIndent() AppendLine("}") } @@ -1319,11 +1315,11 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { return swiftSuffixForNullability(defaultNullability, defaultNullability:CGTypeNullabilityKind.Unknown) } } - + func swiftSuffixForNullabilityForCollectionType(_ type: CGTypeReference) -> String { return swiftSuffixForNullability(type.Nullability, defaultNullability: Dialect == CGSwiftCodeGeneratorDialect.Silver ? CGTypeNullabilityKind.NotNullable : CGTypeNullabilityKind.NullableUnwrapped) } - + func swiftGenerateDefaultInitializerForType(_ type: CGTypeReference?) { if let type = type { if type.ActualNullability == CGTypeNullabilityKind.NotNullable || (type.Nullability == CGTypeNullabilityKind.Default && !type.IsClassType) { @@ -1334,14 +1330,14 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } } } - + override func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNullability: Boolean = false) { super.generateNamedTypeReference(type, ignoreNullability: ignoreNullability) if !ignoreNullability { Append(swiftSuffixForNullability(type.Nullability, defaultNullability: type.DefaultNullability)) } } - + override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { switch (type.Kind) { case .Int: Append("Int") @@ -1368,7 +1364,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { case .Void: Append("()") case .Object: if Dialect == CGSwiftCodeGeneratorDialect.Silver { Append("Object") } else { Append("NSObject") } case .Class: Append("AnyClass") - } + } if !ignoreNullability { Append(swiftSuffixForNullability(type.Nullability, defaultNullability: type.DefaultNullability)) } @@ -1383,15 +1379,15 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append(suffix) } else { swiftGenerateInlineBlockType(type.Block) - } + } } - + override func generatePointerTypeReference(_ type: CGPointerTypeReference) { Append("UnsafePointer<") generateTypeReference(type.`Type`) Append(">") } - + override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { if Dialect == CGSwiftCodeGeneratorDialect.Silver { Append("dynamic<") @@ -1404,7 +1400,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { assert(false, "generateKindOfTypeReference is not supported in Swift, except in Silver") } } - + override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) { Append("(") for m in 0 ..< type.Members.Count { @@ -1418,11 +1414,11 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } Append(")") } - + override func generateSetTypeReference(_ setType: CGSetTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateSetTypeReference is not supported in Swift") } - + override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference, ignoreNullability: Boolean = false) { if Dialect == CGSwiftCodeGeneratorDialect.Silver { Append("ISequence<") @@ -1435,9 +1431,9 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { assert(false, "generateSequenceTypeReference is not supported in Swift except in Silver") } } - + override func generateArrayTypeReference(_ array: CGArrayTypeReference, ignoreNullability: Boolean = false) { - + var bounds = array.Bounds.Count if bounds == 0 { bounds = 1 @@ -1469,7 +1465,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } // bounds are not supported in Swift } - + override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { Append("[") generateTypeReference(type.KeyType) @@ -1480,7 +1476,7 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { Append(swiftSuffixForNullabilityForCollectionType(type)) } } - + // // Helpers // @@ -1492,4 +1488,4 @@ public class CGSwiftCodeGenerator : CGCStyleCodeGenerator { } return lowercaseFirstLetter(name) } -} +} \ No newline at end of file diff --git a/CGVisualBasicNetCodeGenerator.swift b/CGVisualBasicNetCodeGenerator.swift index c7451f9..0a1d350 100644 --- a/CGVisualBasicNetCodeGenerator.swift +++ b/CGVisualBasicNetCodeGenerator.swift @@ -1,7 +1,4 @@ -import Sugar -import Sugar.Collections - -public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { +public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { public override var defaultFileExtension: String { return "vb" } @@ -10,20 +7,20 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { } override func generateHeader() { - + } override func generateFooter() { } - + override func generateImports() { super.generateImports() if currentUnit.Imports.Count > 0 { AppendLine() } } - + override func generateImport(_ imp: CGImport) { if imp.StaticClass != nil { //todo @@ -41,11 +38,11 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { override func generateInlineComment(_ comment: String) { } - + // // Statements // - + override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) { } @@ -198,8 +195,8 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { Append(" = ") generateExpression(statement.Value) AppendLine() - } - + } + override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) { } @@ -242,7 +239,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { generateExpression(param.Value) } } - + override func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) { } @@ -322,7 +319,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) { } - + override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { switch (`operator`) { case .Concat: Append("&") @@ -352,12 +349,12 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { //case .In: Append("in") //case .NotIn: case .Assign: Append("=") - //case .AssignAddition: + //case .AssignAddition: //case .AssignSubtraction: //case .AssignMultiplication: - //case .AssignDivision: - //case .AddEvent: - //case .RemoveEvent: + //case .AssignDivision: + //case .AddEvent: + //case .RemoveEvent: default: Append("/* NOT SUPPORTED */") } } @@ -392,7 +389,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { generateExpression(expression.`Type`) /*if let bounds = expression.ArrayBounds, bounds.Count > 0 { Append("[") - helpGenerateCommaSeparatedList(bounds) { boundExpression in + helpGenerateCommaSeparatedList(bounds) { boundExpression in self.generateExpression(boundExpression) } Append("]") @@ -418,7 +415,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { // handled in base } */ - + internal func vbEscapeCharactersInStringLiteral(_ string: String) -> String { let result = StringBuilder() let len = string.Length @@ -471,19 +468,19 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { // default handled in base } */ - + override func generateSetTypeReference(_ type: CGSetTypeReference, ignoreNullability: Boolean = false) { } - + override func generateSequenceTypeReference(_ type: CGSequenceTypeReference, ignoreNullability: Boolean = false) { } - + // // Type Definitions // - + override func generateAttribute(_ attribute: CGAttribute) { Append("<") generateTypeReference(attribute.`Type`) @@ -491,7 +488,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { Append("(") vbGenerateAttributeParameters(parameters) Append(")") - } + } Append(">") if let comment = attribute.Comment { Append(" ") @@ -500,7 +497,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { AppendLine() } } - + func vbGenerateTypeVisibilityPrefix(_ visibility: CGTypeVisibilityKind) { switch visibility { case .Unspecified: break /* no-op */ @@ -509,7 +506,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { case .Public: Append("Public ") } } - + func vbGenerateMemberTypeVisibilityPrefix(_ visibility: CGMemberVisibilityKind) { switch visibility { case .Unspecified: break /* no-op */ @@ -525,13 +522,13 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { case .Public: Append("Public ") } } - + func vbGenerateStaticPrefix(_ isStatic: Boolean) { if isStatic { Append("Shared ") } } - + func vbGenerateAbstractPrefix(_ isAbstract: Boolean) { if isAbstract { Append("Abstract ") @@ -562,7 +559,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { case .Const: Append("const ") //todo: Oxygene ony? case .Out: Append("out ") case .Params: Append("params ") - default: + default: } generateIdentifier(param.Name) Append(" As ") @@ -635,7 +632,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { } } } - + func vbGenerateAncestorList(_ type: CGClassOrStructTypeDefinition) { if type.Ancestors.Count > 0 { Append(" Of ") @@ -667,15 +664,15 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { override func generateAliasType(_ type: CGTypeAliasDefinition) { } - + override func generateBlockType(_ type: CGBlockTypeDefinition) { - + } - + override func generateEnumType(_ type: CGEnumTypeDefinition) { - + } - + override func generateClassTypeStart(_ type: CGClassTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) vbGenerateStaticPrefix(type.Static) @@ -689,12 +686,12 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { AppendLine() incIndent() } - + override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { decIndent() AppendLine("End Class") } - + override func generateStructTypeStart(_ type: CGStructTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) vbGenerateStaticPrefix(type.Static) @@ -708,12 +705,12 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { AppendLine() incIndent() } - + override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { decIndent() AppendLine("End Structure") - } - + } + override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) vbGenerateSealedPrefix(type.Sealed) @@ -726,24 +723,24 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { AppendLine("{") incIndent() } - + override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { decIndent() AppendLine("End Interface") } - + override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { } - + override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { - } + } // // Type Members // - + override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { if type is CGInterfaceTypeDefinition { vbGenerateStaticPrefix(method.Static && !type.Static) @@ -772,18 +769,18 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { } AppendLine() //vbGenerateGenericConstraints(method.GenericParameters) - + if type is CGInterfaceTypeDefinition || method.Virtuality == CGMemberVirtualityKind.Abstract || method.External || definitionOnly { return } - + incIndent() generateStatements(method.LocalVariables) generateStatements(method.Statements) decIndent() AppendLine("End Sub") } - + override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { } @@ -821,7 +818,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { vbGenerateMemberTypeVisibilityPrefix(property.Visibility) vbGenerateStaticPrefix(property.Static && !type.Static) vbGenerateVirtualityPrefix(property) - + if property.ReadOnly || (property.SetStatements == nil && property.SetExpression == nil && (property.GetStatements != nil || property.GetExpression != nil)) { Append("ReadOnly ") } else { @@ -829,10 +826,10 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { Append("ReadOnly ") } } - + Append("Property ") //if property.Default { - // Append("this") + // Append("this") //} else { generateIdentifier(property.Name) //} @@ -846,10 +843,10 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { Append("[") vbGenerateDefinitionParameters(params) Append("]") - } + } if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil { - + if property.ReadOnly { Append(" { get; }") } else if property.WriteOnly { @@ -862,9 +859,9 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { generateExpression(value) } AppendLine() - + } else { - + if definitionOnly { /*Append("{ ") if property.GetStatements != nil || property.GetExpression != nil { @@ -880,7 +877,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { AppendLine() incIndent() - + if let getStatements = property.GetStatements { AppendLine("Get") incIndent() @@ -895,7 +892,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { } else { AppendLine("WriteOnly") } - + if let setStatements = property.SetStatements { AppendLine("Set") incIndent() @@ -911,7 +908,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { } else { AppendLine("ReadOnly") } - + decIndent() Append("End Property") @@ -942,7 +939,7 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { override func generateNamedTypeReference(_ type: CGNamedTypeReference) { } - + override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { switch (type.Kind) { case .Int: Append("") @@ -969,30 +966,30 @@ public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { case .Void: Append("") case .Object: Append("") case .Class: Append("") - } + } } override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { } - + override func generatePointerTypeReference(_ type: CGPointerTypeReference) { } - + override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { } - + override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) { } - + override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) { } - + override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { } -} +} \ No newline at end of file diff --git a/CodeDomToCG4.swift b/CodeDomToCG4.swift index 7d09b4d..1d70b05 100644 --- a/CodeDomToCG4.swift +++ b/CodeDomToCG4.swift @@ -1,120 +1,120 @@ -import System.Collections.Generic -import System.Linq -import System.Text -import System.CodeDom - -public static class CodeDomToCG4 { - - /*public func convertUnit(_ codeDomUnit: CodeCompileUnit) -> CGCodeUnit? { - - if codeDomUnit.Namespaces.Count >= 1 { - var namespace = codeDomUnit.Namespaces[0]; - - let unit = CGCodeUnit(namespace.Name) - - for i: CodeNamespaceImport in namespace.Imports { - unit.Imports.Add(CGImport(i.Namespace)) - } - for t: CodeTypeDeclaration in namespace.Types { - if let newType = convertType(t) { - unit.Types.Add(newType) - } - } - for c: CodeCommentStatement in namespace.Comments { - unit.HeaderComment.Lines.Add(c.Comment.Text) - } - - // Process additinal namespaces - /*if codeDomUnit.Namespaces.Count > 1 { - for x in 1 ..< codeDomUnit.Namespaces.Count { - var namespace2 = codeDomUnit.Namespaces[x]; - - for i: CodeNamespaceImport in namespace2.Imports { - unit.Imports.Add(CGImport(i.Namespace)) - } - - } - // ToDo: handle additional namespaces? - }*/ - - return unit - } - - return nil - }*/ - - public func convertType(_ codeDomType: CodeTypeDeclaration, ignoreMembers: Boolean = false) -> CGTypeDefinition? { - - if !ignoreMembers && codeDomType.Members.Count > 0 { - throw Exception("convertType does not support converting members yet.") - } - - if codeDomType.IsClass { - let result = CGClassTypeDefinition(codeDomType.Name) - - for b: CodeTypeReference in codeDomType.BaseTypes { - if let ancestor = convertTypeReference(b) { - result.Ancestors.Add(ancestor) - } - } - - return result - } - - throw Exception("convertType does not support converting this kind of type yet.") - } - - public func convertTypeReference(_ codeDomType: CodeTypeReference) -> CGTypeReference? { - - if let codeDomArrayType = codeDomType.ArrayElementType { - if let arrayType = convertTypeReference(codeDomArrayType) { - var bounds = List() - for i in 0 ..< codeDomType.ArrayRank { - bounds.Add(CGArrayBounds()) - } - return CGArrayTypeReference(arrayType, bounds) - } - return nil - } else if codeDomType.UserData.Contains("OxygeneNullable") && String.Compare(codeDomType.BaseType, "SYSTEM.NULLABLE`1", StringComparison.InvariantCultureIgnoreCase) == 0 { - return convertTypeReference(codeDomType.TypeArguments.Item[0])?.NullableNotUnwrapped - } else { - return CGNamedTypeReference(codeDomType.BaseType) - } - } - - public func convertMethod(_ codeDomMethod: CodeMemberMethod, ignoreBody: Boolean = false) -> CGMethodDefinition { - - if !ignoreBody && codeDomMethod.Statements.Count > 0 { - throw Exception("convertMethod does not support converting method bodies yet.") - } - - let result = CGMethodDefinition(codeDomMethod.Name) - - for p: CodeParameterDeclarationExpression in codeDomMethod.Parameters { - let param = CGParameterDefinition(p.Name, convertTypeReference(p.`Type`) ?? CGPredefinedTypeReference.Void) - result.Parameters.Add(param); - } - - if let returnType = codeDomMethod.ReturnType { - result.ReturnType = convertTypeReference(codeDomMethod.ReturnType) - } - - return result - } - - public func convertConstructor(_ codeDomCtor: CodeConstructor, ignoreBody: Boolean = false) -> CGConstructorDefinition { - - if !ignoreBody && codeDomCtor.Statements.Count > 0 { - throw Exception("convertConstructor does not support converting constructor bodies yet.") - } - - let result = CGConstructorDefinition() - - for p: CodeParameterDeclarationExpression in codeDomCtor.Parameters { - let param = CGParameterDefinition(p.Name, convertTypeReference(p.`Type`) ?? CGPredefinedTypeReference.Void) - result.Parameters.Add(param); - } - - return result - } -} +import System.Collections.Generic +import System.Linq +import System.Text +import System.CodeDom + +public static class CodeDomToCG4 { + + /*public func convertUnit(_ codeDomUnit: CodeCompileUnit) -> CGCodeUnit? { + + if codeDomUnit.Namespaces.Count >= 1 { + var namespace = codeDomUnit.Namespaces[0]; + + let unit = CGCodeUnit(namespace.Name) + + for i: CodeNamespaceImport in namespace.Imports { + unit.Imports.Add(CGImport(i.Namespace)) + } + for t: CodeTypeDeclaration in namespace.Types { + if let newType = convertType(t) { + unit.Types.Add(newType) + } + } + for c: CodeCommentStatement in namespace.Comments { + unit.HeaderComment.Lines.Add(c.Comment.Text) + } + + // Process additinal namespaces + /*if codeDomUnit.Namespaces.Count > 1 { + for x in 1 ..< codeDomUnit.Namespaces.Count { + var namespace2 = codeDomUnit.Namespaces[x]; + + for i: CodeNamespaceImport in namespace2.Imports { + unit.Imports.Add(CGImport(i.Namespace)) + } + + } + // ToDo: handle additional namespaces? + }*/ + + return unit + } + + return nil + }*/ + + public func convertType(_ codeDomType: CodeTypeDeclaration, ignoreMembers: Boolean = false) -> CGTypeDefinition? { + + if !ignoreMembers && codeDomType.Members.Count > 0 { + throw Exception("convertType does not support converting members yet.") + } + + if codeDomType.IsClass { + let result = CGClassTypeDefinition(codeDomType.Name) + + for b: CodeTypeReference in codeDomType.BaseTypes { + if let ancestor = convertTypeReference(b) { + result.Ancestors.Add(ancestor) + } + } + + return result + } + + throw Exception("convertType does not support converting this kind of type yet.") + } + + public func convertTypeReference(_ codeDomType: CodeTypeReference) -> CGTypeReference? { + + if let codeDomArrayType = codeDomType.ArrayElementType { + if let arrayType = convertTypeReference(codeDomArrayType) { + var bounds = List() + for i in 0 ..< codeDomType.ArrayRank { + bounds.Add(CGArrayBounds()) + } + return CGArrayTypeReference(arrayType, bounds) + } + return nil + } else if codeDomType.UserData.Contains("OxygeneNullable") && String.EqualsIgnoringCaseInvariant(codeDomType.BaseType, "SYSTEM.NULLABLE`1") { + return convertTypeReference(codeDomType.TypeArguments.Item[0])?.NullableNotUnwrapped + } else { + return CGNamedTypeReference(codeDomType.BaseType) + } + } + + public func convertMethod(_ codeDomMethod: CodeMemberMethod, ignoreBody: Boolean = false) -> CGMethodDefinition { + + if !ignoreBody && codeDomMethod.Statements.Count > 0 { + throw Exception("convertMethod does not support converting method bodies yet.") + } + + let result = CGMethodDefinition(codeDomMethod.Name) + + for p: CodeParameterDeclarationExpression in codeDomMethod.Parameters { + let param = CGParameterDefinition(p.Name, convertTypeReference(p.`Type`) ?? CGPredefinedTypeReference.Void) + result.Parameters.Add(param); + } + + if let returnType = codeDomMethod.ReturnType { + result.ReturnType = convertTypeReference(codeDomMethod.ReturnType) + } + + return result + } + + public func convertConstructor(_ codeDomCtor: CodeConstructor, ignoreBody: Boolean = false) -> CGConstructorDefinition { + + if !ignoreBody && codeDomCtor.Statements.Count > 0 { + throw Exception("convertConstructor does not support converting constructor bodies yet.") + } + + let result = CGConstructorDefinition() + + for p: CodeParameterDeclarationExpression in codeDomCtor.Parameters { + let param = CGParameterDefinition(p.Name, convertTypeReference(p.`Type`) ?? CGPredefinedTypeReference.Void) + result.Parameters.Add(param); + } + + return result + } +} \ No newline at end of file diff --git a/Expressions.swift b/Expressions.swift index a836ba7..0d188ce 100644 --- a/Expressions.swift +++ b/Expressions.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -/* Expressions */ +/* Expressions */ public __abstract class CGExpression: CGStatement { } @@ -17,7 +13,7 @@ public class CGRawExpression : CGExpression { // not language-agnostic. obviosul init(lines.ToList()) }*/ public init(_ lines: String) { - Lines = lines.Replace("\r", "").Split("\n").ToList() + Lines = lines.Replace("\r", "").Split("\n").ToList() } } @@ -32,7 +28,7 @@ public class CGTypeReferenceExpression : CGExpression{ public class CGAssignedExpression: CGExpression { public var Value: CGExpression public var Inverted: Boolean = false - + public init(_ value: CGExpression) { Value = value } @@ -68,7 +64,7 @@ public class CGDefaultExpression: CGExpression { public class CGSelectorExpression: CGExpression { /* Cocoa only */ var Name: String - + public init(_ name: String) { Name = name } @@ -145,14 +141,14 @@ public class CGAnonymousTypeExpression : CGExpression { public var Kind: CGAnonymousTypeKind public var Ancestor: CGTypeReference? public var Members = List() - + public init(_ kind: CGAnonymousTypeKind) { Kind = kind } } public __abstract class CGAnonymousMemberDefinition : CGEntity{ - public var Name: String + public var Name: String public init(_ name: String) { Name = name @@ -190,12 +186,12 @@ public class CGIfThenElseExpression: CGExpression { // aka Ternary operator public var Condition: CGExpression public var IfExpression: CGExpression public var ElseExpression: CGExpression? - + public init(_ condition: CGExpression, _ ifExpression: CGExpression, _ elseExpression: CGExpression?) { Condition = condition IfExpression= ifExpression ElseExpression = elseExpression - } + } } /* @@ -227,7 +223,7 @@ public class CGPointerDereferenceExpression: CGExpression { public init(_ pointerExpression: CGExpression) { PointerExpression = pointerExpression - } + } } public class CGParenthesesExpression: CGExpression { @@ -251,7 +247,7 @@ public class CGUnaryOperatorExpression: CGExpression { Value = value OperatorString = operatorString } - + public static func NotExpression(_ value: CGExpression) -> CGUnaryOperatorExpression { return CGUnaryOperatorExpression(value, CGUnaryOperatorKind.Not) } @@ -270,7 +266,7 @@ public class CGBinaryOperatorExpression: CGExpression { public var RighthandValue: CGExpression public var Operator: CGBinaryOperatorKind? // for standard operators public var OperatorString: String? // for custom operators - + public init(_ lefthandValue: CGExpression, _ righthandValue: CGExpression, _ `operator`: CGBinaryOperatorKind) { LefthandValue = lefthandValue RighthandValue = righthandValue @@ -328,9 +324,9 @@ public enum CGBinaryOperatorKind { /* Literal Expressions */ -public class CGNamedIdentifierExpression: CGExpression { +public class CGNamedIdentifierExpression: CGExpression { public var Name: String - + public init(_ name: String) { Name = name } @@ -357,7 +353,7 @@ public __abstract class CGLanguageAgnosticLiteralExpression: CGExpression { public class CGStringLiteralExpression: CGLiteralExpression { public var Value: String = "" - + public static lazy let Empty: CGStringLiteralExpression = "".AsLiteralExpression() public static lazy let Space: CGStringLiteralExpression = " ".AsLiteralExpression() @@ -365,7 +361,7 @@ public class CGStringLiteralExpression: CGLiteralExpression { } public init(_ value: String) { Value = value - } + } } public class CGCharacterLiteralExpression: CGLiteralExpression { @@ -378,12 +374,12 @@ public class CGCharacterLiteralExpression: CGLiteralExpression { } public init(_ value: Char) { Value = value - } + } } public class CGIntegerLiteralExpression: CGLanguageAgnosticLiteralExpression { public var Value: Int64 = 0 - public var Base = 10 + public var Base = 10 public var NumberKind: CGNumberKind? public static lazy let Zero: CGIntegerLiteralExpression = 0.AsLiteralExpression() @@ -399,11 +395,11 @@ public class CGIntegerLiteralExpression: CGLanguageAgnosticLiteralExpression { } override func StringRepresentation() -> String { - return Sugar.Convert.ToString(Value, 10) + return Convert.ToString(Value, 10) } - + internal func StringRepresentation(# base: Int32) -> String { - return Sugar.Convert.ToString(Value, base) + return Convert.ToString(Value, base) } } @@ -413,9 +409,9 @@ public class CGFloatLiteralExpression: CGLanguageAgnosticLiteralExpression { public private(set) var StringValue: String? public var NumberKind: CGNumberKind? public var Base = 10 // Swift only - + public static lazy let Zero: CGFloatLiteralExpression = CGFloatLiteralExpression(0) - + public init() { } public init(_ value: Double) { @@ -452,7 +448,7 @@ public class CGFloatLiteralExpression: CGLanguageAgnosticLiteralExpression { if DoubleValue != nil { throw Exception("base 16 (Hex) float literals with double value are not currently supported.") } else if let value = IntegerValue { - return Sugar.Convert.ToString(value, base)+".0" + return Convert.ToString(value, base)+".0" } else if let value = StringValue { if value.IndexOf(".") > -1 || value.ToLower().IndexOf("p") > -1 { return value @@ -474,10 +470,10 @@ public enum CGNumberKind { public class CGBooleanLiteralExpression: CGLanguageAgnosticLiteralExpression { public let Value: Boolean - + public static lazy let True = CGBooleanLiteralExpression(true) public static lazy let False = CGBooleanLiteralExpression(false) - + public convenience init() { init(false) } @@ -495,10 +491,10 @@ public class CGBooleanLiteralExpression: CGLanguageAgnosticLiteralExpression { } public class CGArrayLiteralExpression: CGExpression { - public var Elements: List - public var ElementType: CGTypeReference? //c++ only at this moment + public var Elements: List + public var ElementType: CGTypeReference? //c++ only at this moment public var ArrayKind: CGArrayKind = .Dynamic - + public init() { Elements = List() } @@ -517,9 +513,9 @@ public class CGArrayLiteralExpression: CGExpression { } public class CGSetLiteralExpression: CGExpression { - public var Elements: List + public var Elements: List public var ElementType: CGTypeReference? - + public init() { Elements = List() } @@ -536,9 +532,9 @@ public class CGSetLiteralExpression: CGExpression { } public class CGDictionaryLiteralExpression: CGExpression { /* Swift only, currently */ - public var Keys: List - public var Values: List - + public var Keys: List + public var Values: List + public init() { Keys = List() Values = List() @@ -554,7 +550,7 @@ public class CGDictionaryLiteralExpression: CGExpression { /* Swift only, curren public class CGTupleLiteralExpression : CGExpression { public var Members: List - + public init(_ members: List) { Members = members } @@ -597,7 +593,7 @@ public class CGNewInstanceExpression : CGExpression { public class CGDestroyInstanceExpression : CGExpression { public var Instance: CGExpression; - + public init(_ instance: CGExpression) { Instance = instance; } @@ -661,7 +657,7 @@ public class CGMethodCallExpression : CGMemberAccessExpression{ Parameters = parameters } else { Parameters = List() - } + } } public convenience init(_ callSite: CGExpression?, _ name: String, _ parameters: CGCallParameter...) { init(callSite, name, List(parameters)) @@ -677,7 +673,7 @@ public class CGPropertyAccessExpression: CGMemberAccessExpression { Parameters = parameters } else { Parameters = List() - } + } } public convenience init(_ callSite: CGExpression?, _ name: String, _ parameters: CGCallParameter...) { init(callSite, name, List(parameters)) @@ -689,7 +685,7 @@ public class CGCallParameter: CGEntity { public var Value: CGExpression public var Modifier: CGParameterModifierKind = .In public var EllipsisParameter: Boolean = false // used mainly for Objective-C, wioch needs a different syntax when passing elipsis paframs - + public init(_ value: CGExpression) { Value = value } @@ -711,4 +707,4 @@ public class CGArrayElementAccessExpression: CGExpression { public convenience init(_ array: CGExpression, _ parameters: CGExpression...) { init(array, parameters.ToList()) } -} +} \ No newline at end of file diff --git a/Extensions.swift b/Extensions.swift index 595b776..774f4d7 100644 --- a/Extensions.swift +++ b/Extensions.swift @@ -1,8 +1,6 @@ -import Sugar +#if !FAKESUGAR +public extension RemObjects.Elements.RTL.String { -#if !FAKESUGAR -public extension Sugar.String { - public func AsTypeReference() -> CGTypeReference { return CGNamedTypeReference(self) } @@ -18,15 +16,15 @@ public extension Sugar.String { public func AsTypeReferenceExpression() -> CGTypeReferenceExpression { return CGTypeReferenceExpression(CGNamedTypeReference(self)) } - + public func AsTypeReferenceExpression(defaultNullability: CGTypeNullabilityKind) -> CGTypeReferenceExpression { return CGTypeReferenceExpression(CGNamedTypeReference(self, defaultNullability: defaultNullability)) } - + public func AsNamedIdentifierExpression() -> CGNamedIdentifierExpression { return CGNamedIdentifierExpression(self) } - + public func AsLiteralExpression() -> CGStringLiteralExpression { return CGStringLiteralExpression(self) } @@ -42,7 +40,7 @@ public extension Sugar.String { #endif public extension RemObjects.Elements.System.String { - + public func AsTypeReference() -> CGTypeReference { return CGNamedTypeReference(self) } @@ -58,15 +56,15 @@ public extension RemObjects.Elements.System.String { public func AsTypeReferenceExpression() -> CGTypeReferenceExpression { return CGTypeReferenceExpression(CGNamedTypeReference(self)) } - + public func AsTypeReferenceExpression(defaultNullability: CGTypeNullabilityKind) -> CGTypeReferenceExpression { return CGTypeReferenceExpression(CGNamedTypeReference(self, defaultNullability: defaultNullability)) } - + public func AsNamedIdentifierExpression() -> CGNamedIdentifierExpression { return CGNamedIdentifierExpression(self) } - + public func AsLiteralExpression() -> CGStringLiteralExpression { return CGStringLiteralExpression(self) } @@ -118,15 +116,15 @@ public extension CGExpression { public func AsReturnStatement() -> CGReturnStatement { return CGReturnStatement(self) } - + public func AsCallParameter() -> CGCallParameter { return CGCallParameter(self) } - + public func AsCallParameter(_ name: String) -> CGCallParameter { return CGCallParameter(self, name) } - + public func AsEllipsisCallParameter() -> CGCallParameter { let result = CGCallParameter(self) result.EllipsisParameter = true diff --git a/Statements.swift b/Statements.swift index 3ac53c4..e71aeca 100644 --- a/Statements.swift +++ b/Statements.swift @@ -1,348 +1,344 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -/* Statements */ - -public __abstract class CGStatement: CGEntity { -} - -public __abstract class CGBaseMultilineStatement : CGStatement { - public var Lines: List - - public init() { - Lines = List() - } - public init(_ lines: List) { - Lines = lines - } - public init(_ lines: String) { - Lines = lines.Replace("\r", "").Split("\n").ToList() - } -} - -public class CGRawStatement : CGBaseMultilineStatement { // not language-agnostic. obviosuly. -} - -public class CGCommentStatement : CGBaseMultilineStatement { -} - -public class CGSingleLineCommentStatement : CGStatement { - public let Comment: String - - public init(_ comment: String) { - Comment = comment.Trim() - } -} - -public class CGUnsupportedStatement : CGCommentStatement { - init() { - super.init("Unsupported statement.") - } - init(_ statement: String) { - super.init("Unsupported statement: \(statement)") - } -} - -public __abstract class CGBlockStatement : CGStatement { - public var Statements: List - - public init() { - Statements = List() - } - public init(_ statements: List) { - Statements = statements - } - public convenience init(_ statements: CGStatement...) { - init(statements.ToList()) - } -} - -public __abstract class CGNestingStatement : CGStatement { - public var NestedStatement: CGStatement - - public init(_ nestedStatement: CGStatement) { - NestedStatement = nestedStatement - } -} - -public class CGCodeCommentStatement : CGStatement { - public var CommentedOutStatement: CGStatement - - public init(_ statement: CGStatement) { - CommentedOutStatement = statement - } -} - -public class CGConditionalBlockStatement : CGBlockStatement { - public var Condition: CGConditionalDefine - public var ElseStatements: List? - - public init(_ condition: CGConditionalDefine) { - Condition = condition - Statements = List() - } - - public init(_ condition: CGConditionalDefine, _ statements: List) { - Condition = condition - Statements = statements - } - - public convenience init(_ condition: CGConditionalDefine, _ statements: CGStatement...) { - init(condition, statements.ToList()) - } - - public init(_ condition: CGConditionalDefine, _ statements: List, _ elseStatements: List) { - Condition = condition - Statements = statements - ElseStatements = elseStatements - } -} - -public class CGBeginEndBlockStatement : CGBlockStatement { //"begin/end" or "{/}" -} - -public class CGIfThenElseStatement: CGStatement { - public var Condition: CGExpression - public var IfStatement: CGStatement - public var ElseStatement: CGStatement? - - public init(_ condition: CGExpression, _ ifStatement: CGStatement, _ elseStatement: CGStatement? = nil) { - Condition = condition - IfStatement = ifStatement - ElseStatement = elseStatement - } -} - -public enum CGLoopDirectionKind { - case Forward - case Backward -} - -public class CGForToLoopStatement: CGNestingStatement { - public var LoopVariableName: String - public var LoopVariableType: CGTypeReference? // nil means it won't be declared, just used - public var StartValue: CGExpression - public var EndValue: CGExpression - public var Direction: CGLoopDirectionKind = .Forward - - public init(_ loopVariableName: String, _ loopVariableType: CGTypeReference, _ startValue: CGExpression, _ endValue: CGExpression, _ statement: CGStatement) { - super.init(statement) - LoopVariableName = loopVariableName - LoopVariableType = loopVariableType - StartValue = startValue - EndValue = endValue - } -} - -public class CGForEachLoopStatement: CGNestingStatement { - public var LoopVariableName: String - public var LoopVariableType: CGTypeReference //not all languages require this but some do, so we'll require it - public var Collection: CGExpression - - public init(_ loopVariableName: String, _ loopVariableType: CGTypeReference, _ collection: CGExpression, _ statement: CGStatement) { - super.init(statement) - LoopVariableName = loopVariableName - LoopVariableType = loopVariableType - Collection = collection - } -} - -public class CGWhileDoLoopStatement: CGNestingStatement { - public var Condition: CGExpression - - public init(_ condition: CGExpression, _ statement: CGStatement) { - super.init(statement) - Condition = condition - } -} - -public class CGDoWhileLoopStatement: CGBlockStatement { // also "repeat/until" - public var Condition: CGExpression - - public init(_ condition: CGExpression, _ statements: List) { - super.init(statements) - Condition = condition - } - public convenience init(_ condition: CGExpression, _ statements: CGStatement...) { - init(condition, statements.ToList()) - } -} - -public class CGInfiniteLoopStatement: CGNestingStatement {} - -public class CGSwitchStatement: CGStatement { - public var Expression: CGExpression - public var Cases: List - public var DefaultCase: List? - - public init(_ expression: CGExpression, _ cases: List, _ defaultCase: List? = nil) { - Expression = expression - DefaultCase = defaultCase - if let cases = cases { - Cases = cases - } else { - Cases = List() - } - } - public convenience init(_ expression: CGExpression, _ cases: CGSwitchStatementCase[], _ defaultCase: List? = nil) { - init(expression, cases.ToList(), defaultCase) - } -} - -public class CGSwitchStatementCase : CGEntity { - public var CaseExpressions: List - public var Statements: List - - public init(_ caseExpression: CGExpression, _ statements: List) { - CaseExpressions = List() - CaseExpressions.Add(caseExpression) - Statements = statements - } - public init(_ caseExpressions: List, _ statements: List) { - CaseExpressions = caseExpressions - Statements = statements - } - public convenience init(_ caseExpression: CGExpression, _ statements: CGStatement...) { - init(caseExpression, statements.ToList()) - } - public convenience init(_ caseExpressions: List, _ statements: CGStatement...) { - init(caseExpressions, statements.ToList()) - } -} - -public class CGLockingStatement: CGNestingStatement { - var Expression: CGExpression - - public init(_ expression: CGExpression, _ nestedStatement: CGStatement) { - super.init(nestedStatement) - Expression = expression - } -} - -public class CGUsingStatement: CGNestingStatement { - public var Name: String - public var `Type`: CGTypeReference? - public var Value: CGExpression - - public init(_ name: String, _ value: CGExpression, _ nestedStatement: CGStatement) { - super.init(nestedStatement) - Name = name - Value = value - } -} - -public class CGAutoReleasePoolStatement: CGNestingStatement {} - -public class CGTryFinallyCatchStatement: CGBlockStatement { - public var FinallyStatements = List() - public var CatchBlocks = List() -} - -public class CGCatchBlockStatement: CGBlockStatement { - public let Name: String? - public let `Type`: CGTypeReference? - public var Filter: CGExpression? - - public init() { - Name = nil - Type = nil - } - public init(_ name: String) { - Name = name - Type = nil - } - public init(_ name: String, _ type: CGTypeReference) { - Name = name - `Type` = type - } -} - -/* Simple Statements */ - -public class CGReturnStatement: CGStatement { - public var Value: CGExpression? - - public init() { - } - public init(_ value: CGExpression) { - Value = value - } -} - -public class CGYieldStatement: CGStatement { - public var Value: CGExpression - - public init(_ value: CGExpression) { - Value = value - } -} - -public class CGThrowStatement: CGStatement { - var Exception: CGExpression? - - public init() { - } - public init(_ exception: CGExpression?) { - Exception = exception - } -} - -public class CGBreakStatement: CGStatement {} - -public class CGContinueStatement: CGStatement {} - -public class CGEmptyStatement: CGStatement {} - -public class CGConstructorCallStatement : CGStatement { - public var CallSite: CGExpression = CGSelfExpression.`Self` //Should be set to CGSelfExpression or CGInheritedExpression - public var ConstructorName: String? // an optionally be provided for languages that support named .ctors - public var Parameters: List - public var PropertyInitializers = List() // for Oxygene extnded .ctor calls - - public init(_ callSite: CGExpression, _ parameters: List?) { - CallSite = callSite - if let parameters = parameters { - Parameters = parameters - } else { - Parameters = List() - } - } - public convenience init(_ callSite: CGExpression, _ parameters: CGCallParameter...) { - init(callSite, parameters.ToList()) - } -} - -/* Operator statements */ - -public class CGVariableDeclarationStatement: CGStatement { - public var Name: String - public var `Type`: CGTypeReference? - public var Value: CGExpression? - public var Constant = false - public var ReadOnly = false - - public init(_ name: String, _ type: CGTypeReference?, _ value: CGExpression? = nil) { - Name = name - `Type` = type - Value = value - } - /*public convenience init(_ name: String, _ type: CGTypeReference?, _ value: CGExpression? = nil, constant: Boolean) { - init(name, type, value) - Constant = constant - }*/ - public convenience init(_ name: String, _ type: CGTypeReference?, _ value: CGExpression? = nil, readOnly: Boolean) { - init(name, type, value) - ReadOnly = readOnly - } -} - -public class CGAssignmentStatement: CGStatement { - public var Target: CGExpression - public var Value: CGExpression - - public init(_ target: CGExpression, _ value: CGExpression) { - Target = target - Value = value - } +/* Statements */ + +public __abstract class CGStatement: CGEntity { +} + +public __abstract class CGBaseMultilineStatement : CGStatement { + public var Lines: List + + public init() { + Lines = List() + } + public init(_ lines: List) { + Lines = lines + } + public init(_ lines: String) { + Lines = lines.Replace("\r", "").Split("\n").ToList() + } +} + +public class CGRawStatement : CGBaseMultilineStatement { // not language-agnostic. obviosuly. +} + +public class CGCommentStatement : CGBaseMultilineStatement { +} + +public class CGSingleLineCommentStatement : CGStatement { + public let Comment: String + + public init(_ comment: String) { + Comment = comment.Trim() + } +} + +public class CGUnsupportedStatement : CGCommentStatement { + init() { + super.init("Unsupported statement.") + } + init(_ statement: String) { + super.init("Unsupported statement: \(statement)") + } +} + +public __abstract class CGBlockStatement : CGStatement { + public var Statements: List + + public init() { + Statements = List() + } + public init(_ statements: List) { + Statements = statements + } + public convenience init(_ statements: CGStatement...) { + init(statements.ToList()) + } +} + +public __abstract class CGNestingStatement : CGStatement { + public var NestedStatement: CGStatement + + public init(_ nestedStatement: CGStatement) { + NestedStatement = nestedStatement + } +} + +public class CGCodeCommentStatement : CGStatement { + public var CommentedOutStatement: CGStatement + + public init(_ statement: CGStatement) { + CommentedOutStatement = statement + } +} + +public class CGConditionalBlockStatement : CGBlockStatement { + public var Condition: CGConditionalDefine + public var ElseStatements: List? + + public init(_ condition: CGConditionalDefine) { + Condition = condition + Statements = List() + } + + public init(_ condition: CGConditionalDefine, _ statements: List) { + Condition = condition + Statements = statements + } + + public convenience init(_ condition: CGConditionalDefine, _ statements: CGStatement...) { + init(condition, statements.ToList()) + } + + public init(_ condition: CGConditionalDefine, _ statements: List, _ elseStatements: List) { + Condition = condition + Statements = statements + ElseStatements = elseStatements + } +} + +public class CGBeginEndBlockStatement : CGBlockStatement { //"begin/end" or "{/}" +} + +public class CGIfThenElseStatement: CGStatement { + public var Condition: CGExpression + public var IfStatement: CGStatement + public var ElseStatement: CGStatement? + + public init(_ condition: CGExpression, _ ifStatement: CGStatement, _ elseStatement: CGStatement? = nil) { + Condition = condition + IfStatement = ifStatement + ElseStatement = elseStatement + } +} + +public enum CGLoopDirectionKind { + case Forward + case Backward +} + +public class CGForToLoopStatement: CGNestingStatement { + public var LoopVariableName: String + public var LoopVariableType: CGTypeReference? // nil means it won't be declared, just used + public var StartValue: CGExpression + public var EndValue: CGExpression + public var Direction: CGLoopDirectionKind = .Forward + + public init(_ loopVariableName: String, _ loopVariableType: CGTypeReference, _ startValue: CGExpression, _ endValue: CGExpression, _ statement: CGStatement) { + super.init(statement) + LoopVariableName = loopVariableName + LoopVariableType = loopVariableType + StartValue = startValue + EndValue = endValue + } +} + +public class CGForEachLoopStatement: CGNestingStatement { + public var LoopVariableName: String + public var LoopVariableType: CGTypeReference //not all languages require this but some do, so we'll require it + public var Collection: CGExpression + + public init(_ loopVariableName: String, _ loopVariableType: CGTypeReference, _ collection: CGExpression, _ statement: CGStatement) { + super.init(statement) + LoopVariableName = loopVariableName + LoopVariableType = loopVariableType + Collection = collection + } +} + +public class CGWhileDoLoopStatement: CGNestingStatement { + public var Condition: CGExpression + + public init(_ condition: CGExpression, _ statement: CGStatement) { + super.init(statement) + Condition = condition + } +} + +public class CGDoWhileLoopStatement: CGBlockStatement { // also "repeat/until" + public var Condition: CGExpression + + public init(_ condition: CGExpression, _ statements: List) { + super.init(statements) + Condition = condition + } + public convenience init(_ condition: CGExpression, _ statements: CGStatement...) { + init(condition, statements.ToList()) + } +} + +public class CGInfiniteLoopStatement: CGNestingStatement {} + +public class CGSwitchStatement: CGStatement { + public var Expression: CGExpression + public var Cases: List + public var DefaultCase: List? + + public init(_ expression: CGExpression, _ cases: List, _ defaultCase: List? = nil) { + Expression = expression + DefaultCase = defaultCase + if let cases = cases { + Cases = cases + } else { + Cases = List() + } + } + public convenience init(_ expression: CGExpression, _ cases: CGSwitchStatementCase[], _ defaultCase: List? = nil) { + init(expression, cases.ToList(), defaultCase) + } +} + +public class CGSwitchStatementCase : CGEntity { + public var CaseExpressions: List + public var Statements: List + + public init(_ caseExpression: CGExpression, _ statements: List) { + CaseExpressions = List() + CaseExpressions.Add(caseExpression) + Statements = statements + } + public init(_ caseExpressions: List, _ statements: List) { + CaseExpressions = caseExpressions + Statements = statements + } + public convenience init(_ caseExpression: CGExpression, _ statements: CGStatement...) { + init(caseExpression, statements.ToList()) + } + public convenience init(_ caseExpressions: List, _ statements: CGStatement...) { + init(caseExpressions, statements.ToList()) + } +} + +public class CGLockingStatement: CGNestingStatement { + var Expression: CGExpression + + public init(_ expression: CGExpression, _ nestedStatement: CGStatement) { + super.init(nestedStatement) + Expression = expression + } +} + +public class CGUsingStatement: CGNestingStatement { + public var Name: String + public var `Type`: CGTypeReference? + public var Value: CGExpression + + public init(_ name: String, _ value: CGExpression, _ nestedStatement: CGStatement) { + super.init(nestedStatement) + Name = name + Value = value + } +} + +public class CGAutoReleasePoolStatement: CGNestingStatement {} + +public class CGTryFinallyCatchStatement: CGBlockStatement { + public var FinallyStatements = List() + public var CatchBlocks = List() +} + +public class CGCatchBlockStatement: CGBlockStatement { + public let Name: String? + public let `Type`: CGTypeReference? + public var Filter: CGExpression? + + public init() { + Name = nil + Type = nil + } + public init(_ name: String) { + Name = name + Type = nil + } + public init(_ name: String, _ type: CGTypeReference) { + Name = name + `Type` = type + } +} + +/* Simple Statements */ + +public class CGReturnStatement: CGStatement { + public var Value: CGExpression? + + public init() { + } + public init(_ value: CGExpression) { + Value = value + } +} + +public class CGYieldStatement: CGStatement { + public var Value: CGExpression + + public init(_ value: CGExpression) { + Value = value + } +} + +public class CGThrowStatement: CGStatement { + var Exception: CGExpression? + + public init() { + } + public init(_ exception: CGExpression?) { + Exception = exception + } +} + +public class CGBreakStatement: CGStatement {} + +public class CGContinueStatement: CGStatement {} + +public class CGEmptyStatement: CGStatement {} + +public class CGConstructorCallStatement : CGStatement { + public var CallSite: CGExpression = CGSelfExpression.`Self` //Should be set to CGSelfExpression or CGInheritedExpression + public var ConstructorName: String? // an optionally be provided for languages that support named .ctors + public var Parameters: List + public var PropertyInitializers = List() // for Oxygene extnded .ctor calls + + public init(_ callSite: CGExpression, _ parameters: List?) { + CallSite = callSite + if let parameters = parameters { + Parameters = parameters + } else { + Parameters = List() + } + } + public convenience init(_ callSite: CGExpression, _ parameters: CGCallParameter...) { + init(callSite, parameters.ToList()) + } +} + +/* Operator statements */ + +public class CGVariableDeclarationStatement: CGStatement { + public var Name: String + public var `Type`: CGTypeReference? + public var Value: CGExpression? + public var Constant = false + public var ReadOnly = false + + public init(_ name: String, _ type: CGTypeReference?, _ value: CGExpression? = nil) { + Name = name + `Type` = type + Value = value + } + /*public convenience init(_ name: String, _ type: CGTypeReference?, _ value: CGExpression? = nil, constant: Boolean) { + init(name, type, value) + Constant = constant + }*/ + public convenience init(_ name: String, _ type: CGTypeReference?, _ value: CGExpression? = nil, readOnly: Boolean) { + init(name, type, value) + ReadOnly = readOnly + } +} + +public class CGAssignmentStatement: CGStatement { + public var Target: CGExpression + public var Value: CGExpression + + public init(_ target: CGExpression, _ value: CGExpression) { + Target = target + Value = value + } } \ No newline at end of file diff --git a/TypeDefinitions.swift b/TypeDefinitions.swift index b164d96..c02cfe3 100644 --- a/TypeDefinitions.swift +++ b/TypeDefinitions.swift @@ -1,489 +1,485 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -/* Types */ - -public enum CGTypeVisibilityKind { - case Unspecified - case Unit - case Assembly - case Public -} - -public __abstract class CGTypeDefinition : CGEntity { - public var GenericParameters = List() - public var Name: String - public var Members = List() - public var Visibility: CGTypeVisibilityKind = .Unspecified //in delphi, types with .Unit will be put into implementation section - public var Static = false - public var Sealed = false - public var Abstract = false - public var Comment: CGCommentStatement? - public var Attributes = List() - public var Condition: CGConditionalDefine? - - public init(_ name: String) { - Name = name - } -} - -public final class CGGlobalTypeDefinition : CGTypeDefinition { - private init() { - super.init("") - Static = true - } - - public static lazy let GlobalType = CGGlobalTypeDefinition() -} - -public class CGTypeAliasDefinition : CGTypeDefinition { - public var ActualType: CGTypeReference - - public init(_ name: String, _ actualType: CGTypeReference) { - super.init(name) - ActualType = actualType - } -} - -public class CGBlockTypeDefinition : CGTypeDefinition { - public var Parameters = List() - public var ReturnType: CGTypeReference? - public var IsPlainFunctionPointer = false -} - -public class CGEnumTypeDefinition : CGTypeDefinition { - public var BaseType: CGTypeReference? -} - -public __abstract class CGClassOrStructTypeDefinition : CGTypeDefinition { - public var Ancestors: List - public var ImplementedInterfaces: List - public var Partial = false - - public init(_ name: String) { - super.init(name) - Ancestors = List() - ImplementedInterfaces = List() - } - public init(_ name: String, _ ancestor: CGTypeReference) { - super.init(name) - Ancestors = List() - Ancestors.Add(ancestor) - ImplementedInterfaces = List() - } - public init(_ name: String, _ ancestors: List) { - super.init(name) - Ancestors = ancestors - ImplementedInterfaces = List() - } - public init(_ name: String, _ ancestor: CGTypeReference, _ interfaces: List) { - super.init(name) - Ancestors = List() - Ancestors.Add(ancestor) - ImplementedInterfaces = interfaces - } - public init(_ name: String, _ ancestors: List, _ interfaces: List) { - super.init(name) - Ancestors = ancestors - ImplementedInterfaces = interfaces - } -} - -public class CGClassTypeDefinition : CGClassOrStructTypeDefinition { -} - -public class CGStructTypeDefinition : CGClassOrStructTypeDefinition { -} - -public class CGInterfaceTypeDefinition : CGClassOrStructTypeDefinition { - public var InterfaceGuid: Guid?;// legacy delphi only. declaration is : - // type interfaceName = interface (ancestorInterface) ['{GUID}'] memberList end; -} - -public class CGExtensionTypeDefinition : CGClassOrStructTypeDefinition { -} - -/* Type members */ - -public enum CGMemberVisibilityKind { - case Unspecified - case Private - case Unit - case UnitOrProtected - case UnitAndProtected - case Assembly - case AssemblyOrProtected - case AssemblyAndProtected - case Protected - case Public - case Published /* Delphi only */ -} - -public enum CGMemberVirtualityKind { - case None - case Virtual - case Abstract - case Override - case Final - case Reintroduce -} - -public __abstract class CGMemberDefinition: CGEntity { - public var Name: String - public var Visibility: CGMemberVisibilityKind = .Private - public var Virtuality: CGMemberVirtualityKind = .None - public var Static = false - public var Overloaded = false - public var Locked = false /* Oxygene only */ - public var LockedOn: CGExpression? /* Oxygene only */ - public var Comment: CGCommentStatement? - public var Attributes = List() - public var Condition: CGConditionalDefine? - public var ThrownExceptions: List? // nil means unknown; empty list means known to not throw. - - public init(_ name: String) { - Name = name - } -} - -public class CGEnumValueDefinition: CGMemberDefinition { - public var Value: CGExpression? - - public init(_ name: String) { - super.init(name) - } - public convenience init(_ name: String, _ value: CGExpression) { - init(name) - Value = value - } -} - -// -// Methods & Co -// - -public enum CGCallingConventionKind { - case CDecl /* C++ and Delphi */ - case Pascal /* C++ and Delphi */ - case StdCall /* C++ and Delphi */ - case FastCall /* C++ */ - case SafeCall /* C++ and Delphi */ - case ClrCall /* VC++ */ - case ThisCall /* VC++ */ - case VectorCall /* VC++ */ - case Register /* C++Builder and Delphi */ -} - -public __abstract class CGMethodLikeMemberDefinition: CGMemberDefinition { - public var Parameters = List() - public var ReturnType: CGTypeReference? - public var Inline = false - public var External = false - public var Empty = false - public var Partial = false /* Oxygene only */ - public var Async = false /* Oxygene only */ - public var Awaitable = false /* C# only */ - public var Throws = false /* Swift and Java only */ - public var Optional = false /* Swift only */ - public var CallingConvention: CGCallingConventionKind? /* Delphi and C++Builder only */ - public var Statements: List - public var LocalVariables: List? // Legacy Delphi only. - - public init(_ name: String) { - super.init(name) - Statements = List() - } - public init(_ name: String, _ statements: List) { - super.init(name) - Statements = statements - } - public init(_ name: String, _ statements: CGStatement...) { - super.init(name) - Statements = statements.ToList() - } -} - -public class CGMethodDefinition: CGMethodLikeMemberDefinition { - public var GenericParameters: List? -} - -public class CGConstructorDefinition: CGMethodLikeMemberDefinition { - public var Nullability = CGTypeNullabilityKind.NotNullable /* Swift only. currently. */ - - public init() { - super.init("") - } - public init(_ name: String, _ statements: List) { - var name = name - if name == ".ctor" || name == ".cctor" { - name = "" - } - super.init(name, statements) - } - convenience public init(_ name: String, _ statements: CGStatement...) { - init(name, statements.ToList()) - } -} - -public class CGDestructorDefinition: CGMethodLikeMemberDefinition { -} - -public class CGFinalizerDefinition: CGMethodLikeMemberDefinition { - public init() { - super.init("Finalizer") - } - public init(_ name: String, _ statements: List) { - super.init("Finalizer", statements) - } - public init(_ name: String, _ statements: CGStatement...) { - super.init("Finalizer", statements.ToList()) - } -} - -public class CGCustomOperatorDefinition: CGMethodLikeMemberDefinition { -} - -// -// Fields & Co -// - -public __abstract class CGFieldLikeMemberDefinition: CGMemberDefinition { - public var `Type`: CGTypeReference? - - public init(_ name: String) { - super.init(name) - } - public init(_ name: String, _ type: CGTypeReference) { - super.init(name) - `Type` = type - } -} - -public __abstract class CGFieldOrPropertyDefinition: CGFieldLikeMemberDefinition { - public var Initializer: CGExpression? - public var ReadOnly = false - public var WriteOnly = false -} - -public class CGFieldDefinition: CGFieldOrPropertyDefinition { - public var Constant = false -} - -public class CGPropertyDefinition: CGFieldOrPropertyDefinition { - public var Lazy = false - public var Atomic = false - public var Dynamic = false - public var Default = false - public var Parameters = List() - public var GetStatements: List? - public var SetStatements: List? - public var GetExpression: CGExpression? - public var SetExpression: CGExpression? - public var GetterVisibility: CGMemberVisibilityKind? - public var SetterVisibility: CGMemberVisibilityKind? - - public init(_ name: String) { - super.init(name) - } - public init(_ name: String, _ type: CGTypeReference) { - super.init(name, type) - } - public convenience init(_ name: String, _ type: CGTypeReference, _ getStatements: List, _ setStatements: List? = nil) { - init(name, type) - GetStatements = getStatements - SetStatements = setStatements - } - public convenience init(_ name: String, _ type: CGTypeReference, _ getStatements: CGStatement[], _ setStatements: CGStatement[]? = nil) { - init(name, type, getStatements.ToList(), setStatements?.ToList()) - } - public convenience init(_ name: String, _ type: CGTypeReference, _ getExpression: CGExpression, _ setExpression: CGExpression? = nil) { - init(name, type) - GetExpression = getExpression - SetExpression = setExpression - } - - internal func GetterMethodDefinition(`prefix`: String = "get__") -> CGMethodDefinition? { - if let getStatements = GetStatements, let type = `Type` { - let method = CGMethodDefinition(`prefix`+Name, getStatements) - method.ReturnType = type - method.Parameters = Parameters - method.Static = Static - return method - } else if let getExpression = GetExpression, let type = `Type` { - let method = CGMethodDefinition(`prefix`+Name) - method.ReturnType = type - method.Parameters = Parameters - method.Statements.Add(getExpression.AsReturnStatement()) - method.Static = Static - return method - } - return nil - } - - public static let MAGIC_VALUE_PARAMETER_NAME = "___value___" - - internal func SetterMethodDefinition(`prefix`: String = "set__") -> CGMethodDefinition? { - if let setStatements = SetStatements, let type = `Type` { - let method = CGMethodDefinition(`prefix`+Name, setStatements) - method.Parameters.AddRange(Parameters) - method.Parameters.Add(CGParameterDefinition(MAGIC_VALUE_PARAMETER_NAME, type)) - return method - } else if let setExpression = SetExpression, let type = `Type` { - let method = CGMethodDefinition(`prefix`+Name) - method.Parameters.AddRange(Parameters) - method.Parameters.Add(CGParameterDefinition(MAGIC_VALUE_PARAMETER_NAME, type)) - method.Statements.Add(CGAssignmentStatement(setExpression, CGLocalVariableAccessExpression(MAGIC_VALUE_PARAMETER_NAME))) - return method - } - return nil - } - - public var IsShortcutProperty: Boolean { get { return GetStatements == nil && SetStatements == nil && GetExpression == nil && SetExpression == nil } } -} - -public class CGEventDefinition: CGFieldLikeMemberDefinition { - public var AddStatements: List? - public var RemoveStatements: List? - //public var RaiseStatements: List? - - public init(_ name: String, _ type: CGTypeReference) { - super.init(name, type) - } - public convenience init(_ name: String, _ type: CGTypeReference, _ addStatements: List, _ removeStatements: List/*, _ raiseStatements: List? = nil*/) { - init(name, type) - AddStatements = addStatements - RemoveStatements = removeStatements - //RaiseStatements = raiseStatements - } - - internal func AddMethodDefinition() -> CGMethodDefinition? { - if let addStatements = AddStatements, let type = `Type` { - let method = CGMethodDefinition("add__"+Name, addStatements) - method.Parameters.Add(CGParameterDefinition("___value", type)) - return method - } - return nil - } - - internal func RemoveMethodDefinition() -> CGMethodDefinition? { - if let removeStatements = RemoveStatements, let type = `Type` { - let method = CGMethodDefinition("remove__"+Name, removeStatements) - method.Parameters.Add(CGParameterDefinition("___value", type)) - return method - } - return nil - } - - /*internal func RaiseMethodDefinition() -> CGMethodDefinition? { - if let raiseStatements = RaiseStatements, type = `Type` { - let method = CGMethodDefinition("raise__"+Name, raisetatements) - //todo: this would need the same parameters as the block, which we don't have - return method - } - return nil - }*/ -} - -public class CGNestedTypeDefinition: CGMemberDefinition { - public var `Type`: CGTypeDefinition - - public init(_ type: CGTypeDefinition) { - super.init(type.Name) - `Type` = type - } -} - -// -// Parameters -// - -public enum CGParameterModifierKind { - case In - case Out - case Var - case Const - case Params -} - -public class CGParameterDefinition : CGEntity { - public var Name: String - public var ExternalName: String? // Swift and Cocoa only - public var `Type`: CGTypeReference - public var Modifier: CGParameterModifierKind = .In - public var DefaultValue: CGExpression? - - public init(_ name: String, _ type: CGTypeReference) { - Name = name - `Type` = type - } -} - -public class CGAnonymousMethodParameterDefinition : CGEntity { - public var Name: String - public var `Type`: CGTypeReference? - - public init(_ name: String) { - Name = name - } -} - -public class CGGenericParameterDefinition : CGEntity { - public var Constraints = List() - public var Name: String - public var Variance: CGGenericParameterVarianceKind? - - public init(_ name: String) { - Name = name - } -} - -public enum CGGenericParameterVarianceKind { - case Covariant - case Contravariant -} - -public __abstract class CGGenericConstraint : CGEntity { -} - -public class CGGenericHasConstructorConstraint : CGGenericConstraint { -} - -public class CGGenericIsSpecificTypeConstraint : CGGenericConstraint { - public var `Type`: CGTypeReference - - public init(_ type: CGTypeReference) { - `Type` = type - } -} - -public class CGGenericIsSpecificTypeKindConstraint : CGGenericConstraint { - public var Kind: CGGenericConstraintTypeKind - - public init(_ kind: CGGenericConstraintTypeKind) { - Kind = kind - } -} - -public enum CGGenericConstraintTypeKind { - case Class - case Struct - case Interface -} - -public class CGAttribute: CGEntity { - public var `Type`: CGTypeReference - public var Parameters: List? - public var Comment: CGSingleLineCommentStatement? - - public init(_ type: CGTypeReference) { - `Type` = type - } - public init(_ type: CGTypeReference,_ parameters: List) { - `Type` = type - Parameters = parameters - } - public convenience init(_ type: CGTypeReference,_ parameters: CGCallParameter...) { - init(type, parameters.ToList()) - } +/* Types */ + +public enum CGTypeVisibilityKind { + case Unspecified + case Unit + case Assembly + case Public +} + +public __abstract class CGTypeDefinition : CGEntity { + public var GenericParameters = List() + public var Name: String + public var Members = List() + public var Visibility: CGTypeVisibilityKind = .Unspecified //in delphi, types with .Unit will be put into implementation section + public var Static = false + public var Sealed = false + public var Abstract = false + public var Comment: CGCommentStatement? + public var Attributes = List() + public var Condition: CGConditionalDefine? + + public init(_ name: String) { + Name = name + } +} + +public final class CGGlobalTypeDefinition : CGTypeDefinition { + private init() { + super.init("") + Static = true + } + + public static lazy let GlobalType = CGGlobalTypeDefinition() +} + +public class CGTypeAliasDefinition : CGTypeDefinition { + public var ActualType: CGTypeReference + + public init(_ name: String, _ actualType: CGTypeReference) { + super.init(name) + ActualType = actualType + } +} + +public class CGBlockTypeDefinition : CGTypeDefinition { + public var Parameters = List() + public var ReturnType: CGTypeReference? + public var IsPlainFunctionPointer = false +} + +public class CGEnumTypeDefinition : CGTypeDefinition { + public var BaseType: CGTypeReference? +} + +public __abstract class CGClassOrStructTypeDefinition : CGTypeDefinition { + public var Ancestors: List + public var ImplementedInterfaces: List + public var Partial = false + + public init(_ name: String) { + super.init(name) + Ancestors = List() + ImplementedInterfaces = List() + } + public init(_ name: String, _ ancestor: CGTypeReference) { + super.init(name) + Ancestors = List() + Ancestors.Add(ancestor) + ImplementedInterfaces = List() + } + public init(_ name: String, _ ancestors: List) { + super.init(name) + Ancestors = ancestors + ImplementedInterfaces = List() + } + public init(_ name: String, _ ancestor: CGTypeReference, _ interfaces: List) { + super.init(name) + Ancestors = List() + Ancestors.Add(ancestor) + ImplementedInterfaces = interfaces + } + public init(_ name: String, _ ancestors: List, _ interfaces: List) { + super.init(name) + Ancestors = ancestors + ImplementedInterfaces = interfaces + } +} + +public class CGClassTypeDefinition : CGClassOrStructTypeDefinition { +} + +public class CGStructTypeDefinition : CGClassOrStructTypeDefinition { +} + +public class CGInterfaceTypeDefinition : CGClassOrStructTypeDefinition { + public var InterfaceGuid: Guid?;// legacy delphi only. declaration is : + // type interfaceName = interface (ancestorInterface) ['{GUID}'] memberList end; +} + +public class CGExtensionTypeDefinition : CGClassOrStructTypeDefinition { +} + +/* Type members */ + +public enum CGMemberVisibilityKind { + case Unspecified + case Private + case Unit + case UnitOrProtected + case UnitAndProtected + case Assembly + case AssemblyOrProtected + case AssemblyAndProtected + case Protected + case Public + case Published /* Delphi only */ +} + +public enum CGMemberVirtualityKind { + case None + case Virtual + case Abstract + case Override + case Final + case Reintroduce +} + +public __abstract class CGMemberDefinition: CGEntity { + public var Name: String + public var Visibility: CGMemberVisibilityKind = .Private + public var Virtuality: CGMemberVirtualityKind = .None + public var Static = false + public var Overloaded = false + public var Locked = false /* Oxygene only */ + public var LockedOn: CGExpression? /* Oxygene only */ + public var Comment: CGCommentStatement? + public var Attributes = List() + public var Condition: CGConditionalDefine? + public var ThrownExceptions: List? // nil means unknown; empty list means known to not throw. + + public init(_ name: String) { + Name = name + } +} + +public class CGEnumValueDefinition: CGMemberDefinition { + public var Value: CGExpression? + + public init(_ name: String) { + super.init(name) + } + public convenience init(_ name: String, _ value: CGExpression) { + init(name) + Value = value + } +} + +// +// Methods & Co +// + +public enum CGCallingConventionKind { + case CDecl /* C++ and Delphi */ + case Pascal /* C++ and Delphi */ + case StdCall /* C++ and Delphi */ + case FastCall /* C++ */ + case SafeCall /* C++ and Delphi */ + case ClrCall /* VC++ */ + case ThisCall /* VC++ */ + case VectorCall /* VC++ */ + case Register /* C++Builder and Delphi */ +} + +public __abstract class CGMethodLikeMemberDefinition: CGMemberDefinition { + public var Parameters = List() + public var ReturnType: CGTypeReference? + public var Inline = false + public var External = false + public var Empty = false + public var Partial = false /* Oxygene only */ + public var Async = false /* Oxygene only */ + public var Awaitable = false /* C# only */ + public var Throws = false /* Swift and Java only */ + public var Optional = false /* Swift only */ + public var CallingConvention: CGCallingConventionKind? /* Delphi and C++Builder only */ + public var Statements: List + public var LocalVariables: List? // Legacy Delphi only. + + public init(_ name: String) { + super.init(name) + Statements = List() + } + public init(_ name: String, _ statements: List) { + super.init(name) + Statements = statements + } + public init(_ name: String, _ statements: CGStatement...) { + super.init(name) + Statements = statements.ToList() + } +} + +public class CGMethodDefinition: CGMethodLikeMemberDefinition { + public var GenericParameters: List? +} + +public class CGConstructorDefinition: CGMethodLikeMemberDefinition { + public var Nullability = CGTypeNullabilityKind.NotNullable /* Swift only. currently. */ + + public init() { + super.init("") + } + public init(_ name: String, _ statements: List) { + var name = name + if name == ".ctor" || name == ".cctor" { + name = "" + } + super.init(name, statements) + } + convenience public init(_ name: String, _ statements: CGStatement...) { + init(name, statements.ToList()) + } +} + +public class CGDestructorDefinition: CGMethodLikeMemberDefinition { +} + +public class CGFinalizerDefinition: CGMethodLikeMemberDefinition { + public init() { + super.init("Finalizer") + } + public init(_ name: String, _ statements: List) { + super.init("Finalizer", statements) + } + public init(_ name: String, _ statements: CGStatement...) { + super.init("Finalizer", statements.ToList()) + } +} + +public class CGCustomOperatorDefinition: CGMethodLikeMemberDefinition { +} + +// +// Fields & Co +// + +public __abstract class CGFieldLikeMemberDefinition: CGMemberDefinition { + public var `Type`: CGTypeReference? + + public init(_ name: String) { + super.init(name) + } + public init(_ name: String, _ type: CGTypeReference) { + super.init(name) + `Type` = type + } +} + +public __abstract class CGFieldOrPropertyDefinition: CGFieldLikeMemberDefinition { + public var Initializer: CGExpression? + public var ReadOnly = false + public var WriteOnly = false +} + +public class CGFieldDefinition: CGFieldOrPropertyDefinition { + public var Constant = false +} + +public class CGPropertyDefinition: CGFieldOrPropertyDefinition { + public var Lazy = false + public var Atomic = false + public var Dynamic = false + public var Default = false + public var Parameters = List() + public var GetStatements: List? + public var SetStatements: List? + public var GetExpression: CGExpression? + public var SetExpression: CGExpression? + public var GetterVisibility: CGMemberVisibilityKind? + public var SetterVisibility: CGMemberVisibilityKind? + + public init(_ name: String) { + super.init(name) + } + public init(_ name: String, _ type: CGTypeReference) { + super.init(name, type) + } + public convenience init(_ name: String, _ type: CGTypeReference, _ getStatements: List, _ setStatements: List? = nil) { + init(name, type) + GetStatements = getStatements + SetStatements = setStatements + } + public convenience init(_ name: String, _ type: CGTypeReference, _ getStatements: CGStatement[], _ setStatements: CGStatement[]? = nil) { + init(name, type, getStatements.ToList(), setStatements?.ToList()) + } + public convenience init(_ name: String, _ type: CGTypeReference, _ getExpression: CGExpression, _ setExpression: CGExpression? = nil) { + init(name, type) + GetExpression = getExpression + SetExpression = setExpression + } + + internal func GetterMethodDefinition(`prefix`: String = "get__") -> CGMethodDefinition? { + if let getStatements = GetStatements, let type = `Type` { + let method = CGMethodDefinition(`prefix`+Name, getStatements) + method.ReturnType = type + method.Parameters = Parameters + method.Static = Static + return method + } else if let getExpression = GetExpression, let type = `Type` { + let method = CGMethodDefinition(`prefix`+Name) + method.ReturnType = type + method.Parameters = Parameters + method.Statements.Add(getExpression.AsReturnStatement()) + method.Static = Static + return method + } + return nil + } + + public static let MAGIC_VALUE_PARAMETER_NAME = "___value___" + + internal func SetterMethodDefinition(`prefix`: String = "set__") -> CGMethodDefinition? { + if let setStatements = SetStatements, let type = `Type` { + let method = CGMethodDefinition(`prefix`+Name, setStatements) + method.Parameters.Add(Parameters) + method.Parameters.Add(CGParameterDefinition(MAGIC_VALUE_PARAMETER_NAME, type)) + return method + } else if let setExpression = SetExpression, let type = `Type` { + let method = CGMethodDefinition(`prefix`+Name) + method.Parameters.Add(Parameters) + method.Parameters.Add(CGParameterDefinition(MAGIC_VALUE_PARAMETER_NAME, type)) + method.Statements.Add(CGAssignmentStatement(setExpression, CGLocalVariableAccessExpression(MAGIC_VALUE_PARAMETER_NAME))) + return method + } + return nil + } + + public var IsShortcutProperty: Boolean { get { return GetStatements == nil && SetStatements == nil && GetExpression == nil && SetExpression == nil } } +} + +public class CGEventDefinition: CGFieldLikeMemberDefinition { + public var AddStatements: List? + public var RemoveStatements: List? + //public var RaiseStatements: List? + + public init(_ name: String, _ type: CGTypeReference) { + super.init(name, type) + } + public convenience init(_ name: String, _ type: CGTypeReference, _ addStatements: List, _ removeStatements: List/*, _ raiseStatements: List? = nil*/) { + init(name, type) + AddStatements = addStatements + RemoveStatements = removeStatements + //RaiseStatements = raiseStatements + } + + internal func AddMethodDefinition() -> CGMethodDefinition? { + if let addStatements = AddStatements, let type = `Type` { + let method = CGMethodDefinition("add__"+Name, addStatements) + method.Parameters.Add(CGParameterDefinition("___value", type)) + return method + } + return nil + } + + internal func RemoveMethodDefinition() -> CGMethodDefinition? { + if let removeStatements = RemoveStatements, let type = `Type` { + let method = CGMethodDefinition("remove__"+Name, removeStatements) + method.Parameters.Add(CGParameterDefinition("___value", type)) + return method + } + return nil + } + + /*internal func RaiseMethodDefinition() -> CGMethodDefinition? { + if let raiseStatements = RaiseStatements, type = `Type` { + let method = CGMethodDefinition("raise__"+Name, raisetatements) + //todo: this would need the same parameters as the block, which we don't have + return method + } + return nil + }*/ +} + +public class CGNestedTypeDefinition: CGMemberDefinition { + public var `Type`: CGTypeDefinition + + public init(_ type: CGTypeDefinition) { + super.init(type.Name) + `Type` = type + } +} + +// +// Parameters +// + +public enum CGParameterModifierKind { + case In + case Out + case Var + case Const + case Params +} + +public class CGParameterDefinition : CGEntity { + public var Name: String + public var ExternalName: String? // Swift and Cocoa only + public var `Type`: CGTypeReference + public var Modifier: CGParameterModifierKind = .In + public var DefaultValue: CGExpression? + + public init(_ name: String, _ type: CGTypeReference) { + Name = name + `Type` = type + } +} + +public class CGAnonymousMethodParameterDefinition : CGEntity { + public var Name: String + public var `Type`: CGTypeReference? + + public init(_ name: String) { + Name = name + } +} + +public class CGGenericParameterDefinition : CGEntity { + public var Constraints = List() + public var Name: String + public var Variance: CGGenericParameterVarianceKind? + + public init(_ name: String) { + Name = name + } +} + +public enum CGGenericParameterVarianceKind { + case Covariant + case Contravariant +} + +public __abstract class CGGenericConstraint : CGEntity { +} + +public class CGGenericHasConstructorConstraint : CGGenericConstraint { +} + +public class CGGenericIsSpecificTypeConstraint : CGGenericConstraint { + public var `Type`: CGTypeReference + + public init(_ type: CGTypeReference) { + `Type` = type + } +} + +public class CGGenericIsSpecificTypeKindConstraint : CGGenericConstraint { + public var Kind: CGGenericConstraintTypeKind + + public init(_ kind: CGGenericConstraintTypeKind) { + Kind = kind + } +} + +public enum CGGenericConstraintTypeKind { + case Class + case Struct + case Interface +} + +public class CGAttribute: CGEntity { + public var `Type`: CGTypeReference + public var Parameters: List? + public var Comment: CGSingleLineCommentStatement? + + public init(_ type: CGTypeReference) { + `Type` = type + } + public init(_ type: CGTypeReference,_ parameters: List) { + `Type` = type + Parameters = parameters + } + public convenience init(_ type: CGTypeReference,_ parameters: CGCallParameter...) { + init(type, parameters.ToList()) + } } \ No newline at end of file diff --git a/TypeReferences.swift b/TypeReferences.swift index ea88c87..6077733 100644 --- a/TypeReferences.swift +++ b/TypeReferences.swift @@ -1,8 +1,4 @@ -import Sugar -import Sugar.Collections -import Sugar.Linq - -/* Type References */ +/* Type References */ public enum CGTypeNullabilityKind { case Unknown @@ -19,26 +15,26 @@ public __abstract class CGTypeReference : CGEntity { #hint StorageModifier shouldn't really be on the type? refactor! public /*fileprivate*/internal(set) var StorageModifier: CGStorageModifierKind = .Strong public /*fileprivate*/internal(set) var IsClassType = false - - public lazy var NullableUnwrapped: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NullableUnwrapped ? self : self.copyWithNullability(CGTypeNullabilityKind.NullableUnwrapped) + + public lazy var NullableUnwrapped: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NullableUnwrapped ? self : self.copyWithNullability(CGTypeNullabilityKind.NullableUnwrapped) public lazy var NullableNotUnwrapped: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NullableNotUnwrapped ? self : self.copyWithNullability(CGTypeNullabilityKind.NullableNotUnwrapped) - public lazy var NotNullable: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NotNullable ? self : self.copyWithNullability(CGTypeNullabilityKind.NotNullable) - + public lazy var NotNullable: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NotNullable ? self : self.copyWithNullability(CGTypeNullabilityKind.NotNullable) + public var ActualNullability: CGTypeNullabilityKind { if Nullability == CGTypeNullabilityKind.Default || Nullability == CGTypeNullabilityKind.Unknown { return DefaultNullability } return Nullability } - - public var IsVoid: Boolean { + + public var IsVoid: Boolean { if let predef = self as? CGPredefinedTypeReference { return predef.Kind == CGPredefinedTypeKind.Void } return false //return (self as? CGPredefinedTypeReference)?.Kind == CGPredefinedTypeKind.Void // 71722: Silver: can't compare nullable enum to enum } - + public __abstract func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference } @@ -52,7 +48,7 @@ public class CGNamedTypeReference : CGTypeReference { public let Name: String public private(set) var Namespace: CGNamespaceReference? public var GenericArguments: List? - + public var FullName: String { if let namespace = Namespace { return namespace.Name+"."+Name @@ -104,7 +100,7 @@ public class CGNamedTypeReference : CGTypeReference { public class CGPredefinedTypeReference : CGTypeReference { public var Kind: CGPredefinedTypeKind - + //todo:these should become provate and force use of the static members public init(_ kind: CGPredefinedTypeKind) { Kind = kind @@ -146,11 +142,11 @@ public class CGPredefinedTypeReference : CGTypeReference { DefaultValue = CGNilExpression.Nil DefaultNullability = .NullableUnwrapped IsClassType = true - case .Object: + case .Object: DefaultValue = CGNilExpression.Nil DefaultNullability = .NullableUnwrapped IsClassType = true - case .Class: + case .Class: DefaultValue = CGNilExpression.Nil DefaultNullability = .NullableUnwrapped IsClassType = true @@ -169,7 +165,7 @@ public class CGPredefinedTypeReference : CGTypeReference { init(kind) DefaultValue = defaultValue } - + /*public lazy var NullableUnwrapped: CGPredefinedTypeReference = ActualNullability == CGTypeNullabilityKind.NullableUnwrapped ? self : CGPredefinedTypeReference(Kind, nullability: CGTypeNullabilityKind.NullableUnwrapped) public lazy var NullableNotUnwrapped: CGPredefinedTypeReference = ActualNullability == CGTypeNullabilityKind.NullableNotUnwrapped ? self : CGPredefinedTypeReference(Kind, nullability: CGTypeNullabilityKind.NullableNotUnwrapped) public lazy var NotNullable: CGPredefinedTypeReference = ActualNullability == CGTypeNullabilityKind.NotNullable ? self : CGPredefinedTypeReference(Kind, nullability: CGTypeNullabilityKind.NotNullable)*/ @@ -241,7 +237,7 @@ public enum CGPredefinedTypeKind { public class CGIntegerRangeTypeReference : CGTypeReference { public var Start: Integer public var End: Integer - + init(_ start: Integer, _ end: Integer) { Start = start End = end @@ -281,12 +277,12 @@ public class CGPointerTypeReference : CGTypeReference { `Type` = type DefaultNullability = .NullableUnwrapped } - + public convenience init(_ type: CGTypeReference, reference: Boolean) { /* C++ only */ init(type) Reference = reference } - + public static lazy var VoidPointer = CGPointerTypeReference(CGPredefinedTypeReference.Void) override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference { @@ -341,7 +337,7 @@ public class CGKindOfTypeReference : CGTypeReference { public class CGTupleTypeReference : CGTypeReference { public var Members: List - + public init(_ members: List) { Members = members } @@ -415,7 +411,7 @@ public class CGArrayTypeReference : CGTypeReference { Bounds = bounds } else { Bounds = List() - } + } } override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference { @@ -433,7 +429,7 @@ public class CGArrayTypeReference : CGTypeReference { public class CGArrayBounds : CGEntity { public var Start: Int32 = 0 public var End: Int32? - + public init() { } public init(_ start: Int32, end: Int32) { @@ -462,4 +458,4 @@ public class CGDictionaryTypeReference : CGTypeReference { result.IsClassType = IsClassType return result } -} +} \ No newline at end of file