/// <summary> /// Note that it leaves any calls to contract methods in their original locations, /// i.e., it does *not* extract contracts. That is up to the caller of this method. /// </summary> public static bool FileToUnitAndSourceLocationProvider(IMetadataHost host, string filename, List<string> libPaths, List<string> referencedAssemblies, out IModule module, out ISourceLocationProvider/*?*/ sourceLocationProvider) { var text = File.ReadAllText(filename); CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, filename); // This ctor isn't implemented yet. //var mscorlib = new Roslyn.Compilers.AssemblyObjectReference(typeof(object).Assembly); //var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib"); // Roslyn takes care of resolving where it lives. var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); var refs = new List<MetadataReference>(); refs.Add(mscorlib); foreach (var r in referencedAssemblies) { refs.Add(new MetadataFileReference(Path.GetFileNameWithoutExtension((r)))); } var baseFileName = Path.GetFileNameWithoutExtension(filename); var defaultResolver = FileResolver.Default; var ar = new FileResolver(libPaths.Select(lp => Path.GetFullPath(lp)), defaultResolver.KeyFileSearchPaths, defaultResolver.BaseDirectory); var c = CSharpCompilation.Create( baseFileName , syntaxTrees: new SyntaxTree[] { tree } , references: refs , fileResolver: ar , options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); var diags = c.GetDiagnostics(); if (diags.Count() > 0) { foreach (var diag in diags) { Console.WriteLine(diag.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return false; } } //c = c.AddSyntaxTrees(tree); // Use this form to add another syntax tree to the same compilation (getting a new compilation since they're immutable) var binding = c.GetSemanticModel(tree); diags = binding.GetDiagnostics(); if (diags.Count() > 0) { foreach (var d in diags) { Console.WriteLine(d.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return false; } } ConvertRoslynToCCI(host, tree, binding, out module, out sourceLocationProvider); return true; }
private static Compilation CreateTestCompilation() { SyntaxTree programTree = CSharpSyntaxTree.ParseText(File.ReadAllText( @"..\..\Program.cs")); SyntaxTree rewriterTree = CSharpSyntaxTree.ParseText(File.ReadAllText(@"..\..\TypeInferenceRewriter.cs")); SyntaxTree[] sourceTrees = { programTree, rewriterTree }; MetadataReference mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); MetadataReference codeAnalysis = new MetadataFileReference(typeof(SyntaxTree).Assembly.Location); MetadataReference csharpCodeAnalysis = new MetadataFileReference(typeof(CSharpSyntaxTree).Assembly.Location); MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis }; return CSharpCompilation.Create("SyntaxRewriterTest", sourceTrees, references, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); }
void AddReference(MetadataFileReference reference) { if (references.Any(x => x.FullPath == reference.FullPath)) return; references.Add(reference); }
private bool TryResolveDependency(PackageReference dependency, LoadContext loadContext, List<string> errors, out MetadataReference resolved) { resolved = null; var childContext = new LoadContext(dependency.Name, loadContext.TargetFramework); var loadResult = _dependencyLoader.Load(childContext); if (loadResult == null) { string assemblyLocation; if (_globalAssemblyCache.TryResolvePartialName(dependency.Name, out assemblyLocation)) { resolved = new MetadataFileReference(assemblyLocation); return true; } errors.Add(String.Format("Unable to resolve dependency '{0}' for target framework '{1}'.", dependency, loadContext.TargetFramework)); return false; } if (loadResult.Errors != null) { errors.AddRange(loadResult.Errors); return false; } CompiledAssembly compiledAssembly; if (_compiledAssemblies.TryGetValue(dependency.Name, out compiledAssembly)) { resolved = compiledAssembly.MetadataReference; return true; } resolved = new MetadataFileReference(loadResult.Assembly.Location); return true; }
// Private Methods /// <summary> /// Zamienia deklarowane referencje na te, które są w katalogu aplikacji /// </summary> /// <param name="comp"></param> private static void Swap(Cs2PhpCompiler comp) { // ReSharper disable once CSharpWarnings::CS1030 #warning 'Be careful in LINUX' var files = new DirectoryInfo(ExeDir).GetFiles("*.*").ToDictionary(a => a.Name.ToLower(), a => a.FullName); var metadataFileReferences = comp.CSharpProject.MetadataReferences.OfType<MetadataFileReference>() .Select( reference => new { FileShortName = new FileInfo(reference.FilePath).Name.ToLower(), Reference = reference }) .ToArray(); foreach (var fileReference in metadataFileReferences) { string fileFullName; if (!files.TryGetValue(fileReference.FileShortName, out fileFullName)) continue; var remove = fileReference.Reference; var add = new MetadataFileReference(fileFullName, MetadataReferenceProperties.Assembly); if (remove.Display == add.Display) continue; comp.RemoveMetadataReferences(remove); comp.AddMetadataReferences(add); Console.WriteLine("Swap\r\n {0}\r\n {1}", remove.Display, add.Display); } }
// Internal Methods internal static Translator PrepareTranslator() { if (_translator != null) return _translator; var csProject = LangPhpTestCsProj; using (var comp = new Cs2PhpCompiler { VerboseToConsole = true, ThrowExceptions = true }) { Console.WriteLine("Try to load " + csProject); #if DEBUG comp.LoadProject(csProject, "DEBUG"); #else comp.LoadProject(csProject, "RELEASE"); #endif /* linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Compiler\bin\Debug\Lang.Php.Compiler.dll linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Framework\bin\Debug\Lang.Php.Framework.dll linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Test\bin\Debug\Lang.Php.dll */ Console.WriteLine("Preparing before compilation"); string[] removeL = "Lang.Php.Compiler,Lang.Php.Framework,Lang.Php".Split(','); #region Remove Lang.Php reference { foreach (var r in removeL) { // ... will be replaced by reference to dll from compiler base dir // I know - compilation libraries should be loaded into separate application domain var remove = comp.CSharpProject.MetadataReferences.FirstOrDefault(i => i.Display.EndsWith(r + ".dll")); if (remove != null) comp.RemoveMetadataReferences(remove); } } #endregion string[] filenames; #region We have to remove and add again references - strange { // in other cases some referenced libraries are ignored var refToRemove = comp.CSharpProject.MetadataReferences.OfType<MetadataFileReference>().ToList(); foreach (var i in refToRemove) comp.RemoveMetadataReferences(i); var ref1 = refToRemove.Select(i => i.FilePath).ToList(); // foreach (var r in removeL) // ref1.Add(Path.Combine(Directory.GetCurrentDirectory(), r + ".dll")); ref1.Add(typeof(DirectCallAttribute).Assembly.Location); ref1.Add(typeof(EmitContext).Assembly.Location); ref1.Add(typeof(Extension).Assembly.Location); filenames = ref1.Distinct().ToArray(); } #endregion #region Translation assemblies { comp.TranslationAssemblies.Add(typeof(Extension).Assembly); comp.TranslationAssemblies.Add(typeof(Translator).Assembly); } #endregion foreach (var fileName in filenames) { var g = new MetadataFileReference(fileName, MetadataReferenceProperties.Assembly); comp.AddMetadataReferences(g); Console.WriteLine(" Add reference {0}", g.Display); } // using (var sandbox = new AssemblySandbox()) // { // // // Console.WriteLine("Start compile"); // var result = comp.CompileCSharpProject(sandbox, comp.DllFileName); // if (!result.Success) // { // foreach (var i in result.Diagnostics) // Console.WriteLine(i); // } // Assert.True(result.Success, "Compilation failed"); // } TranslationInfo translationInfo = comp.ParseCsSource(); translationInfo.CurrentAssembly = comp.CompiledAssembly; var assemblyTi = translationInfo.GetOrMakeTranslationInfo(comp.CompiledAssembly); var ecBaseDir = Path.Combine(Directory.GetCurrentDirectory(), assemblyTi.RootPath.Replace("/", "\\")); Console.WriteLine("Output root {0}", ecBaseDir); var translationState = new TranslationState(translationInfo); _translator = new Translator(translationState); _translator.Translate(comp.Sandbox); return _translator; } }