string CompileWithInvokingCode(CSFile cs, CSLine invoker, string nameSpace) { CSNamespace ns = new CSNamespace(nameSpace); CSCodeBlock mainBody = CSCodeBlock.Create(invoker); CSMethod main = new CSMethod(CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void, new CSIdentifier("Main"), new CSParameterList(new CSParameter(new CSSimpleType("string", true), "args")), mainBody); CSClass cl = new CSClass(CSVisibility.Public, "NameNotImportant", new CSMethod [] { main }); ns.Block.Add(cl); cs.Namespaces.Add(ns); using (DisposableTempFile csOut = new DisposableTempFile(null, null, "cs", true)) { CodeWriter.WriteToFile(csOut.Filename, cs); using (Stream csExeStm = Compiler.CompileUsing(null, XCodeCompiler.CSharpExe, csOut.Filename, $"-lib:{kSwiftRuntimeMacOutputDirectory} -r:{kSwiftRuntimeLibraryMac}")) { using (DisposableTempFile csExe = new DisposableTempFile(null, null, "exe", true)) { csExeStm.CopyTo(csExe.Stream); csExe.Stream.Close(); string output = Compiler.RunWithMono(csExe.Filename); return(output); } } } }
public static CSFile GenerateTestEntry(CodeElementCollection <ICodeElement> callingCode, string testName, string nameSpace, PlatformName platform, CSClass otherClass = null) { var use = GetTestEntryPointUsings(nameSpace, platform); var ns = new CSNamespace(nameSpace); if (otherClass != null) { ns.Block.Add(otherClass); } var mainBody = new CSCodeBlock(callingCode); mainBody.Add(CaptureSwiftOutputPostlude(testName)); var main = new CSMethod(CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void, (CSIdentifier)"Main", new CSParameterList(new CSParameter(CSSimpleType.CreateArray("string"), "args")), mainBody); var mainClass = new CSClass(CSVisibility.Public, "NameNotImportant", new CSMethod [] { main }); AddSupportingCode(mainClass, platform); ns.Block.Add(mainClass); return(CSFile.Create(use, ns)); }
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 CSDocument Create(DataSet dataset, string dbContextName, string defaultNamespaceName, string projectName) { DbClass cls = new DbClass(dataset, dbContextName); CSDocument document = new CSDocument(dbContextName, projectName); CSNamespace ns = CreateNamespace(defaultNamespaceName, GetUsingList(defaultNamespaceName), cls); document.Namespaces.Add(ns); return(document); }
private CSDocument Create(DataTable dataTable, string namespaceName, string projectName) { CSNamespace ns = new CSNamespace(namespaceName); CSDocument document = new CSDocument(dataTable.TableName, projectName); ns.Classes.Add(new ModelClass(dataTable)); document.Namespaces.Add(ns); return(document); }
private CSDocument Create(DataTable dataTable, string namespaceName, string projectName) { RepositoryPackClass cls = new RepositoryPackClass(dataTable); CSDocument document = new CSDocument(dataTable.TableName, projectName); CSNamespace ns = CreateNamespace(CreateNamespaceName(namespaceName, dataTable.TableName), GetUsingList(namespaceName, dataTable.TableName), cls); document.Namespaces.Add(ns); return(document); }
private CSDocument Create(DataTable dataTable, string defaultNamespaceName, string projectName) { DeleteClass cls = new DeleteClass(dataTable); CSDocument document = new CSDocument(dataTable.TableName, projectName); CSNamespace ns = CreateNamespace(CreateNamespaceName(defaultNamespaceName, dataTable.TableName), GetUsingList(), cls); document.Namespaces.Add(ns); return(document); }
protected virtual CSNamespace CreateNamespace(string namespaceName, string[] usingNamespaceList, T cls) { CSNamespace ns = new CSNamespace(namespaceName, false); foreach (var item in usingNamespaceList) { ns.IncludeNamespaces.Add($"using {item};"); } ns.Classes.Add(cls); return(ns); }
private CSDocument Create(DataTable dataTable, string namespaceName, string projectName) { namespaceName = CreateNamespaceName(namespaceName, dataTable.TableName); SelectClass cls = new SelectClass(dataTable); CSDocument document = new CSDocument(dataTable.TableName, projectName); CSNamespace ns = CreateNamespace(namespaceName, GetUsingList(), cls); document.Namespaces.Add(ns); return(document); }
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); }
public static Tuple <CSNamespace, CSUsingPackages> CreateTestClass(CodeElementCollection <ICodeElement> callingCode, string testName, string expectedOutput, string nameSpace, string testClassName, CSClass otherClass, string skipReason, PlatformName platform) { var use = GetTestClassUsings(nameSpace); // [TomSkip(skipReason)] // public class TomTesttestName : ITomTest // { // public testClassName() { } // public string TestName { get { return testName; } } // public string ExpectedOutput { get { return expectedOuput; } } // public void Run() { // callingCode; // } // } // otherClass CSNamespace ns = new CSNamespace(nameSpace); if (otherClass != null) { ns.Block.Add(otherClass); } CSCodeBlock body = new CSCodeBlock(callingCode); body.Add(CaptureSwiftOutputPostlude(testName)); CSMethod run = new CSMethod(CSVisibility.Public, CSMethodKind.None, CSSimpleType.Void, new CSIdentifier("Run"), new CSParameterList(), body); CSClass testClass = new CSClass(CSVisibility.Public, new CSIdentifier($"TomTest{testName}"), new CSMethod [] { run }); testClass.Inheritance.Add(new CSIdentifier("ITomTest")); testClass.Properties.Add(MakeGetOnlyStringProp("TestName", testName)); testClass.Properties.Add(MakeGetOnlyStringProp("ExpectedOutput", expectedOutput)); ns.Block.Add(testClass); if (skipReason != null) { CSArgumentList al = new CSArgumentList(); al.Add(CSConstant.Val(skipReason)); CSAttribute attr = new CSAttribute("TomSkip", al); attr.AttachBefore(testClass); } return(new Tuple <CSNamespace, CSUsingPackages> (ns, use)); }
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 static CSNamespace CreateManagedConsoleRedirect() { // Same as GetManagedConsoleRedirectCode, just different format. var cs = new CSNamespace(); var console = new CSClass(CSVisibility.Public, "Console", isStatic: true); console.Fields.Add(CSFieldDeclaration.FieldLine(CSSimpleType.String, new CSIdentifier("filename"), isStatic: true)); console.Properties.Add( new CSProperty( CSSimpleType.String, CSMethodKind.Static, new CSIdentifier("Filename"), CSVisibility.None, CSCodeBlock.Create( new CSIfElse( new CSBinaryExpression( CSBinaryOperator.Equal, new CSIdentifier("filename"), new CSIdentifier("null") ), CSCodeBlock.Create( CSAssignment.Assign( new CSIdentifier("filename"), new CSBinaryExpression( CSBinaryOperator.NullCoalesce, CSFunctionCall.Function( "Environment.GetEnvironmentVariable", CSConstant.Val("LEAKTEST_STDOUT_PATH") ), new CSIdentifier("string.Empty") ) ) ) ), CSReturn.ReturnLine(new CSIdentifier("filename")) ), CSVisibility.None, null ) ); console.Methods.Add( new CSMethod( CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void, new CSIdentifier("write"), new CSParameterList( new CSParameter(CSSimpleType.String, new CSIdentifier("value")) ), CSCodeBlock.Create( new CSIfElse( new CSIdentifier("string.IsNullOrEmpty (Filename)"), CSCodeBlock.Create(CSFunctionCall.FunctionCallLine("global::System.Console.Write", new CSIdentifier("value"))), CSCodeBlock.Create(CSFunctionCall.FunctionCallLine("System.IO.File.AppendAllText", new CSIdentifier("Filename"), new CSIdentifier("value"))) ) ) ) ); console.Methods.Add( new CSMethod( CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void, new CSIdentifier("Write"), new CSParameterList( new CSParameter(CSSimpleType.Object, new CSIdentifier("value")) ), CSCodeBlock.Create( CSFunctionCall.FunctionCallLine( "write", false, new CSIdentifier("value?.ToString ()") ) ) ) ); console.Methods.Add( new CSMethod( CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void, new CSIdentifier("Write"), new CSParameterList( new CSParameter(CSSimpleType.String, new CSIdentifier("value")), new CSParameter(CSSimpleType.CreateArray("object"), new CSIdentifier("args"), CSParameterKind.Params) ), CSCodeBlock.Create( CSFunctionCall.FunctionCallLine( "write", false, new CSIdentifier("value == null ? string.Empty : string.Format (value, args)") ) ) ) ); console.Methods.Add( new CSMethod( CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void, new CSIdentifier("WriteLine"), new CSParameterList( new CSParameter(CSSimpleType.Object, new CSIdentifier("value")) ), CSCodeBlock.Create( CSFunctionCall.FunctionCallLine( "write", false, new CSIdentifier("value?.ToString () + Environment.NewLine") ) ) ) ); console.Methods.Add( new CSMethod( CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void, new CSIdentifier("WriteLine"), new CSParameterList( new CSParameter(CSSimpleType.String, new CSIdentifier("value")), new CSParameter(CSSimpleType.CreateArray("object"), new CSIdentifier("args"), CSParameterKind.Params) ), CSCodeBlock.Create( CSFunctionCall.FunctionCallLine( "write", false, new CSIdentifier("(value == null ? string.Empty : string.Format (value, args)) + Environment.NewLine") ) ) ) ); cs.Block.Add(console); return(cs); }
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); }
/// <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); }
/// <summary> /// Read assemblies to list members /// </summary> public void Read() { foreach (ProjectInfo projectInfo in ProjectInfos) { if (!projectInfo.BuildConfigurations.ContainsKey(BuildConfiguration)) { // TODO Logs warn continue; } BuildConfiguration config = projectInfo.BuildConfigurations[BuildConfiguration]; if (string.IsNullOrWhiteSpace(config.OutputPath)) { // TODO Logs warn continue; } // Read assembly Assembly assembly = Assembly.LoadFile(Path.GetFullPath(config.OutputPath)); // Set full path in BuildConfiguration object // Create doc object XmlDoc doc = default; if (!string.IsNullOrWhiteSpace(config.DocumentationFilePath)) { doc = XmlDocDeserializer.Deserialize(config.DocumentationFilePath); } // Create assembly object CSAssembly csAssembly = new CSAssembly(assembly); CSMembers.Add(csAssembly); // Run through all the types foreach (TypeInfo type in assembly.DefinedTypes) { // Get the namespace object from the list of members CSNamespace csNamespace = CSMembers.Namespaces.FirstOrDefault(n => n.Name == type.Namespace); // If the namespace object does not exist, create it if (csNamespace == null) { csNamespace = new CSNamespace(type.Namespace); CSMembers.Add(csNamespace); } // Create type object CSType csType = default; if (type.IsClass) { // TODO Create class object csType = new CSClass(csAssembly, csNamespace, type); } // Create type object if (type.IsInterface) { // TODO Create interface object csType = new CSInterface(csAssembly, csNamespace, type); } // Create type object if (type.IsEnum) { // TODO Create enumeration object csType = new CSEnumeration(csAssembly, csNamespace, type); } // Read doc to get type summary csType.Summary = doc?.Members.FirstOrDefault(m => m.Name == csType.XmlFullName)?.Summary.Value; csAssembly.Types.Add(csType); csNamespace.Types.Add(csType); CSMembers.Add(csType); } } }