protected override bool TryInitializeState(
			Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
			out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
		{
			var baseClassNode = node as TypeSyntax;
			if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
				baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
				((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
			{
				if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
				{
					abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
					cancellationToken.ThrowIfCancellationRequested();

					if (abstractClassType.IsAbstractClass())
					{
						var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
						classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;

						return classType != null && abstractClassType != null;
					}
				}
			}

			classType = null;
			abstractClassType = null;
			return false;
		}
Пример #2
1
        public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
        {
            if (symbol.TypeKind != TypeKind.Enum)
            {
                return;
            }

            var flagsAttribute = WellKnownTypes.FlagsAttribute(compilation);
            if (flagsAttribute == null)
            {
                return;
            }

            var zeroValuedFields = GetZeroValuedFields(symbol).ToImmutableArray();

            bool hasFlagsAttribute = symbol.GetAttributes().Any(a => a.AttributeClass == flagsAttribute);
            if (hasFlagsAttribute)
            {
                CheckFlags(symbol, zeroValuedFields, addDiagnostic);
            }
            else
            {
                CheckNonFlags(symbol, zeroValuedFields, addDiagnostic);
            }
        }
        private static HashSet<ISymbol> GetAutoPropsWithPrivateSetters(INamedTypeSymbol type, CancellationToken cancellationToken)
        {
            HashSet<ISymbol> candidates = null;

            var allProperties = type.GetMembers().Where(s => s.Kind == SymbolKind.Property);
            foreach (var property in allProperties)
            {
                var propertySymbol = (IPropertySymbol)property;
                if (!propertySymbol.IsReadOnly && propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty)
                {
                    var setMethod = propertySymbol.SetMethod;
                    if (setMethod != null && setMethod.DeclaredAccessibility == Accessibility.Private)
                    {
                        // Find the syntax for the setter.
                        var reference = setMethod.DeclaringSyntaxReferences.FirstOrDefault();
                        if (reference != null)
                        {
                            var declaration = reference.GetSyntax(cancellationToken) as AccessorDeclarationSyntax;
                            if (declaration != null && declaration.Body == null)
                            {
                                // An empty body indicates it's an auto-prop
                                (candidates ?? (candidates = new HashSet<ISymbol>())).Add(propertySymbol);
                            }
                        }
                    }
                }
            }

            return candidates;
        }
        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);
        }
 private static void AnalyzeSymbol(INamedTypeSymbol namedTypeSymbol, Action<Diagnostic> addDiagnostic)
 {
     if (namedTypeSymbol.IsValueType && namedTypeSymbol.DoesOverrideEquals() && !IsEqualityOperatorImplemented(namedTypeSymbol))
     {
         addDiagnostic(namedTypeSymbol.CreateDiagnostic(Rule));
     }
 }
        private void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol flagsAttribute)
        {
            var symbol = (INamedTypeSymbol)context.Symbol;

            if (symbol.TypeKind != TypeKind.Enum)
            {
                return;
            }

            SpecialType underlyingType = symbol.EnumUnderlyingType.SpecialType;
            if (underlyingType == SpecialType.System_Int32)
            {
                return;
            }

            // If accessibility of enum is not public exit
            if (symbol.GetResultantVisibility() != SymbolVisibility.Public)
            {
                return;
            }

            // If enum is Int64 and has Flags attributes then exit
            bool hasFlagsAttribute = symbol.GetAttributes().Any(a => a.AttributeClass.Equals(flagsAttribute));
            if (underlyingType == SpecialType.System_Int64 && hasFlagsAttribute)
            {
                return;
            }

            context.ReportDiagnostic(symbol.CreateDiagnostic(Rule, symbol.Name, symbol.EnumUnderlyingType));
        }
        private IEnumerable<SignatureHelpItem> GetDelegateTypeConstructors(
            ObjectCreationExpressionSyntax objectCreationExpression,
            SemanticModel semanticModel,
            ISymbolDisplayService symbolDisplayService,
            IAnonymousTypeDisplayService anonymousTypeDisplayService,
            INamedTypeSymbol delegateType,
            INamedTypeSymbol containingType,
            CancellationToken cancellationToken)
        {
            var invokeMethod = delegateType.DelegateInvokeMethod;
            if (invokeMethod == null)
            {
                return null;
            }

            var position = objectCreationExpression.SpanStart;
            var item = CreateItem(
                invokeMethod, semanticModel, position,
                symbolDisplayService, anonymousTypeDisplayService,
                isVariadic: false,
                documentationFactory: null,
                prefixParts: GetDelegateTypePreambleParts(invokeMethod, semanticModel, position),
                separatorParts: GetSeparatorParts(),
                suffixParts: GetDelegateTypePostambleParts(invokeMethod),
                parameters: GetDelegateTypeParameters(invokeMethod, semanticModel, position, cancellationToken));

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

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

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

            return SpecializedCollections.SingletonEnumerable(item);
        }
        private async Task<Document> ImplementOperatorEquals(Document document, SyntaxNode declaration, INamedTypeSymbol typeSymbol, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
            var generator = editor.Generator;

            if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.EqualityOperatorName))
            {
                var equalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean),
                                                                   WellKnownMemberNames.EqualityOperatorName,
                                                                   new[]
                                                                   {
                                                                       generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)),
                                                                       generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)),
                                                                   },
                                                                   generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException"))));
                editor.AddMember(declaration, equalityOperator);
            }

            if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.InequalityOperatorName))
            {
                var inequalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean),
                                                                   WellKnownMemberNames.InequalityOperatorName,
                                                                   new[]
                                                                   {
                                                                       generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)),
                                                                       generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)),
                                                                   },
                                                                   generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException"))));
                editor.AddMember(declaration, inequalityOperator);
            }

            return editor.GetChangedDocument();

        }
		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 IMethodSymbol GenerateSetAccessor(
                Compilation compilation,
                IPropertySymbol property,
                Accessibility accessibility,
                bool generateAbstractly,
                bool useExplicitInterfaceSymbol,
                INamedTypeSymbol[] attributesToRemove,
                CancellationToken cancellationToken)
            {
                if (property.SetMethod == null)
                {
                    return null;
                }

                var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
                     this.State.ClassOrStructType,
                     attributesToRemove);

                return CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    setMethod,
                    attributes: null,
                    accessibility: accessibility,
                    explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.SetMethod : null,
                    statements: GetSetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));
            }
        public static IEnumerable<ISymbol> CreateFieldDelegatingConstructor(
            this SyntaxGenerator factory,
            string typeName,
            INamedTypeSymbol containingTypeOpt,
            IList<IParameterSymbol> parameters,
            IDictionary<string, ISymbol> parameterToExistingFieldMap,
            IDictionary<string, string> parameterToNewFieldMap,
            CancellationToken cancellationToken)
        {
            var fields = factory.CreateFieldsForParameters(parameters, parameterToNewFieldMap);
            var statements = factory.CreateAssignmentStatements(parameters, parameterToExistingFieldMap, parameterToNewFieldMap)
                                    .Select(s => s.WithAdditionalAnnotations(Simplifier.Annotation));

            foreach (var field in fields)
            {
                yield return field;
            }

            yield return CodeGenerationSymbolFactory.CreateConstructorSymbol(
                attributes: null,
                accessibility: Accessibility.Public,
                modifiers: new DeclarationModifiers(),
                typeName: typeName,
                parameters: parameters,
                statements: statements.ToList(),
                thisConstructorArguments: GetThisConstructorArguments(containingTypeOpt, parameterToExistingFieldMap));
        }
Пример #13
0
 public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     if (symbol.GetMembers().Any(member => IsDllImport(member)) && !IsTypeNamedCorrectly(symbol.Name))
     {
         addDiagnostic(symbol.CreateDiagnostic(Rule));
     }
 }
		public SuggestedHandlerCompletionData (MonoDevelop.Projects.Project project, CodeMemberMethod methodInfo, INamedTypeSymbol codeBehindClass, Location codeBehindClassLocation)
		{
			this.project = project;
			this.methodInfo = methodInfo;
			this.codeBehindClass = codeBehindClass;
			this.codeBehindClassLocation = codeBehindClassLocation;
		}
 private State(SyntaxNode node, INamedTypeSymbol classType, INamedTypeSymbol abstractClassType, IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers)
 {
     this.Location = node;
     this.ClassType = classType;
     this.AbstractClassType = abstractClassType;
     this.UnimplementedMembers = unimplementedMembers;
 }
 /// <summary>
 /// Returns a list of method symbols from a given list of the method symbols, which has its parameter type as
 /// expectedParameterType as its last parameter in addition to matching all the other parameter types of the 
 /// selectedOverload method symbol
 /// </summary>
 /// <param name="methods">List of <see cref="IMethodSymbol"/> to scan for possible overloads</param>
 /// <param name="selectedOverload"><see cref="IMethodSymbol"/> that is currently picked by the user</param>
 /// <param name="expectedTrailingParameterType"><see cref="INamedTypeSymbol"/> type of the leading parameter or the trailing parameter</param>
 public static IEnumerable<IMethodSymbol> GetMethodOverloadsWithDesiredParameterAtTrailing(
      this IEnumerable<IMethodSymbol> methods,
      IMethodSymbol selectedOverload,
      INamedTypeSymbol expectedTrailingParameterType)
 {
     return GetMethodOverloadsWithDesiredParameterAtLeadingOrTrailing(methods, selectedOverload, expectedTrailingParameterType, trailingOnly: true);
 }
 /// <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);
 }
Пример #18
0
 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;
 }
Пример #19
0
        /// <summary>
        /// Changes the base type of the symbol.
        /// </summary>
        public static async Task<ISymbol> SetBaseTypeAsync(
            this SymbolEditor editor,
            INamedTypeSymbol symbol,
            Func<SyntaxGenerator, SyntaxNode> getNewBaseType,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var baseType = symbol.BaseType;

            if (baseType != null)
            {
                // find existing declaration of the base type
                var typeRef = await editor.GetBaseOrInterfaceDeclarationReferenceAsync(symbol, baseType, cancellationToken).ConfigureAwait(false);
                if (typeRef != null)
                {
                    return await editor.EditOneDeclarationAsync(
                        symbol,
                        typeRef.GetLocation(),
                        (e, d) => e.ReplaceNode(typeRef, getNewBaseType(e.Generator)),
                        cancellationToken).ConfigureAwait(false);
                }
            }

            // couldn't find the existing reference to change, so add it to one of the declarations
            return await editor.EditOneDeclarationAsync(symbol, (e, decl) =>
            {
                var newBaseType = getNewBaseType(e.Generator);
                if (newBaseType != null)
                {
                    e.ReplaceNode(decl, (d, g) => g.AddBaseType(d, newBaseType));
                }
            }, cancellationToken).ConfigureAwait(false);
        }
Пример #20
0
        private static RQUnconstructedType BuildNamedType(INamedTypeSymbol type)
        {
            // Anything that is a valid RQUnconstructed types is ALWAYS safe for public APIs

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

            // Anonymous types are unsupported
            if (type.IsAnonymousType)
            {
                return null;
            }

            // the following types are supported for BuildType() used in signatures, but are not supported
            // for UnconstructedTypes
            if (type != type.ConstructedFrom || type.SpecialType == SpecialType.System_Void)
            {
                return null;
            }

            // make an RQUnconstructedType
            var namespaceNames = RQNodeBuilder.GetNameParts(@type.ContainingNamespace);
            var typeInfos = new List<RQUnconstructedTypeInfo>();

            for (INamedTypeSymbol currentType = type; currentType != null; currentType = currentType.ContainingType)
            {
                typeInfos.Insert(0, new RQUnconstructedTypeInfo(currentType.Name, currentType.TypeParameters.Length));
            }

            return new RQUnconstructedType(namespaceNames, typeInfos);
        }
 protected virtual bool IsInitializable(ISymbol member, INamedTypeSymbol containingType)
 {
     return
         !member.IsStatic &&
         member.MatchesKind(SymbolKind.Field, SymbolKind.Property) &&
         member.IsAccessibleWithin(containingType);
 }
 public CompilationSecurityTypes(Compilation compilation)
 {
     HandleProcessCorruptedStateExceptionsAttribute =
         SecurityTypes.HandleProcessCorruptedStateExceptionsAttribute(compilation);
     SystemObject = SecurityTypes.SystemObject(compilation);
     SystemException = SecurityTypes.SystemException(compilation);
     SystemSystemException = SecurityTypes.SystemSystemException(compilation);
     DES = SecurityTypes.DES(compilation);
     DSA = SecurityTypes.DSA(compilation);
     DSASignatureFormatter = SecurityTypes.DSASignatureFormatter(compilation);
     HMACMD5 = SecurityTypes.HMACMD5(compilation);
     RC2 = SecurityTypes.RC2(compilation);
     TripleDES = SecurityTypes.TripleDES(compilation);
     RIPEMD160 = SecurityTypes.RIPEMD160(compilation);
     HMACRIPEMD160 = SecurityTypes.HMACRIPEMD160(compilation);
     XmlDocument = SecurityTypes.XmlDocument(compilation);
     XPathDocument = SecurityTypes.XPathDocument(compilation);
     XmlSchema = SecurityTypes.XmlSchema(compilation);
     DataSet = SecurityTypes.DataSet(compilation);
     XmlSerializer = SecurityTypes.XmlSerializer(compilation);
     DataTable = SecurityTypes.DataTable(compilation);
     XmlNode = SecurityTypes.XmlNode(compilation);
     DataViewManager = SecurityTypes.DataViewManager(compilation);
     XmlTextReader = SecurityTypes.XmlTextReader(compilation);
     XmlReader = SecurityTypes.XmlReader(compilation);
     DtdProcessing = SecurityTypes.DtdProcessing(compilation);
     XmlReaderSettings = SecurityTypes.XmlReaderSettings(compilation);
     XslCompiledTransform = SecurityTypes.XslCompiledTransform(compilation);
     XmlResolver = SecurityTypes.XmlResolver(compilation);
     XmlSecureResolver = SecurityTypes.XmlSecureResolver(compilation);
     XsltSettings = SecurityTypes.XsltSettings(compilation);
 }
		public static IPropertySymbol RemoveAttributeFromParameters(
			this IPropertySymbol property, INamedTypeSymbol attributeType)
		{
			if (attributeType == null)
			{
				return property;
			}

			var someParameterHasAttribute = property.Parameters
				.Any(p => p.GetAttributes().Any(a => a.AttributeClass.Equals(attributeType)));
			if (!someParameterHasAttribute)
			{
				return property;
			}

			return CodeGenerationSymbolFactory.CreatePropertySymbol(
				property.ContainingType,
				property.GetAttributes(),
				property.DeclaredAccessibility,
				property.GetSymbolModifiers(),
				property.Type,
				property.ExplicitInterfaceImplementations.FirstOrDefault(),
				property.Name,
				property.Parameters.Select(p =>
					CodeGenerationSymbolFactory.CreateParameterSymbol(
						p.GetAttributes().Where(a => !a.AttributeClass.Equals(attributeType)).ToList(),
						p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
						p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList(),
				property.GetMethod,
				property.SetMethod,
				property.IsIndexer);
		}
Пример #24
0
        private void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol objectType, INamedTypeSymbol equatableType)
        {
            var namedType = context.Symbol as INamedTypeSymbol;
            if (namedType == null || !(namedType.TypeKind == TypeKind.Struct || namedType.TypeKind == TypeKind.Class))
            {
                return;
            }

            var methodSymbol = namedType
                .GetMembers("Equals")
                .OfType<IMethodSymbol>()
                .Where(m => IsObjectEqualsOverride(m, objectType))
                .FirstOrDefault();
            var overridesObjectEquals = methodSymbol != null;

            var constructedEquatable = equatableType.Construct(namedType);
            var implementation = namedType
                .Interfaces
                .Where(x => x.Equals(constructedEquatable))
                .FirstOrDefault();
            var implementsEquatable = implementation != null;

            if (overridesObjectEquals && !implementsEquatable && namedType.TypeKind == TypeKind.Struct)
            {
                context.ReportDiagnostic(Diagnostic.Create(s_implementIEquatableDescriptor, methodSymbol.Locations[0], namedType));
            }

            if (!overridesObjectEquals && implementsEquatable)
            {
                context.ReportDiagnostic(Diagnostic.Create(s_overridesObjectEqualsDescriptor, namedType.Locations[0], namedType));
            }
        }
Пример #25
0
        private static string GetTypeDisplayString(INamedTypeSymbol symbol)
        {
            if (symbol.SpecialType != SpecialType.None)
            {
                var specialType = symbol.SpecialType;
                var name = Enum.GetName(typeof(SpecialType), symbol.SpecialType).Replace("_", ".");
                return name;
            }

            if (symbol.IsGenericType)
            {
                symbol = symbol.ConstructUnboundGenericType();
            }

            if (symbol.IsUnboundGenericType)
            {
                // TODO: Is this the best to get the fully metadata name?
                var parts = symbol.ToDisplayParts();
                var filteredParts = parts.Where(x => x.Kind != SymbolDisplayPartKind.Punctuation).ToArray();
                var typeName = new StringBuilder();
                foreach (var part in filteredParts.Take(filteredParts.Length - 1))
                {
                    typeName.Append(part.Symbol.Name);
                    typeName.Append(".");
                }
                typeName.Append(symbol.MetadataName);

                return typeName.ToString();
            }

            return symbol.ToDisplayString();
        }
		protected bool TryGetTypes(
			SyntaxNode expression,
			SemanticModel semanticModel,
			out INamedTypeSymbol source,
			out INamedTypeSymbol destination)
		{
			source = null;
			destination = null;

			var info = semanticModel.GetSymbolInfo(expression);
			var methodSymbol = info.Symbol as IMethodSymbol;
			if (methodSymbol == null)
			{
				return false;
			}

			var compilation = semanticModel.Compilation;
			var taskType = compilation.GetTypeByMetadataName("System.Threading.Tasks.Task");
			if (taskType == null)
			{
				return false;
			}

			var returnType = methodSymbol.ReturnType as INamedTypeSymbol;
			if (returnType == null)
			{
				return false;
			}

			source = taskType;
			destination = returnType;
			return true;
		}
 private static TypeDeclarationSyntax AddDisposeDeclarationToDisposeMethod(VariableDeclaratorSyntax variableDeclarator, TypeDeclarationSyntax type, INamedTypeSymbol typeSymbol)
 {
     var disposableMethod = typeSymbol.GetMembers("Dispose").OfType<IMethodSymbol>().FirstOrDefault(d => d.Arity == 0);
     var disposeStatement = SyntaxFactory.ParseStatement($"{variableDeclarator.Identifier.ToString()}.Dispose();");
     TypeDeclarationSyntax newType;
     if (disposableMethod == null)
     {
         var disposeMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "Dispose")
               .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
               .WithBody(SyntaxFactory.Block(disposeStatement))
               .WithAdditionalAnnotations(Formatter.Annotation);
         newType = ((dynamic)type).AddMembers(disposeMethod);
     }
     else
     {
         var existingDisposeMethod = (MethodDeclarationSyntax)disposableMethod.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax();
         if (type.Members.Contains(existingDisposeMethod))
         {
             var newDisposeMethod = existingDisposeMethod.AddBodyStatements(disposeStatement)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newType = type.ReplaceNode(existingDisposeMethod, newDisposeMethod);
         }
         else
         {
             //we will simply anotate the code for now, but ideally we would change another document
             //for this to work we have to be able to fix more than one doc
             var fieldDeclaration = variableDeclarator.Parent.Parent;
             var newFieldDeclaration = fieldDeclaration.WithTrailingTrivia(SyntaxFactory.ParseTrailingTrivia($"//add {disposeStatement.ToString()} to the Dispose method on another file.").AddRange(fieldDeclaration.GetTrailingTrivia()))
                 .WithLeadingTrivia(fieldDeclaration.GetLeadingTrivia());
             newType = type.ReplaceNode(fieldDeclaration, newFieldDeclaration);
         }
     }
     return newType;
 }
        public bool IsOverridable(ISymbol member, INamedTypeSymbol containingType)
        {
            if (member.IsAbstract || member.IsVirtual || member.IsOverride)
            {
                if (member.IsSealed)
                {
                    return false;
                }

                if (!member.IsAccessibleWithin(containingType))
                {
                    return false;
                }

                switch (member.Kind)
                {
                    case SymbolKind.Event:
                        return true;
                    case SymbolKind.Method:
                        return ((IMethodSymbol)member).MethodKind == MethodKind.Ordinary;
                    case SymbolKind.Property:
                        return !((IPropertySymbol)member).IsWithEvents;
                }
            }

            return false;
        }
Пример #29
0
        protected override void BuildDelegateDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options)
        {
            Debug.Assert(typeSymbol.TypeKind == TypeKind.Delegate);

            BuildTypeModifiers(typeSymbol);
            AddText("delegate ");

            var delegateInvokeMethod = typeSymbol.DelegateInvokeMethod;

            AddTypeLink(delegateInvokeMethod.ReturnType, LinkFlags.None);
            AddText(" ");

            var typeQualificationStyle = (options & _VSOBJDESCOPTIONS.ODO_USEFULLNAME) != 0
                ? SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces
                : SymbolDisplayTypeQualificationStyle.NameOnly;

            var typeNameFormat = new SymbolDisplayFormat(
                typeQualificationStyle: typeQualificationStyle,
                genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance);

            AddName(typeSymbol.ToDisplayString(typeNameFormat));

            AddText("(");
            BuildParameterList(delegateInvokeMethod.Parameters);
            AddText(")");

            if (typeSymbol.IsGenericType)
            {
                BuildGenericConstraints(typeSymbol);
            }
        }
Пример #30
0
        internal static IClassMetadata FromNamedTypeSymbol(INamedTypeSymbol symbol)
        {
            if (symbol == null) return null;
            if (symbol.DeclaredAccessibility != Accessibility.Public || symbol.ToDisplayString() == "object") return null;

            return new RoslynClassMetadata(symbol);
        }
        private static async Task <Document> OverrideObjectEqualsAsync(Document document, SyntaxNode declaration,
                                                                       INamedTypeSymbol typeSymbol, INamedTypeSymbol equatableType, CancellationToken cancellationToken)
        {
            var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            var generator = editor.Generator;

            var argumentName = generator.IdentifierName("obj");

            SyntaxNode returnStatement;

            if (HasExplicitEqualsImplementation(typeSymbol, equatableType))
            {
                returnStatement = typeSymbol.TypeKind == TypeKind.Class
                    ? GetReturnStatementForExplicitClass(generator, typeSymbol, argumentName, equatableType)
                    : GetReturnStatementForExplicitStruct(generator, typeSymbol, argumentName, equatableType);
            }
            else
            {
                returnStatement = typeSymbol.TypeKind == TypeKind.Class
                    ? GetReturnStatementForImplicitClass(generator, typeSymbol, argumentName)
                    : GetReturnStatementForImplicitStruct(generator, typeSymbol, argumentName);
            }

            var equalsMethod = generator.MethodDeclaration(
                WellKnownMemberNames.ObjectEquals,
                new[]
            {
                generator.ParameterDeclaration(argumentName.ToString(),
                                               generator.TypeExpression(SpecialType.System_Object))
            },
                returnType: generator.TypeExpression(SpecialType.System_Boolean),
                accessibility: Accessibility.Public,
                modifiers: DeclarationModifiers.Override,
                statements: new[] { returnStatement });

            editor.AddMember(declaration, equalsMethod);

            return(editor.GetChangedDocument());
        }
 static bool IsThrowNotImplementedOperation(INamedTypeSymbol notImplementedExceptionType, IOperation operation)
 => operation is IThrowOperation throwOperation &&
Пример #33
0
 protected bool IsDiagnosticAnalyzer(INamedTypeSymbol type)
 {
     return(type.Equals(DiagnosticAnalyzer));
 }
Пример #34
0
 protected DiagnosticAnalyzerSymbolAnalyzer(INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
 {
     DiagnosticAnalyzer          = diagnosticAnalyzer;
     DiagnosticAnalyzerAttribute = diagnosticAnalyzerAttribute;
 }
 internal override IEnumerable <SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType)
 => containingType.Constructors.SelectMany(c => c.DeclaringSyntaxReferences.Select(d => d.GetSyntax()));
        protected static string MakeUnique(string baseName, INamedTypeSymbol containingType)
        {
            var containingTypeMemberNames = containingType.GetAccessibleMembersInThisAndBaseTypes <ISymbol>(containingType).Select(m => m.Name);

            return(NameGenerator.GenerateUniqueName(baseName, containingTypeMemberNames.ToSet(), StringComparer.Ordinal));
        }
 private static bool IsAccessible(ISymbol symbol, INamedTypeSymbol within)
 {
     return(within == null || symbol.IsAccessibleWithin(within));
 }
Пример #38
0
 /// <summary>
 /// </summary>
 /// <param name="type">
 /// </param>
 public CCodeDelegateWrapperClass(INamedTypeSymbol type)
     : base(type.IsValueType ? new ValueTypeAsClassTypeImpl(type) : type)
 {
     this.invoke = (IMethodSymbol)type.GetMembers("Invoke").First();
 }
        private static async Task <Document> ApplyRuleNameMultipleZeroAsync(Document document, INamedTypeSymbol enumType, CancellationToken cancellationToken)
        {
            // Diagnostic: Remove all members that have the value zero from '{0}' except for one member that is named 'None'.
            // Fix: Remove all members that have the value zero except for one member that is named 'None'.
            SymbolEditor editor = SymbolEditor.Create(document);

            bool needsNewZeroValuedNoneField = true;
            ISet <IFieldSymbol> set          = EnumsShouldHaveZeroValueAnalyzer.GetZeroValuedFields(enumType).ToSet();

            bool makeNextFieldExplicit = false;

            foreach (IFieldSymbol field in enumType.GetMembers().Where(m => m.Kind == SymbolKind.Field))
            {
                bool isZeroValued          = set.Contains(field);
                bool isZeroValuedNamedNone = isZeroValued && EnumsShouldHaveZeroValueAnalyzer.IsMemberNamedNone(field);

                if (!isZeroValued || isZeroValuedNamedNone)
                {
                    if (makeNextFieldExplicit)
                    {
                        await editor.EditOneDeclarationAsync(field, (e, d) => e.ReplaceNode(d, GetExplicitlyAssignedField(field, d, e.Generator)), cancellationToken).ConfigureAwait(false);

                        makeNextFieldExplicit = false;
                    }

                    if (isZeroValuedNamedNone)
                    {
                        needsNewZeroValuedNoneField = false;
                    }
                }
                else
                {
                    await editor.EditOneDeclarationAsync(field, (e, d) => e.RemoveNode(d), cancellationToken).ConfigureAwait(false); // removes the field declaration

                    makeNextFieldExplicit = true;
                }
            }

            if (needsNewZeroValuedNoneField)
            {
                await editor.EditOneDeclarationAsync(enumType, (e, d) => e.InsertMembers(d, 0, new[] { e.Generator.EnumMember("None") }), cancellationToken).ConfigureAwait(false);
            }

            return(editor.GetChangedDocuments().First());
        }
        private static async Task <Document> ApplyRuleNameNoZeroValueAsync(Document document, INamedTypeSymbol enumType, CancellationToken cancellationToken)
        {
            SymbolEditor editor = SymbolEditor.Create(document);

            // remove any non-zero member named 'None'
            foreach (IFieldSymbol field in enumType.GetMembers().Where(m => m.Kind == SymbolKind.Field))
            {
                if (EnumsShouldHaveZeroValueAnalyzer.IsMemberNamedNone(field))
                {
                    await editor.EditOneDeclarationAsync(field, (e, d) => e.RemoveNode(d), cancellationToken).ConfigureAwait(false);
                }
            }

            // insert zero-valued member 'None' to top
            await editor.EditOneDeclarationAsync(enumType, (e, d) => e.InsertMembers(d, 0, new[] { e.Generator.EnumMember("None") }), cancellationToken).ConfigureAwait(false);

            return(editor.GetChangedDocuments().First());
        }
Пример #41
0
 /// <summary>
 /// Returns a value indicating whether the specified symbol has the specified
 /// attribute.
 /// </summary>
 /// <param name="symbol">
 /// The symbol being examined.
 /// </param>
 /// <param name="attribute">
 /// The attribute in question.
 /// </param>
 /// <returns>
 /// <c>true</c> if <paramref name="symbol"/> has an attribute of type
 /// <paramref name="attribute"/>; otherwise <c>false</c>.
 /// </returns>
 /// <remarks>
 /// If <paramref name="symbol"/> is a type, this method does not find attributes
 /// on its base types.
 /// </remarks>
 public static bool HasAttribute(this ISymbol symbol, INamedTypeSymbol attribute)
 {
     return(symbol.GetAttributes().Any(attr => attr.AttributeClass.Equals(attribute)));
 }
    public override LuaSyntaxNode VisitAttribute(AttributeSyntax node) {
      var symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(node.Name).Symbol;
      INamedTypeSymbol typeSymbol = symbol.ContainingType;
      if (!generator_.IsExportAttribute(typeSymbol)) {
        return null;
      }

      INamedTypeSymbol typeDeclarationSymbol = GetTypeDeclarationSymbol(node);
      generator_.AddTypeDeclarationAttribute(typeDeclarationSymbol, typeSymbol);

      ++baseNameNodeCounter_;
      var expression = GetTypeName(typeSymbol);
      --baseNameNodeCounter_;
      LuaInvocationExpressionSyntax invocation = BuildObjectCreationInvocation(symbol, new LuaMemberAccessExpressionSyntax(LuaIdentifierNameSyntax.Global, expression));

      if (node.ArgumentList != null) {
        List<LuaExpressionSyntax> arguments = new List<LuaExpressionSyntax>();
        List<Tuple<LuaExpressionSyntax, LuaExpressionSyntax>> initializers = new List<Tuple<LuaExpressionSyntax, LuaExpressionSyntax>>();
        List<Tuple<NameColonSyntax, ExpressionSyntax>> argumentNodeInfos = new List<Tuple<NameColonSyntax, ExpressionSyntax>>();

        foreach (var argumentNode in node.ArgumentList.Arguments) {
          var argumentExpression = (LuaExpressionSyntax)argumentNode.Expression.Accept(this);
          CheckValueTypeAndConversion(argumentNode.Expression, ref argumentExpression);
          if (argumentNode.NameEquals == null) {
            if (argumentNode.NameColon != null) {
              string name = argumentNode.NameColon.Name.Identifier.ValueText;
              int index = symbol.Parameters.IndexOf(i => i.Name == name);
              Contract.Assert(index != -1);
              arguments.AddAt(index, argumentExpression);
            }
            else {
              arguments.Add(argumentExpression);
            }
          }
          else {
            var name = (LuaExpressionSyntax)argumentNode.NameEquals.Accept(this);
            initializers.Add(Tuple.Create(name, argumentExpression));
          }
        }

        CheckInvocationDeafultArguments(symbol, symbol.Parameters, arguments, argumentNodeInfos, node, false);
        invocation.AddArguments(arguments);

        if (initializers.Count == 0) {
          return invocation;
        }
        else {
          LuaFunctionExpressionSyntax function = new LuaFunctionExpressionSyntax();
          PushFunction(function);
          var temp = GetTempIdentifier(node);
          function.AddParameter(temp);

          foreach (var initializer in initializers) {
            var memberAccess = BuildFieldOrPropertyMemberAccessExpression(temp, initializer.Item1, false);
            var assignmentExpression = BuildLuaSimpleAssignmentExpression(memberAccess, initializer.Item2);
            function.AddStatement(assignmentExpression);
          }

          PopFunction();
          return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Create, invocation, function);
        }
      }
      else {
        return invocation;
      }
    }
Пример #43
0
        /// <summary>
        /// Check whether given overloads has any overload whose parameters has the given type as its parameter type.
        /// </summary>
        public static bool HasOverloadWithParameterOfType(this IEnumerable <IMethodSymbol> overloads, IMethodSymbol self, INamedTypeSymbol type, CancellationToken cancellationToken)
        {
            foreach (var overload in overloads)
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (self?.Equals(overload) == true)
                {
                    continue;
                }

                if (overload.Parameters.ContainsParameterOfType(type))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #44
0
        /// <summary>
        /// Get overload from the given overloads that matches given method signature + given parameter
        /// </summary>
        public static IMethodSymbol GetMatchingOverload(this IMethodSymbol method, IEnumerable <IMethodSymbol> overloads, int parameterIndex, INamedTypeSymbol type, CancellationToken cancellationToken)
        {
            foreach (IMethodSymbol overload in overloads)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // does not account for method with optional parameters
                if (method.Equals(overload) || overload.Parameters.Length != method.Parameters.Length)
                {
                    // either itself, or signature is not same
                    continue;
                }

                if (!method.ParameterTypesAreSame(overload, Enumerable.Range(0, method.Parameters.Length).Where(i => i != parameterIndex), cancellationToken))
                {
                    // check whether remaining parameters match existing types, otherwise, we are not interested
                    continue;
                }

                if (overload.Parameters[parameterIndex].Type.Equals(type) == true)
                {
                    // we no longer interested in this overload. there can be only 1 match
                    return(overload);
                }
            }

            return(null);
        }
Пример #45
0
        /// <summary>
        /// Check whether given parameters contains any parameter with given type.
        /// </summary>
        public static bool ContainsParameterOfType(this IEnumerable <IParameterSymbol> parameters, INamedTypeSymbol type)
        {
            var parametersOfType = GetParametersOfType(parameters, type);

            return(parametersOfType.Any());
        }
Пример #46
0
 /// <summary>
 /// Get parameters which type is the given type
 /// </summary>
 public static IEnumerable <IParameterSymbol> GetParametersOfType(this IEnumerable <IParameterSymbol> parameters, INamedTypeSymbol type)
 {
     return(parameters.Where(p => p.Type.Equals(type) == true));
 }
Пример #47
0
 public static bool MatchMemberByName(this ISymbol member, INamedTypeSymbol type, string name)
 {
     return(member != null && member.ContainingType == type && member.MetadataName == name);
 }
Пример #48
0
 public static bool MatchFieldByName(this ISymbol member, INamedTypeSymbol type, string name)
 {
     return(member != null && member.Kind == SymbolKind.Field && member.MatchMemberByName(type, name));
 }
Пример #49
0
 public static bool MatchMethodDerivedByName(this IMethodSymbol method, INamedTypeSymbol type, string name)
 {
     return(method != null && method.MatchMemberDerivedByName(type, name));
 }
Пример #50
0
 public static bool MatchPropertyDerivedByName(this ISymbol member, INamedTypeSymbol type, string name)
 {
     return(member != null && member.Kind == SymbolKind.Property && member.MatchMemberDerivedByName(type, name));
 }
Пример #51
0
        private void GenerateUnmarshaler(INamedTypeSymbol parametersType, IndentedStringBuilder sb, int packValue)
        {
            using (sb.BlockInvariant($"public static unmarshal(pData:number) : {parametersType.Name}"))
            {
                sb.AppendLineInvariant($"const ret = new {parametersType.Name}();");

                var fieldOffset = 0;
                foreach (var field in parametersType.GetFields())
                {
                    var fieldSize = GetNativeFieldSize(field);

                    if (field.Type is IArrayTypeSymbol arraySymbol)
                    {
                        if (!IsMarshalledExplicitly(field))
                        {
                            // This is required by the mono-wasm AOT engine for fields to be properly considered.
                            throw new InvalidOperationException($"The field {field} is an array but does not have a [MarshalAs(UnmanagedType.LPArray)] attribute");
                        }

                        var elementType     = arraySymbol.ElementType;
                        var elementTSType   = GetTSType(elementType);
                        var isElementString = elementType.SpecialType == SpecialType.System_String;
                        var elementSize     = isElementString ? 4 : fieldSize;

                        using (sb.BlockInvariant(""))
                        {
                            sb.AppendLineInvariant($"const pArray = Module.getValue(pData + {fieldOffset}, \"*\");");

                            using (sb.BlockInvariant("if(pArray !== 0)"))
                            {
                                sb.AppendLineInvariant($"ret.{field.Name} = new Array<{GetTSFieldType(elementType)}>();");

                                using (sb.BlockInvariant($"for(var i=0; i<ret.{field.Name}_Length; i++)"))
                                {
                                    sb.AppendLineInvariant($"const value = Module.getValue(pArray + i * {elementSize}, \"{GetEMField(field.Type)}\");");

                                    if (isElementString)
                                    {
                                        using (sb.BlockInvariant("if(value !== 0)"))
                                        {
                                            sb.AppendLineInvariant($"ret.{field.Name}.push({elementTSType}(MonoRuntime.conv_string(value)));");
                                        }
                                        sb.AppendLineInvariant("else");
                                        using (sb.BlockInvariant(""))
                                        {
                                            sb.AppendLineInvariant($"ret.{field.Name}.push(null);");
                                        }
                                    }
                                    else
                                    {
                                        sb.AppendLineInvariant($"ret.{field.Name}.push({elementTSType}(value));");
                                    }
                                }
                            }
                            sb.AppendLineInvariant("else");
                            using (sb.BlockInvariant(""))
                            {
                                sb.AppendLineInvariant($"ret.{field.Name} = null;");
                            }
                        }
                    }
                    else
                    {
                        using (sb.BlockInvariant(""))
                        {
                            if (field.Type.SpecialType == SpecialType.System_String)
                            {
                                sb.AppendLineInvariant($"const ptr = Module.getValue(pData + {fieldOffset}, \"{GetEMField(field.Type)}\");");

                                using (sb.BlockInvariant("if(ptr !== 0)"))
                                {
                                    sb.AppendLineInvariant($"ret.{field.Name} = {GetTSType(field.Type)}(Module.UTF8ToString(ptr));");
                                }
                                sb.AppendLineInvariant("else");
                                using (sb.BlockInvariant(""))
                                {
                                    sb.AppendLineInvariant($"ret.{field.Name} = null;");
                                }
                            }
                            else
                            {
                                if (CanUseEMHeapProperty(field.Type))
                                {
                                    sb.AppendLineInvariant($"ret.{field.Name} = Module.{GetEMHeapProperty(field.Type)}[(pData + {fieldOffset}) >> {GetEMTypeShift(field)}];");
                                }
                                else
                                {
                                    sb.AppendLineInvariant($"ret.{field.Name} = {GetTSType(field.Type)}(Module.getValue(pData + {fieldOffset}, \"{GetEMField(field.Type)}\"));");
                                }
                            }
                        }
                    }

                    fieldOffset += fieldSize;

                    var adjust = fieldOffset % packValue;
                    if (adjust != 0)
                    {
                        fieldOffset += (packValue - adjust);
                    }
                }

                sb.AppendLineInvariant($"return ret;");
            }
        }
Пример #52
0
 public static bool MatchMemberDerivedByName(this ISymbol member, INamedTypeSymbol type, string name)
 {
     return(member != null && member.ContainingType.DerivesFrom(type) && member.MetadataName == name);
 }
 private static SyntaxNode GetReturnStatementForExplicitStruct(SyntaxGenerator generator,
                                                               INamedTypeSymbol typeSymbol, SyntaxNode argumentName, INamedTypeSymbol equatableType)
 {
     return(generator.ReturnStatement(
                generator.LogicalAndExpression(
                    generator.IsTypeExpression(
                        argumentName,
                        typeSymbol),
                    generator.InvocationExpression(
                        generator.MemberAccessExpression(
                            generator.CastExpression(
                                equatableType.Construct(typeSymbol),
                                generator.ThisExpression()),
                            WellKnownMemberNames.ObjectEquals),
                        generator.CastExpression(
                            typeSymbol,
                            argumentName)))));
 }
        private static async Task <Document> ImplementEquatableInStructAsync(Document document, SyntaxNode declaration,
                                                                             INamedTypeSymbol typeSymbol, Compilation compilation, INamedTypeSymbol equatableType,
                                                                             CancellationToken cancellationToken)
        {
            var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            var generator = editor.Generator;

            var equalsMethod = generator.MethodDeclaration(
                WellKnownMemberNames.ObjectEquals,
                new[]
            {
                generator.ParameterDeclaration("other", generator.TypeExpression(typeSymbol))
            },
                returnType: generator.TypeExpression(SpecialType.System_Boolean),
                accessibility: Accessibility.Public,
                statements: generator.DefaultMethodBody(compilation));

            editor.AddMember(declaration, equalsMethod);

            INamedTypeSymbol constructedType = equatableType.Construct(typeSymbol);

            editor.AddInterfaceType(declaration, generator.TypeExpression(constructedType));

            return(editor.GetChangedDocument());
        }
Пример #55
0
        protected override TDeclarationNode AddNamedType <TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList <bool> availableIndices)
        {
            CheckDeclarationNode <TypeDeclarationSyntax, PackageDeclarationSyntax, CompilationUnitSyntax>(destination);

            if (destination is TypeDeclarationSyntax)
            {
                return(Cast <TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast <TypeDeclarationSyntax>(destination), namedType, options, availableIndices)));
            }
            else if (destination is PackageDeclarationSyntax)
            {
                return(Cast <TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast <PackageDeclarationSyntax>(destination), namedType, options, availableIndices)));
            }
            else
            {
                return(Cast <TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast <CompilationUnitSyntax>(destination), namedType, options, availableIndices)));
            }
        }
        private static bool HasExplicitEqualsImplementation(INamedTypeSymbol typeSymbol, INamedTypeSymbol equatableType)
        {
            INamedTypeSymbol constructedType         = equatableType.Construct(typeSymbol);
            IMethodSymbol    constructedEqualsMethod = constructedType.GetMembers().OfType <IMethodSymbol>().FirstOrDefault();

            foreach (IMethodSymbol method in typeSymbol.GetMembers().OfType <IMethodSymbol>())
            {
                foreach (IMethodSymbol explicitImplementation in method.ExplicitInterfaceImplementations)
                {
                    if (explicitImplementation.Equals(constructedEqualsMethod))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
        {
            Compilation compilation = compilationContext.Compilation;

            INamedTypeSymbol compilationType = compilation.GetTypeByMetadataName(s_compilationTypeFullName);

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

            INamedTypeSymbol symbolType = compilation.GetTypeByMetadataName(s_symbolTypeFullName);

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

            INamedTypeSymbol operationType = compilation.GetTypeByMetadataName(s_operationTypeFullName);

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

            var attributeUsageAttribute = WellKnownTypes.AttributeUsageAttribute(compilation);

            return(new FieldsAnalyzer(compilationType, symbolType, operationType, attributeUsageAttribute, diagnosticAnalyzer, diagnosticAnalyzerAttribute));
        }
 protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
 => containingType.ContainingTypesOrSelfHasUnsafeKeyword();
Пример #59
0
 public FieldsAnalyzer(INamedTypeSymbol compilationType, INamedTypeSymbol symbolType, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
     : base(diagnosticAnalyzer, diagnosticAnalyzerAttribute)
 {
     this.compilationType = compilationType;
     this.symbolType      = symbolType;
 }
 public FieldsAnalyzer(INamedTypeSymbol compilationType, INamedTypeSymbol symbolType, INamedTypeSymbol operationType, INamedTypeSymbol attributeUsageAttribute, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
     : base(diagnosticAnalyzer, diagnosticAnalyzerAttribute)
 {
     _compilationType         = compilationType;
     _symbolType              = symbolType;
     _operationType           = operationType;
     _attributeUsageAttribute = attributeUsageAttribute;
 }