public void Matches_IsTrue_WhenParametersAreEquivalent() { var function1 = @"using System; public static void Run(string id, out string output) { output = string.Empty; }"; // Diferent formatting, qualified name, not using alias var function2 = @"using System; public static void Run( System.String id , out String output ) { string result = string.Empty; output = result; }"; var tree1 = CSharpSyntaxTree.ParseText(function1, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script)); var tree2 = CSharpSyntaxTree.ParseText(function2, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script)); var references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(string).Assembly.Location) }; var compilation1 = CSharpCompilation.Create("test1", references: references).AddSyntaxTrees(tree1); var compilation2 = CSharpCompilation.Create("test2", references: references).AddSyntaxTrees(tree1); var signature1 = CSharpFunctionSignature.FromCompilation(compilation1, new FunctionEntryPointResolver()); var signature2 = CSharpFunctionSignature.FromCompilation(compilation2, new FunctionEntryPointResolver()); Assert.True(signature1.Equals(signature2)); Assert.Equal(signature1.GetHashCode(), signature2.GetHashCode()); }
private static Assembly Compile(string razorGeneratedCode) { var razorSyntaxTree = CSharpSyntaxTree.ParseText(razorGeneratedCode); var assemblyName = Path.GetRandomFileName(); var references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(Templater).Assembly.Location), MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location) }; var compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { razorSyntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { var failures = result.Diagnostics.Where(IsError); throw new InvalidOperationException(); } ms.Seek(0, SeekOrigin.Begin); return Assembly.Load(ms.ToArray()); } }
internal static bool TryGetReference( Solution solution, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference) { // if we have one from snapshot cache, use it. it will make sure same compilation will get same metadata reference always. MetadataOnlyReferenceSet referenceSet; if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out referenceSet)) { reference = referenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); return true; } // okay, now use version based cache that can live multiple compilation as long as there is no semantic changes. // get one for the branch if (TryGetReferenceFromBranch(solution.BranchId, projectReference, finalOrDeclarationCompilation, version, out reference)) { return true; } // see whether we can use primary branch one var primaryBranchId = solution.Workspace.PrimaryBranchId; if (solution.BranchId != primaryBranchId && TryGetReferenceFromBranch(primaryBranchId, projectReference, finalOrDeclarationCompilation, version, out reference)) { return true; } // noop, we don't have any reference = null; return false; }
/// <summary> /// Adds aliases of a specified reference to the merged set of aliases. /// Consider the following special cases: /// /// o {} + {} = {} /// If neither reference has any aliases then the result has no aliases. /// /// o {A} + {} = {A, global} /// {} + {A} = {A, global} /// /// If one and only one of the references has aliases we add the global alias since the /// referenced declarations should now be accessible both via existing aliases /// as well as unqualified. /// /// o {A, A} + {A, B, B} = {A, A, B, B} /// We preserve dups in each alias array, but avoid making more dups when merging. /// </summary> internal void Merge(MetadataReference reference) { if (reference.Properties.HasRecursiveAliases) { if (RecursiveAliasesOpt == null) { RecursiveAliasesOpt = ArrayBuilder<string>.GetInstance(); RecursiveAliasesOpt.AddRange(reference.Properties.Aliases); return; } } else { if (AliasesOpt == null) { AliasesOpt = ArrayBuilder<string>.GetInstance(); AliasesOpt.AddRange(reference.Properties.Aliases); return; } } Merge( aliases: reference.Properties.HasRecursiveAliases ? RecursiveAliasesOpt : AliasesOpt, newAliases: reference.Properties.Aliases); }
/// <summary> /// Get assembly from the given text. /// </summary> /// <param name="tree">SyntaxTree</param> /// <returns>Assembly</returns> protected Assembly GetAssembly(SyntaxTree tree) { Assembly assembly = null; var references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location), MetadataReference.CreateFromFile(typeof(Machine).Assembly.Location), MetadataReference.CreateFromFile(typeof(PSharpBugFindingRuntime).Assembly.Location) }; var compilation = CSharpCompilation.Create( "PSharpTestAssembly", new[] { tree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (result.Success) { ms.Seek(0, SeekOrigin.Begin); assembly = Assembly.Load(ms.ToArray()); } } return assembly; }
private static Assembly GetAssemblyForConfiguration(string fileContents) { var tmpl = @" using UrlFactory.Core; namespace DynamicUrlFactoryConfiguration { public class ConfigFactory { public UrlRequestConfiguration GetConfiguration() { var config = new UrlRequestConfiguration(); {0} return config; } } }"; var syntaxTree = CSharpSyntaxTree.ParseText(String.Format(tmpl, fileContents)); var references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof (object).Assembly.Location), MetadataReference.CreateFromFile(typeof (UrlRequestConfiguration).Assembly.Location) }; var compilation = CSharpCompilation.Create( Path.GetRandomFileName(), syntaxTrees: new[] {syntaxTree}, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (!result.Success) { var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); if (failures.Any()) { throw new CompilationException("Could not compile config file"); } } // move to beginning of stream ms.Seek(0, SeekOrigin.Begin); var assembly = Assembly.Load(ms.ToArray()); return assembly; } }
public override PortableExecutableReference ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) { ResolutionAttempts.Add(new ReferenceAndIdentity(definition, referenceIdentity)); MetadataReference reference; string nameAndVersion = referenceIdentity.Name + (referenceIdentity.Version != AssemblyIdentity.NullVersion ? $", {referenceIdentity.Version}" : ""); return _map.TryGetValue(nameAndVersion, out reference) ? (PortableExecutableReference)reference : null; }
public IVsNavInfo CreateForReference(MetadataReference reference) { var portableExecutableReference = reference as PortableExecutableReference; if (portableExecutableReference != null) { return new NavInfo(this, libraryName: portableExecutableReference.FilePath); } return new NavInfo(this, libraryName: reference.Display); }
public static IEnumerable<IMessageHandler> CompileHandlers(IEnumerable<string> paths) { var handlers = new List<IMessageHandler>(); var assemblyName = "SkypeBot.Handlers"; var syntaxTrees = paths .Select(path => File.ReadAllText(path)) .Select(contents => CSharpSyntaxTree.ParseText(contents)) .ToArray(); var dotNetAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); var references = new MetadataReference[] { MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "mscorlib.dll")), MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.dll")), MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Core.dll")), MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Runtime.dll")), MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Xml.dll")), MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Xml.Linq.dll")), MetadataReference.CreateFromFile(typeof(Program).Assembly.Location), // SkypeBot MetadataReference.CreateFromFile(typeof(ILogger).Assembly.Location), // Serilog }; var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, references, options); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (result.Success) { var assembly = Assembly.Load(ms.ToArray()); foreach (var handlerType in assembly.GetTypes().Where(t => !t.IsInterface && typeof(IMessageHandler).IsAssignableFrom(t))) { handlers.Add((IMessageHandler)Activator.CreateInstance(handlerType)); Log.Information("Initializing handler {HandlerType}", handlerType.Name); } } else { foreach (var error in result.Diagnostics) { var message = error.GetMessage(); var span = error.Location.GetLineSpan(); Log.Error("{FileName} line {LineNumber}: {ErrorMessage:l}", span.Path, span.StartLinePosition.Line, message); } } } return handlers; }
private static CSharpCompilation Compile(string dllName, SyntaxTree[] allTrees, MetadataReference[] references) { var settings = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default) .WithOptimizationLevel(OptimizationLevel.Release); CSharpCompilation compilation = CSharpCompilation.Create( dllName, allTrees, references, settings); return compilation; }
public static void Compile(string source, string assemblyName) { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); MetadataReference[] references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location) }; CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { Console.Error.WriteLine("{0} : {1}", diagnostic.Id, diagnostic.GetMessage()); } } else { ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); Type type = assembly.GetType("RoslynCompileSample.Writer"); object obj = Activator.CreateInstance(type); Console.WriteLine("call compiled code :"); type.InvokeMember("Write", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, new object[] { "Hello World" }); } } }
public static ConversionResult ConvertText(string text, MetadataReference[] references) { if (text == null) throw new ArgumentNullException(nameof(text)); if (references == null) throw new ArgumentNullException(nameof(references)); var tree = CS.SyntaxFactory.ParseSyntaxTree(SourceText.From(text)); var compilation = CS.CSharpCompilation.Create("Conversion", new[] { tree }, references); try { return new ConversionResult(Convert((CS.CSharpSyntaxNode)tree.GetRoot(), compilation.GetSemanticModel(tree, true), null).NormalizeWhitespace().ToFullString()); } catch (Exception ex) { return new ConversionResult(ex); } }
private void Compile(CompilationItem item, IEnumerable<CompilationItem> allItems, List<RoslynCompiledItem> currentlyCompiledItems, MetadataReference auditReference) { if (currentlyCompiledItems.Any(c => c.Project == item.Project)) return; foreach (ProjectReference projectReference in item.Project.ProjectReferences) { CompilationItem referencedItem = allItems.Single(i => i.Project.Id == projectReference.ProjectId); Compile(referencedItem, allItems, currentlyCompiledItems, auditReference); } MetadataReference[] projectReferences = GetProjectReferences(item.Project, currentlyCompiledItems); MetadataReference[] auditReferences = { auditReference }; MetadataReference[] requiredReferences = projectReferences.Union(item.Project.MetadataReferences).Union(auditReferences).ToArray(); string newDllName = PathHelper.GetCoverageDllName(item.Project.Name); CSharpCompilation compilation = Compile(newDllName, item.SyntaxTrees, requiredReferences); currentlyCompiledItems.Add(new RoslynCompiledItem(item.Project, compilation)); }
public override PortableExecutableReference ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) { // resolve assemblies from the directory containing the test and from directory containing corlib string name = referenceIdentity.Name; string testDir = Path.GetDirectoryName(GetType().GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName); string testDependencyAssemblyPath = Path.Combine(testDir, name + ".dll"); if (File.Exists(testDependencyAssemblyPath)) { return MetadataReference.CreateFromFile(testDependencyAssemblyPath, s_resolvedMissingAssemblyReferenceProperties); } string fxDir = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName); string fxAssemblyPath = Path.Combine(fxDir, name + ".dll"); if (File.Exists(fxAssemblyPath)) { return MetadataReference.CreateFromFile(fxAssemblyPath, s_resolvedMissingAssemblyReferenceProperties); } return null; }
public static Compilation CreateCompilation(MetadataReference metadataReference, string language = LanguageNames.CSharp) { var references = new[] { metadataReference }; Compilation compilation = null; if (language == LanguageNames.CSharp) { compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( "Temp", references: references); } else { compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create( "Temp", references: references); } return compilation; }
internal IVsNavInfo GetReferenceNavInfo(MetadataReference reference) { var portableExcutableReference = reference as PortableExecutableReference; if (portableExcutableReference != null) { return new NavInfo( this.LibraryGuid, this.SymbolToolLanguage, libraryName: portableExcutableReference.FilePath); } var compilationReference = reference as CompilationReference; if (compilationReference != null) { return new NavInfo( this.LibraryGuid, this.SymbolToolLanguage, libraryName: compilationReference.Display); } return null; }
/// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } CheckContainsProject(projectId); return this.ForkProject( this.GetProjectState(projectId).RemoveMetadataReference(metadataReference)); }
private static bool TryGetReferenceFromBranch( BranchId branchId, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference) { // get map for the branch var mapFromBranch = s_cache.GetValue(branchId, s_createReferenceSetMap); // if we have one, return it if (mapFromBranch.TryGetValue(projectReference.ProjectId, out var referenceSet) && (version == VersionStamp.Default || referenceSet.Version == version)) { // record it to snapshot based cache. var newReferenceSet = s_snapshotCache.GetValue(finalOrDeclarationCompilation, _ => referenceSet); reference = newReferenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); return true; } reference = null; return false; }
public abstract void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity);
protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity); this.OnMetadataReferenceRemoved(projectId, metadataReference); }
private AssemblyIdentity GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference) { var project = this.CurrentSolution.GetProject(projectId); if (!project.MetadataReferences.Contains(metadataReference)) { project = project.AddMetadataReference(metadataReference); } var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol; return symbol != null ? symbol.Identity : null; }
internal abstract bool TryGetReferencedAssemblySymbol(MetadataReference reference, out IAssemblySymbol symbol, out ImmutableArray<string> aliases);
internal virtual Func <string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return((path, properties) => MetadataReference.CreateFromFile(path, properties)); }
void CreateNewReference () { timeStamp = File.GetLastWriteTimeUtc (path); if (timeStamp == NonExistentFile) { Reference = null; } else { try { Reference = MetadataReference.CreateFromFile (path, MetadataReferenceProperties.Assembly); } catch (Exception e) { LoggingService.LogError ("Error while loading reference " + path + ": " + e.Message, e); } } }
/// <summary> /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>. /// Reports inconsistencies to the given diagnostic bag. /// </summary> /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns> protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics);
protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray <MetadataReference> references, out IDictionary <ValueTuple <string, string>, MetadataReference> boundReferenceDirectives, out ImmutableArray <Location> referenceDirectiveLocations) { boundReferenceDirectives = null; ArrayBuilder <MetadataReference> referencesBuilder = ArrayBuilder <MetadataReference> .GetInstance(); ArrayBuilder <Location> referenceDirectiveLocationsBuilder = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: if (boundReferenceDirectives != null && boundReferenceDirectives.ContainsKey(ValueTuple.Create(referenceDirective.Location.SourceTree.FilePath, referenceDirective.File))) { continue; } MetadataReference boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation); if (boundReference == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File)); continue; } if (boundReferenceDirectives == null) { boundReferenceDirectives = new Dictionary <ValueTuple <string, string>, MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder <Location> .GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder.Add(referenceDirective.Location); boundReferenceDirectives.Add(ValueTuple.Create(referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference); } // add external reference at the end, so that they are processed first: referencesBuilder.AddRange(compilation.ExternalReferences); // Add all explicit references of the previous script compilation. var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousScriptCompilation != null) { referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences); } if (boundReferenceDirectives == null) { // no directive references resolved successfully: boundReferenceDirectives = SpecializedCollections.EmptyDictionary <ValueTuple <string, string>, MetadataReference>(); } references = referencesBuilder.ToImmutable(); referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray <Location> .Empty; } finally { // Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and // we don't want to clutter the test output with leak reports. referencesBuilder.Free(); } }
/// <summary> /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it. /// Two identities are considered equivalent if /// - both assembly names are strong (have keys) and are either equal or FX unified /// - both assembly names are weak (no keys) and have the same simple name. /// </summary> private MetadataReference TryAddAssembly( AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary <string, List <ReferencedAssemblyIdentity> > referencesBySimpleName, bool supersedeLowerVersions) { var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); List <ReferencedAssemblyIdentity> sameSimpleNameIdentities; if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { referencesBySimpleName.Add(identity.Name, new List <ReferencedAssemblyIdentity> { referencedAssembly }); return(null); } if (supersedeLowerVersions) { foreach (var other in sameSimpleNameIdentities) { if (identity.Version == other.Identity.Version) { return(other.Reference); } } // Keep all versions of the assembly and the first identity in the list the one with the highest version: if (sameSimpleNameIdentities[0].Identity.Version > identity.Version) { sameSimpleNameIdentities.Add(referencedAssembly); } else { sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]); sameSimpleNameIdentities[0] = referencedAssembly; } return(null); } ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity); if (identity.IsStrongName) { foreach (var other in sameSimpleNameIdentities) { // Only compare strong with strong (weak is never equivalent to strong and vice versa). // In order to eliminate duplicate references we need to try to match their identities in both directions since // ReferenceMatchesDefinition is not necessarily symmetric. // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.) if (other.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) && IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity)) { equivalent = other; break; } } } else { foreach (var other in sameSimpleNameIdentities) { // only compare weak with weak if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity)) { equivalent = other; break; } } } if (equivalent.Identity == null) { sameSimpleNameIdentities.Add(referencedAssembly); return(null); } // equivalent found - ignore and/or report an error: if (identity.IsStrongName) { Debug.Assert(equivalent.Identity.IsStrongName); // versions might have been unified for a Framework assembly: if (identity != equivalent.Identity) { // Dev12 C# reports an error // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used. // BREAKING CHANGE in VB: we report an error for both languages // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference, equivalent.Identity); } // If the versions match exactly we ignore duplicates w/o reporting errors while // Dev12 C# reports: // error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references. // Dev12 VB reports: // Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. // A second reference to 'D:\Temp\System.dll' cannot be added. } else { Debug.Assert(!equivalent.Identity.IsStrongName); // Dev12 reports an error for all weak-named assemblies, even if the versions are the same. // We treat assemblies with the same name and version equal even if they don't have a strong name. // This change allows us to de-duplicate #r references based on identities rather than full paths, // and is closer to platforms that don't support strong names and consider name and version enough // to identify an assembly. An identity without version is considered to have version 0.0.0.0. if (identity != equivalent.Identity) { MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference, equivalent.Identity); } } Debug.Assert(equivalent.Reference != null); return(equivalent.Reference); }
public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) { Identity = identity; Reference = reference; RelativeAssemblyIndex = relativeAssemblyIndex; }
public WinMdEventTests() { // The following two libraries are shrinked code pulled from // corresponding files in the csharp5 legacy tests const string eventLibSrc = @"namespace EventLibrary { public delegate void voidDelegate(); public delegate T genericDelegate<T>(T t); public delegate dynamic dynamicDelegate(dynamic D); public interface I { event voidDelegate d1; event genericDelegate<object> d2; event dynamicDelegate d3; } }"; EventLibRef = CreateCompilation( eventLibSrc, references: new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929 }, compOptions: new CSharpCompilationOptions( OutputKind.WindowsRuntimeMetadata, allowUnsafe: true), assemblyName: "EventLibrary").EmitToImageReference(); }
public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { throw new NotImplementedException(); }
public DirectiveInfo(MetadataReference metadataReference) { MetadataReference = metadataReference; IsActive = true; }
public BuildReference(MetadataReference reference, bool copyLocal = false, string path = null) { Reference = reference; CopyLocal = copyLocal; Path = path; }
/// <summary> /// Creates a new instance of this project updated to no longer include the specified metadata reference. /// </summary> public Project RemoveMetadataReference(MetadataReference metadataReference) { return this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id); }
static void Main(string[] args) { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@" using System; namespace RoslynCompileSample { public class Writer { public void Write(string message) { var prefix = GetMessagePrefix(); Console.WriteLine(prefix + ""-"" + message); } public string GetMessagePrefix() { return ""pre""; } } }"); string assemblyName = Path.GetRandomFileName(); MetadataReference[] references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location) }; string analyzerAssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\lib\DotNetDoodle.Analyzers.dll"); ImmutableArray<DiagnosticAnalyzer> diagnosticAnalyzers = new AnalyzerFileReference(analyzerAssemblyPath).GetAnalyzers(LanguageNames.CSharp); CompilationWithAnalyzers compilationWithAnalyzers = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).WithAnalyzers(diagnosticAnalyzers); ImmutableArray<Diagnostic> diagsnostics = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result; using (var ms = new MemoryStream()) { EmitResult result = compilationWithAnalyzers.Compilation.Emit(ms); ImmutableArray<Diagnostic> allDiagsnostics = result.Diagnostics.Concat(diagsnostics).ToImmutableArray(); if (!result.Success) { IEnumerable<Diagnostic> failures = allDiagsnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { Console.Error.WriteLine("ERROR: {0}: {1}", diagnostic.Id, diagnostic.GetMessage()); } WriteWarnings(allDiagsnostics); } else { WriteWarnings(allDiagsnostics); ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); Type type = assembly.GetType("RoslynCompileSample.Writer"); object obj = Activator.CreateInstance(type); type.InvokeMember("Write", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, new object[] { "Hello World" }); } } Console.ReadLine(); }
/// <summary> /// Creates a new instance of this project updated to no longer include the specified metadata reference. /// </summary> public Project RemoveMetadataReference(MetadataReference metadataReference) { return(this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id)); }
public ProjectState RemoveMetadataReference(MetadataReference toMetadata) { Contract.Requires(this.MetadataReferences.Contains(toMetadata)); return this.With( projectInfo: this.ProjectInfo.WithMetadataReferences(this.MetadataReferences.Remove(toMetadata)).WithVersion(this.Version.GetNewerVersion())); }
/// <summary> /// This method is called during ApplyChanges to remove a metadata reference from a project. /// /// Override this method to implement the capability of removing metadata references. /// </summary> protected virtual void RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { throw new NotSupportedException(); }