Ejemplo n.º 1
0
        public void TestSizeof(string typeName, string expected)
        {
            using (DisposableTempDirectory temp = new DisposableTempDirectory(null, true)) {
                string csFile = Path.Combine(temp.DirectoryPath, temp.UniqueName("CS", "", "cs"));
                string source = $@"using System;
using SwiftRuntimeLibrary;

using SwiftRuntimeLibrary.SwiftMarshal;
namespace dlopentest
{{
	class MainClass
	{{
		public static void Main (string[] args)
		{{
			var size = StructMarshal.Marshaler.Sizeof(typeof({typeName}));
			Console.WriteLine(size);
		}}
	}}
}}";
                source += TestRunning.GetManagedConsoleRedirectCode();
                File.WriteAllText(csFile, source);

                Compiler.CSCompile(temp.DirectoryPath, new string [] { csFile }, "TestIt.exe", $"-lib:{Compiler.CompilerLocation.SwiftCompilerLib}");
                TestRunning.CopyTestReferencesTo(temp.DirectoryPath);

                string output = Compiler.RunWithMono(Path.Combine(temp.DirectoryPath, "TestIt.exe"), temp.DirectoryPath);
                Assert.AreEqual(expected, output);
            }
        }
Ejemplo n.º 2
0
        public static void TestAndExecuteNoDevice(string swiftCode, CodeElementCollection <ICodeElement> callingCode,
                                                  string expectedOutput, string testName = null,
                                                  PlatformName platform       = PlatformName.None,
                                                  UnicodeMapper unicodeMapper = null)
        {
            SetInvokingTestNameIfUnset(ref testName, out string nameSpace);

            using (var provider = new DisposableTempDirectory()) {
                var compiler = Utils.CompileSwift(swiftCode, provider, nameSpace);

                var libName           = $"lib{nameSpace}.dylib";
                var tempDirectoryPath = Path.Combine(provider.DirectoryPath, "BuildDir");
                Directory.CreateDirectory(tempDirectoryPath);
                File.Copy(Path.Combine(compiler.DirectoryPath, libName), Path.Combine(tempDirectoryPath, libName));

                Utils.CompileToCSharp(provider, tempDirectoryPath, nameSpace, unicodeMapper: unicodeMapper);

                CSFile csFile = TestRunningCodeGenerator.GenerateTestEntry(callingCode, testName, nameSpace, platform);
                csFile.Namespaces.Add(CreateManagedConsoleRedirect());
                CodeWriter.WriteToFile(Path.Combine(tempDirectoryPath, "NameNotImportant.cs"), csFile);

                var sourceFiles = Directory.GetFiles(tempDirectoryPath, "*.cs");
                Compiler.CSCompile(tempDirectoryPath, sourceFiles, "NameNotImportant.exe", platform: platform);

                CopyTestReferencesTo(tempDirectoryPath, platform);

                var output = Execute(tempDirectoryPath, "NameNotImportant.exe", platform);
                Assert.AreEqual(expectedOutput, output);
            }
        }
Ejemplo n.º 3
0
 public CustomSwiftCompiler(SwiftTargetCompilerInfo compilerInfo,
                            DisposableTempDirectory fileProvider,          // can be null
                            bool disposeSuppliedDirectory)
 {
     CompilerInfo         = compilerInfo;
     tempDirectory        = fileProvider ?? new DisposableTempDirectory(null, true);
     disposeTempDirectory = fileProvider != null ? disposeSuppliedDirectory : true;
 }
Ejemplo n.º 4
0
        public void WrapSingleMethod(string type, string returnVal)
        {
            string simpleClass = String.Format("public final class Monty {{ public init() {{ }}\n public func val() -> {0} {{ return {1}; }} }}", type, returnVal);

            using (DisposableTempDirectory provider = new DisposableTempDirectory(null, false)) {
                Utils.CompileSwift(simpleClass, provider);
                Utils.CompileToCSharp(provider);
            }
        }
Ejemplo n.º 5
0
        void CheckName(string typeName, string expected)
        {
            using (DisposableTempDirectory temp = new DisposableTempDirectory(null, true)) {
                string csFile = Path.Combine(temp.DirectoryPath, temp.UniqueName("CS", "", "cs"));
                string source = $@"using System;
using SwiftRuntimeLibrary;

using SwiftRuntimeLibrary.SwiftMarshal;

namespace dlopentest
{{
	class MainClass
	{{
		public static void Main (string[] args)
		{{
			SwiftNominalTypeDescriptor nt = StructMarshal.Marshaler.Metatypeof(typeof({typeName})).GetNominalTypeDescriptor();
			Console.WriteLine(nt.GetFullName());
		}}
	}}
}}";
                source += TestRunning.GetManagedConsoleRedirectCode();
                File.WriteAllText(csFile, source);
                Compiler.CSCompile(temp.DirectoryPath, new string [] { csFile }, "TestIt.exe", $"-lib:{Compiler.CompilerLocation.SwiftCompilerLib}", PlatformName.macOS);
                TestRunning.CopyTestReferencesTo(temp.DirectoryPath);

                string output = Compiler.RunWithMono(Path.Combine(temp.DirectoryPath, "TestIt.exe"), temp.DirectoryPath, platform: PlatformName.macOS);
                Assert.AreEqual(expected, output);

                string tsource = $@"using System;
using NewClassCompilerTests;
using SwiftRuntimeLibrary;
using TomTest;
using SwiftRuntimeLibrary.SwiftMarshal;

namespace MetatypeTests
{{
	public class CheckName{typeName} : ITomTest
	{{
		public void Run()
		{{
			SwiftNominalTypeDescriptor nt = StructMarshal.Marshaler.Metatypeof(typeof({typeName})).GetNominalTypeDescriptor();
			Console.WriteLine(nt.GetMangledName());
		}}

		public string TestName {{ get {{ return ""CheckName{typeName}""; }} }}
		public string ExpectedOutput {{ get {{ return {ToStringLiteral (expected)}; }} }}
	}}
}}";

                string thisTestPath = Path.Combine(Compiler.kSwiftDeviceTestRoot, "MetatypeTests");

                Directory.CreateDirectory(thisTestPath);
                string tpath = Path.Combine(thisTestPath, $"CheckName{typeName}.cs");
                File.WriteAllText(tpath, tsource);
            }
        }
Ejemplo n.º 6
0
        public void GetDirectLayoutModuleName()
        {
            using (var tmp = new DisposableTempDirectory()) {
                CreateFileAtLocation(tmp.DirectoryPath, "Foo");
                Assert.IsNull(SwiftModuleFinder.GetDirectLayoutModuleName(Path.Combine(tmp.DirectoryPath, "Foo")));

                CreateFileAtLocation(tmp.DirectoryPath, "Bar.swiftmodule");
                Assert.AreEqual("Bar", SwiftModuleFinder.GetDirectLayoutModuleName(Path.Combine(tmp.DirectoryPath, "Bar.swiftmodule")));
            }
        }
Ejemplo n.º 7
0
        public void GetAppleModuleName_RequiresValidName()
        {
            using (var tmp = new DisposableTempDirectory()) {
                CreateFileAtLocation(tmp.DirectoryPath, "Foo", "Modules", "Foo.swiftmodule");
                Assert.IsNull(SwiftModuleFinder.GetAppleModuleName(Path.Combine(tmp.DirectoryPath, "Foo")));

                CreateFileAtLocation(tmp.DirectoryPath, ".framework", "Modules", ".swiftmodule");
                Assert.IsNull(SwiftModuleFinder.GetAppleModuleName(Path.Combine(tmp.DirectoryPath, ".framework")));
            }
        }
Ejemplo n.º 8
0
        public static string CompileToCSharp(DisposableTempDirectory provider, string outputDirectory = null, string moduleName = "Xython", string target = "x86_64-apple-macosx10.9", IEnumerable <string> additionalTypeDatabases = null, bool separateProcess = false, UnicodeMapper unicodeMapper = null, int expectedErrorCount = -1)
        {
            NewClassCompiler ncc = DefaultCSharpCompiler(unicodeMapper);

            List <string> typeDatabases = Compiler.kTypeDatabases;

            if (additionalTypeDatabases != null)
            {
                typeDatabases.AddRange(additionalTypeDatabases);
            }

            ClassCompilerLocations classCompilerLocations = new ClassCompilerLocations(new List <string> {
                provider.DirectoryPath, Compiler.kSwiftRuntimeGlueDirectory
            },
                                                                                       new List <string> {
                provider.DirectoryPath, Compiler.kSwiftRuntimeGlueDirectory
            },
                                                                                       typeDatabases);
            ClassCompilerNames compilerNames = new ClassCompilerNames(moduleName, null);

            if (separateProcess)
            {
                var args = new StringBuilder();
                args.Append($"--debug ");
                args.Append($"{Path.Combine (Path.GetDirectoryName (ncc.GetType ().Assembly.Location), "tom-swifty.exe")} ");
                args.Append($"--swift-bin-path={StringUtils.Quote (Compiler.CompilerLocation.SwiftCompilerBin)} ");
                args.Append($"--swift-lib-path={StringUtils.Quote (Path.GetDirectoryName (Compiler.CompilerLocation.SwiftCompilerLib))} ");
                args.Append($"--retain-xml-reflection ");
                foreach (var db in typeDatabases)
                {
                    args.Append($"--type-database-path={StringUtils.Quote (db)} ");
                }
                args.Append($"--retain-swift-wrappers ");
                args.Append($"--wrapping-module-name={StringUtils.Quote (moduleName)}Wrapping ");
                foreach (var l in classCompilerLocations.LibraryDirectories)
                {
                    args.Append($"-L {StringUtils.Quote (l)} ");
                }
                foreach (var m in classCompilerLocations.ModuleDirectories)
                {
                    args.Append($"-M {StringUtils.Quote (m)} ");
                }
                args.Append($"-o {StringUtils.Quote (outputDirectory ?? provider.DirectoryPath)} ");
                args.Append($"--module-name={StringUtils.Quote (moduleName)} ");
                return(ExecAndCollect.Run("mono", args.ToString()));
            }
            else
            {
                ErrorHandling errors = ncc.CompileToCSharp(classCompilerLocations, compilerNames, new List <string> {
                    target
                }, outputDirectory ?? provider.DirectoryPath);
                CheckErrors(errors, expectedErrorCount);
                return(null);
            }
        }
        public void RelativePathsInSymlinks2()
        {
            using (var dir = new DisposableTempDirectory()) {
                var expectedPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(dir.DirectoryPath)));

                var link2 = Path.Combine(dir.DirectoryPath, "link2");
                symlink(Path.Combine(dir.DirectoryPath, "..", "..", ".."), link2);
                var finalPath = PosixHelpers.RealPath(link2);
                Assert.AreEqual(expectedPath, finalPath, "2");
            }
        }
Ejemplo n.º 10
0
        public void GetAppleModuleName_OnlyWorksWithValidStructure()
        {
            using (var tmp = new DisposableTempDirectory()) {
                string framework = Path.Combine(tmp.DirectoryPath, "Foo.framework");
                Directory.CreateDirectory(Path.Combine(framework, "Modules"));
                Assert.IsNull(SwiftModuleFinder.GetAppleModuleName(framework));

                File.Create(Path.Combine(framework, "Modules", "Foo.swiftmodule"));
                Assert.AreEqual("Foo", SwiftModuleFinder.GetAppleModuleName(framework));
            }
        }
Ejemplo n.º 11
0
        public void GetXamarinModuleName_OnlyWorksWithValidStructure()
        {
            const string Arch = "x86_64";

            using (var tmp = new DisposableTempDirectory()) {
                string folder = Path.Combine(tmp.DirectoryPath, "Foo");
                Directory.CreateDirectory(Path.Combine(folder, Arch));
                Assert.IsNull(SwiftModuleFinder.GetXamarinModuleName(folder, Arch));

                CreateFileAtLocation(folder, "x86_64", "Foo.swiftmodule");
                Assert.AreEqual("Foo", SwiftModuleFinder.GetXamarinModuleName(folder, Arch));
            }
        }
Ejemplo n.º 12
0
        string RunBindingToolsForSwift(string swiftCode, string testName = null)
        {
            var nameSpace = "OutputTests";

            using (TempDirectoryFilenameProvider provider = new TempDirectoryFilenameProvider()) {
                var compiler = Utils.CompileSwift(swiftCode, provider, nameSpace);

                var libName = $"lib{nameSpace}.dylib";

                using (DisposableTempDirectory temp = new DisposableTempDirectory()) {
                    File.Copy(Path.Combine(compiler.DirectoryPath, libName), Path.Combine(temp.DirectoryPath, libName));

                    return(Utils.CompileToCSharp(provider, temp.DirectoryPath, nameSpace, separateProcess: true));
                }
            }
        }
Ejemplo n.º 13
0
        static void Compile(SwiftyOptions options, UnicodeMapper unicodeMapper, ErrorHandling errors)
        {
            try {
                using (DisposableTempDirectory temp = new DisposableTempDirectory(null, true)) {
                    SwiftCompilerLocation compilerLocation = new SwiftCompilerLocation(options.SwiftBinPath, options.SwiftLibPath);
                    ClassCompilerOptions  compilerOptions  = new ClassCompilerOptions(options.TargetPlatformIs64Bit, options.Verbose, options.RetainXmlReflection, options.RetainSwiftWrappingCode);
                    NewClassCompiler      classCompiler    = new NewClassCompiler(compilerLocation, compilerOptions, unicodeMapper);

                    ClassCompilerNames     compilerNames          = new ClassCompilerNames(options.ModuleName, options.WrappingModuleName);
                    ClassCompilerLocations classCompilerLocations = new ClassCompilerLocations(options.ModulePaths, options.DylibPaths, options.TypeDatabasePaths);
                    var compileErrors = classCompiler.CompileToCSharp(classCompilerLocations, compilerNames, options.Targets, options.OutputDirectory);
                    errors.Add(compileErrors);
                }
            } catch (Exception err) {
                errors.Add(err);
            }
        }
Ejemplo n.º 14
0
        public static CustomSwiftCompiler CompileSwift(string swiftCode, DisposableTempDirectory provider = null, string moduleName = "Xython", string target = "x86_64-apple-macosx10.9")
        {
            CustomSwiftCompiler compiler = DefaultSwiftCompiler(provider, target: target);

            string []     includeDirectories = null;
            List <string> libraryDirectories = new List <string> {
                compiler.DirectoryPath, Compiler.kSwiftRuntimeGlueDirectory
            };

            if (provider != null)
            {
                includeDirectories = new string [] { provider.DirectoryPath };
                libraryDirectories.Add(provider.DirectoryPath);
            }

            SwiftCompilerOptions options = new SwiftCompilerOptions(moduleName, includeDirectories, libraryDirectories.ToArray(), new string [] { "XamGlue" });

            compiler.CompileString(options, swiftCode);
            return(compiler);
        }
        public FileResult Download(RegionalSubbasinRevisionRequestPrimaryKey regionalSubbasinRevisionRequestPrimaryKey)
        {
            var geometry = regionalSubbasinRevisionRequestPrimaryKey.EntityObject
                           .RegionalSubbasinRevisionRequestGeometry;

            var reprojectedGeometry = CoordinateSystemHelper.ProjectWebMercatorTo2230(geometry);

            var geoJson = DbGeometryToGeoJsonHelper.FromDbGeometryWithNoReproject(reprojectedGeometry);

            var serializedGeoJson = JsonConvert.SerializeObject(geoJson);

            var outputLayerName = $"BMP_{regionalSubbasinRevisionRequestPrimaryKey.EntityObject.TreatmentBMP.TreatmentBMPID}_RevisionRequest";

            using (var workingDirectory = new DisposableTempDirectory())
            {
                var outputPathForLayer =
                    Path.Combine(workingDirectory.DirectoryInfo.FullName, outputLayerName);


                var ogr2OgrCommandLineRunner = new Ogr2OgrCommandLineRunner(NeptuneWebConfiguration.Ogr2OgrExecutable,
                                                                            CoordinateSystemHelper.NAD_83_CA_ZONE_VI_SRID,
                                                                            NeptuneWebConfiguration.HttpRuntimeExecutionTimeout.TotalMilliseconds);

                ogr2OgrCommandLineRunner.ImportGeoJsonToFileGdb(serializedGeoJson, outputPathForLayer,
                                                                outputLayerName, false, true);

                using (var zipFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".zip"))
                {
                    ZipFile.CreateFromDirectory(workingDirectory.DirectoryInfo.FullName, zipFile.FileInfo.FullName);
                    var fileStream = zipFile.FileInfo.OpenRead();
                    var bytes      = fileStream.ReadFully();
                    fileStream.Close();
                    fileStream.Dispose();
                    return(File(bytes, "application/zip", $"{outputLayerName}.zip"));
                }
            }
        }
Ejemplo n.º 16
0
        public static CustomSwiftCompiler DefaultSwiftCompiler(DisposableTempDirectory provider = null, string target = "x86_64-apple-macosx10.9")
        {
            var targetInfo = Compiler.CompilerLocation.GetTargetInfo(target);

            return(new CustomSwiftCompiler(targetInfo, provider, false));
        }
Ejemplo n.º 17
0
        public static void TestAndExecute(string swiftCode, CodeElementCollection <ICodeElement> callingCode,
                                          string expectedOutput,
                                          string testName                  = null,
                                          CSClass otherClass               = null, string skipReason = null,
                                          string iosExpectedOutput         = null,
                                          PlatformName platform            = PlatformName.None,
                                          UnicodeMapper unicodeMapper      = null, int expectedErrorCount = 0,
                                          Action <string> postCompileCheck = null,
                                          string[] expectedOutputContains  = null)
        {
            SetInvokingTestNameIfUnset(ref testName, out string nameSpace);
            string testClassName = "TomTest" + testName;

            using (var provider = new DisposableTempDirectory()) {
                var compiler = Utils.CompileSwift(swiftCode, provider, nameSpace);

                var libName           = $"lib{nameSpace}.dylib";
                var tempDirectoryPath = Path.Combine(provider.DirectoryPath, "BuildDir");
                Directory.CreateDirectory(tempDirectoryPath);
                File.Copy(Path.Combine(compiler.DirectoryPath, libName), Path.Combine(tempDirectoryPath, libName));

                Utils.CompileToCSharp(provider, tempDirectoryPath, nameSpace, unicodeMapper: unicodeMapper, expectedErrorCount: expectedErrorCount);
                if (postCompileCheck != null)
                {
                    postCompileCheck(tempDirectoryPath);
                }

                Tuple <CSNamespace, CSUsingPackages> testClassParts = TestRunningCodeGenerator.CreateTestClass(callingCode, testName, iosExpectedOutput ?? expectedOutput, nameSpace,
                                                                                                               testClassName, otherClass, skipReason, platform);

                var thisTestPath = Path.Combine(Compiler.kSwiftDeviceTestRoot, nameSpace);
                Directory.CreateDirectory(thisTestPath);

                var thisTestPathSwift = Path.Combine(thisTestPath, "swiftsrc");
                Directory.CreateDirectory(thisTestPathSwift);

                var swiftPrefix = string.Empty;
                var swiftSuffix = string.Empty;
                var csPrefix    = string.Empty;
                var csSuffix    = string.Empty;
                var nameSuffix  = string.Empty;
                switch (platform)
                {
                case PlatformName.macOS:
                    swiftPrefix = "#if os(OSX)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __MACOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_macOS";
                    break;

                case PlatformName.iOS:
                    swiftPrefix = "#if os(iOS)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __IOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_iOS";
                    break;

                case PlatformName.tvOS:
                    swiftPrefix = "#if os(tvOS)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __TVOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_tvOS";
                    break;

                case PlatformName.watchOS:
                    swiftPrefix = "#if os(watchOS)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __WATCHOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_watchOS";
                    break;

                case PlatformName.None:
                    break;

                default:
                    throw new NotImplementedException(platform.ToString());
                }

                File.WriteAllText(Path.Combine(thisTestPathSwift, $"{testClassName}{testName}{nameSuffix}.swift"), swiftPrefix + swiftCode + swiftSuffix);

                CSFile csTestFile     = CSFile.Create(testClassParts.Item2, testClassParts.Item1);
                var    csTestFilePath = Path.Combine(thisTestPath, $"{testClassName}{testName}{nameSuffix}.cs");
                // Write out the file without csPrefix/csSuffix
                CodeWriter.WriteToFile(csTestFilePath, csTestFile);
                if (!string.IsNullOrEmpty(csPrefix) || !string.IsNullOrEmpty(csSuffix))
                {
                    // Read the C# code, and prepend/append the csPrefix/csSuffix blobs, then save the modified contents again.
                    File.WriteAllText(csTestFilePath, csPrefix + File.ReadAllText(csTestFilePath) + csSuffix);
                }

                var csFile = TestRunningCodeGenerator.GenerateTestEntry(callingCode, testName, nameSpace, platform, otherClass);
                csFile.Namespaces.Add(CreateManagedConsoleRedirect());
                CodeWriter.WriteToFile(Path.Combine(tempDirectoryPath, "NameNotImportant.cs"), csFile);

                var sourceFiles     = Directory.GetFiles(tempDirectoryPath, "*.cs");
                var objcRuntimePath = Path.Combine(tempDirectoryPath, "ObjCRuntime");
                if (Directory.Exists(objcRuntimePath))
                {
                    sourceFiles = sourceFiles.And(Directory.GetFiles(objcRuntimePath, "*.cs"));
                }

                var compilerWarnings = Compiler.CSCompile(tempDirectoryPath, sourceFiles, "NameNotImportant.exe", platform: platform);

                if (compilerWarnings.Contains("warning"))
                {
                    FailOnBadWarnings(compilerWarnings);
                }

                CopyTestReferencesTo(tempDirectoryPath, platform);

                var output = Execute(tempDirectoryPath, "NameNotImportant.exe", platform);
                if (expectedOutput != null)
                {
                    Assert.AreEqual(expectedOutput, output);
                }
                else
                {
                    foreach (var s in expectedOutputContains)
                    {
                        Assert.IsTrue(output.Contains(s), $"Expected to find string {s} in {output}");
                    }
                }
            }
        }