public AddRequiresExecutor(ICSharpContextActionDataProvider provider, bool shouldBeGeneric,
     ICSharpFunctionDeclaration functionDeclaration, string parameterName, IClrTypeName propertyType)
     : this(provider, shouldBeGeneric, new []{functionDeclaration}, parameterName, propertyType)
 {
     Contract.Requires(provider != null);
     _provider = provider;
 }
        public override sealed bool IsAvailable(IUserDataHolder cache)
        {
            using (ReadLockCookie.Create())
            {
                if (Provider.SelectedElement != null)
                {
                    var catelArgumentType = TypeHelper.CreateTypeByCLRName(CatelCore.Argument, Provider.PsiModule, Provider.SelectedElement.GetResolveContext());
                    _parameterDeclaration = null;
                    _methodDeclaration = null;

                    if (catelArgumentType.GetTypeElement() != null)
                    {
                        if (Provider.SelectedElement != null && Provider.SelectedElement.Parent is IRegularParameterDeclaration)
                        {
                            _parameterDeclaration = Provider.SelectedElement.Parent as IRegularParameterDeclaration;
                            if (_parameterDeclaration.Parent != null && _parameterDeclaration.Parent != null
                                && _parameterDeclaration.Parent.Parent is ICSharpFunctionDeclaration)
                            {
                                _methodDeclaration =
                                    _parameterDeclaration.Parent.Parent as ICSharpFunctionDeclaration;
                            }
                        }
                    }
                    
                }
            }

            return _parameterDeclaration != null && IsArgumentTypeTheExpected(_parameterDeclaration.Type)
                   && _methodDeclaration != null
                   && !IsArgumentChecked(_methodDeclaration, _parameterDeclaration);
        }
        /// <summary>
        /// Returns Code contract based preconditions only for specified <paramref name="functionDeclaration"/>.
        /// </summary>
        public static IEnumerable <ContractRequires> GetRequires(this ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result <IEnumerable <ContractRequires> >() != null);

            return(functionDeclaration.GetPreconditions().OfType <ContractRequires>());
        }
        private static IStatement GetAnchorInitializationAnchorMember(
            [NotNull] ICSharpFunctionDeclaration constructorDeclaration)
        {
            if (constructorDeclaration == null)
            {
                throw new ArgumentNullException("constructorDeclaration");
            }
            var statements = constructorDeclaration.Body.Statements;

            if (statements.IsEmpty)
            {
                return(null);
            }

            var expressionStatement =
                statements.LastOrDefault(statement => statement is IExpressionStatement) as IExpressionStatement;

            if (expressionStatement != null)
            {
                return(expressionStatement);
            }

            var ifStatement = statements.LastOrDefault(statement => statement is IIfStatement);

            return(ifStatement ?? statements.LastOrDefault());
        }
        protected override bool ReturnTypeCompatibleForEnsure(ICSharpFunctionDeclaration methodDeclaration)
        {
            var returnType = methodDeclaration.GetReturnType();

            return(returnType.IsEnumType() ||
                   (returnType.IsNullable() && returnType.GetNullableUnderlyingType().IsEnumType()));
        }
 public EnumCheckRequiresExecutor(EnumCheckRequiresAvailability availability, bool useGenericVersion) 
     : base(availability)
 {
     _availability = availability;
     _useGenericVersion = useGenericVersion;
     _functionDeclaration = _availability.FunctionToInsertPrecondition;
 }
        public static IEnumerable <ContractInvariant> GetInvariants(this ICSharpFunctionDeclaration invariantMethod)
        {
            Contract.Requires(invariantMethod != null);
            Contract.Ensures(Contract.Result <IEnumerable <ContractInvariant> >() != null);

            return(GetContractAssertions(invariantMethod).OfType <ContractInvariant>());
        }
        public static AddContractClassAvailability IsAvailableForSelectedMethod(ICSharpContextActionDataProvider provider, ICSharpFunctionDeclaration selectedFunction = null)
        {
            Contract.Requires(provider != null);
            Contract.Ensures(Contract.Result<AddContractClassAvailability>() != null);

            return new AddContractClassAvailability(provider, true, selectedFunction);
        }
Ejemplo n.º 9
0
        private bool ComputeIsAvailable(out ICSharpFunctionDeclaration currentFunction,
                                        out IClrTypeName propertyType)
        {
            currentFunction = null;
            propertyType    = null;

            var propertyDeclaration = _provider.GetSelectedElement <IPropertyDeclaration>(true, true);

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

            if (propertyDeclaration.IsAuto)
            {
                return(false);
            }

            currentFunction = propertyDeclaration.AccessorDeclarations.FirstOrDefault(a => a.Kind == AccessorKind.SETTER);
            if (currentFunction == null)
            {
                return(false);
            }

            propertyType = propertyDeclaration.Type.GetClrTypeName();

            return(propertyDeclaration.Type.IsReferenceOrNullableType());
        }
Ejemplo n.º 10
0
 public ElementProcessor(
     ICSharpFunctionDeclaration element,
     IHighlightingConsumer consumer)
 {
     _element  = element;
     _consumer = consumer;
 }
 protected override bool IsArgumentChecked(
     ICSharpFunctionDeclaration methodDeclaration, IRegularParameterDeclaration parameterDeclaration)
 {
     // TODO: Verify the completion of the condition || (InvokationDetectionHelper.IsMaximunInvoked(methodDeclaration.Body.GetText(), parameterDeclaration.DeclaredName) && InvokationDetectionHelper.IsMinimalInvoked(methodDeclaration.Body.GetText(), parameterDeclaration.DeclaredName));
     return ArgumentCheckStatementDetectionHelper.IsNotOutOfRangeInvoked(
         methodDeclaration.Body.GetText(), parameterDeclaration.DeclaredName);
 }
Ejemplo n.º 12
0
 public AddRequiresExecutor(ICSharpContextActionDataProvider provider, bool shouldBeGeneric,
                            ICSharpFunctionDeclaration functionDeclaration, string parameterName, IClrTypeName propertyType)
     : this(provider, shouldBeGeneric, new [] { functionDeclaration }, parameterName, propertyType)
 {
     Contract.Requires(provider != null);
     _provider = provider;
 }
        private bool IsEnsuresAvailableFor(out ICSharpFunctionDeclaration selectedFunctionDeclaration)
        {
            var returnTypeEnsuresAvailability = new NullCheckReturnTypeEnsuresAvailability(_provider);

            selectedFunctionDeclaration = returnTypeEnsuresAvailability.SelectedFunctionDeclaration;
            return(returnTypeEnsuresAvailability.IsAvailable);
        }
 public EnumCheckRequiresExecutor(EnumCheckRequiresAvailability availability, bool useGenericVersion)
     : base(availability)
 {
     _availability        = availability;
     _useGenericVersion   = useGenericVersion;
     _functionDeclaration = _availability.FunctionToInsertPrecondition;
 }
Ejemplo n.º 15
0
 private bool CanAddContractClassIfNecessary(ICSharpFunctionDeclaration selectedFunction,
                                             out AddContractClassAvailability addContractAvailability)
 {
     // Adding contract class could be unavailable, thats ok, because this "combo" part is optional!
     addContractAvailability = AddContractClassAvailability.IsAvailableForSelectedMethod(_provider, selectedFunction);
     return(true);
 }
        private bool ComputeIsAvailable(out ICSharpFunctionDeclaration currentFunction)
        {
            currentFunction = null;

            if (!IsReturnOrMethodDeclarationSelected() && !IsPropertyWithGetterSelected())
            {
                return(false);
            }

            var methodDeclaration = GetFunctionDeclaration();

            currentFunction = methodDeclaration;

            if (!methodDeclaration.IsValidForContracts())
            {
                return(false);
            }

            if (ResultIsVoid(methodDeclaration))
            {
                return(false);
            }

            if (!ReturnTypeCompatibleForEnsure(methodDeclaration))
            {
                return(false);
            }

            return(true);
        }
        public static IEnumerable <ContractEnsures> GetEnsures(this ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result <IEnumerable <ContractEnsures> >() != null);

            return(GetContractAssertions(functionDeclaration).OfType <ContractEnsures>());
        }
        public static ContractRequires GetLastRequiresFor(this ICSharpFunctionDeclaration functionDeclaration,
                                                          string parameterName)
        {
            var parameters = functionDeclaration.DeclaredElement.Parameters
                             .Select(p => p.ShortName).TakeWhile(paramName => paramName != parameterName)
                             .Reverse().ToList();

            // Creating lookup where key is argument name, and the value is statements.
            var requiresStatements =
                functionDeclaration
                .GetRequires()
                .ToList();

            /*.SelectMany(x => x.ArgumentNames.Select(a => new {Statement = x, ArgumentName = a}))
             * .ToLookup(x => x.ArgumentName, x => x.Statement)*/
            ;

            // Looking for the last usage of the parameters in the requires statements
            foreach (var p in parameters)
            {
                // TODO: it seems terrible!!! and ugly!
                var precondition = requiresStatements
                                   .LastOrDefault(r => r.ChecksForNotNull(pa =>
                                                                          pa.CompareReferenceArgument(ra => ra.BaseArgumentName == p)));

                if (precondition != null)
                {
                    return(precondition);
                }
            }

            return(null);
        }
        /// <summary>
        /// This method walks the control flow graph counting edges and nodes. Cyclomatic complexity is then calculated from the two values.
        /// </summary>
        private static int CalcCyclomaticComplexity(ICSharpFunctionDeclaration declaration)
        {
            ICSharpControlFlowGraf    graf = CSharpControlFlowBuilder.Build(declaration);
            HashSet <IControlFlowRib> ribs = GetRibs(graf);
            int nodes = GetNodesCount(ribs);

            return(ribs.Count - nodes + 2);
        }
    /// <summary>
    /// This method walks the control flow graph counting edges and nodes. Cyclomatic complexity is then calculated from the two values.
    /// </summary>
    private static int CalcCyclomaticComplexity(ICSharpFunctionDeclaration declaration)
    {
      ICSharpControlFlowGraf graf = CSharpControlFlowBuilder.Build(declaration);
      HashSet<IControlFlowRib> ribs = GetRibs(graf);
      int nodes = GetNodesCount(ribs);

      return ribs.Count - nodes + 2;
    }
Ejemplo n.º 21
0
        /// <summary>
        /// Returns a list of statements for specified function.
        /// </summary>
        public static IList <ProcessedStatement> GetCodeContractBlockStatements(
            this ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result <IList <ProcessedStatement> >() != null);

            return(ContractBlock.CreateCodeContractBlock(functionDeclaration).ProcessedStatements);
        }
Ejemplo n.º 22
0
 public CognitiveComplexityErrorHighlighting(
     ICSharpFunctionDeclaration declaration,
     int complexityDelta,
     int complexityPercentage)
 {
     Declaration          = declaration;
     ComplexityDelta      = complexityDelta;
     ComplexityPercentage = complexityPercentage;
 }
        private void AddRequiresTo([NotNull] ICSharpFunctionDeclaration contractFunction)
        {
            Contract.Requires(contractFunction != null);

            var addRequiresExecutor = new AddRequiresExecutor(_provider, _requiresShouldBeGeneric,
                                                              contractFunction, _availability.ParameterName, _availability.ParameterType);

            addRequiresExecutor.ExecuteTransaction();
        }
 public CognitiveComplexityInfoHighlighting(
     ICSharpFunctionDeclaration declaration,
     int complexityAbsolute,
     int complexityPercentage)
 {
     Declaration          = declaration;
     ComplexityAbsolute   = complexityAbsolute;
     ComplexityPercentage = complexityPercentage;
 }
Ejemplo n.º 25
0
        public static bool HasAttribute(this ICSharpFunctionDeclaration functionDeclaration, Type attributeType)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Requires(functionDeclaration.IsValidForContracts());
            Contract.Requires(attributeType != null);
            Contract.Requires(attributeType.IsAttribute());

            return(functionDeclaration.DeclaredElement.HasAttributeInstance(
                       new ClrTypeName(attributeType.FullName), inherit: true));
        }
        private void CheckTestMethodHasCodeAndCreateWarningIfNot(ICSharpFunctionDeclaration declaration)
        {
            var statements = declaration.Body.Statements;

            if (!statements.Any())
            {
                IHighlighting highlighting = new TestMethodMissingCodeWarning(declaration, "Test method is empty");
                AddHighlighting(declaration.GetNameDocumentRange(), highlighting);
            }
        }
        private void AddRequiresTo(ICSharpFunctionDeclaration contractFunction)
        {
            var executors = _availability.ArgumentNames
                            .Reverse() // This fix an issue that ArgumentCheckExecutor can't find newly created Contract.Requires and adds new Contract.Requires in the opposite order!
                            .Select(pn => ArgumentCheckExecutor(pn.Name, pn.Type, contractFunction));

            foreach (var executor in executors)
            {
                executor.ExecuteTransaction();
            }
        }
        public CognitiveComplexityElementProcessor(ICSharpFunctionDeclaration element)
        {
            _element = element;

#if RIDER
            if (CognitiveComplexityCodeInsightsProvider.ShowIndicators)
            {
                Complexities = new List <(ITreeNode Node, DocumentOffset offset, int complexity)>();
            }
#endif
        }
        internal LegacyContractCustomWarningHighlighting(ICSharpFunctionDeclaration element, CustomWarningValidationResult warning, ValidatedContractBlock contractBlock)
        {
            Contract.Requires(warning != null);
            Contract.Requires(contractBlock != null);

            _toolTip          = warning.GetErrorText();
            _range            = element.GetHighlightingRange();
            _validationResult = warning;
            _contractBlock    = contractBlock;
            MethodName        = warning.GetEnclosingMethodName();
        }
Ejemplo n.º 30
0
        public static IDeclaredType GetReturnType(this ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Requires(functionDeclaration.IsValidForContracts());

            // TODO: add another precondition taht functionDeclaration is resolved!.
            // Only in this case we can ensure that result would be not null
            // Contract.Requires(functionDeclaration.Resolved().IsOk());

            return(functionDeclaration.DeclaredElement.ReturnType as IDeclaredType);
        }
        private EnsuresExecutor(ICSharpContextActionDataProvider provider, ICSharpFunctionDeclaration selectedFunction,
            EnsuresType ensuresType)
            : base(provider)
        {
            Contract.Requires(provider != null);
            Contract.Requires(selectedFunction != null);
            Contract.Requires(Enum.IsDefined(typeof (EnsuresType), ensuresType));

            _selectedFunction = selectedFunction;
            _ensuresFactoryMethod = CreateEnsuresFactoryMethod(ensuresType);
        }
        private EnsuresExecutor(ICSharpContextActionDataProvider provider, ICSharpFunctionDeclaration selectedFunction,
                                EnsuresType ensuresType)
            : base(provider)
        {
            Contract.Requires(provider != null);
            Contract.Requires(selectedFunction != null);
            Contract.Requires(Enum.IsDefined(typeof(EnsuresType), ensuresType));

            _selectedFunction     = selectedFunction;
            _ensuresFactoryMethod = CreateEnsuresFactoryMethod(ensuresType);
        }
        internal LegacyContractCustomWarningHighlighting(ICSharpFunctionDeclaration element, CustomWarningValidationResult warning, ValidatedContractBlock contractBlock)
        {
            Contract.Requires(warning != null);
            Contract.Requires(contractBlock != null);

            _toolTip = warning.GetErrorText();
            _range = element.GetHighlightingRange();
            _validationResult = warning;
            _contractBlock = contractBlock;
            MethodName = warning.GetEnclosingMethodName();
            
        }
        public static ICSharpFunctionDeclaration GetContractFunction(this ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Requires(functionDeclaration.DeclaredElement != null);

            if (functionDeclaration.IsAbstract)
            {
                return(GetContractMethodForAbstractFunction(functionDeclaration));
            }

            return(functionDeclaration);
        }
 internal static LegacyContractCustomWarningHighlighting Create(ICSharpFunctionDeclaration element, CustomWarningValidationResult warning, ValidatedContractBlock contractBlock)
 {
     switch (warning.Warning)
     {
         case MalformedContractCustomWarning.PreconditionInAsyncMethod:
             return new PreconditionInAsyncMethodHighlighting(element, warning, contractBlock);
         case MalformedContractCustomWarning.PreconditionInMethodWithIteratorBlock:
             return new PreconditionInMethodWithIteratorBlockHighlighing(element, warning, contractBlock);
         default:
             return new LegacyContractCustomWarningHighlighting(element, warning, contractBlock);
     }
 }
Ejemplo n.º 36
0
        public static bool IsValidForContracts(this ICSharpFunctionDeclaration functionDeclaration)
        {
            // TODO: is there any other criterias??

            return(functionDeclaration != null &&
                   functionDeclaration.DeclaredElement != null &&
                   // TODO: removed this, because for abstract method we're considering only return types
                   // but not the body!
                   //functionDeclaration.Body != null &&
                   functionDeclaration.IsValid() &&
                   functionDeclaration.GetReturnType() != null);
        }
        /// <summary>Inspects the specified function.</summary>
        /// <param name="function">The function.</param>
        /// <returns>Returns the code annotation attribute.</returns>
        private static CodeAnnotationAttribute Inspect([NotNull] ICSharpFunctionDeclaration function)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }

            var project = function.GetProject();

            if (project == null)
            {
                return(CodeAnnotationAttribute.Undefined);
            }

            var projectFile = project.ProjectFile;

            if (projectFile == null)
            {
                return(CodeAnnotationAttribute.Undefined);
            }

            if (!function.DeclaredElement.ReturnType.IsReferenceType())
            {
                return(CodeAnnotationAttribute.Undefined);
            }

            // return CodeAnnotationAttribute.NotNull;
            new AllNonQualifiedSignatureReferencesResolver().Process(function);
            var builder = new CSharpControlFlowBuilder();
            var graph   = builder.GraphFromNode(function, null, true) as ICSharpControlFlowGraph;

            if (graph == null)
            {
                return(CodeAnnotationAttribute.Undefined);
            }

            var graphInspector = CSharpControlFlowGraphInspector.Inspect(graph, ValueAnalysisMode.OPTIMISTIC);

            switch (graphInspector.SuggestReturnValueAnnotationAttribute)
            {
            case CSharpControlFlowNullReferenceState.NOT_NULL:
                return(CodeAnnotationAttribute.NotNull);

            case CSharpControlFlowNullReferenceState.NULL:
                return(CodeAnnotationAttribute.CanBeNull);

            case CSharpControlFlowNullReferenceState.MAY_BE_NULL:
                return(CodeAnnotationAttribute.CanBeNull);
            }

            return(CodeAnnotationAttribute.NotSet);
        }
        /// <summary>
        /// Returns all preconditions for specified <paramref name="functionDeclaration"/> including simple argument checks.
        /// </summary>
        public static IEnumerable <IPrecondition> GetPreconditions(this ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result <IEnumerable <IPrecondition> >() != null);

            if (functionDeclaration.Body == null)
            {
                return(Enumerable.Empty <IPrecondition>());
            }

            return(functionDeclaration.Body.Statements
                   .Select(ContractStatementFactory.TryCreatePrecondition).Where(p => p != null));
        }
        public static bool Overrides(this IClassLikeDeclaration classLikeDeclaration,
                                     ICSharpFunctionDeclaration baseFunctionDeclaration)
        {
            Contract.Requires(classLikeDeclaration != null);
            Contract.Requires(baseFunctionDeclaration != null);

            Func <IMethodDeclaration, bool> isOverridesCurrentFunction =
                md => md.DeclaredElement.GetAllSuperMembers()
                .Any(overridable => overridable.Member.Equals(baseFunctionDeclaration.DeclaredElement));

            return(classLikeDeclaration
                   .With(x => x.Body)
                   .Return(x => x.Methods.FirstOrDefault(isOverridesCurrentFunction)) != null);
        }
        public static bool Overrides(this IClassLikeDeclaration classLikeDeclaration,
            ICSharpFunctionDeclaration baseFunctionDeclaration)
        {
            Contract.Requires(classLikeDeclaration != null);
            Contract.Requires(baseFunctionDeclaration != null);

            Func<IMethodDeclaration, bool> isOverridesCurrentFunction =
                md => md.DeclaredElement.GetAllSuperMembers()
                    .Any(overridable => overridable.Member.Equals(baseFunctionDeclaration.DeclaredElement));

            return classLikeDeclaration
                .With(x => x.Body)
                .Return(x => x.Methods.FirstOrDefault(isOverridesCurrentFunction)) != null;
        }
        private ICSharpStatement CreateEnumResultIsDefinedEnsures(ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result<ICSharpStatement>() != null);

            string format = "$0.Ensures($1.IsDefined(typeof($2), Contract.Result<$3>()));";
            var returnType = (IDeclaredType)functionDeclaration.DeclaredElement.ReturnType;

            // "typeof" type should be different from the Contract.Result<T> for nullable types!
            var typeofType = returnType.IsNullable() ? returnType.GetNullableUnderlyingType() : returnType;

            var systemEnumType = CreateDeclaredType(typeof(Enum));
            return _factory.CreateStatement(format, ContractType, 
                systemEnumType, typeofType, returnType);
        }
        public ComboEnsuresExecutor(ICSharpContextActionDataProvider provider, 
            AddContractClassAvailability addContractAvailability,
            ICSharpFunctionDeclaration selectedFunctionDeclaration)
            : base(provider)
        {
            Contract.Requires(provider != null);
            Contract.Requires(addContractAvailability != null);
            Contract.Requires(addContractAvailability.IsAvailable);

            Contract.Requires(selectedFunctionDeclaration != null);

            _provider = provider;
            _addContractAvailability = addContractAvailability;
            _selectedFunctionDeclaration = selectedFunctionDeclaration;
        }
        private bool ResultIsAlreadyCheckedByContractEnsures(ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);

            if (functionDeclaration.Body == null)
                return false;

            var returnType = functionDeclaration.GetReturnType();

            if (returnType == null)
                return false;

            return ResultIsAlreadyCheckedByContractEnsures(
                functionDeclaration.GetEnsures(), returnType);
        }
        public static ContractBlock CreateLegacyContractBlock(ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result<ContractBlock>() != null);

            var statements =
                GetStatements(functionDeclaration.Body)
                .Select(ProcessedStatement.Create)
                .Where(x => x.ContractStatement != null)
                .ToList();

            if (statements.All(s => s.ContractStatement.IsIfThrowStatement()))
                return new ContractBlock(statements);
            
            return new ContractBlock(new ProcessedStatement[]{});
        }
        private AddContractClassAvailability(ICSharpContextActionDataProvider provider,
            bool contractForSelectedMethod, ICSharpFunctionDeclaration selectedFunctionDeclaration)
        {
            Contract.Requires(provider != null);
            Contract.Requires(provider.SelectedElement != null);

            _provider = provider;
            _contractForSelectedMethod = contractForSelectedMethod;
            _selectedFunctionDeclaration = selectedFunctionDeclaration ?? GetSelectedFunction();

            IsAvailable = ComputeIsAvailable();
            if (IsAvailable)
            {
                ComputeSelectedDeclarationMember();
            }
        }
        private bool ComputeIsAvailable(out ICSharpFunctionDeclaration currentFunction)
        {
            if (!EnsuresAvailableForSelectedReturnType(out currentFunction))
                return false;

            // For abstract and interface methods contract method differs from the
            // current method
            var contractMethod = currentFunction.GetContractFunction();
            if (contractMethod == null)
                return false;

            if (ResultIsAlreadyCheckedByContractEnsures(contractMethod))
                return false;

            return true;
        }
        // TODO: move close to the rest of errors and messages!!
        private static string ErrorForIncompatibleEnsuresAndReturnType(IType methodResult, IDeclaredType contractResult, 
            ICSharpFunctionDeclaration method)
        {
            string kind = "method";
            string name = method.DeclaredName;

            var property = method as IAccessorDeclaration;
            if (property != null)
            {
                kind = "property";
                name = name.Replace("get_", "");
            }
            
            return string.Format("Detected a call to Result with '{0}' in {1} '{2}', should be '{3}'",
                contractResult.GetPresentableName(CSharpLanguage.Instance), kind, name,
                methodResult.GetPresentableName(CSharpLanguage.Instance));
        }
        public AddContractClassExecutor(ICSharpContextActionDataProvider provider, AddContractClassAvailability addContractForAvailability, 
            ICSharpFunctionDeclaration requiredFunction = null)
        {
            Contract.Requires(provider != null);
            Contract.Requires(addContractForAvailability != null);
            Contract.Requires(addContractForAvailability.IsAvailable);

            _addContractForAvailability = addContractForAvailability;
            _provider = provider;
            _requiredFunction = requiredFunction;

            _factory = _provider.ElementFactory;
            // TODO: look at this class CSharpStatementNavigator

            Contract.Assert(provider.SelectedElement != null);
            
            _currentFile = (ICSharpFile)provider.SelectedElement.GetContainingFile();
        }
        /// <summary>
        /// Code contract statement contains only a list of Code Contract statements.
        /// </summary>
        public static ContractBlock CreateCodeContractBlock(ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result<ContractBlock>() != null);

            var statements =
                GetStatements(functionDeclaration.Body)
                .Select(ProcessedStatement.Create)
                .ToList();

            int lastContractIndex =
                statements.LastIndexOf(
                    s => (s.CodeContractStatement != null &&
                         (s.CodeContractStatement.IsPrecondition ||
                          s.CodeContractStatement.IsPostcondition ||
                          s.CodeContractStatement.StatementType == CodeContractStatementType.EndContractBlock)));

            // Because we're taking +1 item we can skip check for -1!
            return new ContractBlock(statements.Take(lastContractIndex + 1).ToList());
        }
        private bool ComputeIsAvailable(out ICSharpFunctionDeclaration currentFunction)
        {
            currentFunction = null;

            if (!IsReturnOrMethodDeclarationSelected() && !IsPropertyWithGetterSelected())
                return false;

            var methodDeclaration = GetFunctionDeclaration();

            currentFunction = methodDeclaration;

            if (!methodDeclaration.IsValidForContracts())
                return false;

            if (ResultIsVoid(methodDeclaration))
                return false;

            if (!ReturnTypeCompatibleForEnsure(methodDeclaration))
                return false;

            return true;
        }
 protected override bool ReturnTypeCompatibleForEnsure(ICSharpFunctionDeclaration methodDeclaration)
 {
     return methodDeclaration.GetReturnType().IsReferenceOrNullableType();
 }
Ejemplo n.º 52
0
 protected FunctionDeclarationBase(ICSharpFunctionDeclaration functionDeclaration)
     : base(functionDeclaration)
 {
     _functionDeclaration = functionDeclaration;
 }
 internal PreconditionInMethodWithIteratorBlockHighlighing(ICSharpFunctionDeclaration element, CustomWarningValidationResult warning, ValidatedContractBlock contractBlock)
     : base(element, warning, contractBlock)
 {}
 protected override bool IsArgumentChecked(ICSharpFunctionDeclaration methodDeclaration, IRegularParameterDeclaration parameterDeclaration)
 {
     return ArgumentCheckStatementDetectionHelper.IsNotNullOrEmptyInvoked(methodDeclaration.Body.GetText(), parameterDeclaration.DeclaredName);
 }
 private bool ResultIsVoid(ICSharpFunctionDeclaration functionDeclaration)
 {
     return functionDeclaration.GetReturnType().IsVoid();
 }
 protected override bool ReturnTypeCompatibleForEnsure(ICSharpFunctionDeclaration methodDeclaration)
 {
     Contract.Requires(methodDeclaration != null);
     throw new NotImplementedException();
 }
    /// <summary>
    /// Processes the function declaration.
    /// </summary>
    /// <param name="declaration">The declaration.</param>
    private void ProcessFunctionDeclaration(ICSharpFunctionDeclaration declaration)
    {
      // Nothing to calculate
      if(declaration.Body == null)
        return;

      int cyclomatic = CalcCyclomaticComplexity(declaration);

      // Placing highlighting
      if(cyclomatic > myThreshold)
      {
        string message = string.Format("Member has cyclomatic complexity of {0} ({1}%)", cyclomatic, (int)(cyclomatic * 100.0 / myThreshold));
        var warning = new ComplexityWarning(message);
        myHighlightings.Add(new HighlightingInfo(declaration.GetNameDocumentRange(), warning));
      }
    }
 protected abstract bool ReturnTypeCompatibleForEnsure(ICSharpFunctionDeclaration methodDeclaration);
 protected override bool ReturnTypeCompatibleForEnsure(ICSharpFunctionDeclaration methodDeclaration)
 {
     var returnType = methodDeclaration.GetReturnType();
     return returnType.IsEnumType() || 
         (returnType.IsNullable() && returnType.GetNullableUnderlyingType().IsEnumType());
 }
        private ICSharpStatement CreateResultNotNullEnsures(ICSharpFunctionDeclaration functionDeclaration)
        {
            Contract.Requires(functionDeclaration != null);
            Contract.Ensures(Contract.Result<ICSharpStatement>() != null);

            // TODO: IsValid returns true even if resulting expression would not compiles!
            // To check this, please remove semicolon in the string below.
            // Maybe Resolve method would be good!
            // Contract.Ensures(Contract.Result<ICSharpStatement>().IsValid());

            string format = "$0.Ensures(Contract.Result<$1>() != null);";
            var returnType = (IDeclaredType)functionDeclaration.DeclaredElement.ReturnType;

            return _factory.CreateStatement(format, ContractType, returnType);
        }