public MetadataReference GetAddOrUpdate(string path, MetadataReferenceProperties properties)
            {
                using (_gate.DisposableWait())
                {
                    WeakReference<MetadataReference> weakref;
                    MetadataReference mref = null;

                    if (!(_references.TryGetValue(properties, out weakref) && weakref.TryGetTarget(out mref)))
                    {
                        // try to base this metadata reference off of an existing one, so we don't load the metadata bytes twice.
                        foreach (var wr in _references.Values)
                        {
                            if (wr.TryGetTarget(out mref))
                            {
                                mref = mref.WithProperties(properties);
                                break;
                            }
                        }

                        if (mref == null)
                        {
                            mref = _cache._createReference(path, properties);
                        }

                        _references[properties] = new WeakReference<MetadataReference>(mref);
                    }

                    return mref;
                }
            }
        public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
        {
            Dictionary<string, PortableExecutableReference> map;

            if (PathUtilities.IsFilePath(reference))
            {
                if (_pathResolver != null)
                {
                    reference = _pathResolver.ResolvePath(reference, baseFilePath);
                    if (reference == null)
                    {
                        return ImmutableArray<PortableExecutableReference>.Empty;
                    }
                }

                map = _files;
            }
            else
            {
                map = _assemblyNames;
            }

            PortableExecutableReference result;
            return map.TryGetValue(reference, out result) ? ImmutableArray.Create(result) : ImmutableArray<PortableExecutableReference>.Empty;
        }
Example #3
0
        internal Metadata GetMetadata(string fullPath, MetadataReferenceProperties properties)
        {
            // Check if we have an entry in the dictionary.
            FileKey? fileKey = GetUniqueFileKey(fullPath);

            Metadata metadata;
            if (fileKey.HasValue && metadataCache.TryGetValue(fileKey.Value, out metadata) && metadata != null)
            {
                CompilerServerLogger.Log("Using already loaded metadata for assembly reference '{0}'", fileKey);
                return metadata;
            }

            if (properties.Kind == MetadataImageKind.Module)
            {
                var result = CreateModuleMetadata(fullPath, prefetchEntireImage: true);
                //?? never add modules to cache?
                return result;
            }
            else
            {
                var primaryModule = CreateModuleMetadata(fullPath, prefetchEntireImage: false);

                // Get all the modules, and load them. Create an assembly metadata.
                var allModules = GetAllModules(primaryModule, Path.GetDirectoryName(fullPath));
                Metadata result = AssemblyMetadata.Create(allModules);

                result = metadataCache.GetOrAdd(fileKey.Value, result);

                return result;
            }
        }
            public ShadowCopyReference(MetadataShadowCopyProvider provider, string originalPath, MetadataReferenceProperties properties)
                : base(properties, originalPath)
            {
                Debug.Assert(originalPath != null);
                Debug.Assert(provider != null);

                _provider = provider;
            }
 public MetadataFileReference(string fullPath, MetadataReferenceProperties properties, DocumentationProvider documentation = null)
     : base(properties, fullPath, initialDocumentation: documentation ?? DocumentationProvider.Default)
 {
     if (fullPath == null)
     {
         throw new ArgumentNullException("fullPath");
     }
 }
 protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
 {
     return new MetadataImageReference(
         _metadata,
         properties,
         this.DocumentationProvider,
         this.FilePath,
         _display);
 }
        public MetadataReference GetReference(string path, MetadataReferenceProperties properties)
        {
            if (!_referenceSets.TryGetValue(path, out var referenceSet))
            {
                referenceSet = ImmutableInterlocked.GetOrAdd(ref _referenceSets, path, new ReferenceSet(this));
            }

            return referenceSet.GetAddOrUpdate(path, properties);
        }
        /// <summary>
        /// Returns an instance of the reference with specified properties, or this instance if properties haven't changed.
        /// </summary>
        /// <param name="properties">The new properties for the reference.</param>
        /// <exception cref="ArgumentException">Specified values not valid for this reference.</exception>
        public MetadataReference WithProperties(MetadataReferenceProperties properties)
        {
            if (properties == this.Properties)
            {
                return this;
            }

            return WithPropertiesImplReturningMetadataReference(properties);
        }
 protected PortableExecutableReference(
     MetadataReferenceProperties properties,
     string fullPath = null,
     DocumentationProvider initialDocumentation = null)
     : base(properties)
 {
     _filePath = fullPath;
     _lazyDocumentation = initialDocumentation;
 }
        public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
        {
            var path = PathResolver.ResolveReference(reference, baseFilePath);
            if (path == null)
            {
                return ImmutableArray<PortableExecutableReference>.Empty;
            }

            return ImmutableArray.Create(Provider.GetReference(path, properties));
        }
            public override PortableExecutableReference GetReference(string fullPath, MetadataReferenceProperties properties = default(MetadataReferenceProperties))
            {
                AssemblyMetadata metadata;
                if (_cache.TryGetValue(fullPath, out metadata))
                {
                    return metadata.GetReference(MakeDocumentationProvider());
                }

                _cache.Add(fullPath, metadata = AssemblyMetadata.CreateFromFile(fullPath));
                return metadata.GetReference(MakeDocumentationProvider());
            }
        public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
        {
            // Note: currently not handling relative paths, since we don't have tests that use them

            if (File.Exists(reference))
            {
                return ImmutableArray.Create(MetadataReference.CreateFromFile(reference, properties));
            }

            return default(ImmutableArray<PortableExecutableReference>);
        }
 public void AddProjectReference(IProjectContext project, MetadataReferenceProperties properties)
 {
     // AbstractProject and ProjectTracker track project references using the project bin output path.
     // Setting the command line arguments should have already set the output file name and folder.
     // We fetch this output path to add the reference.
     var referencedProject = this.ProjectTracker.GetProject(project.Id);
     var binPathOpt = referencedProject.TryGetBinOutputPath();
     if (!string.IsNullOrEmpty(binPathOpt))
     {
         AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(binPathOpt, properties);
     }
 }
Example #14
0
        /// <summary>
        /// Returns an instance of the reference with specified properties, or this instance if properties haven't changed.
        /// </summary>
        /// <param name="properties">The new properties for the reference.</param>
        /// <exception cref="ArgumentException">Specified values not valid for this reference.</exception> 
        public new CompilationReference WithProperties(MetadataReferenceProperties properties)
        {
            if (properties == this.Properties)
            {
                return this;
            }

            if (properties.Kind == MetadataImageKind.Module)
            {
                throw new ArgumentException(CodeAnalysisResources.CannotCreateReferenceToModule);
            }

            return WithPropertiesImpl(properties);
        }
        public void WithXxx()
        {
            var p = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false);

            Assert.Equal(p.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: false));
            Assert.Equal(p.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: false));
            Assert.Equal(p.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: false));
            Assert.Equal(p.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: false));
            Assert.Equal(p.WithAliases(new[] { "foo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("foo", "aaa"), embedInteropTypes: false));
            Assert.Equal(p.WithEmbedInteropTypes(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true));

            var m = new MetadataReferenceProperties(MetadataImageKind.Module);
            Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
            Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
        }
            internal Snapshot(VisualStudioMetadataReferenceManager provider, MetadataReferenceProperties properties, string fullPath)
                : base(properties, fullPath)
            {
                Contract.Requires(Properties.Kind == MetadataImageKind.Assembly);
                _provider = provider;

                try
                {
                    _timestamp = FileUtilities.GetFileTimeStamp(this.FilePath);
                }
                catch (IOException e)
                {
                    // Reading timestamp of a file might fail. 
                    // Let's remember the failure and report it to the compiler when it asks for metadata.
                    _error = e;
                }
            }
        public VisualStudioMetadataReference(
            VisualStudioMetadataReferenceManager provider,
            IVisualStudioHostProject hostProject,
            string filePath,
            MetadataReferenceProperties properties)
        {
            Contract.ThrowIfTrue(properties.Kind != MetadataImageKind.Assembly);

            _provider = provider;
            _hostProject = hostProject;
            _properties = properties;

            // We don't track changes to netmodules linked to the assembly.
            // Any legitimate change in a linked module will cause the assembly to change as well.
            _fileChangeTracker = new FileChangeTracker(provider.FileChangeService, filePath);
            _fileChangeTracker.UpdatedOnDisk += OnUpdatedOnDisk;
            _fileChangeTracker.StartFileChangeListeningAsync();
        }
        public void Constructor()
        {
            var m = new MetadataReferenceProperties();
            Assert.True(m.Aliases.IsDefault);
            Assert.False(m.EmbedInteropTypes);
            Assert.Equal(MetadataImageKind.Assembly, m.Kind);

            m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "foo"), embedInteropTypes: true);
            AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "foo" }, m.Aliases);
            Assert.True(m.EmbedInteropTypes);
            Assert.Equal(MetadataImageKind.Assembly, m.Kind);

            m = new MetadataReferenceProperties(MetadataImageKind.Module);
            Assert.True(m.Aliases.IsDefault);
            Assert.False(m.EmbedInteropTypes);
            Assert.Equal(MetadataImageKind.Module, m.Kind);

            Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
            Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
        }
        protected PortableExecutableReference(
            MetadataReferenceProperties properties,
            string fullPath = null,
            DocumentationProvider initialDocumentation = null)
            : base(properties)
        {
            // TODO: remove full path normalization
            if (fullPath != null)
            {
                CompilerPathUtilities.RequireAbsolutePath(fullPath, "fullPath");

                try
                {
                    this.fullPath = Path.GetFullPath(fullPath);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(e.Message, "fullPath");
                }
            }

            this.lazyDocumentation = initialDocumentation;
        }
 /// <summary>
 /// Returns an instance of the reference with specified properties.
 /// </summary>
 /// <param name="properties">The new properties for the reference.</param>
 /// <exception cref="NotSupportedException">Specified values not supported.</exception> 
 /// <remarks>Only invoked if the properties changed.</remarks>
 protected abstract PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties);
            public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
            {
                switch (reference)
                {
                    case "1":
                        resolved1 = true;
                        return ImmutableArray.Create(MetadataReference.CreateFromFile(path1));

                    case "2.dll":
                        resolved2 = true;
                        return ImmutableArray.Create(MetadataReference.CreateFromFile(path2));

                    default:
                        return ImmutableArray<PortableExecutableReference>.Empty;
                }
            }
        /// <summary>
        /// Returns an instance of the reference with specified properties, or this instance if properties haven't changed.
        /// </summary>
        /// <param name="properties">The new properties for the reference.</param>
        /// <exception cref="ArgumentException">Specified values not valid for this reference.</exception> 
        public new PortableExecutableReference WithProperties(MetadataReferenceProperties properties)
        {
            if (properties == this.Properties)
            {
                return this;
            }

            return WithPropertiesImpl(properties);
        }
Example #23
0
 public PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties)
 {
     return((PortableExecutableReference)_metadataCache.GetReference(resolvedPath, properties));
 }
Example #24
0
 public override PortableExecutableReference GetReference(string fullPath, MetadataReferenceProperties properties = default(MetadataReferenceProperties))
 {
     Debug.Assert(PathUtilities.IsAbsolute(fullPath));
     return new CachingMetadataReference(fullPath, properties);
 }
Example #25
0
 protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
 {
     return(new SerializedMetadataReference(properties, FilePath, _metadata, _storagesOpt, _provider));
 }
 public override ImmutableArray <PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
 => ImmutableArray.Create(MetadataReference.CreateFromFile(reference, properties));
Example #27
0
        internal void UndoProjectReferenceConversionForDisappearingOutputPath(string binPath)
        {
            AssertIsForeground();

            if (TryGetMetadataFileNameToConvertedProjectReference(binPath, out var projectReference))
            {
                // We converted this, so convert it back to a metadata reference
                RemoveProjectReference(projectReference);

                var metadataReferenceProperties = new MetadataReferenceProperties(
                    MetadataImageKind.Assembly,
                    projectReference.Aliases,
                    projectReference.EmbedInteropTypes);

                AddMetadataReferenceCore(MetadataReferenceProvider.CreateMetadataReference(this, binPath, metadataReferenceProperties));

                Contract.ThrowIfFalse(RemoveMetadataFileNameToConvertedProjectReference(binPath));
            }
        }
Example #28
0
        private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes)
        {
            if (value == null)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
                yield break;
            }
            else if (value.Length == 0)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                yield break;
            }

            // /r:"reference"
            // /r:alias=reference
            // /r:alias="reference"
            // /r:reference;reference
            // /r:"path;containing;semicolons"
            // /r:"unterminated_quotes
            // /r:"quotes"in"the"middle
            // /r:alias=reference;reference      ... error 2034
            // /r:nonidf=reference               ... error 1679

            int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' });

            string alias;
            if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=')
            {
                alias = value.Substring(0, eqlOrQuote);
                value = value.Substring(eqlOrQuote + 1);

                if (!SyntaxFacts.IsValidIdentifier(alias))
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias);
                    yield break;
                }
            }
            else
            {
                alias = null;
            }

            List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
            if (alias != null)
            {
                if (paths.Count > 1)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value);
                    yield break;
                }

                if (paths.Count == 0)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias);
                    yield break;
                }
            }

            foreach (string path in paths)
            {
                // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
                // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.

                var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty;

                var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes);
                yield return new CommandLineReference(path, properties);
            }
        }
 public VisualStudioMetadataReference CreateMetadataReference(IVisualStudioHostProject hostProject, string filePath, MetadataReferenceProperties properties)
 {
     return(new VisualStudioMetadataReference(this, hostProject, filePath, properties));
 }
            public MonoDevelopMetadataReference GetOrCreate(MonoDevelopMetadataReferenceManager provider, string path, MetadataReferenceProperties properties)
            {
                path = new FilePath(path).ResolveLinks();

                if (properties == MetadataReferenceProperties.Assembly)
                {
                    // fast path for no custom properties
                    return(GetOrCreate(cacheAssemblyProperties, path, provider, path, properties));
                }

                Dictionary <MetadataReferenceProperties, MonoDevelopMetadataReference> dict;

                lock (cacheWithCustomProperties) {
                    if (!cacheWithCustomProperties.TryGetValue(path, out dict))
                    {
                        cacheWithCustomProperties [path] = dict = new Dictionary <MetadataReferenceProperties, MonoDevelopMetadataReference> ();
                    }
                }
                return(GetOrCreate(dict, properties, provider, path, properties));
            }
 public PortableExecutableReference CreateMetadataReferenceSnapshot(string filePath, MetadataReferenceProperties properties)
 {
     return(new VisualStudioMetadataReference.Snapshot(this, properties, filePath));
 }
Example #32
0
 internal override CompilationReference WithPropertiesImpl(MetadataReferenceProperties properties)
 {
     return(new CSharpCompilationReference(Compilation, properties));
 }
Example #33
0
 private CSharpCompilationReference(CSharpCompilation compilation, MetadataReferenceProperties properties)
     : base(properties)
 {
     this.Compilation = compilation;
 }
Example #34
0
 public void AddMetadataReference(string referencePath, MetadataReferenceProperties properties)
 {
 }
 public PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties)
 {
     return(_manager.Value.CreateMetadataReferenceSnapshot(resolvedPath, properties));
 }
Example #36
0
        //private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments)
        //{
        //    diagnostics.Add(Diagnostic.Create(Errors.MessageProvider.Instance, (int)errorCode, arguments));
        //}

        private IEnumerable <CommandLineReference> ParseAssemblyReferences(string arg, string value, IList <Diagnostic> diagnostics, bool embedInteropTypes)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentException("value");   // TODO: ErrorCode
            }
            //if (value == null)
            //{
            //    AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
            //    yield break;
            //}
            //else if (value.Length == 0)
            //{
            //    AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
            //    yield break;
            //}

            int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' });

            string alias;

            if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=')
            {
                alias = value.Substring(0, eqlOrQuote);
                value = value.Substring(eqlOrQuote + 1);

                //if (!SyntaxFacts.IsValidIdentifier(alias))
                //{
                //    AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias);
                //    yield break;
                //}
            }
            else
            {
                alias = null;
            }

            List <string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();

            if (alias != null)
            {
                //if (paths.Count > 1)
                //{
                //    AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value);
                //    yield break;
                //}

                //if (paths.Count == 0)
                //{
                //    AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias);
                //    yield break;
                //}
                throw new NotSupportedException();  // TODO: ErrorCode
            }

            foreach (string path in paths)
            {
                var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray <string> .Empty;

                var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes);
                yield return(new CommandLineReference(path, properties));
            }
        }
Example #37
0
 /// <summary>
 /// Creates a <see cref="PortableExecutableReference" /> that correctly retrieves the Visual Studio context,
 /// such as documentation comments in the correct language.
 /// </summary>
 /// <param name="filePath">The file path of the assembly or module.</param>
 /// <param name="properties">The properties for the reference.</param>
 public PortableExecutableReference CreatePortableExecutableReference(string filePath, MetadataReferenceProperties properties)
 {
     return(this.Services.GetService <IMetadataService>().GetReference(filePath, properties));
 }
Example #38
0
 protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
 {
     return(new MissingMetadataReference(properties, FilePath, _provider));
 }
 internal UnresolvedMetadataReference(string reference, MetadataReferenceProperties properties)
     : base(properties)
 {
     this.Reference = reference;
 }
 protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
 {
     return(new Snapshot(_provider, properties, this.FilePath, _fileChangeTrackerOpt));
 }
Example #41
0
 public void AddProjectReference(IWorkspaceProjectContext project, MetadataReferenceProperties properties)
 {
 }
 internal override MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties)
 {
     return(new UnresolvedMetadataReference(this.Reference, properties));
 }
Example #43
0
 /// <summary>
 /// Creates a <see cref="PortableExecutableReference" /> that correctly retrieves the Visual Studio context,
 /// such as documentation comments in the correct language.
 /// </summary>
 /// <param name="filePath">The file path of the assembly or module.</param>
 /// <param name="properties">The properties for the reference.</param>
 public PortableExecutableReference CreatePortableExecutableReference(string filePath, MetadataReferenceProperties properties)
 => this.Services.GetRequiredService <IMetadataService>().GetReference(filePath, properties);
Example #44
0
 internal CachingMetadataReference(string fullPath, MetadataReferenceProperties properties)
     : base(properties, fullPath)
 {
 }
Example #45
0
 protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
 => this;
Example #46
0
            /// <summary>
            /// Resolves the reference.
            /// </summary>
            /// <param name="reference">The reference.</param>
            /// <param name="baseFilePath">The base file path.</param>
            /// <param name="properties">The properties.</param>
            /// <returns></returns>
            public override ImmutableArray <PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
            {
                // Check if we are referencing CodeGen assembly
                ImportUserTypeAssembly codeGenAssembly;

                if (codeGenAssemblies.TryGetValue(reference, out codeGenAssembly))
                {
                    using (MemoryStream stream = new MemoryStream(codeGenAssembly.AssemblyBytes))
                    {
                        return(ImmutableArray.Create(MetadataReference.CreateFromStream(stream, properties, null, codeGenAssembly.AssemblyPath)));
                    }
                }

                // Check the previous resolver
                var result = previousResolver.ResolveReference(reference, baseFilePath, properties);

                if (result.Length > 0)
                {
                    return(result);
                }

                // Try to use file resolver
                try
                {
                    string path = ResolvePath(reference, baseFilePath);

                    if (!string.IsNullOrEmpty(path))
                    {
                        return(ImmutableArray.Create(MetadataReference.CreateFromFile(path, properties)));
                    }
                }
                catch
                {
                }

                // Check if reference holds xml for CodeGen
                ImportUserTypeOptions options = ImportUserTypeOptions.ParseString(reference);

                if (options != null)
                {
                    foreach (ImportUserTypeAssembly assembly in codeGenAssemblies.Values)
                    {
                        if (assembly.Options.Equals(options))
                        {
                            // TODO: Compare that used PDBs have same GUID.
                            codeGenAssembly = assembly;
                            break;
                        }
                    }

                    if (codeGenAssembly == null)
                    {
                        codeGenAssembly = GenerateAssembly(options);
                        AddAssembly(codeGenAssembly);
                    }

                    using (MemoryStream stream = new MemoryStream(codeGenAssembly.AssemblyBytes))
                    {
                        return(ImmutableArray.Create(MetadataReference.CreateFromStream(stream, properties, null, codeGenAssembly.AssemblyPath)));
                    }
                }

                return(ImmutableArray <PortableExecutableReference> .Empty);
            }
 protected override PortableExecutableReference WithPropertiesImpl(
     MetadataReferenceProperties properties
     )
 {
     return(new ShadowCopyReference(_provider, FilePath !, properties));
 }
            public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
            {
                switch (reference)
                {
                    case "throw": throw new TestException();
                }

                return base.ResolveReference(reference, baseFilePath, properties);
            }
            public ShadowCopyReference(MetadataShadowCopyProvider provider, string originalPath, MetadataReferenceProperties properties)
                : base(properties, originalPath)
            {
                Debug.Assert(originalPath != null);
                Debug.Assert(provider != null);

                _provider = provider;
            }
 internal sealed override MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties)
 {
     return WithPropertiesImpl(properties);
 }
 public void AddMetadataReference(string referencePath, MetadataReferenceProperties properties)
 {
     referencePath = FileUtilities.NormalizeAbsolutePath(referencePath);
     AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(referencePath, properties);
 }
 static MonoDevelopMetadataReference GetOrCreate <TKey> (Dictionary <TKey, MonoDevelopMetadataReference> cache, TKey key, MonoDevelopMetadataReferenceManager provider, string path, MetadataReferenceProperties properties)
 {
     lock (cache) {
         if (!cache.TryGetValue(key, out var result))
         {
             cache [key] = result = new MonoDevelopMetadataReference(provider, path, properties);
         }
         return(result);
     }
 }
Example #53
0
        public override ImmutableArray <PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
        {
            if (reference == null)
            {
                return(ImmutableArray <PortableExecutableReference> .Empty);
            }

            if (!HasValidAssemblyFileExtension(reference))
            {
                // Try to resolve using the default resolver (framework assemblies, e.g. System.Core, System.Xml, etc.)
                ImmutableArray <PortableExecutableReference> result = _scriptResolver.ResolveReference(reference, baseFilePath, properties);

                // If the default script resolver can't resolve the assembly
                // check if this is one of host's shared assemblies
                if (result.IsEmpty)
                {
                    Assembly assembly = null;

                    if (SharedAssemblyProviders.Any(p => p.TryResolveAssembly(reference, out assembly)) ||
                        _extensionSharedAssemblyProvider.TryResolveAssembly(reference, out assembly))
                    {
                        result = ImmutableArray.Create(MetadataReference.CreateFromFile(assembly.Location));
                    }
                }

                return(result);
            }

            return(GetMetadataFromReferencePath(reference));
        }
Example #54
0
        protected int AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(string filePath, MetadataReferenceProperties properties)
        {
            AssertIsForeground();

            // If this file is coming from a project, then we should convert it to a project reference instead
            if (this.CanConvertToProjectReferences && ProjectTracker.TryGetProjectByBinPath(filePath, out var project))
            {
                var projectReference = new ProjectReference(project.Id, properties.Aliases, properties.EmbedInteropTypes);
                if (CanAddProjectReference(projectReference))
                {
                    AddProjectReference(projectReference);
                    AddMetadataFileNameToConvertedProjectReference(filePath, projectReference);
                    return VSConstants.S_OK;
                }
            }

            // regardless whether the file exists or not, we still record it. one of reason
            // we do that is some cross language p2p references might be resolved
            // after they are already reported as metadata references. since we use bin path
            // as a way to discover them, if we don't previously record the reference ourselves,
            // cross p2p references won't be resolved as p2p references when we finally have
            // all required information.
            //
            // it looks like
            //    1. project system sometimes won't guarantee build dependency for intellisense build
            //       if it is cross language dependency
            //    2. output path of referenced cross language project might be changed to right one
            //       once it is already added as a metadata reference.
            //
            // but this has one consequence. even if a user adds a project in the solution as
            // a metadata reference explicitly, that dll will be automatically converted back to p2p
            // reference.
            //
            // unfortunately there is no way to prevent this using information we have since,
            // at this point, we don't know whether it is a metadata reference added because
            // we don't have enough information yet for p2p reference or user explicitly added it
            // as a metadata reference.
            AddMetadataReferenceCore(this.MetadataReferenceProvider.CreateMetadataReference(this, filePath, properties));

            // here, we change behavior compared to old C# language service. regardless of file being exist or not,
            // we will always return S_OK. this is to support cross language p2p reference better.
            //
            // this should make project system to cache all cross language p2p references regardless
            // whether it actually exist in disk or not.
            // (see Roslyn bug 7315 for history - http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems?_a=edit&id=7315)
            //
            // after this point, Roslyn will take care of non-exist metadata reference.
            //
            // But, this doesn't sovle the issue where actual metadata reference
            // (not cross language p2p reference) is missing at the time project is opened.
            //
            // in that case, msbuild filter those actual metadata references out, so project system doesn't know
            // path to the reference. since it doesn't know where dll is, it can't (or currently doesn't)
            // setup file change notification either to find out when dll becomes available.
            //
            // at this point, user has 2 ways to recover missing metadata reference once it becomes available.
            //
            // one way is explicitly clicking that missing reference from solution explorer reference node.
            // the other is building the project. at that point, project system will refresh references
            // which will discover new dll and connect to us. once it is connected, we will take care of it.
            return VSConstants.S_OK;
        }
 protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
 {
     throw new NotImplementedException();
 }
        public int OnImportAddedEx(string filename, string project, CompilerOptions optionID)
        {
            filename = FileUtilities.NormalizeAbsolutePath(filename);

            if (optionID != CompilerOptions.OPTID_IMPORTS && optionID != CompilerOptions.OPTID_IMPORTSUSINGNOPIA)
            {
                throw new ArgumentException("optionID was an unexpected value.", "optionID");
            }

            bool embedInteropTypes = optionID == CompilerOptions.OPTID_IMPORTSUSINGNOPIA;
            var properties = new MetadataReferenceProperties(embedInteropTypes: embedInteropTypes);

            // The file may not exist, so let's return an error code. In Dev10, we were
            // never called us for these at all, and the project system would immediately
            // return an S_FALSE. Sadly, returning S_FALSE will convert back to S_OK, which
            // would prevent this file from ever being added again. Roslyn bug 7315 for more.
            return AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(filename, properties, hResultForMissingFile: VSConstants.E_FAIL);
        }
Example #57
0
 /// <summary>
 /// Maps a path to <see cref="PortableExecutableReference"/>.
 /// </summary>
 /// <param name="path">Path.</param>
 /// <param name="properties">Metadata reference properties.</param>
 /// <returns>A <see cref="PortableExecutableReference"/> corresponding to the <paramref name="path"/> and
 /// <paramref name="properties"/> parameters.</returns>
 public virtual PortableExecutableReference GetReference(string path, MetadataReferenceProperties properties)
 {
     return(MetadataReference.CreateFromFile(path, properties));
 }