Esempio n. 1
0
        private protected static async Task AssertCodeCleanupResult(string expected, string code, CodeStyleOption2 <AddImportPlacement> preferredImportPlacement, bool systemUsingsFirst = true, bool separateUsingGroups = false)
        {
            using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf);

            var solution = workspace.CurrentSolution
                           .WithOptions(workspace.Options
                                        .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst)
                                        .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups)
                                        .WithChangedOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredImportPlacement))
                           .WithAnalyzerReferences(new[]
            {
                new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile),
                new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile)
            });

            workspace.TryApplyChanges(solution);

            // register this workspace to solution crawler so that analyzer service associate itself with given workspace
            var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue <IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider;

            incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace);

            var hostdoc  = workspace.Documents.Single();
            var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);

            var codeCleanupService = document.GetLanguageService <ICodeCleanupService>();

            var enabledDiagnostics = codeCleanupService.GetAllDiagnostics();

            var fallbackOptions = new CodeActionOptions(
                CleanupOptions: CodeCleanupOptions.GetDefault(document.Project.LanguageServices) with
            {
                FormattingOptions = new CSharpSyntaxFormattingOptions(separateImportDirectiveGroups: separateUsingGroups)
            });
Esempio n. 2
0
        public async Task CodeCleanersCSharp_Document()
        {
            var document      = CreateDocument("class C { }", LanguageNames.CSharp);
            var cleanDocument = await CodeCleaner.CleanupAsync(document, CodeCleanupOptions.GetDefault(document.Project.LanguageServices));

            Assert.Equal(document, cleanDocument);
        }
Esempio n. 3
0
        public async Task CodeCleanersVisualBasic_Document()
        {
            var document      = CreateDocument(@"Class C
End Class", LanguageNames.VisualBasic);
            var cleanDocument = await CodeCleaner.CleanupAsync(document, CodeCleanupOptions.GetDefault(document.Project.LanguageServices));

            Assert.Equal(document, cleanDocument);
        }
Esempio n. 4
0
        public async Task CodeCleanersCSharp_Annotation()
        {
            var document   = CreateDocument("class C { }", LanguageNames.CSharp);
            var annotation = new SyntaxAnnotation();

            document = document.WithSyntaxRoot((await document.GetSyntaxRootAsync()).WithAdditionalAnnotations(annotation));

            var cleanDocument = await CodeCleaner.CleanupAsync(document, annotation, CodeCleanupOptions.GetDefault(document.Project.LanguageServices));

            Assert.Equal(document, cleanDocument);
        }
Esempio n. 5
0
        protected static async Task <SyntaxNode> ExtractMethodAsync(
            TestWorkspace workspace,
            TestHostDocument testDocument,
            bool succeed = true,
            bool dontPutOutOrRefOnStruct = true,
            bool allowBestEffort         = false)
        {
            var document = workspace.CurrentSolution.GetDocument(testDocument.Id);

            Assert.NotNull(document);

            var options = new ExtractMethodGenerationOptions(
                ExtractOptions: new ExtractMethodOptions(dontPutOutOrRefOnStruct),
                CodeGenerationOptions: CodeGenerationOptions.GetDefault(document.Project.LanguageServices),
                AddImportOptions: AddImportPlacementOptions.Default,
                NamingPreferences: _ => NamingStylePreferences.Default);

            var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);

            var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options.ExtractOptions, localFunction: false);

            var selectedCode = await validator.GetValidSelectionAsync(CancellationToken.None);

            if (!succeed && selectedCode.Status.FailedWithNoBestEffortSuggestion())
            {
                return(null);
            }

            Assert.True(selectedCode.ContainsValidContext);

            // extract method
            var extractor = new CSharpMethodExtractor((CSharpSelectionResult)selectedCode, options, localFunction: false);
            var result    = await extractor.ExtractMethodAsync(CancellationToken.None);

            Assert.NotNull(result);
            Assert.Equal(succeed,
                         result.Succeeded ||
                         result.SucceededWithSuggestion ||
                         (allowBestEffort && result.Status.HasBestEffort()));

            var(doc, _) = await result.GetFormattedDocumentAsync(CodeCleanupOptions.GetDefault(document.Project.LanguageServices), CancellationToken.None);

            return(doc == null
                ? null
                : await doc.GetSyntaxRootAsync());
        }
            public override ValueTask <CleanCodeGenerationOptions> GetCleanCodeGenerationOptionsAsync(HostLanguageServices languageServices, CancellationToken cancellationToken)
            {
                var lineFormattingOptions = _lineFormattingOptionsProvider.GetLineFormattingOptions();
                var codeGenerationOptions = CleanCodeGenerationOptions.GetDefault(languageServices) with
                {
                    CleanupOptions = CodeCleanupOptions.GetDefault(languageServices) with
                    {
                        FormattingOptions = SyntaxFormattingOptions.GetDefault(languageServices).With(new LineFormattingOptions
                        {
                            IndentationSize = lineFormattingOptions.IndentationSize,
                            TabSize         = lineFormattingOptions.TabSize,
                            UseTabs         = lineFormattingOptions.UseTabs,
                            NewLine         = lineFormattingOptions.NewLine,
                        })
                    }
                };

                return(new ValueTask <CleanCodeGenerationOptions>(codeGenerationOptions));
            }
Esempio n. 7
0
        public async Task DontCrash_VB_2()
        {
            var code          = @"
Public Class Class1
    Public Custom Event Event2 As EventHandler
        AddHandler(ByVal value As EventHandler)
        End AddHandler
        RemoveHandler(ByVal value As EventHandler)
        End RemoveHandler
        RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
            e
    End Event

End Class
";
            var document      = CreateDocument(code, LanguageNames.VisualBasic);
            var semanticModel = await document.GetSemanticModelAsync();

            var root = await document.GetSyntaxRootAsync();

            var accessor         = root.DescendantNodes().OfType <VisualBasic.Syntax.AccessorBlockSyntax>().Last();
            var newSemanticModel = await document.ReuseExistingSpeculativeModelAsync(accessor.Statements[0], CancellationToken.None);

            Assert.NotNull(newSemanticModel);
            Assert.False(newSemanticModel.IsSpeculativeSemanticModel);

            var newDocument = CreateDocument(code, LanguageNames.VisualBasic);
            var newRoot     = await newDocument.GetSyntaxRootAsync();

            var newAccessor = newRoot.DescendantNodes().OfType <VisualBasic.Syntax.AccessorBlockSyntax>().Last();

            root             = root.ReplaceNode(accessor, newAccessor);
            document         = document.WithSyntaxRoot(root);
            accessor         = root.DescendantNodes().OfType <VisualBasic.Syntax.AccessorBlockSyntax>().Last();
            newSemanticModel = await document.ReuseExistingSpeculativeModelAsync(accessor.Statements[0], CancellationToken.None);

            Assert.NotNull(newSemanticModel);
            Assert.True(newSemanticModel.IsSpeculativeSemanticModel);

            var cleanDocument = await CodeCleaner.CleanupAsync(document, CodeCleanupOptions.GetDefault(document.Project.LanguageServices));

            Assert.Equal(document, cleanDocument);
        }
        public static async ValueTask <OmniSharpSyntaxFormattingOptionsWrapper> FromDocumentAsync(Document document, OmniSharpLineFormattingOptions fallbackLineFormattingOptions, CancellationToken cancellationToken)
        {
            var defaultOptions  = CodeCleanupOptions.GetDefault(document.Project.LanguageServices);
            var fallbackOptions = defaultOptions with
            {
                FormattingOptions = defaultOptions.FormattingOptions.With(new LineFormattingOptions
                {
                    IndentationSize = fallbackLineFormattingOptions.IndentationSize,
                    TabSize         = fallbackLineFormattingOptions.TabSize,
                    UseTabs         = fallbackLineFormattingOptions.UseTabs,
                    NewLine         = fallbackLineFormattingOptions.NewLine,
                })
            };

            var cleanupOptions = await document.GetCodeCleanupOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);

            return(new OmniSharpSyntaxFormattingOptionsWrapper(cleanupOptions));
        }
    }
Esempio n. 9
0
        internal async Task TestAsync(string testCode, string expected, OptionsCollection?options = null, ParseOptions?parseOptions = null)
        {
            using var workspace = CreateTestWorkspace(testCode, parseOptions);
            options?.SetGlobalOptions(workspace.GlobalOptions);

            var solution = workspace.CurrentSolution;

            var document         = workspace.CurrentSolution.Projects.First().Documents.First();
            var languageServices = document.Project.LanguageServices;

            var cleanupOptions =
                options?.ToAnalyzerConfigOptions(languageServices).GetCodeCleanupOptions(allowImportsInHiddenRegions: false, fallbackOptions: null, languageServices) ??
                CodeCleanupOptions.GetDefault(languageServices);

            var formattingService = document.GetRequiredLanguageService <INewDocumentFormattingService>();
            var formattedDocument = await formattingService.FormatNewDocumentAsync(document, hintDocument : null, cleanupOptions, CancellationToken.None);

            var actual = await formattedDocument.GetTextAsync();

            AssertEx.EqualOrDiff(expected, actual.ToString());
        }
Esempio n. 10
0
        public void OptionsAreMessagePackSerializable(string language)
        {
            var messagePackOptions = MessagePackSerializerOptions.Standard.WithResolver(MessagePackFormatters.DefaultResolver);

            using var workspace = new AdhocWorkspace();
            var languageServices = workspace.Services.GetLanguageServices(language);

            var options = new object[]
            {
                SimplifierOptions.GetDefault(languageServices),
                SyntaxFormattingOptions.GetDefault(languageServices),
                CodeCleanupOptions.GetDefault(languageServices),
                CodeGenerationOptions.GetDefault(languageServices),
                IdeCodeStyleOptions.GetDefault(languageServices),
                CodeActionOptions.GetDefault(languageServices),
                IndentationOptions.GetDefault(languageServices),
                ExtractMethodGenerationOptions.GetDefault(languageServices),

                // some non-default values:
                new VisualBasicIdeCodeStyleOptions(
                    new IdeCodeStyleOptions.CommonOptions()
                {
                    AllowStatementImmediatelyAfterBlock = new CodeStyleOption2 <bool>(false, NotificationOption2.Error)
                },
                    PreferredModifierOrder: new CodeStyleOption2 <string>("Public Private", NotificationOption2.Error))
            };

            foreach (var original in options)
            {
                using var stream = new MemoryStream();
                MessagePackSerializer.Serialize(stream, original, messagePackOptions);
                stream.Position = 0;

                var deserialized = MessagePackSerializer.Deserialize(original.GetType(), stream, messagePackOptions);
                Assert.Equal(original, deserialized);
            }
        }
Esempio n. 11
0
        private static void VerifyRange(string code, ImmutableArray <ICodeCleanupProvider> codeCleanups, ImmutableArray <TextSpan> spans, ref IEnumerable <TextSpan> expectedResult, string language)
        {
            var result          = (IEnumerable <TextSpan>)null;
            var spanCodeCleanup = new MockCodeCleanupProvider()
            {
                CleanupDocumentAsyncImpl = (document, spans, options, cancellationToken) =>
                {
                    result = spans;
                    return(Task.FromResult(document));
                }
            };

            var document = CreateDocument(code, language);

            CodeCleaner.CleanupAsync(document, spans, CodeCleanupOptions.GetDefault(document.Project.LanguageServices), codeCleanups.Concat(spanCodeCleanup)).Wait();

            var sortedSpans   = result.ToList();
            var expectedSpans = expectedResult.ToList();

            sortedSpans.Sort();
            expectedSpans.Sort();

            AssertEx.Equal(expectedSpans, sortedSpans);
        }
Esempio n. 12
0
        private static async Task VerifyAsync(string codeWithMarker, string expectedResult, LanguageVersion langVersion = LanguageVersion.VisualBasic14)
        {
            MarkupTestFile.GetSpans(codeWithMarker,
                                    out var codeWithoutMarker, out ImmutableArray <TextSpan> textSpans);

            var document     = CreateDocument(codeWithoutMarker, LanguageNames.VisualBasic, langVersion);
            var codeCleanups = CodeCleaner.GetDefaultProviders(document).WhereAsArray(p => p.Name is PredefinedCodeCleanupProviderNames.RemoveUnnecessaryLineContinuation or PredefinedCodeCleanupProviderNames.Format);

            var cleanDocument = await CodeCleaner.CleanupAsync(document, textSpans[0], CodeCleanupOptions.GetDefault(document.Project.LanguageServices), codeCleanups);

            var actualResult = (await cleanDocument.GetSyntaxRootAsync()).ToFullString();

            Assert.Equal(expectedResult, actualResult);
        }
Esempio n. 13
0
        public async Task CodeCleanersCSharp_Spans()
        {
            var document = CreateDocument("class C { }", LanguageNames.CSharp);
            var root     = await document.GetSyntaxRootAsync();

            var cleanDocument = await CodeCleaner.CleanupAsync(document, ImmutableArray.Create(root.FullSpan), CodeCleanupOptions.GetDefault(document.Project.LanguageServices));

            Assert.Equal(document, cleanDocument);
        }
Esempio n. 14
0
        ValueTask <CleanCodeGenerationOptions> OptionsProvider <CleanCodeGenerationOptions> .GetOptionsAsync(HostLanguageServices languageServices, CancellationToken cancellationToken)
        {
            var codeActionOptions = GetOptions(languageServices);

            return(ValueTaskFactory.FromResult(new CleanCodeGenerationOptions(
                                                   codeActionOptions.CodeGenerationOptions ?? CodeGenerationOptions.GetDefault(languageServices),
                                                   codeActionOptions.CleanupOptions ?? CodeCleanupOptions.GetDefault(languageServices))));
        }
Esempio n. 15
0
 ValueTask <CodeCleanupOptions> OptionsProvider <CodeCleanupOptions> .GetOptionsAsync(HostLanguageServices languageServices, CancellationToken cancellationToken)
 => ValueTaskFactory.FromResult(GetOptions(languageServices).CleanupOptions ?? CodeCleanupOptions.GetDefault(languageServices));
        private static async Task VerifyAsync(string codeWithMarker, string expectedResult)
        {
            codeWithMarker = FixLineEndings(codeWithMarker);
            expectedResult = FixLineEndings(expectedResult);

            MarkupTestFile.GetSpans(codeWithMarker,
                                    out var codeWithoutMarker, out ImmutableArray <TextSpan> textSpans);

            var document     = CreateDocument(codeWithoutMarker, LanguageNames.VisualBasic);
            var codeCleanups = CodeCleaner.GetDefaultProviders(document).WhereAsArray(p => p.Name is PredefinedCodeCleanupProviderNames.FixIncorrectTokens or PredefinedCodeCleanupProviderNames.Format);

            var cleanDocument = await CodeCleaner.CleanupAsync(document, textSpans[0], CodeCleanupOptions.GetDefault(document.Project.LanguageServices), codeCleanups);

            Assert.Equal(expectedResult, (await cleanDocument.GetSyntaxRootAsync()).ToFullString());
        }