protected override IEnumerable<IHighlighting> DoRun(IInvocationExpression invocationExpression, 
            ContractRequires contractAssertion,
            MemberWithAccess preconditionContainer)
        {
            var preconditionException = 
                contractAssertion.GenericArgumentDeclaredType
                .With(x => x.Resolve())
                .With(x => x.DeclaredElement as IClass);

            if (preconditionException != null)
            {
                if (ExceptionIsLessVisible(preconditionContainer, preconditionException))
                {
                    yield return
                        new RequiresExceptionInconsistentVisibiityHighlighting(preconditionException,
                            preconditionContainer);
                }

                if (DoesntHaveAppropriateConstructor(preconditionException))
                {
                    yield return new RequiresExceptionValidityHighlighting(preconditionException, preconditionContainer);
                }
            }

            if (!MessageIsAppropriateForContractRequires(contractAssertion.Message))
            {
                yield return new InvalidRequiresMessageHighlighting(contractAssertion.Message);
            }

        }
 private static void CalculateConnectionOfDisposableVariables(IInvocationExpression invocationExpression,
     ControlFlowElementData data, List<IRegularParameterDeclaration> thisConnections,
     Dictionary<IRegularParameterDeclaration, IVariableDeclaration> connections)
 {
     foreach (var argument in invocationExpression.InvocationExpressionReference.Invocation.Arguments)
     {
         var cSharpArgument = argument as ICSharpArgument;
         if (cSharpArgument == null)
             continue;
         var argumentExpression = cSharpArgument.Value;
         IRegularParameterDeclaration matchingVarDecl;
         if (argumentExpression is IThisExpression && data.ThisStatus != null)
         {
             if (GetMatchingParameterDeclaration(argument, out matchingVarDecl))
                 continue;
             thisConnections.Add(matchingVarDecl);
             continue;
         }
         var varDecl = TreeNodeHandlerUtil.GetVariableDeclarationForReferenceExpression(argumentExpression);
         if (data[varDecl] != null) // Если переменную не рассматриваем.
         {
             if (GetMatchingParameterDeclaration(argument, out matchingVarDecl))
                 continue;
             connections[matchingVarDecl] = varDecl;
         }
     }
 }
        public InvocationMessage(IExpression originalExpression, IInvocationExpression invocationExpression)
            : base(originalExpression)
        {
            Contract.Requires(invocationExpression != null);

            _invocationExpression = invocationExpression;
        }
        public static IPropertyDeclaration GetPropertyDeclaration(IClassDeclaration classDeclaration, IInvocationExpression invocationExpression)
        {
            IPropertyDeclaration propertyDeclaration = null;
            if (invocationExpression.ArgumentList.Arguments.Count >= 1)
            {
                string propertyName = null;
                var argument = invocationExpression.ArgumentList.Arguments[0];
                if (argument.Value is ILambdaExpression)
                {
                    var lambdaExpression = argument.Value as ILambdaExpression;
                    var referenceExpression = lambdaExpression.BodyExpression as IReferenceExpression;
                    if (referenceExpression != null)
                    {
                        propertyName = referenceExpression.NameIdentifier.Name;
                    }
                }
                else if (argument.Value != null && argument.Value.ConstantValue != null)
                {
                    propertyName = argument.Value.ConstantValue.Value.ToString();
                }

                if (!string.IsNullOrEmpty(propertyName) && classDeclaration.DeclaredElement != null)
                {
                    var property = (from member in classDeclaration.DeclaredElement.GetMembers().OfType<IProperty>() where member.ShortName == propertyName select member).FirstOrDefault();
                    if (property != null)
                    {
                        propertyDeclaration = (IPropertyDeclaration) property.GetDeclarations().FirstOrDefault();
                    }
                }
            }

            return propertyDeclaration;
        }
 private void AnalyzeInvocationExpression(IInvocationExpression operation, INamedTypeSymbol stringComparisonType, Action<Diagnostic> reportDiagnostic)
 {
     IMethodSymbol methodSymbol = operation.TargetMethod;
     if (methodSymbol != null &&
         methodSymbol.ContainingType.SpecialType == SpecialType.System_String &&
         IsEqualsOrCompare(methodSymbol.Name))
     {
         if (!IsAcceptableOverload(methodSymbol, stringComparisonType))
         {
             // wrong overload
             reportDiagnostic(Diagnostic.Create(Rule, GetMethodNameLocation(operation.Syntax)));
         }
         else
         {
             IArgument lastArgument = operation.ArgumentsInSourceOrder.Last();
             if (lastArgument.Value.Kind == OperationKind.FieldReferenceExpression)
             {
                 IFieldSymbol fieldSymbol = ((IFieldReferenceExpression)lastArgument.Value).Field;
                 if (fieldSymbol != null &&
                     fieldSymbol.ContainingType.Equals(stringComparisonType) &&
                     !IsOrdinalOrOrdinalIgnoreCase(fieldSymbol.Name))
                 {
                     // right overload, wrong value
                     reportDiagnostic(lastArgument.Syntax.CreateDiagnostic(Rule));
                 }
             }
         }
     }
 }
        public override void VisitInvocationExpression(IInvocationExpression invocation, IHighlightingConsumer consumer)
        {
            if (IsCallWithTheSameContextAsFunctionOwner(invocation))
                consumer.AddHighlighting(new CallWithSameContextWarning(invocation), invocation.GetHighlightingRange(), File);

            base.VisitInvocationExpression(invocation, consumer);
        }
Beispiel #7
0
        protected override IEnumerable<IComponentRegistration> FromArguments(IInvocationExpression invocationExpression)
        {
            if (invocationExpression.Arguments.Count != 2)
            {
                yield break;
            }

            ICSharpArgument arg1 = invocationExpression.Arguments.First();

            ITypeElement typeElement = arg1.With(f => f.Value as ITypeofExpression)
                                           .With(f => f.ArgumentType as IDeclaredType)
                                           .With(f => f.GetTypeElement());
            if (typeElement == null)
            {
                yield break;
            }

            ICSharpArgument arg2 = invocationExpression.Arguments.Last();
            IEnumerable<ITypeElement> concreteTypes = arg2.With(f => f.Value)
                                                          .With(f => f.GetRegisteredTypes()).ToList();

            if (concreteTypes.Any())
            {
                yield return CreateRegistrations(invocationExpression, typeElement, concreteTypes);
            }
        }
        protected virtual IEnumerable<IComponentRegistration> FromGenericArguments(IInvocationExpression invocationExpression)
        {
            var first = invocationExpression.TypeArguments.First() as IDeclaredType;
            var last = invocationExpression.TypeArguments.Last() as IDeclaredType;

            return CreateRegistration(invocationExpression, first, last);
        }
        public InvalidRequiresMessageHighlighting(IInvocationExpression invocationExpression, Message contractMessage)
        {
            Contract.Requires(contractMessage != null);
            Contract.Requires(invocationExpression != null);

            _range = invocationExpression.GetHighlightingRange();
            _contractMessage = contractMessage;
        }
    public override bool IsAvailable(IUserDataHolder cache)
    {
      var topLevelNode = myProvider.GetTopLevelNode();
      if (topLevelNode == null) return false;

      myChainedInvocation = FindInvocationChain(topLevelNode);

      return myChainedInvocation != null;
    }
        private static IDeclaredType GetGenericRequiresType(IInvocationExpression invocationExpression)
        {
            Contract.Requires(invocationExpression != null);

            return invocationExpression.Reference
                .With(x => x.Invocation)
                .With(x => x.TypeArguments.FirstOrDefault())
                .Return(x => x as IDeclaredType);
        }
        private static ContractAssertionType? GetContractAssertionType(IInvocationExpression invocationExpression)
        {
            var clrType = invocationExpression.GetCallSiteType();
            var method = invocationExpression.GetCalledMethod();

            if (clrType.Return(x => x.FullName) != typeof(Contract).FullName)
                return null;

            return ParseAssertionType(method);
        }
        internal RequiresExceptionValidityHighlighting(IInvocationExpression invocationExpression, IClass exceptionDeclaration, MemberWithAccess preconditionContainer)
        {
            Contract.Requires(exceptionDeclaration != null);
            Contract.Requires(preconditionContainer != null);
            Contract.Requires(invocationExpression != null);

            _range = invocationExpression.GetHighlightingRange();
            _exceptionDeclaration = exceptionDeclaration;
            _preconditionContainer = preconditionContainer;
        }
 public InvocationTestDeclaration(
 IIdentity identity,
 IProject project,
 string text,
 IInvocationExpression invocationExpression)
     : base(invocationExpression)
 {
     _identity = identity;
       _project = project;
       _text = text;
 }
    public sealed override bool IsAvailable(IUserDataHolder cache)
    {
      myOuterInvocation = null;
      myExistingLambdaParameterName = null;

      var topLevelNode = myProvider.GetTopLevelNode();
      if (topLevelNode == null) return false;

      myOuterInvocation = FindChain(topLevelNode);
      return myOuterInvocation != null;
    }
        private Ranges GetUnitTestElementLocation(IInvocationExpression invocation)
        {
            var reference = (invocation.InvokedExpression as IReferenceExpression)
              .AssertNotNull("invocationExpression.InvokedExpression is not a IReferenceExpression");

              var startOffset = reference.NameIdentifier.GetDocumentStartOffset();
              var endOffset = invocation.GetDocumentRange().EndOffsetRange();
              var textRange = startOffset.JoinRight(endOffset);

              return new Ranges(textRange, textRange);
        }
Beispiel #17
0
        private UnitTestElementLocation GetUnitTestElementLocation(IInvocationExpression invocation)
        {
            var projectFile = invocation.GetSourceFile().ToProjectFile();
              var reference = (invocation.InvokedExpression as IReferenceExpression)
              .AssertNotNull("invocationExpression.InvokedExpression is not a IReferenceExpression");

              var startOffset = reference.NameIdentifier.GetDocumentStartOffset();
              var endOffset = invocation.GetDocumentRange().EndOffsetRange();
              var textRange = startOffset.JoinRight(endOffset).TextRange;

              return new UnitTestElementLocation(projectFile, textRange, textRange);
        }
        private static bool IsCallWithTheSameContextAsFunctionOwner(IInvocationExpression invocation)
        {
            var invokedReference = invocation.InvokedExpression as IReferenceExpression;
            if (invokedReference == null || invokedReference.Name != "call")
                return false;

            var function = invokedReference.Qualifier as IReferenceExpression;
            if (function == null)
                return false;

            return AreSame(function.Qualifier, invocation.Arguments.FirstOrDefault());
        }
        private static string CalculateRestrictions(IInvocationExpression invokedExpression)
        {
            // TODO: Set default restrictions per version
            const string defaultRestrictions = "AE";

            // First argument is traditionally the identifier (i.e. the directive name) but can also
            // be an object literal, where the keys are the directive names and the values are the
            // factory functions. We don't support this.
            // Second argument can be:
            // * factory function, which is injectable
            // * array literal specifying injectables for the factory function
            // Return value of the factory function can be:
            // * the "postlink" function, which means we use defaults
            // * a directive definition object, wich is an object literal that contains properties such as restrict
            var argument = invokedExpression.Arguments[1];

            var function = argument as IFunctionExpression;

            if (function == null)
            {
                var arrayLiteral = argument as IArrayLiteral;
                if (arrayLiteral != null && arrayLiteral.ArrayElements.Count > 0)
                {
                    var lastElement = arrayLiteral.ArrayElements.Last();
                    function = lastElement as IFunctionExpression;
                }
            }

            if (function == null || function.Block.Statements.Count == 0)
                return defaultRestrictions;

            IObjectLiteral objectLiteral = null;

            // TODO: Perhaps this should get the JS type, and get the return value of the function
            // This might be better than trying to find an object literal used as a return value
            var lastStatement = function.Block.Statements.Last();
            var returnStatement = lastStatement as IReturnStatement;
            if (returnStatement != null)
            {
                objectLiteral = returnStatement.Value.LastExpression as IObjectLiteral;
            }

            if (objectLiteral == null)
                return defaultRestrictions;

            foreach (var initializer in objectLiteral.Properties.OfType<IObjectPropertyInitializer>())
            {
                if (initializer.DeclaredName == "restrict")
                    return initializer.Value.GetStringLiteralValue() ?? defaultRestrictions;
            }
            return defaultRestrictions;
        }
Beispiel #20
0
        public string Present(IInvocationExpression invocationExpression)
        {
            var method = invocationExpression.Reference.GetResolved<IMethod>();
              if (method == null)
            return null;

              var displayFormatAttributeData = method.GetAttributeData<DisplayFormatAttribute>();
              if (displayFormatAttributeData == null)
            return null;

              var displayFormatAttribute = displayFormatAttributeData.ToCommon();
              var commonExpressions = invocationExpression.Arguments.Select(GetConstantValue);
              return _introspectionPresenter.Present(displayFormatAttribute, commonExpressions);
        }
 private void ScanInvocation([NotNull] IInvocationExpression operation, [NotNull] IMethodSymbol methodToFind)
 {
     if (methodToFind.MethodKind == MethodKind.ExplicitInterfaceImplementation)
     {
         ScanExplicitInterfaceInvocation(operation, methodToFind);
     }
     else
     {
         if (methodsToFind.Any(method => method.Equals(operation.TargetMethod)))
         {
             HasFoundInvocation = true;
         }
     }
 }
 private static bool IsPossibleLinqInvocation(IInvocationExpression invocation)
 {
     switch (invocation.TargetMethod.Name)
     {
         case "Last":
         case "LastOrDefault":
         case "First":
         case "FirstOrDefault":
         case "Count":
             return true;
         default:
             return false;
     }
 }
        protected override bool IsAvailable()
        {
            var expressionInitializer = FieldDeclaration.Initial as IExpressionInitializer;
            _invocationExpression = null;
            if (expressionInitializer != null)
            {
                _invocationExpression = expressionInitializer.Value as IInvocationExpression;
            }

            return _invocationExpression != null
                   && (_invocationExpression.ArgumentList.Arguments.Count == 4
                       && ((_invocationExpression.ArgumentList.Arguments[3].Value is ICSharpLiteralExpression)
                           && (_invocationExpression.ArgumentList.Arguments[3].Value as ICSharpLiteralExpression).Literal.GetTokenType() == CSharpTokenType.FALSE_KEYWORD));
        }
            public override void VisitInvocationExpression(IInvocationExpression invocationExpressionParam, HotMethodAnalyzerContext context)
            {
                // Do not add analysis for invocation expression here. Use 'AnalyzeInvocationExpression' for this goal;
                AnalyzeInvocationExpression(invocationExpressionParam, context);

                // Restriction for depth of analysis
                if (myMaxDepth <= context.Depth)
                {
                    return;
                }

                var reference = (invocationExpressionParam.InvokedExpression as IReferenceExpression)?.Reference;

                var declaredElement = reference?.Resolve().DeclaredElement as IMethod;

                if (declaredElement == null)
                {
                    return;
                }

                context.RegisterInvocationInMethod(declaredElement, reference);
                context.MarkCurrentAsVisited();

                // find all declarations in current file
                var declarations = declaredElement.GetDeclarationsIn(mySourceFile).Where(t => t.GetSourceFile() == mySourceFile);

                // update current declared element in context and then restore it
                var originDeclaredElement = context.CurrentDeclaredElement;

                context.CurrentDeclaredElement = declaredElement;
                foreach (var declaration in declarations)
                {
                    // Do not visit methods twice
                    if (!context.IsCurrentElementVisited())
                    {
                        ourCheckForInterrupt();
                        declaration.ProcessDescendants(this, context);
                    }
                }
                context.CurrentDeclaredElement = originDeclaredElement;

                // propagate costly reachable methods back
                // Note : on this step there is methods that can be marked as costly reachable later (e.g. recursion)
                // so we will propagate costly reachable mark later
                if (context.IsDeclaredElementCostlyReachable(declaredElement))
                {
                    context.MarkCurrentAsCostlyReachable();
                }
            }
Beispiel #25
0
        public PreferAddressByIdToGraphicsParamsQuickFix(PreferAddressByIdToGraphicsParamsWarning warning)
        {
            myInvocationExpression = warning.InvocationMethod;
            myArgument             = warning.Argument;
            myFieldName            = myGraphicsPropertyName = warning.Literal;

            if (!ValidityChecker.IsValidIdentifier(myFieldName))
            {
                myFieldName = "Property";
            }

            myArgumentExpression = warning.ArgumentExpression;
            myMapFunction        = warning.MapFunction;
            myTypeName           = warning.TypeName;
        }
Beispiel #26
0
        private string GetMethodName(IInvocationExpression itemAsT)
        {
            var methodName = itemAsT.MethodName;

            if (itemAsT.TypeArguments.Any())
            {
                var typeArgs = itemAsT.TypeArguments
                               .SelectMany(x => RDom.CSharp.GetSyntaxGroup(x))
                               .Select(x => x.ToFullString())
                               .ToList();
                var typeArgString = string.Join(", ", typeArgs);
                methodName += "<" + typeArgString + ">";
            }
            return(methodName);
        }
Beispiel #27
0
        public IEnumerable <string> GetMockedMethodParameterTypes(IInvocationExpression invocation)
        {
            var mockedMethod     = GetMockedMethodFromSetupMethod(invocation);
            var methodInvocation = GetMockedMethodInvocation(invocation);
            var substitution     = methodInvocation?.Reference?.Resolve()?.Substitution;

            return(mockedMethod.Parameters.Select(p =>
            {
                if (substitution == null)
                {
                    return p.Type.GetPresentableName(CSharpLanguage.Instance);
                }
                return substitution.Apply(p.Type).GetPresentableName(CSharpLanguage.Instance);
            }));
        }
        private static bool IsPossibleLinqInvocation(IInvocationExpression invocation)
        {
            switch (invocation.TargetMethod.Name)
            {
            case "Last":
            case "LastOrDefault":
            case "First":
            case "FirstOrDefault":
            case "Count":
                return(true);

            default:
                return(false);
            }
        }
        public TempValue?AddFunctionCall(IInvocationExpression exp)
        {
            var referenceType = exp.DataType.Known().UnderlyingReferenceType();

            if (referenceType is null)
            {
                return(null);
            }

            var reference = ReferenceToNewInvocationReturnedObject(exp);
            var temp      = ReferenceGraph.AddTempValue(exp, referenceType);

            temp.AddReference(reference);
            return(temp);
        }
        public static bool IsInvocationExpensive([NotNull] IInvocationExpression invocationExpression)
        {
            invocationExpression.GetPsiServices().Locks.AssertReadAccessAllowed();

            var reference = (invocationExpression.InvokedExpression as IReferenceExpression)?.Reference;

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

            var declaredElement = reference.Resolve().DeclaredElement as IMethod;

            return(IsInvokedElementExpensive(declaredElement));
        }
        private void ProcessDirective(IInvocationExpression invokedExpression, string identifier, int offset)
        {
            if (invokedExpression.Arguments.Count != 2)
            {
                return;
            }

            var restrictions = CalculateRestrictions(invokedExpression);

            // Directives declared in code cannot be applied to just a single tag
            var tags      = new string[0];
            var directive = new Directive(identifier, DirectiveUtil.GetNormalisedName(identifier), restrictions, tags, offset, new List <Parameter>());

            cacheItemsBuilder.Add(directive);
        }
        protected virtual IEnumerable<IComponentRegistration> FromArguments(IInvocationExpression invocationExpression)
        {
            List<ITypeofExpression> arguments = invocationExpression.ArgumentList.Arguments
                .Where(argument =>
                {
                    var declaredType = argument.Value.Type() as IDeclaredType;
                    return declaredType != null && declaredType.IsType();
                }).Select(argument => argument.Value as ITypeofExpression)
                .ToList();

            var first = arguments.First().ArgumentType as IDeclaredType;
            var last = arguments.Last().ArgumentType as IDeclaredType;

            return CreateRegistration(invocationExpression, first, last);
        }
        public sealed override bool IsAvailable(IUserDataHolder cache)
        {
            myOuterInvocation             = null;
            myExistingLambdaParameterName = null;

            var topLevelNode = myProvider.GetTopLevelNode();

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

            myOuterInvocation = FindChain(topLevelNode);
            return(myOuterInvocation != null);
        }
Beispiel #34
0
            public override void VisitInvocationExpression([NotNull] IInvocationExpression operation)
            {
                if (!HasFoundInvocation)
                {
                    foreach (IMethodSymbol methodToFind in methodsToFind)
                    {
                        ScanInvocation(operation, methodToFind);
                    }

                    if (!HasFoundInvocation)
                    {
                        base.VisitInvocationExpression(operation);
                    }
                }
            }
        public static string GetCalledMethod(this IInvocationExpression invocationExpression)
        {
            Contract.Requires(invocationExpression != null);

            var result = invocationExpression
                         .With(x => x.InvokedExpression)
                         .With(x => x as IReferenceExpression)
                         .With(x => x.Reference)
                         .With(x => x.Resolve())
                         .With(x => x.DeclaredElement)
                         .With(x => x as IClrDeclaredElement)
                         .Return(x => x.ShortName);

            return(result);
        }
        private CodeContractStatement(ICSharpStatement statement, 
            IInvocationExpression invocationExpression,
            CodeContractStatementType statementType)
            : base(statement)
        {
            Contract.Requires(invocationExpression != null);

            _invocationExpression = invocationExpression;
            _statementType = statementType;

            // Due to weird bug in CC compiler, I can't use the same variable in Contract.Requires
            // and in lambda expression.
            _codeContractExpression = JetBrains.Util.Lazy.Lazy.Of(
                () => Assertions.ContractStatementFactory.TryCreateAssertion(_invocationExpression));
        }
Beispiel #37
0
        private CodeContractStatement(ICSharpStatement statement,
                                      IInvocationExpression invocationExpression,
                                      CodeContractStatementType statementType)
            : base(statement)
        {
            Contract.Requires(invocationExpression != null);

            _invocationExpression = invocationExpression;
            _statementType        = statementType;

            // Due to weird bug in CC compiler, I can't use the same variable in Contract.Requires
            // and in lambda expression.
            _codeContractExpression = JetBrains.Util.Lazy.Of(
                () => Assertions.ContractStatementFactory.TryCreateAssertion(_invocationExpression), true);
        }
Beispiel #38
0
        private IEnumerable <IComponentRegistration> FromArguments(IInvocationExpression invocationExpression)
        {
            List <ITypeofExpression> arguments = invocationExpression.ArgumentList.Arguments
                                                 .Where(argument =>
            {
                var declaredType = argument.Value.Type() as IDeclaredType;
                return(declaredType != null && declaredType.GetClrName().Equals(clrTypeName));
            }).Select(argument => argument.Value as ITypeofExpression)
                                                 .ToList();

            var first = arguments.First().ArgumentType as IDeclaredType;
            var last  = arguments.Last().ArgumentType as IDeclaredType;

            return(CreateRegistration(invocationExpression, first, last));
        }
        private static bool IsSpecificMethod(IInvocationExpression invocationExpression, IClrTypeName typeName, params string[] methodNames)
        {
            var declaredElement = invocationExpression.Reference.Resolve().DeclaredElement as IMethod;

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

            if (methodNames.Any(t => t.Equals(declaredElement.ShortName)))
            {
                return(declaredElement.GetContainingType()?.GetClrName().Equals(typeName) == true);
            }
            return(false);
        }
        private void AddWarning(IInvocationExpression element, IHighlightingConsumer consumer)
        {
            DocumentRange range;

            if (element.FirstChild?.LastChild is ITypeArgumentList typeInvocation)
            {
                range = typeInvocation.GetDocumentRange();
            }
            else
            {
                range = element.InvokedExpression.GetDocumentRange();
            }

            AddHighlighting(consumer, range);
        }
        public IExpression CreateMigrationExpression(IInvocationExpression invocationExpression)
        {
            var arguments = invocationExpression.Arguments
                            .Select(x => x.Value)
                            .ToArray();

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

            var factory      = CSharpElementFactory.GetInstance(invocationExpression);
            var actualValue  = GetActualValue(arguments);
            var shouldMethod = invocationExpression.GetFluentAssertionsPredefinedType().GetShouldMethod(actualValue.Type());

            if (shouldMethod is null)
            {
                return(invocationExpression);
            }

            var shouldExpression  = factory.CreateReferenceExpression("$0.$1", actualValue, shouldMethod);
            var replacementMethod = GetReplacementMethod(shouldMethod);

            if (replacementMethod is null)
            {
                return(invocationExpression);
            }

            var replacementMethodExpression = factory.CreateReferenceExpression("$0().$1", shouldExpression, replacementMethod);
            var list = new List <object> {
                replacementMethodExpression
            };
            var expectedValue = GetExpectedValue(arguments);

            if (expectedValue != null)
            {
                list.Add(expectedValue);
                list.AddRange(arguments.Skip(GetExpectedValueSkipArgumentsCount()));
            }
            else
            {
                list.AddRange(arguments.Skip(1));
            }

            var expressionFormat = $"$0({list.GetExpressionFormatArguments()})";

            return(factory.CreateExpression(expressionFormat, list.ToArray()));
        }
        private bool IsMethod([CanBeNull]  IInvocationExpression invocationExpression, Func <IDeclaredElement, bool> methodFilter)
        {
            if (invocationExpression == null || invocationExpression.Reference == null)
            {
                return(false);
            }

            var resolveResult = invocationExpression.Reference.Resolve();

            if (resolveResult.ResolveErrorType == ResolveErrorType.MULTIPLE_CANDIDATES)
            {
                return(resolveResult.Result.Candidates.Any(methodFilter));
            }

            return(methodFilter(resolveResult.DeclaredElement));
        }
Beispiel #43
0
        /// <summary>
        /// Do not prefix calls with base unless local implementation exists.
        /// </summary>
        /// <param name="node">
        /// The node to process.
        /// </param>
        private void DoNotPrefixCallsWithBaseUnlessLocalImplementationExists(ITreeNode node)
        {
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                IInvocationExpression invocationExpression = currentNode as IInvocationExpression;
                if (invocationExpression != null)
                {
                    SwapBaseToThisUnlessLocalImplementation(invocationExpression);
                }

                if (currentNode.FirstChild != null)
                {
                    this.DoNotPrefixCallsWithBaseUnlessLocalImplementationExists(currentNode.FirstChild);
                }
            }
        }
        public virtual IDeclaredElement GetInvokedElement([NotNull] IInvocationExpression invocationExpression)
        {
            if (invocationExpression == null)
            {
                throw new ArgumentNullException("invocationExpression");
            }

            if (invocationExpression.InvocationExpressionReference.CurrentResolveResult != null)
            {
                return(invocationExpression.InvocationExpressionReference.CurrentResolveResult.DeclaredElement);
            }
            else
            {
                throw new ExpressionHelperException("Null resolved result of invocation expression", invocationExpression);
            }
        }
Beispiel #45
0
        public string Present(IInvocationExpression invocationExpression)
        {
            var method = invocationExpression.Reference.GetResolved<IMethod>();
              if (method == null)
            return null;

              var displayFormatAttributeData = method.GetAttributeData<DisplayFormatAttribute>();
              if (displayFormatAttributeData == null)
            return null;

              var displayFormatAttribute = displayFormatAttributeData.ToCommon();
              var commonExpressions = invocationExpression.Arguments
              .Select((x, i) => new { Index = i, Object = GetConstantValue(x) })
              .ToDictionary(x => x.Index.ToString(), x => x.Object);
              return _introspectionPresenter.Present(displayFormatAttribute, commonExpressions);
        }
        public static IClrTypeName GetCallSiteType(this IInvocationExpression invocationExpression)
        {
            Contract.Requires(invocationExpression != null);

            var type = invocationExpression
                       .With(x => x.InvokedExpression)
                       .With(x => x as IReferenceExpression)
                       .With(x => x.Reference)
                       .With(x => x.Resolve())
                       .With(x => x.DeclaredElement)
                       .With(x => x as IClrDeclaredElement)
                       .With(x => x.GetContainingType())
                       .Return(x => x.GetClrName());

            return(type);
        }
        public override void VisitInvocationExpression(IInvocationExpression operation)
        {
            LogString(nameof(IInvocationExpression));

            var isVirtualStr = operation.IsVirtual ? "virtual " : string.Empty;
            var isStaticStr  = operation.Instance == null ? "static " : string.Empty;
            var spacing      = !operation.IsVirtual && operation.Instance != null ? " " : string.Empty;

            LogString($" ({isVirtualStr}{isStaticStr}{spacing}");
            LogSymbol(operation.TargetMethod, header: string.Empty);
            LogString(")");
            LogCommonPropertiesAndNewLine(operation);

            VisitInstanceExpression(operation.Instance);
            VisitArguments(operation);
        }
        private static void CheckInvocationExpression([NotNull] IInvocationExpression invocation, [NotNull] IHighlightingConsumer consumer)
        {
            var invokedExpression = invocation.InvokedExpression;

            if (invokedExpression == null)
            {
                return;
            }

            CheckInvocationInfo(invocation, invokedExpression as IReferenceExpression, consumer);

            var invocationReference = invocation.InvocationExpressionReference.NotNull("reference != null");

            var resolveResult = invocationReference.Resolve();

            if (resolveResult.ResolveErrorType != ResolveErrorType.OK)
            {
                return;
            }

            var method = resolveResult.DeclaredElement as IMethod;

            if (method == null)
            {
                return;
            }

            if (method.IsIterator)
            {
                consumer.AddHighlighting(
                    new ObjectAllocationHighlighting(invocation, "iterator method call"),
                    invokedExpression.GetExpressionRange());
            }
            else if (method.ReturnType.Classify == TypeClassification.REFERENCE_TYPE)
            {
                var annotationsCache             = invocation.GetPsiServices().GetCodeAnnotationsCache();
                var linqTunnelAnnotationProvider = annotationsCache.GetProvider <LinqTunnelAnnotationProvider>();
                var pureAnnotationProvider       = annotationsCache.GetProvider <PureAnnotationProvider>();

                if (pureAnnotationProvider.GetInfo(method) && linqTunnelAnnotationProvider.GetInfo(method))
                {
                    consumer.AddHighlighting(
                        new ObjectAllocationHighlighting(invocation, "LINQ method call"),
                        invokedExpression.GetExpressionRange());
                }
            }
        }
Beispiel #49
0
        // todo: ?. invocations?
        private static void CheckInvocationExpression([NotNull] IInvocationExpression invocationExpression, [NotNull] IHighlightingConsumer consumer)
        {
            var invokedReference = invocationExpression.InvokedExpression as IReferenceExpression;

            if (invokedReference == null)
            {
                return;
            }

            var resolveResult = invocationExpression.InvocationExpressionReference.Resolve();

            if (!resolveResult.ResolveErrorType.IsAcceptable)
            {
                return;
            }

            var method = resolveResult.DeclaredElement as IMethod;

            if (method == null || method.IsStatic)
            {
                return;
            }

            var classType = method.GetContainingType() as IClass;

            if (classType == null)
            {
                return;
            }

            var qualifierType = GetQualifierExpressionType(invokedReference.QualifierExpression, invokedReference);

            const string description = "inherited 'System.Object' virtual method call on value type instance";

            if (qualifierType.IsValueType())
            {
                consumer.AddHighlighting(
                    new BoxingAllocationHighlighting(invocationExpression, description),
                    invokedReference.NameIdentifier.GetDocumentRange());
            }
            else if (qualifierType.IsUnconstrainedGenericType())
            {
                consumer.AddHighlighting(
                    new BoxingAllocationPossibleHighlighting(invocationExpression, description),
                    invokedReference.NameIdentifier.GetDocumentRange());
            }
        }
Beispiel #50
0
        private static bool TryConvertSyncCallToAsyncCall([NotNull] IInvocationExpression invocationExpression, [NotNull] CSharpElementFactory factory, [NotNull] IPsiModule psiModule)
        {
            var referenceCurrentResolveResult = invocationExpression.Reference?.Resolve();

            if (referenceCurrentResolveResult?.IsValid() != true)
            {
                return(false);
            }

            var invocationMethod = referenceCurrentResolveResult.DeclaredElement as IMethod;

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

            var invokedObjectType = (invocationExpression.ConditionalQualifier as IReferenceExpression)?.QualifierExpression?.Type();

            var asyncMethod = FindEquivalentAsyncMethod(invocationMethod, invokedObjectType, psiModule);

            if (asyncMethod != null)
            {
                if (!TryConvertInnerReferenceToAsync(invocationExpression, factory, psiModule))
                {
                    return(false);
                }
                ReplaceCallToAsync(invocationExpression, factory, useAsync: true);
                return(true);
            }

            var asyncMethodWithFunc = FindEquivalentAsyncMethodWithAsyncFunc(invocationMethod);

            if (asyncMethodWithFunc == null)
            {
                return(false);
            }
            if (!TryConvertInnerReferenceToAsync(invocationExpression, factory, psiModule))
            {
                return(false);
            }

            if (TryConvertParameterFuncToAsync(invocationExpression, factory, psiModule))
            {
                ReplaceCallToAsync(invocationExpression, factory, useAsync: true);
            }
            return(true);
        }
Beispiel #51
0
        public static ICSharpArgument GetTemplateArgument(this IInvocationExpression invocationExpression)
        {
            if (!(invocationExpression.Reference.Resolve().DeclaredElement is ITypeMember typeMember))
            {
                return(null);
            }

            var templateParameterName = typeMember.GetTemplateParameterName();

            if (string.IsNullOrEmpty(templateParameterName))
            {
                return(null);
            }

            return(invocationExpression.ArgumentList.Arguments.FirstOrDefault(
                       a => a.MatchingParameter?.Element.ShortName == templateParameterName));
        }
Beispiel #52
0
        private static IEnumerable <IComponentRegistration> CreateRegistration(IInvocationExpression invocationExpression, IDeclaredType first, IDeclaredType last)
        {
            if (first == null || last == null)
            {
                yield break;
            }

            ITypeElement fromType = first.GetTypeElement();
            ITypeElement toType   = last.GetTypeElement();

            if (fromType != null && toType != null)
            {
                yield return(fromType.Equals(toType)
                                 ? new ComponentRegistration(invocationExpression, fromType)
                                 : new ComponentRegistration(invocationExpression, fromType, toType));
            }
        }
Beispiel #53
0
        private static IReferenceExpression ExtractContractResultReference(IInvocationExpression contractResultExpression)
        {
            Contract.Requires(contractResultExpression != null);

            var callSiteType = contractResultExpression.GetCallSiteType();
            var method       = contractResultExpression.GetCalledMethod();

            if (callSiteType.With(x => x.FullName) != typeof(Contract).FullName ||
                method != "Result")
            {
                return(null);
            }

            return(contractResultExpression
                   .With(x => x.InvokedExpression)
                   .Return(x => x as IReferenceExpression));
        }
Beispiel #54
0
        public string Present(IInvocationExpression invocationExpression)
        {
            var method = invocationExpression.Reference.NotNull().GetResolved <IMethod>();
            var displayFormatAttributeData = method?.GetAttributeData <DisplayFormatAttribute>();

            if (displayFormatAttributeData == null)
            {
                return(null);
            }

            var displayFormatAttribute = displayFormatAttributeData.ToCommon();
            var commonExpressions      = invocationExpression.Arguments
                                         .Select((x, i) => new { Index = i, Object = GetConstantValue(x) })
                                         .ToDictionary(x => x.Index.ToString(), x => x.Object);

            return(_introspectionPresenter.Present(displayFormatAttribute, commonExpressions));
        }
        private IEnumerable<IComponentRegistration> CreateRegistration(IInvocationExpression invocationExpression, IDeclaredType first, IDeclaredType last)
        {
            if (first == null || last == null)
            {
                yield break;
            }

            ITypeElement fromType = first.GetTypeElement();
            ITypeElement toType = last.GetTypeElement();

            if (fromType != null && toType != null)
            {
                yield return fromType.Equals(toType)
                                 ? new ComponentRegistration(invocationExpression, fromType)
                                 : new ComponentRegistration(invocationExpression, fromType, toType);
            }
        }
        private static bool GetTypeParameters(IInvocationExpression invocation, out IType[] typeParameters)
        {
            typeParameters = new IType[0];
            if (invocation.Arguments.Count != 0)
            {
                ICSharpExpression[] expressions;
                if (invocation.Arguments[0].Expression is IArrayCreationExpression)
                {
                    var initiallizer = ((IArrayCreationExpression)invocation.Arguments[0].Expression).ArrayInitializer;
                    if (initiallizer != null)
                    {
                        expressions = initiallizer.ElementInitializers
                                      .Cast <IExpressionInitializer>()
                                      .Select(i => i.Value)
                                      .ToArray();
                    }
                    else
                    {
                        expressions = new ICSharpExpression[0];
                    }
                }
                else
                {
                    expressions = invocation.Arguments.Select(a => a.Expression)
                                  .Cast <ICSharpExpression>()
                                  .ToArray();
                }

                typeParameters = new IType[expressions.Length];

                for (int i = 0; i < expressions.Length; i++)
                {
                    var resolvedType = ResolveReflectedTypeInternal(expressions[i]);
                    if (resolvedType.ResolvedAs == ReflectedTypeResolution.Exact)
                    {
                        typeParameters[i] = resolvedType.Type;
                    }
                    else
                    {
                        return(false); //
                    }
                }
            }

            return(true);
        }
Beispiel #57
0
        protected override IEnumerable<IComponentRegistration> FromGenericArguments(IInvocationExpression invocationExpression)
        {
            var serviceType = invocationExpression.TypeArguments.First() as IDeclaredType;
            if (serviceType == null)
            {
                yield break;
            }

            var typeElement = serviceType.GetTypeElement();
            if (typeElement == null)
            {
                yield break;
            }

            IEnumerable<ITypeElement> concreteTypes = invocationExpression.Arguments.SelectMany(argument => argument.Value.GetRegisteredTypes());

            yield return CreateRegistrations(invocationExpression, typeElement, concreteTypes);
        }
        // This will be called multiple times in the case of chained method calls.
        public override void VisitInvocationExpression(IInvocationExpression invocationExpressionParam)
        {
            // TODO: Loop through here somehow and work up through the string calls like ToLower().ToUpper() et et.
            //do
            //    	    {
                IReferenceExpression expression = invocationExpressionParam.InvokedExpression as IReferenceExpression;
                if (expression == null)
                    return;

                // As I understand it this takes the abstract syntax element that is e.ToString() and resolves it such that
                // we know it's the System.Enum.ToString() method call.
                IResolveResult resolveResult = expression.Reference.Resolve();

                IDeclaredElement e = resolveResult.DeclaredElement;

                if (e == null)
                    return;

                ITypeElement containingType = e.GetContainingType();

                // work up through the string calls
                //invocationExpressionParam = invocationExpressionParam.InvocationExpressionReference as IInvocationExpression;
                //var allowed = new[] { "ToUpper", "ToLower", "ToString" };
                //if (!new List<string>(allowed).Contains(e.ShortName))
                //    return;
            //    	    }
            //while (containingType != null && containingType.CLRName == "System.String");

            if(containingType == null)
                return;

            if(containingType.CLRName == "System.Enum" && e.ShortName == "ToString")
            {
                Found = true;

                // Save the enum declaration so we can implement the fix.
                this.FoundEnumReference = invocationExpressionParam.Reference;
                this.EnumReferenceName = expression.QualifierExpression.GetText();

                IExpressionType qe = expression.QualifierExpression.GetExpressionType();
                this.EnumDeclaredName = ((IDeclaredType)qe).GetPresentableName(PsiLanguageType.GetByProjectFile(invocationExpressionParam.GetProjectFile()));
            }
        }
    /// <summary>The is available.</summary>
    /// <param name="cache">The cache.</param>
    /// <returns>The <see cref="bool"/>.</returns>
    public override bool IsAvailable(IUserDataHolder cache)
    {
      this.InvocationExpression = null;

      var invocationExpression = this.provider.GetSelectedElement<IInvocationExpression>(true, true);
      if (invocationExpression == null)
      {
        return false;
      }

      var referenceExpression = invocationExpression.InvokedExpression as IReferenceExpression;
      if (referenceExpression == null)
      {
        return false;
      }

      var declaredElement = referenceExpression.Reference.Resolve().DeclaredElement;
      if (declaredElement == null)
      {
        return false;
      }

      if (declaredElement.ShortName != "GetItem")
      {
        return false;
      }

      var containingType = this.GetContainingTypeName(declaredElement);
      if (containingType == null)
      {
        return false;
      }

      if (containingType != "Sitecore.Data.Database")
      {
        return false;
      }

      this.InvocationExpression = invocationExpression;

      return true;
    }
Beispiel #60
0
        private IDeclaredType GetDeclaredType(IInvocationExpression invocationExpression)
        {
            if (invocationExpression.TypeArguments.Count > 0)
            {
                return invocationExpression.TypeArguments[0].GetScalarType();
            }

            if (invocationExpression.ArgumentList.Arguments.Count > 0)
            {
                var typeOfExpression = invocationExpression.ArgumentList.Arguments[0].Value as ITypeofExpression;
                if (typeOfExpression == null)
                {
                    return null;
                }

                return typeOfExpression.ArgumentType.GetScalarType();
            }

            return null;
        }