|
| 1 | +// Copyright (c) .NET Foundation and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 2 | + |
| 3 | +using System.Collections.Immutable; |
| 4 | +using Microsoft.CodeAnalysis; |
| 5 | +using Microsoft.CodeAnalysis.CSharp; |
| 6 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 7 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 8 | +using Roslynator.CSharp; |
| 9 | +using Roslynator.CSharp.Analysis; |
| 10 | +using Roslynator.CSharp.CodeStyle; |
| 11 | + |
| 12 | +namespace Roslynator.Formatting.CSharp; |
| 13 | + |
| 14 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 15 | +public sealed class PutExpressionBodyOnItsOwnLineAnalyzer : BaseDiagnosticAnalyzer |
| 16 | +{ |
| 17 | + private static ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics; |
| 18 | + |
| 19 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics |
| 20 | + { |
| 21 | + get |
| 22 | + { |
| 23 | + if (_supportedDiagnostics.IsDefault) |
| 24 | + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.PutExpressionBodyOnItsOwnLine); |
| 25 | + |
| 26 | + return _supportedDiagnostics; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public override void Initialize(AnalysisContext context) |
| 31 | + { |
| 32 | + base.Initialize(context); |
| 33 | + |
| 34 | + context.RegisterSyntaxNodeAction(f => AnalyzeArrowExpressionClause(f), SyntaxKind.ArrowExpressionClause); |
| 35 | + } |
| 36 | + |
| 37 | + private static void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext context) |
| 38 | + { |
| 39 | + var arrowExpressionClause = (ArrowExpressionClauseSyntax)context.Node; |
| 40 | + |
| 41 | + if (ConvertExpressionBodyAnalysis.AllowPutExpressionBodyOnItsOwnLine(arrowExpressionClause.Parent.Kind())) |
| 42 | + { |
| 43 | + AnalyzeArrowExpressionClause(arrowExpressionClause.ArrowToken, context); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static void AnalyzeArrowExpressionClause(SyntaxToken arrowToken, SyntaxNodeAnalysisContext context) |
| 48 | + { |
| 49 | + NewLinePosition newLinePosition = context.GetArrowTokenNewLinePosition(); |
| 50 | + |
| 51 | + SyntaxToken first; |
| 52 | + SyntaxToken second; |
| 53 | + if (newLinePosition == NewLinePosition.After) |
| 54 | + { |
| 55 | + first = arrowToken; |
| 56 | + second = arrowToken.GetNextToken(); |
| 57 | + } |
| 58 | + else |
| 59 | + { |
| 60 | + first = arrowToken.GetPreviousToken(); |
| 61 | + second = arrowToken; |
| 62 | + } |
| 63 | + |
| 64 | + TriviaBlock block = TriviaBlock.FromBetween(first, second); |
| 65 | + |
| 66 | + if (block.Kind == TriviaBlockKind.NoNewLine) |
| 67 | + { |
| 68 | + DiagnosticHelpers.ReportDiagnostic( |
| 69 | + context, |
| 70 | + DiagnosticRules.PutExpressionBodyOnItsOwnLine, |
| 71 | + block.GetLocation()); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments