public SyntaxNode ConvertMethodsToProperty(
            DocumentOptionSet documentOptions, ParseOptions parseOptions,
            SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
            string propertyName, bool nameChanged)
        {
            var propertyDeclaration = ConvertMethodsToPropertyWorker(
                documentOptions, parseOptions, semanticModel,
                generator, getAndSetMethods, propertyName, nameChanged);

            var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value;

            if (expressionBodyPreference != ExpressionBodyPreference.Never)
            {
                if (propertyDeclaration.AccessorList?.Accessors.Count == 1 &&
                    propertyDeclaration.AccessorList?.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration)
                {
                    var getAccessor = propertyDeclaration.AccessorList.Accessors[0];
                    if (getAccessor.ExpressionBody != null)
                    {
                        return(propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody)
                               .WithSemicolonToken(getAccessor.SemicolonToken)
                               .WithAccessorList(null));
                    }
                    else if (getAccessor.Body != null &&
                             getAccessor.Body.TryConvertToExpressionBody(
                                 parseOptions, expressionBodyPreference,
                                 out var arrowExpression, out var semicolonToken))
                    {
                        return(propertyDeclaration.WithExpressionBody(arrowExpression)
                               .WithSemicolonToken(semicolonToken)
                               .WithAccessorList(null));
                    }
                }
            }
            else
            {
                if (propertyDeclaration.ExpressionBody != null &&
                    propertyDeclaration.ExpressionBody.TryConvertToBlock(
                        propertyDeclaration.SemicolonToken,
                        createReturnStatementForExpression: true,
                        block: out var block))
                {
                    var accessor =
                        SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                        .WithBody(block);

                    var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(accessor));
                    return(propertyDeclaration.WithAccessorList(accessorList)
                           .WithExpressionBody(null)
                           .WithSemicolonToken(default(SyntaxToken)));
                }
            }

            return(propertyDeclaration);
        }
            protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, DocumentOptionSet options, out string codeActionId, CancellationToken cancellationToken)
            {
                codeActionId = null;
                var node = SimplifyTypeNamesCodeFixProvider.GetNodeToSimplify(root, model, diagnostic.Location.SourceSpan, options, out var diagnosticId, cancellationToken);
                if (node != null)
                {
                    codeActionId = GetCodeActionId(diagnosticId, node.ToString());
                }

                return node;
            }
Exemple #3
0
 private (CodeAction?fieldAction, CodeAction?propertyAction) AddAllParameterInitializationActions(
     Document document,
     SyntaxNode constructorDeclaration,
     IMethodSymbol method,
     IBlockOperation?blockStatementOpt,
     ImmutableArray <NamingRule> rules,
     DocumentOptionSet options)
 {
     if (blockStatementOpt == null)
     {
         return(default);
        public static OmniSharpDocumentationCommentSnippet?GetDocumentationCommentSnippetFromPreviousLine(
            Document document,
            DocumentOptionSet options,
            TextLine currentLine,
            TextLine previousLine)
        {
            var service           = document.GetRequiredLanguageService <IDocumentationCommentSnippetService>();
            var docCommentOptions = DocumentationCommentOptions.From(options);

            return(Translate(service.GetDocumentationCommentSnippetFromPreviousLine(docCommentOptions, currentLine, previousLine)));
        }
Exemple #5
0
        public static OmniSharpDocumentationCommentSnippet?GetDocumentationCommentSnippetOnEnterTyped(
            Document document,
            SyntaxTree syntaxTree,
            SourceText text,
            int position,
            DocumentOptionSet options,
            CancellationToken cancellationToken)
        {
            var service = document.GetRequiredLanguageService <IDocumentationCommentSnippetService>();

            return(Translate(service.GetDocumentationCommentSnippetOnEnterTyped(syntaxTree, text, position, options, cancellationToken)));
        }
Exemple #6
0
        private async Task <SyntaxNode> SimplifyAsync(Solution solution, DocumentId documentId, SyntaxNode root, CancellationToken cancellationToken)
        {
            Document document = solution.GetDocument(documentId);

            document = document.WithSyntaxRoot(root);

            DocumentOptionSet options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);

            document = await Simplifier.ReduceAsync(document, options, cancellationToken).ConfigureAwait(false);

            return(await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false));
        }
        private bool InsertOnCommandInvoke(
            SyntaxTree syntaxTree,
            SourceText text,
            int position,
            int originalPosition,
            ITextBuffer subjectBuffer,
            ITextView textView,
            DocumentOptionSet options,
            CancellationToken cancellationToken)
        {
            var targetMember = GetTargetMember(syntaxTree, text, position, cancellationToken);

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

            var startPosition = targetMember.GetFirstToken().SpanStart;
            var line          = text.Lines.GetLineFromPosition(startPosition);

            Debug.Assert(!line.IsEmptyOrWhitespace());

            var lines = GetDocumentationCommentStubLines(targetMember);

            Debug.Assert(lines.Count > 2);

            var newLine = options.GetOption(FormattingOptions.NewLine);

            AddLineBreaks(text, lines, newLine);

            // Add indents
            var lineOffset = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(options.GetOption(FormattingOptions.TabSize));

            Debug.Assert(line.Start + lineOffset == startPosition);

            var indentText = lineOffset.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs), options.GetOption(FormattingOptions.TabSize));

            for (var i = 1; i < lines.Count; i++)
            {
                lines[i] = indentText + lines[i];
            }

            lines[lines.Count - 1] = lines[lines.Count - 1] + indentText;

            var newText = string.Join(string.Empty, lines);
            var offset  = lines[0].Length + lines[1].Length - newLine.Length;

            subjectBuffer.Insert(startPosition, newText);

            textView.TryMoveCaretToAndEnsureVisible(subjectBuffer.CurrentSnapshot.GetPoint(startPosition + offset));

            return(true);
        }
 protected virtual Task <IList <TextChange>?> GetFormattingChangesOnReturnAsync(
     IEditorFormattingService formattingService,
     Document document,
     int position,
     DocumentOptionSet documentOptions,
     CancellationToken cancellationToken
     ) =>
 formattingService.GetFormattingChangesOnReturnAsync(
     document,
     position,
     documentOptions,
     cancellationToken
     );
Exemple #9
0
 protected virtual Task <IList <TextChange> > GetFormattingChangesAsync(
     IEditorFormattingService formattingService,
     Document document,
     TextSpan?textSpan,
     DocumentOptionSet documentOptions,
     CancellationToken cancellationToken
     ) =>
 formattingService.GetFormattingChangesAsync(
     document,
     textSpan,
     documentOptions,
     cancellationToken
     );
Exemple #10
0
        private void InsertExteriorTrivia(ITextView view, ITextBuffer subjectBuffer, DocumentOptionSet options, TextLine currentLine, TextLine previousLine)
        {
            var insertionText = CreateInsertionTextFromPreviousLine(previousLine, options);

            var firstNonWhitespaceOffset = currentLine.GetFirstNonWhitespaceOffset();
            var replaceSpan = firstNonWhitespaceOffset != null
                ? TextSpan.FromBounds(currentLine.Start, currentLine.Start + firstNonWhitespaceOffset.Value)
                : currentLine.Span;

            subjectBuffer.Replace(replaceSpan.ToSpan(), insertionText);

            view.TryMoveCaretToAndEnsureVisible(subjectBuffer.CurrentSnapshot.GetPoint(replaceSpan.Start + insertionText.Length));
        }
Exemple #11
0
        private static async Task <LSP.DocumentOnAutoInsertResponseItem?> GetDocumentationCommentResponseAsync(
            LSP.DocumentOnAutoInsertParams autoInsertParams,
            Document document,
            IDocumentationCommentSnippetService service,
            DocumentOptionSet documentOptions,
            CancellationToken cancellationToken
            )
        {
            var syntaxTree = await document
                             .GetRequiredSyntaxTreeAsync(cancellationToken)
                             .ConfigureAwait(false);

            var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            var linePosition = ProtocolConversions.PositionToLinePosition(
                autoInsertParams.Position
                );
            var position = sourceText.Lines.GetPosition(linePosition);

            var result =
                autoInsertParams.Character == "\n"
                    ? service.GetDocumentationCommentSnippetOnEnterTyped(
                    syntaxTree,
                    sourceText,
                    position,
                    documentOptions,
                    cancellationToken
                    )
                    : service.GetDocumentationCommentSnippetOnCharacterTyped(
                    syntaxTree,
                    sourceText,
                    position,
                    documentOptions,
                    cancellationToken
                    );

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

            return(new LSP.DocumentOnAutoInsertResponseItem
            {
                TextEditFormat = LSP.InsertTextFormat.Snippet,
                TextEdit = new LSP.TextEdit
                {
                    NewText = result.SnippetText.Insert(result.CaretOffset, "$0"),
                    Range = ProtocolConversions.TextSpanToRange(result.SpanToReplace, sourceText)
                }
            });
        }
Exemple #12
0
        private IEnumerable <string> GetEnabledDiagnosticIds(DocumentOptionSet docOptions)
        {
            var diagnosticIds = new List <string>();

            foreach (var tuple in _optionDiagnosticsMappings)
            {
                if (docOptions.GetOption(tuple.Item1))
                {
                    diagnosticIds.AddRange(tuple.Item2);
                }
            }

            return(diagnosticIds);
        }
        private static SyntaxNode UseExpressionOrBlockBodyIfDesired(
            DocumentOptionSet documentOptions,
            ParseOptions parseOptions,
            MethodDeclarationSyntax methodDeclaration,
            bool createReturnStatementForExpression
            )
        {
            var expressionBodyPreference =
                documentOptions.GetOption(
                    CSharpCodeStyleOptions.PreferExpressionBodiedMethods
                    ).Value;

            if (
                methodDeclaration.Body != null &&
                expressionBodyPreference != ExpressionBodyPreference.Never
                )
            {
                if (
                    methodDeclaration.Body.TryConvertToArrowExpressionBody(
                        methodDeclaration.Kind(),
                        parseOptions,
                        expressionBodyPreference,
                        out var arrowExpression,
                        out var semicolonToken
                        )
                    )
                {
                    return(methodDeclaration
                           .WithBody(null)
                           .WithExpressionBody(arrowExpression)
                           .WithSemicolonToken(semicolonToken)
                           .WithAdditionalAnnotations(Formatter.Annotation));
                }
            }
            else if (
                methodDeclaration.ExpressionBody != null &&
                expressionBodyPreference == ExpressionBodyPreference.Never
                )
            {
                if (
                    methodDeclaration.ExpressionBody.TryConvertToBlock(
                        methodDeclaration.SemicolonToken,
                        createReturnStatementForExpression,
                        out var block
                        )
                    )
                {
                    return(methodDeclaration
                           .WithExpressionBody(null)
                           .WithSemicolonToken(default)
            static SourceText GetIndentedText(
                SourceText textToIndent,
                TextLine lineToIndent,
                LinePosition desiredCaretLinePosition,
                DocumentOptionSet documentOptions)
            {
                // Indent by the amount needed to make the caret line contain the desired indentation column.
                var amountToIndent = desiredCaretLinePosition.Character - lineToIndent.Span.Length;

                // Create and apply a text change with whitespace for the indentation amount.
                var indentText   = amountToIndent.CreateIndentationString(documentOptions.GetOption(FormattingOptions.UseTabs), documentOptions.GetOption(FormattingOptions.TabSize));
                var indentedText = textToIndent.WithChanges(new TextChange(new TextSpan(lineToIndent.End, 0), indentText));

                return(indentedText);
            }
            public SeparatedSyntaxListCodeActionComputer(
                AbstractSeparatedSyntaxListWrapper <TListSyntax, TListItemSyntax> service,
                Document document, SourceText sourceText, DocumentOptionSet options,
                TListSyntax listSyntax, SeparatedSyntaxList <TListItemSyntax> listItems,
                CancellationToken cancellationToken)
                : base(service, document, sourceText, options, cancellationToken)
            {
                _listSyntax = listSyntax;
                _listItems  = listItems;

                var generator = SyntaxGenerator.GetGenerator(this.OriginalDocument);

                _afterOpenTokenIndentationTrivia = generator.Whitespace(GetAfterOpenTokenIdentation());
                _singleIndentationTrivia         = generator.Whitespace(GetSingleIdentation());
            }
Exemple #16
0
        private int?DoBlockIndent(ITextSnapshotLine line, DocumentOptionSet optionSet)
        {
            for (var lineNumber = line.LineNumber - 1; lineNumber >= 0; --lineNumber)
            {
                var previousLine = line.Snapshot.GetLineFromLineNumber(lineNumber);

                string text = previousLine.GetText();

                if (text.Length > 0)
                {
                    return(GetLeadingWhiteSpace(text, optionSet));
                }
            }

            return(null);
        }
Exemple #17
0
        private int?DoSmartIndent(ITextSnapshotLine line, Document document, DocumentOptionSet optionSet, CancellationToken cancellationToken)
        {
            var indentationService = document.GetLanguageService <IIndentationService>();
            var syntaxFactsService = document.GetLanguageService <ISyntaxFactsService>();

            var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken);

            var indent = FindTotalParentChainIndent(
                syntaxTree.Root,
                line.Start.Position,
                0,
                optionSet.GetOption(FormattingOptions.IndentationSize),
                indentationService,
                syntaxFactsService);

            return(indent);
        }
        private List<SyntaxNode> ConvertPropertyToMembers(
            DocumentOptionSet documentOptions,
            ParseOptions parseOptions,
            SyntaxGenerator generator, 
            IPropertySymbol property,
            PropertyDeclarationSyntax propertyDeclaration,
            IFieldSymbol propertyBackingField,
            string desiredGetMethodName,
            string desiredSetMethodName,
            CancellationToken cancellationToken)
        {
            var result = new List<SyntaxNode>();

            if (propertyBackingField != null)
            {
                var initializer = propertyDeclaration.Initializer?.Value;
                result.Add(generator.FieldDeclaration(propertyBackingField, initializer));
            }

            var getMethod = property.GetMethod;
            if (getMethod != null)
            {
                result.Add(GetGetMethod(
                    documentOptions, parseOptions, 
                    generator, propertyDeclaration, propertyBackingField,
                    getMethod, desiredGetMethodName,
                    copyLeadingTrivia: true,
                    cancellationToken: cancellationToken));
            }

            var setMethod = property.SetMethod;
            if (setMethod != null)
            {
                // Set-method only gets the leading trivia of the property if we didn't copy
                // that trivia to the get-method.
                result.Add(GetSetMethod(
                    documentOptions, parseOptions,
                    generator, propertyDeclaration, propertyBackingField, 
                    setMethod, desiredSetMethodName,
                    copyLeadingTrivia: getMethod == null,
                    cancellationToken: cancellationToken));
            }

            return result;
        }
Exemple #19
0
        private static async Task <Solution> RefactorAsync(
            Document document,
            ParameterSyntax parameter,
            AnonymousFunctionExpressionSyntax anonymousFunction,
            CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            IParameterSymbol parameterSymbol = semanticModel.GetDeclaredSymbol(parameter, cancellationToken);

            ISymbol anonymousFunctionSymbol = semanticModel.GetSymbol(anonymousFunction, cancellationToken);

            string newName = NameGenerators.UnderscoreSuffix.EnsureUniqueParameterName("_", anonymousFunctionSymbol, semanticModel, cancellationToken: cancellationToken);

            DocumentOptionSet options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);

            return(await Renamer.RenameSymbolAsync(document.Solution(), parameterSymbol, newName, options, cancellationToken).ConfigureAwait(false));
        }
Exemple #20
0
        private int?SplitStringLiteral(
            ITextBuffer subjectBuffer, Document document, DocumentOptionSet options, int position, CancellationToken cancellationToken)
        {
            var useTabs = options.GetOption(FormattingOptions.UseTabs);
            var tabSize = options.GetOption(FormattingOptions.TabSize);

            var root       = document.GetSyntaxRootSynchronously(cancellationToken);
            var sourceText = root.SyntaxTree.GetText(cancellationToken);

            var splitter = StringSplitter.Create(document, position, root, sourceText, useTabs, tabSize, cancellationToken);

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

            return(splitter.TrySplit());
        }
        private TypeSyntax GetTypeSyntax(SemanticDocument document, DocumentOptionSet options, ExpressionSyntax expression, bool isConstant, CancellationToken cancellationToken)
        {
            var typeSymbol = GetTypeSymbol(document, expression, cancellationToken);

            if (typeSymbol.ContainsAnonymousType())
            {
                return(SyntaxFactory.IdentifierName("var"));
            }

            if (!isConstant &&
                CanUseVar(typeSymbol) &&
                TypeStyleHelper.IsImplicitTypePreferred(expression, document.SemanticModel, options, cancellationToken))
            {
                return(SyntaxFactory.IdentifierName("var"));
            }

            return(typeSymbol.GenerateTypeSyntax());
        }
        private static SyntaxNode GetGetMethod(
            DocumentOptionSet documentOptions,
            ParseOptions parseOptions,
            SyntaxGenerator generator,
            PropertyDeclarationSyntax propertyDeclaration,
            IFieldSymbol propertyBackingField,
            IMethodSymbol getMethod,
            string desiredGetMethodName,
            CancellationToken cancellationToken)
        {
            var methodDeclaration = GetGetMethodWorker(
                generator, propertyDeclaration, propertyBackingField, getMethod,
                desiredGetMethodName, cancellationToken);

            return(UseExpressionOrBlockBodyIfDesired(
                       documentOptions, parseOptions, methodDeclaration,
                       createReturnStatementForExpression: true));
        }
Exemple #23
0
        private static ImmutableArray <SyntaxNode> ConvertPropertyToMembers(
            DocumentOptionSet documentOptions,
            ParseOptions parseOptions,
            SyntaxGenerator generator,
            IPropertySymbol property,
            PropertyDeclarationSyntax propertyDeclaration,
            IFieldSymbol?propertyBackingField,
            string desiredGetMethodName,
            string desiredSetMethodName,
            CancellationToken cancellationToken)
        {
            using var _ = ArrayBuilder <SyntaxNode> .GetInstance(out var result);

            if (propertyBackingField != null)
            {
                var initializer = propertyDeclaration.Initializer?.Value;
                result.Add(generator.FieldDeclaration(propertyBackingField, initializer));
            }

            var getMethod = property.GetMethod;

            if (getMethod != null)
            {
                result.Add(GetGetMethod(
                               documentOptions, parseOptions,
                               generator, propertyDeclaration, propertyBackingField,
                               getMethod, desiredGetMethodName,
                               cancellationToken: cancellationToken));
            }

            var setMethod = property.SetMethod;

            if (setMethod != null)
            {
                result.Add(GetSetMethod(
                               documentOptions, parseOptions,
                               generator, propertyDeclaration, propertyBackingField,
                               setMethod, desiredSetMethodName,
                               cancellationToken: cancellationToken));
            }

            return(result.ToImmutable());
        }
        private static async Task <Document> DocumentExceptionsAsync(Document document, MemberDeclarationSyntax declaration, ImmutableArray <String> exceptions)
        {
            SyntaxNode?root = await document.GetSyntaxRootAsync();

            if (root is null)
            {
                // ?!
                return(document);
            }

            DocumentationCommentTriviaSyntax?documentation = declaration
                                                             .GetLeadingTrivia()
                                                             .Select(trivia => trivia.GetStructure())
                                                             .OfType <DocumentationCommentTriviaSyntax>()
                                                             .FirstOrDefault();

            DocumentOptionSet options = await document.GetOptionsAsync();

            if (documentation is null)
            {
                root = root.ReplaceNode(
                    declaration,
                    declaration.WithLeadingTrivia(
                        declaration
                        .GetLeadingTrivia()
                        .Add(Trivia(DocumentationComment(ExceptionDocumentation(options, exceptions))))
                        )
                    );
            }
            else
            {
                //
                // TODO: remove duplicates and subtypes that are handled by base types
                //

                root = root.ReplaceNode(
                    documentation,
                    documentation.AddContent(ExceptionDocumentation(options, exceptions))
                    );
            }

            return(document.WithSyntaxRoot(root));
        }
        private List <SyntaxNode> ConvertPropertyToMembers(
            DocumentOptionSet documentOptions,
            ParseOptions parseOptions,
            SyntaxGenerator generator,
            IPropertySymbol property,
            PropertyDeclarationSyntax propertyDeclaration,
            IFieldSymbol propertyBackingField,
            string desiredGetMethodName,
            string desiredSetMethodName,
            CancellationToken cancellationToken)
        {
            var result = new List <SyntaxNode>();

            if (propertyBackingField != null)
            {
                var initializer = propertyDeclaration.Initializer?.Value;
                result.Add(generator.FieldDeclaration(propertyBackingField, initializer));
            }

            var getMethod = property.GetMethod;

            if (getMethod != null)
            {
                result.Add(GetGetMethod(
                               documentOptions, parseOptions,
                               generator, propertyDeclaration, propertyBackingField,
                               getMethod, desiredGetMethodName,
                               cancellationToken: cancellationToken));
            }

            var setMethod = property.SetMethod;

            if (setMethod != null)
            {
                result.Add(GetSetMethod(
                               documentOptions, parseOptions,
                               generator, propertyDeclaration, propertyBackingField,
                               setMethod, desiredSetMethodName,
                               cancellationToken: cancellationToken));
            }

            return(result);
        }
            public BinaryExpressionCodeActionComputer(
                AbstractBinaryExpressionWrapper <TBinaryExpressionSyntax> service,
                Document document,
                SourceText originalSourceText,
                DocumentOptionSet options,
                TBinaryExpressionSyntax binaryExpression,
                ImmutableArray <SyntaxNodeOrToken> exprsAndOperators,
                CancellationToken cancellationToken)
                : base(service, document, originalSourceText, options, cancellationToken)
            {
                _exprsAndOperators = exprsAndOperators;
                _preference        = options.GetOption(CodeStyleOptions.OperatorPlacementWhenWrapping);

                var generator         = SyntaxGenerator.GetGenerator(document);
                var indentationString = OriginalSourceText.GetOffset(binaryExpression.Span.Start)
                                        .CreateIndentationString(UseTabs, TabSize);

                _indentationTrivia           = new SyntaxTriviaList(generator.Whitespace(indentationString));
                _newlineBeforeOperatorTrivia = service.GetNewLineBeforeOperatorTrivia(NewLineTrivia);
            }
        private static SyntaxNode GetGetMethod(
            DocumentOptionSet documentOptions,
            LanguageVersion languageVersion,
            SyntaxGenerator generator,
            PropertyDeclarationSyntax propertyDeclaration,
            IFieldSymbol?propertyBackingField,
            IMethodSymbol getMethod,
            string desiredGetMethodName,
            CancellationToken cancellationToken)
        {
            var methodDeclaration = GetGetMethodWorker(
                generator, propertyDeclaration, propertyBackingField, getMethod,
                desiredGetMethodName, cancellationToken);

            methodDeclaration = CopyLeadingTrivia(propertyDeclaration, methodDeclaration, ConvertValueToReturnsRewriter.Instance);

            return(UseExpressionOrBlockBodyIfDesired(
                       documentOptions, languageVersion, methodDeclaration,
                       createReturnStatementForExpression: true));
        }
        public void ReplaceGetMethodWithProperty(
            DocumentOptionSet documentOptions,
            ParseOptions parseOptions,
            SyntaxEditor editor,
            SemanticModel semanticModel,
            GetAndSetMethods getAndSetMethods,
            string propertyName, bool nameChanged)
        {
            if (!(getAndSetMethods.GetMethodDeclaration is MethodDeclarationSyntax getMethodDeclaration))
            {
                return;
            }

            var newProperty = ConvertMethodsToProperty(
                documentOptions, parseOptions,
                semanticModel, editor.Generator,
                getAndSetMethods, propertyName, nameChanged);

            editor.ReplaceNode(getMethodDeclaration, newProperty);
        }
Exemple #29
0
        private async Task <Document> RemoveSortUsingsAsync(Document document, DocumentOptionSet docOptions, CancellationToken cancellationToken)
        {
            // remove usings
            if (docOptions.GetOption(CodeCleanupOptions.RemoveUnusedImports))
            {
                var removeUsingsService = document.GetLanguageService <IRemoveUnnecessaryImportsService>();
                if (removeUsingsService != null)
                {
                    document = await removeUsingsService.RemoveUnnecessaryImportsAsync(document, cancellationToken).ConfigureAwait(false);
                }
            }

            // sort usings
            if (docOptions.GetOption(CodeCleanupOptions.SortImports))
            {
                document = await OrganizeImportsService.OrganizeImportsAsync(document, cancellationToken).ConfigureAwait(false);
            }

            return(document);
        }
Exemple #30
0
        public void ReplaceGetMethodWithProperty(
            DocumentOptionSet documentOptions,
            ParseOptions parseOptions,
            SyntaxEditor editor,
            SemanticModel semanticModel,
            GetAndSetMethods getAndSetMethods,
            string propertyName, bool nameChanged)
        {
            var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax;

            if (getMethodDeclaration == null)
            {
                return;
            }

            editor.ReplaceNode(getMethodDeclaration,
                               ConvertMethodsToProperty(
                                   documentOptions, parseOptions,
                                   semanticModel, editor.Generator,
                                   getAndSetMethods, propertyName, nameChanged));
        }
        protected override StatementSyntax CreateParameterCheckIfStatement(DocumentOptionSet options, ExpressionSyntax condition, StatementSyntax ifTrueStatement)
        {
            var withBlock       = options.GetOption(CSharpCodeStyleOptions.PreferBraces).Value == CodeAnalysis.CodeStyle.PreferBracesPreference.Always;
            var singleLine      = options.GetOption(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine).Value;
            var closeParenToken = Token(SyntaxKind.CloseParenToken);

            if (withBlock)
            {
                ifTrueStatement = Block(ifTrueStatement);
            }
            else if (singleLine)
            {
                // Any elastic trivia between the closing parenthesis of if and the statement must be removed
                // to convince the formatter to keep everything on a single line.
                // Note: ifTrueStatement and closeParenToken are generated, so there is no need to deal with any existing trivia.
                closeParenToken = closeParenToken.WithTrailingTrivia(Space);
                ifTrueStatement = ifTrueStatement.WithoutLeadingTrivia();
            }

            return(IfStatement(
                       attributeLists: default,
 protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, DocumentOptionSet options, out string codeActionId, CancellationToken cancellationToken)
 {
     codeActionId = null;
     return GetCastNode(root, model, diagnostic.Location.SourceSpan, cancellationToken);
 }
 /// <summary>
 /// Get node on which to add simplifier and formatter annotation for fixing the given diagnostic.
 /// </summary>
 protected virtual SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, DocumentOptionSet options, out string codeActionEquivalenceKey, CancellationToken cancellationToken)
 {
     codeActionEquivalenceKey = null;
     var span = diagnostic.Location.SourceSpan;
     return root.FindNode(diagnostic.Location.SourceSpan, findInsideTrivia: true);
 }
        private TypeSyntax GetTypeSyntax(SemanticDocument document, DocumentOptionSet options, ExpressionSyntax expression, bool isConstant, CancellationToken cancellationToken)
        {
            var typeSymbol = GetTypeSymbol(document, expression, cancellationToken);
            if (typeSymbol.ContainsAnonymousType())
            {
                return SyntaxFactory.IdentifierName("var");
            }

            if (!isConstant && 
                CanUseVar(typeSymbol) && 
                TypeStyleHelper.IsImplicitTypePreferred(expression, document.SemanticModel, options, cancellationToken))
            {
                return SyntaxFactory.IdentifierName("var");
            }

            return typeSymbol.GenerateTypeSyntax();
        }