public static void AnalyzeEnumDeclaration(SyntaxNodeAnalysisContext context) { var enumDeclaration = (EnumDeclarationSyntax)context.Node; SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; if (members.Count <= 1) { return; } int previousIndex = members[0].GetSpanStartLine(); for (int i = 1; i < members.Count; i++) { if (members[i].GetSpanStartLine() == previousIndex) { TextSpan span = TextSpan.FromBounds( members.First().SpanStart, members.Last().Span.End); context.ReportDiagnostic( DiagnosticDescriptors.AddNewLineBeforeEnumMember, Location.Create(enumDeclaration.SyntaxTree, span)); return; } previousIndex = members[i].GetSpanEndLine(); } }
public static bool ArgumentIsLiteralPredicate <T>(SeparatedSyntaxList <ArgumentSyntax> arguments, T value) { return(arguments.Any() && arguments.First().Expression is LiteralExpressionSyntax literal && literal.Token.Value is T argument && argument.Equals(value)); }
protected virtual ImmutableArray <TSyntax> FindUnusedSyntax( TNode node, TListSyntax list, SeparatedSyntaxList <TSyntax> separatedList, SemanticModel semanticModel, CancellationToken cancellationToken) { int count = separatedList.Count(f => !f.IsMissing); if (count == 1) { TSyntax syntax = separatedList.First(f => !f.IsMissing); if (IsFixable(node, list, syntax, semanticModel, cancellationToken) && !syntax.SpanContainsDirectives()) { return(ImmutableArray.Create(syntax)); } } else if (count > 1) { return(FindFixableSyntaxes(node, list, separatedList, count, semanticModel, cancellationToken) .Where(f => !f.SpanContainsDirectives()) .ToImmutableArray()); } return(ImmutableArray <TSyntax> .Empty); }
public static void Analyze(SyntaxNodeAnalysisContext context, EnumDeclarationSyntax enumDeclaration) { SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; if (members.Count > 1) { int previousIndex = members[0].GetSpanStartLine(); for (int i = 1; i < members.Count; i++) { if (members[i].GetSpanStartLine() == previousIndex) { TextSpan span = TextSpan.FromBounds( members.First().Span.Start, members.Last().Span.End); context.ReportDiagnostic( DiagnosticDescriptors.FormatEachEnumMemberOnSeparateLine, Location.Create(enumDeclaration.SyntaxTree, span)); return; } previousIndex = members[i].GetSpanEndLine(); } } }
public static bool CanRefactor( InvocationExpressionSyntax invocation, SemanticModel semanticModel, CancellationToken cancellationToken) { MethodInfo methodInfo; if (semanticModel.TryGetExtensionMethodInfo(invocation, out methodInfo, ExtensionMethodKind.None, cancellationToken) && methodInfo.IsLinqSelect(allowImmutableArrayExtension: true)) { ArgumentListSyntax argumentList = invocation.ArgumentList; if (argumentList?.IsMissing == false) { SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count == 1) { ArgumentSyntax argument = arguments.First(); ExpressionSyntax expression = argument.Expression; if (expression?.IsMissing == false) { SyntaxKind expressionKind = expression.Kind(); if (expressionKind == SyntaxKind.SimpleLambdaExpression) { var lambda = (SimpleLambdaExpressionSyntax)expression; if (CanRefactor(lambda.Parameter, lambda.Body)) { return(true); } } else if (expressionKind == SyntaxKind.ParenthesizedLambdaExpression) { var lambda = (ParenthesizedLambdaExpressionSyntax)expression; ParameterListSyntax parameterList = lambda.ParameterList; if (parameterList != null) { SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; if (parameters.Count == 1 && CanRefactor(parameters.First(), lambda.Body)) { return(true); } } } } } } } return(false); }
public static bool CanRefactor( InvocationExpressionSyntax invocation, SemanticModel semanticModel, CancellationToken cancellationToken) { IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocation, cancellationToken); if (methodSymbol != null && IsEnumerableOrImmutableArrayExtensionSelectMethod(methodSymbol, semanticModel)) { ArgumentListSyntax argumentList = invocation.ArgumentList; if (argumentList?.IsMissing == false) { SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count == 1) { ArgumentSyntax argument = arguments.First(); ExpressionSyntax expression = argument.Expression; if (expression?.IsMissing == false) { SyntaxKind expressionKind = expression.Kind(); if (expressionKind == SyntaxKind.SimpleLambdaExpression) { var lambda = (SimpleLambdaExpressionSyntax)expression; if (CanRefactor(lambda.Parameter, lambda.Body)) { return(true); } } else if (expressionKind == SyntaxKind.ParenthesizedLambdaExpression) { var lambda = (ParenthesizedLambdaExpressionSyntax)expression; ParameterListSyntax parameterList = lambda.ParameterList; if (parameterList != null) { SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; if (parameters.Count == 1 && CanRefactor(parameters.First(), lambda.Body)) { return(true); } } } } } } } return(false); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.MoveBaseClassBeforeAnyInterface)) { return; } SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); BaseListSyntax baseList = root .FindNode(context.Span, getInnermostNodeForTie: true)? .FirstAncestorOrSelf <BaseListSyntax>(); Debug.Assert(baseList != null, $"{nameof(baseList)} is null"); if (baseList == null || baseList.ContainsDiagnostics) { return; } foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.BaseClassMustComeBeforeAnyInterface: { SeparatedSyntaxList <BaseTypeSyntax> types = baseList.Types; if (types.Count > 1) { BaseTypeSyntax baseType = types.First(f => context.Span.Contains(f.Span)); CodeAction codeAction = CodeAction.Create( $"Move '{baseType.Type}' before any interface", cancellationToken => { BaseTypeSyntax firstType = types[0]; SeparatedSyntaxList <BaseTypeSyntax> newTypes = types .Replace(baseType, firstType.WithTriviaFrom(baseType)) .ReplaceAt(0, baseType.WithTriviaFrom(firstType)); BaseListSyntax newBaseList = baseList.WithTypes(newTypes); return(context.Document.ReplaceNodeAsync(baseList, newBaseList, context.CancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } } } }
public static bool ArgumentIsVariablePredicate(SeparatedSyntaxList <ArgumentSyntax> arguments) { if (!arguments.Any()) { return(false); } return(ArgumentIsVariablePredicate(arguments.First())); }
public static bool MethodContainingLambdaPredicate(SeparatedSyntaxList <ArgumentSyntax> arguments) { if (!arguments.Any()) { return(false); } return(arguments.First().Expression is LambdaExpressionSyntax); }
public static async Task ComputeRefactoringAsync(RefactoringContext context, InitializerExpressionSyntax initializer) { SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions; if (!expressions.Any()) { return; } if (!expressions.All(f => f.IsKind(SyntaxKind.ComplexElementInitializerExpression))) { return; } if (!(initializer.Parent is ObjectCreationExpressionSyntax objectCreationExpression)) { return; } var complexElementInitializer = (InitializerExpressionSyntax)expressions.First(); SeparatedSyntaxList <ExpressionSyntax> expressions2 = complexElementInitializer.Expressions; if (expressions2.Count != 2) { return; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); IPropertySymbol propertySymbol = FindIndexerSymbol( objectCreationExpression, expressions2, semanticModel, context.CancellationToken); if (propertySymbol == null) { return; } ITypeSymbol keyType = propertySymbol.Parameters[0].Type; ITypeSymbol valueType = propertySymbol.Type; for (int i = 1; i < expressions.Count; i++) { if (!CanRefactor(((InitializerExpressionSyntax)expressions[i]).Expressions, keyType, valueType, semanticModel)) { return; } } context.RegisterRefactoring( "Use C# 6.0 dictionary initializer", cancellationToken => RefactorAsync(context.Document, initializer, cancellationToken), RefactoringIdentifiers.UseCSharp6DictionaryInitializer); }
private static List <BaseFieldDeclarationSyntax> SplitDeclaration(BaseFieldDeclarationSyntax baseFieldDeclaration) { var fieldDeclaration = baseFieldDeclaration as FieldDeclarationSyntax; if (fieldDeclaration != null) { VariableDeclarationSyntax declaration = fieldDeclaration.Declaration; SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables; VariableDeclaratorSyntax first = variables.First(); var newFieldDeclarations = new List <BaseFieldDeclarationSyntax>(variables.Count); foreach (VariableDeclaratorSyntax variable in variables) { var variableDeclarator = SyntaxFactory.SingletonSeparatedList(variable); var newFieldDeclaration = fieldDeclaration.WithDeclaration(declaration.WithVariables(variableDeclarator)); if (variable != first) { var triviaList = newFieldDeclaration.GetLeadingTrivia().WithoutDirectiveTrivia(); newFieldDeclaration = newFieldDeclaration.WithLeadingTrivia(triviaList); } newFieldDeclarations.Add(newFieldDeclaration); } return(newFieldDeclarations); } var eventFieldDeclaration = baseFieldDeclaration as EventFieldDeclarationSyntax; if (eventFieldDeclaration != null) { VariableDeclarationSyntax declaration = eventFieldDeclaration.Declaration; SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables; var first = variables.First(); var newEventFieldDeclarations = new List <BaseFieldDeclarationSyntax>(variables.Count); foreach (VariableDeclaratorSyntax variable in variables) { var variableDeclarator = SyntaxFactory.SingletonSeparatedList(variable); var newEventFieldDeclaration = eventFieldDeclaration.WithDeclaration(declaration.WithVariables(variableDeclarator)); if (variable != first) { var triviaList = newEventFieldDeclaration.GetLeadingTrivia().WithoutDirectiveTrivia(); newEventFieldDeclaration = newEventFieldDeclaration.WithLeadingTrivia(triviaList); } newEventFieldDeclarations.Add(newEventFieldDeclaration); } return(newEventFieldDeclarations); } return(null); }
public static bool ArgumentIsIdentifierOrLiteralPredicate(SeparatedSyntaxList <ArgumentSyntax> arguments) { if (!arguments.Any()) { return(false); } var argumentsExpression = arguments.First().Expression; return(argumentsExpression is IdentifierNameSyntax || argumentsExpression is LiteralExpressionSyntax); }
protected static bool ValueIsProperty(SeparatedSyntaxList <ArgumentSyntax> arguments) { if (!arguments.Any()) { return(false); } return(arguments.First().Expression is MemberAccessExpressionSyntax valueAccess && valueAccess.Expression is IdentifierNameSyntax identifier && valueAccess.Name.Identifier.Text == "Value"); }
private static bool HasArgumentInvokingCountMethod(SeparatedSyntaxList <ArgumentSyntax> arguments) { if (!arguments.Any()) { return(false); } return(arguments.First().Expression is InvocationExpressionSyntax invocation && invocation.Expression is MemberAccessExpressionSyntax memberAccess && memberAccess.Name.Identifier.Text == nameof(Enumerable.Count) && memberAccess.Expression is IdentifierNameSyntax); }
public static void Analyze(SyntaxNodeAnalysisContext context, AssignmentExpressionSyntax assignment) { ExpressionSyntax right = assignment.Right; if (right?.IsKind(SyntaxKind.ObjectCreationExpression) == true) { var objectCreation = (ObjectCreationExpressionSyntax)right; SemanticModel semanticModel = context.SemanticModel; CancellationToken cancellationToken = context.CancellationToken; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(objectCreation, cancellationToken); if (typeSymbol != null && Symbol.IsEventHandlerOrConstructedFromEventHandlerOfT(typeSymbol, semanticModel)) { ArgumentListSyntax argumentList = objectCreation.ArgumentList; if (argumentList != null) { SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count == 1) { ArgumentSyntax argument = arguments.First(); ExpressionSyntax expression = argument.Expression; if (expression != null) { IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(expression, cancellationToken); if (methodSymbol != null) { ExpressionSyntax left = assignment.Left; if (left?.IsMissing == false && semanticModel.GetSymbol(left, cancellationToken)?.IsEvent() == true && !objectCreation.SpanContainsDirectives()) { context.ReportDiagnostic(DiagnosticDescriptors.RemoveRedundantDelegateCreation, right.GetLocation()); context.FadeOutToken(DiagnosticDescriptors.RemoveRedundantDelegateCreationFadeOut, objectCreation.NewKeyword); context.FadeOutNode(DiagnosticDescriptors.RemoveRedundantDelegateCreationFadeOut, objectCreation.Type); context.FadeOutParentheses(DiagnosticDescriptors.RemoveRedundantDelegateCreationFadeOut, objectCreation.ArgumentList); } } } } } } } }
private static bool IsListUnsorted( SeparatedSyntaxList <EnumMemberDeclarationSyntax> members, SemanticModel semanticModel, CancellationToken cancellationToken = default(CancellationToken)) { int count = members.Count; if (count > 1) { IFieldSymbol firstField = semanticModel.GetDeclaredSymbol(members.First(), cancellationToken); if (firstField?.HasConstantValue == true) { SpecialType enumSpecialType = firstField.ContainingType.EnumUnderlyingType.SpecialType; object previousValue = firstField.ConstantValue; for (int i = 1; i < count - 1; i++) { IFieldSymbol field = semanticModel.GetDeclaredSymbol(members[i], cancellationToken); if (field?.HasConstantValue != true) { return(false); } object value = field.ConstantValue; if (EnumValueComparer.GetInstance(enumSpecialType).Compare(previousValue, value) > 0) { i++; while (i < count) { if (semanticModel.GetDeclaredSymbol(members[i], cancellationToken)?.HasConstantValue != true) { return(false); } i++; } return(true); } previousValue = value; } } } return(false); }
public static VariableDeclaratorSyntax SingleVariableOrDefault(this VariableDeclarationSyntax declaration) { if (declaration == null) { throw new ArgumentNullException(nameof(declaration)); } SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables; return((variables.Count == 1) ? variables.First() : null); }
private static List <BaseFieldDeclarationSyntax> DeclarationSplitter( Document document, VariableDeclarationSyntax declaration, Func <VariableDeclarationSyntax, BaseFieldDeclarationSyntax> declarationFactory, SyntaxTriviaList declarationTrailingTrivia) { SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables; VariableDeclaratorSyntax first = variables.First(); BaseFieldDeclarationSyntax previous = null; var newFieldDeclarations = new List <BaseFieldDeclarationSyntax>(variables.Count); foreach (SyntaxNodeOrToken nodeOrToken in variables.GetWithSeparators()) { if (previous == null) { VariableDeclaratorSyntax variable = (VariableDeclaratorSyntax)nodeOrToken.AsNode(); variable = variable.WithIdentifier(variable.Identifier.WithoutLeadingWhitespace()); var variableDeclarator = SyntaxFactory.SingletonSeparatedList(variable); previous = declarationFactory(declaration.WithVariables(variableDeclarator)); if (variable != first) { var triviaList = previous.GetLeadingTrivia().WithoutDirectiveTrivia(); previous = previous.WithLeadingTrivia(triviaList); } } else { SyntaxToken commaToken = nodeOrToken.AsToken(); SyntaxTriviaList trailingTrivia = commaToken.TrailingTrivia; if (trailingTrivia.Any()) { if (!trailingTrivia.Last().IsKind(SyntaxKind.EndOfLineTrivia)) { trailingTrivia = trailingTrivia.WithoutTrailingWhitespace().Add(FormattingHelper.GetNewLineTrivia(document)); } } else { trailingTrivia = SyntaxTriviaList.Create(FormattingHelper.GetNewLineTrivia(document)); } newFieldDeclarations.Add(previous.WithTrailingTrivia(trailingTrivia)); previous = null; } } newFieldDeclarations.Add(previous.WithTrailingTrivia(declarationTrailingTrivia)); return(newFieldDeclarations); }
private static InvocationExpressionSyntax GetNewInvocation(InvocationExpressionSyntax invocation) { ExpressionSyntax expression = invocation.Expression; ArgumentListSyntax argumentList = invocation.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; ArgumentSyntax argument = arguments.First(); MemberAccessExpressionSyntax newMemberAccess = null; switch (expression.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: { ExpressionSyntax newExpression = argument.Expression .WithLeadingTrivia(expression.GetLeadingTrivia()) .Parenthesize(); newMemberAccess = SimpleMemberAccessExpression( newExpression, (SimpleNameSyntax)expression.WithoutLeadingTrivia()); break; } case SyntaxKind.SimpleMemberAccessExpression: { var memberAccess = (MemberAccessExpressionSyntax)expression; ExpressionSyntax newExpression = argument.Expression .WithTriviaFrom(memberAccess.Expression) .Parenthesize(); newMemberAccess = memberAccess.WithExpression(newExpression); break; } default: { Debug.Fail(expression.Kind().ToString()); return(invocation); } } return(invocation .WithExpression(newMemberAccess) .WithArgumentList(argumentList.WithArguments(arguments.Remove(argument)))); }
private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, DiagnosticBag diagnostics) { BoundStatement initializer; // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { ImmutableArray <BoundLocalDeclaration> unused; initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.RegularVariable, diagnostics, out unused); } else { initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); } BoundExpression condition = null; var innerLocals = ImmutableArray <LocalSymbol> .Empty; ExpressionSyntax conditionSyntax = node.Condition; if (conditionSyntax != null) { originalBinder = originalBinder.GetBinder(conditionSyntax); condition = originalBinder.BindBooleanExpression(conditionSyntax, diagnostics); innerLocals = originalBinder.GetDeclaredLocalsForScope(conditionSyntax); } BoundStatement increment = null; SeparatedSyntaxList <ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var scopeDesignator = incrementors.First(); var incrementBinder = originalBinder.GetBinder(scopeDesignator); increment = incrementBinder.WrapWithVariablesIfAny(scopeDesignator, incrementBinder.BindStatementExpressionList(incrementors, diagnostics)); } var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node)); return(new BoundForStatement(node, this.Locals, initializer, innerLocals, condition, increment, body, this.BreakLabel, this.ContinueLabel)); }
public override void VisitForStatement(ForStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); Binder binder = new ForLoopBinder(_enclosing, node); AddToMap(node, binder); VariableDeclarationSyntax declaration = node.Declaration; if (declaration != null) { VisitRankSpecifiers(declaration.Type, binder); foreach (VariableDeclaratorSyntax variable in declaration.Variables) { Visit(variable, binder); } } else { foreach (ExpressionSyntax initializer in node.Initializers) { Visit(initializer, binder); } } ExpressionSyntax condition = node.Condition; if (condition != null) { binder = new ExpressionVariableBinder(condition, binder); AddToMap(condition, binder); Visit(condition, binder); } SeparatedSyntaxList <ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var incrementorsBinder = new ExpressionListVariableBinder(incrementors, binder); AddToMap(incrementors.First(), incrementorsBinder); foreach (ExpressionSyntax incrementor in incrementors) { Visit(incrementor, incrementorsBinder); } } VisitPossibleEmbeddedStatement(node.Statement, binder); }
private string GetNames(LocalDeclarationStatementSyntax localDeclaration) { VariableDeclarationSyntax declaration = localDeclaration.Declaration; SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables; if (variables.Count == 1) { return($"'{variables.First().Identifier.ValueText}'"); } else { return(string.Join(", ", variables.Select(f => $"'{f.Identifier.ValueText}'"))); } }
private static bool IsListUnsorted( SeparatedSyntaxList <EnumMemberDeclarationSyntax> members, SemanticModel semanticModel, CancellationToken cancellationToken = default(CancellationToken)) { if (members.Any()) { IFieldSymbol firstField = semanticModel.GetDeclaredSymbol(members.First(), cancellationToken); if (firstField?.HasConstantValue == true) { object previousValue = firstField.ConstantValue; for (int i = 1; i < members.Count - 1; i++) { IFieldSymbol field = semanticModel.GetDeclaredSymbol(members[i], cancellationToken); if (field?.HasConstantValue != true) { return(false); } object value = field.ConstantValue; if (EnumMemberValueComparer.Instance.Compare(previousValue, value) > 0) { i++; while (i < members.Count) { if (semanticModel.GetDeclaredSymbol(members[i], cancellationToken)?.HasConstantValue != true) { return(false); } i++; } return(true); } previousValue = value; } } } return(false); }
private static bool ArgumentInvokesDistinctMethod(SeparatedSyntaxList <ArgumentSyntax> arguments) { if (!arguments.Any()) { return(false); } if (arguments.First().Expression is InvocationExpressionSyntax invocation) { var visitor = new FluentAssertionsCSharpSyntaxVisitor(new MemberValidator(nameof(Enumerable.Distinct))); invocation.Accept(visitor); return(visitor.IsValid(invocation) && VariableNameExtractor.ExtractVariabeName(arguments.First()) == VariableNameExtractor.ExtractVariabeName(invocation)); } return(false); }
public static async Task <bool> CanRefactorAsync(RefactoringContext context, ForStatementSyntax forStatement) { VariableDeclaratorSyntax variableDeclarator = forStatement .Declaration? .Variables .SingleOrDefault(shouldthrow: false); if (variableDeclarator != null) { ExpressionSyntax value = variableDeclarator.Initializer?.Value; if (value?.IsNumericLiteralExpression("0") == true) { ExpressionSyntax condition = forStatement.Condition; if (condition?.IsKind(SyntaxKind.LessThanExpression) == true) { ExpressionSyntax right = ((BinaryExpressionSyntax)condition).Right; if (right?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true) { var memberAccess = (MemberAccessExpressionSyntax)right; string memberName = memberAccess.Name?.Identifier.ValueText; if (memberName == "Count" || memberName == "Length") { ExpressionSyntax expression = memberAccess.Expression; if (expression != null) { SeparatedSyntaxList <ExpressionSyntax> incrementors = forStatement.Incrementors; if (incrementors.Count == 1 && incrementors.First().IsKind(SyntaxKind.PostIncrementExpression)) { return(await IsElementAccessAsync(context, forStatement, variableDeclarator, expression).ConfigureAwait(false)); } } } } } } } return(false); }
private static async Task <Document> RefactorAsync( Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken) { ExpressionSyntax expression = invocation.Expression; ArgumentListSyntax argumentList = invocation.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; ArgumentSyntax argument = arguments.First(); MemberAccessExpressionSyntax newMemberAccess = null; switch (expression.Kind()) { case SyntaxKind.IdentifierName: { newMemberAccess = SimpleMemberAccessExpression( argument.Expression.WithLeadingTrivia(expression.GetLeadingTrivia()), (SimpleNameSyntax)expression.WithoutLeadingTrivia()); break; } case SyntaxKind.SimpleMemberAccessExpression: { var memberAccess = (MemberAccessExpressionSyntax)expression; newMemberAccess = memberAccess .WithExpression(argument.Expression.WithTriviaFrom(memberAccess.Expression)); break; } default: { Debug.Assert(false, expression.Kind().ToString()); return(document); } } InvocationExpressionSyntax newInvocation = invocation .WithExpression(newMemberAccess) .WithArgumentList(argumentList.WithArguments(arguments.Remove(argument))); return(await document.ReplaceNodeAsync(invocation, newInvocation, cancellationToken).ConfigureAwait(false)); }
private static InvocationExpressionSyntax GetNewInvocationForAnalysis(InvocationExpressionSyntax invocation) { ExpressionSyntax expression = invocation.Expression; ArgumentListSyntax argumentList = invocation.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; ArgumentSyntax argument = arguments.First(); MemberAccessExpressionSyntax newMemberAccess = CreateNewMemberAccessExpression(); if (newMemberAccess == null) { return(null); } return(invocation .WithExpression(newMemberAccess) .WithArgumentList(argumentList.WithArguments(arguments.Remove(argument)))); MemberAccessExpressionSyntax CreateNewMemberAccessExpression() { switch (expression.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: { return(SimpleMemberAccessExpression( ParenthesizedExpression(argument.Expression), (SimpleNameSyntax)expression)); } case SyntaxKind.SimpleMemberAccessExpression: { var memberAccess = (MemberAccessExpressionSyntax)expression; return(memberAccess.WithExpression(ParenthesizedExpression(argument.Expression))); } default: { Debug.Fail(expression.Kind().ToString()); return(null); } } } }
public static bool SpanContainsDirectives <TNode>(this SeparatedSyntaxList <TNode> list) where TNode : SyntaxNode { if (!list.Any()) { return(false); } for (int i = 1; i < list.Count - 1; i++) { if (list[i].ContainsDirectives) { return(true); } } return(list.First().SpanOrLeadingTriviaContainsDirectives() || list.Last().SpanOrTrailingTriviaContainsDirectives()); }
private static InvocationExpressionSyntax GetNewInvocation(InvocationExpressionSyntax invocation) { ExpressionSyntax expression = invocation.Expression; ArgumentListSyntax argumentList = invocation.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; ArgumentSyntax argument = arguments.First(); MemberAccessExpressionSyntax newMemberAccess = CreateNewMemberAccessExpression(); return(invocation .WithExpression(newMemberAccess) .WithArgumentList(argumentList.WithArguments(arguments.Remove(argument)))); MemberAccessExpressionSyntax CreateNewMemberAccessExpression() { switch (expression.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: { ExpressionSyntax newExpression = argument.Expression .WithLeadingTrivia(expression.GetLeadingTrivia()) .Parenthesize(); return(SimpleMemberAccessExpression( newExpression, (SimpleNameSyntax)expression.WithoutLeadingTrivia())); } case SyntaxKind.SimpleMemberAccessExpression: { var memberAccess = (MemberAccessExpressionSyntax)expression; ExpressionSyntax newExpression = argument.Expression .WithTriviaFrom(memberAccess.Expression) .Parenthesize(); return(memberAccess.WithExpression(newExpression)); } } throw new InvalidOperationException(); } }
public static void AnalyzeInitializerExpression(SyntaxNodeAnalysisContext context) { var initializer = (InitializerExpressionSyntax)context.Node; if (!initializer.ContainsDiagnostics) { SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions; if (expressions.Any() && expressions.All(f => f.IsKind(SyntaxKind.ComplexElementInitializerExpression) && initializer.IsParentKind(SyntaxKind.ObjectCreationExpression))) { var objectCreationExpression = (ObjectCreationExpressionSyntax)initializer.Parent; var complexElementInitializer = (InitializerExpressionSyntax)expressions.First(); SeparatedSyntaxList <ExpressionSyntax> expressions2 = complexElementInitializer.Expressions; if (expressions2.Count == 2) { IPropertySymbol propertySymbol = FindIndexerSymbol( objectCreationExpression, expressions2, context.SemanticModel, context.CancellationToken); if (propertySymbol != null) { ITypeSymbol keyType = propertySymbol.Parameters[0].Type; ITypeSymbol valueType = propertySymbol.Type; if (expressions .Skip(1) .All(f => CanRefactor(((InitializerExpressionSyntax)f).Expressions, keyType, valueType, context.SemanticModel))) { context.ReportDiagnostic( DiagnosticDescriptors.UseCSharp6DictionaryInitializer, Location.Create(initializer.SyntaxTree, expressions.Span)); } } } } } }
private static Location GetLocationWithToken(TypeSyntax type, SeparatedSyntaxList<BaseTypeSyntax> baseTypes) { int start; int end; if (baseTypes.Count == 1 || baseTypes.First().Type != type) { start = type.GetFirstToken().GetPreviousToken().Span.Start; end = type.Span.End; } else { start = type.SpanStart; end = type.GetLastToken().GetNextToken().Span.End; } return Location.Create(type.SyntaxTree, new TextSpan(start, end - start)); }