Skip to content

Commit a4fd5b7

Browse files
Simplify ancestor checks (#79513)
2 parents 764338f + 23b7465 commit a4fd5b7

File tree

6 files changed

+21
-60
lines changed

6 files changed

+21
-60
lines changed

src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
7373
var root = await document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
7474
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
7575

76-
var spanNode = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true)
77-
.GetAncestorsOrThis<TExpressionSyntax>().FirstOrDefault();
76+
var spanNode = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true).GetAncestorOrThis<TExpressionSyntax>();
7877
if (spanNode == null)
7978
return;
8079

src/Analyzers/VisualBasic/CodeFixes/AddExplicitCast/VisualBasicAddExplicitCastCodeFixProvider.vb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.AddExplicitCast
6464

6565
Select Case diagnosticId
6666
Case BC30512, BC42016
67-
Dim argument = spanNode.GetAncestors(Of ArgumentSyntax).FirstOrDefault()
67+
Dim argument = spanNode.GetAncestor(Of ArgumentSyntax)
6868
If argument IsNot Nothing AndAlso argument.GetExpression.Equals(spanNode) Then
6969
' spanNode is an argument expression
7070
Dim argumentList = DirectCast(argument.Parent, ArgumentListSyntax)

src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs

Lines changed: 10 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,59 +1117,40 @@ public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacem
11171117
private static SyntaxNode? GetExpansionTarget(SyntaxToken token)
11181118
{
11191119
// get the directly enclosing statement
1120-
var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault();
1120+
var enclosingStatement = token.GetAncestor<StatementSyntax>();
11211121

11221122
// System.Func<int, int> myFunc = arg => X;
11231123
var possibleLambdaExpression = enclosingStatement == null
1124-
? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax or ParenthesizedLambdaExpressionSyntax).FirstOrDefault()
1124+
? token.GetAncestor<LambdaExpressionSyntax>()
11251125
: null;
1126-
if (possibleLambdaExpression != null)
1127-
{
1128-
var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression);
1129-
if (lambdaExpression.Body is ExpressionSyntax)
1130-
{
1131-
return lambdaExpression.Body;
1132-
}
1133-
}
1126+
if (possibleLambdaExpression?.ExpressionBody is not null)
1127+
return possibleLambdaExpression.ExpressionBody;
11341128

11351129
// int M() => X;
11361130
var possibleArrowExpressionClause = enclosingStatement == null
1137-
? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault()
1131+
? token.GetAncestor<ArrowExpressionClauseSyntax>()
11381132
: null;
11391133
if (possibleArrowExpressionClause != null)
1140-
{
11411134
return possibleArrowExpressionClause.Expression;
1142-
}
11431135

11441136
var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault();
1145-
if (enclosingNameMemberCrefOrnull != null)
1146-
{
1147-
if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
1148-
{
1149-
enclosingNameMemberCrefOrnull = null;
1150-
}
1151-
}
1137+
if (enclosingNameMemberCrefOrnull != null && token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
1138+
enclosingNameMemberCrefOrnull = null;
11521139

1153-
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
1140+
var enclosingXmlNameAttr = token.GetAncestor<XmlNameAttributeSyntax>();
11541141
if (enclosingXmlNameAttr != null)
1155-
{
11561142
return null;
1157-
}
11581143

1159-
var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault();
1144+
var enclosingInitializer = token.GetAncestor<EqualsValueClauseSyntax>();
11601145
if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax)
1161-
{
11621146
return enclosingInitializer.Value;
1163-
}
11641147

11651148
var attributeSyntax = token.GetAncestor<AttributeSyntax>();
11661149
if (attributeSyntax != null)
1167-
{
11681150
return attributeSyntax;
1169-
}
11701151

11711152
// there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
1172-
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault();
1153+
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestor<SimpleNameSyntax>();
11731154
}
11741155

11751156
#region "Helper Methods"

src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpEscapingReducer.cs

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ private static SyntaxToken SimplifyIdentifierToken(
3737
{
3838
var unescapedIdentifier = token.ValueText;
3939

40-
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
40+
var enclosingXmlNameAttr = token.GetAncestor<XmlNameAttributeSyntax>();
4141

4242
// always escape keywords
4343
if (SyntaxFacts.GetKeywordKind(unescapedIdentifier) != SyntaxKind.None && enclosingXmlNameAttr == null)
@@ -52,32 +52,13 @@ private static SyntaxToken SimplifyIdentifierToken(
5252

5353
if (SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) == SyntaxKind.AwaitKeyword)
5454
{
55-
var enclosingLambdaExpression = parent.GetAncestorsOrThis(n => (n is SimpleLambdaExpressionSyntax or ParenthesizedLambdaExpressionSyntax)).FirstOrDefault();
56-
if (enclosingLambdaExpression != null)
57-
{
58-
if (enclosingLambdaExpression is SimpleLambdaExpressionSyntax simpleLambda)
59-
{
60-
if (simpleLambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword)
61-
{
62-
return token;
63-
}
64-
}
65-
66-
if (enclosingLambdaExpression is ParenthesizedLambdaExpressionSyntax parenLamdba)
67-
{
68-
if (parenLamdba.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword)
69-
{
70-
return token;
71-
}
72-
}
73-
}
74-
75-
var enclosingMethodBlock = parent.GetAncestorsOrThis(n => n is MethodDeclarationSyntax).FirstOrDefault();
55+
var enclosingLambdaExpression = parent.GetAncestorOrThis<LambdaExpressionSyntax>();
56+
if (enclosingLambdaExpression != null && enclosingLambdaExpression.AsyncKeyword != default)
57+
return token;
7658

77-
if (enclosingMethodBlock != null && ((MethodDeclarationSyntax)enclosingMethodBlock).Modifiers.Any(SyntaxKind.AsyncKeyword))
78-
{
59+
var enclosingMethodBlock = parent.GetAncestorOrThis<MethodDeclarationSyntax>();
60+
if (enclosingMethodBlock != null && enclosingMethodBlock.Modifiers.Any(SyntaxKind.AsyncKeyword))
7961
return token;
80-
}
8162
}
8263

8364
// within a query all contextual query keywords need to be escaped, even if they appear in a non query context.

src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ private static TDeclarationNode AddStatementsWorker<TDeclarationNode>(
537537

538538
var token = location.FindToken(cancellationToken);
539539

540-
var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault();
540+
var block = token.Parent.GetAncestorOrThis<BlockSyntax>();
541541
if (block != null)
542542
{
543543
var blockStatements = block.Statements.ToSet();

src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicEscapingReducer.vb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
123123
' escape contextual query keywords if they are the first token after a query expression
124124
' and on the following line
125125
Dim previousToken = identifier.GetPreviousToken(False, False, True, True)
126-
Dim queryAncestorOfPrevious = previousToken.GetAncestors(Of QueryExpressionSyntax).FirstOrDefault()
126+
Dim queryAncestorOfPrevious = previousToken.GetAncestor(Of QueryExpressionSyntax)
127127
If queryAncestorOfPrevious IsNot Nothing AndAlso queryAncestorOfPrevious.GetLastToken() = previousToken Then
128128
lastTokenOfQuery = previousToken
129129

@@ -162,7 +162,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
162162
' if this token is part of a XmlDocument, all trailing whitespace is part of the XmlDocument
163163
' so all line breaks actually will not help.
164164
' see VB spec #11.23.3
165-
If previousToken.GetAncestors(Of XmlDocumentSyntax).FirstOrDefault() IsNot Nothing Then
165+
If previousToken.GetAncestor(Of XmlDocumentSyntax) IsNot Nothing Then
166166
Return identifier
167167
End If
168168

0 commit comments

Comments
 (0)