static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as ArrayCreationExpressionSyntax;
            var arrayType = node?.Type;

            if (arrayType == null)
                return false;

            if (node.Initializer == null)
                return false;

            var rs = arrayType.RankSpecifiers;
            if (rs.Count != 1 || rs[0].Sizes.Count != 1)
                return false;

            var intSizeValue = nodeContext.SemanticModel.GetConstantValue(arrayType.RankSpecifiers[0].Sizes[0]);
            if (!intSizeValue.HasValue || !(intSizeValue.Value is int))
                return false;

            var size = (int)intSizeValue.Value;
            if (size <= -1)
                return false;
            
            if (node.Initializer.Expressions.Count == size)
            {
                diagnostic = Diagnostic.Create(descriptor, arrayType.RankSpecifiers[0].Sizes[0].GetLocation());
                return true;
            }

            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as ConditionalExpressionSyntax;

            bool? trueBranch = SimplifyConditionalTernaryExpressionCodeFixProvider.GetBool(node.WhenTrue.SkipParens());
            bool? falseBranch = SimplifyConditionalTernaryExpressionCodeFixProvider.GetBool(node.WhenFalse.SkipParens());

            if (trueBranch == falseBranch ||
                trueBranch == true && falseBranch == false) // Handled by RedundantTernaryExpressionIssue
                return false;

            var typeTrue = nodeContext.SemanticModel.GetTypeInfo(node.WhenTrue);
            var typeFalse = nodeContext.SemanticModel.GetTypeInfo(node.WhenFalse);
            if (typeTrue.Type == null || typeTrue.Type.SpecialType != SpecialType.System_Boolean ||
                typeFalse.Type == null || typeFalse.Type.SpecialType != SpecialType.System_Boolean)
                return false;


            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
            );
            return true;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            var node = nodeContext.Node as InvocationExpressionSyntax;
            var semanticModel = nodeContext.SemanticModel;
            var cancellationToken = nodeContext.CancellationToken;

            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var memberReference = node.Expression as MemberAccessExpressionSyntax;
            if (memberReference == null)
                return false;
            var firstArgument = node.ArgumentList.Arguments.FirstOrDefault();
            if (firstArgument == null || firstArgument.Expression.IsKind(SyntaxKind.NullLiteralExpression))
                return false;
            var expressionSymbol = semanticModel.GetSymbolInfo(node.Expression).Symbol as IMethodSymbol;
            //ignore non-extensions and reduced extensions (so a.Ext, as opposed to B.Ext(a))
            if (expressionSymbol == null || !expressionSymbol.IsExtensionMethod || expressionSymbol.MethodKind == MethodKind.ReducedExtension)
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                memberReference.Name.GetLocation()
            );
            return true;
        }
        void Check(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax condition)
        {
            if (nodeContext.IsFromGeneratedCode())
                return;

            if (condition.IsKind(SyntaxKind.TrueLiteralExpression) || condition.IsKind(SyntaxKind.FalseLiteralExpression))
                return;

            var resolveResult = nodeContext.SemanticModel.GetConstantValue(condition);
            if (!resolveResult.HasValue || !(resolveResult.Value is bool))
                return;

            var value = (bool)resolveResult.Value;

            nodeContext.ReportDiagnostic(Diagnostic.Create(
                descriptor.Id,
                descriptor.Category,
                string.Format(descriptor.MessageFormat.ToString(), value),
                descriptor.DefaultSeverity,
                descriptor.DefaultSeverity,
                descriptor.IsEnabledByDefault,
                4,
                descriptor.Title,
                descriptor.Description,
                descriptor.HelpLinkUri,
                condition.GetLocation(),
                null,
                new[] { value.ToString() }
            ));
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as FieldDeclarationSyntax;
            if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword)))
                return false;

            foreach (var attributeLists in node.AttributeLists)
            {
                foreach (var attribute in attributeLists.Attributes)
                {
                    var attrSymbol = nodeContext.SemanticModel.GetTypeInfo(attribute).Type;
                    if (attrSymbol == null)
                        continue;
                    if (attrSymbol.Name == "ThreadStaticAttribute" && attrSymbol.ContainingNamespace.Name == "System")
                    {
                        diagnostic = Diagnostic.Create(
                            descriptor,
                            attribute.GetLocation()
                        );
                        return true;
                    }
                }
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as MethodDeclarationSyntax;

            if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.OverrideKeyword)))
                return false;
            var lastParam = node.ParameterList.Parameters.LastOrDefault();
            if (lastParam == null || lastParam.Modifiers.Any(m => m.IsKind(SyntaxKind.ParamsKeyword)))
                return false;
            if (lastParam.Type == null || !lastParam.Type.IsKind(SyntaxKind.ArrayType))
                return false;
            var rr = nodeContext.SemanticModel.GetDeclaredSymbol(node);
            if (rr == null || !rr.IsOverride)
                return false;
            var baseMember = rr.OverriddenMethod;
            if (baseMember == null || baseMember.Parameters.Length == 0 || !baseMember.Parameters.Last().IsParams)
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                lastParam.GetLocation(),
                baseMember.Name
            );
            return true;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var options = nodeContext.SemanticModel.SyntaxTree.Options as VisualBasicParseOptions;
            if (options != null && options.LanguageVersion < LanguageVersion.VisualBasic14)
                return false;

            var objectCreateExpression = nodeContext.Node as ObjectCreationExpressionSyntax;

            ExpressionSyntax paramNode;
            if (!CheckExceptionType(nodeContext.SemanticModel, objectCreateExpression, out paramNode))
                return false;
            var paramName = GetArgumentParameterName(paramNode);
            if (paramName == null)
                return false;

            var validNames = GetValidParameterNames(objectCreateExpression);

            if (!validNames.Contains(paramName))
                return false;

            diagnostic = Diagnostic.Create(descriptor, paramNode.GetLocation(), paramName);
            return true;
        }
        private static bool TryGetRedundantNullableDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var objectCreation = nodeContext.Node as ObjectCreationExpressionSyntax;
            if (objectCreation == null)
                return false;

            // No Nullable, but "var"
            var parentVarDeclaration = objectCreation?.Parent?.Parent?.Parent as VariableDeclarationSyntax;
            if (parentVarDeclaration != null && parentVarDeclaration.Type.IsVar)
                return false;

            var objectCreationSymbol = nodeContext.SemanticModel.GetTypeInfo(objectCreation);
            if (objectCreationSymbol.Type != null && objectCreationSymbol.Type.IsNullableType())
            {
                var creationTypeLocation = objectCreation.Type.GetLocation();
                var newKeywordLocation = objectCreation.NewKeyword.GetLocation();
                diagnostic = Diagnostic.Create(descriptor, newKeywordLocation, (IEnumerable<Location>) (new[] { creationTypeLocation }));
                return true;
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as LiteralExpressionSyntax;
            if (!(node.Token.Value is long || node.Token.Value is ulong))
                return false;

            var literal = node.Token.Text;
            if (literal.Length < 2)
                return false;

            char prevChar = literal[literal.Length - 2];
            char lastChar = literal[literal.Length - 1];

            if (prevChar == 'u' || prevChar == 'U') //ul/Ul is not confusing
                return false;

            if (lastChar == 'l' || prevChar == 'l')
            {
                diagnostic = Diagnostic.Create(
                    descriptor,
                    node.GetLocation()
                );
                return true;
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            var node = nodeContext.Node as InvocationExpressionSyntax;
            var semanticModel = nodeContext.SemanticModel;
            var cancellationToken = nodeContext.CancellationToken;

            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var memberReference = node.Expression as MemberAccessExpressionSyntax;
            if (memberReference == null)
                return false;
            var firstArgument = node.ArgumentList.Arguments.FirstOrDefault();
            if (firstArgument == null || firstArgument.Expression.IsKind(SyntaxKind.NullLiteralExpression))
                return false;
            var expressionSymbol = semanticModel.GetSymbolInfo(node.Expression).Symbol as IMethodSymbol;
            // Ignore non-extensions and reduced extensions (so a.Ext, as opposed to B.Ext(a))
            if (expressionSymbol == null || !expressionSymbol.IsExtensionMethod || expressionSymbol.MethodKind == MethodKind.ReducedExtension)
                return false;

            // Don't allow conversion if first parameter is a method name instead of variable (extension method on delegate type)
            var firstParameter = node.ArgumentList?.Arguments.FirstOrDefault();
            if ((firstParameter != null) && (firstParameter.Expression is IdentifierNameSyntax))
            {
                var extensionMethodTargetExpression = semanticModel.GetSymbolInfo(firstParameter.Expression).Symbol as IMethodSymbol;
                if (extensionMethodTargetExpression != null)
                    return false;
            }

            diagnostic = Diagnostic.Create(
                descriptor,
                memberReference.Name.GetLocation()
            );
            return true;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            var node = nodeContext.Node as ClassDeclarationSyntax;
            var semanticModel = nodeContext.SemanticModel;
            var cancellationToken = nodeContext.CancellationToken;

            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            ITypeSymbol classType = semanticModel.GetDeclaredSymbol(node);
            if (!node.Modifiers.Any() || node.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword)) || classType.IsAbstract || classType.IsStatic)
                return false;
            if ((node.BaseList != null) && node.BaseList.Types.Any())
                return false;
            IEnumerable<ISymbol> members = classType.GetMembers().Where(m => !(m is ITypeSymbol));
            if (!members.Any(m => !m.IsImplicitlyDeclared)) // Ignore implicitly declared (e.g. default ctor)
                return false;
            if (Enumerable.Any(members, f => (!f.IsStatic && !f.IsImplicitlyDeclared) || (f is IMethodSymbol && IsMainMethod((IMethodSymbol)f))))
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                node.Identifier.GetLocation()
            );
            return true;
        }
 static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
 {
     diagnostic = default(Diagnostic);
     if (nodeContext.IsFromGeneratedCode())
         return false;
     var assignment = nodeContext.Node as AssignmentExpressionSyntax;
     if (assignment != null)
     {
         if (IsDelegate(nodeContext.SemanticModel, assignment.Left) && IsDelegate(nodeContext.SemanticModel, assignment.Right))
         {
             diagnostic = Diagnostic.Create(
                 descriptor,
                 assignment.GetLocation()
             );
             return true;
         }
     }
     var binex = nodeContext.Node as BinaryExpressionSyntax;
     if (binex != null)
     {
         if (IsDelegate(nodeContext.SemanticModel, binex.Left) && IsDelegate(nodeContext.SemanticModel, binex.Right))
         {
             diagnostic = Diagnostic.Create(
                 descriptor,
                 binex.GetLocation()
             );
             return true;
         }
     }
     return false;
 }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var node = nodeContext.Node as BinaryExpressionSyntax;
            var left = node.Left.SkipParens();
            var right = node.Right.SkipParens();
            ExpressionSyntax expr = null, highlightExpr = null;
            if (left.IsKind(SyntaxKind.NullLiteralExpression))
            {
                expr = right;
                highlightExpr = node.Left;
            }
            if (right.IsKind(SyntaxKind.NullLiteralExpression))
            {
                expr = left;
                highlightExpr = node.Right;
            }
            if (expr == null)
                return false;
            var type = nodeContext.SemanticModel.GetTypeInfo(expr).Type;
            if ((type == null) || (type.TypeKind != TypeKind.TypeParameter) || type.IsReferenceType)
                return false;
            diagnostic = Diagnostic.Create(
                descriptor,
                highlightExpr.GetLocation()
            );
            return true;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            var node = nodeContext.Node as IfStatementSyntax;
            var semanticModel = nodeContext.SemanticModel;
            var cancellationToken = nodeContext.CancellationToken;

            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            if (node.Parent is IfStatementSyntax || node.Parent is ElseClauseSyntax)
                return false;

            var switchExpr = GetSwitchExpression(semanticModel, node.Condition);
            if (switchExpr == null)
                return false;
            var switchSections = new List<SwitchSectionSyntax>();
            if (!CollectSwitchSections(switchSections, semanticModel, node, switchExpr))
                return false;
            if (switchSections.Count(s => !s.Labels.OfType<DefaultSwitchLabelSyntax>().Any()) <= 2)
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                node.IfKeyword.GetLocation()
            );
            return true;
        }
 static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
 {
     diagnostic = default(Diagnostic);
     if (nodeContext.IsFromGeneratedCode())
         return false;
     var node = nodeContext.Node as ParameterSyntax;
     if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.RefKeyword) || m.IsKind(SyntaxKind.OutKeyword)))
         return false;
     foreach (var attributeLists in node.AttributeLists)
     {
         foreach (var attribute in attributeLists.Attributes)
         {
             var attrSymbol = nodeContext.SemanticModel.GetTypeInfo(attribute).Type;
             if (attrSymbol == null)
                 continue;
             if (attrSymbol.Name == "OptionalAttribute" && attrSymbol.ContainingNamespace.Name == "InteropServices")
             {
                 diagnostic = Diagnostic.Create(
                     descriptor,
                     node.GetLocation()
                 );
                 return true;
             }
         }
     }
     return false;
 }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var anyInvoke = nodeContext.Node as InvocationExpressionSyntax;

            var info = nodeContext.SemanticModel.GetSymbolInfo(anyInvoke);

            IMethodSymbol anyResolve = info.Symbol as IMethodSymbol;
            if (anyResolve == null)
            {
                anyResolve = info.CandidateSymbols.OfType<IMethodSymbol>().FirstOrDefault(candidate => HasPredicateVersion(candidate));
            }

            if (anyResolve == null || !HasPredicateVersion(anyResolve))
                return false;

            ExpressionSyntax target, followUp;
            TypeSyntax type;
            ParameterSyntax param;
            if (ReplaceWithOfTypeAnyAnalyzer.MatchSelect(anyInvoke, out target, out type, out param, out followUp))
            {
                // if (member == "Where" && followUp == null) return;
                diagnostic = Diagnostic.Create(
                    descriptor,
                    anyInvoke.GetLocation()
                );
                return true;
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var node = nodeContext.Node as PrefixUnaryExpressionSyntax;

            if (node.IsKind(SyntaxKind.LogicalNotExpression))
            {
                var innerUnaryOperatorExpr = node.Operand.SkipParens() as PrefixUnaryExpressionSyntax;
                if (innerUnaryOperatorExpr == null || !innerUnaryOperatorExpr.IsKind(SyntaxKind.LogicalNotExpression))
                    return false;
                diagnostic = Diagnostic.Create(descriptor, node.GetLocation());
                return true;

            }

            if (node.IsKind(SyntaxKind.BitwiseNotExpression))
            {
                var innerUnaryOperatorExpr = node.Operand.SkipParens() as PrefixUnaryExpressionSyntax;
                if (innerUnaryOperatorExpr == null || !innerUnaryOperatorExpr.IsKind(SyntaxKind.BitwiseNotExpression))
                    return false;
                diagnostic = Diagnostic.Create(descriptor, node.GetLocation());
                return true;
            }
            return false;
        }
        //I think it's a better decision to head in this direction instead of MethodDeclaration.
        private static bool TryGetParamsDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var paramList = nodeContext.Node as ParameterListSyntax;
            var declaration = paramList?.Parent as MethodDeclarationSyntax;

            if (declaration == null)
                return false;

            if (declaration.Modifiers.Count == 0 || !declaration.Modifiers.Any(SyntaxKind.OverrideKeyword))
                return false;

            var lastParam = declaration.ParameterList.Parameters.LastOrDefault();
            SyntaxToken? paramsModifierToken = null;
            if (lastParam == null)
                return false;

            foreach (var x in lastParam.Modifiers)
            {
                if (x.IsKind(SyntaxKind.ParamsKeyword))
                {
                    paramsModifierToken = x;
                    break;
                }
            }

            if (!paramsModifierToken.HasValue)
                return false;

            diagnostic = Diagnostic.Create(descriptor, paramsModifierToken.Value.GetLocation());
            return true;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            InitializerExpressionSyntax initializer = null;
            var node = nodeContext.Node as ArrayCreationExpressionSyntax;
            if (node != null) initializer = node.Initializer;
            var inode = nodeContext.Node as ImplicitArrayCreationExpressionSyntax;
            if (inode != null) initializer = inode.Initializer;

            if (initializer == null)
                return false;
            var varInitializer = nodeContext.Node.Parent.Parent;
            if (varInitializer == null)
                return false;
            var variableDeclaration = varInitializer.Parent as VariableDeclarationSyntax;
            if (variableDeclaration != null)
            {
                if (!variableDeclaration.Type.IsKind(SyntaxKind.ArrayType))
                    return false;
                diagnostic = Diagnostic.Create(
                    descriptor,
                    Location.Create(nodeContext.SemanticModel.SyntaxTree, TextSpan.FromBounds((node != null ? node.NewKeyword : inode.NewKeyword).Span.Start, initializer.Span.Start))
                );
                return true;
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as ConditionalExpressionSyntax;

            //pattern is Any(param) ? Last(param) : null/default
            var anyInvocation = node.Condition as InvocationExpressionSyntax;
            var lastInvocation = node.WhenTrue as InvocationExpressionSyntax;
            var nullDefaultWhenFalse = node.WhenFalse;

            if (anyInvocation == null || lastInvocation == null || nullDefaultWhenFalse == null)
                return false;
            var anyExpression = anyInvocation.Expression as MemberAccessExpressionSyntax;
            if (anyExpression == null || anyExpression.Name.Identifier.ValueText != "Any")
                return false;
            var anyParam = anyInvocation.ArgumentList;

            var lastExpression = lastInvocation.Expression as MemberAccessExpressionSyntax;
            if (lastExpression == null || lastExpression.Name.Identifier.ValueText != "Last" || !lastInvocation.ArgumentList.IsEquivalentTo(anyParam))
                return false;

            if (!nullDefaultWhenFalse.IsKind(SyntaxKind.NullLiteralExpression) && !nullDefaultWhenFalse.IsKind(SyntaxKind.DefaultExpression))
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
            );
            return true;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as CatchClauseSyntax;
            if (node.Declaration != null)
            {
                var type = node.Declaration.Type;
                if (type != null)
                {
                    var typeSymbol = nodeContext.SemanticModel.GetTypeInfo(type).Type;
                    if (typeSymbol == null || typeSymbol.TypeKind == TypeKind.Error || !typeSymbol.GetFullName().Equals("System.Exception"))
                        return false;
                }
            }

            // Don't consider a catch clause with "when (...)" as general
            if (node.Filter != null)
                return false;

            BlockSyntax body = node.Block;
            if (body.Statements.Any())
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                node.CatchKeyword.GetLocation()
            );

            return true;
        }
        private static bool TryGetUnusedLocalVariableDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var method = nodeContext.Node as MethodDeclarationSyntax;
            if ((method == null) || (method.Body == null))
                return false;

            var dataFlow = nodeContext.SemanticModel.AnalyzeDataFlow(method.Body);
            
            var variablesDeclared = dataFlow.VariablesDeclared;
            var variablesRead = dataFlow.ReadInside.Union(dataFlow.ReadOutside);
            var unused = variablesDeclared.Except(variablesRead).Except(dataFlow.WrittenInside).ToArray();

            if (unused.Any())
            {
                foreach (var unusedVar in unused)
                {
                   
                    diagnostic = Diagnostic.Create(descriptor, unusedVar.Locations.First());
                    return true;
                }
            }
            return false;
        }
 static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
 {
     diagnostic = default(Diagnostic);
     if (nodeContext.IsFromGeneratedCode())
         return false;
     var node = nodeContext.Node as IfStatementSyntax;
     ExpressionSyntax target;
     SyntaxTriviaList assignmentTrailingTriviaList;
     if (ConvertIfToOrExpressionAnalyzer.MatchIfElseStatement(node, SyntaxKind.FalseLiteralExpression, out target, out assignmentTrailingTriviaList))
     {
         var varDeclaration = ConvertIfToOrExpressionAnalyzer.FindPreviousVarDeclaration(node);
         if (varDeclaration != null)
         {
             var targetIdentifier = target as IdentifierNameSyntax;
             if (targetIdentifier == null)
                 return false;
             var declaredVarName = varDeclaration.Declaration.Variables.First().Identifier.Value;
             var assignedVarName = targetIdentifier.Identifier.Value;
             if (declaredVarName != assignedVarName)
                 return false;
             if (!ConvertIfToOrExpressionAnalyzer.CheckTarget(targetIdentifier, node.Condition))
                 return false;
             diagnostic = Diagnostic.Create(descriptor, node.IfKeyword.GetLocation(), GettextCatalog.GetString("Convert to '&&' expression"));
             return true;
         }
         else
         {
             if (!ConvertIfToOrExpressionAnalyzer.CheckTarget(target, node.Condition))
                 return false;
             diagnostic = Diagnostic.Create(descriptor, node.IfKeyword.GetLocation(), GettextCatalog.GetString("Replace with '&='"));
             return true;
         }
     }
     return false;
 }
        private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var localDeclarationUnused = nodeContext.Node as LocalDeclarationStatementSyntax;
            var body = localDeclarationUnused?.Parent as BlockSyntax;
            if (body == null)
                return false;

            var dataFlow = nodeContext.SemanticModel.AnalyzeDataFlow(body);
            var variablesDeclared = dataFlow.VariablesDeclared;
            var variablesRead = dataFlow.ReadInside.Union(dataFlow.ReadOutside);
            var unused = variablesDeclared.Except(variablesRead).ToArray();
            if (unused == null)
                return false;

            if (localDeclarationUnused.Declaration == null || !localDeclarationUnused.Declaration.Variables.Any())
                return false; 

            var localDeclarationSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(localDeclarationUnused.Declaration.Variables.FirstOrDefault());
            if (unused.Any())
            {
                if (unused.Contains(localDeclarationSymbol))
                {
                    diagnostic = Diagnostic.Create(descriptor, localDeclarationUnused.Declaration.GetLocation());
                    return true;
                }
            }
            return false;
        }
        private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var node = nodeContext.Node as IfStatementSyntax;
            if (node == null)
                return false;

            var methodBody = node.Parent as BlockSyntax;
            if (methodBody == null)
                return false;

            var ifStatementIndex = methodBody.Statements.IndexOf(node);
            if (ifStatementIndex == methodBody.Statements.Count - 1)
                return false;

            if (node.Statement is ReturnStatementSyntax &&
                methodBody.Statements[ifStatementIndex + 1] is ReturnStatementSyntax)
            {
                diagnostic = Diagnostic.Create(descriptor, node.GetLocation());
                return true;
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var node = nodeContext.Node as BinaryExpressionSyntax;

            var flowAnalzyer = new FlowAnalyzer<NullFlowState>(nodeContext.SemanticModel, new NullFlowState(nodeContext.SemanticModel));

            var analyzer = flowAnalzyer.Analyze(nodeContext.Node);
            var state = analyzer.GetFlowState(node.Left);

            var leftState = state.GetReferenceState(node.Left);
            if (leftState == NullState.NotNull) {
                diagnostic = Diagnostic.Create (descriptor, node.Right.GetLocation (), "Remove redundant right side");
                return true;
            }
            if (leftState == NullState.Null) {
                diagnostic = Diagnostic.Create (descriptor, node.Left.GetLocation (), "Remove redundant left side");
                return true;
            }
            if (state.GetReferenceState(node.Right) == NullState.Null) {
                diagnostic = Diagnostic.Create (descriptor, node.Right.GetLocation (), "Remove redundant left side");
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as InvocationExpressionSyntax;
            MemberAccessExpressionSyntax mre = node.Expression as MemberAccessExpressionSyntax;
            if (mre == null)
                return false;
            if (mre.Name.Identifier.ValueText != "LastIndexOf")
                return false;

            var rr = nodeContext.SemanticModel.GetSymbolInfo(node, nodeContext.CancellationToken);
            if (rr.Symbol == null)
                return false;
            var symbol = rr.Symbol;
            if (!(symbol.ContainingType != null && symbol.ContainingType.SpecialType == SpecialType.System_String))
                return false;
            var parameters = symbol.GetParameters();
            var firstParameter = parameters.FirstOrDefault();
            if (firstParameter == null || firstParameter.Type.SpecialType != SpecialType.System_String)
                return false;   // First parameter not a string
            var lastParameter = parameters.Last();
            if (lastParameter.Type.Name == "StringComparison")
                return false;   // already specifying a string comparison
            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
            );
            return true;
        }
        private static bool TryGetRedundantNullableDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;

            var objectCreation = nodeContext.Node as ObjectCreationExpressionSyntax;
            if (objectCreation == null)
                return false;

            //Not so sure about this check but was there before
            var parentVarDeclaration = objectCreation?.Parent?.Parent?.Parent as VariableDeclarationSyntax;
            if (parentVarDeclaration != null && parentVarDeclaration.Type.IsVar)
                return false;

            var objectCreationSymbol = nodeContext.SemanticModel.GetTypeInfo(objectCreation);
            //IsNullable method fails the analysis
            //Used string comparison for testing even though it's bad on performance.
            if (objectCreationSymbol.Type != null && objectCreationSymbol.Type.OriginalDefinition.ToString().Equals("System.Nullable<T>"))
            {
                diagnostic = Diagnostic.Create(descriptor, objectCreation.GetLocation());
                return true;
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var objectCreateExpression = nodeContext.Node as ObjectCreationExpressionSyntax;

            ExpressionSyntax paramNode;
            ExpressionSyntax altParamNode;
            bool canAddParameterName;
            if (!CheckExceptionType(nodeContext.SemanticModel, objectCreateExpression, out paramNode, out altParamNode, out canAddParameterName))
                return false;

            var paramName = GetArgumentParameterName(paramNode);
            if (paramName == null)
                return false;
            var validNames = GetValidParameterNames(objectCreateExpression);

            if (!validNames.Contains(paramName))
            {
                // Case 1: Parameter name is swapped
                var altParamName = GetArgumentParameterName(altParamNode);
                if (altParamName != null && validNames.Contains(altParamName))
                {
                    diagnostic = Diagnostic.Create(descriptor2, altParamNode.GetLocation());
                    return true;
                }
                //var guessName = GuessParameterName(nodeContext.SemanticModel, objectCreateExpression, validNames);

                // General case: mark only
                diagnostic = Diagnostic.Create(descriptor, paramNode.GetLocation(), paramName);
                return true;
            }
            return false;
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var semanticModel = nodeContext.SemanticModel;

            var node = nodeContext.Node as MemberAccessExpressionSyntax;

            var symbol = semanticModel.GetSymbolInfo(node.Name).Symbol;
            if (symbol == null)
                return false;

            RoslynReflectionAllowedContext surroundingContext = RoslynReflectionAllowedContext.None;
            var surroundingClass = node.Ancestors().OfType<ClassDeclarationSyntax>().FirstOrDefault();
            if (surroundingClass == null)
                return false;
            var surroundingClassSymbol = semanticModel.GetDeclaredSymbol(surroundingClass);
            if (surroundingClassSymbol == null)
                return false;
            var surroundingClassAttributes = surroundingClassSymbol.GetAttributes();
            if (surroundingClassAttributes.Any(a => a.AttributeClass.GetFullName() == typeof(DiagnosticAnalyzerAttribute).FullName))
                surroundingContext = RoslynReflectionAllowedContext.Analyzers;
            else if (surroundingClassAttributes.Any(a => a.AttributeClass.GetFullName() == typeof(ExportCodeFixProviderAttribute).FullName))
                surroundingContext = RoslynReflectionAllowedContext.CodeFixes;
            else if (surroundingClassAttributes.Any(a => a.AttributeClass.GetFullName() == typeof(ExportCodeRefactoringProviderAttribute).FullName))
                surroundingContext = RoslynReflectionAllowedContext.CodeFixes;
            else
                return false;

            var reflectionUsageAttributeData =
                symbol.GetAttributes().FirstOrDefault(a => a.AttributeClass.GetFullName() == typeof(RoslynReflectionUsageAttribute).FullName);
            if (reflectionUsageAttributeData == null)
            {
                var containingTypeSymbol = symbol.ContainingType;
                if (containingTypeSymbol != null)
                {
                    reflectionUsageAttributeData =
                        containingTypeSymbol.GetAttributes().FirstOrDefault(a => a.AttributeClass.GetFullName() == typeof(RoslynReflectionUsageAttribute).FullName);
                }
            }

            if (reflectionUsageAttributeData == null)
                return false;

            RoslynReflectionAllowedContext allowedContext = RoslynReflectionAllowedContext.None;
            var attributeParam = reflectionUsageAttributeData.ConstructorArguments.FirstOrDefault();
            if (attributeParam.Value is int)
                allowedContext = (RoslynReflectionAllowedContext)attributeParam.Value;

            if (allowedContext.HasFlag(surroundingContext))
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                node.Name.GetLocation()
            );
            return true;
        }
 static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
 {
     diagnostic = default(Diagnostic);
     if (nodeContext.IsFromGeneratedCode())
     {
         return(false);
     }
     //var node = nodeContext.Node as ;
     //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
     //return true;
     return(false);
 }
        static void AnalyzeField(SyntaxNodeAnalysisContext nodeContext)
        {
            if (nodeContext.IsFromGeneratedCode())
            {
                return;
            }
            var node = nodeContext.Node as FieldDeclarationSyntax;

            if (node?.Declaration?.Variables == null)
            {
                return;
            }
            if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.ConstKeyword)))
            {
                return;
            }
            var type = nodeContext.SemanticModel.GetTypeInfo(node.Declaration.Type).Type;

            if (type == null)
            {
                return;
            }
            foreach (var v in node.Declaration.Variables)
            {
                var initializer = v.Initializer?.Value;
                if (initializer == null)
                {
                    continue;
                }

                if (initializer.IsKind(SyntaxKind.DefaultExpression))
                {
                    //var defaultExpr = (DefaultExpressionSyntax)initializer;
                    //var defaultType = nodeContext.SemanticModel.GetTypeInfo(defaultExpr.Type).Type;
                    //if (defaultType == type) {
                    nodeContext.ReportDiagnostic(Diagnostic.Create(descriptor, v.Initializer.GetLocation()));
                    //}
                    continue;
                }

                var constValue = nodeContext.SemanticModel.GetConstantValue(initializer);
                if (!constValue.HasValue)
                {
                    continue;
                }
                if (IsDefaultValue(type, constValue.Value))
                {
                    nodeContext.ReportDiagnostic(Diagnostic.Create(descriptor, v.Initializer.GetLocation()));
                }
            }
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var prefixUnaryExpression = nodeContext.Node as PrefixUnaryExpressionSyntax;

            if (prefixUnaryExpression != null)
            {
                if (IsNonFlagsEnum(nodeContext.SemanticModel, prefixUnaryExpression.Operand))
                {
                    diagnostic = Diagnostic.Create(
                        descriptor,
                        prefixUnaryExpression.OperatorToken.GetLocation()
                        );
                    return(true);
                }
            }

            var assignmentExpression = nodeContext.Node as AssignmentExpressionSyntax;

            if (assignmentExpression != null)
            {
                if (IsNonFlagsEnum(nodeContext.SemanticModel, assignmentExpression.Left) || IsNonFlagsEnum(nodeContext.SemanticModel, assignmentExpression.Right))
                {
                    diagnostic = Diagnostic.Create(
                        descriptor,
                        assignmentExpression.OperatorToken.GetLocation()
                        );
                    return(true);
                }
            }

            var binaryExpression = nodeContext.Node as BinaryExpressionSyntax;

            if (binaryExpression != null)
            {
                if (IsNonFlagsEnum(nodeContext.SemanticModel, binaryExpression.Left) || IsNonFlagsEnum(nodeContext.SemanticModel, binaryExpression.Right))
                {
                    diagnostic = Diagnostic.Create(
                        descriptor,
                        binaryExpression.OperatorToken.GetLocation()
                        );
                    return(true);
                }
            }
            return(false);
        }
Example #34
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as InvocationExpressionSyntax;
            MemberAccessExpressionSyntax mre = node.Expression as MemberAccessExpressionSyntax;

            if (mre == null)
            {
                return(false);
            }
            if (mre.Name.Identifier.ValueText != "EndsWith")
            {
                return(false);
            }

            var rr = nodeContext.SemanticModel.GetSymbolInfo(node, nodeContext.CancellationToken);

            if (rr.Symbol == null)
            {
                return(false);
            }
            var symbol = rr.Symbol;

            if (!(symbol.ContainingType != null && symbol.ContainingType.SpecialType == SpecialType.System_String))
            {
                return(false);
            }
            var parameters     = symbol.GetParameters();
            var firstParameter = parameters.FirstOrDefault();

            if (firstParameter == null || firstParameter.Type.SpecialType != SpecialType.System_String)
            {
                return(false);   // First parameter not a string
            }
            var lastParameter = parameters.Last();

            if (lastParameter.Type.Name == "StringComparison")
            {
                return(false);   // already specifying a string comparison
            }
            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
                );
            return(true);
        }
Example #35
0
        void AnalyzeForStatement(SyntaxNodeAnalysisContext nodeContext)
        {
            if (nodeContext.IsFromGeneratedCode())
            {
                return;
            }
            var node = nodeContext.Node as ForStatementSyntax;

            if (node?.Declaration?.Variables == null)
            {
                return;
            }
            foreach (var variable in node.Declaration.Variables)
            {
                var local = nodeContext.SemanticModel.GetDeclaredSymbol(variable);
                if (local == null)
                {
                    return;
                }
                if (!node.Condition.DescendantNodesAndSelf().OfType <IdentifierNameSyntax>().Any(n => n.Identifier.ValueText == local.Name))
                {
                    continue;
                }
                bool wasModified = false;
                foreach (var identifier in node.DescendantNodesAndSelf().OfType <IdentifierNameSyntax>())
                {
                    if (identifier.Identifier.ValueText != local.Name)
                    {
                        continue;
                    }

                    if (!IsModified(identifier))
                    {
                        continue;
                    }

                    if (nodeContext.SemanticModel.GetSymbolInfo(identifier).Symbol == local)
                    {
                        wasModified = true;
                        break;
                    }
                }

                if (!wasModified)
                {
                    nodeContext.ReportDiagnostic(Diagnostic.Create(descriptor, variable.Identifier.GetLocation()));
                }
            }
        }
Example #36
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            var node              = nodeContext.Node as InvocationExpressionSyntax;
            var semanticModel     = nodeContext.SemanticModel;
            var cancellationToken = nodeContext.CancellationToken;

            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var memberReference = node.Expression as MemberAccessExpressionSyntax;

            if (memberReference == null)
            {
                return(false);
            }
            var firstArgument = node.ArgumentList.Arguments.FirstOrDefault();

            if (firstArgument == null || firstArgument.Expression.IsKind(SyntaxKind.NullLiteralExpression))
            {
                return(false);
            }
            var expressionSymbol = semanticModel.GetSymbolInfo(node.Expression).Symbol as IMethodSymbol;

            // Ignore non-extensions and reduced extensions (so a.Ext, as opposed to B.Ext(a))
            if (expressionSymbol == null || !expressionSymbol.IsExtensionMethod || expressionSymbol.MethodKind == MethodKind.ReducedExtension)
            {
                return(false);
            }

            // Don't allow conversion if first parameter is a method name instead of variable (extension method on delegate type)
            var firstParameter = node.ArgumentList?.Arguments.FirstOrDefault();

            if ((firstParameter != null) && (firstParameter.Expression is IdentifierNameSyntax))
            {
                var extensionMethodTargetExpression = semanticModel.GetSymbolInfo(firstParameter.Expression).Symbol as IMethodSymbol;
                if (extensionMethodTargetExpression != null)
                {
                    return(false);
                }
            }

            diagnostic = Diagnostic.Create(
                descriptor,
                memberReference.Name.GetLocation()
                );
            return(true);
        }
Example #37
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node      = nodeContext.Node as ArrayCreationExpressionSyntax;
            var arrayType = node?.Type;

            if (arrayType == null)
            {
                return(false);
            }

            if (node.Initializer == null)
            {
                return(false);
            }

            var rs = arrayType.RankSpecifiers;

            if (rs.Count != 1 || rs[0].Sizes.Count != 1)
            {
                return(false);
            }

            var intSizeValue = nodeContext.SemanticModel.GetConstantValue(arrayType.RankSpecifiers[0].Sizes[0]);

            if (!intSizeValue.HasValue || !(intSizeValue.Value is int))
            {
                return(false);
            }

            var size = (int)intSizeValue.Value;

            if (size <= -1)
            {
                return(false);
            }

            if (node.Initializer.Expressions.Count == size)
            {
                diagnostic = Diagnostic.Create(descriptor, arrayType.RankSpecifiers[0].Sizes[0].GetLocation());
                return(true);
            }

            return(false);
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as CatchClauseSyntax;

            if (node.Declaration == null)
            {
                diagnostic = Diagnostic.Create(
                    descriptor,
                    node.CatchKeyword.GetLocation()
                    );
                return(true);
            }
            else
            {
                var type = node.Declaration.Type;
                if (type != null)
                {
                    var typeSymbol = nodeContext.SemanticModel.GetTypeInfo(type).Type;
                    if (typeSymbol == null || typeSymbol.TypeKind == TypeKind.Error || !typeSymbol.GetFullName().Equals("System.Exception"))
                    {
                        return(false);
                    }

                    // Don't consider a catch clause with "when (...)" as general
                    if (node.Filter != null)
                    {
                        return(false);
                    }

                    BlockSyntax body = node.Block;
                    if (body.Statements.Any())
                    {
                        return(false);
                    }

                    diagnostic = Diagnostic.Create(
                        descriptor,
                        node.CatchKeyword.GetLocation()
                        );
                    return(true);
                }
            }
            return(false);
        }
Example #39
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            InitializerExpressionSyntax initializer = null;
            var node = nodeContext.Node as ArrayCreationExpressionSyntax;

            if (node != null)
            {
                initializer = node.Initializer;
            }
            var inode = nodeContext.Node as ImplicitArrayCreationExpressionSyntax;

            if (inode != null)
            {
                initializer = inode.Initializer;
            }

            if (initializer == null)
            {
                return(false);
            }
            var varInitializer = nodeContext.Node.Parent.Parent;

            if (varInitializer == null)
            {
                return(false);
            }
            var variableDeclaration = varInitializer.Parent as VariableDeclarationSyntax;

            if (variableDeclaration != null)
            {
                if (!variableDeclaration.Type.IsKind(SyntaxKind.ArrayType))
                {
                    return(false);
                }
                diagnostic = Diagnostic.Create(
                    descriptor,
                    Location.Create(nodeContext.SemanticModel.SyntaxTree, TextSpan.FromBounds((node != null ? node.NewKeyword : inode.NewKeyword).Span.Start, initializer.Span.Start))
                    );
                return(true);
            }
            return(false);
        }
Example #40
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as ForStatementSyntax;

            if (!node.Condition.IsKind(SyntaxKind.TrueLiteralExpression))
            {
                return(false);
            }
            diagnostic = Diagnostic.Create(descriptor, node.Condition.GetLocation());
            return(true);
        }
        static void GetDiagnostics(SyntaxNodeAnalysisContext nodeContext, SeparatedSyntaxList <AttributeArgumentSyntax>?arguments)
        {
            if (nodeContext.IsFromGeneratedCode())
            {
                return;
            }

            if (!arguments.HasValue)
            {
                return;
            }

            var node = nodeContext.Node;

            CheckParameters(nodeContext, nodeContext.SemanticModel.GetSymbolInfo(node).Symbol, arguments.Value);
        }
        static bool TryGetDiagnostic2(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var node = nodeContext.Node as PrefixUnaryExpressionSyntax;

            if (CheckConstant(nodeContext, node, ref diagnostic))
            {
                return(true);
            }
            return(false);
        }
Example #43
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as FinallyClauseSyntax;

            if (node.Block != null && node.Block.Statements.Count == 0)
            {
                diagnostic = Diagnostic.Create(descriptor, node.FinallyKeyword.GetLocation());
                return(true);
            }
            return(false);
        }
Example #44
0
        //I think it's a better decision to head in this direction instead of MethodDeclaration.
        private static bool TryGetParamsDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var paramList   = nodeContext.Node as ParameterListSyntax;
            var declaration = paramList?.Parent as MethodDeclarationSyntax;

            if (declaration == null)
            {
                return(false);
            }

            if (declaration.Modifiers.Count == 0 || !declaration.Modifiers.Any(SyntaxKind.OverrideKeyword))
            {
                return(false);
            }

            var         lastParam           = declaration.ParameterList.Parameters.LastOrDefault();
            SyntaxToken?paramsModifierToken = null;

            if (lastParam == null)
            {
                return(false);
            }

            foreach (var x in lastParam.Modifiers)
            {
                if (x.IsKind(SyntaxKind.ParamsKeyword))
                {
                    paramsModifierToken = x;
                    break;
                }
            }

            if (!paramsModifierToken.HasValue)
            {
                return(false);
            }

            diagnostic = Diagnostic.Create(descriptor, paramsModifierToken.Value.GetLocation());
            return(true);
        }
Example #45
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as IfStatementSyntax;
            ExpressionSyntax target;
            SyntaxTriviaList assignmentTrailingTriviaList;

            if (ConvertIfToOrExpressionAnalyzer.MatchIfElseStatement(node, SyntaxKind.FalseLiteralExpression, out target, out assignmentTrailingTriviaList))
            {
                var varDeclaration = ConvertIfToOrExpressionAnalyzer.FindPreviousVarDeclaration(node);
                if (varDeclaration != null)
                {
                    var targetIdentifier = target as IdentifierNameSyntax;
                    if (targetIdentifier == null)
                    {
                        return(false);
                    }
                    var declaredVarName = varDeclaration.Declaration.Variables.First().Identifier.Value;
                    var assignedVarName = targetIdentifier.Identifier.Value;
                    if (declaredVarName != assignedVarName)
                    {
                        return(false);
                    }
                    if (!ConvertIfToOrExpressionAnalyzer.CheckTarget(targetIdentifier, node.Condition))
                    {
                        return(false);
                    }
                    diagnostic = Diagnostic.Create(descriptor, node.IfKeyword.GetLocation(), GettextCatalog.GetString("Convert to '&&' expression"));
                    return(true);
                }
                else
                {
                    if (!ConvertIfToOrExpressionAnalyzer.CheckTarget(target, node.Condition))
                    {
                        return(false);
                    }
                    diagnostic = Diagnostic.Create(descriptor, node.IfKeyword.GetLocation(), GettextCatalog.GetString("Replace with '&='"));
                    return(true);
                }
            }
            return(false);
        }
        static bool TryGetDiagnosticFromBinaryExpression(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as BinaryExpressionSyntax;

            if (CSharpUtil.AreConditionsEqual(node.Left, node.Right))
            {
                diagnostic = Diagnostic.Create(descriptor, node.GetLocation(), node.IsKind(SyntaxKind.EqualsExpression) ? "true" : "false");
                return(true);
            }

            return(false);
        }
Example #47
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var node = nodeContext.Node as AttributeSyntax;

            if (node.ArgumentList == null || node.ArgumentList.Arguments.Count > 0)
            {
                return(false);
            }
            diagnostic = Diagnostic.Create(descriptor, node.GetLocation());
            return(true);
        }
Example #48
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var node = nodeContext.Node as Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax;

            if (IsEmbeddedStatement(node))
            {
                return(false);
            }
            diagnostic = Diagnostic.Create(descriptor, node.GetLocation());
            return(true);
        }
Example #49
0
        protected override void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            if (context.IsFromGeneratedCode())
            {
                return;
            }
            foreach (var n in context.Node.Ancestors(ascendOutOfTrivia: false))
            {
                if (s_kindsOfInterest.Contains(n.Kind()))
                {
                    // Already simplified an ancestor of this node.
                    return;
                }
            }

            Diagnostic diagnostic;
            Func <SyntaxNode, bool> descendIntoChildren = n =>
            {
                if (!IsRegularCandidate(n) ||
                    !TrySimplifyTypeNameExpression(context.SemanticModel, n, context.Options, out diagnostic, context.CancellationToken))
                {
                    return(true);
                }
                context.ReportDiagnostic(diagnostic);
                return(false);
            };

            // find regular node first - search from top to down. once found one, don't get into its children
            foreach (var candidate in context.Node.DescendantNodesAndSelf(descendIntoChildren))
            {
                context.CancellationToken.ThrowIfCancellationRequested();
            }

            // now search structure trivia
            foreach (var candidate in context.Node.DescendantNodesAndSelf(descendIntoChildren: n => !IsCrefCandidate(n), descendIntoTrivia: true))
            {
                context.CancellationToken.ThrowIfCancellationRequested();

                if (IsCrefCandidate(candidate) &&
                    TrySimplifyTypeNameExpression(context.SemanticModel, candidate, context.Options, out diagnostic, context.CancellationToken))
                {
                    context.ReportDiagnostic(diagnostic);
                }
            }
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as ConditionalExpressionSyntax;

            //pattern is Any(param) ? Last(param) : null/default
            var anyInvocation        = node.Condition as InvocationExpressionSyntax;
            var lastInvocation       = node.WhenTrue as InvocationExpressionSyntax;
            var nullDefaultWhenFalse = node.WhenFalse;

            if (anyInvocation == null || lastInvocation == null || nullDefaultWhenFalse == null)
            {
                return(false);
            }
            var anyExpression = anyInvocation.Expression as MemberAccessExpressionSyntax;

            if (anyExpression == null || anyExpression.Name.Identifier.ValueText != "Any")
            {
                return(false);
            }
            var anyParam = anyInvocation.ArgumentList;

            var lastExpression = lastInvocation.Expression as MemberAccessExpressionSyntax;

            if (lastExpression == null || lastExpression.Name.Identifier.ValueText != "Last" || !lastInvocation.ArgumentList.IsEquivalentTo(anyParam))
            {
                return(false);
            }

            if (!nullDefaultWhenFalse.IsKind(SyntaxKind.NullLiteralExpression) && !nullDefaultWhenFalse.IsKind(SyntaxKind.DefaultExpression))
            {
                return(false);
            }

            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
                );
            return(true);
        }
        static void AnalyzeParameterList(SyntaxNodeAnalysisContext nodeContext)
        {
            if (nodeContext.IsFromGeneratedCode())
            {
                return;
            }
            var node = nodeContext.Node as TypeParameterListSyntax;

            var member = node.Parent;

            if (member == null)
            {
                return;
            }

            var memberSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(member);

            if (memberSymbol.IsAbstract || memberSymbol.IsVirtual || memberSymbol.IsOverride)
            {
                return;
            }
            if (memberSymbol.ExplicitInterfaceImplementations().Length > 0)
            {
                return;
            }

            var walker = new ReferenceFinder(nodeContext);

            walker.Visit(member);

            foreach (var param in node.Parameters)
            {
                var sym = nodeContext.SemanticModel.GetDeclaredSymbol(param);
                if (sym == null)
                {
                    continue;
                }
                if (!walker.UsedTypeParameters.Contains(sym))
                {
                    var diagnostic = Diagnostic.Create(descriptor, param.Identifier.GetLocation(), sym.Name);
                    nodeContext.ReportDiagnostic(diagnostic);
                }
            }
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as ObjectCreationExpressionSyntax;

            if (!(node.Parent is ExpressionStatementSyntax))
            {
                return(false);
            }
            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
                );
            return(true);
        }
        private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var localDeclarationUnused = nodeContext.Node as LocalDeclarationStatementSyntax;
            var body = localDeclarationUnused?.Parent as BlockSyntax;

            if (body == null)
            {
                return(false);
            }

            var dataFlow          = nodeContext.SemanticModel.AnalyzeDataFlow(body);
            var variablesDeclared = dataFlow.VariablesDeclared;
            var variablesRead     = dataFlow.ReadInside.Union(dataFlow.ReadOutside);
            var unused            = variablesDeclared.Except(variablesRead).ToArray();

            if (unused == null)
            {
                return(false);
            }

            if (localDeclarationUnused.Declaration == null || !localDeclarationUnused.Declaration.Variables.Any())
            {
                return(false);
            }

            var localDeclarationSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(localDeclarationUnused.Declaration.Variables.FirstOrDefault());

            if (unused.Any())
            {
                if (unused.Contains(localDeclarationSymbol))
                {
                    diagnostic = Diagnostic.Create(descriptor, localDeclarationUnused.Declaration.GetLocation());
                    return(true);
                }
            }
            return(false);
        }
Example #54
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as MethodDeclarationSyntax;

            if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.OverrideKeyword)))
            {
                return(false);
            }
            var lastParam = node.ParameterList.Parameters.LastOrDefault();

            if (lastParam == null || lastParam.Modifiers.Any(m => m.IsKind(SyntaxKind.ParamsKeyword)))
            {
                return(false);
            }
            if (lastParam.Type == null || !lastParam.Type.IsKind(SyntaxKind.ArrayType))
            {
                return(false);
            }
            var rr = nodeContext.SemanticModel.GetDeclaredSymbol(node);

            if (rr == null || !rr.IsOverride)
            {
                return(false);
            }
            var baseMember = rr.OverriddenMethod;

            if (baseMember == null || baseMember.Parameters.Length == 0 || !baseMember.Parameters.Last().IsParams)
            {
                return(false);
            }

            diagnostic = Diagnostic.Create(
                descriptor,
                lastParam.GetLocation(),
                baseMember.Name
                );
            return(true);
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var objectCreateExpression = nodeContext.Node as ObjectCreationExpressionSyntax;

            ExpressionSyntax paramNode;
            ExpressionSyntax altParamNode;
            bool             canAddParameterName;

            if (!CheckExceptionType(nodeContext.SemanticModel, objectCreateExpression, out paramNode, out altParamNode, out canAddParameterName))
            {
                return(false);
            }

            var paramName = GetArgumentParameterName(paramNode);

            if (paramName == null)
            {
                return(false);
            }
            var validNames = GetValidParameterNames(objectCreateExpression);

            if (!validNames.Contains(paramName))
            {
                // Case 1: Parameter name is swapped
                var altParamName = GetArgumentParameterName(altParamNode);
                if (altParamName != null && validNames.Contains(altParamName))
                {
                    diagnostic = Diagnostic.Create(descriptor2, altParamNode.GetLocation());
                    return(true);
                }
                //var guessName = GuessParameterName(nodeContext.SemanticModel, objectCreateExpression, validNames);

                // General case: mark only
                diagnostic = Diagnostic.Create(descriptor, paramNode.GetLocation(), paramName);
                return(true);
            }
            return(false);
        }
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as ConditionalExpressionSyntax;

            if (!node.WhenTrue.IsEquivalentTo(node.WhenFalse, true))
            {
                return(false);
            }
            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
                );
            return(true);
        }
        private static bool TryGetRedundantNullableDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var objectCreation = nodeContext.Node as ObjectCreationExpressionSyntax;

            if (objectCreation == null)
            {
                return(false);
            }

            // No Nullable, but "var"
            var parentVarDeclaration = objectCreation?.Parent?.Parent?.Parent as VariableDeclarationSyntax;

            if (parentVarDeclaration != null && parentVarDeclaration.Type.IsVar)
            {
                return(false);
            }

            // No Nullable, but "var"
            var conditionalExpression = objectCreation.WalkUpParentheses().Parent as ConditionalExpressionSyntax;

            if (conditionalExpression != null && conditionalExpression.WhenFalse.SkipParens() == objectCreation)
            {
                return(false);
            }

            var objectCreationSymbol = nodeContext.SemanticModel.GetTypeInfo(objectCreation);

            if (objectCreationSymbol.Type != null && objectCreationSymbol.Type.IsNullableType())
            {
                var creationTypeLocation = objectCreation.Type.GetLocation();
                var newKeywordLocation   = objectCreation.NewKeyword.GetLocation();
                diagnostic = Diagnostic.Create(descriptor, newKeywordLocation, (IEnumerable <Location>)(new[] { creationTypeLocation }));
                return(true);
            }
            return(false);
        }
Example #58
0
        void Check(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax condition)
        {
            if (nodeContext.IsFromGeneratedCode())
            {
                return;
            }

            if (condition == null)
            {
                return;
            }

            if (condition.IsKind(SyntaxKind.TrueLiteralExpression) || condition.IsKind(SyntaxKind.FalseLiteralExpression))
            {
                return;
            }

            var resolveResult = nodeContext.SemanticModel.GetConstantValue(condition);

            if (!resolveResult.HasValue || !(resolveResult.Value is bool))
            {
                return;
            }

            var value = (bool)resolveResult.Value;

            nodeContext.ReportDiagnostic(Diagnostic.Create(
                                             descriptor.Id,
                                             descriptor.Category,
                                             string.Format(descriptor.MessageFormat.ToString(), value),
                                             descriptor.DefaultSeverity,
                                             descriptor.DefaultSeverity,
                                             descriptor.IsEnabledByDefault,
                                             4,
                                             descriptor.Title,
                                             descriptor.Description,
                                             descriptor.HelpLinkUri,
                                             condition.GetLocation(),
                                             null,
                                             new[] { value.ToString() }
                                             ));
        }
Example #59
0
        static bool TryGetDiagnosticForForeach(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            var node = nodeContext.Node as ForEachStatementSyntax;

            if (!Check(node.Statement))
            {
                return(false);
            }

            diagnostic = Diagnostic.Create(
                descriptor,
                node.Statement.GetLocation()
                );
            return(true);
        }
Example #60
0
        private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }

            var node             = nodeContext.Node as IfStatementSyntax;
            var methodBody       = node?.Parent as BlockSyntax;
            var ifStatementIndex = methodBody?.Statements.IndexOf(node);

            if (node?.Statement is ReturnStatementSyntax &&
                methodBody?.Statements[ifStatementIndex.Value + 1] is ReturnStatementSyntax)
            {
                diagnostic = Diagnostic.Create(descriptor, node.GetLocation());
                return(true);
            }
            return(false);
        }