Esempio n. 1
0
        private static async Task <SyntaxNode> ReplaceMemberCall(CodeFixContext context, SyntaxNode root)
        {
            SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken);

            Diagnostic diagnostic = context.Diagnostics.Where(x => x.Id == DateTimeOffsetUsageAnalyzer.DiagnosticId).FirstOrDefault();

            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;

            SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan);
            MemberAccessExpressionSyntax memberAccess = node.DescendantNodesAndSelf(x => !(x is MemberAccessExpressionSyntax))
                                                        .OfType <MemberAccessExpressionSyntax>()
                                                        .First();

            string           propertyName = memberAccess.Name.ToString();
            SyntaxTriviaList trivia       = node.GetTrailingTrivia();

            MemberAccessExpressionSyntax expression = SyntaxFactory.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                SyntaxFactory.MemberAccessExpression(
                    SyntaxKind.SimpleMemberAccessExpression,
                    SyntaxFactory.MemberAccessExpression(
                        SyntaxKind.SimpleMemberAccessExpression,
                        SyntaxFactory.IdentifierName("Tocsoft"),
                        SyntaxFactory.IdentifierName("DateTimeAbstractions")),
                    SyntaxFactory.IdentifierName("ClockOffset"))
                .WithAdditionalAnnotations(Simplifier.Annotation),
                SyntaxFactory.IdentifierName(propertyName)).WithTrailingTrivia(trivia);

            root = root.ReplaceNode(memberAccess, expression);
            return(root);
        }
        public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            Document document = context.Document;

            Microsoft.CodeAnalysis.Text.TextSpan textSpan = context.Span;
            CancellationToken cancellationToken           = context.CancellationToken;

            CompilationUnitSyntax root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false) as CompilationUnitSyntax;

            SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            // if length is 0 then no particular range is selected, so pick the first enclosing member
            if (textSpan.Length == 0)
            {
                MemberDeclarationSyntax decl = root.FindToken(textSpan.Start).Parent.AncestorsAndSelf().OfType <MemberDeclarationSyntax>().FirstOrDefault();
                if (decl != null)
                {
                    textSpan = decl.FullSpan;
                }
            }

            IEnumerable <ExpandablePropertyInfo> properties = ExpansionChecker.GetExpandableProperties(textSpan, root, model);

            if (properties.Any())
            {
                CodeAction action = CodeAction.Create(
                    "Apply INotifyPropertyChanged pattern",
                    c => ImplementNotifyPropertyChangedAsync(document, root, model, properties, c),
                    equivalenceKey: nameof(ImplementNotifyPropertyChangedCodeRefactoringProvider));

                context.RegisterRefactoring(action);
            }
        }
        public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            Document document = context.Document;

            Microsoft.CodeAnalysis.Text.TextSpan textSpan = context.Span;
            CancellationToken cancellationToken           = context.CancellationToken;

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxToken token = root.FindToken(textSpan.Start);

            // Only trigger if the text span is within the 'if' keyword token of an if-else statement.

            if (token.Kind() != SyntaxKind.IfKeyword ||
                !token.Span.IntersectsWith(textSpan.Start) ||
                !token.Span.IntersectsWith(textSpan.End))
            {
                return;
            }

            if (!(token.Parent is IfStatementSyntax ifStatement) || ifStatement.Else == null)
            {
                return;
            }

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (ReturnConditionalAnalyzer.TryGetNewReturnStatement(ifStatement, semanticModel, out ReturnStatementSyntax returnStatement))
            {
                ConvertToConditionalCodeAction action =
                    new ConvertToConditionalCodeAction("Convert to conditional expression",
                                                       (c) => Task.FromResult(ConvertToConditional(document, semanticModel, ifStatement, returnStatement, c)));
                context.RegisterRefactoring(action);
            }
        }
Esempio n. 4
0
        public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            Document document = context.Document;

            Microsoft.CodeAnalysis.Text.TextSpan textSpan = context.Span;
            CancellationToken cancellationToken           = context.CancellationToken;

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxToken token = root.FindToken(textSpan.Start);

            if (token.Parent == null)
            {
                return;
            }

            PropertyDeclarationSyntax propertyDeclaration = token.Parent.FirstAncestorOrSelf <PropertyDeclarationSyntax>();

            // Refactor only properties with both a getter and a setter.
            if (propertyDeclaration == null ||
                !HasBothAccessors(propertyDeclaration) ||
                !propertyDeclaration.Identifier.Span.IntersectsWith(textSpan.Start))
            {
                return;
            }

            context.RegisterRefactoring(
                new ConvertToAutoPropertyCodeAction("Convert to auto property",
                                                    (c) => ConvertToAutoPropertyAsync(document, propertyDeclaration, c)));
        }
        private static void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            ISymbol namedTypeSymbol = context.Symbol;

            if (namedTypeSymbol.GetAttributes().Any())
            {
                IDictionary <int, AttributeData> lineDictionary = new Dictionary <int, AttributeData>();
                foreach (AttributeData attribute in namedTypeSymbol.GetAttributes())
                {
                    SyntaxReference applicationSyntaxReference    = attribute.ApplicationSyntaxReference;
                    Microsoft.CodeAnalysis.Text.TextSpan textSpan = applicationSyntaxReference.Span;
                    SyntaxTree           syntaxTree = applicationSyntaxReference.SyntaxTree;
                    FileLinePositionSpan lineSpan   = syntaxTree.GetLineSpan(textSpan);

                    IEnumerable <int> symbolLineNumbers = namedTypeSymbol.Locations
                                                          .Where(x => x.GetLineSpan().Path == lineSpan.Path)
                                                          .Select(x => x.GetLineSpan().StartLinePosition.Line);

                    int attributeLineNo = lineSpan.StartLinePosition.Line;
                    if (lineDictionary.ContainsKey(attributeLineNo) || symbolLineNumbers.Contains(attributeLineNo))
                    {
                        Location   location   = syntaxTree.GetLocation(textSpan);
                        Diagnostic diagnostic = Diagnostic.Create(_Rule, location, attribute.AttributeClass.Name);

                        context.ReportDiagnostic(diagnostic);
                    }
                    else
                    {
                        lineDictionary.Add(attributeLineNo, attribute);
                    }
                }
            }
        }
Esempio n. 6
0
        private static void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            ISymbol namedTypeSymbol = context.Symbol;

            if (namedTypeSymbol.GetAttributes().Any())
            {
                IDictionary <int, AttributeData> lineDict = new Dictionary <int, AttributeData>();
                foreach (AttributeData attribute in namedTypeSymbol.GetAttributes())
                {
                    SyntaxReference applicationSyntaxReference    = attribute.ApplicationSyntaxReference;
                    Microsoft.CodeAnalysis.Text.TextSpan textspan = applicationSyntaxReference.Span;
                    SyntaxTree           syntaxTree = applicationSyntaxReference.SyntaxTree;
                    FileLinePositionSpan linespan   = syntaxTree.GetLineSpan(textspan);

                    int lineNo = linespan.StartLinePosition.Line;
                    if (lineDict.ContainsKey(lineNo))
                    {
                        Location   location   = syntaxTree.GetLocation(textspan);
                        Diagnostic diagnostic = Diagnostic.Create(_Rule, location, attribute.AttributeClass.Name);

                        context.ReportDiagnostic(diagnostic);
                    }
                    else
                    {
                        lineDict.Add(lineNo, attribute);
                    }
                }
            }
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            Diagnostic diagnostic = context.Diagnostics.First();

            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;

            // Find the type declaration identified by the diagnostic.
            SyntaxToken declaration = root.FindToken(diagnosticSpan.Start);

            // Find the enclosing AttributeList
            SyntaxNode attributeList = declaration.Parent;

            while (attributeList.Kind() != SyntaxKind.AttributeList)
            {
                attributeList = attributeList.Parent;
            }

            // Get the class, method or property adjacent to the AttributeList
            SyntaxNode parentDeclaration = attributeList.Parent;

            // Register a code action that will invoke the fix.
            context.RegisterCodeFix(
                CodeAction.Create(
                    title: Title,
                    createChangedDocument: c => PutOnSeparateLine(context.Document, parentDeclaration, c),
                    equivalenceKey: Title),
                diagnostic);
        }
Esempio n. 8
0
        protected void InsertCodeSnippet(string shortcut, TextSpan span)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            EnsureDocumentActivated();
            var vsSpan = NavigateToSource(span);

            WpfTextView.TextBuffer.Replace(vsSpan, shortcut);
            DTE.ExecuteCommand(VsCommands.Edit.InsertTab, string.Empty);
        }
Esempio n. 9
0
 public override void VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node)
 {
     if (_buildingSpans)
     {
         var span = new Microsoft.CodeAnalysis.Text.TextSpan(_activeSpanStart, node.Span.End - _activeSpanStart);
         _rhinoSdkSpans.Add(span);
     }
     base.VisitEndIfDirectiveTrivia(node);
 }
Esempio n. 10
0
        public static Span ToSpan(this Microsoft.CodeAnalysis.Text.TextSpan span)
        {
            if (span == null)
            {
                return(Create.Span(1, 1));
            }

            return(Create.Span(span.Start, span.Length));
        }
Esempio n. 11
0
        protected SnapshotSpan NavigateToSource(TextSpan span)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var          textView = WpfTextView;
            SnapshotSpan result   = span.ToSnapshotSpan(textView.TextBuffer.CurrentSnapshot);

            NavigateToSource(textView, result);
            EnsureExpanded(textView, result);
            return(result);
        }
Esempio n. 12
0
 bool InSpans(Microsoft.CodeAnalysis.Text.TextSpan span)
 {
     for (int i = 0; i < _rhinoSdkSpans.Count; i++)
     {
         if (_rhinoSdkSpans[i].IntersectsWith(span))
         {
             return(true);
         }
     }
     return(false);
 }
Esempio n. 13
0
        private bool RefreshSelectionChanged(TextSpan selectionSpan)
        {
            if (IsBusy)
            {
                return(false);
            }

            var codeMapper = CodeMapper;

            return(codeMapper != null && codeMapper.Document == Document && codeMapper.RefreshSelectionChanged(selectionSpan));
        }
Esempio n. 14
0
        public static LineCounts Visit(SyntaxToken identifier, SyntaxNode body)
        {
            var start = identifier.GetLocation().SourceSpan.Start;
            var end   = body.GetLocation().SourceSpan.End - 1;

            var textSpan = new Microsoft.CodeAnalysis.Text.TextSpan(start, end - start);

            var text = body.SyntaxTree.GetText().GetSubText(textSpan) + "\r\n";

            return(LineCounter.ComputeLineCounts(text));
        }
        private bool TryGetNode(SyntaxNode root, Microsoft.CodeAnalysis.Text.TextSpan span, out SyntaxNode node)
        {
            node = null;
            var ancestors = root.FindToken(span.Start).GetAncestors <SyntaxNode>();

            if (!ancestors.Any())
            {
                return(false);
            }

            node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);
            return(node != null);
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken);

            Diagnostic diagnostic = context.Diagnostics.First();

            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;

            // Find the local declaration identified by the diagnostic.
            LocalDeclarationStatementSyntax declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <LocalDeclarationStatementSyntax>().First();

            // Register a code action that will invoke the fix.
            context.RegisterCodeFix(CodeAction.Create("Make constant", c => MakeConstAsync(context.Document, declaration, c), equivalenceKey: diagnostic.Location.ToString()), diagnostic);
        }
Esempio n. 17
0
        /// <summary>
        /// Registers code fixes async.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>A Task.</returns>
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            Diagnostic diagnostic = context.Diagnostics.First();

            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;

            MethodDeclarationSyntax declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <MethodDeclarationSyntax>().First();

            context.RegisterCodeFix(
                CodeAction.Create(
                    title: title,
                    createChangedDocument: c => this.AddDocumentationHeaderAsync(context.Document, root, declaration, c),
                    equivalenceKey: title),
                diagnostic);
        }
Esempio n. 18
0
            public static List <Code> CodesFromDocumentation(Syntax.DocumentationCommentTriviaSyntax documentation)
            {
                var result = new List <Code>();

                foreach (var element in documentation.DescendantNodes().OfType <Syntax.XmlElementSyntax>())
                {
                    bool isDoctest = false;
                    foreach (Syntax.XmlAttributeSyntax attr in element.StartTag.Attributes)
                    {
                        if (attr.Name.ToString().ToLowerInvariant() == "doctest")
                        {
                            int valueStart = attr.StartQuoteToken.Span.End;
                            int valueEnd   = attr.EndQuoteToken.Span.Start;

                            TextSpan valueSpan = new TextSpan(valueStart, valueEnd - valueStart);

                            string value = attr.SyntaxTree
                                           .GetText()
                                           .GetSubText(valueSpan)
                                           .ToString();

                            isDoctest = value.ToLowerInvariant() == "true";
                        }
                    }

                    if (!isDoctest)
                    {
                        continue;
                    }

                    string name = element.StartTag.Name.ToString().ToLowerInvariant();
                    if (name != "code")
                    {
                        continue;
                    }

                    string text     = CodeFromElementText(element.Content.ToString());
                    var    lineSpan = element.SyntaxTree.GetLineSpan(element.Span);

                    int line   = lineSpan.StartLinePosition.Line;
                    int column = lineSpan.StartLinePosition.Character;
                    result.Add(new Code(text, line, column));
                }

                return(result);
            }
Esempio n. 19
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            Diagnostic diagnostic = context.Diagnostics.First();

            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;

            // Find the type declaration identified by the diagnostic.
            var declaration = root.FindToken(diagnosticSpan.Start).Parent as MethodDeclarationSyntax;

            // Register a code action that will invoke the fix.
            context.RegisterCodeFix(
                CodeAction.Create(
                    title: Title,
                    createChangedDocument: c => MakeReturnTask(context.Document, declaration, c),
                    equivalenceKey: Title),
                diagnostic);
        }
Esempio n. 20
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            Diagnostic diagnostic = context.Diagnostics.First();

            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;

            // Find the type declaration identified by the diagnostic.
            InvocationExpressionSyntax declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <InvocationExpressionSyntax>().First();

            // Register a code action that will invoke the fix.
            context.RegisterCodeFix(
                CodeAction.Create(
                    title: CodeFixResources.CodeFixTitle,
                    createChangedDocument: c => ReplaceWithFormattableStringInvariant(context.Document, declaration, c),
                    equivalenceKey: nameof(CodeFixResources.CodeFixTitle)),
                diagnostic);
        }
        static CodeAction HandleUsingStatement(Document document, Microsoft.CodeAnalysis.Text.TextSpan span, SyntaxNode root, UsingStatementSyntax usingStatement, VariableDeclaratorSyntax variable)
        {
            return(CodeActionFactory.Create(
                       span,
                       DiagnosticSeverity.Info,
                       "Iterate via 'foreach'",
                       ct =>
            {
                ForEachStatementSyntax foreachStmt = BuildForeach(SyntaxFactory.IdentifierName(variable.Identifier));

                var innerBlock = usingStatement.Statement.EnsureBlock();

                var newBlock = innerBlock.WithStatements(innerBlock.Statements.Insert(0, foreachStmt)).WithAdditionalAnnotations(Formatter.Annotation);
                var newUsing = usingStatement.WithStatement(newBlock);
                var newRoot = root.ReplaceNode(usingStatement, newUsing);

                return Task.FromResult(document.WithSyntaxRoot(newRoot));
            }
                       ));
        }
        private void FormatTrackingSpan(IBraceCompletionSession session, bool shouldHonorAutoFormattingOnCloseBraceOption)
        {
            if (!session.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutoFormattingOnTyping))
            {
                return;
            }

            if (!session.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace) && shouldHonorAutoFormattingOnCloseBraceOption)
            {
                return;
            }

            var snapshot      = session.SubjectBuffer.CurrentSnapshot;
            var startPoint    = session.OpeningPoint.GetPoint(snapshot);
            var endPoint      = session.ClosingPoint.GetPoint(snapshot);
            var startPosition = startPoint.Position;
            var endPosition   = endPoint.Position;

            var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
            var style    = document != null
                ? document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None).GetOption(FormattingOptions.SmartIndent)
                : FormattingOptions.SmartIndent.DefaultValue;

            if (style == FormattingOptions.IndentStyle.Smart)
            {
                // skip whitespace
                while (startPosition >= 0 && char.IsWhiteSpace(snapshot[startPosition]))
                {
                    startPosition--;
                }

                // skip token
                startPosition--;
                while (startPosition >= 0 && !char.IsWhiteSpace(snapshot[startPosition]))
                {
                    startPosition--;
                }
            }

            session.SubjectBuffer.Format(TextSpan.FromBounds(Math.Max(startPosition, 0), endPosition));
        }
        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            Document document = context.Document;

            Microsoft.CodeAnalysis.Text.TextSpan textSpan = context.Span;
            CancellationToken cancellationToken           = context.CancellationToken;

            CompilationUnitSyntax root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxToken   token         = root.FindToken(textSpan.Start);
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (token.Kind() == SyntaxKind.IdentifierToken &&
                token.Parent.Kind() == SyntaxKind.ClassDeclaration)
            {
                string className = token.Text;

                CreateEqualityCompareCodeAction action = new CreateEqualityCompareCodeAction($"Create EqualityCompare for {className}",
                                                                                             (c) => Task.FromResult(CreateEqualityCompareConverterForClass(document, semanticModel, token, root, c)));
                context.RegisterRefactoring(action);
            }
        }
            static DocumentRegion GetRegion(SyntaxTrivia trivia)
            {
                var fullSpan = trivia.FullSpan;
                var text     = trivia.ToString();

                if (text.Length > 2)
                {
                    if (text [text.Length - 2] == '\r' && text [text.Length - 1] == '\n')
                    {
                        fullSpan = new Microsoft.CodeAnalysis.Text.TextSpan(fullSpan.Start, fullSpan.Length - 2);
                    }
                    else if (NewLine.IsNewLine(text [text.Length - 1]))
                    {
                        fullSpan = new Microsoft.CodeAnalysis.Text.TextSpan(fullSpan.Start, fullSpan.Length - 1);
                    }
                }
                try {
                    var lineSpan = trivia.SyntaxTree.GetLineSpan(fullSpan);
                    return((DocumentRegion)lineSpan);
                } catch (Exception) {
                    return(DocumentRegion.Empty);
                }
            }
Esempio n. 25
0
        public sealed override void VisitReturnStatement(ReturnStatementSyntax returnSyntax)
        {
            this.Context.CurrentNode.OutgoingEdges.Clear();
            this.Context.CurrentNode.Operation = new BorderOperation(SpecialOperationKind.Return, null, null);

            // Get rid of the semicolon
            int expressionEnd  = returnSyntax.SemicolonToken.FullSpan.Start;
            var expressionSpan = new Microsoft.CodeAnalysis.Text.TextSpan(
                returnSyntax.SpanStart,
                expressionEnd - returnSyntax.SpanStart);

            this.Context.CurrentNode.DisplayNode = this.Context.AddDisplayNode(expressionSpan);

            if (returnSyntax.Expression != null)
            {
                var expressionNode = this.Context.PrependCurrentNode(returnSyntax.Expression);

                expressionNode.VariableModel        = this.Context.TryCreateTemporaryVariableModel(returnSyntax.Expression);
                this.Context.CurrentNode.ValueModel = expressionNode.VariableModel;

                this.Context.CurrentNode.LabelOverride = returnSyntax;
            }
        }
Esempio n. 26
0
        private bool TryGetFieldSpan([NotNullWhen(true)] out TextSpan?fieldSpan)
        {
            fieldSpan = null;
            var surfaceBufferFieldSpan = new VsTextSpan[1];

            if (snippetExpansionClient.ExpansionSession == null)
            {
                return(false);
            }

            if (snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
            {
                return(false);
            }

            if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan))
            {
                return(false);
            }

            fieldSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length);
            return(true);
        }
        private async Task <List <TextEdit> > FormatCSharpAsync(FormattingContext context, CancellationToken cancellationToken)
        {
            var sourceText  = context.SourceText;
            var csharpEdits = new List <TextEdit>();

            foreach (var mapping in context.CodeDocument.GetCSharpDocument().SourceMappings)
            {
                var span = new TextSpan(mapping.OriginalSpan.AbsoluteIndex, mapping.OriginalSpan.Length);
                if (!ShouldFormat(context, span, allowImplicitStatements: true))
                {
                    // We don't want to format this range.
                    continue;
                }

                // These should already be remapped.
                var range = span.AsRange(sourceText);
                var edits = await CSharpFormatter.FormatAsync(context, range, cancellationToken);

                csharpEdits.AddRange(edits.Where(e => range.Contains(e.Range)));
            }

            return(csharpEdits);
        }
        static CodeAction Handle(Document document, Microsoft.CodeAnalysis.Text.TextSpan span, SyntaxNode root, SyntaxNode node, ExpressionSyntax iterateOver, bool replaceNode)
        {
            return(CodeActionFactory.Create(
                       span,
                       DiagnosticSeverity.Info,
                       "Iterate via 'foreach'",
                       ct =>
            {
                ForEachStatementSyntax foreachStmt = BuildForeach(iterateOver);

                SyntaxNode newRoot;
                if (replaceNode)
                {
                    newRoot = root.ReplaceNode(node.GetAncestor <StatementSyntax>(), new[] { foreachStmt });
                }
                else
                {
                    newRoot = root.InsertNodesAfter(node.GetAncestor <StatementSyntax>(), new[] { foreachStmt });
                }
                return Task.FromResult(document.WithSyntaxRoot(newRoot));
            }
                       ));
        }
Esempio n. 29
0
        /// <inheritdoc/>
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.

            // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
            Diagnostic diagnostic = context.Diagnostics[0];
            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;

            // Find the type declaration identified by the diagnostic.
#pragma warning disable CS8602 // Dereference of a possibly null reference.
            TypeDeclarationSyntax declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <TypeDeclarationSyntax>().First();
#pragma warning restore CS8602 // Dereference of a possibly null reference.

            // Register a code action that will invoke the fix.
            context.RegisterCodeFix(
                CodeAction.Create(
                    title: Title,
                    createChangedSolution: c => this.MakeUppercaseAsync(context.Document, declaration, c),
                    equivalenceKey: Title),
                diagnostic);
        }
Esempio n. 30
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode?root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            Diagnostic diagnostic = context.Diagnostics.First();

            Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;
            // 获取diagnostic 传递来的 FriendClassType 值
            diagnostic.Properties.TryGetValue("FriendClassType", out string?frienClassType);
            if (frienClassType == null)
            {
                return;
            }

            ClassDeclarationSyntax?classDeclaration = root?.FindToken(diagnosticSpan.Start).Parent?.AncestorsAndSelf().OfType <ClassDeclarationSyntax>().First();
            // 构造Code Action
            CodeAction action = CodeAction.Create(
                "Add FriendClass Attribute",
                c => AddFriendClassAttributeAsync(context.Document, classDeclaration, frienClassType, c),
                equivalenceKey: nameof(EntityFiledAccessCodeFixProvider));

            // 注册codeFix Code Action
            context.RegisterCodeFix(action, diagnostic);
        }
Esempio n. 31
0
 public SourceLocationWrapper(SyntaxTree tree, Microsoft.CodeAnalysis.Text.TextSpan span) {
   this.tree = tree;
   this.span = span;
 }
			static DocumentRegion GetRegion (SyntaxTrivia trivia)
			{
				var fullSpan = trivia.FullSpan;
				var text = trivia.ToString ();
				if (text.Length > 2) {
					if (text [text.Length - 2] == '\r' && text [text.Length - 1] == '\n')
						fullSpan = new Microsoft.CodeAnalysis.Text.TextSpan (fullSpan.Start, fullSpan.Length - 2);
					else if (NewLine.IsNewLine (text [text.Length - 1]))
						fullSpan = new Microsoft.CodeAnalysis.Text.TextSpan (fullSpan.Start, fullSpan.Length - 1);
				}
				try {
					var lineSpan = trivia.SyntaxTree.GetLineSpan (fullSpan);
					return (DocumentRegion)lineSpan;
				} catch (Exception) {
					return DocumentRegion.Empty;
				}
			}