public static IMethodSymbol GetExplictCoversionOp(this ITypeSymbol type, ITypeSymbol returnTypeSymbol,
            ITypeSymbol originalTypeSymbol, bool allowNarrowing = false)
        {
            if (!returnTypeSymbol.IsPrimitiveInteger())
                allowNarrowing = false;

            if (!allowNarrowing)
            {
                return
                    type.GetMembers("op_Explicit")
                        .OfType<IMethodSymbol>()
                        .FirstOrDefault(
                    h =>
                                returnTypeSymbol.IsAssignableFrom(h.ReturnType) &&
                    h.Parameters[0].Type.IsAssignableFrom(originalTypeSymbol));
            }
            IMethodSymbol bestMatch = null;
            int lastSizeDiff = 1000;
            foreach (var member in type.GetMembers("op_Explicit")
                .OfType<IMethodSymbol>().Where(h =>
                    h.Parameters[0].Type.IsAssignableFrom(originalTypeSymbol)))
            {
                var sizediff = member.ReturnType.SizeOf() - returnTypeSymbol.SizeOf();
                if (sizediff <= lastSizeDiff)
                {
                    lastSizeDiff = sizediff;
                    bestMatch = member;
                }
            }
            return bestMatch;
        }
        private SyntaxNode FixMethod(
            bool keepVoid, IMethodSymbol methodSymbol, MethodDeclarationSyntax method,
            ITypeSymbol taskType, INamedTypeSymbol taskOfTType)
        {
            var newReturnType = method.ReturnType;

            if (methodSymbol.ReturnsVoid)
            {
                if (!keepVoid)
                {
                    newReturnType = taskType.GenerateTypeSyntax();
                }
            }
            else
            {
                if (!IsTaskLike(methodSymbol.ReturnType, taskType, taskOfTType))
                {
                    // If it's not already Task-like, then wrap the existing return type
                    // in Task<>.
                    newReturnType = taskOfTType.Construct(methodSymbol.ReturnType).GenerateTypeSyntax();
                }
            }

            var newModifiers = method.Modifiers.Add(s_asyncToken);
            return method.WithReturnType(newReturnType).WithModifiers(newModifiers);
        }
		public EventCreationCompletionData (ICompletionDataKeyHandler keyHandler, RoslynCodeCompletionFactory factory, ITypeSymbol delegateType, string varName, INamedTypeSymbol curType) : base (factory, keyHandler)
		{
			this.DisplayText = varName;
			this.delegateType = delegateType;
			this.factory = factory;
			this.Icon = "md-newmethod";
		}
        private static async Task<Document> ChangeToImmutableArrayCreateRange(
            ObjectCreationExpressionSyntax objectCreation,
            InitializerExpressionSyntax initializer,
            INamedTypeSymbol immutableArrayType,
            ITypeSymbol elementType,
            Document document,
            CancellationToken cancellationToken)
        {
            var generator = SyntaxGenerator.GetGenerator(document);

            var arrayElementType = (TypeSyntax)generator.TypeExpression(elementType);
            var arrayType = SyntaxFactory.ArrayType(arrayElementType, 
                SyntaxFactory.SingletonList(
                    SyntaxFactory.ArrayRankSpecifier(
                        SyntaxFactory.SingletonSeparatedList(
                            (ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression()))));

            var arrayCreationExpression = SyntaxFactory.ArrayCreationExpression(
                type: arrayType,
                initializer: SyntaxFactory.InitializerExpression(
                    kind: SyntaxKind.ArrayInitializerExpression,
                    expressions: initializer.Expressions))
                .WithAdditionalAnnotations(Formatter.Annotation);
            
            var type = generator.TypeExpression(immutableArrayType);
            var memberAccess = generator.MemberAccessExpression(type, "CreateRange");
            var invocation = generator.InvocationExpression(memberAccess, arrayCreationExpression);

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = oldRoot.ReplaceNode(objectCreation, invocation);

            return document.WithSyntaxRoot(newRoot);
        }
Example #5
0
		private static IEnumerable<string> GetContainingTypeName(ITypeSymbol symbol)
		{
			for (var typeSymbol = symbol; typeSymbol != null; typeSymbol = typeSymbol.ContainingSymbol as ITypeSymbol)
			{
				yield return typeSymbol.Name;
			}
		}
            public AnalyzerResult(
                SemanticDocument document,
                IEnumerable<ITypeParameterSymbol> typeParametersInDeclaration,
                IEnumerable<ITypeParameterSymbol> typeParametersInConstraintList,
                IList<VariableInfo> variables,
                VariableInfo variableToUseAsReturnValue,
                ITypeSymbol returnType,
                bool awaitTaskReturn,
                bool instanceMemberIsUsed,
                bool endOfSelectionReachable,
                OperationStatus status)
            {
                var semanticModel = document.SemanticModel;

                this.UseInstanceMember = instanceMemberIsUsed;
                this.EndOfSelectionReachable = endOfSelectionReachable;
                this.AwaitTaskReturn = awaitTaskReturn;
                this.SemanticDocument = document;
                _typeParametersInDeclaration = typeParametersInDeclaration.Select(s => semanticModel.ResolveType(s)).ToList();
                _typeParametersInConstraintList = typeParametersInConstraintList.Select(s => semanticModel.ResolveType(s)).ToList();
                _variables = variables;
                this.ReturnType = semanticModel.ResolveType(returnType);
                _variableToUseAsReturnValue = variableToUseAsReturnValue;
                this.Status = status;
            }
 /// <summary>
 /// Is this a method on <see cref="Enumerable" /> which takes only a single parameter?
 /// </summary>
 /// <remarks>
 /// Many of the methods we target, like Last, have overloads that take a filter delegate.  It is 
 /// completely appropriate to use such methods even with <see cref="IReadOnlyList{T}" />.  Only the single parameter
 /// ones are suspect
 /// </remarks>
 private static bool IsSingleParameterLinqMethod(IMethodSymbol methodSymbol, ITypeSymbol enumerableType)
 {
     Debug.Assert(methodSymbol.ReducedFrom == null);
     return
         methodSymbol.ContainingSymbol.Equals(enumerableType) &&
         methodSymbol.Parameters.Length == 1;
 }
Example #8
0
        /// <summary>
        /// Analyzes if type information is obvious to the reader by simply looking at the assignment expression.
        /// </summary>
        /// <remarks>
        /// <paramref name="typeInDeclaration"/> accepts null, to be able to cater to codegen features
        /// that are about to generate a local declaration and do not have this information to pass in.
        /// Things (like analyzers) that do have a local declaration already, should pass this in.
        /// </remarks>
        public static bool IsTypeApparentInAssignmentExpression(
            TypeStylePreference stylePreferences,
            ExpressionSyntax initializerExpression,
            SemanticModel semanticModel,
            CancellationToken cancellationToken,
            ITypeSymbol typeInDeclaration = null)
        {
            // default(type)
            if (initializerExpression.IsKind(SyntaxKind.DefaultExpression))
            {
                return true;
            }

            // literals, use var if options allow usage here.
            if (initializerExpression.IsAnyLiteralExpression())
            {
                return stylePreferences.HasFlag(TypeStylePreference.ImplicitTypeForIntrinsicTypes);
            }

            // constructor invocations cases:
            //      = new type();
            if (initializerExpression.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializerExpression.IsKind(SyntaxKind.AnonymousObjectCreationExpression))
            {
                return true;
            }

            // explicit conversion cases: 
            //      (type)expr, expr is type, expr as type
            if (initializerExpression.IsKind(SyntaxKind.CastExpression) ||
                initializerExpression.IsKind(SyntaxKind.IsExpression) ||
                initializerExpression.IsKind(SyntaxKind.AsExpression))
            {
                return true;
            }

            // other Conversion cases:
            //      a. conversion with helpers like: int.Parse methods
            //      b. types that implement IConvertible and then invoking .ToType()
            //      c. System.Convert.Totype()
            var memberName = GetRightmostInvocationExpression(initializerExpression).GetRightmostName();
            if (memberName == null)
            {
                return false;
            }

            var methodSymbol = semanticModel.GetSymbolInfo(memberName, cancellationToken).Symbol as IMethodSymbol;
            if (methodSymbol == null)
            {
                return false;
            }

            if (memberName.IsRightSideOfDot())
            {
                var containingTypeName = memberName.GetLeftSideOfDot();
                return IsPossibleCreationOrConversionMethod(methodSymbol, typeInDeclaration, semanticModel, containingTypeName, cancellationToken);
            }

            return false;
        }
		public CreatePartialCompletionData (ICompletionDataKeyHandler keyHandler, RoslynCodeCompletionFactory factory, int declarationBegin, ITypeSymbol currentType, ISymbol member, bool afterKeyword) : base (keyHandler, factory, member)
		{
			this.afterKeyword = afterKeyword;
			this.currentType = currentType;
			this.declarationBegin = declarationBegin;
			this.GenerateBody = true;
		}
        public static string ConvertPInvokeType(ITypeSymbol returnType, PInvokeMode mode = PInvokeMode.None)
        {
            var dType = TypeProcessor.ConvertType(returnType);

            if (returnType.TypeKind == TypeKind.Delegate)
            {
                return GetDelegateRawType(dType);

//				var dlg =returnType.OriginalDefinition as IMethodSymbol;
//				if (dlg.Parameters.Length == 0)
////					return "() => " + TryConvertType (dlg.ReturnType);
////				else
////					return "(" + string.Join (", ", dlg.Parameters.ToList ().Select (o => TryConvertType (o.Type))) + ") => " + TryConvertType (dlg.ReturnType);
//
//			
//
//				return TypeProcessor.ConvertType (dlg.ReturnType) + " delegate" +
//						dlg.Parameters.ToList ().Select (o => ConvertPInvokeType (o.Type)) + ")";

//				return dType.RemoveFromStartOfString("Delegate!(").SubstringBeforeLast(')');
            }

            //TODO this should become a class with different options like CharSet etc ..
            switch (dType)
            {
                case "String":
                    return "char *"; //TODO: Should be dependent on the charset
                case "Array_T!(String)":
                    return "char**";
            }
            return dType;
        }
		private static string ResolveTypeName(ITypeSymbol symbol)
		{
			INamedTypeSymbol symbol3;
			var builder = new StringBuilder();
			var flag = false;
			var symbol2 = symbol as IArrayTypeSymbol;
			if (symbol2 != null)
			{
				flag = true;
				symbol = symbol2.ElementType;
			}

			builder.Append(symbol.Name);
			if (((symbol3 = symbol as INamedTypeSymbol) != null) && symbol3.TypeArguments.Any())
			{
				IEnumerable<string> values = (from x in symbol3.TypeArguments.AsEnumerable() select ResolveTypeName(x)).ToArray<string>();
				builder.AppendFormat("<{0}>", string.Join(", ", values));
			}

			if (flag)
			{
				builder.Append("[]");
			}

			return builder.ToString();
		}
Example #12
0
        private static bool TryGetAllEnumMembers(
            ITypeSymbol enumType,
            Dictionary<long, ISymbol> enumValues)
        {
            foreach (var member in enumType.GetMembers())
            {
                // skip `.ctor` and `__value`
                var fieldSymbol = member as IFieldSymbol;
                if (fieldSymbol == null || fieldSymbol.Type.SpecialType != SpecialType.None)
                {
                    continue;
                }

                if (fieldSymbol.ConstantValue == null)
                {
                    // We have an enum that has problems with it (i.e. non-const members).  We won't
                    // be able to determine properly if the switch is complete.  Assume it is so we
                    // don't offer to do anything.
                    return false;
                }

                // Multiple enum members may have the same value.  Only consider the first one
                // we run int.
                var enumValue = IntegerUtilities.ToInt64(fieldSymbol.ConstantValue);
                if (!enumValues.ContainsKey(enumValue))
                {
                    enumValues.Add(enumValue, fieldSymbol);
                }
            }

            return true;
        }
Example #13
0
 public Property(string name, ITypeSymbol type, bool hasGetter, bool hasSetter)
 {
     Name = name;
     Type = type;
     HasSetter = hasSetter;
     HasGetter = hasGetter;
 }
 protected override bool IsAssignableTo(Compilation compilation, ITypeSymbol fromSymbol, ITypeSymbol toSymbol)
 {
     return
         fromSymbol != null &&
         toSymbol != null &&
         ((CSharpCompilation)compilation).ClassifyConversion(fromSymbol, toSymbol).IsImplicit;
 }
 private bool TypeHasWeakIdentity(ITypeSymbol type, SemanticModel model)
 {
     switch (type.TypeKind)
     {
         case TypeKind.ArrayType:
             var arrayType = type as IArrayTypeSymbol;
             return arrayType != null && arrayType.ElementType.IsPrimitiveType();
         case TypeKind.Class:
         case TypeKind.TypeParameter:
             Compilation compilation = model.Compilation;
             INamedTypeSymbol marshalByRefObjectTypeSymbol = compilation.GetTypeByMetadataName("System.MarshalByRefObject");
             INamedTypeSymbol executionEngineExceptionTypeSymbol = compilation.GetTypeByMetadataName("System.ExecutionEngineException");
             INamedTypeSymbol outOfMemoryExceptionTypeSymbol = compilation.GetTypeByMetadataName("System.OutOfMemoryException");
             INamedTypeSymbol stackOverflowExceptionTypeSymbol = compilation.GetTypeByMetadataName("System.StackOverflowException");
             INamedTypeSymbol memberInfoTypeSymbol = compilation.GetTypeByMetadataName("System.Reflection.MemberInfo");
             INamedTypeSymbol parameterInfoTypeSymbol = compilation.GetTypeByMetadataName("System.Reflection.ParameterInfo");
             INamedTypeSymbol threadTypeSymbol = compilation.GetTypeByMetadataName("System.Threading.Thread");
             return
                 type.SpecialType == SpecialType.System_String ||
                 type.Equals(executionEngineExceptionTypeSymbol) ||
                 type.Equals(outOfMemoryExceptionTypeSymbol) ||
                 type.Equals(stackOverflowExceptionTypeSymbol) ||
                 type.Inherits(marshalByRefObjectTypeSymbol) ||
                 type.Inherits(memberInfoTypeSymbol) ||
                 type.Inherits(parameterInfoTypeSymbol) ||
                 type.Inherits(threadTypeSymbol);
         
         // What about struct types?
         default:
             return false;
     }
 }
Example #16
0
        /// <summary>
        /// The Enumerable.Last method will only special case indexable types that implement <see cref="IList{T}" />.  Types 
        /// which implement only <see cref="IReadOnlyList{T}"/> will be treated the same as IEnumerable{T} and go through a 
        /// full enumeration.  This method identifies such types.
        /// 
        /// At this point it only identifies <see cref="IReadOnlyList{T}"/> directly but could easily be extended to support
        /// any type which has an index and count property.  
        /// </summary>
        private bool IsTypeWithInefficientLinqMethods(SyntaxNodeAnalysisContext context, ExpressionSyntax targetSyntax, ITypeSymbol readonlyListType, ITypeSymbol listType)
        {
            var targetTypeInfo = context.SemanticModel.GetTypeInfo(targetSyntax);
            if (targetTypeInfo.Type == null)
            {
                return false;
            }

            var targetType = targetTypeInfo.Type;

            // If this type is simply IReadOnlyList<T> then no further checking is needed.  
            if (targetType.TypeKind == TypeKind.Interface && targetType.OriginalDefinition.Equals(readonlyListType))
            {
                return true;
            }

            bool implementsReadOnlyList = false;
            bool implementsList = false;
            foreach (var current in targetType.AllInterfaces)
            {
                if (current.OriginalDefinition.Equals(readonlyListType))
                {
                    implementsReadOnlyList = true;
                }

                if (current.OriginalDefinition.Equals(listType))
                {
                    implementsList = true;
                }
            }

            return implementsReadOnlyList && !implementsList;
        }
 internal static IPropertySymbol CreatePropertySymbol(
     INamedTypeSymbol containingType,
     IList<AttributeData> attributes,
     Accessibility accessibility,
     DeclarationModifiers modifiers,
     ITypeSymbol type,
     IPropertySymbol explicitInterfaceSymbol,
     string name,
     IList<IParameterSymbol> parameters,
     IMethodSymbol getMethod,
     IMethodSymbol setMethod,
     bool isIndexer = false,
     SyntaxNode initializer = null)
 {
     var result = new CodeGenerationPropertySymbol(
         containingType,
         attributes,
         accessibility,
         modifiers,
         type,
         explicitInterfaceSymbol,
         name,
         isIndexer,
         parameters,
         getMethod,
         setMethod);
     CodeGenerationPropertyInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, initializer);
     return result;
 }
Example #18
0
        /// <summary>
        /// Gets the reference to the declaration of the base or interface type as part of the symbol's declaration. 
        /// </summary>
        public static async Task<SyntaxNode> GetBaseOrInterfaceDeclarationReferenceAsync(
            this SymbolEditor editor,
            ISymbol symbol,
            ITypeSymbol baseOrInterfaceType,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (baseOrInterfaceType == null)
            {
                throw new ArgumentNullException(nameof(baseOrInterfaceType));
            }

            if (baseOrInterfaceType.TypeKind != TypeKind.Error)
            {
                baseOrInterfaceType = (ITypeSymbol)(await editor.GetCurrentSymbolAsync(baseOrInterfaceType, cancellationToken).ConfigureAwait(false));
            }

            // look for the base or interface declaration in all declarations of the symbol
            var currentDecls = await editor.GetCurrentDeclarationsAsync(symbol, cancellationToken).ConfigureAwait(false);

            foreach (var decl in currentDecls)
            {
                var doc = editor.OriginalSolution.GetDocument(decl.SyntaxTree);
                var model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                var gen = SyntaxGenerator.GetGenerator(doc);

                var typeRef = gen.GetBaseAndInterfaceTypes(decl).FirstOrDefault(r => model.GetTypeInfo(r, cancellationToken).Type.Equals(baseOrInterfaceType));
                if (typeRef != null)
                {
                    return typeRef;
                }
            }

            return null;
        }
 /// <summary>
 /// Checks if 'symbol' is accessible from within name type 'within', with an optional
 /// qualifier of type "throughTypeOpt".
 /// </summary>
 public static bool IsAccessibleWithin(
     this ISymbol symbol,
     INamedTypeSymbol within,
     ITypeSymbol throughTypeOpt = null)
 {
     return IsSymbolAccessible(symbol, within, throughTypeOpt, out var failedThroughTypeCheck);
 }
        private static bool IsDerivedTypeRecursive(ITypeSymbol derivedType, ITypeSymbol type)
        {
            if (derivedType == type) return true;
            if (derivedType.BaseType == null) return false;

            return IsDerivedTypeRecursive(derivedType.BaseType, type);
        }
 private async Task<Document> ReplaceVarWithExplicitType(Document document, SyntaxNode varNode, ITypeSymbol explicitTypeSymbol, CancellationToken cancellationToken)
 {
     DocumentEditor documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken);
     SyntaxNode explicitTypeNode = documentEditor.Generator.TypeExpression(explicitTypeSymbol).WithAdditionalAnnotations(Simplifier.Annotation);
     documentEditor.ReplaceNode(varNode, explicitTypeNode);
     return documentEditor.GetChangedDocument();
 }
        private static bool IsRequiredCastForReferenceEqualityComparison(ITypeSymbol outerType, CastExpressionSyntax castExpression, SemanticModel semanticModel, out ExpressionSyntax other)
        {
            if (outerType.SpecialType == SpecialType.System_Object)
            {
                var expression = castExpression.WalkUpParentheses();
                var parentNode = expression.Parent;
                if (parentNode.IsKind(SyntaxKind.EqualsExpression) || parentNode.IsKind(SyntaxKind.NotEqualsExpression))
                {
                    // Reference comparison.
                    var binaryExpression = (BinaryExpressionSyntax)parentNode;
                    other = binaryExpression.Left == expression ?
                        binaryExpression.Right :
                        binaryExpression.Left;

                    // Explicit cast not required if we are comparing with type parameter with a class constraint.
                    var otherType = semanticModel.GetTypeInfo(other).Type;
                    if (otherType != null && otherType.TypeKind != TypeKind.TypeParameter)
                    {
                        return !other.WalkDownParentheses().IsKind(SyntaxKind.CastExpression);
                    }
                }
            }

            other = null;
            return false;
        }
Example #23
0
        internal static string GetType(ITypeSymbol typeSymbol, IEnumerable<string> knownClassNames)
        {
            string typeName;

            var success = GetKnownTypeName(typeSymbol, out typeName);
            if (success) { return typeName; }

            if (IsCollection(typeSymbol))
            {
                return GetCollectionTypeName(typeSymbol, knownClassNames);
            }

            if (typeSymbol.Name == "Task")
            {
                var namedTypeSymbol = typeSymbol as INamedTypeSymbol;

                var typeArgument = namedTypeSymbol?.TypeArguments.FirstOrDefault();
                if (typeArgument != null)
                {
                    return GetType(typeArgument, knownClassNames);
                }

                return Constants.VoidType;
            }

            if (typeSymbol.Name.Equals("void", StringComparison.OrdinalIgnoreCase))
            {
                return Constants.VoidType;
            }

            return knownClassNames.Contains(typeSymbol.Name) ? typeSymbol.Name : Constants.AnyType;
        }
Example #24
0
 public IndexerProperty(
     ITypeSymbol type, 
     bool hasGetter, 
     bool hasSetter):
     base("Item",type,hasGetter, hasSetter)
 {
 }
		protected void FilterTypeSymbol(ITypeSymbol symbol)
		{
			switch (symbol.TypeKind)
			{
				case TypeKind.Class:
				case TypeKind.Delegate:
				case TypeKind.Enum:
				case TypeKind.Interface:
					{
						var qualifiedName = symbol.GetQualifiedName().ToString();
						if (!_types.ContainsKey(qualifiedName))
						{
							_types.Add(qualifiedName, symbol);
						}

						break;
					}

				case TypeKind.Dynamic:
				case TypeKind.Error:
				case TypeKind.TypeParameter:
					break;

				default:
					return;
			}
		}
        public static BinaryOperationKind DeriveAdditionKind(ITypeSymbol type)
        {
            switch (type.SpecialType)
            {
                case SpecialType.System_Int32:
                case SpecialType.System_Int64:
                case SpecialType.System_Int16:
                case SpecialType.System_SByte:
                    return BinaryOperationKind.IntegerAdd;
                case SpecialType.System_UInt32:
                case SpecialType.System_UInt64:
                case SpecialType.System_UInt16:
                case SpecialType.System_Byte:
                case SpecialType.System_Char:
                case SpecialType.System_Boolean:
                    return BinaryOperationKind.UnsignedAdd;
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                    return BinaryOperationKind.FloatingAdd;
                case SpecialType.System_Object:
                    return BinaryOperationKind.ObjectAdd;
            }

            if (type.TypeKind == TypeKind.Enum)
            {
                return Semantics.BinaryOperationKind.EnumAdd;
            }

            return Semantics.BinaryOperationKind.None;
        }
            public static IEnumerable<ITypeParameterSymbol> Collect(ITypeSymbol typeSymbol)
            {
                var collector = new TypeParameterCollector();
                typeSymbol.Accept(collector);

                return collector._typeParameters;
            }
Example #28
0
 private CodeTypeRef(CodeModelState state, object parent, ProjectId projectId, ITypeSymbol typeSymbol)
     : base(state)
 {
     _parentHandle = new ParentHandle<object>(parent);
     _projectId = projectId;
     _symbolId = typeSymbol.GetSymbolKey();
 }
 private static MemberDeclarationSyntax GenerateBackingField(ITypeSymbol typeSymbol, string backingFieldName, Workspace workspace)
 {
     var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
     SyntaxNode type = generator.TypeExpression(typeSymbol);
     FieldDeclarationSyntax fieldDecl = ParseMember($"private _field_Type_ {backingFieldName};") as FieldDeclarationSyntax;
     return fieldDecl.ReplaceNode(fieldDecl.Declaration.Type, type.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation)); 
 }
Example #30
0
		public List<IMethodSymbol> GetExtensionMethods(string name, ITypeSymbol type)
		{
			List<IMethodSymbol> methods;

			if (type == null)
			{
				throw new ArgumentNullException(nameof(type));
			}

			if (!extensionMethodsByName.TryGetValue(name, out methods))
			{
				return new List<IMethodSymbol>();
			}

			var retval = new List<KeyValuePair<IMethodSymbol, int>>();

			foreach (var method in methods)
			{
				var depth = method.Parameters[0].Type?.IsAssignableFrom(type, 0);

				if (depth > -1)
				{
					retval.Add(new KeyValuePair<IMethodSymbol, int>(method, depth.Value));
				}
			}

			return retval.OrderBy(c => c.Key.ContainingAssembly.Equals(this.compilation.Assembly) ? 0 : c.Value + 1).Select(c => c.Key).ToList();
		}
        private static async Task RenameMethodAccoringToTypeNameAsync(
            RefactoringContext context,
            MethodDeclarationSyntax methodDeclaration)
        {
            TypeSyntax returnType = methodDeclaration.ReturnType;

            if (returnType?.IsVoid() != false)
            {
                return;
            }

            SyntaxToken identifier = methodDeclaration.Identifier;

            if (!context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(identifier))
            {
                return;
            }

            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken);

            ITypeSymbol typeSymbol = GetType(returnType, semanticModel, context.CancellationToken);

            if (typeSymbol == null)
            {
                return;
            }

            string newName = NameGenerator.CreateName(typeSymbol);

            if (string.IsNullOrEmpty(newName))
            {
                return;
            }

            newName = "Get" + newName;

            if (methodSymbol.IsAsync)
            {
                newName += "Async";
            }

            string oldName = identifier.ValueText;

            if (string.Equals(oldName, newName, StringComparison.Ordinal))
            {
                return;
            }

            if (!await MemberNameGenerator.IsUniqueMemberNameAsync(
                    newName,
                    methodSymbol,
                    context.Solution,
                    cancellationToken: context.CancellationToken).ConfigureAwait(false))
            {
                return;
            }

            context.RegisterRefactoring(
                $"Rename '{oldName}' to '{newName}'",
                cancellationToken => Renamer.RenameSymbolAsync(context.Solution, methodSymbol, newName, default(OptionSet), cancellationToken),
                RefactoringIdentifiers.RenameMethodAccordingToTypeName);
        }
 protected override void SetAbstractValueForArrayElementInitializer(IArrayCreationOperation arrayCreation, ImmutableArray <AbstractIndex> indices, ITypeSymbol elementType, IOperation initializer, DisposeAbstractValue value)
 {
     // Escaping from array element assignment is handled in PointsTo analysis.
     // We do not need to do anything here.
 }
Example #33
0
        private static void AssertTypeInfo(SemanticModel model, TypeSyntax typeSyntax, ITypeSymbol expectedType)
        {
            TypeInfo typeInfo = model.GetTypeInfo(typeSyntax);

            Assert.Equal(expectedType, typeInfo.Type);
            Assert.Equal(expectedType, typeInfo.ConvertedType);
            Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax));
            Assert.True(model.GetConversion(typeSyntax).IsIdentity);
        }
Example #34
0
 public abstract bool TryDetermineReturnType(
     SyntaxToken startToken,
     SemanticModel semanticModel,
     CancellationToken cancellationToken,
     out ITypeSymbol returnType,
     out SyntaxToken nextToken);
Example #35
0
 public abstract ISet <ISymbol> FilterOverrides(ISet <ISymbol> members, ITypeSymbol returnType);
Example #36
0
 public static bool TypeIsString(ITypeSymbol type) =>
 type.Name == "String" && type.ContainingNamespace.Name == "System";
Example #37
0
 public static bool TypeIsNodePath(ITypeSymbol type) =>
 type.Name == "NodePath" && type.ContainingNamespace.Name == "Godot";
 public abstract void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName);
Example #39
0
 private static void CheckTypes(SyntaxNodeAnalysisContext context, ITypeSymbol oldType, ITypeSymbol newType, Location location = null)
 {
     if (newType.IsLite() && oldType.IsEntity())
     {
         context.ReportDiagnostic(Diagnostic.Create(RuleCastToLiteEntity1, location ?? context.Node.GetLocation()));
     }
     else if (newType.IsEntity() && oldType.IsLite())
     {
         context.ReportDiagnostic(Diagnostic.Create(RuleCastToEntityEntity, location ?? context.Node.GetLocation()));
     }
 }
Example #40
0
 public static bool HasOnlyBlittableFields(this ITypeSymbol type) => HasOnlyBlittableFields(type, ImmutableHashSet.Create <ITypeSymbol>(SymbolEqualityComparer.Default));
        protected override bool CanBeConvertedTo(ExpressionSyntax expression, ITypeSymbol type, SemanticModel semanticModel)
        {
            var conversion = semanticModel.ClassifyConversion(expression, type);

            return(conversion.Exists && (conversion.IsIdentity || conversion.IsImplicit));
        }
 public CompositeMethodNames AddComponent(ITypeSymbol symbol)
 {
     _symbols.Add(symbol);
     return(CompositeMethodNames.AppendDefault($"Member_{symbol}"));
 }
Example #43
0
 private TypeInfo(ITypeSymbol type, int startIndex)
 {
     this.Type       = type;
     this.StartIndex = startIndex;
 }
Example #44
0
    private static void CheckPattern(SyntaxNodeAnalysisContext context, ITypeSymbol oldType, PatternSyntax syntax)
    {
        switch (syntax)
        {
        case BinaryPatternSyntax bp:
            CheckPattern(context, oldType, bp.Left);
            CheckPattern(context, oldType, bp.Right);
            break;

        case ConstantPatternSyntax cp:
            CheckTypes(context, oldType, context.SemanticModel.GetTypeInfo(cp.Expression).Type);
            break;

        case DeclarationPatternSyntax dp:
            CheckTypes(context, oldType, context.SemanticModel.GetTypeInfo(dp.Type).Type, dp.GetLocation());
            break;

        case DiscardPatternSyntax: break;

        case ParenthesizedPatternSyntax p:
            CheckPattern(context, oldType, p.Pattern);
            break;

        case RecursivePatternSyntax rp:

            ITypeSymbol ti;
            if (rp.Type != null)
            {
                ti = context.SemanticModel.GetTypeInfo(rp.Type).Type;
                CheckTypes(context, oldType, ti, rp.GetLocation());
            }
            else
            {
                ti = oldType;
            }

            if (rp.PropertyPatternClause != null)
            {
                foreach (var sp in rp.PropertyPatternClause.Subpatterns)
                {
                    var member = ti.GetMembers(sp.NameColon.Name.Identifier.ToString()).Only();
                    if (member is IPropertySymbol ps)
                    {
                        CheckPattern(context, ps.Type, sp.Pattern);
                    }
                    else if (member is IFieldSymbol fi)
                    {
                        CheckPattern(context, fi.Type, sp.Pattern);
                    }
                }
            }

            break;

        case TypePatternSyntax tp:
            CheckTypes(context, oldType, context.SemanticModel.GetTypeInfo(tp.Type).Type, tp.GetLocation());
            break;

        case UnaryPatternSyntax up:
            CheckPattern(context, oldType, up.Pattern);
            break;

        case VarPatternSyntax: break;

        default:
            break;
        }
    }
Example #45
0
 internal abstract Cci.ITypeReference Translate(ITypeSymbol symbol, SyntaxNode syntaxOpt, DiagnosticBag diagnostics);
Example #46
0
 public static TypeInfo Create(ITypeSymbol type)
 {
     Debug.Assert(type != null);
     return(new TypeInfo(type, -1));
 }
Example #47
0
 internal sealed override Cci.ITypeReference EncTranslateType(ITypeSymbol type, DiagnosticBag diagnostics)
 {
     return(EncTranslateLocalVariableType((TTypeSymbol)type, diagnostics));
 }
 internal static ExpressionSyntax?ShouldCast(InvocationExpressionSyntax invocation, ITypeSymbol returnType, SemanticModel semanticModel)
 {
     if (returnType != KnownSymbol.Object &&
         semanticModel.IsAccessible(invocation.SpanStart, returnType))
     {
         return(Expression(invocation));
Example #49
0
 public static TDeclarationNode UpdateDeclarationType <TDeclarationNode>(TDeclarationNode destination, Workspace workspace, ITypeSymbol newType, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode
 {
     return(GetCodeGenerationService(workspace, destination.Language).UpdateDeclarationType(destination, newType, options ?? new CodeGenerationOptions(reuseSyntax: true), cancellationToken));
 }
Example #50
0
 internal sealed override Cci.ITypeReference Translate(ITypeSymbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
 {
     return(Translate((TTypeSymbol)symbol, (TSyntaxNode)syntaxNodeOpt, diagnostics));
 }
 private static bool HasSerializableAttribute(ITypeSymbol typeSymbol) =>
 typeSymbol.GetAttributes()
 .Any(a => a.AttributeClass.Is(KnownType.System_SerializableAttribute));
Example #52
0
 internal abstract Cci.ITypeReference EncTranslateType(ITypeSymbol type, DiagnosticBag diagnostics);
Example #53
0
 internal static ITypeSymbol GetNullableUnderlyingType(ITypeSymbol type)
 {
     Debug.Assert(IsNullableType(type));
     return(((INamedTypeSymbol)type).TypeArguments[0]);
 }
 private static bool IsOrImplementsISerializable(ITypeSymbol typeSymbol) =>
 typeSymbol.Is(KnownType.System_Runtime_Serialization_ISerializable) ||
 typeSymbol.Implements(KnownType.System_Runtime_Serialization_ISerializable);
Example #55
0
            protected override bool IsImplicitReferenceConversion(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
            {
                var conversion = compilation.ClassifyConversion(sourceType, targetType);

                return(conversion.IsImplicit && conversion.IsReference);
            }
 private static bool ImplementsISerializable(ITypeSymbol typeSymbol) =>
 typeSymbol != null &&
 typeSymbol.IsPubliclyAccessible() &&
 typeSymbol.AllInterfaces.Any(IsOrImplementsISerializable);
Example #57
0
        public static IEnumerable <IEventSymbol> GetEventsOnTypeHierarchy(this ITypeSymbol thisType, Func <IEventSymbol, bool>?filter, BindingFlags?bindingFlags = BindingFlags.Default)
        {
            ITypeSymbol?type       = thisType;
            bool        onBaseType = false;

            while (type != null)
            {
                foreach (var @event in type.GetMembers().OfType <IEventSymbol> ())
                {
                    // Ignore private properties on a base type - those are completely ignored by reflection
                    // (anything private on the base type is not visible via the derived type)
                    // Note that properties themselves are not actually private, their accessors are
                    if (onBaseType &&
                        (@event.AddMethod == null || @event.AddMethod.DeclaredAccessibility == Accessibility.Private) &&
                        (@event.RemoveMethod == null || @event.RemoveMethod.DeclaredAccessibility == Accessibility.Private))
                    {
                        continue;
                    }

                    if (filter != null && !filter(@event))
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Static)
                    {
                        if ((@event.AddMethod != null) && [email protected])
                        {
                            continue;
                        }
                        if ((@event.RemoveMethod != null) && [email protected])
                        {
                            continue;
                        }
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Instance)
                    {
                        if ((@event.AddMethod != null) && @event.AddMethod.IsStatic)
                        {
                            continue;
                        }
                        if ((@event.RemoveMethod != null) && @event.RemoveMethod.IsStatic)
                        {
                            continue;
                        }
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.Public)
                    {
                        if ((@event.AddMethod == null || (@event.AddMethod.DeclaredAccessibility != Accessibility.Public)) &&
                            (@event.RemoveMethod == null || (@event.RemoveMethod.DeclaredAccessibility != Accessibility.Public)))
                        {
                            continue;
                        }
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.NonPublic)
                    {
                        if ((@event.AddMethod != null) && @event.AddMethod.DeclaredAccessibility == Accessibility.Public)
                        {
                            continue;
                        }
                        if ((@event.RemoveMethod != null) && @event.RemoveMethod.DeclaredAccessibility == Accessibility.Public)
                        {
                            continue;
                        }
                    }

                    yield return(@event);
                }

                if ((bindingFlags & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly)
                {
                    yield break;
                }

                type       = type.BaseType;
                onBaseType = true;
            }
        }
 public static string ToDisplayStringNullable(this ITypeSymbol typeSymbol) =>
 typeSymbol.ToDisplayString(ToNullableFlowState(typeSymbol.NullableAnnotation));
Example #59
0
        public static IEnumerable <IMethodSymbol> GetMethodsOnTypeHierarchy(this ITypeSymbol thisType, Func <IMethodSymbol, bool>?filter, BindingFlags?bindingFlags = null)
        {
            ITypeSymbol?type       = thisType;
            bool        onBaseType = false;

            while (type != null)
            {
                foreach (var method in type.GetMembers().OfType <IMethodSymbol> ())
                {
                    // Ignore constructors as those are not considered methods from a reflection's point of view
                    if (method.MethodKind == MethodKind.Constructor)
                    {
                        continue;
                    }

                    // Ignore private methods on a base type - those are completely ignored by reflection
                    // (anything private on the base type is not visible via the derived type)
                    if (onBaseType && method.DeclaredAccessibility == Accessibility.Private)
                    {
                        continue;
                    }

                    // Note that special methods like property getter/setter, event adder/remover will still get through and will be marked.
                    // This is intentional as reflection treats these as methods as well.
                    if (filter != null && !filter(method))
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Static && !method.IsStatic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Instance && method.IsStatic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.Public && method.DeclaredAccessibility != Accessibility.Public)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.NonPublic && method.DeclaredAccessibility == Accessibility.Public)
                    {
                        continue;
                    }

                    yield return(method);
                }

                if ((bindingFlags & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly)
                {
                    yield break;
                }

                type       = type.BaseType;
                onBaseType = true;
            }
        }
Example #60
0
        // Can not pass SymbolEqualityComparer to HashSet since the collection type is ITypeSymbol and not ISymbol.
#pragma warning disable RS1024
        // declaredOnly will cause this to retrieve only members of the type, not of its base types. This includes interfaces recursively
        // required by this type (but not members of these interfaces, or interfaces required only by base types).
        public static void GetAllOnType(this ITypeSymbol type, bool declaredOnly, List <ISymbol> members) => GetAllOnType(type, declaredOnly, members, new HashSet <ITypeSymbol> (SymbolEqualityComparer.Default));