public static string GetAssemblyInfo(IAssemblySymbol assemblySymbol)
 {
     return string.Format(
         "{0} {1}",
         FeaturesResources.Assembly,
         assemblySymbol.Identity.GetDisplayName());
 }
        private static bool ShouldCreateFromScratch(
            Solution solution,
            IAssemblySymbol assembly,
            string filePath,
            out string prefix,
            out VersionStamp version,
            CancellationToken cancellationToken)
        {
            prefix = null;
            version = default(VersionStamp);

            var service = solution.Workspace.Services.GetService<IAssemblySerializationInfoService>();
            if (service == null)
            {
                return true;
            }

            // check whether the assembly that belong to a solution is something we can serialize
            if (!service.Serializable(solution, filePath))
            {
                return true;
            }

            if (!service.TryGetSerializationPrefixAndVersion(solution, filePath, out prefix, out version))
            {
                return true;
            }

            return false;
        }
        protected void AddAssemblyLink(IAssemblySymbol assemblySymbol)
        {
            var name = assemblySymbol.Identity.Name;
            var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForAssembly(assemblySymbol);

            _description.AddDescriptionText3(name, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
        }
 /// <summary>
 /// Checks if 'symbol' is accessible from within assembly 'within'.
 /// </summary>
 public static bool IsAccessibleWithin(
     this ISymbol symbol,
     IAssemblySymbol within,
     ITypeSymbol throughTypeOpt = null)
 {
     return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out var failedThroughTypeCheck);
 }
        protected void AddAssemblyLink(IAssemblySymbol assemblySymbol)
        {
            var name = assemblySymbol.Identity.Name;
            var navInfo = _libraryManager.GetAssemblyNavInfo(assemblySymbol);

            _description.AddDescriptionText3(name, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
        }
Beispiel #6
0
 public static IEnumerable<TypeDiff> CompareTo(this IAssemblySymbol assembly, IAssemblySymbol comparedTo)
 {
     var types = assembly.GlobalNamespace.GetTypes();
     var comparedToTypes = comparedTo.GlobalNamespace.GetTypes();
     var result = types.FullOuterJoin(comparedToTypes, NamespaceOrTypeSymbolComparer.Instance, (a, b) => a.CompareTo(b));
     return result;
 }
 public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly)
 {
     return
         Equals(assembly, toAssembly) ||
         (assembly.IsInteractive && toAssembly.IsInteractive) ||
         toAssembly.GivesAccessTo(assembly);
 }
        /// <summary>
        /// this is for a metadata reference in a solution
        /// </summary>
        private static async Task<SymbolTreeInfo> LoadOrCreateAsync(Solution solution, IAssemblySymbol assembly, string filePath, CancellationToken cancellationToken)
        {
            // if assembly is not from a file, just create one on the fly
            if (filePath == null || !File.Exists(filePath) || !FilePathUtilities.PartOfFrameworkOrReferencePaths(filePath))
            {
                return Create(VersionStamp.Default, assembly, cancellationToken);
            }

            // if solution is not from a disk, just create one.
            if (solution.FilePath == null || !File.Exists(solution.FilePath))
            {
                return Create(VersionStamp.Default, assembly, cancellationToken);
            }

            // okay, see whether we can get one from persistence service.
            var relativePath = FilePathUtilities.GetRelativePath(solution.FilePath, filePath);
            var version = VersionStamp.Create(File.GetLastWriteTimeUtc(filePath));

            var persistentStorageService = solution.Workspace.Services.GetService<IPersistentStorageService>();

            // attempt to load from persisted state. metadata reference is solution wise information
            SymbolTreeInfo info;
            using (var storage = persistentStorageService.GetStorage(solution))
            {
                var key = PrefixMetadataSymbolTreeInfo + relativePath;
                using (var stream = await storage.ReadStreamAsync(key, cancellationToken).ConfigureAwait(false))
                {
                    if (stream != null)
                    {
                        using (var reader = new ObjectReader(stream))
                        {
                            info = ReadFrom(reader);
                            if (info != null && VersionStamp.CanReusePersistedVersion(version, info.version))
                            {
                                return info;
                            }
                        }
                    }
                }

                cancellationToken.ThrowIfCancellationRequested();

                // compute it if we couldn't load it from cache
                info = Create(version, assembly, cancellationToken);
                if (info != null)
                {
                    using (var stream = SerializableBytes.CreateWritableStream())
                    using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken))
                    {
                        info.WriteTo(writer);
                        stream.Position = 0;

                        await storage.WriteStreamAsync(key, stream, cancellationToken).ConfigureAwait(false);
                    }
                }
            }

            return info;
        }
 public static IEnumerable<string> GetAssemblyAttributes(IAssemblySymbol assemblySymbol)
 {
     var attributes = assemblySymbol.GetAttributes();
     foreach (var attribute in attributes)
     {
         yield return attribute.ToString();
     }
 }
Beispiel #10
0
        public ExternAliasRecord(string alias, IAssemblySymbol targetAssembly)
        {
            Debug.Assert(alias != null);
            Debug.Assert(targetAssembly != null);

            Alias = alias;
            TargetAssembly = targetAssembly;
        }
 private static bool AssemblyHasPublicTypes(IAssemblySymbol assembly)
 {
     return assembly
             .GlobalNamespace
             .GetMembers()
             .OfType<INamedTypeSymbol>()
             .Where(s => s.DeclaredAccessibility == Accessibility.Public)
             .Any();
 }
        private static bool IsOrUsesAssemblyType(ITypeSymbol typeSymbol, IAssemblySymbol assemblySymbol)
        {
            if (typeSymbol.ContainingAssembly == assemblySymbol)
            {
                return true;
            }

            INamedTypeSymbol namedTypeSymbol = typeSymbol as INamedTypeSymbol;
            return namedTypeSymbol != null && namedTypeSymbol.IsGenericType
                && namedTypeSymbol.TypeArguments.Any(t => IsOrUsesAssemblyType(t, assemblySymbol));
        }
 public static bool IsObjectMapperFrameworkAssembly(IAssemblySymbol assemblySymbol)
 {
     if (assemblySymbol.Name != "ObjectMapper.Framework")
     {
         return false;
     }
     if (!assemblySymbol.Identity.IsStrongName || !_publicKeyToken.SequenceEqual(assemblySymbol.Identity.PublicKeyToken))
     {
         return false;
     }
     return true;
 }
 public MetadataSearchScope(
     Solution solution,
     IAssemblySymbol assembly,
     PortableExecutableReference metadataReference,
     bool ignoreCase,
     CancellationToken cancellationToken)
     : base(ignoreCase, cancellationToken)
 {
     _solution = solution;
     _assembly = assembly;
     _metadataReference = metadataReference;
 }
        internal static SymbolTreeInfo CreateSourceSymbolTreeInfo(
            Solution solution, VersionStamp version, IAssemblySymbol assembly,
            string filePath, CancellationToken cancellationToken)
        {
            if (assembly == null)
            {
                return null;
            }

            var unsortedNodes = new List<Node> { new Node(assembly.GlobalNamespace.Name, Node.RootNodeParentIndex) };

            GenerateSourceNodes(assembly.GlobalNamespace, unsortedNodes, s_getMembersNoPrivate);

            return CreateSymbolTreeInfo(solution, version, filePath, unsortedNodes);
        }
Beispiel #16
0
 public ImportRecord(
     ImportTargetKind targetKind,
     string alias = null,
     ITypeSymbol targetType = null,
     string targetString = null,
     IAssemblySymbol targetAssembly = null,
     string targetAssemblyAlias = null)
 {
     TargetKind = targetKind;
     Alias = alias;
     TargetType = targetType;
     TargetString = targetString;
     TargetAssembly = targetAssembly;
     TargetAssemblyAlias = targetAssemblyAlias;
 }
Beispiel #17
0
 public IEnumerable<ISymbol> Find(IAssemblySymbol assembly, Func<string, bool> predicate, CancellationToken cancellationToken)
 {
     for (int i = 0, n = _nodes.Count; i < n; i++)
     {
         cancellationToken.ThrowIfCancellationRequested();
         var node = _nodes[i];
         if (predicate(node.Name))
         {
             foreach (var symbol in Bind(i, assembly.GlobalNamespace, cancellationToken))
             {
                 cancellationToken.ThrowIfCancellationRequested();
                 yield return symbol;
             }
         }
     }
 }
Beispiel #18
0
        /// <summary>
        /// Get all symbols that have a name matching the specified name.
        /// </summary>
        public IEnumerable<ISymbol> Find(
            IAssemblySymbol assembly,
            string name,
            bool ignoreCase,
            CancellationToken cancellationToken)
        {
            var comparer = GetComparer(ignoreCase);

            foreach (var node in FindNodes(name, comparer))
            {
                foreach (var symbol in Bind(node, assembly.GlobalNamespace, cancellationToken))
                {
                    yield return symbol;
                }
            }
        }
        internal static SymbolTreeInfo CreateSourceSymbolTreeInfo(
            Solution solution, VersionStamp version, IAssemblySymbol assembly,
            string filePath, CancellationToken cancellationToken)
        {
            if (assembly == null)
            {
                return null;
            }

            var unsortedNodes = ArrayBuilder<BuilderNode>.GetInstance();
            unsortedNodes.Add(new BuilderNode(assembly.GlobalNamespace.Name, RootNodeParentIndex));

            GenerateSourceNodes(assembly.GlobalNamespace, unsortedNodes, s_getMembersNoPrivate);

            return CreateSymbolTreeInfo(
                solution, version, filePath, unsortedNodes.ToImmutableAndFree(), 
                inheritanceMap: new OrderPreservingMultiDictionary<string, string>());
        }
        public static string GetAssemblyDisplay(Compilation compilation, IAssemblySymbol assemblySymbol)
        {
            // This method is only used to generate a comment at the top of Metadata-as-Source documents and
            // previous submissions are never viewed as metadata (i.e. we always have compilations) so there's no
            // need to consume compilation.ScriptCompilationInfo.PreviousScriptCompilation.

            // TODO (https://github.com/dotnet/roslyn/issues/6859): compilation.GetMetadataReference(assemblySymbol)?
            var assemblyReference = compilation.References.Where(r =>
            {
                var referencedSymbol = compilation.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol;
                return
                    referencedSymbol != null &&
                    referencedSymbol.MetadataName == assemblySymbol.MetadataName;
            })
            .FirstOrDefault();

            return assemblyReference?.Display ?? FeaturesResources.location_unknown;
        }
Beispiel #21
0
        /// <summary>
        /// Get all symbols that have a name matching the specified name.
        /// </summary>
        public IEnumerable<ISymbol> Find(
            IAssemblySymbol assembly,
            string name,
            bool ignoreCase,
            CancellationToken cancellationToken)
        {
            // The node list is always ordered using StringComparer.InvariantCulture, which guarantees that upper and lower case
            // symbols are adjacent in the order. Because of this, it is possible to also use StringComparer.InvariantCultureIgnoreCase on 
            // this same list, because all mixed cases equivalent strings will be contiguous.
            var comparer = GetComparer(ignoreCase);

            foreach (var node in FindNodes(name, comparer))
            {
                foreach (var symbol in Bind(node, assembly.GlobalNamespace, cancellationToken))
                {
                    yield return symbol;
                }
            }
        }
        public static string GetAssemblyDisplay(Compilation compilation, IAssemblySymbol assemblySymbol)
        {
            var assemblyReference = compilation.References.Where(r =>
            {
                var referencedSymbol = compilation.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol;
                return
                    referencedSymbol != null &&
                    referencedSymbol.MetadataName == assemblySymbol.MetadataName;
            })
            .FirstOrDefault();

            if (assemblyReference != null && assemblyReference.Display != null)
            {
                return assemblyReference.Display;
            }
            else
            {
                return FeaturesResources.LocationUnknown;
            }
        }
    public IAssemblyReference Map(IAssemblySymbol assembly) {
      Contract.Requires(assembly != null);
      Contract.Ensures(Contract.Result<IAssemblyReference>() != null);

      IAssemblyReference cciAssembly = null;
      if (!assemblySymbolCache.TryGetValue(assembly, out cciAssembly)) {
        var an = assembly.Identity;
        IEnumerable<byte> pkt = an.PublicKeyToken.AsEnumerable();
        if (pkt == null)
          pkt = new byte[0];
        var identity = new Microsoft.Cci.AssemblyIdentity(
          this.nameTable.GetNameFor(an.Name),
          an.CultureName == null ? "" : an.CultureName, // REVIEW: This can't be right
          an.Version,
          pkt,
          "unknown://location" // BUGBUG an.Location == null ? "unknown://location" : an.Location
          );
        cciAssembly = new Microsoft.Cci.Immutable.AssemblyReference(this.host, identity);
        assemblySymbolCache[assembly] = cciAssembly;
      }
      Contract.Assume(cciAssembly != null);
      return cciAssembly;
    }
Beispiel #24
0
        public static bool IsOrContainsAccessibleAttribute(this ISymbol symbol, ISymbol withinType, IAssemblySymbol withinAssembly)
        {
            if (symbol is IAliasSymbol alias)
            {
                symbol = alias.Target;
            }

            var namespaceOrType = symbol as INamespaceOrTypeSymbol;

            if (namespaceOrType == null)
            {
                return(false);
            }

            if (namespaceOrType.IsAttribute() && namespaceOrType.IsAccessibleWithin(withinType ?? withinAssembly))
            {
                return(true);
            }

            // PERF: Avoid allocating a lambda capture as this method is recursive
            foreach (var namedType in namespaceOrType.GetTypeMembers())
            {
                if (namedType.IsOrContainsAccessibleAttribute(withinType, withinAssembly))
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #25
0
 public virtual void VisitAssembly(IAssemblySymbol symbol)
 {
     DefaultVisit(symbol);
 }
 public override void WriteEndAssembly(IAssemblySymbol assemblySymbol)
 {
     DecreaseDepth();
 }
Beispiel #27
0
        private static async Task <Uri> GetAssemblyFullPathAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
        {
            IAssemblySymbol containingAssembly = GetContainingAssembly(symbol);

            return(await GetAssemblyFullPathAsync(containingAssembly, solution, cancellationToken).ConfigureAwait(false));
        }
 public sealed override void VisitAssembly(IAssemblySymbol symbol)
 {
     throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
 }
 public override object VisitAssembly(IAssemblySymbol assemblySymbol)
 {
     WriteType(SymbolKeyType.Assembly);
     AssemblySymbolKey.Create(assemblySymbol, this);
     return(null);
 }
 public RoslynMetadataExtractor(Compilation compilation, IAssemblySymbol assembly = null)
 {
     _compilation = compilation ?? throw new ArgumentNullException(nameof(compilation));
     _assembly    = assembly ?? compilation.Assembly;
 }
 /// <summary>
 /// Adds given retargeting assembly for this compilation into the cache.
 /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method.
 /// </summary>
 internal void CacheRetargetingAssemblySymbolNoLock(IAssemblySymbol assembly)
 {
     _retargetingAssemblySymbols.Add(assembly);
 }
 public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly)
 {
     return
         (Equals(assembly, toAssembly) ||
          (assembly.IsInteractive && toAssembly.IsInteractive) ||
          toAssembly.GivesAccessTo(assembly));
 }
Beispiel #33
0
 public bool GivesAccessTo(IAssemblySymbol toAssembly)
 {
     throw new NotImplementedException();
 }
 public MappingEngine(SemanticModel semanticModel, SyntaxGenerator syntaxGenerator, IAssemblySymbol contextAssembly)
 {
     this.semanticModel   = semanticModel;
     this.syntaxGenerator = syntaxGenerator;
     this.contextAssembly = contextAssembly;
 }
Beispiel #35
0
        /// <summary>
        /// this gives you SymbolTreeInfo for a metadata
        /// </summary>
        public static async Task <SymbolTreeInfo> GetInfoForAssemblyAsync(Solution solution, IAssemblySymbol assembly, string filePath, CancellationToken cancellationToken)
        {
            SymbolTreeInfo info;

            if (s_assemblyInfos.TryGetValue(assembly, out info))
            {
                return(info);
            }

            // IAssemblySymbol is immutable, even if we encounter a race, we might do same work twice but still will be correct.
            // now, we can't use AsyncLazy here since constructing information requires a solution. if we ever get cancellation before
            // finishing calculating, async lazy will hold onto solution graph until next call (if it ever gets called)
            info = await LoadOrCreateAsync(solution, assembly, filePath, cancellationToken).ConfigureAwait(false);

            return(s_assemblyInfos.GetValue(assembly, _ => info));
        }
        public static async Task <MappingEngine> Create(Document document, CancellationToken cancellationToken, IAssemblySymbol contextAssembly)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            var syntaxGenerator = SyntaxGenerator.GetGenerator(document);

            return(new MappingEngine(semanticModel, syntaxGenerator, contextAssembly));
        }
        internal static Symbol GetRuntimeMember(NamedTypeSymbol declaringType, ref MemberDescriptor descriptor, SignatureComparer <MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, IAssemblySymbol accessWithinOpt)
        {
            Symbol     result = null;
            SymbolKind targetSymbolKind;
            MethodKind targetMethodKind = MethodKind.Ordinary;
            bool       isStatic         = (descriptor.Flags & MemberFlags.Static) != 0;

            switch (descriptor.Flags & MemberFlags.KindMask)
            {
            case MemberFlags.Constructor:
                targetSymbolKind = SymbolKind.Method;
                targetMethodKind = MethodKind.Constructor;
                //  static constructors are never called explicitly
                Debug.Assert(!isStatic);
                break;

            case MemberFlags.Method:
                targetSymbolKind = SymbolKind.Method;
                break;

            case MemberFlags.PropertyGet:
                targetSymbolKind = SymbolKind.Method;
                targetMethodKind = MethodKind.PropertyGet;
                break;

            case MemberFlags.Field:
                targetSymbolKind = SymbolKind.Field;
                break;

            case MemberFlags.Property:
                targetSymbolKind = SymbolKind.Property;
                break;

            default:
                throw ExceptionUtilities.UnexpectedValue(descriptor.Flags);
            }

            foreach (var member in declaringType.GetMembers(descriptor.Name))
            {
                Debug.Assert(member.Name.Equals(descriptor.Name));

                if (member.Kind != targetSymbolKind || member.IsStatic != isStatic || !(member.DeclaredAccessibility == Accessibility.Public))
                {
                    continue;
                }

                switch (targetSymbolKind)
                {
                case SymbolKind.Method:
                {
                    MethodSymbol method     = (MethodSymbol)member;
                    MethodKind   methodKind = method.MethodKind;
                    // Treat user-defined conversions and operators as ordinary methods for the purpose
                    // of matching them here.
                    if (methodKind == MethodKind.Conversion || methodKind == MethodKind.UserDefinedOperator)
                    {
                        methodKind = MethodKind.Ordinary;
                    }

                    if (method.Arity != descriptor.Arity || methodKind != targetMethodKind ||
                        ((descriptor.Flags & MemberFlags.Virtual) != 0) != (method.IsVirtual || method.IsOverride || method.IsAbstract))
                    {
                        continue;
                    }

                    if (!comparer.MatchMethodSignature(method, descriptor.Signature))
                    {
                        continue;
                    }
                }

                break;

                case SymbolKind.Property:
                {
                    PropertySymbol property = (PropertySymbol)member;
                    if (((descriptor.Flags & MemberFlags.Virtual) != 0) != (property.IsVirtual || property.IsOverride || property.IsAbstract))
                    {
                        continue;
                    }

                    if (!comparer.MatchPropertySignature(property, descriptor.Signature))
                    {
                        continue;
                    }
                }

                break;

                case SymbolKind.Field:
                    if (!comparer.MatchFieldSignature((FieldSymbol)member, descriptor.Signature))
                    {
                        continue;
                    }

                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(targetSymbolKind);
                }

                // ambiguity
                if ((object)result != null)
                {
                    result = null;
                    break;
                }

                result = member;
            }
            return(result);
        }
Beispiel #38
0
 internal abstract Cci.IAssemblyReference Translate(IAssemblySymbol symbol, DiagnosticBag diagnostics);
Beispiel #39
0
 /// <inheritdoc/>
 public override IEnumerable <ISymbol> VisitAssembly(IAssemblySymbol symbol)
 {
     return(symbol.GlobalNamespace.Accept(this));
 }
Beispiel #40
0
 public AssemblyWrapper(IAssemblySymbol assembly, MetadataLoadContextInternal metadataLoadContext)
 {
     Symbol = assembly;
     _metadataLoadContext = metadataLoadContext;
 }
Beispiel #41
0
 public static bool HasReferenceToAssembly(this Project project, IAssemblySymbol assemblySymbol)
 {
     return(project.HasReferenceToAssembly(assemblySymbol.Name));
 }
Beispiel #42
0
        /// <summary>
        /// this gives you SymbolTreeInfo for a metadata
        /// </summary>
        public static async Task<SymbolTreeInfo> GetInfoForAssemblyAsync(Solution solution, IAssemblySymbol assembly, string filePath, CancellationToken cancellationToken)
        {
            SymbolTreeInfo info;
            if (s_assemblyInfos.TryGetValue(assembly, out info))
            {
                return info;
            }

            // IAssemblySymbol is immutable, even if we encounter a race, we might do same work twice but still will be correct.
            // now, we can't use AsyncLazy here since constructing information requires a solution. if we ever get cancellation before
            // finishing calculating, async lazy will hold onto solution graph until next call (if it ever gets called)
            info = await LoadOrCreateAsync(solution, assembly, filePath, cancellationToken).ConfigureAwait(false);
            return s_assemblyInfos.GetValue(assembly, _ => info);
        }
        private static async Task AddDeclarationsAsync(Project project, Compilation startingCompilation, IAssemblySymbol startingAssembly, string name, bool ignoreCase, SymbolFilter filter, List <ISymbol> list, CancellationToken cancellationToken)
        {
            Func <string, bool> predicate = n => ignoreCase?CaseInsensitiveComparison.Comparer.Equals(name, n) : StringComparer.Ordinal.Equals(name, n);

            using (Logger.LogBlock(FunctionId.SymbolFinder_Project_AddDeclarationsAsync, cancellationToken))
                using (var set = SharedPools.Default <HashSet <ISymbol> >().GetPooledObject())
                {
                    if (!await project.ContainsSymbolsWithNameAsync(predicate, filter, cancellationToken).ConfigureAwait(false))
                    {
                        return;
                    }

                    var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                    if ((startingCompilation != null) && (startingAssembly != null) && (compilation.Assembly != startingAssembly))
                    {
                        // Return symbols from skeleton assembly in this case so that symbols have the same language as startingCompilation.
                        list.AddRange(
                            FilterByCriteria(compilation.GetSymbolsWithName(predicate, filter, cancellationToken), filter)
                            .Select(s => s.GetSymbolKey().Resolve(startingCompilation, cancellationToken: cancellationToken).Symbol).WhereNotNull());
                    }
                    else
                    {
                        list.AddRange(FilterByCriteria(compilation.GetSymbolsWithName(predicate, filter, cancellationToken), filter));
                    }
                }
        }
 /// <summary>
 /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. 
 /// </summary>
 public new MetadataReference GetMetadataReference(IAssemblySymbol assemblySymbol)
 {
     return this.GetBoundReferenceManager().ReferencedAssembliesMap.Where(kvp => object.ReferenceEquals(kvp.Value.Symbol, assemblySymbol)).Select(kvp => kvp.Key).FirstOrDefault();
 }
Beispiel #45
0
 internal sealed override Cci.IAssemblyReference Translate(IAssemblySymbol symbol, DiagnosticBag diagnostics)
 {
     return(Translate((TAssemblySymbol)symbol, diagnostics));
 }
 private bool IsTagHelperAssembly(IAssemblySymbol assembly)
 {
     return(assembly.Name != null && !assembly.Name.StartsWith("System.", StringComparison.Ordinal));
 }
Beispiel #47
0
 public virtual TResult VisitAssembly(IAssemblySymbol symbol)
 {
     return(DefaultVisit(symbol));
 }
        public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferredCultureName = null)
        {
            if (_symbolData.TryGetValue(symbol, out SymbolDocumentationData data) &&
                data.XmlDocumentation != null)
            {
                if (object.ReferenceEquals(data.XmlDocumentation, SymbolXmlDocumentation.Default))
                {
                    return(null);
                }

                return(data.XmlDocumentation);
            }

            IAssemblySymbol assembly = symbol.ContainingAssembly;

            if (assembly != null)
            {
                SymbolXmlDocumentation xmlDocumentation = GetXmlDocumentation(assembly, preferredCultureName)?.GetXmlDocumentation(symbol);

                if (xmlDocumentation != null)
                {
                    _symbolData[symbol] = data.WithXmlDocumentation(xmlDocumentation);
                    return(xmlDocumentation);
                }

                CultureInfo preferredCulture = null;

                if (preferredCultureName != null &&
                    !_cultures.TryGetValue(preferredCultureName, out preferredCulture))
                {
                    preferredCulture = ImmutableInterlocked.GetOrAdd(ref _cultures, preferredCultureName, f => new CultureInfo(f));
                }

                string xml = symbol.GetDocumentationCommentXml(preferredCulture: preferredCulture, expandIncludes: true);

                if (!string.IsNullOrEmpty(xml))
                {
                    xml = XmlDocumentation.Unindent(xml);

                    if (!string.IsNullOrEmpty(xml))
                    {
                        var element = XElement.Parse(xml, LoadOptions.PreserveWhitespace);

                        xmlDocumentation = new SymbolXmlDocumentation(symbol, element);

                        _symbolData[symbol] = data.WithXmlDocumentation(xmlDocumentation);
                        return(xmlDocumentation);
                    }
                }
            }

            if (!_additionalXmlDocumentationPaths.IsDefault)
            {
                if (_additionalXmlDocumentations.IsDefault)
                {
                    _additionalXmlDocumentations = _additionalXmlDocumentationPaths
                                                   .Select(f => XmlDocumentation.Load(f))
                                                   .ToImmutableArray();
                }

                string commentId = symbol.GetDocumentationCommentId();

                foreach (XmlDocumentation xmlDocumentation in _additionalXmlDocumentations)
                {
                    SymbolXmlDocumentation documentation = xmlDocumentation.GetXmlDocumentation(symbol, commentId);

                    if (documentation != null)
                    {
                        _symbolData[symbol] = data.WithXmlDocumentation(documentation);
                        return(documentation);
                    }
                }
            }

            _symbolData[symbol] = data.WithXmlDocumentation(SymbolXmlDocumentation.Default);
            return(null);
        }
Beispiel #49
0
 internal override MetadataReference GetMetadataReference(IAssemblySymbol assemblySymbol) => _metadataMap.TryGetOrDefault(assemblySymbol);
 public override void WriteStartAssembly(IAssemblySymbol assemblySymbol)
 {
     WriteIndentation();
 }
Beispiel #51
0
        /// <summary>
        /// Maps given assembly symbol to an assembly ref.
        /// </summary>
        /// <remarks>
        /// The compiler represents every submission by a compilation instance for which it creates a distinct source assembly symbol.
        /// However multiple submissions might compile into a single dynamic assembly and so we need to map the corresponding assembly symbols to 
        /// the name of the dynamic assembly.
        /// </remarks>
        internal AssemblyIdentity MapAssemblySymbol(IAssemblySymbol symbol, bool collectible)
        {
            if (symbol.IsInteractive)
            {
                if (collectible)
                {
                    // collectible assemblies can't reference other generated assemblies
                    throw ExceptionUtilities.Unreachable;
                }
                else if (!_uncollectibleCodeManager.ContainsAssembly(symbol.Identity.Name))
                {
                    // uncollectible assemblies can reference uncollectible dynamic or uncollectible CCI generated assemblies:
                    return _uncollectibleCodeManager.dynamicAssemblyName;
                }
            }

            return symbol.Identity;
        }
Beispiel #52
0
        public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly)
        {
            var areEquals = assembly.Equals(toAssembly);

            if (areEquals == false && toAssembly == null)
            {
                return(false);
            }

            return
                (areEquals ||
                 (assembly.IsInteractive && toAssembly.IsInteractive) ||
                 toAssembly.GivesAccessTo(assembly));
        }
Beispiel #53
0
        /// <summary>
        /// Get all symbols that have a matching name as determined by the predicate.
        /// </summary>
        public IEnumerable<ISymbol> Search(
            IAssemblySymbol assembly,
            Func<string, bool> predicate,
            CancellationToken cancellationToken)
        {
            string lastName = null;
            bool lastGood = false;

            for (int i = 0; i < _nodes.Count; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var node = _nodes[i];
                var isSameName = (object)node.Name == (object)lastName;
                if ((isSameName && lastGood) // check for same string instance to avoid invoking predicate when we already know the outcome (assumes no side effects of predicate.)
                    || (!string.IsNullOrEmpty(node.Name) // don't consider unnamed things like the global namespace itself.
                          && predicate(node.Name)))
                {
                    lastGood = true;

                    // yield all symbols for this node
                    foreach (var symbol in Bind(i, assembly.GlobalNamespace, cancellationToken))
                    {
                        yield return symbol;
                    }
                }
                else
                {
                    lastGood = false;
                }

                lastName = node.Name;
            }
        }
Beispiel #54
0
 public override void VisitAssembly([NotNull] IAssemblySymbol symbol)
 {
     Visit(symbol.GlobalNamespace);
 }
Beispiel #55
0
        internal static SymbolTreeInfo Create(VersionStamp version, IAssemblySymbol assembly, CancellationToken cancellationToken)
        {
            if (assembly == null)
            {
                return null;
            }

            var list = new List<Node>();
            GenerateNodes(assembly.GlobalNamespace, list);

            return new SymbolTreeInfo(version, SortNodes(list));
        }
 internal abstract MetadataReference GetMetadataReference(IAssemblySymbol assemblySymbol);
 public static void Create(IAssemblySymbol symbol, SymbolKeyWriter visitor)
 {
     // If the format of this ever changed, then it's necessary to fixup the
     // SymbolKeyComparer.RemoveAssemblyKeys function.
     visitor.WriteString(symbol.Identity.Name);
 }
 private Task <Tuple <MetadataItem, bool> > GetAssemblyMetadataFromCacheAsync(IEnumerable <string> files, Compilation compilation, IAssemblySymbol assembly, string outputFolder, bool forceRebuild, string filterConfigFile, IReadOnlyDictionary <Compilation, IEnumerable <IMethodSymbol> > extensionMethods)
 {
     if (files == null || !files.Any())
     {
         return(null);
     }
     return(GetMetadataFromProjectLevelCacheAsync(
                files,
                files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile }))),
                s => Task.FromResult(compilation),
                s => Task.FromResult(assembly),
                s => null,
                outputFolder,
                false,
                false,
                filterConfigFile,
                extensionMethods));
 }
 protected override MetadataReference CommonGetMetadataReference(IAssemblySymbol assemblySymbol)
 {
     var symbol = assemblySymbol as AssemblySymbol;
     if ((object)symbol != null)
     {
         return this.GetMetadataReference(symbol);
     }
     else
     {
         return null;
     }
 }
Beispiel #60
0
        // Is a protected symbol inside "originalContainingType" accessible from within "within",
        // which much be a named type or an assembly.
        private static bool IsProtectedSymbolAccessible(
            INamedTypeSymbol withinType,
            IAssemblySymbol withinAssembly,
            ITypeSymbol throughTypeOpt,
            INamedTypeSymbol originalContainingType,
            out bool failedThroughTypeCheck)
        {
            failedThroughTypeCheck = false;

            // It is not an error to define protected member in a sealed Script class,
            // it's just a warning. The member behaves like a private one - it is visible
            // in all subsequent submissions.
            if (withinAssembly.IsInteractive && originalContainingType.IsScriptClass)
            {
                return(true);
            }

            if (withinType == null)
            {
                // If we're not within a type, we can't access a protected symbol
                return(false);
            }

            // A protected symbol is accessible if we're (optionally nested) inside the type that it
            // was defined in.

            // NOTE(ericli): It is helpful to consider 'protected' as *increasing* the
            // accessibility domain of a private member, rather than *decreasing* that of a public
            // member. Members are naturally private; the protected, internal and public access
            // modifiers all increase the accessibility domain. Since private members are accessible
            // to nested types, so are protected members.

            // NOTE(cyrusn): We do this check up front as it is very fast and easy to do.
            if (IsNestedWithinOriginalContainingType(withinType, originalContainingType))
            {
                return(true);
            }

            // Protected is really confusing.  Check out 3.5.3 of the language spec "protected access
            // for instance members" to see how it works.  I actually got the code for this from
            // LangCompiler::CheckAccessCore
            {
                var current = withinType.OriginalDefinition;
                var originalThroughTypeOpt = throughTypeOpt == null ? null : throughTypeOpt.OriginalDefinition;
                while (current != null)
                {
                    Contract.Requires(current.IsDefinition);

                    if (current.InheritsFromOrEqualsIgnoringConstruction(originalContainingType))
                    {
                        // NOTE(cyrusn): We're continually walking up the 'throughType's inheritance
                        // chain.  We could compute it up front and cache it in a set.  However, i
                        // don't want to allocate memory in this function.  Also, in practice
                        // inheritance chains should be very short.  As such, it might actually be
                        // slower to create and check inside the set versus just walking the
                        // inheritance chain.
                        if (originalThroughTypeOpt == null ||
                            originalThroughTypeOpt.InheritsFromOrEqualsIgnoringConstruction(current))
                        {
                            return(true);
                        }
                        else
                        {
                            failedThroughTypeCheck = true;
                        }
                    }

                    // NOTE(cyrusn): The container of an original type is always original.
                    current = current.ContainingType;
                }
            }

            return(false);
        }