提交 2c990168 编写于 作者: C Cyrus Najmabadi

use pattern matching

上级 8025e92d
......@@ -155,8 +155,7 @@ private static bool InvalidLevel(int? level)
case SyntaxKind.ArrowExpressionClause:
{
// Arrow expression clause declares getter symbol for properties and indexers.
var parentProperty = node.Parent as BasePropertyDeclarationSyntax;
if (parentProperty != null)
if (node.Parent is BasePropertyDeclarationSyntax parentProperty)
{
builder.Add(GetExpressionBodyDeclarationInfo(parentProperty, (ArrowExpressionClauseSyntax)node, model, getSymbol, cancellationToken));
}
......@@ -233,8 +232,7 @@ private static bool InvalidLevel(int? level)
var codeBlocks = GetParameterListInitializersAndAttributes(t.ParameterList);
codeBlocks = codeBlocks.Concat(t.Body);
var ctorDecl = t as ConstructorDeclarationSyntax;
if (ctorDecl != null && ctorDecl.Initializer != null)
if (t is ConstructorDeclarationSyntax ctorDecl && ctorDecl.Initializer != null)
{
codeBlocks = codeBlocks.Concat(ctorDecl.Initializer);
}
......
......@@ -349,10 +349,9 @@ private SyntaxNode GetNodeContainingTargetNode(SyntaxNode matchingNode)
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = semanticModel.GetSymbolInfo((InvocationExpressionSyntax)originalNode, cancellationToken);
var methodSymbol = symbolInfo.Symbol as IMethodSymbol;
var isReducedExtensionMethod = false;
if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ReducedExtension)
if (symbolInfo.Symbol is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.ReducedExtension)
{
isReducedExtensionMethod = true;
}
......@@ -576,8 +575,7 @@ private List<SyntaxTrivia> GetPermutedTrivia(CSharpSyntaxNode node, List<XmlElem
continue;
}
var structuredTrivia = trivia.GetStructure() as DocumentationCommentTriviaSyntax;
if (structuredTrivia == null)
if (!(trivia.GetStructure() is DocumentationCommentTriviaSyntax structuredTrivia))
{
updatedLeadingTrivia.Add(trivia);
continue;
......
......@@ -63,8 +63,7 @@ public CSharpAddAwaitCodeFixProvider()
Document document,
CancellationToken cancellationToken)
{
var expression = oldNode as ExpressionSyntax;
if (expression == null)
if (!(oldNode is ExpressionSyntax expression))
{
return SpecializedTasks.Default<SyntaxNode>();
}
......
......@@ -68,8 +68,7 @@ public override ImmutableArray<string> FixableDiagnosticIds
return null;
}
var methodSymbol = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol as IMethodSymbol;
if (methodSymbol == null)
if (!(semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol is IMethodSymbol methodSymbol))
{
return null;
}
......@@ -80,8 +79,7 @@ public override ImmutableArray<string> FixableDiagnosticIds
return null;
}
var methodDeclaration = (await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) as MethodDeclarationSyntax;
if (methodDeclaration == null)
if (!((await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) is MethodDeclarationSyntax methodDeclaration))
{
return null;
}
......
......@@ -150,10 +150,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
// Don't offer this if there are any errors or ambiguities.
return false;
}
var lambdaMethod = lambdaSemanticInfo.Symbol as IMethodSymbol;
var invocationMethod = invocationSemanticInfo.Symbol as IMethodSymbol;
if (lambdaMethod == null || invocationMethod == null)
if (!(lambdaSemanticInfo.Symbol is IMethodSymbol lambdaMethod) || !(invocationSemanticInfo.Symbol is IMethodSymbol invocationMethod))
{
return false;
}
......
......@@ -54,10 +54,7 @@ public override async Task ProvideCompletionsAsync(CompletionContext context)
{
return;
}
var attributeArgumentList = token.Parent as AttributeArgumentListSyntax;
var attributeSyntax = token.Parent.Parent as AttributeSyntax;
if (attributeSyntax == null || attributeArgumentList == null)
if (!(token.Parent.Parent is AttributeSyntax attributeSyntax) || !(token.Parent is AttributeArgumentListSyntax attributeArgumentList))
{
return;
}
......@@ -96,8 +93,7 @@ public override async Task ProvideCompletionsAsync(CompletionContext context)
private bool IsAfterNameColonArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is AttributeArgumentListSyntax argumentList)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
......@@ -122,8 +118,7 @@ private bool IsAfterNameColonArgument(SyntaxToken token)
private bool IsAfterNameEqualsArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is AttributeArgumentListSyntax argumentList)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
......@@ -216,8 +211,7 @@ private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argu
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
if (within != null && attributeType != null)
if (within != null && semanticModel.GetTypeInfo(attribute, cancellationToken).Type is INamedTypeSymbol attributeType)
{
return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
......
......@@ -58,8 +58,7 @@ public override async Task ProvideCompletionsAsync(CompletionContext context)
return;
}
var argumentList = token.Parent as BaseArgumentListSyntax;
if (argumentList == null)
if (!(token.Parent is BaseArgumentListSyntax argumentList))
{
return;
}
......@@ -157,9 +156,8 @@ private ISet<string> GetExistingNamedParameters(BaseArgumentListSyntax argumentL
ObjectCreationExpressionSyntax objectCreationExpression,
CancellationToken cancellationToken)
{
var type = semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type as INamedTypeSymbol;
var within = semanticModel.GetEnclosingNamedType(position, cancellationToken);
if (type != null && within != null && type.TypeKind != TypeKind.Delegate)
if (semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type is INamedTypeSymbol type && within != null && type.TypeKind != TypeKind.Delegate)
{
return type.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
......
......@@ -70,8 +70,7 @@ protected override IEnumerable<INamedTypeSymbol> LookupCandidateSymbols(SyntaxCo
private static bool IsPartialTypeDeclaration(SyntaxNode syntax)
{
var declarationSyntax = syntax as BaseTypeDeclarationSyntax;
return declarationSyntax != null && declarationSyntax.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.PartialKeyword));
return syntax is BaseTypeDeclarationSyntax declarationSyntax && declarationSyntax.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.PartialKeyword));
}
protected override ImmutableDictionary<string, string> GetProperties(
......
......@@ -31,8 +31,7 @@ public CSharpDesignerAttributeService(Workspace workspace) : base(workspace)
protected override IEnumerable<SyntaxNode> GetAllTopLevelTypeDefined(SyntaxNode node)
{
var compilationUnit = node as CompilationUnitSyntax;
if (compilationUnit == null)
if (!(node is CompilationUnitSyntax compilationUnit))
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
......
......@@ -111,8 +111,7 @@ private static bool IsCrefCandidate(SyntaxNode node)
issueSpan = default;
diagnosticId = IDEDiagnosticIds.SimplifyNamesDiagnosticId;
var memberAccess = node as MemberAccessExpressionSyntax;
if (memberAccess != null && memberAccess.Expression.IsKind(SyntaxKind.ThisExpression))
if (node is MemberAccessExpressionSyntax memberAccess && memberAccess.Expression.IsKind(SyntaxKind.ThisExpression))
{
// don't bother analyzing "this.Goo" expressions. They will be analyzed by
// the CSharpSimplifyThisOrMeDiagnosticAnalyzer.
......
......@@ -293,14 +293,12 @@ private static int GetEndPosition(SyntaxNodeOrToken nodeOrToken)
TryCreateSpanForNode(localFunction.ExpressionBody.Expression, position);
default:
var expression = node as ExpressionSyntax;
if (expression != null)
if (node is ExpressionSyntax expression)
{
return IsBreakableExpression(expression) ? CreateSpan(expression) : default(TextSpan?);
}
var statement = node as StatementSyntax;
if (statement != null)
if (node is StatementSyntax statement)
{
return TryCreateSpanForStatement(statement, position);
}
......@@ -343,8 +341,7 @@ private static TextSpan CreateSpanForConstructorInitializer(ConstructorInitializ
private static TextSpan? TryCreateSpanForSwitchLabel(SwitchLabelSyntax switchLabel, int position)
{
var switchSection = switchLabel.Parent as SwitchSectionSyntax;
if (switchSection == null || switchSection.Statements.Count == 0)
if (!(switchLabel.Parent is SwitchSectionSyntax switchSection) || switchSection.Statements.Count == 0)
{
return null;
}
......@@ -666,14 +663,12 @@ private static int GetItemIndexByPosition<TNode>(SeparatedSyntaxList<TNode> list
private static SyntaxTokenList GetModifiers(VariableDeclarationSyntax declaration)
{
BaseFieldDeclarationSyntax fieldDeclaration;
LocalDeclarationStatementSyntax localDeclaration;
if ((fieldDeclaration = declaration.Parent as BaseFieldDeclarationSyntax) != null)
if (declaration.Parent is BaseFieldDeclarationSyntax fieldDeclaration)
{
return fieldDeclaration.Modifiers;
}
if ((localDeclaration = declaration.Parent as LocalDeclarationStatementSyntax) != null)
if (declaration.Parent is LocalDeclarationStatementSyntax localDeclaration)
{
return localDeclaration.Modifiers;
}
......
......@@ -907,8 +907,7 @@ internal override bool IsDeclarationWithInitializer(SyntaxNode declaration)
internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration)
{
var ctor = constructorDeclaration as ConstructorDeclarationSyntax;
return ctor != null && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer));
return constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer));
}
internal override bool IsPartial(INamedTypeSymbol type)
......
......@@ -283,8 +283,7 @@ private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> state
foreach (var statement in statements)
{
var declStatement = statement as LocalDeclarationStatementSyntax;
if (declStatement == null)
if (!(statement is LocalDeclarationStatementSyntax declStatement))
{
// found one
return OperationStatus.Succeeded;
......@@ -452,8 +451,7 @@ private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> state
// We don't have a good refactoring for this, so we just annotate the conflict
// For instance, when a local declared by a pattern declaration (`3 is int i`) is
// used outside the block we're trying to extract.
var designation = pattern.Designation as SingleVariableDesignationSyntax;
if (designation == null)
if (!(pattern.Designation is SingleVariableDesignationSyntax designation))
{
break;
}
......
......@@ -32,8 +32,7 @@ public IEnumerable<StatementSyntax> RemoveRedundantBlock(IEnumerable<StatementSy
}
// that statement must be a block
var block = statements.Single() as BlockSyntax;
if (block == null)
if (!(statements.Single() is BlockSyntax block))
{
return statements;
}
......@@ -159,8 +158,7 @@ private bool IsDeclarationMergable(StatementSyntax statement)
// 3. no trivia except whitespace
// 4. type must be known
var declarationStatement = statement as LocalDeclarationStatementSyntax;
if (declarationStatement == null)
if (!(statement is LocalDeclarationStatementSyntax declarationStatement))
{
return false;
}
......@@ -231,10 +229,7 @@ public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern
{
return statements;
}
var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
var returnStatement = statements.ElementAtOrDefault(1) as ReturnStatementSyntax;
if (declaration == null || returnStatement == null)
if (!(statements.ElementAtOrDefault(0) is LocalDeclarationStatementSyntax declaration) || !(statements.ElementAtOrDefault(1) is ReturnStatementSyntax returnStatement))
{
return statements;
}
......@@ -266,11 +261,7 @@ public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern
public IEnumerable<StatementSyntax> RemoveDeclarationAssignmentPattern(IEnumerable<StatementSyntax> statements)
{
// if we have inline temp variable as service, we could just use that service here.
// since it is not a service right now, do very simple clean up
var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
var assignment = statements.ElementAtOrDefault(1) as ExpressionStatementSyntax;
if (declaration == null || assignment == null)
if (!(statements.ElementAtOrDefault(0) is LocalDeclarationStatementSyntax declaration) || !(statements.ElementAtOrDefault(1) is ExpressionStatementSyntax assignment))
{
return statements;
}
......
......@@ -32,8 +32,7 @@ private CSharpTriviaResult(SemanticDocument document, ITriviaSavedResult result)
protected override AnnotationResolver GetAnnotationResolver(SyntaxNode callsite, SyntaxNode method)
{
var methodDefinition = method as MethodDeclarationSyntax;
if (callsite == null || methodDefinition == null)
if (callsite == null || !(method is MethodDeclarationSyntax methodDefinition))
{
return null;
}
......
......@@ -18,8 +18,7 @@ internal static class Extensions
{
public static ExpressionSyntax GetUnparenthesizedExpression(this SyntaxNode node)
{
var parenthesizedExpression = node as ParenthesizedExpressionSyntax;
if (parenthesizedExpression == null)
if (!(node is ParenthesizedExpressionSyntax parenthesizedExpression))
{
return node as ExpressionSyntax;
}
......@@ -146,8 +145,7 @@ public static bool ContainArgumentlessThrowWithoutEnclosingCatch(this IEnumerabl
continue;
}
var throwStatement = token.Parent as ThrowStatementSyntax;
if (throwStatement == null || throwStatement.Expression != null)
if (!(token.Parent is ThrowStatementSyntax throwStatement) || throwStatement.Expression != null)
{
continue;
}
......
......@@ -56,8 +56,7 @@ public override ImmutableArray<string> FixableDiagnosticIds
protected override bool CanFullyQualify(Diagnostic diagnostic, ref SyntaxNode node)
{
var simpleName = node as SimpleNameSyntax;
if (simpleName == null)
if (!(node is SimpleNameSyntax simpleName))
{
return false;
}
......
......@@ -230,8 +230,7 @@ protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbo
{
while (true)
{
var parentType = typeNameToReplace.Parent as TypeSyntax;
if (parentType == null)
if (!(typeNameToReplace.Parent is TypeSyntax parentType))
{
break;
}
......
......@@ -31,8 +31,7 @@ protected override bool IsIdentifierNameGeneration(SyntaxNode node)
if (identifierToken.ValueText != string.Empty &&
!identifierName.IsVar)
{
var memberAccess = identifierName.Parent as MemberAccessExpressionSyntax;
simpleNameOrMemberAccessExpression = memberAccess != null && memberAccess.Name == identifierName
simpleNameOrMemberAccessExpression = identifierName.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == identifierName
? (ExpressionSyntax)memberAccess
: identifierName;
......
......@@ -148,8 +148,7 @@ protected override bool IsValidSymbol(ISymbol symbol, SemanticModel semanticMode
{
methodSymbol = null;
typeToGenerateIn = document.SemanticModel.GetTypeInfo(castExpression.Type, cancellationToken).Type as INamedTypeSymbol;
var parameterSymbol = document.SemanticModel.GetTypeInfo(castExpression.Expression, cancellationToken).Type as INamedTypeSymbol;
if (typeToGenerateIn == null || parameterSymbol == null || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
if (typeToGenerateIn == null || !(document.SemanticModel.GetTypeInfo(castExpression.Expression, cancellationToken).Type is INamedTypeSymbol parameterSymbol) || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
{
return false;
}
......@@ -179,8 +178,7 @@ protected override bool IsValidSymbol(ISymbol symbol, SemanticModel semanticMode
{
methodSymbol = null;
typeToGenerateIn = document.SemanticModel.GetTypeInfo(expression, cancellationToken).ConvertedType as INamedTypeSymbol;
var parameterSymbol = document.SemanticModel.GetTypeInfo(expression, cancellationToken).Type as INamedTypeSymbol;
if (typeToGenerateIn == null || parameterSymbol == null || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
if (typeToGenerateIn == null || !(document.SemanticModel.GetTypeInfo(expression, cancellationToken).Type is INamedTypeSymbol parameterSymbol) || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
{
return false;
}
......
......@@ -414,14 +414,12 @@ protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<s
{
foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
{
var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
if (simpleAssignmentExpression == null)
if (!(expression is AssignmentExpressionSyntax simpleAssignmentExpression))
{
continue;
}
var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
if (name == null)
if (!(simpleAssignmentExpression.Left is SimpleNameSyntax name))
{
continue;
}
......@@ -648,8 +646,7 @@ private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
{
var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
if (!(localRoot is NamespaceDeclarationSyntax namespaceDecl) || namespaceDecl.Name is AliasQualifiedNameSyntax)
{
return null;
}
......@@ -824,8 +821,7 @@ internal override bool IsGenericName(SimpleNameSyntax simpleName)
return false;
}
var genericName = simpleName as GenericNameSyntax;
return genericName != null;
return simpleName is GenericNameSyntax genericName;
}
internal override bool IsSimpleName(ExpressionSyntax expression)
......
......@@ -40,10 +40,9 @@ public CSharpImplementInterfaceService()
var interfaceSymbolInfo = model.GetSymbolInfo(interfaceNode, cancellationToken);
if (interfaceSymbolInfo.CandidateReason != CandidateReason.WrongArity)
{
var interfaceType = interfaceSymbolInfo.GetAnySymbol() as INamedTypeSymbol;
cancellationToken.ThrowIfCancellationRequested();
if (interfaceType != null && interfaceType.TypeKind == TypeKind.Interface)
if (interfaceSymbolInfo.GetAnySymbol() is INamedTypeSymbol interfaceType && interfaceType.TypeKind == TypeKind.Interface)
{
classOrStructDecl = interfaceNode.Parent.Parent.Parent as TypeDeclarationSyntax;
classOrStructType = model.GetDeclaredSymbol(classOrStructDecl, cancellationToken) as INamedTypeSymbol;
......
......@@ -92,8 +92,7 @@ private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context, INamedTypeSymb
return;
}
var argumentList = argumentNode.Parent as ArgumentListSyntax;
if (argumentList == null)
if (!(argumentNode.Parent is ArgumentListSyntax argumentList))
{
return;
}
......@@ -125,8 +124,7 @@ private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context, INamedTypeSymb
}
var semanticModel = context.SemanticModel;
var outLocalSymbol = semanticModel.GetSymbolInfo(argumentExpression, cancellationToken).Symbol as ILocalSymbol;
if (outLocalSymbol == null)
if (!(semanticModel.GetSymbolInfo(argumentExpression, cancellationToken).Symbol is ILocalSymbol outLocalSymbol))
{
// The out-argument wasn't referencing a local. So we don't have an local
// declaration that we can attempt to inline here.
......@@ -138,15 +136,13 @@ private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context, INamedTypeSymb
// esoteric and would make us have to write a lot more complex code to support
// that scenario.
var localReference = outLocalSymbol.DeclaringSyntaxReferences.FirstOrDefault();
var localDeclarator = localReference?.GetSyntax(cancellationToken) as VariableDeclaratorSyntax;
if (localDeclarator == null)
if (!(localReference?.GetSyntax(cancellationToken) is VariableDeclaratorSyntax localDeclarator))
{
return;
}
var localDeclaration = localDeclarator.Parent as VariableDeclarationSyntax;
var localStatement = localDeclaration?.Parent as LocalDeclarationStatementSyntax;
if (localStatement == null)
if (!(localDeclaration?.Parent is LocalDeclarationStatementSyntax localStatement))
{
return;
}
......@@ -175,8 +171,7 @@ private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context, INamedTypeSymb
// for references to the local to make sure that no reads/writes happen before
// the out-argument. If there are any reads/writes we can't inline as those
// accesses will become invalid.
var enclosingBlockOfLocalStatement = localStatement.Parent as BlockSyntax;
if (enclosingBlockOfLocalStatement == null)
if (!(localStatement.Parent is BlockSyntax enclosingBlockOfLocalStatement))
{
return;
}
......
......@@ -152,8 +152,7 @@ internal partial class CSharpIntroduceVariableService
private static bool IsConstantField(MemberDeclarationSyntax member)
{
var field = member as FieldDeclarationSyntax;
return field != null && field.Modifiers.Any(SyntaxKind.ConstKeyword);
return member is FieldDeclarationSyntax field && field.Modifiers.Any(SyntaxKind.ConstKeyword);
}
protected static int DetermineFirstChange(SyntaxList<MemberDeclarationSyntax> oldMembers, SyntaxList<MemberDeclarationSyntax> newMembers)
......
......@@ -87,9 +87,8 @@ internal partial class CSharpIntroduceVariableService
var rewrittenBody = Rewrite(
document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken);
var delegateType = document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType as INamedTypeSymbol;
var newBody = delegateType != null && delegateType.DelegateInvokeMethod != null && delegateType.DelegateInvokeMethod.ReturnsVoid
var newBody = document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType is INamedTypeSymbol delegateType && delegateType.DelegateInvokeMethod != null && delegateType.DelegateInvokeMethod.ReturnsVoid
? SyntaxFactory.Block(declarationStatement)
: SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody));
......
......@@ -92,8 +92,7 @@ private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
var expressionStatement = (ExpressionStatementSyntax)innerStatement;
// Check that it's of the form: "if (a != null) { a(); }
var invocationExpression = ((ExpressionStatementSyntax)innerStatement).Expression as InvocationExpressionSyntax;
if (invocationExpression == null)
if (!(((ExpressionStatementSyntax)innerStatement).Expression is InvocationExpressionSyntax invocationExpression))
{
return;
}
......
......@@ -36,8 +36,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
{
var options = context.Options as WorkspaceAnalyzerOptions;
if (options == null)
if (!(context.Options is WorkspaceAnalyzerOptions options))
{
return;
}
......
......@@ -36,8 +36,7 @@ public void RemoveSetMethod(SyntaxEditor editor, SyntaxNode setMethodDeclaration
GetAndSetMethods getAndSetMethods,
string propertyName, bool nameChanged)
{
var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax;
if (getMethodDeclaration == null)
if (!(getAndSetMethods.GetMethodDeclaration is MethodDeclarationSyntax getMethodDeclaration))
{
return;
}
......@@ -226,9 +225,8 @@ private static AccessorDeclarationSyntax CreateGetAccessorWorker(GetAndSetMethod
private static AccessorDeclarationSyntax CreateSetAccessorWorker(
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods)
{
var setMethodDeclaration = getAndSetMethods.SetMethodDeclaration as MethodDeclarationSyntax;
var setMethod = getAndSetMethods.SetMethod;
if (setMethodDeclaration == null || setMethod?.Parameters.Length != 1)
if (!(getAndSetMethods.SetMethodDeclaration is MethodDeclarationSyntax setMethodDeclaration) || setMethod?.Parameters.Length != 1)
{
return null;
}
......@@ -352,8 +350,7 @@ public void ReplaceSetReference(SyntaxEditor editor, SyntaxToken nameToken, stri
return;
}
var nameNode = nameToken.Parent as IdentifierNameSyntax;
if (nameNode == null)
if (!(nameToken.Parent is IdentifierNameSyntax nameNode))
{
return;
}
......
......@@ -36,8 +36,7 @@ public CSharpReplacePropertyWithMethodsService()
string desiredSetMethodName,
CancellationToken cancellationToken)
{
var propertyDeclaration = propertyDeclarationNode as PropertyDeclarationSyntax;
if (propertyDeclaration == null)
if (!(propertyDeclarationNode is PropertyDeclarationSyntax propertyDeclaration))
{
return SpecializedCollections.EmptyList<SyntaxNode>();
}
......
......@@ -71,8 +71,7 @@ protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document d
}
var semanticModel = await document.GetSemanticModelForNodeAsync(attribute, cancellationToken).ConfigureAwait(false);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
if (attributeType == null)
if (!(semanticModel.GetTypeInfo(attribute, cancellationToken).Type is INamedTypeSymbol attributeType))
{
return null;
}
......
......@@ -80,8 +80,7 @@ protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document d
return null;
}
var simpleName = genericIdentifier.Parent as SimpleNameSyntax;
if (simpleName == null)
if (!(genericIdentifier.Parent is SimpleNameSyntax simpleName))
{
return null;
}
......
......@@ -90,7 +90,6 @@ protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document d
methodGroup = methodGroup.Sort(
symbolDisplayService, semanticModel, invocationExpression.SpanStart);
var expressionType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type as INamedTypeSymbol;
var anonymousTypeDisplayService = document.GetLanguageService<IAnonymousTypeDisplayService>();
var documentationCommentFormattingService = document.GetLanguageService<IDocumentationCommentFormattingService>();
......@@ -109,7 +108,7 @@ protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document d
GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken),
selectedItem);
}
else if (expressionType != null && expressionType.TypeKind == TypeKind.Delegate)
else if (semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type is INamedTypeSymbol expressionType && expressionType.TypeKind == TypeKind.Delegate)
{
var items = GetDelegateInvokeItems(invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService,
documentationCommentFormattingService, within, expressionType, out var selectedItem, cancellationToken);
......
......@@ -61,8 +61,7 @@ protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document d
}
var semanticModel = await document.GetSemanticModelForNodeAsync(objectCreationExpression, cancellationToken).ConfigureAwait(false);
var type = semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type as INamedTypeSymbol;
if (type == null)
if (!(semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type is INamedTypeSymbol type))
{
return null;
}
......
......@@ -22,8 +22,7 @@ internal class ParenthesizedLambdaExpressionStructureProvider : AbstractSyntaxNo
return;
}
var lambdaBlock = lambdaExpression.Body as BlockSyntax;
if (lambdaBlock == null ||
if (!(lambdaExpression.Body is BlockSyntax lambdaBlock) ||
lambdaBlock.OpenBraceToken.IsMissing ||
lambdaBlock.CloseBraceToken.IsMissing)
{
......
......@@ -22,8 +22,7 @@ internal class SimpleLambdaExpressionStructureProvider : AbstractSyntaxNodeStruc
return;
}
var lambdaBlock = lambdaExpression.Body as BlockSyntax;
if (lambdaBlock == null ||
if (!(lambdaExpression.Body is BlockSyntax lambdaBlock) ||
lambdaBlock.OpenBraceToken.IsMissing ||
lambdaBlock.CloseBraceToken.IsMissing)
{
......
......@@ -94,8 +94,7 @@ public static ExpressionSyntax GetExpressionBody(LambdaExpressionSyntax declarat
// able to create the right sort of block body (i.e. with a return-statement or
// expr-statement). So, if we can't figure out what lambda type this is, we should not
// proceed.
var lambdaType = semanticModel.GetTypeInfo(declaration, cancellationToken).ConvertedType as INamedTypeSymbol;
if (lambdaType == null || lambdaType.DelegateInvokeMethod == null)
if (!(semanticModel.GetTypeInfo(declaration, cancellationToken).ConvertedType is INamedTypeSymbol lambdaType) || lambdaType.DelegateInvokeMethod == null)
{
return (canOffer: false, fixesError: false);
}
......
......@@ -83,8 +83,7 @@ protected override void InitializeWorker(AnalysisContext context)
{
// Validate we're on a piece of syntax we expect. While not necessary for analysis, we
// want to make sure we're on something the fixer will know how to actually fix.
var invocationSyntax = invocation.Syntax as InvocationExpressionSyntax;
if (invocationSyntax is null ||
if (!(invocation.Syntax is InvocationExpressionSyntax invocationSyntax) ||
invocationSyntax.ArgumentList is null)
{
return default;
......
......@@ -44,14 +44,12 @@ protected override bool IsNotEquals(BinaryExpressionSyntax condition)
conditionPartToCheck = null;
isEquals = true;
var patternExpression = conditionNode as IsPatternExpressionSyntax;
if (patternExpression == null)
if (!(conditionNode is IsPatternExpressionSyntax patternExpression))
{
return false;
}
var constantPattern = patternExpression.Pattern as ConstantPatternSyntax;
if (constantPattern == null)
if (!(patternExpression.Pattern is ConstantPatternSyntax constantPattern))
{
return false;
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册