Esempio n. 1
0
        /// <summary>Creates a variable declaration for catch clause.</summary>
        /// <param name="exceptionType">The type of a created variable.</param>
        /// <param name="context">The context. </param>
        public ICatchVariableDeclaration CreateCatchVariableDeclarationNode(IDeclaredType exceptionType, ITreeNode context)
        {
            var tryStatement = _factory.CreateStatement("try {} catch(Exception e) {}") as ITryStatement;

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

            var catchClause = tryStatement.Catches[0] as ISpecificCatchClause;

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

            var exceptionDeclaration = catchClause.ExceptionDeclaration;

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

            if (exceptionType != null)
            {
                var declaredTypeUsageNode = _factory.CreateTypeUsage(exceptionType, context);
                catchClause.SetExceptionTypeUsage(declaredTypeUsageNode);
            }

            return(exceptionDeclaration);
        }
Esempio n. 2
0
        private static string GetModuleFullName([NotNull] IType type)
        {
            IDeclaredType scalarType = type.GetScalarType();

            if (scalarType != null)
            {
                AssemblyNameInfo assembly = scalarType.Assembly;
                if (assembly != null)
                {
                    return(assembly.FullName);
                }
            }

            var assemblyPsiModule = type.Module as IAssemblyPsiModule;

            if (assemblyPsiModule != null)
            {
                string name = assemblyPsiModule.Assembly.AssemblyName.FullName;
                if (name != null)
                {
                    return(name);
                }
            }

            return(type.Module.DisplayName);
        }
Esempio n. 3
0
        /// <summary>Creates a try statement for the given exception type and variable name. </summary>
        /// <param name="exceptionType">The exception type. </param>
        /// <param name="exceptionVariableName">The exception variable name. </param>
        /// <param name="context">The context. </param>
        /// <returns>The try statement. </returns>
        public ITryStatement CreateTryStatement(IDeclaredType exceptionType, string exceptionVariableName, ITreeNode context)
        {
            var tryStatement = _factory.CreateStatement("try {} catch($0 $1) {}",
                                                        exceptionType.GetClrName().ShortName, exceptionVariableName) as ITryStatement;

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

            var catchClause = tryStatement.Catches[0] as ISpecificCatchClause;

            if (catchClause == null)
            {
                return(tryStatement);
            }

            var exceptionDeclaration = catchClause.ExceptionDeclaration;

            if (exceptionDeclaration == null)
            {
                return(tryStatement);
            }

#if R8
            var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType);
#else
            var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType, context);
#endif

            exceptionDeclaration.SetDeclaredTypeUsage(declaredTypeUsageNode);

            return(tryStatement);
        }
        public static bool IsAssignableFrom(this Type type, IDeclaredType c)
        {
            if (c == null)
                return false;

            return type.FullName == c.GetClrName().FullName || c.GetAllSuperTypes().Any(superType => type.FullName == superType.GetClrName().FullName);
        }
Esempio n. 5
0
        /// <summary>Creates a try statement for the given exception type and variable name. </summary>
        /// <param name="exceptionType">The exception type. </param>
        /// <param name="exceptionVariableName">The exception variable name. </param>
        /// <param name="context">The context. </param>
        /// <returns>The try statement. </returns>
        public ITryStatement CreateTryStatement(IDeclaredType exceptionType, string exceptionVariableName, ITreeNode context)
        {
            var tryStatement = _factory.CreateStatement("try {} catch($0 $1) {$2    // TODO: Handle the $0$2}",
                                                        exceptionType.GetClrName().FullName, exceptionVariableName, Environment.NewLine) as ITryStatement;

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

            var catchClause = tryStatement.Catches[0] as ISpecificCatchClause;

            if (catchClause == null)
            {
                return(tryStatement);
            }

            var exceptionDeclaration = catchClause.ExceptionDeclaration;

            if (exceptionDeclaration == null)
            {
                return(tryStatement);
            }

            var declaredTypeUsageNode = _factory.CreateTypeUsage(exceptionType, context);

            catchClause.SetExceptionTypeUsage(declaredTypeUsageNode);

            return(tryStatement);
        }
Esempio n. 6
0
            public override void VisitDeclaredType(IDeclaredType declaredType)
            {
                if (!myTypes.Add(declaredType))
                {
                    return;
                }

                var typeElement = declaredType.GetTypeElement();

                if (typeElement == null)
                {
                    return;
                }

                var substitution   = declaredType.GetSubstitution();
                var typeParameters = typeElement.TypeParameters;

                if (typeParameters.Count == 0)
                {
                    return;
                }

                foreach (var typeParameter in typeParameters)
                {
                    substitution[typeParameter].Accept(this);
                }
            }
        /// <summary>Creates a specific catch clause with given <paramref name="exceptionType"/> and <paramref name="catchBody"/>.</summary>
        /// <param name="exceptionType">Type of the exception to catch.</param>
        /// <param name="catchBody">Body of the created catch.</param>
        /// <param name="variableName">A name for catch variable.</param>
        public ISpecificCatchClause CreateSpecificCatchClause(IDeclaredType exceptionType, IBlock catchBody, string variableName)
        {
            var tryStatement = _factory.CreateStatement("try {} catch(Exception $0) {}", variableName) as ITryStatement;
            if (tryStatement == null)
                return null;

            var catchClause = tryStatement.Catches[0] as ISpecificCatchClause;
            if (catchClause == null)
                return null;

            if (catchBody == null)
            {
                catchBody = _factory.CreateBlock("{$1    // TODO: Handle the $0 $1}",
                    exceptionType.GetClrName().ShortName, Environment.NewLine);
            }

            if (exceptionType != null)
            {
                var exceptionDeclaration = catchClause.ExceptionDeclaration;
                if (exceptionDeclaration == null)
                    return null;

            #if R8
                var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType);
            #else
                var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType, catchBody);

            #endif
                exceptionDeclaration.SetDeclaredTypeUsage(declaredTypeUsageNode);
            }

            catchClause.SetBody(catchBody);
            return catchClause;
        }
        private static bool IsTaskType(IDeclaredType type)
        {
            string typeName = type.GetClrName().FullName;

            return(string.Equals(typeName, TaskTypeName, StringComparison.Ordinal) ||
                   string.Equals(typeName, TaskOfTTypeName, StringComparison.Ordinal));
        }
Esempio n. 9
0
        private bool IsNinjectBindCall(ITreeNode element)
        {
            var invocationExpression = element as IInvocationExpression;

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

            var resolve = invocationExpression.InvocationExpressionReference.Resolve().Result;
            var method  = resolve.DeclaredElement as IMethod;

            if (method == null)
            {
                return(false);
            }
            ITypeElement containingType = method.GetContainingType();

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

            if (bindingRootType == null)
            {
                bindingRootType = TypeFactory.CreateTypeByCLRName("Ninject.Syntax.IBindingRoot", element.GetPsiModule());
            }

            return(containingType.IsDescendantOf(bindingRootType.GetTypeElement()));
        }
        public void Generate(CSharpGeneratorContext context,
                             IList <GeneratorDeclaredElement <ITypeOwner> > elements,
                             CSharpElementFactory factory)
        {
            IMethodDeclaration methodDeclaration = null;

            ITypeElement declaredElement = context.ClassDeclaration.DeclaredElement;

            if (declaredElement != null)
            {
                IDeclaredType byteType = TypeFactory.CreateTypeByCLRName(PredefinedType.BYTE_FQN, context.PsiModule,
                                                                         context.Anchor.GetResolveContext());
                _byteArrayType      = TypeFactory.CreateArrayType(byteType, 1);
                _typeConversionRule = new CSharpTypeConversionRule(context.PsiModule);
                IOverridableMember member = declaredElement.Methods.FirstOrDefault(ValidateMethod);
                if (member != null)
                {
                    methodDeclaration = (IMethodDeclaration)member.GetDeclarations().FirstOrDefault();
                    Generate(context, methodDeclaration, elements, factory);
                    return;
                }
            }
            string method = String.Format("public Int32 {0}(Byte[] bytes, Int32 startIndex)", MethodName);

            methodDeclaration = (IMethodDeclaration)factory.CreateTypeMemberDeclaration(method);
            Generate(context, methodDeclaration, elements, factory);
            context.PutMemberDeclaration(methodDeclaration, null,
                                         newDeclaration => new GeneratorDeclarationElement(newDeclaration));
        }
Esempio n. 11
0
        public static bool IsContainerCall(this ITreeNode node, string containerClrTypeName)
        {
            var invocationExpression = node as IInvocationExpression;

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

            var resolve = invocationExpression.InvocationExpressionReference.Resolve().Result;
            var method  = resolve.DeclaredElement as IMethod;

            if (method == null)
            {
                return(false);
            }
            ITypeElement containingType = method.GetContainingType();

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

            IDeclaredType containerClrType = CreateTypeByClrName(node, containerClrTypeName);

            return(containingType.IsDescendantOf(containerClrType.GetTypeElement()));
        }
Esempio n. 12
0
        private bool ownsTypeMatch(IDeclaration declaration)
        {
            if (string.IsNullOrEmpty(_isOfType))
            {
                return(true);
            }

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

            if (declaration is ITypeOwner)
            {
                IDeclaredType declaredType = ((ITypeOwner)declaration).Type as IDeclaredType;
                if (declaredType == null)
                {
                    return(false);
                }
                ITypeElement typeElement = declaredType.GetTypeElement();
                if (typeElement == null)
                {
                    return(false);
                }
                return(typeElement.IsDescendantOf(_isOfTypeType));
            }
            else
            {
                return(false);
            }
        }
        public static void Initialize(CSharpGeneratorContext context)
        {
            IDeclaredType byteType = TypeFactory.CreateTypeByCLRName(PredefinedType.BYTE_FQN, context.PsiModule, context.Anchor.GetResolveContext());

            _byteArrayType  = TypeFactory.CreateArrayType(byteType, 1);
            _conversionRule = new CSharpTypeConversionRule(context.PsiModule);
        }
        private ICSharpStatement CreateRequiresStatement(bool isGeneric)
        {
            Contract.Ensures(Contract.Result <ICSharpStatement>() != null);

            ITypeElement contractType   = CreateDeclaredType(typeof(Contract));
            ITypeElement systemEnumType = CreateDeclaredType(typeof(System.Enum));

            ITypeElement customEnumType = CreateDeclaredType(_availability.ParameterUnderlyingType);

            ICSharpStatement statement = null;

            if (isGeneric)
            {
                string        format            = "$0.Requires<$1>($2.IsDefined(typeof($3), $4));";
                IDeclaredType argumentException = GetPredefinedType().ArgumentException;

                statement = _factory.CreateStatement(format,
                                                     contractType, argumentException, systemEnumType, customEnumType, _availability.ParameterName);
            }
            else
            {
                string format = "$0.Requires($1.IsDefined(typeof($2), $3));";
                statement = _factory.CreateStatement(format,
                                                     contractType, systemEnumType, customEnumType, _availability.ParameterName);
            }

            return(statement);
        }
        static bool IsTestMethodOfOldMsTest([CanBeNull] IMethodDeclaration methodDeclaration)
        {
            if (methodDeclaration == null || !methodDeclaration.IsDeclaredInOldMsTestProject())
            {
                return(false);
            }

            var testMethodAttributeTypes = null as IDeclaredType[];

            return(methodDeclaration.Attributes.Any(
                       attribute =>
            {
                if (attribute == null)
                {
                    return false;
                }

                if (testMethodAttributeTypes == null)
                {
                    testMethodAttributeTypes = new IDeclaredType[testMethodAttributes.Length];
                    for (var i = 0; i < testMethodAttributes.Length; i++)
                    {
                        testMethodAttributeTypes[i] = TypeFactory.CreateTypeByCLRName(
                            testMethodAttributes[i],
                            NullableAnnotation.Unknown,
                            methodDeclaration.GetPsiModule());
                    }
                }

                var attributeType = attribute.GetAttributeInstance().GetAttributeType();

                return testMethodAttributeTypes.Any(
                    type => attributeType.Equals(type, TypeEqualityComparer.Default) || attributeType.IsSubtypeOf(type));
            }));
        }
Esempio n. 16
0
 /// <summary>
 /// Translates a general-case declared type.
 /// </summary>
 /// <param name="declaredType">The <see cref="IDeclaredType"/> to translate.</param>
 public virtual void TranslateType(IDeclaredType declaredType)
 {
     if (declaredType is IClassType)
     {
         this.TranslateType((IClassType)declaredType);
     }
     else if (declaredType is IEnumeratorType)
     {
         this.TranslateType((IEnumeratorType)declaredType);
     }
     else if (declaredType is IDelegateType)
     {
         this.TranslateType((IDelegateType)declaredType);
     }
     else if (declaredType is IInterfaceType)
     {
         this.TranslateType((IInterfaceType)declaredType);
     }
     else if (declaredType is IStructType)
     {
         this.TranslateType((IStructType)declaredType);
     }
     else
     {
         throw new NotSupportedException(string.Format("Type {0} not supported", declaredType.GetType().Name));
     }
 }
Esempio n. 17
0
        public static string CatchVariableName(ITreeNode treeNode, IDeclaredType exceptionType)
        {
            var namingPolicyManager   = new NamingPolicyManager(LanguageManager.Instance, treeNode.GetSolution());
            var nameParser            = new NameParser(treeNode.GetSolution(), namingPolicyManager, new HostCulture());
            var nameSuggestionManager = new NameSuggestionManager(treeNode.GetSolution(), nameParser, namingPolicyManager);
            var policy = namingPolicyManager.GetPolicy(NamedElementKinds.Locals, treeNode.Language, treeNode.GetSourceFile());

            var namesCollection = nameSuggestionManager.CreateEmptyCollection(
                PluralityKinds.Single, treeNode.Language, true, treeNode.GetSourceFile());

            var entryOptions = new EntryOptions
            {
                PluralityKind          = PluralityKinds.Single,
                PredefinedPrefixPolicy = PredefinedPrefixPolicy.Preserve,
                Emphasis      = Emphasis.Good,
                SubrootPolicy = SubrootPolicy.Decompose
            };

            namesCollection.Add(exceptionType, entryOptions);
            namesCollection.Prepare(policy.NamingRule, ScopeKind.Common, new SuggestionOptions());

            try
            {
                return(namesCollection.GetRoots().FirstOrDefault()?.GetFinalPresentation() ?? String.Empty);
            }
            catch (ArgumentNullException)
            {
                return(String.Empty);
            }
        }
Esempio n. 18
0
        private static IList <string> ProcessArgumentsExpression(IArgumentsOwner argumentsOwner, MvcKind kind)
        {
#if SDK80
            IDeclaredType stringType = TypeFactory.CreateTypeByCLRName(PredefinedType.STRING_FQN, argumentsOwner.GetPsiModule(), argumentsOwner.GetResolveContext());
#else
            IDeclaredType stringType = TypeFactory.CreateTypeByCLRName(PredefinedType.STRING_FQN, argumentsOwner.GetPsiModule());
#endif

            var enumerabe1 = from expression in RetrieveArgumentExpressions(argumentsOwner, kind)
                             let finder = new RecursiveElementCollector <IExpression>(
                literalExpression =>
            {
                if (!literalExpression.GetExpressionType().IsImplicitlyConvertibleTo(
                        stringType, IntentionLanguageSpecific.GetTypeConversion(literalExpression)))
                {
                    return(false);
                }

                string initializerName;
                IInvocationInfo invocationInfo;
                GetMvcLiteral(literalExpression, out invocationInfo, out initializerName);
                return((invocationInfo == argumentsOwner) &&
                       expression.Second.Any(_ => StringComparer.OrdinalIgnoreCase.Equals(_.B, initializerName)));
            })
                                          select new { finder, expression };
            return((from x in enumerabe1
                    from literal in x.finder.ProcessElement(x.expression.First).GetResults()
                    select literal.ConstantValue.Value as string).ToList());
        }
        /// <summary>Creates a variable declaration for catch clause.</summary>
        /// <param name="exceptionType">The type of a created variable.</param>
        /// <param name="context">The context. </param>
        public ICatchVariableDeclaration CreateCatchVariableDeclarationNode(IDeclaredType exceptionType, ITreeNode context)
        {
            var tryStatement = _factory.CreateStatement("try {} catch(Exception e) {}") as ITryStatement;
            if (tryStatement == null)
                return null;

            var catchClause = tryStatement.Catches[0] as ISpecificCatchClause;
            if (catchClause == null)
                return null;

            var exceptionDeclaration = catchClause.ExceptionDeclaration;
            if (exceptionDeclaration == null)
                return null;

            if (exceptionType != null)
            {
            #if R8
                var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType);
            #else
                var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType, context);
            #endif
                exceptionDeclaration.SetDeclaredTypeUsage(declaredTypeUsageNode);
            }

            return exceptionDeclaration;
        }
Esempio n. 20
0
        private IDeclaredType GetExceptionType()
        {
            if (_exceptionTypeLoaded)
            {
                return(_exceptionType);
            }

            try
            {
#if R10
                _exceptionType = TypeFactory.CreateTypeByCLRName(ExceptionType, ServiceLocator.StageProcess.PsiModule);
#else
                _exceptionType = TypeFactory.CreateTypeByCLRName(ExceptionType, ServiceLocator.StageProcess.PsiModule, ServiceLocator.StageProcess.PsiModule.GetContextFromModule());
#endif
            }
            catch (Exception ex)
            {
                Logger.LogException(string.Format("[Exceptional] Error loading excluded method exception '{0}'", ExceptionType), ex);
            }
            finally
            {
                _exceptionTypeLoaded = true;
            }
            return(_exceptionType);
        }
Esempio n. 21
0
        private static bool IsInstantiableExceptionType([NotNull] IDeclaredType declaredType, [NotNull] ICSharpExpression context)
        {
            var predefinedType = context.GetPredefinedType();
            var conversionRule = context.GetTypeConversionRule();

            return(conversionRule.IsImplicitlyConvertibleTo(declaredType, predefinedType.Exception) &&
                   TypeUtils.CanInstantiateType(declaredType, context) != CanInstantiate.No);
        }
        /// <summary>Adds a catch clause to the try statement. </summary>
        /// <param name="exceptionType">The exception type in the added catch clause. </param>
        public void AddCatchClause(IDeclaredType exceptionType)
        {
            var codeElementFactory = new CodeElementFactory(GetElementFactory());
            var variableName       = NameFactory.CatchVariableName(Node, exceptionType);
            var catchClauseNode    = codeElementFactory.CreateSpecificCatchClause(exceptionType, null, variableName);

            Node.AddCatchClause(catchClauseNode);
        }
Esempio n. 23
0
 IMembers IMembers.GetPartialClone(IDeclaredType parent)
 {
     if (!(parent is TParent))
     {
         throw new ArgumentException("must be of type TParent", "parent");
     }
     return((IMembers)this.OnGetPartialClone((TParent)parent));
 }
        public ContractResultPredicateArgument(IDeclaredType resultTypeName, 
            IReferenceExpression contractResultReference)
        {
            Contract.Requires(resultTypeName != null);
            Contract.Requires(contractResultReference != null);

            _resultTypeName = resultTypeName;
            _contractResultReference = contractResultReference;
        }
        /// <summary>Checks whether the block catches the given exception. </summary>
        /// <param name="exception">The exception. </param>
        /// <returns><c>true</c> if the exception is caught in the block; otherwise, <c>false</c>. </returns>
        public override bool CatchesException(IDeclaredType exception)
        {
            if (CatchClauses.Any(catchClauseModel => catchClauseModel.Catches(exception)))
            {
                return(true);
            }

            return(ParentBlock.CatchesException(exception));
        }
Esempio n. 26
0
        public ContractResultPredicateArgument(IDeclaredType resultTypeName,
                                               IReferenceExpression contractResultReference)
        {
            Contract.Requires(resultTypeName != null);
            Contract.Requires(contractResultReference != null);

            _resultTypeName          = resultTypeName;
            _contractResultReference = contractResultReference;
        }
Esempio n. 27
0
        public void HandleGetSize(TypeHandlingContext context)
        {
            IDeclaredType valueType = context.Type.GetScalarType();

            if (valueType == null)
            {
                throw new NotSupportedException();
            }

            ITypeHandler valueHandler = TypeHandlers.All.SingleOrDefault(h => h.CanHandle(context.WithType(valueType)));

            if (valueHandler == null)
            {
                throw new NotSupportedException();
            }

            var exists = context.Variables.Declare(VariableKeys.NotNull);

            context.Builder.AppendFormat("var {0} = {1} != null;", exists, context.TypeOwnerName);
            TypeHandlers.Boolean.HandleGetSize(new TypeHandlingContext(context)
            {
                TypeOwnerName = exists
            });

            context.Builder.AppendFormat("if({0})", exists).Append("{");
            TypeHandlers.Int32.HandleGetSize(new TypeHandlingContext(context)
            {
                TypeOwnerName = String.Format("{0}.Length", context.TypeOwnerName)
            });
            context.Builder.AppendFormat("if({0}.Length > 0)", context.TypeOwnerName);
            context.Builder.Append("{");
            if (valueHandler.BinarySizePersistent)
            {
                var size = context.Variables.Declare(VariableKeys.ValueSize);

                context.Builder.AppendFormat("var {0} = 0;", size);

                valueHandler.HandleGetSize(new TypeHandlingContext(context)
                {
                    SizeVariableKey = VariableKeys.ValueSize
                });

                context.Builder.AppendFormat("{0} += {1}*{2}.Length;", context.GetSizeVariableName(), size, context.TypeOwnerName);
            }
            else
            {
                var indexName = context.Variables.Declare(Index);
                context.Builder.AppendFormat("for(Int32 {0} = 0; {0} < {1}.Length; {0}++)", indexName, context.TypeOwnerName);
                context.Builder.Append("{");
                valueHandler.HandleGetSize(new TypeHandlingContext(context)
                {
                    TypeOwnerName = String.Format("{0}[{1}]", context.TypeOwnerName, indexName)
                });
                context.Builder.Append("}");
            }
            context.Builder.Append("}}");
        }
        private static bool AddEnumerationMembers([NotNull] CSharpCodeCompletionContext context,
                                                  [NotNull] GroupedItemsCollector collector,
                                                  [NotNull] IDeclaredType qualifierType,
                                                  [NotNull] IReferenceExpression referenceExpression)
        {
            var enumerationType = (IEnum)qualifierType.GetTypeElement().NotNull();
            var substitution    = qualifierType.GetSubstitution();
            var memberValues    = new List <Pair <IField, string> >();

            var isFlagsEnum = enumerationType.HasAttributeInstance(FlagsAttributeClrName, false);

            if (!isFlagsEnum)
            {
                foreach (var member in enumerationType.EnumMembers)
                {
                    var formattable = member.ConstantValue.Value as IFormattable;
                    var memberValue = (formattable != null)
            ? formattable.ToString("D", CultureInfo.InvariantCulture) : string.Empty;
                    memberValues.Add(Pair.Of(member, memberValue));
                }
            }
            else
            {
                foreach (var member in enumerationType.EnumMembers)
                {
                    var convertible = member.ConstantValue.Value as IConvertible;
                    var memberValue = (convertible != null)
            ? GetBinaryRepresentation(convertible) : string.Empty;
                    memberValues.Add(Pair.Of(member, memberValue));
                }
            }

            if (memberValues.Count == 0)
            {
                return(false);
            }

            // create pointer to . in reference expression
            var maxLength        = memberValues.Max(x => x.Second.Length);
            var reparsedDotRange = referenceExpression.Delimiter.GetTreeTextRange();
            var originalDotRange = context.UnterminatedContext.ToOriginalTreeRange(reparsedDotRange);
            var file             = context.BasicContext.File;
            var dotMarker        = file.GetDocumentRange(originalDotRange).CreateRangeMarker();

            foreach (var member in memberValues)
            {
                var normalizedValue = member.Second.PadLeft(maxLength, '0');
                var value           = isFlagsEnum ? normalizedValue : member.Second;

                var instance       = new DeclaredElementInstance <IField>(member.First, substitution);
                var textLookupItem = new EnumMemberLookupItem(dotMarker, instance, normalizedValue, value, isFlagsEnum);

                collector.AddSomewhere(textLookupItem);
            }

            return(true);
        }
        protected override void Run(IClassDeclaration classDeclaration, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            if (!myIsEnabled.Value)
            {
                return;
            }

            var typeElement = classDeclaration.DeclaredElement;

            if (typeElement == null || !ZoneConstants.IsZoneClass(typeElement))
            {
                return;
            }

            var mark    = myMarks.GetMark(typeElement.GetContainingNamespace());
            var classes = myMarks.EnumerateClasses(mark).ToList();

            // find all base zones
            var baseZones = new HashSet <IClass>();

            foreach (var cls in classes)
            {
                foreach (var baseZone in MarksService.EnumerableMarkClasses(cls, true))
                {
                    if (!baseZone.Equals(cls))
                    {
                        baseZones.Add(baseZone);
                    }
                }
            }

            foreach (var typeUsage in classDeclaration.SuperTypeUsageNodes.OfType <IUserDeclaredTypeUsage>())
            {
                IDeclaredType superType        = CSharpTypeFactory.CreateDeclaredType(typeUsage);
                var           superTypeElement = superType.GetTypeElement();
                if (superTypeElement != null)
                {
                    if (ZoneConstants.IsIRequire(superTypeElement as IInterface))
                    {
                        var substitution = superType.GetSubstitution();
                        foreach (var parameter in substitution.Domain)
                        {
                            var zoneType = substitution[parameter] as IDeclaredType;
                            if (zoneType != null)
                            {
                                var zoneClass = zoneType.GetTypeElement() as IClass;
                                if (zoneClass != null && baseZones.Contains(zoneClass))
                                {
                                    consumer.AddHighlighting(new RedundantDependencySpecificationError(typeUsage), classDeclaration.GetContainingNode <IFile>());
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        private bool IsAvailableInternal(IDataContext context, out IParameter systemTypeParameter, out IMethod method)
        {
            systemTypeParameter = null;
            method = null;

            var declaredElements = context.GetData(Psi.Services.DataConstants.DECLARED_ELEMENTS);

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

            method = declaredElements.OfType <IMethod>().FirstOrDefault();
            if (method == null)
            {
                return(false);
            }

            if (method is ICompiledElement)
            {
                return(false);
            }

            IList <IDeclaration> declarations = method.GetDeclarations();

            if (declarations.Count == 0)
            {
                return(false);
            }

            IList <IParameter> parameters = method.Parameters;

            if (parameters.Count == 0)
            {
                return(false);
            }

            IPsiModule module = method.Module;

            IDeclaredType systemType = TypeFactory.CreateTypeByCLRName("System.Type", module);

            foreach (IParameter parameter in parameters)
            {
                if (parameter.Type.Equals(systemType))
                {
                    systemTypeParameter = parameter;
                }
            }

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

            return(true);
        }
        public ChangeToAsyncTaskFix([NotNull] AvoidAsyncVoidHighlighting highlighting)
        {
            this.highlighting = highlighting;

            var psiModule = highlighting.MethodDeclaration.GetPsiModule();

            var predefinedType = psiModule.GetPredefinedType();

            taskType = predefinedType.Task;
        }
Esempio n. 32
0
        public ChangeToAsyncTaskFix([NotNull] AvoidAsyncVoidHighlighting highlighting)
        {
            this.highlighting = highlighting;

            var psiModule = highlighting.Declaration.GetPsiModule();

            var predefinedType = psiModule.GetPredefinedType();

            taskType = predefinedType.Task;
        }
            public VarByTypeItem([NotNull] PrefixExpressionContext context, [NotNull] IDeclaredType referencedType)
                : base("var", context)
            {
                myReferencedType   = referencedType;
                myLookupItemsOwner = context.PostfixContext.ExecutionContext.LookupItemsOwner;

                var canInstantiate = TypeUtils.CanInstantiateType(referencedType, context.Expression);

                myHasRequiredArguments = (canInstantiate & CanInstantiate.ConstructorWithParameters) != 0;
            }
Esempio n. 34
0
        static bool IsValidFieldOfType(this IDeclaredElement element, Type type)
        {
            IDeclaredType fieldType = element.GetValidatedFieldType();

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

            return(new CLRTypeName(fieldType.GetCLRName()) == new CLRTypeName(type.FullName));
        }
Esempio n. 35
0
        protected virtual bool ResultIsAlreadyCheckedByContractEnsures(
            IEnumerable <ContractEnsures> ensureAssertions, IDeclaredType methodReturnType)
        {
            Contract.Requires(ensureAssertions != null);
            Contract.Requires(methodReturnType != null);

            return(ensureAssertions
                   .Any(e => e.ChecksForNotNull(
                            pa => pa.With(x => x as ContractResultPredicateArgument)
                            .With(x => x.ResultTypeName.FullName) == methodReturnType.GetClrName().FullName)));
        }
        public ThrownExceptionModel(IAnalyzeUnit analyzeUnit, IExceptionsOriginModel exceptionsOrigin,
            IDeclaredType exceptionType, string exceptionDescription, bool isEventInvocationException, string exceptionAccessor)
            : base(analyzeUnit)
        {
            ExceptionType = exceptionType;
            ExceptionDescription = exceptionDescription;
            ExceptionsOrigin = exceptionsOrigin;
            ExceptionAccessor = exceptionAccessor;

            IsEventInvocationException = isEventInvocationException;

            CheckAccessorOverride(exceptionsOrigin, exceptionType);
        }
Esempio n. 37
0
        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);
            }
        }
        public override bool IsAvailable(IUserDataHolder cache)
        {
            using (ReadLockCookie.Create())
            {
                if (Provider.SelectedElement != null)
                {
                    _superType = TypeHelper.CreateTypeByCLRName(SuperTypeName, Provider.PsiModule, Provider.SelectedElement.GetResolveContext());
                    if (_superType.GetTypeElement() != null)
                    {
                        _classDeclaration = Provider.SelectedElement.Parent as IClassDeclaration;
                    }
                }
            }

            // !_classDeclaration.IsStatic doesn't work, IsStatic is returns true
            return _classDeclaration != null && !_classDeclaration.IsStaticEx() && _classDeclaration.SuperTypes.IsEmpty();
        }
        // 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));
        }
        private IDeclaredType GetExceptionType()
        {
            if (_exceptionTypeLoaded)
                return _exceptionType;

            try
            {
            #if R10
                _exceptionType = TypeFactory.CreateTypeByCLRName(ExceptionType, ServiceLocator.StageProcess.PsiModule);
            #else
                _exceptionType = TypeFactory.CreateTypeByCLRName(ExceptionType, ServiceLocator.StageProcess.PsiModule, ServiceLocator.StageProcess.PsiModule.GetContextFromModule());
            #endif
            }
            catch (Exception ex)
            {
                Logger.LogException(string.Format("[Exceptional] Error loading excluded method exception '{0}'", ExceptionType), ex);
            }
            finally
            {
                _exceptionTypeLoaded = true;
            }
            return _exceptionType;
        }
        public static string CatchVariableName(ITreeNode treeNode, IDeclaredType exceptionType)
        {
            var namingPolicyManager = new NamingPolicyManager(LanguageManager.Instance, treeNode.GetSolution());
            var nameParser = new NameParser(treeNode.GetSolution(), namingPolicyManager);
            var nameSuggestionManager = new NameSuggestionManager(treeNode.GetSolution(), nameParser, namingPolicyManager);
            var policy = namingPolicyManager.GetPolicy(NamedElementKinds.Locals, treeNode.Language, treeNode.GetSourceFile());

            var namesCollection = nameSuggestionManager.CreateEmptyCollection(
                PluralityKinds.Single, treeNode.Language, true, treeNode.GetSourceFile());

            var entryOptions = new EntryOptions
            {
                PluralityKind = PluralityKinds.Single,
                PredefinedPrefixPolicy = PredefinedPrefixPolicy.Preserve,
                Emphasis = Emphasis.Good,
                SubrootPolicy = SubrootPolicy.Decompose
            };

            namesCollection.Add(exceptionType, entryOptions);
            namesCollection.Prepare(policy.NamingRule, ScopeKind.Common, new SuggestionOptions());

            return namesCollection.FirstName();
        }
        public bool IsException(IDeclaredType exceptionType)
        {
            if (ExceptionType == null)
                return false;

            if (exceptionType == null)
                return false;

            return ExceptionType.Equals(exceptionType);
        }
        /// <summary>Creates a try statement for the given exception type and variable name. </summary>
        /// <param name="exceptionType">The exception type. </param>
        /// <param name="exceptionVariableName">The exception variable name. </param>
        /// <param name="context">The context. </param>
        /// <returns>The try statement. </returns>
        public ITryStatement CreateTryStatement(IDeclaredType exceptionType, string exceptionVariableName, ITreeNode context)
        {
            var tryStatement = _factory.CreateStatement("try {} catch($0 $1) {}",
                exceptionType.GetClrName().ShortName, exceptionVariableName) as ITryStatement;
            if (tryStatement == null)
                return null;

            var catchClause = tryStatement.Catches[0] as ISpecificCatchClause;
            if (catchClause == null)
                return tryStatement;

            var exceptionDeclaration = catchClause.ExceptionDeclaration;
            if (exceptionDeclaration == null)
                return tryStatement;

            #if R8
            var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType);
            #else
            var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType, context);
            #endif

            exceptionDeclaration.SetDeclaredTypeUsage(declaredTypeUsageNode);

            return tryStatement;
        }
 internal GenericExceptionNameBuilder(IDeclaredType exceptionType)
 {
     _exceptionType = exceptionType;
 }
 private void CheckAccessorOverride(IExceptionsOriginModel exceptionsOrigin, IDeclaredType exceptionType)
 {
     var doc = GetXmlDocId(exceptionsOrigin.Node);
     if (doc != null)
     {
         var fullMethodName = Regex.Replace(doc.Substring(2), "(`[0-9]+)|(\\(.*?\\))", ""); // TODO: merge with other
         var overrides = ServiceLocator.Settings.GetExceptionAccessorOverrides();
         var ov =
             overrides.SingleOrDefault(
                 o => o.FullMethodName == fullMethodName && o.GetExceptionType().Equals(exceptionType));
         if (ov != null)
             ExceptionAccessor = ov.ExceptionAccessor;
     }
 }
 public OptionalExceptionConfiguration(IDeclaredType exceptionType, OptionalExceptionReplacementType replacementType)
 {
     ExceptionType = exceptionType;
     ReplacementType = replacementType;
 }
Esempio n. 47
0
 internal static bool IsAssignableFrom(this Type type, IDeclaredType c)
 {
     return type.FullName == c.GetClrName().FullName || c.GetAllSuperTypes().Any(superType => type.FullName == superType.GetClrName().FullName);
 }
Esempio n. 48
0
 public bool IsImplementingType(IDeclaredType type, Type implementedType)
 {
     return GetImplementedTypes(type).Any(x => x.GetClrName().FullName == implementedType.FullName);
 }
Esempio n. 49
0
        private bool IsNinjectBindCall(ITreeNode element)
        {
            var invocationExpression = element as IInvocationExpression;
            if (invocationExpression == null)
            {
                return false;
            }

            var resolve = invocationExpression.InvocationExpressionReference.Resolve().Result;
            var method = resolve.DeclaredElement as IMethod;
            if (method == null)
            {
                return false;
            }
            ITypeElement containingType = method.GetContainingType();
            if (containingType == null)
            {
                return false;
            }

            if (bindingRootType == null)
            {
                bindingRootType = TypeFactory.CreateTypeByCLRName("Ninject.Syntax.IBindingRoot", element.GetPsiModule());
            }

            return containingType.IsDescendantOf(bindingRootType.GetTypeElement());
        }
 protected override bool ResultIsAlreadyCheckedByContractEnsures(IEnumerable<ContractEnsures> ensureAssertions, IDeclaredType methodReturnType)
 {
     // Ensures for enums should be available for System.Enum and for System.Enum?
     // thats why we should extract underlying type out of the nullable type.
     var returnType = methodReturnType.IsNullable() ? methodReturnType.GetNullableUnderlyingType() : methodReturnType;
     return ensureAssertions
         .Any(e => e.ChecksForNotNull(
             pa => pa.With(x => x as ContractResultPredicateArgument)
                 .With(x => x.ResultTypeName.FullName) == returnType.GetClrTypeName().FullName));
 }
        private StaticTypeWrapper MakeType(IDeclaredType typeHandle)
        {
            ITypeParameter typeParameterHandle = typeHandle.GetTypeElement() as ITypeParameter;
            if (typeParameterHandle != null)
                return MakeGenericParameterType(typeParameterHandle);

            return MakeDeclaredType(typeHandle);
        }
 internal static bool IsAssignableFrom(this Type type, IDeclaredType c)
 {
     return type.FullName == c.GetCLRName() || TypeElementUtil.GetAllSuperTypes(c).Any(superType => type.FullName == superType.GetCLRName());
 }
        private void ProcessSuperType(XunitTestClassElement classElement, IDeclaredType type)
        {
            var @class = type.GetTypeElement() as IClass;
            if (@class == null)
                return;

            foreach (IMethod method in @class.GetMembers().Where(UnitTestElementPsiIdentifier.IsUnitTest))
                GetOrCreateMethodElement(classElement, @class, method);
        }
        private StaticDeclaredTypeWrapper MakeDeclaredType(IDeclaredType typeHandle)
        {
            return declaredTypeMemoizer.Memoize(typeHandle, () =>
            {
                ITypeElement typeElement = typeHandle.GetTypeElement();
                if (typeElement == null)
                    throw new ReflectionResolveException(
                        String.Format(
                            "Cannot obtain type element for type '{0}' possibly because its source code is not available.",
                            typeHandle.GetCLRName()));

                return MakeDeclaredType(typeElement, typeHandle.GetSubstitution());
            });
        }
        protected virtual bool ResultIsAlreadyCheckedByContractEnsures(
            IEnumerable<ContractEnsures> ensureAssertions, IDeclaredType methodReturnType)
        {
            Contract.Requires(ensureAssertions != null);
            Contract.Requires(methodReturnType != null);

            return ensureAssertions
                .Any(e => e.ChecksForNotNull(
                    pa => pa.With(x => x as ContractResultPredicateArgument)
                        .With(x => x.ResultTypeName.FullName) == methodReturnType.GetClrName().FullName));
        }