private void AssertHasModifier(BaseTypeDeclarationSyntax type, SyntaxKind modifier)
 {
     Assert.Contains(
         type.Modifiers,
         t => t.Kind() == modifier
         );
 }
Exemple #2
0
 private static SyntaxToken GetLastMainModifier(BaseTypeDeclarationSyntax node)
 {
     return(node.Modifiers.Last(m => m.IsKind(SyntaxKind.PublicKeyword) ||
                                m.IsKind(SyntaxKind.ProtectedKeyword) ||
                                m.IsKind(SyntaxKind.InternalKeyword) ||
                                m.IsKind(SyntaxKind.PrivateKeyword)));
 }
Exemple #3
0
        private static BaseTypeDeclarationSyntax AddGeneratedCodeAttribute(BaseTypeDeclarationSyntax typeDecl)
        {
            AttributeListSyntax attributeListForGeneratedCodeAttribute =
                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(MakeGeneratedCodeAttribute()));

            var enumDecl = typeDecl as EnumDeclarationSyntax;

            if (enumDecl != null)
            {
                return(enumDecl.AddAttributeLists(attributeListForGeneratedCodeAttribute));
            }

            var classDecl = typeDecl as ClassDeclarationSyntax;

            if (classDecl != null)
            {
                return(classDecl.AddAttributeLists(attributeListForGeneratedCodeAttribute));
            }

            var interfaceDecl = typeDecl as InterfaceDeclarationSyntax;

            if (interfaceDecl != null)
            {
                return(interfaceDecl.AddAttributeLists(attributeListForGeneratedCodeAttribute));
            }

            throw new ArgumentException("Invalid argument type: " + typeDecl.GetType().Name, nameof(typeDecl));
        }
        private async Task<Solution> RenameType(Document document, BaseTypeDeclarationSyntax typeDecl, CancellationToken cancellationToken)
        {
            try
            {
                var newName = GetDocumentName(document);

                // Get the symbol representing the type to be renamed.
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
                var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);

                // Produce a new solution that has all references to that type renamed, including the declaration.
                var originalSolution = document.Project.Solution;
                var optionSet = originalSolution.Workspace.Options;
                var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);

                // Return the new solution with the now-uppercase type name.
                return newSolution;
            }
            catch (Exception e)
            {
                LogException(e);
                return document.Project.Solution;
            }

        }
Exemple #5
0
        protected override async Task <Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
        {
            Document document = _context.Context.Document;

            SyntaxNode rootNode = await document.GetSyntaxRootAsync(_context.Context.CancellationToken).ConfigureAwait(false);

            BaseTypeDeclarationSyntax node = GetClassTypeNode(rootNode);

            if (node == null)
            {
                return(document);
            }

            // if the context is not in a class, return the Document
            ClassDeclarationSyntax nodeClassConceiler = node.AncestorsAndSelf().OfType <ClassDeclarationSyntax>().Single();

            if (nodeClassConceiler == null)
            {
                return(document);
            }

            // First, remove all but the first MainModifier
            while (HasMoreThanOneMainModifier(node))
            {
                // Remove the last MainModifier
                rootNode = rootNode.ReplaceToken(GetLastMainModifier(node), SyntaxFactory.Token(SyntaxKind.None));
                node     = GetClassTypeNode(rootNode);
            }

            // Second, replace the MainModifier with the NewModifiers
            rootNode = rootNode.ReplaceToken(node.Modifiers.First(), _context.NewModifiers);

            // Cleanup additional modifiers (ie. "internal" left behind)
            return(document.WithSyntaxRoot(rootNode));
        }
        public static BaseTypeDeclarationSyntax WithModifiers(this BaseTypeDeclarationSyntax typeDeclaration, SyntaxTokenList modifiers)
        {
            var classDeclaration = typeDeclaration as ClassDeclarationSyntax;

            if (classDeclaration != null)
            {
                return(classDeclaration.WithModifiers(modifiers));
            }

            var structDeclaration = typeDeclaration as StructDeclarationSyntax;

            if (structDeclaration != null)
            {
                return(structDeclaration.WithModifiers(modifiers));
            }

            var interfaceDeclaration = typeDeclaration as InterfaceDeclarationSyntax;

            if (interfaceDeclaration != null)
            {
                return(interfaceDeclaration.WithModifiers(modifiers));
            }

            var enumDeclaration = typeDeclaration as EnumDeclarationSyntax;

            if (enumDeclaration != null)
            {
                return(enumDeclaration.WithModifiers(modifiers));
            }

            return(typeDeclaration);
        }
        protected Ust ConvertBaseTypeDeclaration(
            BaseTypeDeclarationSyntax node,
            TypeTypeLiteral typeTypeToken,
            IEnumerable <EntityDeclaration> typeMembers)
        {
            var nameLiteral = ConvertId(node.Identifier);
            var modifiers   = node.Modifiers.Select(ConvertModifier).ToList();
            var baseTypes   = node.BaseList?.Types.Select(t =>
            {
                var name = t.Type is IdentifierNameSyntax id ? id.Identifier.ValueText : t.ToString();
                return(new TypeToken(name, t.GetTextSpan()));
            }).ToList() ?? new List <TypeToken>();

            var result = new TypeDeclaration(
                typeTypeToken,
                nameLiteral,
                baseTypes,
                typeMembers,
                node.GetTextSpan())
            {
                Modifiers = modifiers,
            };

            return(result);
        }
Exemple #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeData"/> class.
        /// </summary>
        /// <param name="declaration"><see cref="BaseTypeDeclarationSyntax"/> this <see cref="TypeData"/> represents.</param>
        /// <param name="compilation">Parent <see cref="ICompilationData"/> of this <see cref="TypeData"/>.</param>
        /// <param name="symbol"><see cref="INamedTypeSymbol"/> this <see cref="TypeData"/> represents.</param>
        /// <param name="semanticModel"><see cref="SemanticModel"/> of the <paramref name="declaration"/>.</param>
        /// <param name="partialDeclarations">A collection of <see cref="TypeDeclarationSyntax"/> that represent the partial declarations of the target <paramref name="symbol"/>.</param>
        /// <param name="modifiers">A collection of all modifiers applied to the <paramref name="symbol"/>.</param>
        /// <param name="containingTypes">A collection of <see cref="ITypeData"/>s the <paramref name="symbol"/> is contained within.</param>
        /// <param name="containingNamespaces">A collection of <see cref="INamespaceSymbol"/>s the <paramref name="symbol"/> is contained within.</param>
        /// <param name="attributes">A collection of <see cref="AttributeData"/>s representing the <paramref name="symbol"/> attributes.</param>
        protected internal TypeData(
            BaseTypeDeclarationSyntax declaration,
            ICompilationData compilation,
            INamedTypeSymbol symbol,
            SemanticModel semanticModel,
            IEnumerable <BaseTypeDeclarationSyntax>?partialDeclarations = null,
            IEnumerable <SyntaxToken>?modifiers                 = null,
            IEnumerable <ITypeData>?containingTypes             = null,
            IEnumerable <INamespaceSymbol>?containingNamespaces = null,
            IEnumerable <AttributeData>?attributes              = null
            ) : base(
                declaration,
                compilation,
                symbol,
                semanticModel,
                containingTypes,
                containingNamespaces,
                attributes
                )
        {
            _partialDeclarations = partialDeclarations?.OfType <TypeDeclarationSyntax>().ToArray();

            if (modifiers is not null)
            {
                _modifiers = modifiers.ToArray();
            }
        }
Exemple #9
0
            async Task AddPartialTypeDeclarationsAsync(BaseTypeDeclarationSyntax node, CancellationToken cancellationToken)
            {
                await _Bar._SemanticContext.UpdateAsync(cancellationToken);

                var symbol = await _Bar._SemanticContext.GetSymbolAsync(node, cancellationToken);

                if (symbol == null)
                {
                    return;
                }
                var current = node.SyntaxTree;
                int c       = 1;

                foreach (var item in symbol.DeclaringSyntaxReferences)
                {
                    if (item.SyntaxTree == current || String.Equals(item.SyntaxTree.FilePath, current.FilePath, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                    var partial = await item.GetSyntaxAsync(cancellationToken);

                    var i = _Menu.Add(partial, _Bar._SemanticContext);
                    i.Content.Text = System.IO.Path.GetFileName(item.SyntaxTree.FilePath);
                    i.Type         = SymbolItemType.Container;
                    AddMemberDeclarations(partial, true);
                    ++c;
                }
                _PartialCount = c;
            }
Exemple #10
0
 public MyCodeAction(Document document, string title, SyntaxNode root, BaseTypeDeclarationSyntax type)
 {
     this.root     = root;
     this.title    = title;
     this.type     = type;
     this.document = document;
 }
        internal static Accessibility GetEffectiveAccessibility(this DelegateDeclarationSyntax syntax, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            if (syntax == null)
            {
                throw new ArgumentNullException(nameof(syntax));
            }

            if (semanticModel == null)
            {
                throw new ArgumentNullException(nameof(semanticModel));
            }

            Accessibility declaredAccessibility = syntax.GetDeclaredAccessibility(semanticModel, cancellationToken);

            if (declaredAccessibility <= Accessibility.Private)
            {
                return(declaredAccessibility);
            }

            BaseTypeDeclarationSyntax enclosingType = syntax.Parent as BaseTypeDeclarationSyntax;

            if (enclosingType == null)
            {
                return(Accessibility.Internal);
            }

            Accessibility enclosingAccessibility = enclosingType.GetEffectiveAccessibility(semanticModel, cancellationToken);

            return(CombineEffectiveAccessibility(declaredAccessibility, enclosingAccessibility));
        }
        private static bool TypeParameterNamesMatch(BaseTypeDeclarationSyntax baseTypeDeclarationSyntax, TypeSyntax name)
        {
            TypeParameterListSyntax typeParameterList;

            if (baseTypeDeclarationSyntax.IsKind(SyntaxKind.ClassDeclaration))
            {
                typeParameterList = (baseTypeDeclarationSyntax as ClassDeclarationSyntax)?.TypeParameterList;
            }
            else
            {
                typeParameterList = (baseTypeDeclarationSyntax as StructDeclarationSyntax)?.TypeParameterList;
            }

            var genericName = name as GenericNameSyntax;

            if (genericName != null)
            {
                var genericNameArgumentNames = genericName.TypeArgumentList.Arguments.Cast <SimpleNameSyntax>().Select(p => p.Identifier.ToString());
                var classParameterNames      = typeParameterList?.Parameters.Select(p => p.Identifier.ToString()) ?? Enumerable.Empty <string>();
                // Make sure the names match up
                return(genericNameArgumentNames.SequenceEqual(classParameterNames));
            }
            else
            {
                return(typeParameterList == null ||
                       !typeParameterList.Parameters.Any());
            }
        }
        private static void HandleBaseTypeLikeDeclaration(SyntaxNodeAnalysisContext context)
        {
            BaseTypeDeclarationSyntax baseType = context.Node as BaseTypeDeclarationSyntax;

            // baseType can be null here if we are looking at a delegate declaration
            if (baseType != null && baseType.BaseList != null && baseType.BaseList.Types.Any())
            {
                return;
            }

            DocumentationCommentTriviaSyntax documentation = context.Node.GetDocumentationCommentTriviaSyntax();

            XmlNodeSyntax inheritDocElement = documentation?.Content.GetFirstXmlElement(XmlCommentHelper.InheritdocXmlTag);

            if (inheritDocElement == null)
            {
                return;
            }

            if (HasXmlCrefAttribute(inheritDocElement))
            {
                return;
            }

            context.ReportDiagnostic(Diagnostic.Create(Descriptor, inheritDocElement.GetLocation()));
        }
Exemple #14
0
        public static string GetFullContainerName(BaseTypeDeclarationSyntax basetype)
        {
            if (basetype == null)
            {
                throw new ArgumentNullException();
            }
            string ns     = "";
            var    parent = basetype.Parent;

            while (parent != null)
            {
                var parentClassDeclaration = parent as ClassDeclarationSyntax;
                if (parentClassDeclaration != null)
                {
                    ns = $"{parentClassDeclaration.Identifier}.{ns}";
                }
                var namespaceDeclaration = parent as NamespaceDeclarationSyntax;
                if (namespaceDeclaration != null)
                {
                    ns = $"{namespaceDeclaration.Name}.{ns}";
                }
                parent = parent.Parent;
            }

            string className           = $"{ns}{basetype.Identifier}";
            ClassDeclarationSyntax cds = basetype as ClassDeclarationSyntax;

            if (cds != null && cds.TypeParameterList != null)
            {
                className += cds.TypeParameterList.ToString();
            }
            return(className);
        }
Exemple #15
0
            private bool CompareBaseLists(BaseTypeDeclarationSyntax oldType, BaseTypeDeclarationSyntax newType)
            {
                if (oldType.BaseList == null && newType.BaseList == null)
                {
                    return(true);
                }

                if (oldType.BaseList != null && newType.BaseList != null)
                {
                    var oldTypes = oldType.BaseList.Types;
                    var newTypes = newType.BaseList.Types;

                    if (oldTypes.Count != newTypes.Count)
                    {
                        return(false);
                    }

                    for (int i = 0; i < oldTypes.Count; i++)
                    {
                        if (!CompareTypes(oldTypes[i].Type, newTypes[i].Type))
                        {
                            return(false);
                        }
                    }

                    return(true);
                }

                // In this case, one of the base lists is null.
                return(false);
            }
Exemple #16
0
 /// <summary>
 /// Creates the compilation unit for the specified <paramref name="typeDeclarationSyntax"/>.
 /// </summary>
 /// <param name="typeDeclarationSyntax">The <see cref="BaseTypeDeclarationSyntax"/></param>
 /// <returns>The <see cref="CompilationUnitSyntax"/></returns>
 protected virtual CompilationUnitSyntax CreateCompilationUnit(BaseTypeDeclarationSyntax typeDeclarationSyntax)
 {
     return(CompilationUnit()
            .WithUsings(
                List(
                    new UsingDirectiveSyntax[] {
         UsingDirective(IdentifierName("System"))
         .WithUsingKeyword(
             Token(
                 TriviaList(
                     Comment(HEADCOMMENT)),
                 SyntaxKind.UsingKeyword,
                 TriviaList())),
         UsingDirective(
             QualifiedName(
                 QualifiedName(
                     IdentifierName("System"),
                     IdentifierName("Collections")),
                 IdentifierName("Generic")))
     }))
            .WithMembers(
                SingletonList <MemberDeclarationSyntax>(
                    NamespaceDeclaration(
                        IdentifierName(_namespace))
                    .WithMembers(
                        SingletonList <MemberDeclarationSyntax>(typeDeclarationSyntax))))
            .NormalizeWhitespace());
 }
 private Document MoveTypeToFile(BaseTypeDeclarationSyntax typeDeclaration, Document curentDocument)
 {
     var typeName = typeDeclaration.Identifier.Text;
     var fileName = typeName + ".cs";
     var newDocument = MoveTypeToFile(curentDocument, typeDeclaration, fileName);
     return newDocument;
 }
        private static int Compare(BaseTypeDeclarationSyntax x, BaseTypeDeclarationSyntax y)
        {
            int result;

            if (EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
                EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result) &&
                EqualIdentifierName(x.Identifier, y.Identifier, out result))
            {
                if (x.Kind() == SyntaxKind.ClassDeclaration)
                {
                    EqualTypeParameterCount(
                        ((ClassDeclarationSyntax)x).TypeParameterList,
                        ((ClassDeclarationSyntax)y).TypeParameterList,
                        out result);
                }
                else if (x.Kind() == SyntaxKind.StructDeclaration)
                {
                    EqualTypeParameterCount(
                        ((StructDeclarationSyntax)x).TypeParameterList,
                        ((StructDeclarationSyntax)y).TypeParameterList,
                        out result);
                }
                else
                {
                    EqualTypeParameterCount(
                        ((InterfaceDeclarationSyntax)x).TypeParameterList,
                        ((InterfaceDeclarationSyntax)y).TypeParameterList,
                        out result);
                }
            }

            return(result);
        }
Exemple #19
0
        private static void GetBraceTokens(
            BaseTypeDeclarationSyntax typeDeclaration,
            bool hasMembers,
            out SyntaxToken openBrace,
            out SyntaxToken closeBrace)
        {
            openBrace  = EnsureToken(typeDeclaration.OpenBraceToken);
            closeBrace = EnsureToken(typeDeclaration.CloseBraceToken);

            if (!hasMembers)
            {
                // Bug 5711: Crazy special case.  If there are no members, take any trivia that
                // belongs to the end brace and attach it to the opening brace.
                int index         = -1;
                var leadingTrivia = closeBrace.LeadingTrivia;
                for (int i = leadingTrivia.Count - 1; i >= 0; i--)
                {
                    if (!leadingTrivia[i].IsWhitespaceOrEndOfLine())
                    {
                        index = i;
                        break;
                    }
                }

                if (index != -1)
                {
                    openBrace = openBrace.WithTrailingTrivia(
                        openBrace.TrailingTrivia.Concat(closeBrace.LeadingTrivia.Take(index + 1)));
                    closeBrace = closeBrace.WithLeadingTrivia(
                        closeBrace.LeadingTrivia.Skip(index + 1));
                }
            }
        }
Exemple #20
0
        private static bool TryGetChangedName(string identifierName, BaseTypeDeclarationSyntax typeDeclaration, bool isUnderscoreAccepted,
                                              out string suggestion)
        {
            var suggestionPrefix = typeDeclaration is InterfaceDeclarationSyntax ? "I" : string.Empty;
            var namesToCheck     = identifierName.Split(new[] { "_" }, StringSplitOptions.None);

            if (LeadingIShouldBeIgnored(namesToCheck[0], typeDeclaration))
            {
                namesToCheck[0] = namesToCheck[0].Substring(1);
            }

            var suggestedNames = namesToCheck.Select(s => CamelCaseConverter.Convert(s));

            if (isUnderscoreAccepted)
            {
                suggestion = string.Join("_", suggestedNames);
            }
            else
            {
                var concatenated = string.Join(string.Empty, suggestedNames);

                // do a second path, to suggest a real camel case string. A_B_C -> ABC -> Abc
                suggestion = CamelCaseConverter.Convert(concatenated);
            }

            suggestion = suggestionPrefix + suggestion;
            return(identifierName != suggestion);
        }
Exemple #21
0
        private string ParseSummary(BaseTypeDeclarationSyntax node)
        {
            string summary = null;

            var doc = ParseDocumentation(node);

            if (doc["summary"] != null)
            {
                summary = doc["summary"].GetText();
            }

            if (HasModifier(node, "protected"))
            {
                summary = AppendSummary(summary, "This class is protected.");
            }

            var deprecationReason = GetDeprecationReason(node);

            if (deprecationReason != null)
            {
                summary = AppendSummary(summary, deprecationReason);
            }

            return(summary);
        }
            private SyntaxKind?GetExistingPartialVisibility(BaseTypeDeclarationSyntax originalDeclarationSyntax)
            {
                // Getting the SemanticModel is a relatively expensive operation.  Can take a few seconds in
                // projects of significant size.  It is delay created to avoid this in files which already
                // conform to the standards.
                if (_semanticModel == null)
                {
                    _semanticModel = _document.GetSemanticModelAsync(_cancellationToken).Result;
                }

                var symbol = _semanticModel.GetDeclaredSymbol(originalDeclarationSyntax, _cancellationToken);

                if (symbol == null)
                {
                    return(null);
                }

                switch (symbol.DeclaredAccessibility)
                {
                case Accessibility.Friend:
                    return(SyntaxKind.InternalKeyword);

                case Accessibility.Public:
                    return(SyntaxKind.PublicKeyword);

                case Accessibility.Private:
                    return(SyntaxKind.PrivateKeyword);

                case Accessibility.Protected:
                    return(SyntaxKind.ProtectedKeyword);

                default: return(null);
                }
            }
Exemple #23
0
        public static string GetFullName(this BaseTypeDeclarationSyntax token)
        {
            if (token == null)
            {
                return("");
            }

            dynamic node = token;

            if (node == null)
            {
                return(null);
            }

            List <string> parts = new List <string>();

            parts.Add(node.Identifier.Text);
            var parent = node.Parent;

            while (parent != null && parent is BaseTypeDeclarationSyntax)
            {
                parts.Add(parent.Identifier.Text);
                parent = parent.Parent;
            }

            parts.Reverse();
            return(string.Join(".", parts.ToArray()));
        }
 public static AttributeSyntax FindAttribute(this BaseTypeDeclarationSyntax typeDeclaration, SemanticModel model, string typeName)
 {
     return(typeDeclaration.AttributeLists
            .SelectMany(x => x.Attributes)
            .Where(x => model.GetTypeInfo(x).Type?.ToDisplayString() == typeName)
            .FirstOrDefault());
 }
Exemple #25
0
        private static void HandleBaseTypeLikeDeclaration(SyntaxNodeAnalysisContext context)
        {
            BaseTypeDeclarationSyntax baseType = context.Node as BaseTypeDeclarationSyntax;

            // baseType can be null here if we are looking at a delegate declaration
            if (baseType != null && baseType.BaseList != null && baseType.BaseList.Types.Any())
            {
                return;
            }

            DocumentationCommentTriviaSyntax documentation = context.Node.GetDocumentationCommentTriviaSyntax();
            if (documentation == null)
            {
                return;
            }

            Location location;

            if (documentation.Content.GetFirstXmlElement(XmlCommentHelper.IncludeXmlTag) is XmlEmptyElementSyntax includeElement)
            {
                var declaration = context.SemanticModel.GetDeclaredSymbol(baseType, context.CancellationToken);
                if (declaration == null)
                {
                    return;
                }

                var rawDocumentation = declaration.GetDocumentationCommentXml(expandIncludes: true, cancellationToken: context.CancellationToken);
                var completeDocumentation = XElement.Parse(rawDocumentation, LoadOptions.None);

                var inheritDocElement = completeDocumentation.Nodes().OfType<XElement>().FirstOrDefault(element => element.Name == XmlCommentHelper.InheritdocXmlTag);
                if (inheritDocElement == null)
                {
                    return;
                }

                if (HasXmlCrefAttribute(inheritDocElement))
                {
                    return;
                }

                location = includeElement.GetLocation();
            }
            else
            {
                XmlNodeSyntax inheritDocElement = documentation.Content.GetFirstXmlElement(XmlCommentHelper.InheritdocXmlTag);
                if (inheritDocElement == null)
                {
                    return;
                }

                if (HasXmlCrefAttribute(inheritDocElement))
                {
                    return;
                }

                location = inheritDocElement.GetLocation();
            }

            context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
        }
Exemple #26
0
        protected override void EnterClass(BaseTypeDeclarationSyntax node)
        {
            var cls = ParseClass(node);

            if (_currentNamespace.HasClass(cls.Type))
            {
                var existingClass = _currentNamespace.GetClassByType(cls.Type);

                // Some classes in C# exist multiple times with varying amounts of generics
                // We keep the one with the most generics
                if (existingClass.Type.TypeParameters.Count >= cls.Type.TypeParameters.Count)
                {
                    // Add documentation if the existing class has been registered without it and it is available here
                    existingClass.Summary ??= cls.Summary;

                    _currentClass = existingClass;
                    return;
                }
            }

            if (_currentClass != null)
            {
                cls.ParentClass = _currentClass;
                _currentClass.InnerClasses.Add(cls);
            }

            _currentNamespace.RegisterClass(cls);
            _currentClass = cls;
        }
            public void HandleTypeDeclaration(SyntaxNodeAnalysisContext context)
            {
                if (context.GetDocumentationMode() != DocumentationMode.Diagnose)
                {
                    return;
                }

                BaseTypeDeclarationSyntax declaration = (BaseTypeDeclarationSyntax)context.Node;

                if (declaration.Modifiers.Any(SyntaxKind.PartialKeyword))
                {
                    // Handled by SA1601
                    return;
                }

                Accessibility declaredAccessibility  = declaration.GetDeclaredAccessibility(context.SemanticModel, context.CancellationToken);
                Accessibility effectiveAccessibility = declaration.GetEffectiveAccessibility(context.SemanticModel, context.CancellationToken);

                if (this.NeedsComment(declaration.Kind(), declaration.Parent.Kind(), declaredAccessibility, effectiveAccessibility))
                {
                    if (!XmlCommentHelper.HasDocumentation(declaration))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, declaration.Identifier.GetLocation()));
                    }
                }
            }
Exemple #28
0
 public PullUpFieldAction(IDocument document, FieldDeclarationSyntax fieldDeclaration, TypeDeclarationSyntax containingTypeDeclaration, BaseTypeDeclarationSyntax baseTypeDeclaration)
 {
     this.document                  = document;
     this.fieldDeclaration          = fieldDeclaration;
     this.containingTypeDeclaration = containingTypeDeclaration;
     this.baseTypeDeclaration       = baseTypeDeclaration;
 }
Exemple #29
0
        private void AddNestedType(BaseTypeDeclarationSyntax node)
        {
            var blockAdded = false;

            if (node.HasLeadingTrivia)
            {
                var leadingTrivia = node.GetLeadingTrivia();

                if (node.ShouldBeHidden(leadingTrivia))
                {
                    return;
                }

                // inline multiline comment
                AddMultiLineDocumentationComment(leadingTrivia);

                if (node.ShouldBeConvertedToJson(leadingTrivia))
                {
                    string json;
                    if (node.TryGetJsonForSyntaxNode(out json))
                    {
                        var startingLine = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
                        Blocks.Add(new JavaScriptBlock(json, startingLine, ClassDepth, node.Identifier.Text));
                        blockAdded = true;
                    }
                }
            }

            if (!blockAdded)
            {
                Blocks.Add(new CSharpBlock(node, ClassDepth));
            }
        }
            void AddTypeToMemberList(BaseTypeDeclarationSyntax btype)
            {
                if (btype is EnumDeclarationSyntax e)
                {
                    foreach (var member in e.Members)
                    {
                        memberList.Add(member);
                    }
                    return;
                }
                var type = (TypeDeclarationSyntax)btype;

                foreach (var member in type.Members)
                {
                    if (member is FieldDeclarationSyntax)
                    {
                        foreach (var variable in ((FieldDeclarationSyntax)member).Declaration.Variables)
                        {
                            memberList.Add(variable);
                        }
                    }
                    else if (member is EventFieldDeclarationSyntax)
                    {
                        foreach (var variable in ((EventFieldDeclarationSyntax)member).Declaration.Variables)
                        {
                            memberList.Add(variable);
                        }
                    }
                    else
                    {
                        memberList.Add(member);
                    }
                }
            }
Exemple #31
0
 private void ParseTestFixtureClass(BaseTypeDeclarationSyntax classDeclaration)
 {
     if (SyntaxHelper.GetAllBaseTypes(classDeclaration).Any(t => t.ToString() == "IExpectException"))
     {
         HandlerName = ExpectExceptionHandlerMethodName;
     }
 }
            public static void HandleBaseTypeDeclaration(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
            {
                if (context.GetDocumentationMode() == DocumentationMode.None)
                {
                    return;
                }

                BaseTypeDeclarationSyntax declaration = (BaseTypeDeclarationSyntax)context.Node;

                if (!declaration.Modifiers.Any(SyntaxKind.PartialKeyword))
                {
                    return;
                }

                Accessibility declaredAccessibility  = declaration.GetDeclaredAccessibility(context.SemanticModel, context.CancellationToken);
                Accessibility effectiveAccessibility = declaration.GetEffectiveAccessibility(context.SemanticModel, context.CancellationToken);

                if (SA1600ElementsMustBeDocumented.NeedsComment(settings.DocumentationRules, declaration.Kind(), declaration.Parent.Kind(), declaredAccessibility, effectiveAccessibility))
                {
                    if (!XmlCommentHelper.HasDocumentation(declaration))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, declaration.Identifier.GetLocation()));
                    }
                }
            }
			public MyCodeAction (Document document, string title, SyntaxNode root, BaseTypeDeclarationSyntax type)
			{
				this.root = root;
				this.title = title;
				this.type = type;
				this.document = document;

			}
 private async Task<Solution> MoveTypeToFile(Document document, BaseTypeDeclarationSyntax typeDeclaration, CancellationToken c)
 {
     try
     {
         var curentDocument = await DeleteDeclarationFromDocument(typeDeclaration, document);
         var newDocument = MoveTypeToFile(typeDeclaration, curentDocument);
         return newDocument.Project.Solution;
         //dte.ActiveDocument.ProjectItem. -> new_item.Open();
     }
     catch (Exception e)
     {
         LogException(e);
         return document.Project.Solution;
     }
 }
 public static TypeNameText From(BaseTypeDeclarationSyntax syntax)
 {
     var identifier = syntax.Identifier.Text;
     var typeArgs = string.Empty;
     var typeDeclaration = syntax as TypeDeclarationSyntax;
     if (typeDeclaration != null && typeDeclaration.TypeParameterList != null)
     {
         var count = typeDeclaration.TypeParameterList.Parameters.Count;
         identifier = $"\"{identifier}`{count}\"";
         typeArgs = "<" + string.Join(",", typeDeclaration.TypeParameterList.Parameters) + ">";
     }
     return new TypeNameText
     {
         Identifier = identifier,
         TypeArguments = typeArgs
     };
 }
        private Document MoveTypeToFile(Document document, BaseTypeDeclarationSyntax typeDeclaration, string newFileName)
        {
            var nameSpaces = typeDeclaration.GetAncestorsOrThis<NamespaceDeclarationSyntax>().Reverse();
            var root = typeDeclaration.GetAncestorOrThis<CompilationUnitSyntax>();


            //agregate -> create namespaces from bottom to top
            var rootNameSpace = nameSpaces.Aggregate(typeDeclaration, (MemberDeclarationSyntax curentBody, NamespaceDeclarationSyntax curentNamespace) =>
            {
                var newBody = new SyntaxList<MemberDeclarationSyntax>().Add(curentBody);
                return SyntaxFactory.NamespaceDeclaration(curentNamespace.Name, curentNamespace.Externs, curentNamespace.Usings, newBody)
                                    .WithLeadingTrivia(curentNamespace.GetLeadingTrivia())
                                    .WithTrailingTrivia(curentNamespace.GetTrailingTrivia());
            });

            var newRoot = SyntaxFactory.CompilationUnit(root.Externs, root.Usings, root.AttributeLists, new SyntaxList<MemberDeclarationSyntax>().Add(rootNameSpace));

            var newDoc = document.Project.AddDocument(newFileName, newRoot, document.Folders);
            return newDoc;
        }
        private async Task<Solution> MoveClassIntoNewFileAsync(Document document, BaseTypeDeclarationSyntax typeDecl, CancellationToken cancellationToken)
        {
            var identifierToken = typeDecl.Identifier;

            // symbol representing the type
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
            var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);

            // remove type from current files
            var currentSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken);
            var currentRoot = await currentSyntaxTree.GetRootAsync(cancellationToken);
            var replacedRoot = currentRoot.RemoveNode(typeDecl, SyntaxRemoveOptions.KeepNoTrivia);

            document = document.WithSyntaxRoot(replacedRoot);

            // TODO: use Simplifier instead.
            document = await RemoveUnusedImportDirectivesAsync(document, cancellationToken);

            // create new tree for a new file
            // we drag all the usings because we don't know which are needed
            // and there is no easy way to find out which
            var currentUsings = currentRoot.DescendantNodesAndSelf().Where(s => s is UsingDirectiveSyntax);

            var newFileTree = SyntaxFactory.CompilationUnit()
                .WithUsings(SyntaxFactory.List<UsingDirectiveSyntax>(currentUsings.Select(i => ((UsingDirectiveSyntax)i))))
                .WithMembers(
                            SyntaxFactory.SingletonList<MemberDeclarationSyntax>(
                                SyntaxFactory.NamespaceDeclaration(
                                    SyntaxFactory.IdentifierName(typeSymbol.ContainingNamespace.ToString()))
                .WithMembers(SyntaxFactory.SingletonList<MemberDeclarationSyntax>(typeDecl))))
                .WithoutLeadingTrivia()
                .NormalizeWhitespace();

            //move to new File
            //TODO: handle name conflicts
            var newDocument = document.Project.AddDocument(string.Format("{0}.cs", identifierToken.Text), SourceText.From(newFileTree.ToFullString()), document.Folders);

            newDocument = await RemoveUnusedImportDirectivesAsync(newDocument, cancellationToken);

            return newDocument.Project.Solution;
        }
        private static bool TypeParameterNamesMatch(BaseTypeDeclarationSyntax baseTypeDeclarationSyntax, TypeSyntax name)
        {
            TypeParameterListSyntax typeParameterList;
            if (baseTypeDeclarationSyntax.IsKind(SyntaxKind.ClassDeclaration))
            {
                typeParameterList = (baseTypeDeclarationSyntax as ClassDeclarationSyntax)?.TypeParameterList;
            }
            else
            {
                typeParameterList = (baseTypeDeclarationSyntax as StructDeclarationSyntax)?.TypeParameterList;
            }

            var genericName = name as GenericNameSyntax;
            if (genericName != null)
            {
                var genericNameArgumentNames = genericName.TypeArgumentList.Arguments.Cast<SimpleNameSyntax>().Select(p => p.Identifier.ToString());
                var classParameterNames = typeParameterList?.Parameters.Select(p => p.Identifier.ToString()) ?? Enumerable.Empty<string>();

                // Make sure the names match up
                return genericNameArgumentNames.SequenceEqual(classParameterNames);
            }
            else
            {
                return typeParameterList == null
                    || !typeParameterList.Parameters.Any();
            }
        }
        private static void EnsureAndGetBraceTokens(
            BaseTypeDeclarationSyntax typeDeclaration,
            bool hasMembers,
            out SyntaxToken openBrace,
            out SyntaxToken closeBrace)
        {
            openBrace = EnsureToken(typeDeclaration.OpenBraceToken);
            closeBrace = EnsureToken(typeDeclaration.CloseBraceToken, appendNewLineIfMissing: true);

            if (!hasMembers)
            {
                // Bug 539673: If there are no members, take any trivia that
                // belongs to the end brace and attach it to the opening brace.
                int index = -1;
                var leadingTrivia = closeBrace.LeadingTrivia;
                for (int i = leadingTrivia.Count - 1; i >= 0; i--)
                {
                    if (!leadingTrivia[i].IsWhitespaceOrEndOfLine())
                    {
                        index = i;
                        break;
                    }
                }

                if (index != -1)
                {
                    openBrace = openBrace.WithTrailingTrivia(
                        openBrace.TrailingTrivia.Concat(closeBrace.LeadingTrivia.Take(index + 1)));
                    closeBrace = closeBrace.WithLeadingTrivia(
                        closeBrace.LeadingTrivia.Skip(index + 1));
                }
            }
        }
Exemple #40
0
        public JsBlockStatement CreateDefaultConstructor(BaseTypeDeclarationSyntax type)
        {
            var classType = transformer.model.GetDeclaredSymbol(type);

            var fullTypeName = type.GetFullName();
            var constructorBlock = new JsBlockStatement();

            if (fullTypeName != "System.Object")
            {
                constructorBlock.Express(InvokeParameterlessBaseClassConstructor(classType.BaseType));
            }

            if (type is ClassDeclarationSyntax)
            {
                constructorBlock.Aggregate(InitializeInstanceFields((ClassDeclarationSyntax)type));
            }

            var block = new JsBlockStatement();
            var constructorName = classType.GetDefaultConstructorName();
            block.Add(StoreInPrototype(constructorName, Js.Reference(SpecialNames.DefineConstructor).Invoke(
                Js.Reference(SpecialNames.TypeInitializerTypeFunction), 
                Js.Function().Body(constructorBlock))));

            return block;            
        }
        private string GetQualifiedTypeName(BaseTypeDeclarationSyntax cls)
        {
            var qname = cls.Identifier.ToString();

            foreach (var a in cls.Ancestors())
            {
                if(a is NamespaceDeclarationSyntax)
                {
                    qname = a.ChildNodes().First().ToString() + "." + qname;
                }
                else if(a is ClassDeclarationSyntax)
                {
                    qname = ((ClassDeclarationSyntax)a).Identifier + "+" + qname;
                }
            }

            return qname;
        }
Exemple #42
0
        internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl)
        {
            Debug.Assert(typeDecl != null);

            return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken);
        }
			void AddTypeToMemberList (BaseTypeDeclarationSyntax btype)
			{
				var e = btype as EnumDeclarationSyntax;
				if (e !=null){
					foreach (var member in e.Members) {
						memberList.Add (member);
					}
					return;
				}
				var type = btype as TypeDeclarationSyntax;
				foreach (var member in type.Members) {
					if (member is FieldDeclarationSyntax) {
						foreach (var variable in ((FieldDeclarationSyntax)member).Declaration.Variables)
							memberList.Add (variable);
					} else if (member is EventFieldDeclarationSyntax) {
						foreach (var variable in ((EventFieldDeclarationSyntax)member).Declaration.Variables)
							memberList.Add (variable);
					} else {
						memberList.Add (member);
					}
				}
			}
 private static bool IsNestedType(BaseTypeDeclarationSyntax typeDeclaration)
 {
     return typeDeclaration?.Parent is BaseTypeDeclarationSyntax;
 }
Exemple #45
0
 private CSharpSyntaxContext(
     Workspace workspace,
     SemanticModel semanticModel,
     int position,
     SyntaxToken leftToken,
     SyntaxToken targetToken,
     TypeDeclarationSyntax containingTypeDeclaration,
     BaseTypeDeclarationSyntax containingTypeOrEnumDeclaration,
     bool isInNonUserCode,
     bool isPreProcessorDirectiveContext,
     bool isPreProcessorKeywordContext,
     bool isPreProcessorExpressionContext,
     bool isTypeContext,
     bool isNamespaceContext,
     bool isNamespaceDeclarationNameContext,
     bool isStatementContext,
     bool isGlobalStatementContext,
     bool isAnyExpressionContext,
     bool isNonAttributeExpressionContext,
     bool isConstantExpressionContext,
     bool isAttributeNameContext,
     bool isEnumTypeMemberAccessContext,
     bool isNameOfContext,
     bool isInQuery,
     bool isInImportsDirective,
     bool isLabelContext,
     bool isTypeArgumentOfConstraintContext,
     bool isRightOfDotOrArrowOrColonColon,
     bool isIsOrAsContext,
     bool isObjectCreationTypeContext,
     bool isDefiniteCastTypeContext,
     bool isGenericTypeArgumentContext,
     bool isEnumBaseListContext,
     bool isIsOrAsTypeContext,
     bool isLocalVariableDeclarationContext,
     bool isDeclarationExpressionContext,
     bool isFixedVariableDeclarationContext,
     bool isParameterTypeContext,
     bool isPossibleLambdaOrAnonymousMethodParameterTypeContext,
     bool isImplicitOrExplicitOperatorTypeContext,
     bool isPrimaryFunctionExpressionContext,
     bool isDelegateReturnTypeContext,
     bool isTypeOfExpressionContext,
     ISet<SyntaxKind> precedingModifiers,
     bool isInstanceContext,
     bool isCrefContext,
     bool isCatchFilterContext,
     bool isDestructorTypeContext)
     : base(workspace, semanticModel, position, leftToken, targetToken,
            isTypeContext, isNamespaceContext, isNamespaceDeclarationNameContext,
            isPreProcessorDirectiveContext,
            isRightOfDotOrArrowOrColonColon, isStatementContext, isAnyExpressionContext,
            isAttributeNameContext, isEnumTypeMemberAccessContext, isNameOfContext,
            isInQuery, isInImportsDirective)
 {
     this.ContainingTypeDeclaration = containingTypeDeclaration;
     this.ContainingTypeOrEnumDeclaration = containingTypeOrEnumDeclaration;
     this.IsInNonUserCode = isInNonUserCode;
     this.IsPreProcessorKeywordContext = isPreProcessorKeywordContext;
     this.IsPreProcessorExpressionContext = isPreProcessorExpressionContext;
     this.IsGlobalStatementContext = isGlobalStatementContext;
     this.IsNonAttributeExpressionContext = isNonAttributeExpressionContext;
     this.IsConstantExpressionContext = isConstantExpressionContext;
     this.IsLabelContext = isLabelContext;
     this.IsTypeArgumentOfConstraintContext = isTypeArgumentOfConstraintContext;
     this.IsIsOrAsContext = isIsOrAsContext;
     this.IsObjectCreationTypeContext = isObjectCreationTypeContext;
     this.IsDefiniteCastTypeContext = isDefiniteCastTypeContext;
     this.IsGenericTypeArgumentContext = isGenericTypeArgumentContext;
     this.IsEnumBaseListContext = isEnumBaseListContext;
     this.IsIsOrAsTypeContext = isIsOrAsTypeContext;
     this.IsLocalVariableDeclarationContext = isLocalVariableDeclarationContext;
     this.IsDeclarationExpressionContext = isDeclarationExpressionContext;
     this.IsFixedVariableDeclarationContext = isFixedVariableDeclarationContext;
     this.IsParameterTypeContext = isParameterTypeContext;
     this.IsPossibleLambdaOrAnonymousMethodParameterTypeContext = isPossibleLambdaOrAnonymousMethodParameterTypeContext;
     this.IsImplicitOrExplicitOperatorTypeContext = isImplicitOrExplicitOperatorTypeContext;
     this.IsPrimaryFunctionExpressionContext = isPrimaryFunctionExpressionContext;
     this.IsDelegateReturnTypeContext = isDelegateReturnTypeContext;
     this.IsTypeOfExpressionContext = isTypeOfExpressionContext;
     this.PrecedingModifiers = precedingModifiers;
     this.IsInstanceContext = isInstanceContext;
     this.IsCrefContext = isCrefContext;
     this.IsCatchFilterContext = isCatchFilterContext;
     this.IsDestructorTypeContext = isDestructorTypeContext;
 }
        public string GetFullRepositoryModelName(BaseTypeDeclarationSyntax codeclass)
        {
            var semanticModel = _repositoryModelsCompilation.GetSemanticModel(codeclass.SyntaxTree);

            var symbol = semanticModel.GetDeclaredSymbol(codeclass);

            return symbol.ContainingNamespace + "." + codeclass.Identifier.Text;
        }
            private VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
            {
                int startPosition;

                switch (part)
                {
                    case EnvDTE.vsCMPart.vsCMPartName:
                    case EnvDTE.vsCMPart.vsCMPartAttributes:
                    case EnvDTE.vsCMPart.vsCMPartWhole:
                    case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
                    case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
                        throw Exceptions.ThrowENotImpl();

                    case EnvDTE.vsCMPart.vsCMPartHeader:
                        startPosition = node.GetFirstTokenAfterAttributes().SpanStart;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
                        if (node.AttributeLists.Count == 0)
                        {
                            throw Exceptions.ThrowEFail();
                        }

                        goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;

                    case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
                        startPosition = node.GetFirstToken().SpanStart;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartNavigate:
                        startPosition = node.Identifier.SpanStart;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartBody:
                        if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing)
                        {
                            throw Exceptions.ThrowEFail();
                        }

                        return GetBodyStartPoint(text, node.OpenBraceToken);

                    default:
                        throw Exceptions.ThrowEInvalidArg();
                }

                return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
            }
        /// <summary>
        /// Given a type declaration, get the corresponding type symbol.
        /// </summary>
        /// <param name="declarationSyntax">The syntax node that declares a type.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The type symbol that was declared.</returns>
        /// <remarks>
        /// NOTE:   We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol.
        /// </remarks>
        public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
        {
            CheckSyntaxNode(declarationSyntax);

            return GetDeclaredType(declarationSyntax);
        }
 public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
 {
     // Can't define type inside a member.
     return null;
 }
            private VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
            {
                int endPosition;

                switch (part)
                {
                    case EnvDTE.vsCMPart.vsCMPartName:
                    case EnvDTE.vsCMPart.vsCMPartAttributes:
                    case EnvDTE.vsCMPart.vsCMPartHeader:
                    case EnvDTE.vsCMPart.vsCMPartWhole:
                    case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
                    case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
                        throw Exceptions.ThrowENotImpl();

                    case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
                        if (node.AttributeLists.Count == 0)
                        {
                            throw Exceptions.ThrowEFail();
                        }

                        endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
                        endPosition = node.Span.End;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartNavigate:
                        endPosition = node.Identifier.Span.End;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartBody:
                        return GetBodyEndPoint(text, node.CloseBraceToken);

                    default:
                        throw Exceptions.ThrowEInvalidArg();
                }

                return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
            }
 public BaseTypeDeclarationTranslation(BaseTypeDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
     Modifiers = syntax.Modifiers.Get(this);
     AttributeList = syntax.AttributeLists.Get<AttributeListSyntax, AttributeListTranslation>(this);
 }
            private bool CompareBaseLists(BaseTypeDeclarationSyntax oldType, BaseTypeDeclarationSyntax newType)
            {
                if (oldType.BaseList == null && newType.BaseList == null)
                {
                    return true;
                }

                if (oldType.BaseList != null && newType.BaseList != null)
                {
                    var oldTypes = oldType.BaseList.Types;
                    var newTypes = newType.BaseList.Types;

                    if (oldTypes.Count != newTypes.Count)
                    {
                        return false;
                    }

                    for (int i = 0; i < oldTypes.Count; i++)
                    {
                        if (!CompareTypes(oldTypes[i].Type, newTypes[i].Type))
                        {
                            return false;
                        }
                    }

                    return true;
                }

                // In this case, one of the base lists is null.
                return false;
            }
        public string GetTypeNamespace(BaseTypeDeclarationSyntax codeclass)
        {
            var semanticModel = _fullCompilation.GetSemanticModel(codeclass.SyntaxTree);

            var symbol = semanticModel.GetDeclaredSymbol(codeclass);

            return symbol.ContainingNamespace.ToString();
        }
Exemple #54
0
 /// <summary>
 /// Given a type declaration, get the corresponding type symbol.
 /// </summary>
 /// <param name="declarationSyntax">The syntax node that declares a type.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The type symbol that was declared.</returns>
 /// <remarks>
 /// NOTE:   We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol.
 /// </remarks>
 public abstract INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken));
        private NamedTypeSymbol GetDeclaredType(BaseTypeDeclarationSyntax declarationSyntax)
        {
            Debug.Assert(declarationSyntax != null);

            var name = declarationSyntax.Identifier.ValueText;
            return GetDeclaredNamedType(declarationSyntax, name);
        }
			Document CreateNewFile (BaseTypeDeclarationSyntax type, string correctFileName)
			{
				var doc = IdeApp.Workbench.ActiveDocument;
				var content = doc.Editor.Text;

				var types = new List<BaseTypeDeclarationSyntax> (
					root
					.DescendantNodesAndSelf (n => !(n is BaseTypeDeclarationSyntax))
					.OfType<BaseTypeDeclarationSyntax> ()
					.Where (t => t.SpanStart != type.SpanStart)
				);
				types.Sort ((x, y) => y.SpanStart.CompareTo (x.SpanStart));

				foreach (var removeType in types) {
					var bounds = CalcTypeBounds (removeType);
					content = content.Remove (bounds.Offset, bounds.Length);
				}

				if (doc.HasProject) {
					string header = StandardHeaderService.GetHeader (doc.Project, correctFileName, true);
					if (!string.IsNullOrEmpty (header))
						content = header + doc.Editor.GetEolMarker () + StripHeader (content);
				}
				content = StripDoubleBlankLines (content);

				File.WriteAllText (correctFileName, content);
				if (doc.HasProject) {
					doc.Project.AddFile (correctFileName);
					IdeApp.ProjectOperations.SaveAsync (doc.Project);
				}

				doc.Editor.RemoveText (CalcTypeBounds (type));

				return document;
			}
 private SyntaxNode RegisterBaseTypeDeclarationCodeFix(SyntaxNode syntaxRoot, BaseTypeDeclarationSyntax node, IndentationOptions indentationOptions)
 {
     return this.ReformatElement(syntaxRoot, node, node.OpenBraceToken, node.CloseBraceToken, indentationOptions);
 }
			ISegment CalcTypeBounds (BaseTypeDeclarationSyntax type)
			{
				int start = type.Span.Start;
				int end = type.Span.End;
				foreach (var trivia in type.GetLeadingTrivia ()) {
					if (trivia.Kind () == SyntaxKind.SingleLineDocumentationCommentTrivia) {
						start = trivia.FullSpan.Start;
					}
				}

				return TextSegment.FromBounds (start, end);
			}
        private static bool BaseTypeDeclarationContainsPosition(BaseTypeDeclarationSyntax declaration, int position)
        {
            if (position <= declaration.OpenBraceToken.SpanStart)
            {
                return false;
            }

            if (declaration.CloseBraceToken.IsMissing)
            {
                return true;
            }

            return position <= declaration.CloseBraceToken.SpanStart;
        }
		internal static string GetCorrectFileName (Document document, BaseTypeDeclarationSyntax type)
		{
			if (type == null)
				return document.FilePath;
			return Path.Combine (Path.GetDirectoryName (document.FilePath), type.Identifier + Path.GetExtension (document.FilePath));
		}