public override void VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            var symbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(node).Symbol;

            if (symbol != null)
            {
                Enums.AsyncDetected type = DetectCPUAsynchronousUsages(node,symbol);
                Result.StoreDetectedCPUAsyncUsage(type);

                // Check whether there are some blocking operations under task, threadpool, and thread!
                //if (type == Enums.AsyncDetected.Task || type == Enums.AsyncDetected.Threadpool || type == Enums.AsyncDetected.Thread)
                //{
                //    foreach (var methodCall in node.DescendantNodes().OfType<InvocationExpressionSyntax>())
                //    {
                //        var methodCallSymbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(methodCall).Symbol;

                //        if (methodCallSymbol != null)
                //        {
                //            var synctype = ((IMethodSymbol)methodCallSymbol.OriginalDefinition).DetectSynchronousUsages(SemanticModel);

                //            if (synctype != Utilities.Enums.SyncDetected.None)
                //                Logs.TempLog.Info("LONGRUNNING {0} {1}{2}--------------------------", methodCallSymbol, Document.FilePath, node.ToLog());
                //        }
                //    }
                //}

            }

            base.VisitInvocationExpression(node);
        }
        public override void VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            var symbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(node).Symbol;
            
            if (symbol != null)
            {
                var type = DetectIOAsynchronousUsages(node, symbol);
                Result.StoreDetectedIOAsyncUsage(type);

                //DetectBlockingOperations(node, symbol);

                //if (type == Enums.AsyncDetected.EAP)
                //    Logs.TempLog2.Info("{0}{1}*****************************************", Document.FilePath, node.FirstAncestorOrSelf<MethodDeclarationSyntax>().ToLog());

                if (type == Enums.AsyncDetected.TAP)
                    //Logs.TempLog3.Info("{0}{1}*****************************************", Document.FilePath, node.FirstAncestorOrSelf<MethodDeclarationSyntax>().ToLog());
                    Logs.TempLog3.Info("{0}", symbol);

                //if (type == Enums.AsyncDetected.APM)
                //    Logs.TempLog4.Info("{0}{1}*****************************************", Document.FilePath, node.FirstAncestorOrSelf<MethodDeclarationSyntax>().ToLog());

            }

            base.VisitInvocationExpression(node);
        }
        public static ArgumentSyntax FindAsyncStateInvocationArgument(InvocationExpressionSyntax apmSyntax, IMethodSymbol apmSymbol)
        {
            var parameterIndex = FindMethodParameterIndex(apmSymbol, "object", "state");
            var callbackArgument = apmSyntax.ArgumentList.Arguments.ElementAt(parameterIndex);

            return callbackArgument;
        }
        private IEnumerable<SignatureHelpItem> GetDelegateInvokeItems(
            InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService,
            IDocumentationCommentFormattingService documentationCommentFormattingService, ISymbol within, INamedTypeSymbol delegateType, CancellationToken cancellationToken)
        {
            var invokeMethod = delegateType.DelegateInvokeMethod;
            if (invokeMethod == null)
            {
                return null;
            }

            // Events can only be invoked directly from the class they were declared in.
            var expressionSymbol = semanticModel.GetSymbolInfo(invocationExpression.Expression, cancellationToken).GetAnySymbol();
            if (expressionSymbol.IsKind(SymbolKind.Event) &&
                !expressionSymbol.ContainingType.OriginalDefinition.Equals(within.OriginalDefinition))
            {
                return null;
            }

            var position = invocationExpression.SpanStart;
            var item = CreateItem(
                invokeMethod, semanticModel, position,
                symbolDisplayService, anonymousTypeDisplayService,
                isVariadic: invokeMethod.IsParams(),
                documentation: SpecializedCollections.EmptyEnumerable<SymbolDisplayPart>(),
                prefixParts: GetDelegateInvokePreambleParts(invokeMethod, semanticModel, position),
                separatorParts: GetSeparatorParts(),
                suffixParts: GetDelegateInvokePostambleParts(),
                parameters: GetDelegateInvokeParameters(invokeMethod, semanticModel, position, documentationCommentFormattingService, cancellationToken));

            return SpecializedCollections.SingletonEnumerable(item);
        }
        /// <summary>
        /// Creates a new ExpressionSyntax to replace the defaultIfNull InvocationExpressionSyntax
        /// </summary>
        public static ExpressionSyntax CreateRelacementNode(InvocationExpressionSyntax defaultIfNullexpression)
        {
            // We should change from  x.DefaultIfNull(y => y.z...)  or  x.DefaultIfNull(y => y.[..]...)
            //                  into  x?.z...                           x?[..]...

            // Get the expression on which DefaultIfNull is invoked, this is the x
            var rootExpression = (defaultIfNullexpression.Expression as MemberAccessExpressionSyntax)?.Expression;

            // Get the first parameter to DefaultIfNull, this is the Lambda y => y.z...
            var lambda = GetLambdaFromFirstArgument(defaultIfNullexpression);
            if (lambda == null) return defaultIfNullexpression;

            // Get the MemberAccessExpression y.z or ElementAccessExpression y[..] from the lamba body
            var accessExpression = GetLeftMostAccessExpression(lambda);
            if (accessExpression == null) return defaultIfNullexpression;

            // A ConditionalAccessExpression requires a ..BindingExpression instead of the ..AccessExpression
            var bindingExpression = ToBindingExpression(accessExpression);

            // Replace the AccessExpression from the Labmda body with the BindingExpression this will result in the .z... or [..]... part
            var whenNotNullExpression = (ExpressionSyntax)lambda.Body.ReplaceNode(accessExpression, bindingExpression)
                                                                        .WithTriviaFrom(accessExpression);

            // Combine the x and .z... into x?.z...
            return SyntaxFactory.ConditionalAccessExpression(
                expression: rootExpression,
                whenNotNull: whenNotNullExpression).WithTriviaFrom(defaultIfNullexpression);
        }
Example #6
0
        public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            // Replace the module method name with a qualified one if this is a module ctor
            bool nodeChanged = IsInvocationAModuleCtor(node);
            ExpressionSyntax nodeExpression = nodeChanged
                ? ((IdentifierNameSyntax)node.Expression).WithIdentifier(
                    SyntaxFactory.Identifier("ConfigScript." + ((IdentifierNameSyntax)node.Expression).Identifier.Text)
                        .WithTriviaFrom(((IdentifierNameSyntax)node.Expression).Identifier))
                : node.Expression;

            // Get a hash of all the previous @doc and @ctx lambda parameters and don't replace the same
            HashSet<string> currentScopeLambdaParameters = new HashSet<string>(
                node.Ancestors().OfType<LambdaExpressionSyntax>().SelectMany(
                    x => x.DescendantNodes().OfType<ParameterSyntax>()).Select(x => x.Identifier.Text));

            // Only do the replacement if this is a module ctor or a module fluent method
            ArgumentListSyntax argumentList = node.ArgumentList;
            if(nodeChanged || IsInvocationAFluentMethod(node))
            {
                // Replace @doc and @ctx argument expressions with the appropriate lambda expressions, and stop descending if we hit another module ctor
                foreach (ArgumentSyntax argument in node.ArgumentList.Arguments)
                {
                    // Don't replace existing lambda expressions
                    if (!(argument.Expression is LambdaExpressionSyntax))
                    {
                        List<IdentifierNameSyntax> identifierNames = argument
                            .DescendantNodes(x => !(x is InvocationExpressionSyntax) || !IsInvocationAModuleCtorOrFluentMethod((InvocationExpressionSyntax)x))
                            .OfType<IdentifierNameSyntax>()
                            .Where(x => x != null && !currentScopeLambdaParameters.Contains(x.Identifier.Text))
                            .ToList();
                        IdentifierNameSyntax docReplacementName = identifierNames.FirstOrDefault(x => x.Identifier.Text.StartsWith("@doc"));
                        IdentifierNameSyntax ctxReplacementName = identifierNames.FirstOrDefault(x => x.Identifier.Text.StartsWith("@ctx"));
                        if (docReplacementName != null)
                        {
                            argumentList = argumentList.ReplaceNode(argument, SyntaxFactory.Argument(
                                SyntaxFactory.ParenthesizedLambdaExpression(
                                    SyntaxFactory.ParameterList(
                                        new SeparatedSyntaxList<ParameterSyntax>()
                                            .Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(docReplacementName.Identifier.Text)))
                                            .Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(ctxReplacementName == null ? "_" : ctxReplacementName.Identifier.Text)))),
                                    argument.Expression))
                                .WithTriviaFrom(argument));
                            nodeChanged = true;
                        }
                        else if (ctxReplacementName != null)
                        {
                            argumentList = argumentList.ReplaceNode(argument, SyntaxFactory.Argument(
                                SyntaxFactory.SimpleLambdaExpression(
                                    SyntaxFactory.Parameter(SyntaxFactory.Identifier(ctxReplacementName.Identifier.Text)),
                                    argument.Expression))
                                .WithTriviaFrom(argument));
                            nodeChanged = true;
                        }
                    }
                }
            }

            // Build and return the result node (or just return the original node)
            return base.VisitInvocationExpression(nodeChanged ? node.WithExpression(nodeExpression).WithArgumentList(argumentList) : node);
        }
        public override void VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            var symbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(node).Symbol;

            if (symbol != null)
            {
                if(symbol.ToString().Contains("System.Threading.Tasks.Task.WaitAll"))
                {
                    var block = node.Ancestors().OfType<BlockSyntax>().First();

                    if (block.DescendantNodes().OfType<ForEachStatementSyntax>().Any() || block.DescendantNodes().OfType<ForStatementSyntax>().Any())
                        return;
                    foreach (var invocation in block.DescendantNodes().OfType<InvocationExpressionSyntax>())
                    {
                        var symbol2 = (IMethodSymbol)SemanticModel.GetSymbolInfo(invocation).Symbol;
                        if (symbol2!=null && symbol2.IsTaskCreationMethod())
                        {
                            Logs.TempLog3.Info("{0}{1}--------------------------", Document.FilePath, block.ToLog());
                            break;
                        }
                    }
                    
                }

            }


            base.VisitInvocationExpression(node);
        }
        private async Task<Document> CreateInterpolatedString(InvocationExpressionSyntax invocation, Document document, CancellationToken cancellationToken)
        {
            Assert(invocation.ArgumentList != null);
            Assert(invocation.ArgumentList.Arguments.Count >= 2);
            Assert(invocation.ArgumentList.Arguments[0].Expression.IsKind(SyntaxKind.StringLiteralExpression));

            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            var arguments = invocation.ArgumentList.Arguments;
            var text = ((LiteralExpressionSyntax)arguments[0].Expression).Token.ToString();

            var builder = ImmutableArray.CreateBuilder<ExpressionSyntax>();
            for (int i = 1; i < arguments.Count; i++)
            {
                builder.Add(CastAndParenthesize(arguments[i].Expression, semanticModel));
            }

            var expandedArguments = builder.ToImmutable();

            var interpolatedString = (InterpolatedStringExpressionSyntax)SyntaxFactory.ParseExpression("$" + text);

            var newInterpolatedString = InterpolatedStringRewriter.Visit(interpolatedString, expandedArguments);

            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = root.ReplaceNode(invocation, newInterpolatedString);

            return document.WithSyntaxRoot(newRoot);
        }
        private Task<Document> ConvertToInterpolatedString(Document document, SyntaxNode root, InvocationExpressionSyntax invocation, CancellationToken cancellationToken)
        {
            string previousString = null;
            var parts = new List<InterpolatedStringContentSyntax>(invocation.ArgumentList.Arguments.Count);
            for (int i = 0; i < invocation.ArgumentList.Arguments.Count; i++)
            {
                ArgumentSyntax argument = invocation.ArgumentList.Arguments[i];
                var literal = argument.Expression as LiteralExpressionSyntax;

                if (literal?.IsKind(SyntaxKind.StringLiteralExpression) ?? false)
                {
                    //strings needs to be collapsed, otherwise VS will insert additional whitespaces
                    previousString += literal.Token.Text.Substring(1, literal.Token.Text.Length - 2);
                }
                else
                {
                    if (previousString != null)
                    {
                        parts.Add(InterpolatedStringGenerator.TextPart(previousString));
                        previousString = null;
                    }
                    parts.Add(InterpolatedStringGenerator.ExpressionPart(argument.Expression.WithoutLeadingTrivia().WithoutTrailingTrivia()));
                }
            }
            if (previousString != null)
            {
                parts.Add(InterpolatedStringGenerator.TextPart(previousString));
            }

            SyntaxNode interpolated = InterpolatedStringGenerator.InterpolatedString(parts);

            root = root.ReplaceNode(invocation, interpolated);

            return Task.FromResult(document.WithSyntaxRoot(root));
        }
        public override void VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            var symbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(node).Symbol;
            
            if (symbol != null)
            {
                var asynctype = DetectAsynchronousUsages(node, symbol);
                Result.StoreDetectedAsyncUsage(asynctype);
                Result.WriteDetectedAsyncUsage(asynctype, Document.FilePath, symbol);
                Result.WriteDetectedAsyncUsageToTable(asynctype,Document,symbol,node);
                //if (asynctype == Enums.AsyncDetected.Task || asynctype == Enums.AsyncDetected.Threadpool || asynctype == Enums.AsyncDetected.Thread)
                //{
                //    foreach (var methodCall in node.DescendantNodes().OfType<InvocationExpressionSyntax>())
                //    {

                //        var methodCallSymbol = (MethodSymbol)SemanticModel.GetSymbolInfo(methodCall).Symbol;

                //        if (methodCallSymbol != null)
                //        {
                //            var synctype = ((MethodSymbol)methodCallSymbol.OriginalDefinition).DetectSynchronousUsages(SemanticModel);

                //            if (synctype != Utilities.Enums.SyncDetected.None)
                //                Logs.TempLog.Info("LONGRUNNING {0} {1}\r\n{2}\r\n--------------------------", methodCallSymbol, Document.FilePath, node);
                //        }
                //    }
                //}
                 
            }


            base.VisitInvocationExpression(node);
        }
 public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
 {
     return SimplifyExpression(
         node,
         newNode: base.VisitInvocationExpression(node),
         simplifier: SimplifyExtensionMethod);
 }
 public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
 {
     var memberAccessExpression = node.Expression as MemberAccessExpressionSyntax;
     if (memberAccessExpression != null && memberAccessExpression.Name.ToString() == "TransformExpression")
         _transform = true;
     return base.VisitInvocationExpression(node);
 }
        static Document PerformAction(Document document, SyntaxNode root, InvocationExpressionSyntax invocationNode)
        {
            var arg = invocationNode.ArgumentList.Arguments.Select(a => a.Expression).First();
            if (!arg.DescendantNodesAndSelf().OfType<BinaryExpressionSyntax>().All(bop => bop.IsKind(SyntaxKind.BitwiseOrExpression)))
                return document;

            arg = ConvertBitwiseFlagComparisonToHasFlagsCodeRefactoringProvider.MakeFlatExpression(arg, SyntaxKind.BitwiseAndExpression);
            if (arg is BinaryExpressionSyntax)
                arg = SyntaxFactory.ParenthesizedExpression(arg);

            SyntaxNode nodeToReplace = invocationNode;
            while (nodeToReplace.Parent is ParenthesizedExpressionSyntax)
                nodeToReplace = nodeToReplace.Parent;

            bool negateHasFlags = nodeToReplace.Parent != null && nodeToReplace.Parent.IsKind(SyntaxKind.LogicalNotExpression);
            if (negateHasFlags)
                nodeToReplace = nodeToReplace.Parent;

            var expr = SyntaxFactory.BinaryExpression(
                negateHasFlags ? SyntaxKind.EqualsExpression : SyntaxKind.NotEqualsExpression,
                SyntaxFactory.ParenthesizedExpression(SyntaxFactory.BinaryExpression(SyntaxKind.BitwiseAndExpression, ((MemberAccessExpressionSyntax)invocationNode.Expression).Expression, arg))
                .WithAdditionalAnnotations(Formatter.Annotation),
                SyntaxFactory.ParseExpression("0")
            );

            var newRoot = root.ReplaceNode((SyntaxNode)
                nodeToReplace,
                expr.WithAdditionalAnnotations(Formatter.Annotation)
            );
            return document.WithSyntaxRoot(newRoot);
        }
            private void AnalyzeInvocationExpression(InvocationExpressionSyntax node, SemanticModel model, Action<Diagnostic> reportDiagnostic)
            {
                if (node.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
                {
                    var memberAccess = (MemberAccessExpressionSyntax)node.Expression;
                    if (memberAccess.Name != null && IsEqualsOrCompare(memberAccess.Name.Identifier.ValueText))
                    {
                        var methodSymbol = model.GetSymbolInfo(memberAccess.Name).Symbol as IMethodSymbol;
                        if (methodSymbol != null && methodSymbol.ContainingType.SpecialType == SpecialType.System_String)
                        {
                            Debug.Assert(IsEqualsOrCompare(methodSymbol.Name));

                            if (!IsAcceptableOverload(methodSymbol, model))
                            {
                                // wrong overload
                                reportDiagnostic(memberAccess.Name.GetLocation().CreateDiagnostic(Rule));
                            }
                            else
                            {
                                var lastArgument = node.ArgumentList.Arguments.Last();
                                var lastArgSymbol = model.GetSymbolInfo(lastArgument.Expression).Symbol;
                                if (lastArgSymbol != null && lastArgSymbol.ContainingType != null &&
                                    lastArgSymbol.ContainingType.Equals(StringComparisonType) &&
                                    !IsOrdinalOrOrdinalIgnoreCase(lastArgument, model))
                                {
                                    // right overload, wrong value
                                    reportDiagnostic(lastArgument.GetLocation().CreateDiagnostic(Rule));
                                }
                            }
                        }
                    }
                }
            }
 private static bool HasCheckForNullThatReturns(InvocationExpressionSyntax invocation, SemanticModel semanticModel, ISymbol symbol)
 {
     var method = invocation.FirstAncestorOfKind(SyntaxKind.MethodDeclaration) as MethodDeclarationSyntax;
     if (method != null && method.Body != null)
     {
         var ifs = method.Body.Statements.OfKind(SyntaxKind.IfStatement);
         foreach (IfStatementSyntax @if in ifs)
         {
             if ([email protected]?.IsKind(SyntaxKind.EqualsExpression) ?? true) continue;
             var equals = (BinaryExpressionSyntax)@if.Condition;
             if (equals.Left == null || equals.Right == null) continue;
             if (@if.GetLocation().SourceSpan.Start > invocation.GetLocation().SourceSpan.Start) return false;
             ISymbol identifierSymbol;
             if (equals.Right.IsKind(SyntaxKind.NullLiteralExpression) && equals.Left.IsKind(SyntaxKind.IdentifierName))
                 identifierSymbol = semanticModel.GetSymbolInfo(equals.Left).Symbol;
             else if (equals.Left.IsKind(SyntaxKind.NullLiteralExpression) && equals.Right.IsKind(SyntaxKind.IdentifierName))
                 identifierSymbol = semanticModel.GetSymbolInfo(equals.Right).Symbol;
             else continue;
             if (!symbol.Equals(identifierSymbol)) continue;
             if (@if.Statement == null) continue;
             if (@if.Statement.IsKind(SyntaxKind.Block))
             {
                 var ifBlock = (BlockSyntax)@if.Statement;
                 if (ifBlock.Statements.OfKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement).Any()) return true;
             }
             else
             {
                 if (@if.Statement.IsAnyKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement)) return true;
             }
         }
     }
     return false;
 }
 private static SyntaxNode RemoveCall(SyntaxNode root,
     InvocationExpressionSyntax castInvocation, MemberAccessExpressionSyntax memberAccess)
 {
     return castInvocation != null
         ? RemoveExtensionMethodCall(root, castInvocation)
         : RemoveStaticMemberCall(root, memberAccess);
 }
 private static bool IsLambdaWithoutBody(InvocationExpressionSyntax invocation)
 {
     var arg = invocation.ArgumentList?.Arguments.First();
     var lambda = arg.Expression as LambdaExpressionSyntax;
     if (lambda == null) return false;
     return !(lambda.Body is BlockSyntax);
 }
Example #18
0
        /// <summary>
        /// Rewrites the statement with a monitor statement.
        /// </summary>
        /// <param name="node">LocalDeclarationStatementSyntax</param>
        /// <returns>StatementSyntax</returns>
        private SyntaxNode RewriteStatement(InvocationExpressionSyntax node)
        {
            var arguments = new List<ArgumentSyntax>();
            arguments.Add(node.ArgumentList.Arguments[0]);

            string payload = "";
            for (int i = 1; i < node.ArgumentList.Arguments.Count; i++)
            {
                if (i == node.ArgumentList.Arguments.Count - 1)
                {
                    payload += node.ArgumentList.Arguments[i].ToString();
                }
                else
                {
                    payload += node.ArgumentList.Arguments[i].ToString() + ", ";
                }
            }

            arguments[0] = SyntaxFactory.Argument(SyntaxFactory.ParseExpression(
                "new " + arguments[0].ToString() + "(" + payload + ")"));

            var rewritten = node.
                WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))).
                WithExpression((node.Expression as GenericNameSyntax).
                WithIdentifier(SyntaxFactory.Identifier("this.Monitor"))).
                WithTriviaFrom(node);

            return rewritten;
        }
        private static void CheckIsInstanceOfTypeCallWithTypeArgument(InvocationExpressionSyntax invocation, IMethodSymbol methodSymbol,
            SyntaxNodeAnalysisContext context)
        {
            if (methodSymbol.Name != "IsInstanceOfType" ||
                !methodSymbol.ContainingType.Is(KnownType.System_Type) ||
                !invocation.HasExactlyNArguments(1))
            {
                return;
            }

            var argument = invocation.ArgumentList.Arguments.First().Expression;

            var typeInfo = context.SemanticModel.GetTypeInfo(argument).Type;
            if (!typeInfo.Is(KnownType.System_Type))
            {
                return;
            }

            var invocationInArgument = argument as InvocationExpressionSyntax;
            var message = IsGetTypeCall(invocationInArgument, context.SemanticModel)
                ? MessageIsInstanceOfTypeWithGetType
                : MessageIsInstanceOfType;

            context.ReportDiagnostic(Diagnostic.Create(Rule, argument.GetLocation(), message));
        }
		async Task<Document> MakeUppercaseAsync(Document document, InvocationExpressionSyntax invocation,
			CancellationToken cancellationToken)
		{
			var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
			var typeSymbol = semanticModel.GetSymbolInfo(invocation.Expression, cancellationToken).Symbol;
			var nfluentCheck = semanticModel.Compilation.NFluentCheckType();

			if (typeSymbol == null || nfluentCheck == null) return document;

			var newMethod = typeSymbol.Name == "AreEqual" ? "IsEqualTo" : "IsNotEqualTo";

			var checkThat = CheckThat(nfluentCheck, invocation.ArgumentList.Arguments[1]);

			var replacement = InvocationExpression(
				MemberAccessExpression(
					SyntaxKind.SimpleMemberAccessExpression,
					checkThat,
					IdentifierName(newMethod)),
				ArgumentList(SingletonSeparatedList(invocation.ArgumentList.Arguments[0])))
				.WithTriviaFrom(invocation);

			var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
			var newSyntaxRoot = syntaxRoot.ReplaceNode(invocation, replacement);
			var newDocument = document.WithSyntaxRoot(newSyntaxRoot);

			var withUsings = await UsingHelpers.AddUsingsAsync(newDocument, replacement, cancellationToken,
				nfluentCheck.ContainingNamespace);

			return withUsings;
		}
Example #21
0
        private async Task<Document> ChangeToOneLiteral(InvocationExpressionSyntax ex, Document document, CancellationToken cancellationToken)
        {
            var literal1 = ex.GetLiteralExpression();
            if (literal1 == null) return document;

            var literal2 = ex.GetLiteralArgument();
            if (literal2 == null) return document;

            var x = int.Parse(literal1.Token.ValueText);
            var y = int.Parse(literal2.Token.ValueText);
            var newValue = 0;

            switch (ex.GetMemberName())
            {
                case "Add": newValue = x + y; break;
                case "Sub": newValue = x - y; break;
                case "Mul": newValue = x * y; break;
                case "Div": newValue = x / y; break;
            }

            var newLiteral = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(newValue))
                .WithLeadingTrivia(ex.GetLeadingTrivia())
                .WithTrailingTrivia(ex.GetTrailingTrivia())
                ;

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = oldRoot.ReplaceNode(ex, newLiteral);

            return document.WithSyntaxRoot(newRoot);
        }
Example #22
0
        public ExpressionSyntax Replace(InvocationExpressionSyntax invocation)
        {
            var replacement = string.Format(@"Nake.TaskRegistry.Invoke(""{0}"", {1})",
                                              task.FullName, BuildArgumentString(invocation));

            return SyntaxFactory.ParseExpression(replacement)
                         .WithLeadingTrivia(invocation.GetLeadingTrivia());
        }
        static SyntaxNode ToStaticMethodInvocation(SemanticModel model, InvocationExpressionSyntax invocation, MemberAccessExpressionSyntax memberAccess, SymbolInfo invocationRR)
        {
            var newArgumentList = invocation.ArgumentList.Arguments.ToList();
            newArgumentList.Insert(0, SyntaxFactory.Argument(memberAccess.Expression.WithoutLeadingTrivia()));

            var newTarget = memberAccess.WithExpression(SyntaxFactory.ParseTypeName(invocationRR.Symbol.ContainingType.ToMinimalDisplayString(model, memberAccess.SpanStart)));
            return SyntaxFactory.InvocationExpression(newTarget, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(newArgumentList)));
        }
 static bool VerifyMethodCalled(InvocationExpressionSyntax methodCalled, SyntaxNodeAnalysisContext nodeContext)
 {
     if (methodCalled == null)
         throw new ArgumentNullException();
     var expression = methodCalled.Expression as MemberAccessExpressionSyntax;
     var symbol = nodeContext.SemanticModel.GetSymbolInfo(expression).Symbol;
     return symbol.ContainingType.SpecialType == SpecialType.System_String && symbol.Name == "ToCharArray";
 }
        public bool IsPure(InvocationExpressionSyntax methodInvocation)
        {
            Contract.Requires(methodInvocation != null);

            var symbol = _semanticModel.GetSymbolInfo(methodInvocation).Symbol as IMethodSymbol;

            return symbol != null && IsPure(symbol);
        }
		protected override ExpressionSyntax InspectExpression(InvocationExpressionSyntax node, int cancellationTokenPos, IMethodSymbol candidate, bool explicitExtensionMethodCall)
		{
			var result = base.InspectExpression(node, cancellationTokenPos, candidate, explicitExtensionMethodCall);

			this.results.Add(new ValidatorResult { MethodInvocationSyntax = node, ReplacementExpressionSyntax = result, ReplacementMethodSymbol = candidate });

			return node;
		}
 private static SyntaxNode ReplaceInvocation(InvocationExpressionSyntax invocation, ExpressionSyntax newInvocation, SyntaxNode root)
 {
     if (invocation.Parent.IsKind(SyntaxKind.LogicalNotExpression))
         return root.ReplaceNode(invocation.Parent, newInvocation);
     var negatedInvocation = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, newInvocation);
     var newRoot = root.ReplaceNode(invocation, negatedInvocation);
     return newRoot;
 }
Example #28
0
        static string BuildArgumentString(InvocationExpressionSyntax invocation)
        {
            var arguments = invocation.ArgumentList.Arguments;

            return arguments.Count != 0
                ? string.Join(", ", arguments.Select(FormatArgument))
                : "new Nake.TaskArgument[0]";
        }
        public static bool TryGetFormattingParameters(
            SemanticModel semanticModel,
            InvocationExpressionSyntax invocationExpression,
            out ExpressionSyntax formatArgument, out IList<ExpressionSyntax> arguments,
            Func<IParameterSymbol, ExpressionSyntax, bool> argumentFilter,
            CancellationToken cancellationToken = default (CancellationToken))
        {
            if (semanticModel == null)
                throw new ArgumentNullException(nameof(semanticModel));
            if (invocationExpression == null)
                throw new ArgumentNullException(nameof(invocationExpression));
            var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression.Expression, cancellationToken);
            if (argumentFilter == null)
                argumentFilter = (p, e) => true;

            var symbol = symbolInfo.Symbol;
            formatArgument = null;
            arguments = new List<ExpressionSyntax>();
            var method = symbol as IMethodSymbol;

            if (method == null || method.Kind != SymbolKind.Method)
                return false;

            // Serach for method of type: void Name(string format, params object[] args);
            IList<IMethodSymbol> methods = method.ContainingType.GetMembers (method.Name).OfType<IMethodSymbol>().ToList();
            if (!methods.Any(m => m.Parameters.Length == 2 && 
                             m.Parameters[0].Type.SpecialType == SpecialType.System_String && parameterNames.Contains(m.Parameters[0].Name) && 
                             m.Parameters[1].IsParams))
                return false;

            // TODO: Handle argument -> parameter mapping.
            //var argumentToParameterMap = invocationResolveResult.GetArgumentToParameterMap();
            //var resolvedParameters = invocationResolveResult.Member.Parameters;
            var allArguments = invocationExpression.ArgumentList.Arguments.ToArray();
            for (int i = 0; i < allArguments.Length; i++) {
                var parameterIndex = i; //argumentToParameterMap[i];
                if (parameterIndex < 0 || parameterIndex >= method.Parameters.Length) {
                    // No valid mapping for this argument, skip it
                    continue;
                }
                var parameter = method.Parameters[parameterIndex];
                var argument = allArguments[i];
                if (i == 0 && parameter.Type.SpecialType == SpecialType.System_String && parameterNames.Contains(parameter.Name)) {
                    formatArgument = argument.Expression;
                } else if (formatArgument != null && parameter.IsParams /*&& !invocationResolveResult.IsExpandedForm*/) {
                    var ace = argument.Expression as ArrayCreationExpressionSyntax;
                    if (ace == null || ace.Initializer == null)
                        return false;
                    foreach (var element in ace.Initializer.Expressions) {
                        if (argumentFilter(parameter, element))
                            arguments.Add(argument.Expression);
                    }
                } else if (formatArgument != null && argumentFilter(parameter, argument.Expression)) {
                    arguments.Add(argument.Expression);
                }
            }
            return formatArgument != null;
        }
		public override void VisitInvocationExpression(InvocationExpressionSyntax node)
		{
			var symbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(node).Symbol;

			if (symbol != null)
			{
                IsAsyncLibraryConstruct(symbol.OriginalDefinition);

                if (symbol.IsAPMBeginMethod())
                {
                    Logs.TempLog.Info(SourceFile.FilePath + "\n" + node + "\n" + symbol + "\n"+ node.FirstAncestorOrSelf<MethodDeclarationSyntax>() + "******************\n");
                    Result.APM++;
                }
                else if (node.IsEAPMethod())
                {
                    Result.EAP++;
                }
                else if (symbol.IsTAPMethod())
                {
                    // printing TAP methods: Logs.TempLog.Info(SourceFile.FilePath + "\n" + node + "\n" + symbol + "******************\n");
                    Result.TAP++;
                }
                else if (symbol.IsThreadStart())
                {
                    Result.ThreadInit++;
                }
                else if (symbol.IsThreadPoolQueueUserWorkItem())
                {
                    Result.ThreadPoolQueue++;
                }
                else if (symbol.IsBackgroundWorkerMethod())
                {
                    Result.BackgroundWorker++;
                }
                else if (symbol.IsAsyncDelegate())
                {
                    Result.AsyncDelegate++;
                }
                else if (symbol.IsTaskCreationMethod())
                {
                    Result.TaskInit++;
                }
                else if (symbol.IsParallelFor())
                {
                    Result.ParallelFor++;
                }
                else if (symbol.IsParallelForEach())
                {
                    Result.ParallelForEach++;
                }
                else if (symbol.IsParallelInvoke())
                {
                    Result.ParallelInvoke++;
                }
			}

			base.VisitInvocationExpression(node);
		}
Example #31
0
        private static InvocationExpressionSyntax Merge(
            InvocationExpressionSyntax outerMostInvocation,
            MemberAccessExpressionSyntax innerMostWhereAccess,
            List <ExpressionSyntax> whereArguments,
            SemanticModel semanticModel)
        {
            var firstArgument = whereArguments[0];

            string               parameterName;
            ParameterSyntax      firstParameter;
            IdentifierNameSyntax firstParameterIdentifier;
            ExpressionSyntax     filterExpression;

            if (firstArgument.IsKind(SyntaxKind.SimpleLambdaExpression))
            {
                var lambda = (SimpleLambdaExpressionSyntax)firstArgument;
                firstParameter           = lambda.Parameter;
                parameterName            = firstParameter.Identifier.Text;
                firstParameterIdentifier = SyntaxFactory.IdentifierName(firstParameter.Identifier);
                filterExpression         = MakeExpressionFromLambdaBody(lambda.Body);
            }
            else
            {
                parameterName = NameHelper.GetLambdaParameterName(
                    outerMostInvocation.SpanStart,
                    semanticModel);

                var parameterIdentifier = SyntaxFactory
                                          .Identifier(parameterName)
                                          .WithAdditionalAnnotations(RenameAnnotation.Create());

                firstParameter = SyntaxFactory.Parameter(parameterIdentifier);

                firstParameterIdentifier = SyntaxFactory.IdentifierName(parameterIdentifier);

                filterExpression = ExtendedSyntaxFactory.MakeInvocation(
                    firstArgument,
                    firstParameterIdentifier);
            }


            for (int i = 1; i < whereArguments.Count; ++i)
            {
                ExpressionSyntax andOperand;

                if (whereArguments[i].IsKind(SyntaxKind.SimpleLambdaExpression))
                {
                    var currentLambda        = (SimpleLambdaExpressionSyntax)whereArguments[i];
                    var currentParameter     = currentLambda.Parameter;
                    var currentParameterName = currentParameter.Identifier.Text;

                    if (currentParameterName != parameterName)
                    {
                        var parameterSymbol = semanticModel.GetDeclaredSymbol(currentParameter);

                        var substituteRewriter = new SubstituteRewriter(
                            currentParameterName,
                            parameterSymbol,
                            semanticModel,
                            firstParameterIdentifier);

                        var newBody = (CSharpSyntaxNode)currentLambda.Body.Accept(substituteRewriter);

                        andOperand = MakeExpressionFromLambdaBody(newBody);
                    }
                    else
                    {
                        andOperand = MakeExpressionFromLambdaBody(currentLambda.Body);
                    }
                }
                else
                {
                    andOperand = ExtendedSyntaxFactory.MakeInvocation(
                        whereArguments[i],
                        firstParameterIdentifier);
                }

                filterExpression = SyntaxFactory.BinaryExpression(
                    SyntaxKind.LogicalAndExpression,
                    filterExpression,
                    andOperand);
            }

            var newLambda = SyntaxFactory.SimpleLambdaExpression(
                firstParameter,
                filterExpression);

            var newInvocation = ExtendedSyntaxFactory.MakeInvocation(
                innerMostWhereAccess,
                newLambda);

            return(newInvocation);
        }
        public override void VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            Console.WriteLine($"[Walker] Found expression: {node}");

            base.VisitInvocationExpression(node);
        }
Example #33
0
        public static SyntaxNode MethodInvocation(string name, MethodBase methodInfo, SyntaxNode instance, List <ArgumentSyntax> argumentList, TypeArgumentListSyntax typeArgumentList)
        {
            var sepList = SyntaxFactory.SeparatedList(argumentList);

            if (methodInfo == null)
            {
                return(SyntaxFactory.EmptyStatement());
            }

            var  propertyInfos = methodInfo.DeclaringType?.GetProperties();
            var  isSetAccessor = propertyInfos?.FirstOrDefault(prop => prop.GetSetMethod() == methodInfo);
            var  isGetAccessor = propertyInfos?.FirstOrDefault(prop => prop.GetGetMethod() == methodInfo);
            bool isProperty    = isSetAccessor != null || isGetAccessor != null;
            var  methodName    = methodInfo.Name;

            if (isProperty)
            {
                methodName = name.Substring(4);
            }

            bool             isGenericMethod        = methodInfo.IsGenericMethod;
            ExpressionSyntax finalExpressionSyntax  = null;
            ExpressionSyntax memberAccessExpression = instance == null?SyntaxFactory.IdentifierName(methodInfo.DeclaringType?.Name) : instance as ExpressionSyntax;

            if (!isProperty)
            {
                if (methodInfo.IsConstructor)
                {
                    finalExpressionSyntax = SyntaxFactory.ObjectCreationExpression(
                        TypeSystem.BuildTypeSyntax(methodInfo.DeclaringType))
                                            .WithArgumentList(SyntaxFactory.ArgumentList(sepList));
                }
                else
                {
                    SimpleNameSyntax genericName = isGenericMethod
                        ? (SimpleNameSyntax)SyntaxFactory.GenericName(
                        SyntaxFactory.Identifier(methodName))
                                                   .WithTypeArgumentList(typeArgumentList)
                        : SyntaxFactory.IdentifierName(methodName);

                    InvocationExpressionSyntax invocation = SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            memberAccessExpression,
                            genericName
                            )
                        );
                    finalExpressionSyntax = invocation
                                            .WithArgumentList(SyntaxFactory.ArgumentList(sepList));
                }
            }
            else
            {
                if (isGetAccessor != null)
                {
                    if (isGetAccessor.GetIndexParameters().Length > 0)
                    {
                        finalExpressionSyntax = SyntaxFactory.ElementAccessExpression(
                            memberAccessExpression,
                            SyntaxFactory.BracketedArgumentList(sepList));
                    }
                    else
                    {
                        finalExpressionSyntax = SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            memberAccessExpression,
                            SyntaxFactory.IdentifierName(methodName));
                    }
                }
                else if (isSetAccessor != null)
                {
                    ExpressionSyntax left;
                    if (isSetAccessor.GetIndexParameters().Length > 0)
                    {
                        left = SyntaxFactory.ElementAccessExpression(memberAccessExpression, SyntaxFactory.BracketedArgumentList(
                                                                         SyntaxFactory.SeparatedList(argumentList.Take(argumentList.Count - 1))
                                                                         ));
                    }
                    else
                    {
                        left = SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            memberAccessExpression,
                            SyntaxFactory.IdentifierName(methodName));
                    }

                    finalExpressionSyntax = SyntaxFactory.AssignmentExpression(
                        SyntaxKind.SimpleAssignmentExpression,
                        left,
                        argumentList.Last().Expression);
                }
            }

            return(finalExpressionSyntax);
        }
Example #34
0
        ParameterHintingResult HandleInvocationExpression(SemanticModel semanticModel, InvocationExpressionSyntax node, CancellationToken cancellationToken)
        {
            var info   = semanticModel.GetSymbolInfo(node, cancellationToken);
            var result = new ParameterHintingResult(node.SpanStart);

            var targetTypeInfo = semanticModel.GetTypeInfo(node.Expression);

            if (targetTypeInfo.Type != null && targetTypeInfo.Type.TypeKind == TypeKind.Delegate)
            {
                result.AddData(factory.CreateMethodDataProvider(targetTypeInfo.Type.GetDelegateInvokeMethod()));
                return(result);
            }

            var         within = semanticModel.GetEnclosingNamedTypeOrAssembly(node.SpanStart, cancellationToken);
            ITypeSymbol type;
            string      name         = null;
            bool        staticLookup = false;
            var         ma           = node.Expression as MemberAccessExpressionSyntax;
            var         mb           = node.Expression as MemberBindingExpressionSyntax;

            if (mb != null)
            {
                info = semanticModel.GetSymbolInfo(mb, cancellationToken);
                type = (info.Symbol ?? info.CandidateSymbols.FirstOrDefault())?.ContainingType;
                name = mb.Name.Identifier.ValueText;
            }
            else if (ma != null)
            {
                staticLookup = semanticModel.GetSymbolInfo(ma.Expression).Symbol is ITypeSymbol;
                type         = semanticModel.GetTypeInfo(ma.Expression).Type;
                name         = info.Symbol?.Name ?? ma.Name.Identifier.ValueText;
            }
            else
            {
                type = within as ITypeSymbol;
                name = info.Symbol?.Name ?? node.Expression.ToString();
                var sym = semanticModel.GetEnclosingSymbol(node.SpanStart, cancellationToken);
                staticLookup = sym.IsStatic;
            }
            var addedMethods = new List <IMethodSymbol> ();
            var filterMethod = new HashSet <IMethodSymbol> ();

            for (; type != null; type = type.BaseType)
            {
                foreach (var method in type.GetMembers().OfType <IMethodSymbol> ().Concat(GetExtensionMethods(semanticModel, type, node, cancellationToken)).Where(m => m.Name == name))
                {
                    if (staticLookup && !method.IsStatic)
                    {
                        continue;
                    }
                    if (method.OverriddenMethod != null)
                    {
                        filterMethod.Add(method.OverriddenMethod);
                    }
                    if (filterMethod.Contains(method))
                    {
                        continue;
                    }
                    if (addedMethods.Any(added => SignatureComparer.Instance.HaveSameSignature(method, added, true)))
                    {
                        continue;
                    }
                    if (method.IsAccessibleWithin(within))
                    {
                        if (info.Symbol != null)
                        {
                            var smethod = (IMethodSymbol)info.Symbol;
                            if (smethod != null && smethod.OriginalDefinition == method)
                            {
                                continue;
                            }
                        }
                        addedMethods.Add(method);
                        result.AddData(factory.CreateMethodDataProvider(method));
                    }
                }
            }
            if (info.Symbol != null && !addedMethods.Contains(info.Symbol))
            {
                if (!staticLookup || info.Symbol.IsStatic)
                {
                    result.AddData(factory.CreateMethodDataProvider((IMethodSymbol)info.Symbol));
                }
            }
            return(result);
        }
Example #35
0
 protected override SyntaxNode GetInvocationReceiver(InvocationExpressionSyntax invocation)
 {
     return((invocation.Expression as MemberAccessExpressionSyntax)?.Expression);
 }
Example #36
0
 public static ArgumentSyntax FirstArgument(this InvocationExpressionSyntax node)
 {
     return node.ArgumentList.Arguments.FirstOrDefault();
 }
Example #37
0
 protected override SyntaxNode GetInvocationExpression(InvocationExpressionSyntax invocation)
 {
     return(invocation.Expression);
 }
Example #38
0
 public static ExpressionSyntax GetLeftSideExpression(this InvocationExpressionSyntax node)
 {
     return node.Expression.As<MemberAccessExpressionSyntax>()?.Expression;
 }
Example #39
0
 public static string GetLeftSideIdentifier(this InvocationExpressionSyntax node)
 {
     return node.Expression.As<MemberAccessExpressionSyntax>()?.Expression.ToString();
 }
Example #40
0
 public static SimpleNameSyntax GetRightSideNameSyntax(this InvocationExpressionSyntax node)
 {
     return node.Expression.As<MemberAccessExpressionSyntax>()?.Name;
 }
        private static void CheckForIsAssignableFrom(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation,
                                                     MemberAccessExpressionSyntax memberAccess, IMethodSymbol methodSymbol,
                                                     ExpressionSyntax argument)
        {
            if (methodSymbol.Name != "IsAssignableFrom" ||
                !TypeExaminationOnSystemType.IsGetTypeCall(argument as InvocationExpressionSyntax, context.SemanticModel))
            {
                return;
            }

            if (memberAccess.Expression is TypeOfExpressionSyntax)
            {
                context.ReportDiagnostic(Diagnostic.Create(rule, invocation.GetLocation(),
                                                           ImmutableDictionary <string, string> .Empty
                                                           .Add(UseIsOperatorKey, true.ToString())
                                                           .Add(ShouldRemoveGetType, true.ToString()),
                                                           MessageIsOperator));
            }
            else
            {
                context.ReportDiagnostic(Diagnostic.Create(rule, invocation.GetLocation(),
                                                           ImmutableDictionary <string, string> .Empty
                                                           .Add(UseIsOperatorKey, false.ToString())
                                                           .Add(ShouldRemoveGetType, true.ToString()),
                                                           MessageIsInstanceOfType));
            }
        }
Example #42
0
        public async Task <JObject> Resolve(InvocationExpressionSyntax method, Dictionary <string, JObject> memberAccessValues, CancellationToken token)
        {
            var methodName   = "";
            int isTryingLinq = 0;

            try
            {
                JObject rootObject = null;
                var     expr       = method.Expression;
                if (expr is MemberAccessExpressionSyntax)
                {
                    var memberAccessExpressionSyntax = expr as MemberAccessExpressionSyntax;
                    rootObject = await Resolve(memberAccessExpressionSyntax.Expression.ToString(), token);

                    methodName = memberAccessExpressionSyntax.Name.ToString();
                }
                else if (expr is IdentifierNameSyntax)
                {
                    if (scopeCache.ObjectFields.TryGetValue("this", out JObject valueRet))
                    {
                        rootObject = await GetValueFromObject(valueRet, token);

                        methodName = expr.ToString();
                    }
                }

                if (rootObject != null)
                {
                    DotnetObjectId.TryParse(rootObject?["objectId"]?.Value <string>(), out DotnetObjectId objectId);
                    var typeIds = await sdbHelper.GetTypeIdFromObject(sessionId, int.Parse(objectId.Value), true, token);

                    int methodId = await sdbHelper.GetMethodIdByName(sessionId, typeIds[0], methodName, token);

                    var className = await sdbHelper.GetTypeNameOriginal(sessionId, typeIds[0], token);

                    if (methodId == 0) //try to search on System.Linq.Enumerable
                    {
                        if (linqTypeId == -1)
                        {
                            linqTypeId = await sdbHelper.GetTypeByName(sessionId, "System.Linq.Enumerable", token);
                        }
                        methodId = await sdbHelper.GetMethodIdByName(sessionId, linqTypeId, methodName, token);

                        if (methodId != 0)
                        {
                            foreach (var typeId in typeIds)
                            {
                                var genericTypeArgs = await sdbHelper.GetTypeParamsOrArgsForGenericType(sessionId, typeId, token);

                                if (genericTypeArgs.Count > 0)
                                {
                                    isTryingLinq = 1;
                                    methodId     = await sdbHelper.MakeGenericMethod(sessionId, methodId, genericTypeArgs, token);

                                    break;
                                }
                            }
                        }
                    }
                    if (methodId == 0)
                    {
                        var typeName = await sdbHelper.GetTypeName(sessionId, typeIds[0], token);

                        throw new Exception($"Method '{methodName}' not found in type '{typeName}'");
                    }
                    var commandParamsObj       = new MemoryStream();
                    var commandParamsObjWriter = new MonoBinaryWriter(commandParamsObj);
                    if (isTryingLinq == 0)
                    {
                        commandParamsObjWriter.WriteObj(objectId, sdbHelper);
                    }
                    if (method.ArgumentList != null)
                    {
                        commandParamsObjWriter.Write((int)method.ArgumentList.Arguments.Count + isTryingLinq);
                        if (isTryingLinq == 1)
                        {
                            commandParamsObjWriter.WriteObj(objectId, sdbHelper);
                        }
                        foreach (var arg in method.ArgumentList.Arguments)
                        {
                            if (arg.Expression is LiteralExpressionSyntax)
                            {
                                if (!await commandParamsObjWriter.WriteConst(sessionId, arg.Expression as LiteralExpressionSyntax, sdbHelper, token))
                                {
                                    return(null);
                                }
                            }
                            if (arg.Expression is IdentifierNameSyntax)
                            {
                                var argParm = arg.Expression as IdentifierNameSyntax;
                                if (!await commandParamsObjWriter.WriteJsonValue(sessionId, memberAccessValues[argParm.Identifier.Text], sdbHelper, token))
                                {
                                    return(null);
                                }
                            }
                        }
                        var retMethod = await sdbHelper.InvokeMethod(sessionId, commandParamsObj.ToArray(), methodId, "methodRet", token);

                        return(await GetValueFromObject(retMethod, token));
                    }
                }
                return(null);
            }
            catch (Exception)
            {
                throw new Exception($"Unable to evaluate method '{methodName}'");
            }
        }
 public Xor7ExpressionSyntax(InvocationExpressionSyntax syntax)
 {
     _innerXor7 = syntax;
 }
        public static Type GetNodeDataType(SyntaxNode node)
        {
            InvocationExpressionSyntax castedNode = (InvocationExpressionSyntax)node;

            return(TypeResolver.GetNodeDataType(castedNode.Expression));
        }
 private static bool IsCompatibleGetComponent(InvocationExpressionSyntax invocation, SemanticModel model)
 {
     // We are looking for the exact GetComponent method, not other derivatives, so we do not want to use KnownMethods.IsGetComponentName(nameSyntax)
     if (invocation.GetMethodNameSyntax() is not {
         Identifier : { Text : nameof(UnityEngine.Component.GetComponent) }
     })
Example #46
0
 public override void VisitInvocationExpression(InvocationExpressionSyntax node)
 {
     IsComplex = true;
     base.VisitInvocationExpression(node);
 }
        private static bool IsTaskCompletedWithWhenAll(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationExpr, string taskVariableName)
        {
            // We only care about awaited invocations, because an un-awaited Task.WhenAll will be an error.
            if (invocationExpr.Parent is not AwaitExpressionSyntax)
            {
                return(false);
            }

            IEnumerable <MemberAccessExpressionSyntax>?memberAccessList = invocationExpr.ChildNodes().OfType <MemberAccessExpressionSyntax>();

            if (memberAccessList.Count() != 1)
            {
                return(false);
            }

            MemberAccessExpressionSyntax?memberAccess = memberAccessList.First();

            // Does the invocation have the expected `Task.WhenAll` syntax? This is cheaper to verify before looking up its semantic type.
            var correctSyntax =
                ((IdentifierNameSyntax)memberAccess.Expression).Identifier.ValueText == Types.Task.TypeName &&
                ((IdentifierNameSyntax)memberAccess.Name).Identifier.ValueText == Types.Task.WhenAll;

            if (!correctSyntax)
            {
                return(false);
            }

            // Is this `Task.WhenAll` invocation from the System.Threading.Tasks.Task type?
            ITypeSymbol?classType   = context.SemanticModel.GetTypeInfo(memberAccess.Expression).Type;
            var         correctType = classType.Name == Types.Task.TypeName && classType.BelongsToNamespace(Types.Task.Namespace);

            if (!correctType)
            {
                return(false);
            }

            // Is the task variable passed as an argument to `Task.WhenAll`?
            return(IsVariablePassedToInvocation(invocationExpr, taskVariableName, byRef: false));
        }
        private static bool TryGetCastInLambda(SyntaxKind asOrIs, IMethodSymbol methodSymbol, InvocationExpressionSyntax invocation, out string type)
        {
            type = null;
            if (!AsIsSyntaxKinds.Contains(asOrIs))
            {
                return(false);
            }

            var arguments = GetReducedArguments(methodSymbol, invocation);

            if (arguments.Count != 1)
            {
                return(false);
            }

            var expression      = arguments.First().Expression;
            var lambdaBody      = GetExpressionFromLambda(expression).RemoveParentheses() as BinaryExpressionSyntax;
            var lambdaParameter = GetLambdaParameter(expression);

            if (lambdaBody == null ||
                lambdaParameter == null ||
                !lambdaBody.IsKind(asOrIs))
            {
                return(false);
            }

            var castedExpression = lambdaBody.Left.RemoveParentheses();

            if (lambdaParameter != castedExpression.ToString())
            {
                return(false);
            }

            type = lambdaBody.Right.ToString();
            return(true);
        }
Example #49
0
 public override IEnumerable <Instruction> VisitInvocationExpression(InvocationExpressionSyntax node)
 {
     return(_CreateEnumerable(new Invocation((InvocationExpression)_expressionFactory.Create(node))));
 }
        private static bool IsFirstExpressionInLambdaIsNullChecking(IMethodSymbol methodSymbol, InvocationExpressionSyntax invocation)
        {
            var arguments = GetReducedArguments(methodSymbol, invocation);

            if (arguments.Count != 1)
            {
                return(false);
            }
            var expression = arguments.First().Expression;

            var binaryExpression = GetExpressionFromLambda(expression).RemoveParentheses() as BinaryExpressionSyntax;
            var lambdaParameter  = GetLambdaParameter(expression);

            while (binaryExpression != null)
            {
                if (!binaryExpression.IsKind(SyntaxKind.LogicalAndExpression))
                {
                    return(binaryExpression.IsKind(SyntaxKind.NotEqualsExpression) &&
                           IsNullChecking(binaryExpression, lambdaParameter));
                }
                binaryExpression = binaryExpression.Left.RemoveParentheses() as BinaryExpressionSyntax;
            }
            return(false);
        }
        private static void CheckForIsInstanceOfType(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation,
                                                     MemberAccessExpressionSyntax memberAccess, IMethodSymbol methodSymbol)
        {
            if (methodSymbol.Name != "IsInstanceOfType")
            {
                return;
            }

            if (memberAccess.Expression is TypeOfExpressionSyntax)
            {
                context.ReportDiagnostic(Diagnostic.Create(rule, invocation.GetLocation(),
                                                           ImmutableDictionary <string, string> .Empty
                                                           .Add(UseIsOperatorKey, true.ToString())
                                                           .Add(ShouldRemoveGetType, false.ToString()),
                                                           MessageIsOperator));
            }
        }
 private static bool IsExpressionInLambdaIsCast(IMethodSymbol methodSymbol, InvocationExpressionSyntax invocation, out string typeName)
 {
     return(TryGetCastInLambda(SyntaxKind.AsExpression, methodSymbol, invocation, out typeName) ||
            TryGetCastInLambda(methodSymbol, invocation, out typeName));
 }
        private static bool CheckForCastSimplification(IMethodSymbol outerMethodSymbol, InvocationExpressionSyntax outerInvocation,
                                                       IMethodSymbol innerMethodSymbol, InvocationExpressionSyntax innerInvocation, SyntaxNodeAnalysisContext context)
        {
            string typeNameInInner;

            if (MethodNamesForTypeCheckingWithSelect.Contains(outerMethodSymbol.Name) &&
                innerMethodSymbol.Name == SelectMethodName &&
                IsFirstExpressionInLambdaIsNullChecking(outerMethodSymbol, outerInvocation) &&
                TryGetCastInLambda(SyntaxKind.AsExpression, innerMethodSymbol, innerInvocation, out typeNameInInner))
            {
                context.ReportDiagnostic(Diagnostic.Create(Rule, GetReportLocation(innerInvocation),
                                                           string.Format(MessageUseInstead, $"\"OfType<{typeNameInInner}>()\"")));
                return(true);
            }

            string typeNameInOuter;

            if (outerMethodSymbol.Name == SelectMethodName &&
                innerMethodSymbol.Name == WhereMethodName &&
                IsExpressionInLambdaIsCast(outerMethodSymbol, outerInvocation, out typeNameInOuter) &&
                TryGetCastInLambda(SyntaxKind.IsExpression, innerMethodSymbol, innerInvocation, out typeNameInInner) &&
                typeNameInOuter == typeNameInInner)
            {
                context.ReportDiagnostic(Diagnostic.Create(Rule, GetReportLocation(innerInvocation),
                                                           string.Format(MessageUseInstead, $"\"OfType<{typeNameInInner}>()\"")));
                return(true);
            }

            return(false);
        }
 private static List <ArgumentSyntax> GetReducedArguments(IMethodSymbol methodSymbol, InvocationExpressionSyntax invocation)
 {
     return(methodSymbol.MethodKind == MethodKind.ReducedExtension
         ? invocation.ArgumentList.Arguments.ToList()
         : invocation.ArgumentList.Arguments.Skip(1).ToList());
 }
Example #55
0
        private static SyntaxNode RemoveExtensionMethodCall(SyntaxNode root, InvocationExpressionSyntax invocation)
        {
            var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression;

            return(root.ReplaceNode(invocation, memberAccess.Expression));
        }
Example #56
0
        IEnumerable <IMethodSymbol> GetExtensionMethods(SemanticModel semanticModel, ITypeSymbol typeToExtend, InvocationExpressionSyntax node, CancellationToken cancellationToken)
        {
            var usedNamespaces = new List <string> ();

            foreach (var un in semanticModel.GetUsingNamespacesInScope(node))
            {
                usedNamespaces.Add(MonoDevelop.Ide.TypeSystem.NR5CompatibiltyExtensions.GetFullName(un));
            }
            var enclosingNamespaceName = MonoDevelop.Ide.TypeSystem.NR5CompatibiltyExtensions.GetFullName(semanticModel.GetEnclosingNamespace(node.SpanStart, cancellationToken));

            var stack = new Stack <INamespaceOrTypeSymbol> ();

            stack.Push(semanticModel.Compilation.GlobalNamespace);

            while (stack.Count > 0)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
                var current   = stack.Pop();
                var currentNs = current as INamespaceSymbol;
                if (currentNs != null)
                {
                    foreach (var member in currentNs.GetNamespaceMembers())
                    {
                        var currentNsName = MonoDevelop.Ide.TypeSystem.NR5CompatibiltyExtensions.GetFullName(member);
                        if (usedNamespaces.Any(u => u.StartsWith(currentNsName, StringComparison.Ordinal)) ||
                            enclosingNamespaceName == currentNsName ||
                            (enclosingNamespaceName.StartsWith(currentNsName, StringComparison.Ordinal) &&
                             enclosingNamespaceName [currentNsName.Length] == '.'))
                        {
                            stack.Push(member);
                        }
                    }

                    foreach (var member in currentNs.GetTypeMembers())
                    {
                        stack.Push(member);
                    }
                }
                else
                {
                    var type = (INamedTypeSymbol)current;
                    if (type.IsImplicitClass || type.IsScriptClass)
                    {
                        continue;
                    }
                    if (type.DeclaredAccessibility != Accessibility.Public)
                    {
                        if (type.DeclaredAccessibility != Accessibility.Internal)
                        {
                            continue;
                        }
                        if (!type.IsAccessibleWithin(semanticModel.Compilation.Assembly))
                        {
                            continue;
                        }
                    }
                    if (!type.MightContainExtensionMethods)
                    {
                        continue;
                    }
                    foreach (var extMethod in type.GetMembers().OfType <IMethodSymbol> ().Where(method => method.IsExtensionMethod))
                    {
                        var reducedMethod = extMethod.ReduceExtensionMethod(typeToExtend);
                        if (reducedMethod != null)
                        {
                            yield return(reducedMethod);
                        }
                    }
                }
            }
        }
Example #57
0
 public ServiceDependencyItem(CSharpCompilation compilation, InvocationExpressionSyntax expression)
 {
     Compilation = compilation;
     Expression  = expression;
 }
        private static bool MethodIsNotUsingPredicate(IMethodSymbol methodSymbol, InvocationExpressionSyntax invocation)
        {
            var arguments = GetReducedArguments(methodSymbol, invocation);

            return(!arguments.Any() && MethodNamesWithPredicate.Contains(methodSymbol.Name));
        }
        public static bool GetClassificationForCommandPublication(ISemanticModel model, InvocationExpressionSyntax syntax, CancellationToken cancellationToken)
        {
            if (syntax == null)
            {
                return(false);
            }

            var memberExpression = syntax.Expression as MemberAccessExpressionSyntax;

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

            return(memberExpression.Name.Identifier.ValueText == "Send");
        }
Example #60
0
        public static string GetSymbolName(InvocationExpressionSyntax node, SymbolInfo si, string name, SemanticModel semanticModel)
        {
            var symbol = si.Symbol;

            if (symbol == null && si.CandidateSymbols.Any())
            {
                symbol = si.CandidateSymbols.First();
            }

            if (symbol != null && symbol.Kind != SymbolKind.Namespace)
            {
                //bool preserveMemberChange = !(symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property);

                int enumMode = -1;

                if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum && symbol is IFieldSymbol)
                {
                    string enumAttr = Translator.Bridge_ASSEMBLY + ".EnumAttribute";
                    enumMode = 7;

                    foreach (var attr in symbol.ContainingType.GetAttributes())
                    {
                        if (attr.AttributeClass != null && attr.AttributeClass.FullyQualifiedName() == enumAttr && attr.ConstructorArguments.Any())
                        {
                            enumMode = (int)attr.ConstructorArguments.First().Value;
                            break;
                        }
                    }
                }

                var  nameAttr = SyntaxHelper.GetInheritedAttribute(symbol, Bridge.Translator.Translator.Bridge_ASSEMBLY + ".NameAttribute");
                bool isIgnore = symbol.ContainingType != null && SyntaxHelper.IsExternalType(symbol.ContainingType);

                name = symbol.Name;

                if (nameAttr != null)
                {
                    var value = nameAttr.ConstructorArguments.First().Value;
                    if (value is string)
                    {
                        name = value.ToString();
                        name = Helpers.ConvertNameTokens(name, symbol.Name);
                        if (!isIgnore && symbol.IsStatic && Helpers.IsReservedStaticName(name))
                        {
                            name = Helpers.ChangeReservedWord(name);
                        }
                        return(name);
                    }

                    //preserveMemberChange = !(bool)value;
                    enumMode = -1;
                }

                if (enumMode > 6)
                {
                    switch (enumMode)
                    {
                    case 7:
                        break;

                    case 8:
                        name = name.ToLowerInvariant();
                        break;

                    case 9:
                        name = name.ToUpperInvariant();
                        break;
                    }
                }

                /*else
                 * {
                 *  name = !preserveMemberChange ? Object.Net.Utilities.StringUtils.ToLowerCamelCase(name) : name;
                 * }*/

                if (!isIgnore && symbol.IsStatic && Helpers.IsReservedStaticName(name))
                {
                    name = Helpers.ChangeReservedWord(name);
                }
            }

            return(name);
        }