Exemplo n.º 1
0
        private static void AnalyzeInvocationExpressionSyntax(SyntaxNodeAnalysisContext context, IEnumerable <INamedTypeSymbol> registeredSymbols)
        {
            var invocationExpressionSyntax = (InvocationExpressionSyntax)context.Node;

            ISymbol symbol = context.SemanticModel.GetSymbol(invocationExpressionSyntax, context.CancellationToken);

            if (symbol is null)
            {
                return;
            }

            INamedTypeSymbol containingType = symbol.ContainingType;

            foreach (var registeredSymbol in registeredSymbols)
            {
                if (containingType?.Equals(registeredSymbol) == true)
                {
                    if (symbol.Kind == SymbolKind.Method &&
                        (symbol.Name == "ToString"))
                    {
                        SeparatedSyntaxList <ArgumentSyntax> arguments = invocationExpressionSyntax.ArgumentList.Arguments;

                        if (!arguments.Any())
                        {
                            return;
                        }

                        if (!arguments.Any(e => e.Expression.TryGetInferredMemberName() == "InvariantCulture"))
                        {
                            context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
                        }
                    }
                }
            }
        }
        public static async Task ComputeRefactoringAsync(RefactoringContext context, EnumDeclarationSyntax enumDeclaration)
        {
            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            INamedTypeSymbol enumSymbol = semanticModel.GetDeclaredSymbol(enumDeclaration, context.CancellationToken);

            if (!enumSymbol.IsEnumWithFlags(semanticModel))
            {
                return;
            }

            SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members;

            if (!members.Any(f => f.EqualsValue == null))
            {
                return;
            }

            SpecialType specialType = enumSymbol.EnumUnderlyingType.SpecialType;

            List <object> values = GetExplicitValues(enumDeclaration, semanticModel, context.CancellationToken);

            Optional <object> optional = FlagsUtility.GetUniquePowerOfTwo(specialType, values);

            if (!optional.HasValue)
            {
                return;
            }

            context.RegisterRefactoring(
                "Generate enum values",
                cancellationToken => RefactorAsync(context.Document, enumDeclaration, enumSymbol, startFromHighestExistingValue: false, cancellationToken: cancellationToken),
                RefactoringIdentifiers.GenerateEnumValues);

            if (!members.Any(f => f.EqualsValue != null))
            {
                return;
            }

            Optional <object> optional2 = FlagsUtility.GetUniquePowerOfTwo(specialType, values, startFromHighestExistingValue: true);

            if (!optional2.HasValue)
            {
                return;
            }

            if (optional.Value.Equals(optional2.Value))
            {
                return;
            }

            context.RegisterRefactoring(
                $"Generate enum values (starting from {optional2.Value})",
                cancellationToken => RefactorAsync(context.Document, enumDeclaration, enumSymbol, startFromHighestExistingValue: true, cancellationToken: cancellationToken),
                RefactoringIdentifiers.GenerateEnumValues);
        }
Exemplo n.º 3
0
        public static void ComputeRefactoring(
            RefactoringContext context,
            EnumDeclarationSyntax enumDeclaration,
            SemanticModel semanticModel)
        {
            INamedTypeSymbol enumSymbol = semanticModel.GetDeclaredSymbol(enumDeclaration, context.CancellationToken);

            if (enumSymbol?.HasAttribute(MetadataNames.System_FlagsAttribute) != true)
            {
                return;
            }

            SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members;

            if (!members.Any(f => f.EqualsValue == null))
            {
                return;
            }

            ImmutableArray <ulong> values = GetExplicitValues(enumDeclaration, semanticModel, context.CancellationToken);

            Optional <ulong> optional = FlagsUtility <ulong> .Instance.GetUniquePowerOfTwo(values);

            if (!optional.HasValue)
            {
                return;
            }

            if (!ConvertHelpers.CanConvertFromUInt64(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType))
            {
                return;
            }

            Document document = context.Document;

            context.RegisterRefactoring(
                "Declare explicit values",
                ct => RefactorAsync(document, enumDeclaration, enumSymbol, values, startFromHighestExistingValue: false, cancellationToken: ct),
                RefactoringDescriptors.GenerateEnumValues);

            if (members.Any(f => f.EqualsValue != null))
            {
                Optional <ulong> optional2 = FlagsUtility <ulong> .Instance.GetUniquePowerOfTwo(values, startFromHighestExistingValue : true);

                if (optional2.HasValue &&
                    optional.Value != optional2.Value)
                {
                    context.RegisterRefactoring(
                        $"Declare explicit values (starting from {optional2.Value})",
                        ct => RefactorAsync(document, enumDeclaration, enumSymbol, values, startFromHighestExistingValue: true, cancellationToken: ct),
                        RefactoringDescriptors.GenerateEnumValues,
                        "StartFromHighestExistingValue");
                }
            }
        }
 private static bool ContainsAuthorizationAttribute(SeparatedSyntaxList <AttributeSyntax> attributes)
 {
     if (attributes.Any(x => (x.Name as IdentifierNameSyntax).Identifier.ValueText == "AllowAnonymous"))
     {
         return(true);
     }
     if (attributes.Any(x => (x.Name as IdentifierNameSyntax).Identifier.ValueText == "Authorize"))
     {
         return(true);
     }
     return(false);
 }
        public static void AnalyzeTypeParameterList(SyntaxNodeAnalysisContext context)
        {
            var typeParameterList = (TypeParameterListSyntax)context.Node;

            SeparatedSyntaxList <TypeParameterSyntax> typeParameters = typeParameterList.Parameters;

            if (!typeParameters.Any())
            {
                return;
            }

            SyntaxList <TypeParameterConstraintClauseSyntax> constraintClauses = GetConstraintClauses(typeParameterList.Parent);

            if (!constraintClauses.Any())
            {
                return;
            }

            if (constraintClauses.SpanContainsDirectives())
            {
                return;
            }

            if (!IsFixable(typeParameters, constraintClauses))
            {
                return;
            }

            context.ReportDiagnostic(
                DiagnosticDescriptors.ReorderTypeParameterConstraints,
                constraintClauses.First());
        }
        public static void Analyze(
            SyntaxNodeAnalysisContext context,
            MemberDeclarationSyntax memberDeclaration,
            SeparatedSyntaxList <TypeParameterSyntax> typeParameters)
        {
            if (typeParameters.Any(f => !f.IsMissing))
            {
                SyntaxTrivia trivia = memberDeclaration.GetSingleLineDocumentationComment();

                if (trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia))
                {
                    var comment = trivia.GetStructure() as DocumentationCommentTriviaSyntax;

                    if (comment?.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) == true)
                    {
                        var names = new HashSet <string>(DocumentationCommentRefactoring.GetNameAttributeValues(comment, "typeparam"));

                        foreach (TypeParameterSyntax typeParameter in typeParameters)
                        {
                            if (!typeParameter.IsMissing &&
                                !names.Contains(typeParameter.Identifier.ValueText))
                            {
                                context.ReportDiagnostic(
                                    DiagnosticDescriptors.AddTypeParameterToDocumentationComment,
                                    typeParameter);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        public static ParametersInfo Create(DelegateDeclarationSyntax delegateDeclaration, bool allowMissing = false)
        {
            ParameterListSyntax parameterList = delegateDeclaration.ParameterList;

            if (!Check(parameterList, allowMissing))
            {
                return(Default);
            }

            SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

            if (!CheckParameters(parameters, allowMissing))
            {
                return(Default);
            }

            TypeParameterListSyntax typeParameterList = delegateDeclaration.TypeParameterList;
            SeparatedSyntaxList <TypeParameterSyntax> typeParameters = typeParameterList?.Parameters ?? default(SeparatedSyntaxList <TypeParameterSyntax>);

            if (!CheckTypeParameters(typeParameters, allowMissing))
            {
                return(Default);
            }

            if (!parameters.Any() &&
                !typeParameters.Any())
            {
                return(Default);
            }

            return(new ParametersInfo(typeParameterList, parameterList, default(CSharpSyntaxNode)));
        }
        public static void Analyze(
            SyntaxNodeAnalysisContext context,
            MemberDeclarationSyntax memberDeclaration,
            SeparatedSyntaxList <ParameterSyntax> parameters)
        {
            if (!parameters.Any())
            {
                return;
            }

            DocumentationCommentTriviaSyntax comment = memberDeclaration.GetSingleLineDocumentationComment();

            if (comment == null)
            {
                return;
            }

            ImmutableArray <string> values = DocumentationCommentAnalysis.GetAttributeValues(comment, XmlElementKind.Param, "name");

            if (values.IsDefault)
            {
                return;
            }

            foreach (ParameterSyntax parameter in parameters)
            {
                if (!parameter.IsMissing &&
                    !values.Contains(parameter.Identifier.ValueText))
                {
                    context.ReportDiagnostic(DiagnosticDescriptors.AddParameterToDocumentationComment, parameter.Identifier);
                }
            }
        }
Exemplo n.º 9
0
        private static ForStatementSyntax CreateForStatement(
            WhileStatementSyntax whileStatement,
            VariableDeclarationSyntax declaration,
            SeparatedSyntaxList <ExpressionSyntax> initializers,
            SeparatedSyntaxList <ExpressionSyntax> incrementors)
        {
            StatementSyntax statement = whileStatement.Statement;

            if (statement?.IsKind(SyntaxKind.Block) == true)
            {
                var block = (BlockSyntax)statement;

                incrementors = SeparatedList(GetIncrementors(block));

                if (incrementors.Any())
                {
                    SyntaxList <StatementSyntax> statements = block.Statements;

                    statement = block.WithStatements(List(statements.Take(statements.Count - incrementors.Count)));
                }
            }

            return(ForStatement(
                       declaration,
                       initializers,
                       whileStatement.Condition,
                       incrementors,
                       statement));
        }
Exemplo n.º 10
0
        public static string GetName(TypeDeclarationSyntax syntax)
        {
            string valueText          = syntax.Identifier.ValueText;
            string containingTypeName = TypeNameResolver.GetContainingTypeName(syntax.Parent);

            if (!string.IsNullOrWhiteSpace(containingTypeName))
            {
                valueText = string.Concat(containingTypeName, ".", valueText);
            }
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(valueText);
            if (syntax.TypeParameterList != null)
            {
                SeparatedSyntaxList <TypeParameterSyntax> parameters = syntax.TypeParameterList.Parameters;
                if (parameters.Any())
                {
                    string str = string.Join(", ",
                                             from x in (IEnumerable <TypeParameterSyntax>) parameters
                                             select x.Identifier.ValueText);
                    stringBuilder.AppendFormat("<{0}>", str);
                }
            }
            return(stringBuilder.ToString());
        }
Exemplo n.º 11
0
        public static void ComputeRefactorings(RefactoringContext context, SwitchExpressionSyntax switchExpression)
        {
            SeparatedSyntaxList <SwitchExpressionArmSyntax> arms = switchExpression.Arms;

            if (!context.Span.IsEmptyAndContainedInSpan(switchExpression.SwitchKeyword))
            {
                return;
            }

            if (!switchExpression.IsParentKind(SyntaxKind.ReturnStatement))
            {
                return;
            }

            if (switchExpression.GoverningExpression.IsMissing)
            {
                return;
            }

            if (!arms.Any())
            {
                return;
            }

            if (!arms.All(f => f.Pattern.IsKind(SyntaxKind.ConstantPattern, SyntaxKind.DiscardPattern)))
            {
                return;
            }

            context.RegisterRefactoring(
                "Convert to 'switch' statement",
                ct => ConvertSwitchExpressionToSwitchStatement(context.Document, switchExpression, ct),
                RefactoringIdentifiers.ConvertSwitchExpressionToSwitchStatement);
        }
Exemplo n.º 12
0
        public Func <SyntaxGenerator, ClassDeclarationSyntax, ClassDeclarationSyntax> GetRemoveBaseClassAction(string baseClass)
        {
            ClassDeclarationSyntax RemoveBaseClass(SyntaxGenerator syntaxGenerator, ClassDeclarationSyntax node)
            {
                SeparatedSyntaxList <BaseTypeSyntax> currentBaseTypes = node.BaseList.Types;
                SeparatedSyntaxList <BaseTypeSyntax> newBaseTypes     = new SeparatedSyntaxList <BaseTypeSyntax>();

                foreach (var baseTypeSyntax in currentBaseTypes)
                {
                    if (!baseTypeSyntax.GetText().ToString().Trim().Equals(baseClass))
                    {
                        newBaseTypes.Add(baseTypeSyntax);
                    }
                }

                if (!newBaseTypes.Any())
                {
                    node = node.WithBaseList(null);
                }
                else
                {
                    node = node.WithBaseList(node.BaseList.WithTypes(newBaseTypes));
                }
                return(node);
            }

            return(RemoveBaseClass);
        }
        static string GenerateProperty(string typeFullName, string propertyType, string propertyName, bool readOnly, bool bindableReadOnly, Tuple <MemberVisibility, MemberVisibility, bool> overridedPropertyVisibility, SeparatedSyntaxList <ArgumentSyntax> attributes)
        {
            string getterModifier    = overridedPropertyVisibility == null ? "public " : overridedPropertyVisibility.Item2.ToCSharp(MemberVisibility.Private);
            string setterModifier    = overridedPropertyVisibility == null ? (readOnly ? "private " : "") : overridedPropertyVisibility.Item1.ToCSharp(overridedPropertyVisibility.Item2);
            var    nonBrowsable      = overridedPropertyVisibility != null && overridedPropertyVisibility.Item3;
            var    withDXDescription = attributes.Any(x => x.ToString() == "DXDescription");
            string attributesString  =
                (nonBrowsable ? "[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]\r\n" : "") +
                (withDXDescription ? $"[DXDescription(\"{typeFullName},{propertyName}\")]\r\n" : "") +
                string.Concat(attributes.Select(attribute => {
                if (attribute.ToString() == "DXDescription")
                {
                    return(null);
                }
                var attributeExpression = attribute.Expression as InvocationExpressionSyntax;
                if (attributeExpression == null)
                {
                    return(null);
                }
                return("[" + attributeExpression.ToString() + "]\r\n");
            }));
            string setterAttributes = bindableReadOnly && !nonBrowsable ? "[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]\r\n    " : string.Empty;
            string keySuffix        = readOnly ? "Key" : "";

            return
                ($@"{attributesString}{getterModifier}{propertyType} {propertyName} {{
    get {{ return ({propertyType})GetValue({propertyName}Property); }}
    {setterAttributes}{setterModifier}set {{ SetValue({propertyName}Property{keySuffix}, value); }}
}}
");
        }
Exemplo n.º 14
0
        public static AnalysisResult Analyze(InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            ArgumentListSyntax argumentList = invocationExpression.ArgumentList;

            if (argumentList != null)
            {
                SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

                if (arguments.Any())
                {
                    if (arguments.Count > 1 ||
                        !(arguments[0].Expression is LiteralExpressionSyntax))
                    {
                        MethodInfo methodInfo;
                        if (semanticModel.TryGetMethodInfo(invocationExpression, out methodInfo, cancellationToken) &&
                            methodInfo.Symbol.IsNonReducedExtensionMethod())
                        {
                            InvocationExpressionSyntax newInvocationExpression = GetNewInvocation(invocationExpression);

                            if (semanticModel
                                .GetSpeculativeMethodSymbol(invocationExpression.SpanStart, newInvocationExpression)?
                                .ReducedFromOrSelf()
                                .Equals(methodInfo.ConstructedFrom) == true)
                            {
                                return(new AnalysisResult(invocationExpression, newInvocationExpression, methodInfo.Symbol));
                            }
                        }
                    }
                }
            }

            return(default(AnalysisResult));
        }
        public static bool IsApplicableSpan(InitializerExpressionSyntax initializer, TextSpan span)
        {
            SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions;

            if (!expressions.Any())
            {
                return(true);
            }

            if (span.IsEmpty)
            {
                if (expressions.Count == expressions.SeparatorCount &&
                    TextSpan.FromBounds(expressions.GetSeparator(expressions.Count - 1).Span.End, initializer.CloseBraceToken.SpanStart).Contains(span))
                {
                    return(true);
                }

                TextSpan span2 = TextSpan.FromBounds(expressions.Last().Span.End, initializer.CloseBraceToken.SpanStart);

                if (span2.Length > 0)
                {
                    span2 = new TextSpan(span2.Start + 1, span2.Length - 1);

                    if (span2.Contains(span))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 16
0
        public static SelectionResult Create <TNode>(SeparatedSyntaxList <TNode> nodes, TextSpan span, int minCount, int maxCount) where TNode : SyntaxNode
        {
            ThrowIfNotValidRange(minCount, maxCount);

            if (!nodes.Any())
            {
                return(Fail);
            }

            if (span.IsEmpty)
            {
                return(Fail);
            }

            SelectionResult result = Create(nodes, span);

            if (!result.Success)
            {
                return(Fail);
            }

            if (!result.IsInRange(minCount, maxCount))
            {
                return(Fail);
            }

            return(result);
        }
        public void SeparatedSyntaxList_Empty()
        {
            var list = new SeparatedSyntaxList <NameExpressionSyntax>(new SyntaxNodeOrToken[0]);

            Assert.Equal(0, list.Count);
            Assert.False(list.Any());
        }
Exemplo n.º 18
0
 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));
 }
        public static void Analyze(
            SyntaxNodeAnalysisContext context,
            MemberDeclarationSyntax memberDeclaration,
            SeparatedSyntaxList <TypeParameterSyntax> typeParameters)
        {
            if (typeParameters.Any())
            {
                DocumentationCommentTriviaSyntax comment = memberDeclaration.GetSingleLineDocumentationComment();

                if (comment != null)
                {
                    ImmutableArray <string> values = DocumentationCommentAnalysis.GetAttributeValues(comment, "typeparam", "TYPEPARAM", "name");

                    if (!values.IsDefault)
                    {
                        foreach (TypeParameterSyntax typeParameter in typeParameters)
                        {
                            if (!typeParameter.IsMissing &&
                                !values.Contains(typeParameter.Identifier.ValueText))
                            {
                                context.ReportDiagnostic(
                                    DiagnosticDescriptors.AddTypeParameterToDocumentationComment,
                                    typeParameter.Identifier);
                            }
                        }
                    }
                }
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, InitializerExpressionSyntax initializer)
        {
            if (initializer.IsKind(SyntaxKind.ComplexElementInitializerExpression) &&
                initializer.IsParentKind(SyntaxKind.CollectionInitializerExpression))
            {
                initializer = (InitializerExpressionSyntax)initializer.Parent;
            }

            if (context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(initializer) ||
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(initializer.Expressions))
            {
                SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions;

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.FormatInitializer) &&
                    expressions.Any() &&
                    !initializer.IsKind(SyntaxKind.ComplexElementInitializerExpression) &&
                    initializer.IsParentKind(
                        SyntaxKind.ArrayCreationExpression,
                        SyntaxKind.ImplicitArrayCreationExpression,
                        SyntaxKind.ObjectCreationExpression,
                        SyntaxKind.CollectionInitializerExpression))
                {
                    if (initializer.IsSingleLine(includeExteriorTrivia: false))
                    {
                        context.RegisterRefactoring(
                            "Format initializer on multiple lines",
                            cancellationToken => SyntaxFormatter.ToMultiLineAsync(
                                context.Document,
                                initializer,
                                cancellationToken),
                            RefactoringIdentifiers.FormatInitializer);
                    }
                    else if (expressions.All(expression => expression.IsSingleLine()) &&
                             initializer.DescendantTrivia(initializer.Span).All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                    {
                        context.RegisterRefactoring(
                            "Format initializer on a single line",
                            cancellationToken => SyntaxFormatter.ToSingleLineAsync(
                                context.Document,
                                initializer,
                                cancellationToken),
                            RefactoringIdentifiers.FormatInitializer);
                    }
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandInitializer))
                {
                    await ExpandInitializerRefactoring.ComputeRefactoringsAsync(context, initializer).ConfigureAwait(false);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseCSharp6DictionaryInitializer) &&
                    context.SupportsCSharp6)
                {
                    await UseCSharp6DictionaryInitializerRefactoring.ComputeRefactoringAsync(context, initializer).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 21
0
        public static bool ArgumentIsVariablePredicate(SeparatedSyntaxList <ArgumentSyntax> arguments)
        {
            if (!arguments.Any())
            {
                return(false);
            }

            return(ArgumentIsVariablePredicate(arguments.First()));
        }
        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 not ObjectCreationExpressionSyntax objectCreationExpression)
            {
                return;
            }

            var complexElementInitializer = (InitializerExpressionSyntax)expressions[0];

            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 index initializer",
                ct => RefactorAsync(context.Document, initializer, ct),
                RefactoringDescriptors.UseIndexInitializer);
        }
Exemplo n.º 23
0
        public static bool MethodContainingLambdaPredicate(SeparatedSyntaxList <ArgumentSyntax> arguments)
        {
            if (!arguments.Any())
            {
                return(false);
            }

            return(arguments.First().Expression is LambdaExpressionSyntax);
        }
        private static bool CanExpand(
            InitializerExpressionSyntax initializer,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            var objectCreationExpression = (ObjectCreationExpressionSyntax)initializer.Parent;

            if (objectCreationExpression.Type != null)
            {
                ExpressionSyntax expression = initializer.Expressions[0];

                if (expression.IsKind(SyntaxKind.SimpleAssignmentExpression))
                {
                    var assignment = (AssignmentExpressionSyntax)expression;

                    ExpressionSyntax left = assignment.Left;

                    if (left.IsKind(SyntaxKind.ImplicitElementAccess))
                    {
                        var implicitElementAccess = (ImplicitElementAccessSyntax)left;

                        BracketedArgumentListSyntax argumentList = implicitElementAccess.ArgumentList;

                        if (argumentList?.Arguments.Any() == true)
                        {
                            return(HasPublicWritableIndexer(
                                       argumentList.Arguments[0].Expression,
                                       objectCreationExpression,
                                       semanticModel,
                                       cancellationToken));
                        }
                    }
                    else
                    {
                        return(true);
                    }
                }
                else if (expression.IsKind(SyntaxKind.ComplexElementInitializerExpression))
                {
                    var initializerExpression = (InitializerExpressionSyntax)expression;

                    SeparatedSyntaxList <ExpressionSyntax> expressions = initializerExpression.Expressions;

                    if (expressions.Any())
                    {
                        return(HasPublicWritableIndexer(expressions[0], objectCreationExpression, semanticModel, cancellationToken));
                    }
                }
                else
                {
                    return(HasPublicAddMethod(expression, objectCreationExpression, semanticModel, cancellationToken));
                }
            }

            return(false);
        }
Exemplo n.º 25
0
        public static Task <Document> RefactorAsync(
            Document document,
            ForStatementSyntax forStatement,
            CancellationToken cancellationToken)
        {
            var statements = new List <StatementSyntax>();

            VariableDeclarationSyntax declaration = forStatement.Declaration;

            if (declaration != null)
            {
                statements.Add(LocalDeclarationStatement(declaration));
            }
            else
            {
                foreach (ExpressionSyntax initializer in forStatement.Initializers)
                {
                    statements.Add(ExpressionStatement(initializer));
                }
            }

            StatementSyntax statement = forStatement.Statement ?? Block();

            SeparatedSyntaxList <ExpressionSyntax> incrementors = forStatement.Incrementors;

            if (incrementors.Any())
            {
                if (!statement.IsKind(SyntaxKind.Block))
                {
                    statement = Block(statement);
                }

                ExpressionStatementSyntax[] incrementorStatements = incrementors
                                                                    .Select(f => ExpressionStatement(f).WithFormatterAnnotation())
                                                                    .ToArray();

                var rewriter = new InsertIncrementorsBeforeContinueRewriter(incrementorStatements);

                statement = (StatementSyntax)rewriter.Visit(statement);

                statement = ((BlockSyntax)statement).AddStatements(incrementorStatements);
            }

            statements.Add(WhileStatement(forStatement.Condition ?? TrueLiteralExpression(), statement));

            statements[0] = statements[0].WithLeadingTrivia(forStatement.GetLeadingTrivia());

            if (forStatement.IsEmbedded())
            {
                return(document.ReplaceNodeAsync(forStatement, Block(statements), cancellationToken));
            }
            else
            {
                return(document.ReplaceNodeAsync(forStatement, statements, cancellationToken));
            }
        }
Exemplo n.º 26
0
 private Doc PrintArgumentListLikeSyntax(
     SyntaxToken openParenToken,
     SeparatedSyntaxList <ArgumentSyntax> arguments,
     SyntaxToken closeParenToken) =>
 Concat(
     this.PrintSyntaxToken(openParenToken),
     arguments.Any()
             ? Indent(
         SoftLine,
         this.PrintSeparatedSyntaxList(
             arguments,
             this.PrintArgumentSyntax,
             Line
             )
         )
             : Doc.Null,
     arguments.Any() ? SoftLine : Doc.Null,
     this.PrintSyntaxToken(closeParenToken)
     );
            private static bool MathodContainingArgumentInvokingLambda(SeparatedSyntaxList <ArgumentSyntax> arguments)
            {
                if (!arguments.Any())
                {
                    return(false);
                }

                return(arguments[0].Expression is InvocationExpressionSyntax invocation &&
                       MemberValidator.MethodContainingLambdaPredicate(invocation.ArgumentList.Arguments));
            }
Exemplo n.º 28
0
        public static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext context)
        {
            var localDeclaration = (LocalDeclarationStatementSyntax)context.Node;

            SemanticModel     semanticModel     = context.SemanticModel;
            CancellationToken cancellationToken = context.CancellationToken;

            if (!localDeclaration.IsConst)
            {
                StatementContainer container;
                if (StatementContainer.TryCreate(localDeclaration, out container))
                {
                    SyntaxList <StatementSyntax> statements = container.Statements;

                    if (statements.Count > 1)
                    {
                        int index = statements.IndexOf(localDeclaration);

                        if (index < statements.Count - 1)
                        {
                            VariableDeclarationSyntax variableDeclaration = localDeclaration.Declaration;

                            if (variableDeclaration?.IsMissing == false)
                            {
                                SeparatedSyntaxList <VariableDeclaratorSyntax> variables = variableDeclaration.Variables;

                                if (variables.Any())
                                {
                                    TypeSyntax  type       = variableDeclaration.Type;
                                    ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken);

                                    if (typeSymbol?.SupportsConstantValue() == true &&
                                        variables.All(variable => HasConstantValue(variable.Initializer?.Value, typeSymbol, semanticModel, cancellationToken)))
                                    {
                                        TextSpan span = TextSpan.FromBounds(statements[index + 1].Span.Start, statements.Last().Span.End);
                                        IEnumerable <SyntaxNode> nodes = container.Node.DescendantNodes(span);

                                        if (!IsAnyVariableInvalidOrAssigned(
                                                variables,
                                                nodes,
                                                semanticModel,
                                                cancellationToken))
                                        {
                                            context.ReportDiagnostic(
                                                DiagnosticDescriptors.MarkLocalVariableAsConst,
                                                type);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
        public static bool ArgumentIsIdentifierOrLiteralPredicate(SeparatedSyntaxList <ArgumentSyntax> arguments)
        {
            if (!arguments.Any())
            {
                return(false);
            }

            var argumentsExpression = arguments.First().Expression;

            return(argumentsExpression is IdentifierNameSyntax || argumentsExpression is LiteralExpressionSyntax);
        }
            private static bool HaveCountArgumentsValidator(SeparatedSyntaxList <ArgumentSyntax> arguments)
            {
                if (!arguments.Any())
                {
                    return(false);
                }

                return(arguments[0].Expression is LiteralExpressionSyntax literal &&
                       literal.Token.Value is int argument &&
                       argument == 0);
            }