// The containing symbol can be one of many things. 
            // 1) Null when this is the global namespace for a compilation.  
            // 2) The SymbolId for an assembly symbol if this is the global namespace for an
            //    assembly.
            // 3) The SymbolId for a module symbol if this is the global namespace for a module.
            // 4) The SymbolId for the containing namespace symbol if this is not a global
            //    namespace.

            public static void Create(INamespaceSymbol symbol, SymbolKeyWriter visitor)
            {
                visitor.WriteString(symbol.MetadataName);

                if (symbol.ContainingNamespace != null)
                {
                    visitor.WriteBoolean(false);
                    visitor.WriteSymbolKey(symbol.ContainingNamespace);
                }
                else
                {
                    // A global namespace can either belong to a module or to a compilation.
                    Debug.Assert(symbol.IsGlobalNamespace);
                    switch (symbol.NamespaceKind)
                    {
                        case NamespaceKind.Module:
                            visitor.WriteBoolean(false);
                            visitor.WriteSymbolKey(symbol.ContainingModule);
                            break;
                        case NamespaceKind.Assembly:
                            visitor.WriteBoolean(false);
                            visitor.WriteSymbolKey(symbol.ContainingAssembly);
                            break;
                        case NamespaceKind.Compilation:
                            visitor.WriteBoolean(true);
                            visitor.WriteSymbolKey(null);
                            break;
                        default:
                            throw new NotImplementedException();
                    }
                }
            }
 public static void Attach(
     INamespaceSymbol @namespace,
     IList<ISymbol> imports)
 {
     var info = new CodeGenerationNamespaceInfo(imports ?? SpecializedCollections.EmptyList<ISymbol>());
     namespaceToInfoMap.Add(@namespace, info);
 }
Beispiel #3
0
        private SDNamespace GetParsedNamespace(INamespaceSymbol namespaceSymbol)
        {
            var descriptionFiles = _descriptionFiles.Where(d => Path.GetFileName(d).ToLower().Contains(namespaceSymbol.Name.ToLower() + ".sdnd"));

            var descriptions = new SDLanguageItemCollection<SDTemplate>();
            foreach (var file in descriptionFiles)
            {
                if (!string.IsNullOrEmpty(namespaceSymbol.Name.Trim()))
                {
                    var splitted = Path.GetFileName(file).ToLower().Replace(namespaceSymbol.Name.ToLower(), " ").Split('.');
                    if (splitted.Length > 0 && splitted[0].Length == 2 && CultureInfo.GetCultures(CultureTypes.AllCultures).Any(c => c.TwoLetterISOLanguageName == splitted[0]))
                    {
                        descriptions.Add(splitted[0], new SDTemplate(File.ReadAllText(file), ParserOptions.Tokens));
                        ExecuteOnDocLanguageFound(splitted[0].ToLower());
                    }
                    else if (splitted.Length > 0 && string.IsNullOrEmpty(splitted[0].Trim()))
                    {
                        descriptions.Add("default", new SDTemplate(File.ReadAllText(file), ParserOptions.Tokens));
                    }
                }
            }

            return new SDNamespace(namespaceSymbol.GetIdentifier())
            {
                Assemblyname = namespaceSymbol.ContainingAssembly.Name,
                Descriptions = descriptions
            };
        }
    public IUnitNamespaceReference Map(INamespaceSymbol namespaceSymbol) {
      Contract.Requires(namespaceSymbol != null);
      Contract.Ensures(Contract.Result<IUnitNamespaceReference>() != null);
      IUnitNamespaceReference nsr = null;
      if (!namespaceSymbolCache.TryGetValue(namespaceSymbol, out nsr)) {

        if (namespaceSymbol.ContainingAssembly.Equals(this.assemblyBeingTranslated)) {
          var n = this.CreateNamespaceDefinition(namespaceSymbol);
          return n;
        }

        if (namespaceSymbol.IsGlobalNamespace) {
          var n = new Microsoft.Cci.MutableCodeModel.RootUnitNamespaceReference() {
            Unit = Map(namespaceSymbol.ContainingAssembly),
          };
          nsr = n;
        } else {
          var ns = new Microsoft.Cci.MutableCodeModel.NestedUnitNamespaceReference() {
            ContainingUnitNamespace = Map(namespaceSymbol.ContainingNamespace),
            Name = this.nameTable.GetNameFor(namespaceSymbol.Name),
          };
          nsr = ns;
        }
        namespaceSymbolCache[namespaceSymbol] = nsr;
      }
      Contract.Assume(nsr != null);
      return nsr;
    }
 public override void VisitNamespace(INamespaceSymbol symbol)
 {
     foreach (var member in symbol.GetMembers())
     {
         member.Accept(this);
     }
 }
 public override void VisitNamespace(INamespaceSymbol symbol)
 {
     ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
     {
         DisplayName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(symbol),
         DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified).GetName(symbol),
     });
 }
		public static Task<Document> AddNamespaceOrTypeDeclarationAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
		{
			try {
				return (Task<Document>)addNamespaceOrTypeDeclarationAsyncMethod.Invoke (null, new object[] { solution, destination, namespaceOrType, options != null ? options.Instance : null, cancellationToken });
			} catch (TargetInvocationException ex) {
				ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
				return null;
			}
		}
        public override void VisitNamespace(INamespaceSymbol symbol)
        {
            symbols.Add(symbol);

            foreach (var childSymbol in symbol.GetMembers())
            {
                childSymbol.Accept(this);
            }
        }
 internal static EnvDTE.CodeElements Create(
     CodeModelState state,
     object parent,
     ProjectId projectId,
     INamespaceSymbol namespaceSymbol)
 {
     var collection = new ExternalNamespaceCollection(state, parent, projectId, namespaceSymbol);
     return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
 }
        private static void CollectTypes(INamespaceSymbol ns, List<ITypeSymbol> types)
        {
            types.AddRange(ns.GetTypeMembers().Cast<ITypeSymbol>());

            foreach (var nestedNs in ns.GetNamespaceMembers())
            {
                CollectTypes(nestedNs, types);
            }
        }
Beispiel #11
0
 public IVsNavInfo CreateForNamespace(INamespaceSymbol namespaceSymbol, Project project, Compilation compilation, bool useExpandedHierarchy = false)
 {
     return Create(
         namespaceSymbol.ContainingAssembly,
         project,
         compilation,
         useExpandedHierarchy,
         namespaceName: GetNamespaceName(namespaceSymbol));
 }
        /// <summary>
        /// Get the full name of a namespace. i.e. "OuterNamespace.Inner.ClassName"
        /// </summary>
        /// <param name="namespaceSymbol">namespace to get name of</param>
        /// <returns>Full display name for a namespaceSymbol</returns>
        internal static string GetFullName(INamespaceSymbol namespaceSymbol)
        {
            if (namespaceSymbol.ContainingNamespace != null &&
                !namespaceSymbol.ContainingNamespace.IsGlobalNamespace)
            {
                return GetFullName(namespaceSymbol.ContainingNamespace) + "." + namespaceSymbol.Name;
            }

            return namespaceSymbol.Name;
        }
        private static void GetNameParts(INamespaceSymbol namespaceSymbol, List<string> result)
        {
            if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace)
            {
                return;
            }

            GetNameParts(namespaceSymbol.ContainingNamespace, result);
            result.Add(namespaceSymbol.Name);
        }
        protected void AddNamespaceLink(INamespaceSymbol namespaceSymbol)
        {
            if (namespaceSymbol.IsGlobalNamespace)
            {
                return;
            }

            var text = namespaceSymbol.ToDisplayString();
            var navInfo = _libraryManager.GetNamespaceNavInfo(namespaceSymbol, _project, GetCompilation(), useExpandedHierarchy: false);

            _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
        }
Beispiel #15
0
		private void Visit(INamespaceSymbol nameSpace)
		{
			foreach (var type in nameSpace.GetTypeMembers())
			{
				Visit(type);
			}

			foreach (var innerNameSpace in nameSpace.GetNamespaceMembers())
			{
				Visit(innerNameSpace);
			}
		}
        private static SyntaxNode GenerateNamespaceDeclarationWorker(
            string name, INamespaceSymbol innermostNamespace)
        {
            var usings = GenerateUsingDirectives(innermostNamespace);

            // If they're just generating the empty namespace then make that into compilation unit.
            if (name == string.Empty)
            {
                return SyntaxFactory.CompilationUnit().WithUsings(usings);
            }

            return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings);
        }
Beispiel #17
0
        public override void VisitNamespace(INamespaceSymbol symbol)
        {
            if (IsUnimportantSymbol(symbol))
                return;

            PrettyPrint(symbol);
            tabCount++;
            foreach(var childSymbol in symbol.GetMembers())
            {
                childSymbol.Accept(this);
            }
            tabCount--;
        }
        internal static async Task<GraphNodeId> GetIdForNamespaceAsync(INamespaceSymbol symbol, Solution solution, CancellationToken cancellationToken)
        {
            CodeQualifiedIdentifierBuilder builder = new CodeQualifiedIdentifierBuilder();

            var assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
            if (assembly != null)
            {
                builder.Assembly = assembly;
            }

            builder.Namespace = symbol.ToDisplayString();

            return builder.ToQualifiedIdentifier();
        }
Beispiel #19
0
        internal void ParseProjectNamespacesRecursively(INamespaceSymbol namespaceSymbol)
        {
            HandleOnItemParseStart(namespaceSymbol.Name);
            if (!ParserOptions.SharpDoxConfig.ExcludedIdentifiers.Contains(namespaceSymbol.GetIdentifier()))
            {
                var sdNamespace = GetParsedNamespace(namespaceSymbol);
                ParserOptions.SDRepository.AddNamespace(sdNamespace);
                _typeParser.ParseProjectTypes(namespaceSymbol.GetTypeMembers().ToList());
            }

            foreach (var childNamespaceSymbol in namespaceSymbol.GetNamespaceMembers())
            {
                ParseProjectNamespacesRecursively(childNamespaceSymbol);
            }
        }
        private static string GetFullNamespace(INamespaceSymbol namespaceSymbol)
        {
            string fullNamespace = namespaceSymbol.Name;

            if (!string.IsNullOrEmpty(fullNamespace))
            {
                string parentNamespace = CodeAnalysisHelper.GetFullNamespace(namespaceSymbol.ContainingNamespace);
                if (!string.IsNullOrEmpty(parentNamespace))
                {
                    fullNamespace = parentNamespace + Type.Delimiter + fullNamespace;
                }
            }

            return fullNamespace;
        }
Beispiel #21
0
 private SDType CreateSDType(ITypeSymbol typeSymbol, INamespaceSymbol namespaceSymbol)
 {
     var sdNamespace = new SDNamespace(namespaceSymbol.GetIdentifier()) { IsProjectStranger = true };
     var sdType = new SDType(typeSymbol.GetIdentifier(), typeSymbol.Name, sdNamespace)
     {
         Accessibility = typeSymbol.DeclaredAccessibility.ToString().ToLower(),
         IsAbstract = typeSymbol.IsAbstract,
         IsReferenceType = typeSymbol.IsReferenceType,
         IsSealed = typeSymbol.IsSealed,
         IsStatic = typeSymbol.IsStatic,
         IsProjectStranger = true,
         Kind = typeSymbol.TypeKind.ToString().ToLower()
     };
     return sdType;
 }
Beispiel #22
0
        public static CompilationUnitSyntax AddNamespaceTo(
            ICodeGenerationService service,
            CompilationUnitSyntax destination,
            INamespaceSymbol @namespace,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var declaration = GenerateNamespaceDeclaration(service, @namespace, options);
            if (!(declaration is NamespaceDeclarationSyntax))
            {
                throw new ArgumentException(CSharpWorkspaceResources.NamespaceCanNotBeAddedIn);
            }

            var members = Insert(destination.Members, (NamespaceDeclarationSyntax)declaration, options, availableIndices);
            return destination.WithMembers(members);
        }
        private static INamespaceSymbol GetNamespace(string nspace, INamespaceSymbol namespaceSymbol)
        {
            namespaceSymbol = namespaceSymbol.GetNamespaceMembers()
                .FirstOrDefault(ns =>
                    {
                        string fullNamespace = CodeAnalysisHelper.GetFullNamespace(ns);
                        return nspace == fullNamespace || nspace.StartsWith(fullNamespace + Type.Delimiter);
                    });

            if (namespaceSymbol != null && CodeAnalysisHelper.GetFullNamespace(namespaceSymbol) != nspace)
            {
                namespaceSymbol = CodeAnalysisHelper.GetNamespace(nspace, namespaceSymbol);
            }

            return namespaceSymbol;
        }
        public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2)
        {
            var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts);
            var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts);

            for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++)
            {
                var comp = names1[i].CompareTo(names2[i]);
                if (comp != 0)
                {
                    return comp;
                }
            }

            return names1.Count - names2.Count;
        }
Beispiel #25
0
        public static NamespaceDeclarationSyntax AddNamespaceTo(
            ICodeGenerationService service,
            NamespaceDeclarationSyntax destination,
            INamespaceSymbol @namespace,
            CodeGenerationOptions options,
            IList<bool> availableIndices,
            CancellationToken cancellationToken)
        {
            var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
            if (!(declaration is NamespaceDeclarationSyntax))
            {
                throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
            }

            var members = Insert(destination.Members, (NamespaceDeclarationSyntax)declaration, options, availableIndices);
            return destination.WithMembers(members);
        }
        internal static SyntaxNode GenerateNamespaceDeclaration(
            ICodeGenerationService service,
            INamespaceSymbol @namespace,
            CodeGenerationOptions options,
            CancellationToken cancellationToken)
        {
            options = options ?? CodeGenerationOptions.Default;
            GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace);

            var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options);

            declaration = options.GenerateMembers
                    ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken)
                    : declaration;

            return AddCleanupAnnotationsTo(declaration);
        }
Beispiel #27
0
        private void AddNamespace(INamespaceSymbol namespaceSymbol)
        {
            if (!_names.IsEmpty) return;

            var classList = namespaceSymbol.GetMembers();

            var methodsList = classList.ToList().SelectMany(x => x.GetMembers());

            var methods = new List<ISymbol>(methodsList);
            try
            {
                _names = new ConcurrentBag<ISymbol>(methods);
            }
            catch
            {
            }
        }
Beispiel #28
0
        public override void VisitNamespace(INamespaceSymbol symbol)
        {
            if (_finished || _symbolPredicate == null || _symbolPredicate(symbol))
            {
                AddDocument(symbol, true, new MetadataItems
                {
                    { CodeAnalysisKeys.SpecificKind, (k, m) => symbol.Kind.ToString() },
                    { CodeAnalysisKeys.MemberNamespaces, DocumentsFor(symbol.GetNamespaceMembers()) },
                    { CodeAnalysisKeys.MemberTypes, DocumentsFor(symbol.GetTypeMembers()) }
                });
            }

            // Descend if not finished, regardless if this namespace was included
            if (!_finished)
            {
                Parallel.ForEach(symbol.GetMembers(), s => s.Accept(this));
            }
        }
		static INamespaceSymbol FindNamespace(INamespaceSymbol globalNamespace, string fullName, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (string.IsNullOrEmpty(fullName))
				return globalNamespace;
			var stack = new Stack<INamespaceSymbol>();
			stack.Push(globalNamespace);

			while (stack.Count > 0) {
				if (cancellationToken.IsCancellationRequested)
					return null;
				var currentNs = stack.Pop();
				if (currentNs.GetFullName() == fullName)
					return currentNs;
				foreach (var childNamespace in currentNs.GetNamespaceMembers())
					stack.Push(childNamespace);
			}
			return null;
		}
Beispiel #30
0
        private static IList<string> GetNameParts(INamespaceSymbol @namespace)
        {
            var parts = new List<string>();

            if (@namespace == null)
            {
                return parts;
            }

            while ([email protected])
            {
                parts.Add(@namespace.Name);
                @namespace = @namespace.ContainingNamespace;
            }

            parts.Reverse();
            return parts;
        }
Beispiel #31
0
        public static ImmutableArray <SymbolDisplayPart> GetDisplayParts(
            ISymbol symbol,
            SymbolDisplayFormat format,
            SymbolDisplayTypeDeclarationOptions typeDeclarationOptions = SymbolDisplayTypeDeclarationOptions.None,
            Func <INamedTypeSymbol, bool> isVisibleAttribute           = null,
            bool formatBaseList            = false,
            bool formatConstraints         = false,
            bool formatParameters          = false,
            bool splitAttributes           = true,
            bool includeAttributeArguments = false,
            bool omitIEnumerable           = false,
            bool useNameOnlyIfPossible     = false)
        {
            ImmutableArray <SymbolDisplayPart> parts;

            if (symbol is INamedTypeSymbol typeSymbol)
            {
                parts = typeSymbol.ToDisplayParts(format, typeDeclarationOptions);
            }
            else
            {
                parts      = symbol.ToDisplayParts(format);
                typeSymbol = null;
            }

            ImmutableArray <AttributeData> attributes = ImmutableArray <AttributeData> .Empty;
            bool hasAttributes = false;

            if (isVisibleAttribute != null)
            {
                attributes = symbol.GetAttributes();

                hasAttributes = attributes.Any(f => isVisibleAttribute(f.AttributeClass));
            }

            int baseListCount         = 0;
            INamedTypeSymbol baseType = null;
            ImmutableArray <INamedTypeSymbol> interfaces = default;

            if (typeSymbol != null)
            {
                if (typeSymbol.TypeKind.Is(TypeKind.Class, TypeKind.Interface))
                {
                    baseType = typeSymbol.BaseType;

                    if (baseType?.SpecialType == SpecialType.System_Object)
                    {
                        baseType = null;
                    }
                }

                interfaces = typeSymbol.Interfaces;

                if (omitIEnumerable &&
                    interfaces.Any(f => f.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T))
                {
                    interfaces = interfaces.RemoveAll(f => f.SpecialType == SpecialType.System_Collections_IEnumerable);
                }

                baseListCount = interfaces.Length;

                if (baseType != null)
                {
                    baseListCount++;
                }
            }

            int constraintCount = 0;
            int whereIndex      = -1;

            for (int i = 0; i < parts.Length; i++)
            {
                if (parts[i].IsKeyword("where"))
                {
                    if (whereIndex == -1)
                    {
                        whereIndex = i;
                    }

                    constraintCount++;
                }
            }

            if (!hasAttributes &&
                baseListCount == 0 &&
                constraintCount == 0 &&
                (!formatParameters || symbol.GetParameters().Length <= 1))
            {
                return(parts);
            }

            INamespaceSymbol containingNamespace = (useNameOnlyIfPossible) ? symbol.ContainingNamespace : null;

            ImmutableArray <SymbolDisplayPart> .Builder builder = ImmutableArray.CreateBuilder <SymbolDisplayPart>(parts.Length);

            AddAttributes(builder, attributes, isVisibleAttribute, containingNamespace, splitAttributes: splitAttributes, includeAttributeArguments: includeAttributeArguments);

            if (baseListCount > 0)
            {
                if (whereIndex != -1)
                {
                    builder.AddRange(parts, whereIndex);
                }
                else
                {
                    builder.AddRange(parts);
                    builder.AddSpace();
                }

                builder.AddPunctuation(":");
                builder.AddSpace();

                if (baseType != null)
                {
                    builder.AddDisplayParts(baseType, containingNamespace);

                    if (interfaces.Any())
                    {
                        builder.AddPunctuation(",");

                        if (formatBaseList)
                        {
                            builder.AddLineBreak();
                            builder.AddIndentation();
                        }
                        else
                        {
                            builder.AddSpace();
                        }
                    }
                }

                interfaces = interfaces.Sort((x, y) =>
                {
                    INamespaceSymbol n1 = x.ContainingNamespace;
                    INamespaceSymbol n2 = y.ContainingNamespace;

                    if (!MetadataNameEqualityComparer <INamespaceSymbol> .Instance.Equals(n1, n2))
                    {
                        return(string.CompareOrdinal(
                                   n1.ToDisplayString(SymbolDisplayFormats.TypeNameAndContainingTypesAndNamespaces),
                                   n2.ToDisplayString(SymbolDisplayFormats.TypeNameAndContainingTypesAndNamespaces)));
                    }

                    return(string.CompareOrdinal(
                               ToDisplayString(x, containingNamespace),
                               ToDisplayString(y, containingNamespace)));
                });

                ImmutableArray <INamedTypeSymbol> .Enumerator en = interfaces.GetEnumerator();

                if (en.MoveNext())
                {
                    while (true)
                    {
                        builder.AddDisplayParts(en.Current, containingNamespace);

                        if (en.MoveNext())
                        {
                            builder.AddPunctuation(",");

                            if (formatBaseList)
                            {
                                builder.AddLineBreak();
                                builder.AddIndentation();
                            }
                            else
                            {
                                builder.AddSpace();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                if (whereIndex != -1)
                {
                    if (!formatConstraints ||
                        (baseListCount == 1 && constraintCount == 1))
                    {
                        builder.AddSpace();
                    }
                }
            }
            else if (whereIndex != -1)
            {
                builder.AddRange(parts, whereIndex);
            }
            else
            {
                builder.AddRange(parts);
            }

            if (whereIndex != -1)
            {
                for (int i = whereIndex; i < parts.Length; i++)
                {
                    if (parts[i].IsKeyword("where"))
                    {
                        if (formatConstraints &&
                            (baseListCount > 1 || constraintCount > 1))
                        {
                            builder.AddLineBreak();
                            builder.AddIndentation();
                        }

                        builder.Add(parts[i]);
                    }
                    else if (parts[i].IsTypeName() &&
                             parts[i].Symbol is INamedTypeSymbol namedTypeSymbol)
                    {
                        builder.AddDisplayParts(namedTypeSymbol, containingNamespace);
                    }
                    else
                    {
                        builder.Add(parts[i]);
                    }
                }
            }

            if (formatParameters)
            {
                ImmutableArray <IParameterSymbol> parameters = symbol.GetParameters();

                if (parameters.Length > 1)
                {
                    FormatParameters(symbol, builder, DeclarationListOptions.DefaultValues.IndentChars);
                }
            }

            return(builder.ToImmutableArray());
        }
Beispiel #32
0
        private static void AddDisplayParts(this ImmutableArray <SymbolDisplayPart> .Builder builder, ISymbol symbol, INamespaceSymbol containingNamespace)
        {
            if (containingNamespace != null &&
                symbol.ContainingNamespace == containingNamespace)
            {
                builder.AddRange(symbol.ToDisplayParts(SymbolDisplayFormats.TypeNameAndContainingTypes));
            }
            else
            {
                builder.AddRange(symbol.ToDisplayParts(SymbolDisplayFormats.TypeNameAndContainingTypesAndNamespaces));
            }

            if (!(symbol is INamedTypeSymbol typeSymbol))
            {
                return;
            }

            ImmutableArray <ITypeSymbol> typeArguments = typeSymbol.TypeArguments;

            ImmutableArray <ITypeSymbol> .Enumerator en = typeArguments.GetEnumerator();

            if (en.MoveNext())
            {
                builder.AddPunctuation("<");

                while (true)
                {
                    if (en.Current.Kind == SymbolKind.NamedType)
                    {
                        builder.AddDisplayParts((INamedTypeSymbol)en.Current, containingNamespace);
                    }
                    else
                    {
                        Debug.Assert(en.Current.Kind == SymbolKind.TypeParameter, en.Current.Kind.ToString());

                        builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.TypeParameterName, en.Current, en.Current.Name));
                    }

                    if (en.MoveNext())
                    {
                        builder.AddPunctuation(",");
                        builder.AddSpace();
                    }
                    else
                    {
                        break;
                    }
                }

                builder.AddPunctuation(">");
            }
        }
 private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace)
 => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace;
Beispiel #34
0
 protected virtual bool ShallAnalyze(INamespaceSymbol symbol) => true;
Beispiel #35
0
        private static string CalcFullName(ISymbol type, bool includeSelfName)
        {
            if (null == type)
            {
                return(string.Empty);
            }
            List <string> list = new List <string>();

            if (includeSelfName)
            {
                //如果一个类标记为忽略,如果它是泛型类,则创建对象的名字使用泛型参数构建而不是实际类型参数构建
                //这种类因为需要在脚本里手动实现,假定都是可以一个类实现泛型类的功能的。
                //注意:由于这里是计算类型名称,使用命令行参数标记的忽略是没有效果(它使用名称来标记),此时仍然需要使用属性标记忽略的泛型类
                bool ignore = ClassInfo.HasAttribute(type, "Cs2Dsl.IgnoreAttribute");
                if (ignore)
                {
                    list.Add(CalcNameWithTypeParameters(type));
                }
                else
                {
                    list.Add(CalcNameWithTypeArguments(type));
                }
            }
            INamespaceSymbol ns = type.ContainingNamespace;
            var    ct           = type.ContainingType;
            string name         = string.Empty;

            if (null != ct)
            {
                bool ignore = ClassInfo.HasAttribute(ct, "Cs2Dsl.IgnoreAttribute");
                if (ignore)
                {
                    name = CalcNameWithTypeParameters(ct);
                }
                else
                {
                    name = CalcNameWithTypeArguments(ct);
                }
            }
            while (null != ct && name.Length > 0)
            {
                list.Insert(0, name);
                ns = ct.ContainingNamespace;
                ct = ct.ContainingType;
                if (null != ct)
                {
                    bool ignore = ClassInfo.HasAttribute(ct, "Cs2Dsl.IgnoreAttribute");
                    if (ignore)
                    {
                        name = CalcNameWithTypeParameters(ct);
                    }
                    else
                    {
                        name = CalcNameWithTypeArguments(ct);
                    }
                }
                else
                {
                    name = string.Empty;
                }
            }
            while (null != ns && ns.Name.Length > 0)
            {
                list.Insert(0, ns.Name);
                ns = ns.ContainingNamespace;
            }
            return(string.Join(".", list.ToArray()));
        }
        private void WriteLocalLink(ISymbol symbol)
        {
            int cnc = 0;

            INamespaceSymbol cn = symbol.ContainingNamespace;

            while (cn?.IsGlobalNamespace == false)
            {
                cn = cn.ContainingNamespace;
                cnc++;
            }

            while (cnc > 0)
            {
                WriteString(GetContainingNamespace(cnc).Name);
                WriteString("_");
                cnc--;
            }

            INamedTypeSymbol ct = symbol.ContainingType;

            int ctc = 0;

            while (ct != null)
            {
                ct = ct.ContainingType;
                ctc++;
            }

            while (ctc > 0)
            {
                WriteType(GetContainingType(ctc));
                WriteString("_");
                ctc--;
            }

            if (symbol.IsKind(SymbolKind.NamedType))
            {
                WriteType((INamedTypeSymbol)symbol);
            }
            else
            {
                WriteString(symbol.Name);
            }

            INamespaceSymbol GetContainingNamespace(int count)
            {
                INamespaceSymbol n = symbol.ContainingNamespace;

                while (count > 1)
                {
                    n = n.ContainingNamespace;
                    count--;
                }

                return(n);
            }

            INamedTypeSymbol GetContainingType(int count)
            {
                INamedTypeSymbol t = symbol.ContainingType;

                while (count > 1)
                {
                    t = t.ContainingType;
                    count--;
                }

                return(t);
            }

            void WriteType(INamedTypeSymbol typeSymbol)
            {
                WriteString(typeSymbol.Name);

                int arity = typeSymbol.Arity;

                if (arity > 0)
                {
                    WriteString("_");
                    WriteString(arity.ToString());
                }
            }
        }
Beispiel #37
0
 public virtual void VisitNamespace(INamespaceSymbol symbol)
 {
     DefaultVisit(symbol);
 }
Beispiel #38
0
 /// <summary>
 /// Create a new solution where the declaration of the destination symbol has an additional namespace or type of the same signature as the specified namespace or type symbol.
 /// Returns the document in the new solution where the destination symbol is declared.
 /// </summary>
 public static Task <Document> AddNamespaceOrTypeDeclarationAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
 {
     return(GetCodeGenerationService(solution.Workspace, destination.Language).AddNamespaceOrTypeAsync(solution, destination, namespaceOrType, options, cancellationToken));
 }
Beispiel #39
0
 /// <summary>
 /// Returns a newly created namespace declaration node from the provided namespace.
 /// </summary>
 public static SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, Workspace workspace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions options = null)
 {
     return(GetCodeGenerationService(workspace, @namespace.Language).CreateNamespaceDeclaration(@namespace, destination, options));
 }
Beispiel #40
0
        /// <summary>
        /// Gets the mappers for the namespaces contained in <see cref="ElementMapper{T}.Left"/> and <see cref="ElementMapper{T}.Right"/>
        /// </summary>
        /// <returns>The list of <see cref="NamespaceMapper"/>.</returns>
        public IEnumerable <NamespaceMapper> GetNamespaces()
        {
            if (_namespaces == null)
            {
                _namespaces = new Dictionary <INamespaceSymbol, NamespaceMapper>(Settings.EqualityComparer);
                AddOrCreateMappers(Left, ElementSide.Left);

                if (Right.Length == 1)
                {
                    AddOrCreateMappers(Right[0], ElementSide.Right);
                }
                else
                {
                    for (int i = 0; i < Right.Length; i++)
                    {
                        AddOrCreateMappers(Right[i], ElementSide.Right, i);
                    }
                }

                void AddOrCreateMappers(IAssemblySymbol symbol, ElementSide side, int setIndex = 0)
                {
                    if (symbol == null)
                    {
                        return;
                    }

                    Dictionary <INamespaceSymbol, List <INamedTypeSymbol> > typeForwards = ResolveTypeForwards(symbol, Settings.EqualityComparer, setIndex);

                    Stack <INamespaceSymbol> stack = new();

                    stack.Push(symbol.GlobalNamespace);
                    while (stack.Count > 0)
                    {
                        INamespaceSymbol nsSymbol        = stack.Pop();
                        bool             hasTypeForwards = typeForwards.TryGetValue(nsSymbol, out List <INamedTypeSymbol> types);
                        if (hasTypeForwards || nsSymbol.GetTypeMembers().Length > 0)
                        {
                            NamespaceMapper mapper = AddMapper(nsSymbol);
                            if (hasTypeForwards)
                            {
                                mapper.AddForwardedTypes(types, side, setIndex);

                                // remove the typeforwards for this namespace as we did
                                // find and instance of the namespace on the current assembly
                                // and we don't want to create a mapper with the namespace in
                                // the assembly where the forwarded type is defined.
                                typeForwards.Remove(nsSymbol);
                            }
                        }

                        foreach (INamespaceSymbol child in nsSymbol.GetNamespaceMembers())
                        {
                            stack.Push(child);
                        }
                    }

                    // If the current assembly didn't have a namespace symbol for the resolved typeforwards
                    // use the namespace symbol in the assembly where the forwarded type is defined.
                    // But create the mapper with typeForwardsOnly setting to not visit types defined in the target assembly.
                    foreach (KeyValuePair <INamespaceSymbol, List <INamedTypeSymbol> > kvp in typeForwards)
                    {
                        NamespaceMapper mapper = AddMapper(kvp.Key, checkIfExists: true, typeforwardsOnly: true);
                        mapper.AddForwardedTypes(kvp.Value, side, setIndex);
                    }

                    NamespaceMapper AddMapper(INamespaceSymbol ns, bool checkIfExists = false, bool typeforwardsOnly = false)
                    {
                        if (!_namespaces.TryGetValue(ns, out NamespaceMapper mapper))
                        {
                            mapper = new NamespaceMapper(Settings, Right.Length, typeforwardsOnly: typeforwardsOnly);
                            _namespaces.Add(ns, mapper);
                        }
                        else if (checkIfExists && mapper.GetElement(side, setIndex) != null)
                        {
                            return(mapper);
                        }

                        mapper.AddElement(ns, side, setIndex);
                        return(mapper);
                    }
                }

                Dictionary <INamespaceSymbol, List <INamedTypeSymbol> > ResolveTypeForwards(IAssemblySymbol assembly, IEqualityComparer <ISymbol> comparer, int index)
                {
                    Dictionary <INamespaceSymbol, List <INamedTypeSymbol> > typeForwards = new(comparer);

                    foreach (INamedTypeSymbol symbol in assembly.GetForwardedTypes())
                    {
                        if (symbol.TypeKind != TypeKind.Error)
                        {
                            if (!typeForwards.TryGetValue(symbol.ContainingNamespace, out List <INamedTypeSymbol> types))
                            {
                                types = new List <INamedTypeSymbol>();
                                typeForwards.Add(symbol.ContainingNamespace, types);
                            }

                            types.Add(symbol);
                        }
                        else
                        {
                            // If we should warn on missing references and we are unable to resolve the type forward, then we should log a diagnostic
                            if (Settings.WarnOnMissingReferences)
                            {
                                _assemblyLoadErrors[index].Add(new CompatDifference(
                                                                   DiagnosticIds.AssemblyReferenceNotFound,
                                                                   string.Format(Resources.MatchingAssemblyNotFound, $"{symbol.ContainingAssembly.Name}.dll"),
                                                                   DifferenceType.Changed,
                                                                   string.Empty));
                            }
                        }
                    }

                    return(typeForwards);
                }
            }

            return(_namespaces.Values);
        }
Beispiel #41
0
 public virtual TResult VisitNamespace(INamespaceSymbol symbol)
 {
     return(DefaultVisit(symbol));
 }
Beispiel #42
0
 private static RQNamespace BuildNamespace(INamespaceSymbol @namespace)
 {
     return(new RQNamespace(RQNodeBuilder.GetNameParts(@namespace)));
 }
Beispiel #43
0
        private static bool IsRootNamespace(ISymbol symbol)
        {
            INamespaceSymbol s = null;

            return(((s = symbol as INamespaceSymbol) != null) && s.IsGlobalNamespace);
        }
Beispiel #44
0
 public abstract SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken);
 public override void VisitNamespace(INamespaceSymbol symbol)
 {
     Parallel.ForEach(symbol.GetMembers(), s => s.Accept(this));
 }
Beispiel #46
0
 protected abstract TDeclarationNode AddNamespace <TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList <bool> availableIndices, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
Beispiel #47
0
        private static async Task <GraphNode> GetOrCreateNodeForNamespaceAsync(Graph graph, INamespaceSymbol symbol, Solution solution, CancellationToken cancellationToken)
        {
            var id = await GraphNodeIdCreation.GetIdForNamespaceAsync(symbol, solution, cancellationToken).ConfigureAwait(false);

            var node = graph.Nodes.GetOrCreate(id);

            node.AddCategory(CodeNodeCategories.Namespace);

            return(node);
        }
Beispiel #48
0
 public TDeclarationNode AddNamespace <TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
 => WithAnnotations(AddNamespace(destination, @namespace, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken), cancellationToken), options);
Beispiel #49
0
 protected virtual IEnumerable <Diagnostic> Analyze(INamespaceSymbol symbol) => Enumerable.Empty <Diagnostic>();
Beispiel #50
0
 private bool HasAccessibleTypes(INamespaceSymbol @namespace, SemanticModel model, CancellationToken cancellationToken)
 {
     return(Enumerable.Any(@namespace.GetAllTypes(cancellationToken), t => t.IsAccessibleWithin(model.Compilation.Assembly)));
 }
Beispiel #51
0
 protected sealed override IEnumerable <Diagnostic> AnalyzeNamespace(INamespaceSymbol symbol) => ShallAnalyze(symbol)
                                                                                              ? Analyze(symbol)
                                                                                              : Enumerable.Empty <Diagnostic>();
Beispiel #52
0
 protected override INamespaceSymbol CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol)
 {
     throw new NotImplementedException();
 }
Beispiel #53
0
 static void BuildNamespace(this INamespaceSymbol ns, Context cx, TextWriter trapFile)
 {
     trapFile.WriteSubId(Namespace.Create(cx, ns));
     trapFile.Write('.');
 }
Beispiel #54
0
 protected override INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
 {
     return(new MissingNamespaceSymbol((NamespaceSymbol)container, name));
 }
Beispiel #55
0
 public static bool IsRuntimeCompilerServices(this INamespaceSymbol symbol)
 {
     return(symbol.Name == "CompilerServices" && symbol.ContainingNamespace.Name == "Runtime" && symbol.ContainingNamespace.ContainingNamespace.Name == "System");
 }
        public void WriteType(INamedTypeSymbol type, string kind, INamedTypeSymbol oldType)
        {
            bool isTypeRemoved = type == null && oldType != null;

            if (isTypeRemoved)
            {
                type = oldType;
            }

            if (type.ContainingNamespace != currentNamespace)
            {
                var nsname = type.GetFullNamespace();
                currentNamespace = type.ContainingNamespace;
                sw.WriteLine($"<div class='namespaceHeader' id='{nsname}'>{nsname}</div>");
            }
            sw.WriteLine($"<div class='objectBox {(isTypeRemoved ? " typeRemoved'" : "")}' id='{type.GetFullTypeName()}'>");
            bool isEmpty       = true;
            var  memberBuilder = new StringBuilder();

            {
                //List out members
                if (type.GetConstructors(oldType).Any())
                {
                    isEmpty = false;
                    memberBuilder.AppendLine($"<div class='members'><h4>Constructors</h4><ul>");
                    foreach (var method in type.GetConstructors(oldType))
                    {
                        var str = FormatMember(method.Item1);
                        if (method.Item2)
                        {
                            str = $"<span class='memberRemoved'>{str}</span>";
                        }
                        memberBuilder.AppendLine($"{GetIcon(method.Item1, str)}");
                    }
                    memberBuilder.AppendLine("</ul></div>");
                }
                if (type.GetProperties(oldType).Any())
                {
                    isEmpty = false;
                    memberBuilder.AppendLine($"<div class='members'><h4>Properties</h4><ul>");
                    foreach (var method in type.GetProperties(oldType))
                    {
                        var str = FormatMember(method.Item1);
                        if (method.Item2)
                        {
                            str = $"<span class='memberRemoved'>{str}</span>";
                        }
                        memberBuilder.AppendLine($"{GetIcon(method.Item1, str)}");
                    }
                    memberBuilder.AppendLine("</ul></div>");
                }
                if (type.GetMethods(oldType).Any())
                {
                    isEmpty = false;
                    memberBuilder.AppendLine($"<div class='members'><h4>Methods</h4><ul>");
                    foreach (var method in type.GetMethods(oldType))
                    {
                        var str = FormatMember(method.Item1);
                        if (method.Item2)
                        {
                            str = $"<span class='memberRemoved'>{str}</span>";
                        }
                        memberBuilder.AppendLine($"{GetIcon(method.Item1, str)}");
                    }
                    memberBuilder.AppendLine("</ul></div>");
                }
                if (type.GetEvents(oldType).Any())
                {
                    isEmpty = false;
                    memberBuilder.AppendLine($"<div class='members'><h4>Events</h4><ul>");
                    foreach (var method in type.GetEvents(oldType))
                    {
                        var str = FormatMember(method.Item1);
                        if (method.Item2)
                        {
                            str = $"<span class='memberRemoved'>{str}</span>";
                        }
                        memberBuilder.AppendLine($"{GetIcon(method.Item1, str)}");
                    }
                    memberBuilder.AppendLine("</ul></div>");
                }
                if (type.TypeKind == TypeKind.Enum)
                {
                    isEmpty = false;
                    memberBuilder.AppendLine("<ul class='members'>");
                    foreach (var e in type.GetEnums(oldType))
                    {
                        string str = Briefify(e);
                        memberBuilder.AppendLine($"{GetIcon(e, str)}");
                    }
                    memberBuilder.AppendLine("</ul>");
                }
            }
            sw.WriteLine($"<div class='header {kind}{(isEmpty ? " noMembers" : "")}'>");

            //Write class name + Inheritance
            var brief = type.GetDescription();

            sw.Write($"<span ");
            if (!string.IsNullOrEmpty(brief))
            {
                sw.Write($"title=\"{System.Web.HttpUtility.HtmlEncode(brief)}\"");
            }
            sw.Write($">{System.Web.HttpUtility.HtmlEncode(type.Name)}");
            if (type.BaseType != null && type.BaseType.Name != "Object" && type.TypeKind != TypeKind.Enum)
            {
                if (oldType == null || type.BaseType.ToDisplayString() != oldType.BaseType.ToDisplayString())
                {
                    sw.Write(" : ");
                    if (oldType != null)
                    {
                        sw.Write($"<span class='memberRemoved'>{FormatType(oldType.BaseType)}</span>");
                    }
                    sw.Write(FormatType(type.BaseType));
                }
            }
            sw.WriteLine("</span>");
            //Document interfaces
            if (type.GetInterfaces(oldType).Any())
            {
                isEmpty = false;
                sw.Write("<br/>Implements ");
                int i = 0;
                foreach (var iface in type.GetInterfaces(oldType))
                {
                    if (i > 0)
                    {
                        sw.Write(", ");
                    }
                    if (iface.Item2)
                    {
                        sw.Write("<span class='memberRemoved'>");
                    }
                    sw.Write(FormatType(iface.Item1));
                    if (iface.Item2)
                    {
                        sw.Write("</span>");
                    }
                    i++;
                }
                sw.WriteLine("</span>");
            }
            sw.WriteLine("</div>"); //End header box

            sw.Write(memberBuilder.ToString());
            sw.WriteLine("</div>");
            sw.Flush();
        }
Beispiel #57
0
        private static void AddAttributes(
            ImmutableArray <SymbolDisplayPart> .Builder builder,
            ImmutableArray <AttributeData> attributes,
            Func <INamedTypeSymbol, bool> predicate = null,
            INamespaceSymbol containingNamespace    = null,
            bool splitAttributes           = true,
            bool includeAttributeArguments = false,
            bool isAssemblyAttribute       = false,
            bool addNewLine = true)
        {
            using (IEnumerator <AttributeData> en = attributes
                                                    .Where(f => predicate(f.AttributeClass))
                                                    .OrderBy(f => ToDisplayString(f.AttributeClass, containingNamespace)).GetEnumerator())
            {
                if (en.MoveNext())
                {
                    builder.AddPunctuation("[");

                    if (isAssemblyAttribute)
                    {
                        builder.AddKeyword("assembly");
                        builder.AddPunctuation(":");
                        builder.AddSpace();
                    }

                    while (true)
                    {
                        builder.AddDisplayParts(en.Current.AttributeClass, containingNamespace);

                        if (includeAttributeArguments)
                        {
                            AddAttributeArguments(en.Current);
                        }

                        if (en.MoveNext())
                        {
                            if (splitAttributes)
                            {
                                builder.AddPunctuation("]");

                                if (addNewLine)
                                {
                                    builder.AddLineBreak();
                                }
                                else
                                {
                                    builder.AddSpace();
                                }

                                builder.AddPunctuation("[");

                                if (isAssemblyAttribute)
                                {
                                    builder.AddKeyword("assembly");
                                    builder.AddPunctuation(":");
                                    builder.AddSpace();
                                }
                            }
                            else
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    builder.AddPunctuation("]");

                    if (addNewLine)
                    {
                        builder.AddLineBreak();
                    }
                }
            }

            void AddAttributeArguments(AttributeData attributeData)
            {
                bool hasConstructorArgument = false;
                bool hasNamedArgument       = false;

                AppendConstructorArguments();
                AppendNamedArguments();

                if (hasConstructorArgument || hasNamedArgument)
                {
                    builder.AddPunctuation(")");
                }

                void AppendConstructorArguments()
                {
                    ImmutableArray <TypedConstant> .Enumerator en = attributeData.ConstructorArguments.GetEnumerator();

                    if (en.MoveNext())
                    {
                        hasConstructorArgument = true;
                        builder.AddPunctuation("(");

                        while (true)
                        {
                            AddConstantValue(en.Current);

                            if (en.MoveNext())
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }

                void AppendNamedArguments()
                {
                    ImmutableArray <KeyValuePair <string, TypedConstant> > .Enumerator en = attributeData.NamedArguments.GetEnumerator();

                    if (en.MoveNext())
                    {
                        hasNamedArgument = true;

                        if (hasConstructorArgument)
                        {
                            builder.AddPunctuation(",");
                            builder.AddSpace();
                        }
                        else
                        {
                            builder.AddPunctuation("(");
                        }

                        while (true)
                        {
                            builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, null, en.Current.Key));
                            builder.AddSpace();
                            builder.AddPunctuation("=");
                            builder.AddSpace();
                            AddConstantValue(en.Current.Value);

                            if (en.MoveNext())
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }

            void AddConstantValue(TypedConstant typedConstant)
            {
                switch (typedConstant.Kind)
                {
                case TypedConstantKind.Primitive:
                {
                    builder.Add(new SymbolDisplayPart(
                                    GetSymbolDisplayPart(typedConstant.Type.SpecialType),
                                    null,
                                    SymbolDisplay.FormatPrimitive(typedConstant.Value, quoteStrings: true, useHexadecimalNumbers: false)));

                    break;
                }

                case TypedConstantKind.Enum:
                {
                    OneOrMany <EnumFieldSymbolInfo> oneOrMany = EnumUtility.GetConstituentFields(typedConstant.Value, (INamedTypeSymbol)typedConstant.Type);

                    OneOrMany <EnumFieldSymbolInfo> .Enumerator en = oneOrMany.GetEnumerator();

                    if (en.MoveNext())
                    {
                        while (true)
                        {
                            AddDisplayParts(builder, en.Current.Symbol, containingNamespace);

                            if (en.MoveNext())
                            {
                                builder.AddSpace();
                                builder.AddPunctuation("|");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        builder.AddPunctuation("(");
                        AddDisplayParts(builder, (INamedTypeSymbol)typedConstant.Type, containingNamespace);
                        builder.AddPunctuation(")");
                        builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.NumericLiteral, null, typedConstant.Value.ToString()));
                    }

                    break;
                }

                case TypedConstantKind.Type:
                {
                    builder.AddKeyword("typeof");
                    builder.AddPunctuation("(");
                    AddDisplayParts(builder, (ISymbol)typedConstant.Value, containingNamespace);
                    builder.AddPunctuation(")");

                    break;
                }

                case TypedConstantKind.Array:
                {
                    var arrayType = (IArrayTypeSymbol)typedConstant.Type;

                    builder.AddKeyword("new");
                    builder.AddSpace();
                    AddDisplayParts(builder, arrayType.ElementType, containingNamespace);

                    builder.AddPunctuation("[");
                    builder.AddPunctuation("]");
                    builder.AddSpace();
                    builder.AddPunctuation("{");
                    builder.AddSpace();

                    ImmutableArray <TypedConstant> .Enumerator en = typedConstant.Values.GetEnumerator();

                    if (en.MoveNext())
                    {
                        while (true)
                        {
                            AddConstantValue(en.Current);

                            if (en.MoveNext())
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    builder.AddSpace();
                    builder.AddPunctuation("}");
                    break;
                }

                default:
                {
                    throw new InvalidOperationException();
                }
                }

                SymbolDisplayPartKind GetSymbolDisplayPart(SpecialType specialType)
                {
                    switch (specialType)
                    {
                    case SpecialType.System_Boolean:
                        return(SymbolDisplayPartKind.Keyword);

                    case SpecialType.System_SByte:
                    case SpecialType.System_Byte:
                    case SpecialType.System_Int16:
                    case SpecialType.System_UInt16:
                    case SpecialType.System_Int32:
                    case SpecialType.System_UInt32:
                    case SpecialType.System_Int64:
                    case SpecialType.System_UInt64:
                    case SpecialType.System_Single:
                    case SpecialType.System_Double:
                        return(SymbolDisplayPartKind.NumericLiteral);

                    case SpecialType.System_Char:
                    case SpecialType.System_String:
                        return(SymbolDisplayPartKind.StringLiteral);

                    default:
                        throw new InvalidOperationException();
                    }
                }
            }
        }
 internal NamespaceSymbolKey(INamespaceSymbol symbol, Visitor visitor)
 {
     _containerKeyOpt = DetermineContainerKey(symbol, visitor);
     _metadataName    = symbol.MetadataName;
 }
Beispiel #59
0
        /// <summary>
        /// When overridden in a derived class, determines whether two objects of type <typeparamref name="TSymbol" /> are equal.
        /// </summary>
        /// <param name="x">The first object to compare.</param>
        /// <param name="y">The second object to compare.</param>
        /// <returns>true if the specified objects are equal; otherwise, false.</returns>
        public override bool Equals(TSymbol x, TSymbol y)
        {
            if (object.ReferenceEquals(x, y))
            {
                return(true);
            }

            if (Default.Equals(x, default(TSymbol)))
            {
                return(false);
            }

            if (Default.Equals(y, default(TSymbol)))
            {
                return(false);
            }

            if (!StringComparer.Ordinal.Equals(x.MetadataName, y.MetadataName))
            {
                return(false);
            }

            INamedTypeSymbol t1 = x.ContainingType;
            INamedTypeSymbol t2 = y.ContainingType;

            while (!object.ReferenceEquals(t1, t2))
            {
                if (t1 == null)
                {
                    return(false);
                }

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

                if (!StringComparer.Ordinal.Equals(t1.MetadataName, t2.MetadataName))
                {
                    return(false);
                }

                t1 = t1.ContainingType;
                t2 = t2.ContainingType;
            }

            INamespaceSymbol n1 = x.ContainingNamespace;
            INamespaceSymbol n2 = y.ContainingNamespace;

            while (!object.ReferenceEquals(n1, n2))
            {
                if (n1 == null)
                {
                    return(false);
                }

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

                if (!StringComparer.Ordinal.Equals(n1.MetadataName, n2.MetadataName))
                {
                    return(false);
                }

                n1 = n1.ContainingNamespace;
                n2 = n2.ContainingNamespace;
            }

            return(true);
        }
 private bool HasAnyPublicTypes(INamespaceSymbol subNamespaceSymbol)
 {
     return(subNamespaceSymbol.GetTypeMembers().Any(t => IsAccessible(t)));
 }