/// <summary> /// Constructor. /// </summary> /// <param name="configuration">Configuration</param> private CompilationContext(LanguageServicesConfiguration configuration) { this.Configuration = configuration; this.ActiveCompilationTarget = configuration.CompilationTargets.First(); this.SolutionMap = new Dictionary<CompilationTarget, Solution>(); this.PSharpProjectMap = new Dictionary<CompilationTarget, List<PSharpProject>>(); }
private CompilationModules GetCompileModules(CompilationTarget target) { // The only thing that matters is the runtime environment // when loading the compilation modules, so use that as the cache key var key = Tuple.Create( target.Name, _environment.RuntimeFramework, _environment.Configuration, "compilemodules"); return(_cache.Get <CompilationModules>(key, _ => { var modules = new List <ICompileModule>(); var preprocessAssembly = _loadContext.Load(new AssemblyName(target.Name + "!preprocess")); foreach (var preprocessType in preprocessAssembly.ExportedTypes) { if (preprocessType.GetTypeInfo().ImplementedInterfaces.Contains(typeof(ICompileModule))) { var module = (ICompileModule)ActivatorUtilities.CreateInstance(_services, preprocessType); modules.Add(module); } } return new CompilationModules { Modules = modules, }; })); }
public async Task TestDiscovery(DnxSdk sdk) { using (var server = sdk.Dth.CreateServer()) using (var client = server.CreateClient()) { var solution = TestProjectsRepository.EnsureRestoredSolution("DthTestProjects"); var project = solution.GetProject("EmptyConsoleApp"); client.Initialize(project.ProjectDirectory); client.DrainMessage(7); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(IPAddress.Loopback, server.Port)); var stream = new NetworkStream(socket); var compiler = new DesignTimeHostCompiler(stream); client.SendPayLoad(1, DthMessageTypes.EnumerateProjectContexts); var target = new CompilationTarget("EmptyConsoleApp", VersionUtility.ParseFrameworkName("dnx451"), "Debug", aspect: null); var response = await compiler.Compile(project.ProjectDirectory, target); Assert.NotNull(response); Assert.Empty(response.Diagnostics); Assert.NotEmpty(response.AssemblyBytes); } }
public async Task <CompileResponse> Compile(string projectPath, CompilationTarget library) { var contexts = await _projectContexts.Task.ConfigureAwait(false); int contextId; if (!contexts.TryGetValue(projectPath, out contextId)) { throw new InvalidOperationException($"The context of the project at {projectPath} could not be determined. This can happen if a project references other projects by source, and those projects have a global.json file specifying a different version of the SDK."); } _queue.Send(new GetCompiledAssemblyMessage { Name = library.Name, Configuration = library.Configuration, TargetFramework = library.TargetFramework, Aspect = library.Aspect, ContextId = contextId }); _watcher.WatchProject(projectPath); var task = _compileResponses.GetOrAdd(contextId, _ => new TaskCompletionSource <CompileResponse>()).Task; return(await task.ConfigureAwait(false)); }
/// <summary> /// Constructor. /// </summary> /// <param name="configuration">Configuration</param> private CompilationContext(LanguageServicesConfiguration configuration) { this.Configuration = configuration; this.ActiveCompilationTarget = configuration.CompilationTargets.First(); this.SolutionMap = new Dictionary <CompilationTarget, Solution>(); this.PSharpProjectMap = new Dictionary <CompilationTarget, List <PSharpProject> >(); }
public CompilationProjectContext( CompilationTarget target, string projectDirectory, string projectFilePath, string title, string description, string copyright, string version, Version assemblyFileVersion, bool embedInteropTypes, CompilationFiles files, ICompilerOptions compilerOptions) { Target = target; ProjectDirectory = projectDirectory; ProjectFilePath = projectFilePath; Files = files; Title = title; Description = description; Copyright = copyright; Version = version; AssemblyFileVersion = assemblyFileVersion; EmbedInteropTypes = embedInteropTypes; CompilerOptions = compilerOptions; }
public static Assembly CompileCode(string code, CompilationTarget target = CompilationTarget.Library) { var parsed = new LightParser().Parse(code); AssertEx.That(() => !parsed.HasErrors); var processor = TestEnvironment.Container.Resolve <LightProcessor>(); processor.Process(parsed.Root, new ProcessingOptions { ReferencedAssemblies = { typeof(CompilationHelper).Assembly } }); var assemblyName = GetAssemblyName(); var compilationArguments = new CompilationArguments { AssemblyName = assemblyName, AssemblyVersion = new Version(0, 1, 0, 0), Target = target }; var stream = new MemoryStream(); var compiler = TestEnvironment.Container.Resolve <LightCompiler>(); compiler.Compile((AstRoot)parsed.Root, stream, compilationArguments); var bytes = stream.ToArray(); var assembly = Assembly.Load(bytes); WriteAssemblyOnDiskAndPEVerify(assembly, bytes, target); return(assembly); }
public LibraryExport GetLibraryExport(CompilationTarget target) { Project project; // Can't find a project file with the name so bail if (!_projectResolver.TryResolveProject(target.Name, out project)) { return null; } var targetFrameworkInformation = project.GetTargetFramework(target.TargetFramework); // This is the target framework defined in the project. If there were no target frameworks // defined then this is the targetFramework specified if (targetFrameworkInformation.FrameworkName != null) { target = target.ChangeTargetFramework(targetFrameworkInformation.FrameworkName); } var metadataReferences = new List<IMetadataReference>(); var sourceReferences = new List<ISourceReference>(); if (!string.IsNullOrEmpty(targetFrameworkInformation.AssemblyPath)) { var assemblyPath = ResolvePath(project, target.Configuration, targetFrameworkInformation.AssemblyPath); var pdbPath = ResolvePath(project, target.Configuration, targetFrameworkInformation.PdbPath); metadataReferences.Add(new CompiledProjectMetadataReference(project.ToCompilationContext(target), assemblyPath, pdbPath)); } else { var libraryManager = _serviceProvider.GetService<IOrchardLibraryManager>(); return libraryManager.GetLibraryExport(target.Name, target.Aspect); } return new LibraryExport(metadataReferences, sourceReferences); }
// you should be able to find assemblies in c:\Users\<user>\AppData\Local\Temp\Light.Tests\ private static void WriteAssemblyOnDiskAndPEVerify(Assembly assembly, byte[] bytes, CompilationTarget target) { var outputDirectory = Path.Combine(Path.GetTempPath(), "Light.Tests", TestContext.CurrentContext.Parent.Test.Name); Directory.CreateDirectory(outputDirectory); var extension = target == CompilationTarget.Console ? ".exe" : ".dll"; var path = Path.Combine(outputDirectory, assembly.GetName().Name + extension); File.WriteAllBytes(path, bytes); PEVerifier.Verify(path, assembly); }
private static void PrepareCompilation(ICompilerOptions compilerOptions, out RoslynCompiler compiler, out CompilationProjectContext projectContext) { var cacheContextAccessor = new FakeCacheContextAccessor { Current = new CacheContext(null, (d) => { }) }; compiler = new RoslynCompiler(null, cacheContextAccessor, new FakeNamedDependencyProvider(), null, null, null); var compilationTarget = new CompilationTarget("test", new FrameworkName(".NET Framework, Version=4.0"), "Release", null); projectContext = new CompilationProjectContext( compilationTarget, Directory.GetCurrentDirectory(), "project.json", "title", "description", "copyright", "1.0.0", new System.Version(1, 0), false, new CompilationFiles(Enumerable.Empty<string>(), Enumerable.Empty<string>()), compilerOptions); }
public Assembly Load(AssemblyName assemblyName) { Project project; string name = assemblyName.FullName; if (!Project.TryGetProject(_virtualPathProvider.Combine(_path, name), out project)) { return(null); } return(_cache.Get <Assembly>(assemblyName.Name, cacheContext => { var target = new CompilationTarget( name, project.GetTargetFramework(_applicationEnvironment.RuntimeFramework).FrameworkName, _applicationEnvironment.Configuration, null); _moduleContext = new ModuleLoaderContext( _serviceProvider, project.ProjectDirectory, target.Configuration, target.TargetFramework); foreach (var lib in _moduleContext.DependencyWalker.Libraries) { _libraryManager.AddLibrary(lib.ToLibrary()); } var compilationEngineFactory = new CompilationEngineFactory( NoopWatcher.Instance, new CompilationCache()); var engine = compilationEngineFactory.CreateEngine(new CompilationEngineContext( _moduleContext.LibraryManager, _moduleContext.ProjectGraphProvider, _moduleContext.ServiceProvider, target.TargetFramework, target.Configuration)); _packageAssemblyLookup.AddLoader( _moduleContext.NuGetDependencyProvider); var p = engine.LoadProject(project, null, _assemblyLoadContextAccessor.Default); var exports = engine.RootLibraryExporter.GetExport(project.Name); foreach (var metadataReference in exports.MetadataReferences) { _libraryManager.AddMetadataReference(metadataReference); } return p; })); }
static void ParseCommandLineArgs(string[] args) { var showHelp = args.Length == 0; string vsVersions = string.Join(", ", Enum.GetNames(typeof(VisualStudioVersion)) .Select(s => s.StartsWith("VS", StringComparison.InvariantCulture) ? s.Substring(2) : s)); var optionSet = new Mono.Options.OptionSet() { { "gen=", "target generator (C, C++, Obj-C, Java)", v => Generator = v }, { "p|platform=", "target platform (iOS, macOS, Android, Windows)", v => Platform = v }, { "o|out|outdir=", "output directory", v => OutputDir = v }, { "c|compile", "compiles the generated output", v => CompileCode = true }, { "d|debug", "enables debug mode for generated native and managed code", v => DebugMode = true }, { "t|target=", "compilation target (static, shared, app)", v => Target = ConvertToCompilationTarget(v) }, { "dll|shared", "compiles as a shared library", v => Target = CompilationTarget.SharedLibrary }, { "static", "compiles as a static library", v => Target = CompilationTarget.StaticLibrary }, { "vs=", $"Visual Studio version for compilation: {vsVersions} (defaults to Latest)", v => VsVersion = v }, { "v|verbose", "generates diagnostic verbose output", v => Verbose = true }, { "h|help", "show this message and exit", v => showHelp = v != null }, }; Generator = "C"; VsVersion = "latest"; try { Assemblies = optionSet.Parse(args); } catch (Mono.Options.OptionException e) { Console.WriteLine(e.Message); Environment.Exit(0); } if (showHelp) { // Print usage and exit. Console.WriteLine("{0} [options]+ ManagedAssembly.dll", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine("Generates target language bindings for interop with managed code."); Console.WriteLine(); optionSet.WriteOptionDescriptions(Console.Out); Environment.Exit(0); } if (Assemblies == null || Assemblies.Count == 0) { Console.WriteLine("At least one managed assembly must be passed as input."); Environment.Exit(0); } }
internal static CompilationProjectContext ToCompilationContext(this Project project, CompilationTarget target) { Debug.Assert(string.Equals(target.Name, project.Name, StringComparison.Ordinal), "The provided target should be for the current project!"); return new CompilationProjectContext( target, project.ProjectDirectory, project.ProjectFilePath, project.Version.GetNormalizedVersionString(), project.AssemblyFileVersion, project.EmbedInteropTypes, project.Files.GetCompilationFiles(), project.GetCompilerOptions(target.TargetFramework, target.Configuration)); }
private static void PrepareCompilation(ICompilerOptions compilerOptions, out RoslynCompiler compiler, out CompilationProjectContext projectContext) { var cacheContextAccessor = new FakeCacheContextAccessor { Current = new CacheContext(null, (d) => { }) }; compiler = new RoslynCompiler(null, cacheContextAccessor, new FakeNamedDependencyProvider(), null, null, null); var compilationTarget = new CompilationTarget("test", new FrameworkName(".NET Framework, Version=4.0"), "Release", null); projectContext = new CompilationProjectContext( compilationTarget, Directory.GetCurrentDirectory(), "project.json", "title", "description", "copyright", "1.0.0", new System.Version(1, 0), false, new CompilationFiles(Enumerable.Empty <string>(), Enumerable.Empty <string>()), compilerOptions); }
public Assembly Load(AssemblyName assemblyName) { Project project; string name = assemblyName.FullName; if (!Project.TryGetProject(_virtualPathProvider.Combine(_path, name), out project)) { return null; } return _cache.Get<Assembly>(assemblyName.Name, cacheContext => { var target = new CompilationTarget( name, project.GetTargetFramework(_applicationEnvironment.RuntimeFramework).FrameworkName, _applicationEnvironment.Configuration, null); _moduleContext = new ModuleLoaderContext( _serviceProvider, project.ProjectDirectory, target.Configuration, target.TargetFramework); foreach (var lib in _moduleContext.DependencyWalker.Libraries) { _libraryManager.AddLibrary(lib.ToLibrary()); } var compilationEngineFactory = new CompilationEngineFactory( NoopWatcher.Instance, new CompilationCache()); var engine = compilationEngineFactory.CreateEngine(new CompilationEngineContext( _moduleContext.LibraryManager, _moduleContext.ProjectGraphProvider, _moduleContext.ServiceProvider, target.TargetFramework, target.Configuration)); _packageAssemblyLookup.AddLoader( _moduleContext.NuGetDependencyProvider); var p = engine.LoadProject(project, null, _assemblyLoadContextAccessor.Default); var exports = engine.RootLibraryExporter.GetExport(project.Name); foreach (var metadataReference in exports.MetadataReferences) { _libraryManager.AddMetadataReference(metadataReference); } return p; }); }
public void DoesNotOssSignAndInPreproccessAssembly() { // Arrange var compilerOptions = new FakeCompilerOptions() { UseOssSigning = true }; var target = new CompilationTarget(TestName, new FrameworkName(TestFrameworkName), string.Empty, "preprocess"); // Act var compilationContext = Compile(compilerOptions, target); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilationContext.Compilation.Options.OutputKind); Assert.Equal(null, compilationContext.Compilation.Options.CryptoKeyFile); Assert.Equal(0, compilationContext.Compilation.Options.CryptoPublicKey.Length); Assert.False(compilationContext.Compilation.Options.DelaySign); }
public CompilationProjectContext( CompilationTarget target, string projectDirectory, string projectFilePath, string version, Version assemblyFileVersion, bool embedInteropTypes, CompilationFiles files, ICompilerOptions compilerOptions) { Target = target; ProjectDirectory = projectDirectory; ProjectFilePath = projectFilePath; Files = files; Version = version; AssemblyFileVersion = assemblyFileVersion; EmbedInteropTypes = embedInteropTypes; CompilerOptions = compilerOptions; }
public async Task<CompileResponse> Compile(string projectPath, CompilationTarget library) { var contexts = await _projectContexts.Task.ConfigureAwait(false); int contextId; if (!contexts.TryGetValue(projectPath, out contextId)) { throw new InvalidOperationException($"The context of the project at {projectPath} could not be determined. This can happen if a project references other projects by source, and those projects have a global.json file specifying a different version of the SDK."); } _queue.Send(new GetCompiledAssemblyMessage { Name = library.Name, Configuration = library.Configuration, TargetFramework = library.TargetFramework, Aspect = library.Aspect, ContextId = contextId }); var task = _compileResponses.GetOrAdd(contextId, _ => new TaskCompletionSource<CompileResponse>()).Task; return await task.ConfigureAwait(false); }
public LibraryExport GetLibraryExport(CompilationTarget target) { Project project; // Can't find a project file with the name so bail if (!_projectResolver.TryResolveProject(target.Name, out project)) { return(null); } var targetFrameworkInformation = project.GetTargetFramework(target.TargetFramework); // This is the target framework defined in the project. If there were no target frameworks // defined then this is the targetFramework specified if (targetFrameworkInformation.FrameworkName != null) { target = target.ChangeTargetFramework(targetFrameworkInformation.FrameworkName); } var metadataReferences = new List <IMetadataReference>(); var sourceReferences = new List <ISourceReference>(); if (!string.IsNullOrEmpty(targetFrameworkInformation.AssemblyPath)) { var assemblyPath = ResolvePath(project, target.Configuration, targetFrameworkInformation.AssemblyPath); var pdbPath = ResolvePath(project, target.Configuration, targetFrameworkInformation.PdbPath); metadataReferences.Add(new CompiledProjectMetadataReference(project.ToCompilationContext(target), assemblyPath, pdbPath)); } else { var libraryManager = _serviceProvider.GetService <IOrchardLibraryManager>(); return(libraryManager.GetLibraryExport(target.Name, target.Aspect)); } return(new LibraryExport(metadataReferences, sourceReferences)); }
public static Assembly CompileCode(string code, CompilationTarget target = CompilationTarget.Library) { var parsed = new LightParser().Parse(code); AssertEx.That(() => !parsed.HasErrors); var processor = TestEnvironment.Container.Resolve<LightProcessor>(); processor.Process(parsed.Root); var assemblyName = GetAssemblyName(); var compilationArguments = new CompilationArguments { AssemblyName = assemblyName, AssemblyVersion = new Version(0, 1, 0, 0), Target = target }; var stream = new MemoryStream(); var compiler = TestEnvironment.Container.Resolve<LightCompiler>(); compiler.Compile((AstRoot)parsed.Root, stream, compilationArguments); var bytes = stream.ToArray(); var assembly = Assembly.Load(bytes); WriteAssemblyOnDiskAndPEVerify(assembly, bytes, target); return assembly; }
/// <summary> /// Constructor. /// </summary> protected Configuration() { this.SolutionFilePath = ""; this.OutputFilePath = ""; this.ProjectName = ""; this.Timeout = 0; this.PauseOnAssertionFailure = false; this.InteroperationEnabled = true; this.CompilationTarget = CompilationTarget.Execution; this.OptimizationTarget = OptimizationTarget.Release; this.CustomCompilerPassAssemblyPaths = new HashSet<string>(); this.AnalyzeDataFlow = false; this.AnalyzeDataRaces = false; this.DoStateTransitionAnalysis = false; this.ShowControlFlowInformation = false; this.ShowDataFlowInformation = false; this.ShowFullDataFlowInformation = false; this.AssemblyToBeAnalyzed = ""; this.ScheduleFile = ""; this.SchedulingStrategy = SchedulingStrategy.Random; this.SchedulingIterations = 1; this.RandomSchedulingSeed = null; this.PerformFullExploration = false; this.MaxSchedulingSteps = 0; this.ParallelBugFindingTasks = 1; this.TestingSchedulerProcessId = -1; this.TestingProcessId = -1; this.ConsiderDepthBoundHitAsBug = false; this.PrioritySwitchBound = 0; this.DelayBound = 0; this.CoinFlipBound = 0; this.SafetyPrefixBound = 0; this.AttachDebugger = false; this.ScheduleIntraMachineConcurrency = false; this.LivenessTemperatureThreshold = 0; this.CacheProgramState = false; this.EnableCycleReplayingStrategy = false; this.BoundOperations = false; this.DynamicEventQueuePrioritization = false; this.EnableDataRaceDetection = false; this.EnableVisualization = false; this.ContainerId = 0; this.NumberOfContainers = 1; this.RemoteApplicationFilePath = ""; this.Verbose = 1; this.ShowWarnings = false; this.EnableDebugging = false; this.EnableProfiling = false; this.KeepTemporaryFiles = false; this.RedirectTestConsoleOutput = true; this.PrintTrace = false; this.SuppressTrace = false; this.ThrowInternalExceptions = false; }
public Assembly Load(AssemblyName assemblyName) { Project project; string name = assemblyName.FullName; if (!Project.TryGetProject(_virtualPathProvider.Combine(_path, name), out project)) { return(null); } var cache = (ICache)_serviceProvider.GetService(typeof(ICache)); var target = new CompilationTarget( name, project.GetTargetFramework(_applicationEnvironment.RuntimeFramework).FrameworkName, _applicationEnvironment.Configuration, null); ModuleLoaderContext moduleContext = new ModuleLoaderContext( _serviceProvider, project.ProjectDirectory); moduleContext.DependencyWalker.Walk(name, project.Version, target.TargetFramework); var cacheContextAccessor = (ICacheContextAccessor)_serviceProvider.GetService(typeof(ICacheContextAccessor)); var loadContextFactory = (IAssemblyLoadContextFactory)_serviceProvider.GetService(typeof(IAssemblyLoadContextFactory)) ?? new AssemblyLoadContextFactory(_serviceProvider); var compiler = new InternalRoslynCompiler( cache, cacheContextAccessor, new NamedCacheDependencyProvider(), loadContextFactory, _fileWatcher, _applicationEnvironment, _serviceProvider); _orchardLibraryManager.AddAdditionalRegistrations(moduleContext.DependencyWalker.Libraries); var exports = ProjectExportProviderHelper.GetExportsRecursive( _orchardLibraryManager, moduleContext.LibraryExportProvider, new CompilationTarget(name, target.TargetFramework, target.Configuration, target.Aspect), true); _orchardLibraryManager.AddAdditionalLibraryExportRegistrations(name, exports); foreach (var dependency in project.Dependencies) { if (!_orchardLibraryManager.MetadataReferences.ContainsKey(dependency.Name)) { continue; } exports.MetadataReferences.Add(_orchardLibraryManager.MetadataReferences[dependency.Name]); } var compliationContext = compiler.CompileProject( project.ToCompilationContext(target), exports.MetadataReferences, exports.SourceReferences, () => CompositeResourceProvider.Default.GetResources(project)); var roslynProjectReference = new RoslynProjectReference(compliationContext); _orchardLibraryManager.AddMetadataReference(name, roslynProjectReference); var loadContext = _assemblyLoadContextAccessor.Default; return(roslynProjectReference.Load(loadContext)); }
/// <summary> /// Constructor. /// </summary> protected Configuration() { this.SolutionFilePath = ""; this.OutputFilePath = ""; this.ProjectName = ""; this.Timeout = 0; this.PauseOnAssertionFailure = false; this.InteroperationEnabled = true; this.CompilationTarget = CompilationTarget.Execution; this.OptimizationTarget = OptimizationTarget.Release; this.CustomCompilerPassAssemblyPaths = new HashSet <string>(); this.AnalyzeDataFlow = false; this.AnalyzeDataRaces = false; this.DoStateTransitionAnalysis = false; this.ShowControlFlowInformation = false; this.ShowDataFlowInformation = false; this.ShowFullDataFlowInformation = false; this.AssemblyToBeAnalyzed = ""; this.TestMethodName = ""; this.ScheduleFile = ""; this.SchedulingStrategy = SchedulingStrategy.Random; this.SchedulingIterations = 1; this.RandomSchedulingSeed = null; this.PerformFullExploration = false; this.MaxFairSchedulingSteps = 0; this.MaxUnfairSchedulingSteps = 0; this.UserExplicitlySetMaxFairSchedulingSteps = false; this.ParallelBugFindingTasks = 1; this.TestingSchedulerProcessId = -1; this.TestingProcessId = -1; this.ConsiderDepthBoundHitAsBug = false; this.PrioritySwitchBound = 0; this.DelayBound = 0; this.CoinFlipBound = 0; this.SafetyPrefixBound = 0; this.AttachDebugger = false; this.ScheduleIntraMachineConcurrency = false; this.LivenessTemperatureThreshold = 0; this.CacheProgramState = false; this.EnableCycleReplayingStrategy = false; this.BoundOperations = false; this.DynamicEventQueuePrioritization = false; this.EnableDataRaceDetection = false; this.ReportCodeCoverage = false; this.ContainerId = 0; this.NumberOfContainers = 1; this.RemoteApplicationFilePath = ""; this.Verbose = 1; this.ShowWarnings = false; this.EnableDebugging = false; this.EnableProfiling = false; this.KeepTemporaryFiles = false; this.RedirectTestConsoleOutput = true; this.PrintTrace = false; this.SuppressTrace = false; this.ThrowInternalExceptions = false; }
// you should be able to find assemblies in c:\Users\<user>\AppData\Local\Temp\Light.Tests\ private static void WriteAssemblyOnDiskAndPEVerify(Assembly assembly, byte[] bytes, CompilationTarget target) { var parent = TestContext.CurrentContext.Parent; while (parent.Test.CodeElement.Kind != CodeElementKind.Type) { parent = parent.Parent; } var outputDirectory = Path.Combine(Path.GetTempPath(), "Light.Tests", parent.Test.Name); Directory.CreateDirectory(outputDirectory); var extension = target == CompilationTarget.Console ? ".exe" : ".dll"; var path = Path.Combine(outputDirectory, assembly.GetName().Name + extension); File.WriteAllBytes(path, bytes); foreach (var referenced in ReferencedAssemblies) { var referencePath = Path.Combine(outputDirectory, Path.GetFileName(referenced.Location)); lock (parent) { if (!File.Exists(referencePath) || File.GetLastWriteTimeUtc(referencePath) < File.GetLastWriteTimeUtc(referenced.Location)) { File.Copy(referenced.Location, referencePath, true); } } } PEVerifier.Verify(path, assembly); }
private static CompilationContext Compile(FakeCompilerOptions compilerOptions, CompilationTarget target) { var cacheContextAccessor = new FakeCacheContextAccessor { Current = new CacheContext(null, (d) => { }) }; var compilationProjectContext = new CompilationProjectContext( target, Directory.GetCurrentDirectory(), "project.json", TestTitle, TestDescription, TestCopyright, TestVersion, Version.Parse(TestAssemblyFileVersion), false, new CompilationFiles( new List <string> { }, new List <string> { }), compilerOptions); var compiler = new RoslynCompiler(null, cacheContextAccessor, new FakeNamedDependencyProvider(), null, null, null); var assembly = typeof(object).GetTypeInfo().Assembly; var metadataReference = new FakeMetadataReference() { MetadataReference = MetadataReference.CreateFromFile((string)assembly.GetType().GetProperty("Location").GetValue(assembly)) }; var compilationContext = compiler.CompileProject( compilationProjectContext, new List <IMetadataReference> { metadataReference }, new List <ISourceReference> { }, () => new List <ResourceDescriptor>(), "Debug"); return(compilationContext); }
public static Assembly CompileFromResource(string resourceName, CompilationTarget target = CompilationTarget.Library) { var code = Resource.ReadAllText(typeof(Resource), resourceName); return(CompileCode(code, target)); }
public static CompilationTarget ChangeAspect(this CompilationTarget target, string aspect) { return(new CompilationTarget(target.Name, target.TargetFramework, target.Configuration, aspect)); }
private CompilationModules GetCompileModules(CompilationTarget target, string configuration) { // The only thing that matters is the runtime environment // when loading the compilation modules, so use that as the cache key var key = Tuple.Create( target.Name, _environment.RuntimeFramework, configuration, "compilemodules"); return _cache.Get<CompilationModules>(key, _ => { var modules = new List<ICompileModule>(); var preprocessAssembly = _loadContext.Load(new AssemblyName(target.Name + "!preprocess")); foreach (var preprocessType in preprocessAssembly.ExportedTypes) { if (preprocessType.GetTypeInfo().ImplementedInterfaces.Contains(typeof(ICompileModule))) { var module = (ICompileModule)ActivatorUtilities.CreateInstance(_services, preprocessType); modules.Add(module); } } return new CompilationModules { Modules = modules, }; }); }
// you should be able to find assemblies in c:\Users\<user>\AppData\Local\Temp\Light.Tests\ private static void WriteAssemblyOnDiskAndPEVerify(Assembly assembly, byte[] bytes, CompilationTarget target) { var parent = TestContext.CurrentContext.Parent; while (parent.Test.CodeElement.Kind != CodeElementKind.Type) { parent = parent.Parent; } var outputDirectory = Path.Combine(Path.GetTempPath(), "Light.Tests", parent.Test.Name); Directory.CreateDirectory(outputDirectory); var extension = target == CompilationTarget.Console ? ".exe" : ".dll"; var path = Path.Combine(outputDirectory, assembly.GetName().Name + extension); File.WriteAllBytes(path, bytes); foreach (var referenced in ReferencedAssemblies) { var referencePath = Path.Combine(outputDirectory, Path.GetFileName(referenced.Location)); lock (parent) { if (!File.Exists(referencePath) || File.GetLastWriteTimeUtc(referencePath) < File.GetLastWriteTimeUtc(referenced.Location)) File.Copy(referenced.Location, referencePath, true); } } PEVerifier.Verify(path, assembly); }
public static CompilationTarget ChangeTargetFramework(this CompilationTarget target, FrameworkName targetFramework) { return(new CompilationTarget(target.Name, targetFramework, target.Configuration, target.Aspect)); }
public static Assembly CompileFromResource(string resourceName, CompilationTarget target = CompilationTarget.Library) { var code = Resource.ReadAllText(typeof(Resource), resourceName); return CompileCode(code, target); }
internal static CompilationProjectContext ToCompilationContext(this Project project, CompilationTarget target) { Debug.Assert(string.Equals(target.Name, project.Name, StringComparison.Ordinal), "The provided target should be for the current project!"); return(new CompilationProjectContext( target, project.ProjectDirectory, project.ProjectFilePath, project.Version.GetNormalizedVersionString(), project.AssemblyFileVersion, project.EmbedInteropTypes, project.Files.GetCompilationFiles(), project.GetCompilerOptions(target.TargetFramework, target.Configuration))); }
private static CompilationContext Compile(FakeCompilerOptions compilerOptions, CompilationTarget target) { var cacheContextAccessor = new FakeCacheContextAccessor {Current = new CacheContext(null, (d) => { })}; var compilationProjectContext = new CompilationProjectContext( target, Directory.GetCurrentDirectory(), "project.json", TestTitle, TestDescription, TestCopyright, TestVersion, Version.Parse(TestAssemblyFileVersion), false, new CompilationFiles( new List<string> {}, new List<string> {}), compilerOptions); var compiler = new RoslynCompiler(null, cacheContextAccessor, new FakeNamedDependencyProvider(), null, null, null); var assembly = typeof (object).GetTypeInfo().Assembly; var metadataReference = new FakeMetadataReference() { MetadataReference = MetadataReference.CreateFromFile((string)assembly.GetType().GetProperty("Location").GetValue(assembly)) }; var compilationContext = compiler.CompileProject( compilationProjectContext, new List<IMetadataReference> { metadataReference }, new List<ISourceReference> {}, () => new List<ResourceDescriptor>(), "Debug"); return compilationContext; }
/// <summary> /// Constructor. /// </summary> protected Configuration() { this.SolutionFilePath = string.Empty; this.OutputFilePath = string.Empty; this.ProjectName = string.Empty; this.Timeout = 0; this.CompilationTarget = CompilationTarget.Execution; this.OptimizationTarget = OptimizationTarget.Release; this.CustomCompilerPassAssemblyPaths = new HashSet <string>(); this.AnalyzeDataFlow = false; this.AnalyzeDataRaces = false; this.DoStateTransitionAnalysis = false; this.ShowControlFlowInformation = false; this.ShowDataFlowInformation = false; this.ShowFullDataFlowInformation = false; this.RewriteCSharpVersion = new Version(); this.RuntimeGeneration = 0; this.AssemblyToBeAnalyzed = string.Empty; this.TestingRuntimeAssembly = string.Empty; this.TestMethodName = string.Empty; this.SchedulingStrategy = SchedulingStrategy.Random; this.ReductionStrategy = ReductionStrategy.None; this.SchedulingIterations = 1; this.RandomSchedulingSeed = null; this.IncrementalSchedulingSeed = false; this.PerformFullExploration = false; this.MaxFairSchedulingSteps = 0; this.MaxUnfairSchedulingSteps = 0; this.UserExplicitlySetMaxFairSchedulingSteps = false; this.ParallelBugFindingTasks = 1; this.RunAsParallelBugFindingTask = false; this.TestingSchedulerEndPoint = Guid.NewGuid().ToString(); this.TestingSchedulerProcessId = -1; this.TestingProcessId = 0; this.ConsiderDepthBoundHitAsBug = false; this.PrioritySwitchBound = 0; this.DelayBound = 0; this.CoinFlipBound = 0; this.SafetyPrefixBound = 0; this.EnableLivenessChecking = true; this.LivenessTemperatureThreshold = 0; this.EnableCycleDetection = false; this.EnableUserDefinedStateHashing = false; this.EnableMonitorsInProduction = false; this.EnableNoApiCallAfterTransitionStmtAssertion = true; this.AttachDebugger = false; this.ScheduleFile = string.Empty; this.ScheduleTrace = string.Empty; this.EnableDataRaceDetection = false; this.ReportCodeCoverage = false; this.ReportActivityCoverage = false; this.DebugActivityCoverage = false; this.ContainerId = 0; this.NumberOfContainers = 1; this.RemoteApplicationFilePath = string.Empty; this.Verbose = 1; this.ShowWarnings = false; this.EnableDebugging = false; this.EnableProfiling = false; this.KeepTemporaryFiles = false; this.EnableColoredConsoleOutput = false; this.ThrowInternalExceptions = false; this.DisableEnvironmentExit = true; }
public Assembly Load(AssemblyName assemblyName) { Project project; string name = assemblyName.FullName; if (!Project.TryGetProject(_virtualPathProvider.Combine(_path, name), out project)) { return null; } var cache = (ICache)_serviceProvider.GetService(typeof(ICache)); var target = new CompilationTarget( name, project.GetTargetFramework(_applicationEnvironment.RuntimeFramework).FrameworkName, _applicationEnvironment.Configuration, null); ModuleLoaderContext moduleContext = new ModuleLoaderContext( _serviceProvider, project.ProjectDirectory); moduleContext.DependencyWalker.Walk(name, project.Version, target.TargetFramework); var cacheContextAccessor = (ICacheContextAccessor)_serviceProvider.GetService(typeof(ICacheContextAccessor)); var loadContextFactory = (IAssemblyLoadContextFactory)_serviceProvider.GetService(typeof(IAssemblyLoadContextFactory)) ?? new AssemblyLoadContextFactory(_serviceProvider); var compiler = new InternalRoslynCompiler( cache, cacheContextAccessor, new NamedCacheDependencyProvider(), loadContextFactory, _fileWatcher, _applicationEnvironment, _serviceProvider); _orchardLibraryManager.AddAdditionalRegistrations(moduleContext.DependencyWalker.Libraries); var exports = ProjectExportProviderHelper.GetExportsRecursive( _orchardLibraryManager, moduleContext.LibraryExportProvider, new CompilationTarget(name, target.TargetFramework, target.Configuration, target.Aspect), true); _orchardLibraryManager.AddAdditionalLibraryExportRegistrations(name, exports); foreach (var dependency in project.Dependencies) { if (!_orchardLibraryManager.MetadataReferences.ContainsKey(dependency.Name)) continue; exports.MetadataReferences.Add(_orchardLibraryManager.MetadataReferences[dependency.Name]); } var compliationContext = compiler.CompileProject( project.ToCompilationContext(target), exports.MetadataReferences, exports.SourceReferences, () => CompositeResourceProvider.Default.GetResources(project)); var roslynProjectReference = new RoslynProjectReference(compliationContext); _orchardLibraryManager.AddMetadataReference(name, roslynProjectReference); var loadContext = _assemblyLoadContextAccessor.Default; return roslynProjectReference.Load(loadContext); }
public static CompilationTarget ChangeName(this CompilationTarget target, string name) { return(new CompilationTarget(name, target.TargetFramework, target.Configuration, target.Aspect)); }
protected override bool ParseOption(string name, Bpl.CommandLineOptionEngine.CommandLineParseState ps) { var args = ps.args; // convenient synonym switch (name) { case "dprelude": if (ps.ConfirmArgumentCount(1)) { DafnyPrelude = args[ps.i]; } return(true); case "dprint": if (ps.ConfirmArgumentCount(1)) { DafnyPrintFile = args[ps.i]; } return(true); case "printMode": if (ps.ConfirmArgumentCount(1)) { if (args[ps.i].Equals("Everything")) { PrintMode = PrintModes.Everything; } else if (args[ps.i].Equals("NoIncludes")) { PrintMode = PrintModes.NoIncludes; } else if (args[ps.i].Equals("NoGhost")) { PrintMode = PrintModes.NoGhost; } else if (args[ps.i].Equals("DllEmbed")) { PrintMode = PrintModes.DllEmbed; } else { throw new Exception("Invalid value for printMode"); } } return(true); case "rprint": if (ps.ConfirmArgumentCount(1)) { DafnyPrintResolvedFile = args[ps.i]; } return(true); case "view": if (ps.ConfirmArgumentCount(1)) { DafnyPrintExportedViews = args[ps.i].Split(',').ToList(); } return(true); case "compile": { int compile = 0; if (ps.GetNumericArgument(ref compile, 5)) { // convert option to two booleans Compile = compile != 0; ForceCompile = compile == 2 || compile == 4; RunAfterCompile = compile == 3 || compile == 4; } return(true); } case "compileTarget": if (ps.ConfirmArgumentCount(1)) { if (args[ps.i].Equals("cs")) { CompileTarget = CompilationTarget.Csharp; } else if (args[ps.i].Equals("js")) { CompileTarget = CompilationTarget.JavaScript; } else if (args[ps.i].Equals("go")) { CompileTarget = CompilationTarget.Go; } else if (args[ps.i].Equals("java")) { CompileTarget = CompilationTarget.Java; } else if (args[ps.i].Equals("php")) { CompileTarget = CompilationTarget.Php; } else { throw new Exception("Invalid value for compileTarget"); } } return(true); case "compileVerbose": { int verbosity = 0; if (ps.GetNumericArgument(ref verbosity, 2)) { CompileVerbose = verbosity == 1; } return(true); } case "dafnyVerify": { int verify = 0; if (ps.GetNumericArgument(ref verify, 2)) { DafnyVerify = verify != 0; // convert to boolean } return(true); } case "spillTargetCode": { int spill = 0; if (ps.GetNumericArgument(ref spill, 4)) { SpillTargetCode = spill; } return(true); } case "out": { if (ps.ConfirmArgumentCount(1)) { DafnyPrintCompiledFile = args[ps.i]; } return(true); } case "coverage": { if (ps.ConfirmArgumentCount(1)) { CoverageLegendFile = args[ps.i]; } return(true); } case "dafnycc": Dafnycc = true; Induction = 0; Compile = false; UseAbstractInterpretation = false; // /noinfer return(true); case "noCheating": { int cheat = 0; // 0 is default, allows cheating if (ps.GetNumericArgument(ref cheat, 2)) { DisallowSoundnessCheating = cheat == 1; } return(true); } case "pmtrace": MatchCompilerDebug = true; return(true); case "titrace": TypeInferenceDebug = true; return(true); case "induction": ps.GetNumericArgument(ref Induction, 4); return(true); case "inductionHeuristic": ps.GetNumericArgument(ref InductionHeuristic, 7); return(true); case "noIncludes": DisallowIncludes = true; return(true); case "noExterns": DisallowExterns = true; return(true); case "noNLarith": DisableNLarith = true; return(true); case "arith": { int a = 0; if (ps.GetNumericArgument(ref a, 11)) { ArithMode = a; } return(true); } case "autoReqPrint": if (ps.ConfirmArgumentCount(1)) { AutoReqPrintFile = args[ps.i]; } return(true); case "noAutoReq": ignoreAutoReq = true; return(true); case "allowGlobals": AllowGlobals = true; return(true); case "stats": PrintStats = true; return(true); case "funcCallGraph": PrintFunctionCallGraph = true; return(true); case "warnShadowing": WarnShadowing = true; return(true); case "verifyAllModules": VerifyAllModules = true; return(true); case "separateModuleOutput": SeparateModuleOutput = true; return(true); case "deprecation": { int d = 1; if (ps.GetNumericArgument(ref d, 3)) { DeprecationNoise = d; } return(true); } case "countVerificationErrors": { int countErrors = 1; // defaults to reporting verification errors if (ps.GetNumericArgument(ref countErrors, 2)) { CountVerificationErrors = countErrors == 1; } return(true); } case "printTooltips": PrintTooltips = true; return(true); case "autoTriggers": { int autoTriggers = 0; if (ps.GetNumericArgument(ref autoTriggers, 2)) { AutoTriggers = autoTriggers == 1; } return(true); } case "rewriteFocalPredicates": { int rewriteFocalPredicates = 0; if (ps.GetNumericArgument(ref rewriteFocalPredicates, 2)) { RewriteFocalPredicates = rewriteFocalPredicates == 1; } return(true); } case "optimize": { Optimize = true; return(true); } case "allocated": { ps.GetNumericArgument(ref Allocated, 5); return(true); } case "noIronDafny": { IronDafny = false; return(true); } case "ironDafny": { IronDafny = true; return(true); } case "optimizeResolution": { int d = 2; if (ps.GetNumericArgument(ref d, 3)) { OptimizeResolution = d; } return(true); } case "definiteAssignment": { int da = 0; if (ps.GetNumericArgument(ref da, 4)) { DefiniteAssignmentLevel = da; } return(true); } case "useRuntimeLib": { UseRuntimeLib = true; return(true); } case "disableScopes": { DisableScopes = true; return(true); } case "printIncludes": if (ps.ConfirmArgumentCount(1)) { if (args[ps.i].Equals("None")) { PrintIncludesMode = IncludesModes.None; } else if (args[ps.i].Equals("Immediate")) { PrintIncludesMode = IncludesModes.Immediate; } else if (args[ps.i].Equals("Transitive")) { PrintIncludesMode = IncludesModes.Transitive; } else { throw new Exception("Invalid value for includesMode"); } if (PrintIncludesMode == IncludesModes.Immediate || PrintIncludesMode == IncludesModes.Transitive) { Compile = false; DontShowLogo = true; DafnyVerify = false; } } return(true); default: break; } // not a Dafny-specific option, so defer to superclass return(base.ParseOption(name, ps)); }
public AssemblyResolver(CompilationTarget target) => _target = target;