Example #1
0
 internal static bool CheckTarget(ExpressionSyntax target, ExpressionSyntax expr)
 {
     if (target.IsKind(SyntaxKind.IdentifierName))
     {
         return(!expr.DescendantNodesAndSelf().OfType <IdentifierNameSyntax>().Any(n => ((IdentifierNameSyntax)target).Identifier.ValueText == n.Identifier.ValueText));
     }
     if (target.IsKind(SyntaxKind.SimpleMemberAccessExpression))
     {
         var descendantTargetNodes = target.DescendantNodesAndSelf();
         return(!expr.DescendantNodesAndSelf().Any(
                    n =>
         {
             // If n is a simple idenifier, try to find it in target expression as well
             if (n.IsKind(SyntaxKind.IdentifierName))
             {
                 return descendantTargetNodes.Any(tn =>
                                                  tn.IsKind(SyntaxKind.IdentifierName) && (((IdentifierNameSyntax)tn).Identifier.ValueText == ((IdentifierNameSyntax)n).Identifier.ValueText));
             }
             // StartsWith() is a very simple solution, but should be enough in usual cases
             if (n.IsKind(SyntaxKind.SimpleMemberAccessExpression))
             {
                 return ((MemberAccessExpressionSyntax)target).Expression.ToString().StartsWith(((MemberAccessExpressionSyntax)n).Expression.ToString());
             }
             return false;
         }
                    ));
     }
     return(false);
 }
Example #2
0
 internal static bool CheckTarget(ExpressionSyntax target, ExpressionSyntax expr)
 {
     if (target.IsKind(SyntaxKind.IdentifierName))
     {
         return(!expr.DescendantNodesAndSelf().OfType <IdentifierNameSyntax>().Any(n => ((IdentifierNameSyntax)target).Identifier.ValueText == n.Identifier.ValueText));
     }
     if (target.IsKind(SyntaxKind.SimpleMemberAccessExpression))
     {
         return(!expr.DescendantNodesAndSelf().Any(
                    n =>
         {
             if (n.IsKind(SyntaxKind.IdentifierName))
             {
                 return ((MemberAccessExpressionSyntax)target).Expression.ToString() == ((IdentifierNameSyntax)n).Identifier.ValueText;
             }
             if (n.IsKind(SyntaxKind.SimpleMemberAccessExpression))
             {
                 return ((MemberAccessExpressionSyntax)target).Expression.ToString() == ((MemberAccessExpressionSyntax)n).Expression.ToString();
             }
             return false;
         }
                    ));
     }
     return(false);
 }
Example #3
0
        private static bool IsCompileTimeConstantPassword(SyntaxNodeAnalysisContext context, ExpressionSyntax syntax)
        {
            if (syntax is LiteralExpressionSyntax literal &&
                literal.Kind() == SyntaxKind.StringLiteralExpression)
            {
                var v = context.Compilation.GetSemanticModel(syntax.SyntaxTree).GetConstantValue(literal);
                if (!v.HasValue)
                {
                    return(false);
                }
                return(true);
            }

            if (syntax is ImplicitArrayCreationExpressionSyntax ||
                syntax is ArrayCreationExpressionSyntax || syntax is InitializerExpressionSyntax)
            {
                if (!syntax.HasInitializer())
                {
                    var rank = syntax.DescendantNodesAndSelf().OfType <ArrayRankSpecifierSyntax>().FirstOrDefault();
                    if (rank == null)
                    {
                        return(false);
                    }
                    var firstRank = rank.Sizes.FirstOrDefault();
                    return(firstRank.IsOrContainsCompileTimeConstantValue <int>(context, out _));
                }

                return(true);
            }

            return(false);
        }
        bool ConditionContainsNullCheck(ExpressionSyntax condition, ExpressionSyntax identifierToCheck)
        {
            var identifierNameToCheck = identifierToCheck as IdentifierNameSyntax;
            var memberAccessExpressionToCheck = identifierToCheck as MemberAccessExpressionSyntax;

            return condition.DescendantNodesAndSelf().Any(n =>
            {
                var binaryExpr = n as BinaryExpressionSyntax;
                if (binaryExpr != null)
                {

                    IdentifierNameSyntax identifierName = binaryExpr.Left as IdentifierNameSyntax;
                    if ((identifierName != null) && (identifierNameToCheck != null) && (identifierName.Identifier.ValueText == identifierNameToCheck.Identifier.ValueText))
                        return binaryExpr.IsKind(SyntaxKind.NotEqualsExpression) && binaryExpr.Right.IsKind(SyntaxKind.NullLiteralExpression);
                    MemberAccessExpressionSyntax memberAccessExpressionSyntax = binaryExpr.Left as MemberAccessExpressionSyntax;
                    if ((memberAccessExpressionSyntax != null) && (memberAccessExpressionToCheck != null) && (memberAccessExpressionSyntax.ToString() == identifierToCheck.ToString()))
                        return binaryExpr.IsKind(SyntaxKind.NotEqualsExpression) && binaryExpr.Right.IsKind(SyntaxKind.NullLiteralExpression);

                    identifierName = binaryExpr.Right as IdentifierNameSyntax;
                    if ((identifierName != null) && (identifierNameToCheck != null) && (identifierName.Identifier.ValueText == identifierNameToCheck.Identifier.ValueText))
                        return binaryExpr.IsKind(SyntaxKind.NotEqualsExpression) && binaryExpr.Left.IsKind(SyntaxKind.NullLiteralExpression);
                    memberAccessExpressionSyntax = binaryExpr.Right as MemberAccessExpressionSyntax;
                    if ((memberAccessExpressionSyntax != null) && (memberAccessExpressionToCheck != null) && (memberAccessExpressionSyntax.ToString() == identifierToCheck.ToString()))
                        return binaryExpr.IsKind(SyntaxKind.NotEqualsExpression) && binaryExpr.Left.IsKind(SyntaxKind.NullLiteralExpression);
                }

                return false;
            });
        }
Example #5
0
        bool IsLoopVariable(ExpressionSyntax condition, string name)
        {
            var identifier = condition as IdentifierNameSyntax;

            if ((identifier != null) && (identifier.Identifier.ValueText == name))
            {
                return(true);
            }

            foreach (var n in condition.DescendantNodesAndSelf())
            {
                var binOp = n as BinaryExpressionSyntax;
                if (binOp != null && binOp.Left.DescendantNodesAndSelf().OfType <IdentifierNameSyntax> ().Any(i => i.Identifier.ValueText == name))
                {
                    return(true);
                }
                if (n is PrefixUnaryExpressionSyntax || n is PostfixUnaryExpressionSyntax)
                {
                    if (n.DescendantNodesAndSelf().OfType <IdentifierNameSyntax> ().Any(i => i.Identifier.ValueText == name))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
 private static bool HasDisposableNotLocalIdentifier(ExpressionSyntax expression, SemanticModel semanticModel)
 {
     return(expression
            .DescendantNodesAndSelf()
            .OfType <IdentifierNameSyntax>()
            .Any(identifier => IsDisposableNotLocalIdentifier(identifier, semanticModel)));
 }
 internal static bool CheckTarget(ExpressionSyntax target, ExpressionSyntax expr)
 {
     if (target.IsKind(SyntaxKind.IdentifierName))
         return !expr.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().Any(n => ((IdentifierNameSyntax)target).Identifier.ValueText == n.Identifier.ValueText);
     if (target.IsKind(SyntaxKind.SimpleMemberAccessExpression))
         return !expr.DescendantNodesAndSelf().Any(
                 n =>
                 {
                     // StartsWith() is a very simple solution, but should be enough in usual cases
                     if (n.IsKind(SyntaxKind.IdentifierName))
                         return ((MemberAccessExpressionSyntax)target).Expression.ToString().StartsWith(((IdentifierNameSyntax)n).Identifier.ValueText);
                     if (n.IsKind(SyntaxKind.SimpleMemberAccessExpression))
                         return ((MemberAccessExpressionSyntax)target).Expression.ToString().StartsWith(((MemberAccessExpressionSyntax)n).Expression.ToString());
                     return false;
                 }
             );
     return false;
 }
Example #8
0
 private static IEnumerable <SyntaxToken> GetIdentifiers(ExpressionSyntax expression)
 {
     return(expression.RemoveParentheses() is IdentifierNameSyntax identifier?ImmutableArray.Create(identifier.Identifier)
                : expression.DescendantNodesAndSelf()
                .OfType <AssignmentExpressionSyntax>()
                .Select(a => a.Left)
                .OfType <IdentifierNameSyntax>()
                .Select(i => i.Identifier)
                .ToImmutableArray());
 }
        private static bool MayHaveSideEffects(ExpressionSyntax expression)
        {
            // Checks to see if the expression being invoked looks side-effect free.  If so, changing from executing
            // each time in the lambda to only executing it once could have impact on the program.

            return(!expression.DescendantNodesAndSelf().All(
                       n => n is TypeSyntax or
                       TypeArgumentListSyntax or
                       MemberAccessExpressionSyntax or
                       InstanceExpressionSyntax or
                       LiteralExpressionSyntax));
        }
        private static bool CompileTimeTooShortLiteralOrArray(SyntaxNodeAnalysisContext context, ExpressionSyntax syntax)
        {
            if (syntax is LiteralExpressionSyntax literal &&
                literal.Kind() == SyntaxKind.NumericLiteralExpression)
            {
                var v = context.SemanticModel.GetConstantValue(literal);
                if (!v.HasValue)
                {
                    return(false);
                }

                if ((int)v.Value < MinimumSaltSize)
                {
                    return(true);
                }
                return(false);
            }

            if (syntax is ImplicitArrayCreationExpressionSyntax ||
                syntax is ArrayCreationExpressionSyntax || syntax is InitializerExpressionSyntax)
            {
                if (!syntax.HasInitializer())
                {
                    var rank = syntax.DescendantNodesAndSelf().OfType <ArrayRankSpecifierSyntax>().FirstOrDefault();
                    if (rank == null)
                    {
                        return(false);
                    }
                    var firstRank = rank.Sizes.FirstOrDefault();
                    if (firstRank.IsOrContainsCompileTimeConstantValue <int>(context, out var rankValue))
                    {
                        return(rankValue < MinimumSaltSize);
                    }
                    return(false);
                }

                int count;
                if (syntax is ArrayCreationExpressionSyntax arrayCreation)
                {
                    count = arrayCreation.Initializer.Expressions.Count;
                }
                else if (syntax is ImplicitArrayCreationExpressionSyntax implicitArrayCreation)
                {
                    count = implicitArrayCreation.Initializer.Expressions.Count;
                }
                else
                {
                    count = ((InitializerExpressionSyntax)syntax).Expressions.Count;
                }
                return(count < MinimumSaltSize);
            }
            return(false);
        }
 private SyntaxToken GetRangeVariable(ExpressionSyntax node)
 {
     try
     {
         return(Identifier(
                    node.DescendantNodesAndSelf().
                    Select(n => _model.GetSymbolInfo(n).Symbol).
                    SingleOrDefault(n => n is IRangeVariableSymbol)?.Name));
     }
     catch (Exception)
     {
         return(Identifier(_state.SourceIdentifier.ValueText));
     }
 }
Example #12
0
        /// <summary>
        /// Analyzes the assignment expression and rejects a given declaration if it is unsuitable for implicit typing.
        /// </summary>
        /// <returns>
        /// false, if implicit typing cannot be used.
        /// true, otherwise.
        /// </returns>
        protected override bool AssignmentSupportsStylePreference(
            SyntaxToken identifier,
            TypeSyntax typeName,
            ExpressionSyntax initializer,
            SemanticModel semanticModel,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            var expression = GetInitializerExpression(initializer);

            // var cannot be assigned null
            if (expression.IsKind(SyntaxKind.NullLiteralExpression))
            {
                return(false);
            }

            // cannot use implicit typing on method group, anonymous function or on dynamic
            var declaredType = semanticModel.GetTypeInfo(typeName, cancellationToken).Type;

            if (declaredType != null &&
                (declaredType.TypeKind == TypeKind.Delegate || declaredType.TypeKind == TypeKind.Dynamic))
            {
                return(false);
            }

            // variables declared using var cannot be used further in the same initialization expression.
            if (initializer.DescendantNodesAndSelf()
                .Where(n => (n as IdentifierNameSyntax)?.Identifier.ValueText.Equals(identifier.ValueText) == true)
                .Any(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol?.IsKind(SymbolKind.Local) == true))
            {
                return(false);
            }

            // Get the conversion that occurred between the expression's type and type implied by the expression's context
            // and filter out implicit conversions. If an implicit conversion (other than identity) exists
            // and if we're replacing the declaration with 'var' we'd be changing the semantics by inferring type of
            // initializer expression and thereby losing the conversion.
            var conversion = semanticModel.GetConversion(expression, cancellationToken);

            if (conversion.Exists && conversion.IsImplicit && !conversion.IsIdentity)
            {
                return(false);
            }

            // final check to compare type information on both sides of assignment.
            var initializerType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;

            return(declaredType.Equals(initializerType));
        }
        private ExpressionSyntax AddImplicitThis(ExpressionSyntax bodyExpression, SemanticModel sm, ITypeSymbol type)
        {
            var candidates =
                (from ident in bodyExpression.DescendantNodesAndSelf().OfType <IdentifierNameSyntax>()
                 where ident.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression || ((MemberAccessExpressionSyntax)ident.Parent).Expression == ident
                 let symbol = sm.GetSymbolInfo(ident).Symbol
                              where !symbol.IsStatic && (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Field)
                              where type.GetInheritedMembers().Contains(symbol)
                              select ident).ToList();

            var result = bodyExpression.ReplaceNodes(candidates, (ident, _) => SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                                                                    SyntaxFactory.ThisExpression(), ident));

            return(result);
        }
 static string GetParameterName(SemanticModel model, ExpressionSyntax expr)
 {
     foreach (var node in expr.DescendantNodesAndSelf())
     {
         if (!(node is ExpressionSyntax))
         {
             continue;
         }
         var rr = model.GetSymbolInfo(node).Symbol as IParameterSymbol;
         if (rr != null)
         {
             return(rr.Name);
         }
     }
     return(null);
 }
Example #15
0
        private static bool ContainsPossibleUpdate(StatementSyntax statement, ExpressionSyntax expression,
                                                   SemanticModel semanticModel)
        {
            var checkedSymbols = expression.DescendantNodesAndSelf()
                                 .Select(node => semanticModel.GetSymbolInfo(node).Symbol)
                                 .Where(symbol => symbol != null)
                                 .ToImmutableHashSet();

            var statementDescendents  = statement.DescendantNodesAndSelf().ToList();
            var assignmentExpressions = statementDescendents
                                        .OfType <AssignmentExpressionSyntax>()
                                        .Any(expressionSyntax =>
            {
                var symbol = semanticModel.GetSymbolInfo(expressionSyntax.Left).Symbol;
                return(symbol != null && checkedSymbols.Contains(symbol));
            });

            if (assignmentExpressions)
            {
                return(true);
            }

            var postfixUnaryExpression = statementDescendents
                                         .OfType <PostfixUnaryExpressionSyntax>()
                                         .Any(expressionSyntax =>
            {
                var symbol = semanticModel.GetSymbolInfo(expressionSyntax.Operand).Symbol;
                return(symbol != null && checkedSymbols.Contains(symbol));
            });

            if (postfixUnaryExpression)
            {
                return(true);
            }

            var prefixUnaryExpression = statementDescendents
                                        .OfType <PrefixUnaryExpressionSyntax>()
                                        .Any(expressionSyntax =>
            {
                var symbol = semanticModel.GetSymbolInfo(expressionSyntax.Operand).Symbol;
                return(symbol != null && checkedSymbols.Contains(symbol));
            });

            return(prefixUnaryExpression);
        }
            public ImmutableHashSet <FindSymbolResult> FindPropertyOrFieldSymbols(SemanticModel model, ExpressionSyntax expression, CancellationToken token)
            {
                if (model == null)
                {
                    throw new ArgumentNullException(nameof(model));
                }
                if (expression == null)
                {
                    throw new ArgumentNullException(nameof(expression));
                }

                ImmutableHashSet <FindSymbolResult> symbolResults = ImmutableHashSet <FindSymbolResult> .Empty;

                ImmutableHashSet <FindSymbolResult> .Builder builder = symbolResults.ToBuilder();

                token.ThrowIfCancellationRequested();
                EnumerateNodes(ref builder, model, expression.DescendantNodesAndSelf(), token);
                return(builder.ToImmutable());
            }
        private static bool ContainsLocalDefinedInLoopBody(
            ExpressionSyntax condition,
            TextSpan span,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            foreach (SyntaxNode node in condition.DescendantNodesAndSelf())
            {
                if (node.IsKind(SyntaxKind.IdentifierName))
                {
                    ISymbol symbol = semanticModel.GetSymbol((ExpressionSyntax)node, cancellationToken);

                    if (symbol?.Kind == SymbolKind.Local &&
                        symbol.GetSyntaxOrDefault(cancellationToken)?.Span.IsContainedIn(span) == true)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #18
0
        public static string?ResolveStringConstantExpression(this ExpressionSyntax expression)
        {
            if (expression is LiteralExpressionSyntax literal && literal.Token.IsKind(SyntaxKind.StringLiteralToken))
            {
                return(literal.Token.ValueText);
            }

            var values = new List <string>();

            foreach (var node in expression.DescendantNodesAndSelf())
            {
                switch (node)
                {
                case BinaryExpressionSyntax binaryExpression:
                    if (!binaryExpression.IsKind(SyntaxKind.AddExpression))
                    {
                        return(null);
                    }
                    break;

                case LiteralExpressionSyntax literalExpression:
                    if (!literalExpression.Token.IsKind(SyntaxKind.StringLiteralToken))
                    {
                        return(null);
                    }
                    values.Add(literalExpression.Token.ValueText);
                    break;

                case ParenthesizedExpressionSyntax _:
                    break;

                default:
                    return(null);
                }
            }

            return(string.Concat(values));
        }
 static string GetParameterName(SemanticModel model, ExpressionSyntax expr)
 {
     foreach (var node in expr.DescendantNodesAndSelf())
     {
         if (!(node is ExpressionSyntax))
             continue;
         var rr = model.GetSymbolInfo(node).Symbol as IParameterSymbol;
         if (rr != null)
             return rr.Name;
     }
     return null;
 }
        private ExpressionSyntax AddImplicitThis(ExpressionSyntax bodyExpression, SemanticModel sm, ITypeSymbol type)
        {
            var candidates =
                (from ident in bodyExpression.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>()
                 where ident.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression || ((MemberAccessExpressionSyntax)ident.Parent).Expression == ident
                 let symbol = sm.GetSymbolInfo(ident).Symbol
                 where !symbol.IsStatic && (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Field)
                 where type.GetInheritedMembers().Contains(symbol)
                 select ident).ToList();

            var result = bodyExpression.ReplaceNodes(candidates, (ident, _) => SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                SyntaxFactory.ThisExpression(), ident));

            return result;
        }
        /// <summary>
        /// Analyzes the assignment expression and rejects a given declaration if it is unsuitable for implicit typing.
        /// </summary>
        /// <returns>
        /// false, if implicit typing cannot be used.
        /// true, otherwise.
        /// </returns>
        protected override bool AssignmentSupportsStylePreference(
            SyntaxToken identifier,
            TypeSyntax typeName,
            ExpressionSyntax initializer,
            SemanticModel semanticModel,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            var expression = GetInitializerExpression(initializer);

            // var cannot be assigned null
            if (expression.IsKind(SyntaxKind.NullLiteralExpression))
            {
                return false;
            }

            // cannot use implicit typing on method group, anonymous function or on dynamic
            var declaredType = semanticModel.GetTypeInfo(typeName, cancellationToken).Type;
            if (declaredType != null &&
               (declaredType.TypeKind == TypeKind.Delegate || declaredType.TypeKind == TypeKind.Dynamic))
            {
                return false;
            }

            // variables declared using var cannot be used further in the same initialization expression.
            if (initializer.DescendantNodesAndSelf()
                    .Where(n => (n as IdentifierNameSyntax)?.Identifier.ValueText.Equals(identifier.ValueText) == true)
                    .Any(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol?.IsKind(SymbolKind.Local) == true))
            {
                return false;
            }

            // Get the conversion that occurred between the expression's type and type implied by the expression's context
            // and filter out implicit conversions. If an implicit conversion (other than identity) exists
            // and if we're replacing the declaration with 'var' we'd be changing the semantics by inferring type of
            // initializer expression and thereby losing the conversion.
            var conversion = semanticModel.GetConversion(expression, cancellationToken);
            if (conversion.Exists && conversion.IsImplicit && !conversion.IsIdentity)
            {
                return false;
            }

            // final check to compare type information on both sides of assignment.
            var initializerType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
            return declaredType.Equals(initializerType);
        }
Example #22
0
 /// <summary>
 /// Returns all identifiers.
 /// </summary>
 /// <param name="expr">Expression</param>
 /// <returns>Identifiers</returns>
 public HashSet <IdentifierNameSyntax> GetIdentifiers(ExpressionSyntax expr)
 {
     return(new HashSet <IdentifierNameSyntax>(expr.DescendantNodesAndSelf().
                                               OfType <IdentifierNameSyntax>()));
 }
 internal static bool CheckTarget(ExpressionSyntax target, ExpressionSyntax expr)
 {
     if (target.IsKind(SyntaxKind.IdentifierName))
         return !expr.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().Any(n => ((IdentifierNameSyntax)target).Identifier.ValueText == n.Identifier.ValueText);
     if (target.IsKind(SyntaxKind.SimpleMemberAccessExpression))
         return !expr.DescendantNodesAndSelf().Any(
                 n =>
                 {
                     if (n.IsKind(SyntaxKind.IdentifierName))
                         return ((MemberAccessExpressionSyntax)target).Expression.ToString() == ((IdentifierNameSyntax)n).Identifier.ValueText;
                     if (n.IsKind(SyntaxKind.SimpleMemberAccessExpression))
                         return ((MemberAccessExpressionSyntax)target).Expression.ToString() == ((MemberAccessExpressionSyntax)n).Expression.ToString();
                     return false;
                 }
             );
     return false;
 }
Example #24
0
        public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) {

            if (node.Kind() == SyntaxKind.EqualsExpression) {

                bool wasVariableInside = false;

                ExpressionSyntax equalsExpressionRight = node.Right;

                IEnumerable<SyntaxNode> list = equalsExpressionRight.DescendantNodesAndSelf();

                foreach(SyntaxNode n in list) {

                    if(n is IdentifierNameSyntax) {

                        //Console.WriteLine(n.ToString());
                        wasVariableInside = true;

                    } 

                }          
                  
                if (!wasVariableInside) {
                
                    ExpressionSyntax left = node.Left.WithoutTrailingTrivia();
                    ExpressionSyntax right = node.Right.WithTrailingTrivia(node.GetFirstToken().TrailingTrivia);
                    SyntaxToken sign = node.OperatorToken;

                    node = node.ReplaceNode(node, SyntaxFactory.BinaryExpression
                        (SyntaxKind.EqualsExpression, right, sign, left));                

                }
                   
              
            } else if(node.Kind() == SyntaxKind.NotEqualsExpression)  {

                ExpressionSyntax notEqualsExpressionRight = node.Right;

                bool wasVariableInside = false;

                IEnumerable<SyntaxNode> list = notEqualsExpressionRight.DescendantNodesAndSelf();


                foreach (SyntaxNode n in list) {

                        if (n is IdentifierNameSyntax) {

                            //Console.WriteLine(n.ToString());
                            wasVariableInside = true;

                        }

                    }

                if (!wasVariableInside) {

                    ExpressionSyntax left = node.Left.WithoutTrailingTrivia();
                    ExpressionSyntax right = node.Right.WithTrailingTrivia(node.GetFirstToken().TrailingTrivia);
                    SyntaxToken sign = node.OperatorToken;

                    node = node.ReplaceNode(node, SyntaxFactory.BinaryExpression
                        (SyntaxKind.EqualsExpression, right, sign, left));

                }


            }

            return base.VisitBinaryExpression(node);
        }
        bool ConditionContainsNullCheck(ExpressionSyntax condition, ExpressionSyntax identifierToCheck)
        {
            var identifierNameToCheck = identifierToCheck as IdentifierNameSyntax;
            var memberAccessExpressionToCheck = identifierToCheck as MemberAccessExpressionSyntax;

            return condition.DescendantNodesAndSelf().Any(n =>
            {
                var binaryExpr = n as BinaryExpressionSyntax;
                if (binaryExpr != null)
                {

                    IdentifierNameSyntax identifierName = binaryExpr.Left as IdentifierNameSyntax;
                    if ((identifierName != null) && (identifierNameToCheck != null) && (identifierName.Identifier.ValueText == identifierNameToCheck.Identifier.ValueText))
                        return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Right.IsKind(SyntaxKind.NothingLiteralExpression);
                    MemberAccessExpressionSyntax memberAccessExpressionSyntax = binaryExpr.Left as MemberAccessExpressionSyntax;
                    if ((memberAccessExpressionSyntax != null) && (memberAccessExpressionToCheck != null) && (memberAccessExpressionSyntax.ToString() == identifierToCheck.ToString()))
                        return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Right.IsKind(SyntaxKind.NothingLiteralExpression);

                    identifierName = binaryExpr.Right as IdentifierNameSyntax;
                    if ((identifierName != null) && (identifierNameToCheck != null) && (identifierName.Identifier.ValueText == identifierNameToCheck.Identifier.ValueText))
                        return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Left.IsKind(SyntaxKind.NothingLiteralExpression);
                    memberAccessExpressionSyntax = binaryExpr.Right as MemberAccessExpressionSyntax;
                    if ((memberAccessExpressionSyntax != null) && (memberAccessExpressionToCheck != null) && (memberAccessExpressionSyntax.ToString() == identifierToCheck.ToString()))
                        return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Left.IsKind(SyntaxKind.NothingLiteralExpression);
                }

                return false;
            });
        }
Example #26
0
 /// <summary>
 /// Returns all identifiers.
 /// </summary>
 /// <param name="expr">Expression</param>
 /// <returns>Identifiers</returns>
 public HashSet<IdentifierNameSyntax> GetIdentifiers(ExpressionSyntax expr)
 {
     return new HashSet<IdentifierNameSyntax>(expr.DescendantNodesAndSelf().
             OfType<IdentifierNameSyntax>());
 }