示例#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)
            });
示例#2
0
        static void ValidateCSharpOptions(CSharpSyntaxFormattingOptions formattingOptions)
        {
            ValidateCommonOptions(formattingOptions);

            Assert.False(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterControlFlowStatementKeyword));
            Assert.False(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterSemicolonsInForStatement));
            Assert.False(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterColonInBaseTypeDeclaration));
            Assert.False(formattingOptions.Spacing.HasFlag(SpacePlacement.BeforeColonInBaseTypeDeclaration));
            Assert.False(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterComma));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.IgnoreAroundVariableDeclaration));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterMethodDeclarationName));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BetweenEmptyMethodDeclarationParentheses));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.WithinMethodDeclarationParenthesis));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterMethodCallName));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BetweenEmptyMethodCallParentheses));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.WithinMethodCallParentheses));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.WithinExpressionParentheses));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.WithinCastParentheses));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BeforeSemicolonsInForStatement));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.WithinOtherParentheses));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterCast));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BeforeOpenSquareBracket));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BetweenEmptySquareBrackets));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.WithinSquareBrackets));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BeforeComma));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterDot));
            Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BeforeDot));

            Assert.Equal(BinaryOperatorSpacingOptions.Remove, formattingOptions.SpacingAroundBinaryOperator);

            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeMembersInObjectInitializers));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeMembersInAnonymousTypes));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeElse));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeCatch));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeFinally));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInTypes));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInAnonymousTypes));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInObjectCollectionArrayInitializers));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInProperties));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInMethods));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInAccessors));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInAnonymousMethods));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInLambdaExpressionBody));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInControlBlocks));
            Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BetweenQueryExpressionClauses));

            Assert.Equal(LabelPositionOptions.LeftMost, formattingOptions.LabelPositioning);

            Assert.True(formattingOptions.Indentation.HasFlag(IndentationPlacement.Braces));
            Assert.False(formattingOptions.Indentation.HasFlag(IndentationPlacement.BlockContents));
            Assert.False(formattingOptions.Indentation.HasFlag(IndentationPlacement.SwitchCaseContents));
            Assert.False(formattingOptions.Indentation.HasFlag(IndentationPlacement.SwitchCaseContentsWhenBlock));
            Assert.False(formattingOptions.Indentation.HasFlag(IndentationPlacement.SwitchSection));

            Assert.False(formattingOptions.WrappingPreserveSingleLine);
            Assert.False(formattingOptions.WrappingKeepStatementsOnSingleLine);
        }
示例#3
0
 public CSharpSyntaxWrappingOptions(
     CSharpSyntaxFormattingOptions formattingOptions,
     int wrappingColumn,
     OperatorPlacementWhenWrappingPreference operatorPlacement,
     bool newLinesForBracesInObjectCollectionArrayInitializers)
     : base(formattingOptions, wrappingColumn, operatorPlacement)
 {
     NewLinesForBracesInObjectCollectionArrayInitializers = newLinesForBracesInObjectCollectionArrayInitializers;
 }
        public void FormatWithTabs()
        {
            var code     = @"#region Assembly mscorlib
// C:\
#endregion

using System.Collections;

class F
{
    string s;
}";
            var expected = @"#region Assembly mscorlib
// C:\
#endregion

using System.Collections;

class F
{
	string s;
}";
            var tree     = SyntaxFactory.ParseCompilationUnit(code);

            var newLineText = SyntaxFactory.ElasticEndOfLine(DefaultWorkspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp));

            tree = tree.ReplaceTokens(tree.DescendantTokens(descendIntoTrivia: true)
                                      .Where(tr => tr.IsKind(SyntaxKind.EndOfDirectiveToken)), (o, r) => o.WithTrailingTrivia(o.LeadingTrivia.Add(newLineText))
                                      .WithLeadingTrivia(SyntaxFactory.TriviaList())
                                      .WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation));

            using var workspace = new AdhocWorkspace();

            var options = new CSharpSyntaxFormattingOptions()
            {
                Common = new SyntaxFormattingOptions.CommonOptions
                {
                    LineFormatting = new LineFormattingOptions {
                        UseTabs = true
                    }
                }
            };

            var formatted = Formatter.Format(tree, workspace.Services, options, CancellationToken.None);

            var actual = formatted.ToFullString();

            Assert.Equal(expected, actual);
        }
示例#5
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 options = CodeActionOptions.Default;

            var solution = workspace.CurrentSolution
                           .WithOptions(workspace.Options
                                        .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst)
                                        .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);

            var formattingOptions = new CSharpSyntaxFormattingOptions(
                lineFormatting: LineFormattingOptions.Default,
                separateImportDirectiveGroups: separateUsingGroups,
                spacing: CSharpSyntaxFormattingOptions.Default.Spacing,
                spacingAroundBinaryOperator: CSharpSyntaxFormattingOptions.Default.SpacingAroundBinaryOperator,
                newLines: CSharpSyntaxFormattingOptions.Default.NewLines,
                labelPositioning: CSharpSyntaxFormattingOptions.Default.LabelPositioning,
                indentation: CSharpSyntaxFormattingOptions.Default.Indentation,
                wrappingKeepStatementsOnSingleLine: CSharpSyntaxFormattingOptions.Default.WrappingKeepStatementsOnSingleLine,
                wrappingPreserveSingleLine: CSharpSyntaxFormattingOptions.Default.WrappingPreserveSingleLine);

            // 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 newDoc = await codeCleanupService.CleanupAsync(
                document, enabledDiagnostics, new ProgressTracker(), options, formattingOptions, CancellationToken.None);

            var actual = await newDoc.GetTextAsync();

            Assert.Equal(expected, actual.ToString());
        }
        public void NewLineOptions_LineFeedOnly()
        {
            using var workspace = new AdhocWorkspace();
            var tree = SyntaxFactory.ParseCompilationUnit("class C\r\n{\r\n}");

            // replace all EOL trivia with elastic markers to force the formatter to add EOL back
            tree = tree.ReplaceTrivia(tree.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.EndOfLineTrivia)), (o, r) => SyntaxFactory.ElasticMarker);

            var options = new CSharpSyntaxFormattingOptions(new LineFormattingOptions(NewLine: "\n"));

            var formatted = Formatter.Format(tree, workspace.Services, options, CancellationToken.None);

            var actual   = formatted.ToFullString();
            var expected = "class C\n{\n}";

            Assert.Equal(expected, actual);
        }
 private BraceCompletionFormattingRule(FormattingOptions2.IndentStyle indentStyle, CSharpSyntaxFormattingOptions options)
 {
     _indentStyle = indentStyle;
     _options     = options;
 }