예제 #1
0
        static List <string> HomonymPartsFor(FunctionDeclaration func, TypeMapper mapper)
        {
            var parts = func.ParameterLists.Last().Select(arg => arg.NameIsRequired ? arg.PublicName : "_").ToList();

            if (func.ReturnTypeSpec == null || func.ReturnTypeSpec.IsEmptyTuple)
            {
                parts.Add("void");
            }
            else
            {
                var use = new CSUsingPackages();
                if (func.ReturnTypeSpec is ProtocolListTypeSpec pl)
                {
                    var sb = new StringBuilder();
                    foreach (var nt in pl.Protocols.Keys)
                    {
                        sb.Append(MangledReturnType(func, mapper, use, nt));
                    }
                    parts.Add(sb.ToString());
                }
                else
                {
                    parts.Add(MangledReturnType(func, mapper, use, func.ReturnTypeSpec));
                }
            }
            return(parts);
        }
        CSInterface BuildCSIface(ClassDeclaration cl, CSUsingPackages use)
        {
            var csName = NewClassCompiler.StubbedClassName(cl.ToFullyQualifiedName(true), typeMapper);
            var iface  = new CSInterface(CSVisibility.Public, csName);

            return(iface);
        }
 public static CSType ToCSSimpleType(NetTypeBundle ntb, CSUsingPackages use)
 {
     if (!String.IsNullOrEmpty(ntb.NameSpace))
     {
         use.AddIfNotPresent(ntb.NameSpace);
     }
     return(ntb.Entity == EntityType.Tuple ? ToCSTuple(ntb.TupleTypes, use) : ntb.ToCSType(use));
 }
예제 #4
0
        static string MangledReturnType(FunctionDeclaration func, TypeMapper mapper, CSUsingPackages use, TypeSpec ts)
        {
            var ntb            = mapper.MapType(func, ts, false, true);
            var type           = NetTypeBundle.ToCSSimpleType(ntb, use);
            var returnTypeName = type.ToString().Replace(".", "").Replace("<", "").Replace(">", "");

            return(returnTypeName);
        }
예제 #5
0
        public void ArcClassStruct()
        {
            string swiftCode =
                "public final class Foo {\npublic var _nm:String\npublic init(name:String) {\n_nm = name }\n" +
                "deinit {\nprint(_nm)\n}\n}\n" +
                "public struct Bar {\n public var a:Foo\n public init(f:Foo) {\n a = f\n}\n }\n"
            ;

            swiftCode += TestRunning.CreateSwiftConsoleRedirect();

            using (TempDirectoryFilenameProvider provider = new TempDirectoryFilenameProvider(null, true)) {
                Utils.CompileSwift(swiftCode, provider);

                string libFileName = Path.Combine(provider.DirectoryPath, "libXython.dylib");
                var    errors      = new ErrorHandling();

                ModuleInventory.FromFile(libFileName, errors);
                Utils.CheckErrors(errors);

                Utils.CompileToCSharp(provider);

                CSUsingPackages use = new CSUsingPackages("System", "System.Runtime.InteropServices", "SwiftRuntimeLibrary");

                CSNamespace ns     = new CSNamespace("Xython");
                CSFile      csfile = CSFile.Create(use, ns);

                CSIdentifier inst  = new CSIdentifier("inst");
                CSLine       newer = CSVariableDeclaration.VarLine((CSSimpleType)"Foo", inst, CSFunctionCall.Ctor("Foo",
                                                                                                                  CSFunctionCall.Function("SwiftString.FromString", CSConstant.Val("nothing"))));

                CSIdentifier inst1  = new CSIdentifier("bar");
                CSLine       newer1 = CSVariableDeclaration.VarLine((CSSimpleType)"Bar", inst1, CSFunctionCall.Ctor("Bar", inst));

                CSLine disposer  = CSFunctionCall.FunctionCallLine(inst.Name + ".Dispose", false);
                CSLine disposer1 = CSFunctionCall.FunctionCallLine(inst1.Name + ".Dispose", false);

                CSCodeBlock mainBody = CSCodeBlock.Create(newer, newer1, disposer, disposer1);

                CSMethod main = new CSMethod(CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void,
                                             (CSIdentifier)"Main", new CSParameterList(new CSParameter(CSSimpleType.CreateArray("string"), "args")),
                                             mainBody);
                CSClass mainClass = new CSClass(CSVisibility.Public, "NameNotImportant", new CSMethod [] { main });
                ns.Block.Add(mainClass);

                string csOutFilename  = provider.ProvideFileFor(provider.UniqueName(null, "CSWrap", "cs"));
                var    exeOutFilename = provider.UniquePath(null, "CSWrap", "exe");

                CodeWriter.WriteToFile(csOutFilename, csfile);

                Compiler.CSCompile(provider.DirectoryPath, Directory.GetFiles(provider.DirectoryPath, "*.cs"), exeOutFilename);

                TestRunning.CopyTestReferencesTo(provider.DirectoryPath);

                string output = Compiler.RunWithMono(exeOutFilename, provider.DirectoryPath);
                Assert.AreEqual("nothing\n", output);
            }
        }
 public static CSSimpleType ToCSTuple(IList <NetTypeBundle> innerTypes, CSUsingPackages use)
 {
     if (innerTypes.Count <= 7)
     {
         return(new CSSimpleType("Tuple", false, ToCSSimpleType(innerTypes, use).ToArray()));
     }
     else
     {
         IEnumerable <CSType> head = ToCSSimpleType(innerTypes.Take(7), use);
         CSType tail = ToCSTuple(innerTypes.Skip(7).ToList(), use);
         return(new CSSimpleType("Tuple", false, Enumerable.Concat(head, Enumerable.Repeat(tail, 1)).ToArray()));
     }
 }
        public void Compile()
        {
            if (verbose)
            {
                NewClassCompiler.ReportCompileStatus(protocols, "ObjC protocols");
            }

            if (!protocols.Any())
            {
                return;
            }

            var    use       = new CSUsingPackages("System", "ObjCRuntime", "Foundation");
            string nameSpace = typeMapper.MapModuleToNamespace(module.Name);
            var    nm        = new CSNamespace(nameSpace);

            var objCClasses = ObjCClasses();

            foreach (var cl in objCClasses)
            {
                var csIface = BuildCSIface(cl, use);
                nm.Block.Add(csIface);
            }

            foreach (var proto in protocols)
            {
                if (proto.IsDeprecated || proto.IsUnavailable)
                {
                    continue;
                }
                try {
                    var iface = CompileProtocol(proto, use);
                    nm.Block.Add(iface);
                } catch (Exception e) {
                    errors.Add(e);
                }
            }
            var csfile = new CSFile(use, new CSNamespace [] { nm });

            string csOutputFileName = $"{nameSpace}ObjCProtocol.cs";

            NewClassCompiler.WriteCSFile(csOutputFileName, outputDirectory, csfile);

            var needsSwiftRuntimeLibrary = use.Elements.Any(elem => (elem as CSUsing).Contents.Contains("SwiftRuntimeLibrary"));

            YouCantBtouchThis(csOutputFileName, needsSwiftRuntimeLibrary);
            CleanUpExtraneousFiles(protocols, csOutputFileName);
        }
        static CSUsingPackages GetTestEntryPointUsings(string nameSpace, PlatformName platform)
        {
            var usings = new CSUsingPackages()
                         .And("System")
                         .And("System.IO")
                         .And(nameSpace)
                         .And("SwiftRuntimeLibrary")
                         .And("SwiftRuntimeLibrary.SwiftMarshal")
                         .And("System.Runtime.InteropServices");

            if (platform != PlatformName.None)
            {
                usings = usings.And("Foundation");
            }

            return(usings);
        }
예제 #9
0
        static List <string> HomonymPartsFor(TLFunction func, TypeMapper mapper)
        {
            var parts = func.Signature.EachParameter.Select(arg => arg.Name.Name).ToList();

            if (func.Signature.ReturnType == null || func.Signature.ReturnType.IsEmptyTuple)
            {
                parts.Add("void");
            }
            else
            {
                var use            = new CSUsingPackages();
                var ntb            = mapper.MapType(func.Signature.ReturnType, false);
                var type           = NetTypeBundle.ToCSSimpleType(ntb, use);
                var returnTypeName = type.ToString().Replace(".", "").Replace("<", "").Replace(">", "");
                parts.Add(returnTypeName);
            }
            return(parts);
        }
        public CSType ToCSType(CSUsingPackages use)
        {
            if (!String.IsNullOrEmpty(NameSpace))
            {
                use.AddIfNotPresent(NameSpace);
            }
            if (IsGenericReference)
            {
                CSGenericReferenceType genref = new CSGenericReferenceType(GenericDepth, GenericIndex);
                if (this.GenericConstraints.Count > 0)
                {
                    genref.InterfaceConstraints.AddRange(this.GenericConstraints.Select(ntb => ntb.ToCSType(use)));
                }
                return(genref);
            }

            return(Entity == EntityType.Tuple ? ToCSTuple(TupleTypes, use) :
                   new CSSimpleType(Type, false, GenericTypes.Select(ntb => ntb.ToCSType(use)).ToArray()));
        }
        CSInterface CompileProtocol(ProtocolDeclaration proto, CSUsingPackages use)
        {
            var iface = new CSInterface(CSVisibility.Public, proto.Name);

            kProtocolAttribute.AttachBefore(iface);
            var filteredInheritance = proto.Inheritance.FindAll(inh => !TypeSpecIsAnyOrAnyObject(inh.InheritedTypeSpec));

            iface.Inheritance.AddRange(filteredInheritance.Select(inh => {
                var netIface = typeMapper.GetDotNetNameForTypeSpec(inh.InheritedTypeSpec);
                use.AddIfNotPresent(netIface.Namespace);
                return(new CSIdentifier(netIface.TypeName));
            }));

            foreach (var funcDecl in proto.AllMethodsNoCDTor())
            {
                if (funcDecl.IsProperty && !funcDecl.IsSubscript)
                {
                    continue;
                }
                try {
                    CompileFunc(funcDecl, proto, iface, use);
                } catch (Exception e) {
                    errors.Add(ErrorHelper.CreateWarning(ReflectorError.kWrappingBase + 14, e, $"Error compiling ObjC protocol method {proto.ToFullyQualifiedName ()}.{funcDecl.Name}"));
                }
            }

            foreach (var propDecl in proto.AllProperties())
            {
                try {
                    CompileProp(propDecl, proto, iface, use);
                } catch (Exception e) {
                    errors.Add(ErrorHelper.CreateWarning(ReflectorError.kWrappingBase + 14, e, $"Error compiling ObjC protocol property {proto.ToFullyQualifiedName ()}.{propDecl.Name}"));
                }
            }
            var anyRequired = proto.AllMethodsNoCDTor().Any(func => !func.IsOptional);

            if (anyRequired)
            {
                kAbstractAttribute.AttachBefore(iface);
            }

            return(iface);
        }
        public CSMethod CompileMethod(FunctionDeclaration func, CSUsingPackages packs, string libraryPath,
                                      string mangledName, string functionName, bool isPinvoke, bool isFinal, bool isStatic)
        {
            isStatic = isStatic || func.IsExtension;
            var extraProtoArgs        = new CSGenericTypeDeclarationCollection();
            var extraProtoConstraints = new CSGenericConstraintCollection();
            var args = typeMap.MapParameterList(func, func.ParameterLists.Last(), isPinvoke, false, extraProtoArgs, extraProtoConstraints);

            if (isPinvoke && func.ParameterLists.Count > 1)
            {
                var      metaTypeBundle = new NetTypeBundle("SwiftRuntimeLibrary", "SwiftMetatype", false, false, EntityType.None);
                NetParam p = new NetParam("metaClass", metaTypeBundle);
                args.Add(p);
            }

            NetTypeBundle returnType = null;

            if (func.ReturnTypeSpec is ProtocolListTypeSpec plitem && !isPinvoke)
            {
                returnType = new NetTypeBundle("System", "object", false, false, EntityType.ProtocolList);
            }
        public CSProperty CompileProperty(string propertyName, CSUsingPackages packs, SwiftType swiftPropertyType, bool hasGetter, bool hasSetter,
                                          CSMethodKind methodKind)
        {
            propertyName = typeMap.SanitizeIdentifier(propertyName);
            NetTypeBundle propertyType = typeMap.MapType(swiftPropertyType, false);

            if (!(swiftPropertyType is SwiftGenericArgReferenceType))
            {
                AddUsingBlock(packs, propertyType);
            }
            ICodeElement [] uselessLine = new ICodeElement [] { CSReturn.ReturnLine(new CSIdentifier("useless")) };

            CSCodeBlock getterBlock = null;

            if (hasGetter)
            {
                getterBlock = new CSCodeBlock(uselessLine);
            }
            CSCodeBlock setterBlock = null;

            if (hasSetter)
            {
                setterBlock = new CSCodeBlock(uselessLine);
            }

            CSProperty theProp = new CSProperty(propertyType.ToCSType(packs), methodKind,
                                                new CSIdentifier(propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock);

            if (getterBlock != null)
            {
                getterBlock.Clear();
            }
            if (setterBlock != null)
            {
                setterBlock.Clear();
            }

            return(theProp);
        }
예제 #14
0
        public static Stream BasicClass(string nameSpace, string className, CSMethod m, ClassMutator mutator, UsingMutator useMutator = null)
        {
            CSUsingPackages use = new CSUsingPackages("System");

            if (useMutator != null)
            {
                use = useMutator(use);
            }

            CSClass cl = new CSClass(CSVisibility.Public, className, m != null ? new CSMethod [] { m } : null);

            if (mutator != null)
            {
                cl = mutator(cl);
            }

            CSNamespace ns = new CSNamespace(nameSpace);

            ns.Block.Add(cl);

            CSFile file = CSFile.Create(use, ns);

            return(CodeWriter.WriteToStream(file));
        }
 public MarshalEngineCSafeSwiftToCSharp(CSUsingPackages use, List <string> identifiersUsed, TypeMapper typeMapper)
 {
     this.use             = use;
     this.typeMapper      = typeMapper;
     this.identifiersUsed = Ex.ThrowOnNull(identifiersUsed, "identifiersUsed");
 }
예제 #16
0
        static CSFile GeneratePInvokesFromTypes(TypeAggregator types, PlatformName platform, string framework)
        {
            var fileName  = Path.GetFileNameWithoutExtension(framework);             // /path/XamGlue.framework -> XamGlue
            var dylibFile = Path.Combine(framework, fileName);
            var funcs     = TLFunctionsForFile(dylibFile, platform);

            var ns  = new CSNamespace("SwiftRuntimeLibrary.SwiftMarshal");
            var use = new CSUsingPackages();

            use.And(new CSUsing("System.Runtime.InteropServices"))
            .And(new CSUsing("System"))
            .And(new CSUsing("System.Collections.Generic"))
            .And(new CSUsing("SwiftRuntimeLibrary"));

            var csFile  = new CSFile(use, new CSNamespace [] { ns });
            var csClass = new CSClass(CSVisibility.Internal, $"{fileName}Metadata");

            new CSComment(kRobotText).AttachBefore(use);

            CSConditionalCompilation.If(PlatformToCSCondition(platform)).AttachBefore(use);
            CSConditionalCompilation.Endif.AttachAfter(ns);
            ns.Block.Add(csClass);

            var typeOntoPinvoke = new List <KeyValuePair <CSBaseExpression, CSBaseExpression> > ();

            var typesToProcess = new List <TypeDefinition> ();

            typesToProcess.AddRange(types.PublicEnums);
            typesToProcess.AddRange(types.PublicStructs);

            // pre-sort by function name
            typesToProcess.Sort((type1, type2) => String.CompareOrdinal(FuncIDForTypeDefinition(type1), FuncIDForTypeDefinition(type2)));

            foreach (var type in typesToProcess)
            {
                if (type.HasGenericParameters)
                {
                    continue;
                }
                var moduleName = type.Namespace;
                var name       = type.Name;
                if (TypeAggregator.FilterModuleAndName(platform, moduleName, ref name))
                {
                    var pinvoke = PInvokeForType(type, funcs);
                    if (pinvoke != null)
                    {
                        csClass.Methods.Add(pinvoke);
                        use.AddIfNotPresent(type.Namespace);
                        var typeOf   = new CSSimpleType(type.FullName).Typeof();
                        var funcName = pinvoke.Name;
                        typeOntoPinvoke.Add(new KeyValuePair <CSBaseExpression, CSBaseExpression> (typeOf, funcName));
                    }
                }
            }

            var initializers = typeOntoPinvoke.Select(typeAndFunc => new CSInitializer(new CSBaseExpression [] { typeAndFunc.Key, typeAndFunc.Value }, false));
            var bindingExpr  = new CSInitializedType(new CSFunctionCall("Dictionary<Type, Func<SwiftMetatype>>", true), new CSInitializer(initializers, true));
            var bindingDecl  = new CSFieldDeclaration(new CSSimpleType("Dictionary<Type, Func<SwiftMetatype>>"), "ObjCBindingSwiftMetatypes", bindingExpr, CSVisibility.Internal, true);

            csClass.Fields.Add(new CSLine(bindingDecl));

            use.Sort((package1, package2) => String.CompareOrdinal(package1.Package, package2.Package));

            return(csFile);
        }
예제 #17
0
        /// <summary>
        /// Creates a list of all types, and a hash table which is initialized on first lookup from C# type
        /// to Swift types.
        /// </summary>
        /// <param name="types">Aggregated types, a subset of which are included</param>
        /// <param name="platform">Platform targeted (typically iOS or Mac)</param>
        /// <param name="namespaces">Namespaces to include</param>
        /// <param name="framework">Name of framework used (typically XamGlue)</param>
        /// <returns>CSFile which, when written, has function looking up in hash table as described in summary</returns>
        static CSFile GenerateCSharpHashTableFromTypes(TypeAggregator types, PlatformName platform, List <string> namespaces, string framework)
        {
            var fileName = Path.GetFileNameWithoutExtension(framework);
            var ns       = new CSNamespace("SwiftRuntimeLibrary.SwiftMarshal");
            var use      = new CSUsingPackages();

            use.And(new CSUsing("System.Runtime.InteropServices"))
            .And(new CSUsing("System"))
            .And(new CSUsing("System.Collections.Generic"))
            .And(new CSUsing("SwiftRuntimeLibrary"));

            var csFile  = new CSFile(use, new CSNamespace [] { ns });
            var csClass = new CSClass(CSVisibility.Internal, $"{fileName}Metadata");

            new CSComment(kRobotText).AttachBefore(use);

            CSConditionalCompilation.If(PlatformToCSCondition(platform)).AttachBefore(use);
            CSConditionalCompilation.Endif.AttachAfter(ns);
            ns.Block.Add(csClass);

            // collect all possible types, filter and sort
            var selectedTypes = new List <TypeDefinition> ();

            selectedTypes.AddRange(types.PublicEnums);
            selectedTypes.AddRange(types.PublicStructs);
            selectedTypes = selectedTypes.FindAll(type => IncludeType(type, namespaces, platform));
            selectedTypes.Sort((type1, type2) => String.CompareOrdinal(type1.FullName, type2.FullName));

            // add used namespaces to import list, sort list
            foreach (var type in selectedTypes)
            {
                use.AddIfNotPresent(type.Namespace);
            }
            use.Sort((package1, package2) => String.CompareOrdinal(package1.Package, package2.Package));

            // create list of types to translate
            var typesForList       = selectedTypes.Select(type => new CSSimpleType(type.FullName).Typeof());
            var listInitializeExpr = new CSInitializedType(
                new CSFunctionCall("List<Type>", true),
                new CSInitializer(typesForList, true)
                );
            var listBindingDecl = new CSFieldDeclaration(new CSSimpleType("List<Type>"), "csImportTypes", listInitializeExpr, CSVisibility.Internal, true);

            csClass.Fields.Add(new CSLine(listBindingDecl));

            // create pinvoke for function
            var dylibFile = Path.Combine(framework, fileName);
            var funcs     = TLFunctionsForFile(dylibFile, platform);

            var handleTranslationCode = new CSIdentifier(@"
		public static unsafe bool GetSwiftType (Type t, out SwiftMetatype md) {
			using (var swiftStr = new SwiftString (t.FullName)) {
				return SwiftCore.GetEnumMetadataByName (swiftStr.SwiftData, out md);
			}
		}

		internal static Dictionary<Type, SwiftMetatype> csImportMeta = null;
		internal static bool TryGetImportedMetadata (Type cSharpType, out SwiftMetatype md) {
			if (csImportMeta == null) {
				csImportMeta = new Dictionary<Type, SwiftMetatype> (csImportTypes.Count);
				foreach (var t in csImportTypes) {
					SwiftMetatype meta;
					GetSwiftType(t, out meta);
					csImportMeta [t] = meta;
				}
			}
			return csImportMeta.TryGetValue (cSharpType, out md);
		}"        );

            csClass.Fields.Add(new CSLine(handleTranslationCode, false));

            return(csFile);
        }
        public CSDelegateTypeDecl CompileToDelegateDeclaration(FunctionDeclaration func, CSUsingPackages packs,
                                                               string mangledName, string delegateName, bool objectsAreIntPtrs, CSVisibility vis, bool isSwiftProtocol)
        {
            bool returnIsGeneric = func.IsTypeSpecGeneric(func.ReturnTypeSpec);
            var  args            = typeMap.MapParameterList(func, func.ParameterLists.Last(), objectsAreIntPtrs, true, null, null);

            RemapSwiftClosureRepresensation(args);
            var returnType = returnIsGeneric ? null : typeMap.MapType(func, func.ReturnTypeSpec, objectsAreIntPtrs, true);

            delegateName = delegateName ?? typeMap.SanitizeIdentifier(func.Name);

            args.ForEach(a => AddUsingBlock(packs, a.Type));

            if (returnType != null && !returnIsGeneric)
            {
                AddUsingBlock(packs, returnType);
            }

            CSType csReturnType = returnType == null || returnType.IsVoid ? CSSimpleType.Void : returnType.ToCSType(packs);
            var    csParams     = new CSParameterList();

            for (int i = 0; i < args.Count; i++)
            {
                var         arg          = args [i];
                var         argIsGeneric = func.IsTypeSpecGeneric(func.ParameterLists.Last() [i].TypeSpec);
                CSParameter csParam      = null;
                var         parmType     = func.ParameterLists.Last() [i].TypeSpec;
                if (arg.Type.Entity == EntityType.Tuple || (!argIsGeneric && IsObjCStruct(parmType)))
                {
                    csParam = new CSParameter(CSSimpleType.IntPtr, new CSIdentifier(arg.Name), CSParameterKind.None, null);
                }
                else
                {
                    csParam = new CSParameter(arg.Type.ToCSType(packs), new CSIdentifier(arg.Name),
                                              arg.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null);
                }
                csParams.Add(csParam);
            }

            if (isSwiftProtocol)
            {
                packs.AddIfNotPresent(typeof(SwiftExistentialContainer1));
                csParams.Insert(0, new CSParameter(new CSSimpleType(typeof(SwiftExistentialContainer1)), new CSIdentifier("self"), CSParameterKind.Ref));
            }
            else
            {
                csParams.Insert(0, new CSParameter(CSSimpleType.IntPtr, new CSIdentifier("self")));
            }

            var retvalName = "xam_retval";
            var retvalID   = new CSIdentifier(retvalName);

            if (func.HasThrows || returnIsGeneric || !returnType.IsVoid)               // && func.Signature.ReturnType.IsStruct || func.Signature.ReturnType.IsEnum) {
            {
                if (func.HasThrows)
                {
                    csParams.Insert(0, new CSParameter(CSSimpleType.IntPtr, retvalName, CSParameterKind.None));
                    csReturnType = CSSimpleType.Void;
                }
                else
                {
                    if (!returnIsGeneric)
                    {
                        if (!(func.ReturnTypeSpec is ClosureTypeSpec))
                        {
                            Entity ent = typeMap.GetEntityForTypeSpec(func.ReturnTypeSpec);
                            if (ent == null && !(func.ReturnTypeSpec is ProtocolListTypeSpec))
                            {
                                throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 8, $"Unable to find entity for class {csReturnType.ToString ()}.");
                            }

                            if (ent != null && (ent.IsStructOrEnum || ent.EntityType == EntityType.Protocol))
                            {
                                csParams.Insert(0, new CSParameter(CSSimpleType.IntPtr, retvalID, CSParameterKind.None));
                                csReturnType = CSSimpleType.Void;
                            }
                            else if (func.ReturnTypeSpec is ProtocolListTypeSpec pl)
                            {
                                csParams.Insert(0, new CSParameter(new CSSimpleType($"SwiftExistentialContainer{pl.Protocols.Count}"), retvalID, CSParameterKind.Ref));
                                csReturnType = CSSimpleType.Void;
                            }
                        }
                    }
                    else
                    {
                        csParams.Insert(0, new CSParameter(CSSimpleType.IntPtr, retvalID, CSParameterKind.None));
                    }
                }
            }

            return(new CSDelegateTypeDecl(vis, csReturnType, new CSIdentifier(delegateName), csParams));
        }
 public static CSSimpleType ToCSOptional(NetTypeBundle optType, CSUsingPackages use)
 {
     use.AddIfNotPresent(typeof(SwiftOptional <>));
     return(new CSSimpleType("SwiftOptional", false, optType.ToCSType(use)));
 }
 static IEnumerable <CSType> ToCSSimpleType(IEnumerable <NetTypeBundle> ntbs, CSUsingPackages use)
 {
     return(ntbs.Select(ntb => ToCSSimpleType(ntb, use)));
 }
        void CompileProp(PropertyDeclaration propDecl, ProtocolDeclaration proto, CSInterface iface, CSUsingPackages use)
        {
            var getter     = propDecl.GetGetter();
            var setter     = propDecl.GetSetter();
            var publicProp = topLevelFunctionCompiler.CompileProperty(use, null, getter, setter, CSMethodKind.None);

            publicProp = new CSProperty(publicProp.PropType, CSMethodKind.None, publicProp.Name,
                                        CSVisibility.None, new CSCodeBlock(), CSVisibility.None, setter != null ? new CSCodeBlock() : null);
            ExportAttribute(getter.ObjCSelector).AttachBefore(publicProp);
            if (!propDecl.IsOptional)
            {
                kAbstractAttribute.AttachBefore(publicProp);
            }
            iface.Properties.Add(publicProp);
        }
        void CompileFunc(FunctionDeclaration funcDecl, ProtocolDeclaration proto, CSInterface iface, CSUsingPackages use)
        {
            var homonymSuffix = Homonyms.HomonymSuffix(funcDecl, proto.Members.OfType <FunctionDeclaration> (), typeMapper);

            var publicMethod = topLevelFunctionCompiler.CompileMethod(funcDecl, use, swiftLibPath, null, null, false, false, false);

            // recast with no visibility and with the homonym suffix, if any
            publicMethod = new CSMethod(CSVisibility.None, CSMethodKind.Interface, publicMethod.Type,
                                        new CSIdentifier(publicMethod.Name.Name + homonymSuffix), publicMethod.Parameters, null);
            ExportAttribute(funcDecl.ObjCSelector).AttachBefore(publicMethod);
            if (!funcDecl.IsOptional)
            {
                kAbstractAttribute.AttachBefore(publicMethod);
            }
            iface.Methods.Add(publicMethod);
        }
        public CSProperty CompileProperty(CSUsingPackages packs, string propertyName,
                                          FunctionDeclaration getter, FunctionDeclaration setter, CSMethodKind methodKind = CSMethodKind.None)
        {
            var           swiftPropertyType = GetPropertyType(getter, setter);
            NetTypeBundle propertyType      = null;

            if (TypeMapper.IsCompoundProtocolListType(swiftPropertyType))
            {
                propertyType = new NetTypeBundle("System", "object", false, false, EntityType.ProtocolList);
            }
            else
            {
                propertyType = typeMap.MapType(getter, swiftPropertyType, false, true);
            }
            propertyName = propertyName ?? typeMap.SanitizeIdentifier(getter != null ? getter.PropertyName : setter.PropertyName);
            bool isSubscript = getter != null ? getter.IsSubscript :
                               setter.IsSubscript;

            if (!getter.IsTypeSpecGeneric(swiftPropertyType))
            {
                AddUsingBlock(packs, propertyType);
            }

            var uselessLine = new ICodeElement [] { CSReturn.ReturnLine(new CSIdentifier("useless")) };

            CSCodeBlock getterBlock = null;

            if (getter != null)
            {
                getterBlock = new CSCodeBlock(uselessLine);
            }
            CSCodeBlock setterBlock = null;

            if (setter != null)
            {
                setterBlock = new CSCodeBlock(uselessLine);
            }

            CSProperty theProp = null;

            if (isSubscript)
            {
                List <ParameterItem> swiftParms = null;
                if (getter != null)
                {
                    swiftParms = getter.ParameterLists [1];
                }
                else
                {
                    swiftParms = setter.ParameterLists [1].Skip(1).ToList();
                }
                var args = typeMap.MapParameterList(getter, swiftParms, false, false, null, null);
                args.ForEach(a => AddUsingBlock(packs, a.Type));

                var csParams =
                    new CSParameterList(
                        args.Select(a =>
                                    new CSParameter(a.Type.ToCSType(packs),
                                                    new CSIdentifier(a.Name), a.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null)));
                theProp = new CSProperty(propertyType.ToCSType(packs), methodKind, CSVisibility.Public, getterBlock,
                                         CSVisibility.Public, setterBlock, csParams);
            }
            else
            {
                theProp = new CSProperty(propertyType.ToCSType(packs), methodKind,
                                         new CSIdentifier(propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock);
            }
            if (getterBlock != null)
            {
                getterBlock.Clear();
            }
            if (setterBlock != null)
            {
                setterBlock.Clear();
            }

            return(theProp);
        }