Example #1
0
            public void Analyze(OperationAnalysisContext analysisContext)
            {
                var invocationExpression = (IInvocationOperation)analysisContext.Operation;

                if (invocationExpression.TargetMethod.OriginalDefinition.Equals(_gcSuppressFinalizeMethodSymbol))
                {
                    _suppressFinalizeCalled = true;

                    // Check for GC.SuppressFinalize outside of IDisposable.Dispose()
                    if (_expectedUsage == SuppressFinalizeUsage.MustNotCall)
                    {
                        analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
                                                             OutsideDisposeRule,
                                                             _containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                                             _gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
                    }

                    // Checks for GC.SuppressFinalize(this)
                    if (!invocationExpression.Arguments.HasExactly(1))
                    {
                        return;
                    }

                    if (invocationExpression.SemanticModel.GetSymbolInfo(invocationExpression.Arguments.Single().Value.Syntax, analysisContext.CancellationToken).Symbol is not IParameterSymbol parameterSymbol || !parameterSymbol.IsThis)
                    {
                        analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
                                                             NotPassedThisRule,
                                                             _containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                                             _gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
                    }
                }
            }
        private static void ValidateClientReturnType(GeneratorExecutionContext context, INamedTypeSymbol returnTypeSymbol, IMethodSymbol methodSymbol, INamedTypeSymbol taskSymbol)
        {
            if (returnTypeSymbol.IsGenericType)
            {
                var location = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax().GetLocation() ?? Location.None;

                context.ReportDiagnostic(Diagnostic.Create(
                                             DiagnosticDescriptorCollection.ReceiverMethodReturnTypeRule,
                                             location,
                                             methodSymbol.ToDisplayString()));

                throw new Exception($"Return value type of {methodSymbol.ToDisplayString()} must be Task.");
            }
            else
            {
                if (!returnTypeSymbol.Equals(taskSymbol, SymbolEqualityComparer.Default))
                {
                    var location = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax().GetLocation() ?? Location.None;

                    context.ReportDiagnostic(Diagnostic.Create(
                                                 DiagnosticDescriptorCollection.ReceiverMethodReturnTypeRule,
                                                 location,
                                                 methodSymbol.ToDisplayString()));

                    throw new Exception($"Return value type of {methodSymbol.ToDisplayString()} must be Task.");
                }
            }
        }
        private static string GetCodeFixTitle(
            string resourceString,
            IMethodSymbol methodToUpdate,
            bool includeParameters
            )
        {
            var methodDisplay = methodToUpdate.ToDisplayString(
                new SymbolDisplayFormat(
                    typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
                    extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
                    parameterOptions: SymbolDisplayParameterOptions.None,
                    memberOptions: methodToUpdate.IsConstructor()
                      ? SymbolDisplayMemberOptions.None
                      : SymbolDisplayMemberOptions.IncludeContainingType
                    )
                );

            var parameters = methodToUpdate.Parameters.Select(p => p.ToDisplayString(SimpleFormat));
            var signature  = includeParameters
                ? $"{methodDisplay}({string.Join(", ", parameters)})"
                : methodDisplay;
            var title = string.Format(resourceString, signature);

            return(title);
        }
        private static string ExtractGenericParameterSignature(IMethodSymbol methodSymbol)
        {
            var methodSignature  = methodSymbol.ToDisplayString(MethodFormat);
            var firstParenthesis = methodSignature.IndexOf('(');

            if (firstParenthesis == -1)
            {
                // some weird COM interop indexers are treated as methods
                // for example:
                // [Guid("04A72314-32E9-48E2-9B87-A63603454F3E")]
                // [TypeLibType(4160)]
                // [ComImport]
                // public interface _DTE
                // ...
                //      [DispId(212)]
                //      [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
                //      [return: MarshalAs(UnmanagedType.Interface)]
                //      Properties get_Properties([MarshalAs(UnmanagedType.BStr)] string Category, [MarshalAs(UnmanagedType.BStr)] string Page);
                return(string.Empty);
            }

            methodSignature = methodSignature.Substring(firstParenthesis);
            if (methodSymbol.Language == LanguageNames.VisualBasic)
            {
                if (methodSignature != "()")
                {
                    methodSignature = methodSignature.Replace("()", "[]");
                }

                methodSignature = methodSignature.Replace("ParamArray ", "params ");
                methodSignature = methodSignature.Replace("ByRef ", "out ");
            }

            return(methodSignature);
        }
        private SignatureHelpItem BuildSignature(IMethodSymbol symbol)
        {
            var signature = new SignatureHelpItem();

            signature.Documentation = symbol.GetDocumentationCommentXml();
            if (symbol.MethodKind == MethodKind.Constructor)
            {
                signature.Name  = symbol.ContainingType.Name;
                signature.Label = symbol.ContainingType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
            }
            else
            {
                signature.Name  = symbol.Name;
                signature.Label = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
            }

            signature.Parameters = GetParameters(symbol).Select(parameter =>
            {
                return(new SignatureHelpParameter()
                {
                    Name = parameter.Name,
                    Label = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
                    Documentation = parameter.GetDocumentationCommentXml()
                });
            });
            return(signature);
        }
        private void WriteMsilMethod(IMethodSymbol method, IMethodSymbol target)
        {
            string token = target.ToDisplayString();
            int    pos   = token.IndexOf('(');

            token = TypeToMsil(target.ReturnType) + " " + NameToMsil(token.Remove(pos)) + "(" + string.Join(", ", target.Parameters.Select(ParamToMsil)) + ")";

            WriteIndent();
            Output.Write(".method private final hidebysig newslot virtual instance bool " + method.Name + "()");
            WriteBlockStart(CodeGenBlockType.Method);
            WriteIndent();
            Output.WriteLine(".override method instance bool " + NameToMsil(method.Name) + "()");
            WriteIndent();
            Output.WriteLine(".maxstack 2");
            WriteIndent();
            Output.WriteLine("ldarg.0");
            WriteIndent();
            Output.WriteLine("ldvirtftn instance " + token);
            WriteIndent();
            Output.WriteLine("ldftn instance " + token);
            WriteIndent();
            Output.WriteLine("ceq");
            WriteIndent();
            Output.WriteLine("ret");
            WriteBlockEnd(CodeGenBlockType.Method);
        }
Example #7
0
        private static string GetMethodName(IMethodSymbol methodSymbol)
        {
            SymbolDisplayFormat format = (methodSymbol.MethodKind == MethodKind.UserDefinedOperator) ?
                                         _testDataOperatorKeyFormat :
                                         _testDataKeyFormat;

            return(methodSymbol.ToDisplayString(format));
        }
Example #8
0
        protected override void BuildMethodDeclaration(
            IMethodSymbol methodSymbol,
            _VSOBJDESCOPTIONS options
            )
        {
            BuildMemberModifiers(methodSymbol);

            if (
                methodSymbol.MethodKind != MethodKind.Constructor &&
                methodSymbol.MethodKind != MethodKind.Destructor &&
                methodSymbol.MethodKind != MethodKind.StaticConstructor &&
                methodSymbol.MethodKind != MethodKind.Conversion
                )
            {
                AddTypeLink(methodSymbol.ReturnType, LinkFlags.None);
                AddText(" ");
            }

            if (methodSymbol.MethodKind == MethodKind.Conversion)
            {
                switch (methodSymbol.Name)
                {
                case WellKnownMemberNames.ImplicitConversionName:
                    AddName("implicit operator ");
                    break;

                case WellKnownMemberNames.ExplicitConversionName:
                    AddName("explicit operator ");
                    break;
                }

                AddTypeLink(methodSymbol.ReturnType, LinkFlags.None);
            }
            else
            {
                var methodNameFormat = new SymbolDisplayFormat(
                    genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters
                    | SymbolDisplayGenericsOptions.IncludeVariance
                    );

                AddName(methodSymbol.ToDisplayString(methodNameFormat));
            }

            AddText("(");

            if (methodSymbol.IsExtensionMethod)
            {
                AddText("this ");
            }

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

            if (methodSymbol.IsGenericMethod)
            {
                BuildGenericConstraints(methodSymbol);
            }
        }
Example #9
0
        private static string GetMethodName(IMethodSymbolInternal methodSymbol)
        {
            IMethodSymbol iMethod = (IMethodSymbol)methodSymbol.GetISymbol();
            var           format  = (iMethod.MethodKind == MethodKind.UserDefinedOperator) ?
                                    _testDataOperatorKeyFormat :
                                    _testDataKeyFormat;

            return(iMethod.ToDisplayString(format));
        }
Example #10
0
        private static void CompareOrderOfParameters([NotNull] IMethodSymbol method, [NotNull] IMethodSymbol longestOverload,
                                                     SymbolAnalysisContext context)
        {
            List <IParameterSymbol> parametersInLongestOverload = longestOverload.Parameters.ToList();

            if (!AreParametersDeclaredInSameOrder(method, parametersInLongestOverload))
            {
                context.ReportDiagnostic(Diagnostic.Create(OrderRule, method.Locations[0],
                                                           method.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat)));
            }
        }
        public override string?VisitMethod(IMethodSymbol symbol)
        {
            if (symbol.MethodKind != MethodKind.Ordinary || symbol.IsInterfaceRequired() == false)
            {
                return(null);
            }

            var result = symbol.ToDisplayString(SymbolDisplayFormats.KP2PInterfaceDeclaration) + ";";

            return(result);
        }
Example #12
0
        public SignatureViewModel(IMethodSymbol method, string documentation = null)
        {
            Documentation = documentation;

            Parameters = method
                         .Parameters
                         .Select(p => new ParameterViewModel(p))
                         .ToArray();

            Label = method.ToDisplayString(Constants.SymbolDisplayFormat);
        }
Example #13
0
        /// <summary>
        /// Construct a new MethodAPIV instance, represented by the provided symbol.
        /// </summary>
        /// <param name="symbol">The symbol representing the method.</param>
        public MethodApiView(IMethodSymbol symbol)
        {
            this.Id            = symbol.ToDisplayString();
            this.IsConstructor = false;
            if (symbol.MethodKind == MethodKind.Constructor)
            {
                this.Name          = symbol.ContainingType.Name;
                this.IsConstructor = true;
            }
            else
            {
                this.Name       = symbol.Name;
                this.ReturnType = new TypeReferenceApiView(symbol.ReturnType);
            }
            this.Accessibility = symbol.DeclaredAccessibility.ToString().ToLower();

            this.IsInterfaceMethod = symbol.ContainingType.TypeKind == TypeKind.Interface;
            this.IsStatic          = symbol.IsStatic;
            this.IsVirtual         = symbol.IsVirtual;
            this.IsSealed          = symbol.IsSealed;
            this.IsOverride        = symbol.IsOverride;
            this.IsAbstract        = symbol.IsAbstract;
            this.IsExtensionMethod = symbol.IsExtensionMethod;
            this.IsExtern          = symbol.IsExtern;

            List <AttributeApiView>     attributes     = new List <AttributeApiView>();
            List <TypeParameterApiView> typeParameters = new List <TypeParameterApiView>();
            List <ParameterApiView>     parameters     = new List <ParameterApiView>();

            foreach (AttributeData attribute in symbol.GetAttributes())
            {
                if ((attribute.AttributeClass.DeclaredAccessibility == Microsoft.CodeAnalysis.Accessibility.Public ||
                     attribute.AttributeClass.DeclaredAccessibility == Microsoft.CodeAnalysis.Accessibility.Protected) &&
                    !ignoredAttributeNames.Contains(attribute.AttributeClass.Name) &&
                    !attribute.AttributeClass.IsImplicitlyDeclared)
                {
                    attributes.Add(new AttributeApiView(attribute, this.Id));
                }
            }
            foreach (ITypeParameterSymbol typeParam in symbol.TypeParameters)
            {
                typeParameters.Add(new TypeParameterApiView(typeParam));
            }
            foreach (IParameterSymbol param in symbol.Parameters)
            {
                parameters.Add(new ParameterApiView(param));
            }

            this.Attributes     = attributes.ToArray();
            this.TypeParameters = typeParameters.ToArray();
            this.Parameters     = parameters.ToArray();
        }
        private static void ReportReturnStatement([NotNull] IReturnOperation returnOperation, OperationAnalysisContext context)
        {
            IMethodSymbol method = returnOperation.TryGetContainingMethod(context.Compilation);

            if (method != null && !method.IsSynthesized())
            {
                Location location = returnOperation.ReturnedValue.Syntax.GetLocation();
                string   kind     = method.GetKind().ToLowerInvariant();

                context.ReportDiagnostic(Diagnostic.Create(Rule, location, kind,
                                                           method.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat)));
            }
        }
Example #15
0
 private static void ReportDiagnostic(
     OperationAnalysisContext oaContext,
     IInvocationOperation invocationExpression,
     IMethodSymbol targetMethod,
     IMethodSymbol correctOverload)
 {
     oaContext.ReportDiagnostic(
         invocationExpression.Syntax.CreateDiagnostic(
             Rule,
             targetMethod.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
             oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
             correctOverload.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
 }
Example #16
0
            public void Analyze(OperationAnalysisContext analysisContext)
            {
                var invocationExpression = (IInvocationExpression)analysisContext.Operation;

                if (invocationExpression.TargetMethod.OriginalDefinition.Equals(_gcSuppressFinalizeMethodSymbol))
                {
                    _suppressFinalizeCalled = true;

                    if (_semanticModel == null)
                    {
                        _semanticModel = analysisContext.Compilation.GetSemanticModel(analysisContext.Operation.Syntax.SyntaxTree);
                    }

                    // Check for GC.SuppressFinalize outside of IDisposable.Dispose()
                    if (_expectedUsage == SuppressFinalizeUsage.MustNotCall)
                    {
                        analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
                                                             OutsideDisposeRule,
                                                             _containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                                             _gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
                    }

                    // Checks for GC.SuppressFinalize(this)
                    if (invocationExpression.ArgumentsInSourceOrder.Count() != 1)
                    {
                        return;
                    }

                    var parameterSymbol = _semanticModel.GetSymbolInfo(invocationExpression.ArgumentsInSourceOrder.Single().Syntax).Symbol as IParameterSymbol;
                    if (parameterSymbol == null || !parameterSymbol.IsThis)
                    {
                        analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
                                                             NotPassedThisRule,
                                                             _containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                                             _gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
                    }
                }
            }
        private static SignatureInformation BuildSignature(IMethodSymbol symbol)
        {
            var parameters = symbol.Parameters
                             .Select(parameter =>
                                     new ParameterInformation(
                                         label: parameter.Name,
                                         documentation: new FormattedValue("text/markdown", DocumentationConverter.ConvertDocumentation(parameter.GetDocumentationCommentXml(expandIncludes: true)))));

            var signatureInformation = new SignatureInformation(
                label: symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
                documentation: new FormattedValue("text/markdown", DocumentationConverter.ConvertDocumentation(symbol.GetDocumentationCommentXml(expandIncludes: true))),
                parameters: parameters.ToList());

            return(signatureInformation);
        }
Example #18
0
        public static string GetUniqueHashName(IMethodSymbol methodSymbol)
        {
            var    str  = methodSymbol.ToDisplayString(ConvertHashDisplayFormat);
            string name = methodSymbol.Name;

            if (name == ".ctor")
            {
                SymbolDisplayFormat format = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.Omitted,
                                                                     SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions.None,
                                                                     SymbolDisplayMemberOptions.None, parameterOptions: SymbolDisplayParameterOptions.None);

                var clssName = methodSymbol.ToDisplayString(format);

                name = "ctor";
                //if(clssName == "SyntaxTrivia" && )
                //{
                //    name += "_C";
                //}
            }

            var result = $"{name}_{Hash( str )}";

            return(result);
        }
        public static ReferenceAnnotation GetMethodInvocationInfo(IMethodSymbol caller, IMethodSymbol callee, int invocationIndex, FileLinePositionSpan span)
        {
            var result = new ReferenceAnnotation()
            {
                declarationId = CodeGraphHelper.GetSymbolId(callee),
                symbolId      = CodeGraphHelper.GetSymbolId(caller, invocationIndex),
                declFile      = callee.Locations.First().GetMappedLineSpan().Path,
                symbolType    = SymbolType.Method,
                label         = callee.Name,
                hover         = callee.ToDisplayString(),
                refType       = "ref",
                range         = CodeGraphHelper.GetRange(span)
            };

            return(result);
        }
Example #20
0
        private static SignatureHelpItem BuildSignature(IMethodSymbol symbol)
        {
            var signature = new SignatureHelpItem
            {
                Documentation = DocumentationConverter.GetDocumentation(symbol, "\n"),
                Name          = symbol.MethodKind == MethodKind.Constructor ? symbol.ContainingType.Name : symbol.Name,
                Label         = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
                Parameters    = GetParameters(symbol).Select(parameter => new SignatureHelpParameter
                {
                    Name          = parameter.Name,
                    Label         = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
                    Documentation = DocumentationConverter.GetDocumentation(parameter, "\n"),
                })
            };

            return(signature);
        }
Example #21
0
        private static string ExtractGenericParameterSignature(IMethodSymbol methodSymbol)
        {
            var methodSignature = methodSymbol.ToDisplayString(MethodFormat);

            methodSignature = methodSignature.Substring(methodSignature.IndexOf('('));
            if (methodSymbol.Language == LanguageNames.VisualBasic)
            {
                if (methodSignature != "()")
                {
                    methodSignature = methodSignature.Replace("()", "[]");
                }

                methodSignature = methodSignature.Replace("ParamArray ", "params ");
            }

            return(methodSignature);
        }
        public static DeclarationAnnotation GetMethodDeclarationInfo(SyntaxNode node, IMethodSymbol symbol)
        {
            var span = CodeGraphHelper.GetSpan(node);

            var result = new DeclarationAnnotation()
            {
                symbolId   = CodeGraphHelper.GetSymbolId(symbol),
                symbolType = SymbolType.Method,
                label      = symbol.Name,
                hover      = symbol.ToDisplayString(),
                refType    = "decl",
                glyph      = "72",
                range      = CodeGraphHelper.GetRange(span)
            };

            return(result);
        }
Example #23
0
        private static void AnalyzeOverload(OverloadsInfo info, [NotNull] IMethodSymbol overload)
        {
            if (!overload.IsOverride && !overload.IsInterfaceImplementation() &&
                !overload.HidesBaseMember(info.Context.CancellationToken))
            {
                CompareOrderOfParameters(overload, info.LongestOverload, info.Context);
            }

            var invocationWalker = new MethodInvocationWalker(info.MethodGroup);

            if (!InvokesAnotherOverload(overload, invocationWalker, info.Context))
            {
                IMethodSymbol methodToReport = overload.PartialImplementationPart ?? overload;

                info.Context.ReportDiagnostic(Diagnostic.Create(InvokeRule, methodToReport.Locations[0],
                                                                methodToReport.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat)));
            }
        }
        private static Signature BuildSignature(IMethodSymbol symbol)
        {
            var signature = new Signature
            {
                Documentation = symbol.GetDocumentationCommentXml(),
                Name          = symbol.MethodKind == MethodKind.Constructor ? symbol.ContainingType.Name : symbol.Name,
                Label         = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
            };

            signature.Parameters = symbol.Parameters.Select(parameter => new SignatureParameter
            {
                Name          = parameter.Name,
                Label         = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
                Documentation = parameter.GetDocumentationCommentXml(),
            }).ToList();

            return(signature);
        }
        /// <summary>
        ///   Creates the default method that is assigned to a binding delegate that throws an <see cref="UnboundPortException"/>.
        /// </summary>
        private MethodDeclarationSyntax CreateUnboundPortThrowMethod()
        {
            var parameters     = _methodSymbol.Parameters.Select(parameter => Syntax.GlobalParameterDeclaration(parameter));
            var methodName     = Syntax.LiteralExpression(_methodSymbol.ToDisplayString());
            var objectCreation = Syntax.ObjectCreationExpression(SemanticModel.GetTypeSymbol <UnboundPortException>(), methodName);
            var throwStatement = (StatementSyntax)Syntax.ThrowStatement(objectCreation);

            var method = Syntax.MethodDeclaration(
                name: GetUnboundPortThrowMethodName(),
                parameters: parameters,
                returnType: Syntax.GlobalTypeExpression(_methodSymbol.ReturnType),
                accessibility: Accessibility.Private,
                modifiers: DeclarationModifiers.Static | DeclarationModifiers.Unsafe,
                statements: new[] { throwStatement });

            method = Syntax.AddAttribute <CompilerGeneratedAttribute>(method);
            method = Syntax.AddAttribute <DebuggerStepThroughAttribute>(method);
            return((MethodDeclarationSyntax)method);
        }
Example #26
0
        private static SignatureHelpItem BuildSignature(IMethodSymbol symbol)
        {
            var signature = new SignatureHelpItem();

            signature.Documentation           = symbol.GetDocumentationCommentXml();
            signature.Name                    = symbol.MethodKind == MethodKind.Constructor ? symbol.ContainingType.Name : symbol.Name;
            signature.Label                   = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
            signature.StructuredDocumentation = DocumentationConverter.GetStructuredDocumentation(symbol);

            signature.Parameters = symbol.Parameters.Select(parameter =>
            {
                return(new SignatureHelpParameter()
                {
                    Name = parameter.Name,
                    Label = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
                    Documentation = signature.StructuredDocumentation.GetParameterText(parameter.Name)
                });
            });

            return(signature);
        }
Example #27
0
        private void AnalyzeOverloads([NotNull][ItemNotNull] ICollection <IMethodSymbol> methodGroup,
                                      [NotNull] IMethodSymbol longestOverload, SymbolAnalysisContext context)
        {
            foreach (IMethodSymbol overload in methodGroup.Where(method => !method.Equals(longestOverload)))
            {
                if (!overload.IsOverride && !overload.IsInterfaceImplementation() &&
                    !overload.HidesBaseMember(context.CancellationToken))
                {
                    CompareOrderOfParameters(overload, longestOverload, context);
                }

                ImmutableArray <IMethodSymbol> otherOverloads = methodGroup.Where(m => !m.Equals(overload)).ToImmutableArray();

                if (!HasInvocationToAnyOf(otherOverloads, overload, context))
                {
                    IMethodSymbol methodToReport = overload.PartialImplementationPart ?? overload;

                    context.ReportDiagnostic(Diagnostic.Create(InvokeRule, methodToReport.Locations[0],
                                                               methodToReport.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat)));
                }
            }
        }
 private string GetTooltipForMethod(IMethodSymbol methodSymbol)
     => methodSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat
         .AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters)
         .AddParameterOptions(SymbolDisplayParameterOptions.IncludeName)
         .AddMemberOptions(SymbolDisplayMemberOptions.IncludeType));
Example #29
0
        public virtual SymbolFilterReason GetReason(IMethodSymbol symbol)
        {
            var canBeImplicitlyDeclared = false;

            if (!Includes(SymbolGroupFilter.Method))
                return SymbolFilterReason.SymbolGroup;

            switch (symbol.MethodKind)
            {
                case MethodKind.Constructor:
                    {
                        TypeKind typeKind = symbol.ContainingType.TypeKind;

                        Debug.Assert(typeKind.Is(TypeKind.Class, TypeKind.Struct, TypeKind.Enum), symbol.ToDisplayString(SymbolDisplayFormats.Test));

                        if (typeKind == TypeKind.Class
                            && !symbol.Parameters.Any())
                        {
                            canBeImplicitlyDeclared = true;
                        }

                        break;
                    }
                case MethodKind.Conversion:
                case MethodKind.UserDefinedOperator:
                case MethodKind.Ordinary:
                case MethodKind.StaticConstructor:
                case MethodKind.Destructor:
                case MethodKind.ExplicitInterfaceImplementation:
                    {
                        break;
                    }
                default:
                    {
                        return SymbolFilterReason.Other;
                    }
            }

            if (!canBeImplicitlyDeclared && symbol.IsImplicitlyDeclared)
                return SymbolFilterReason.ImplicitlyDeclared;

            if (!symbol.IsVisible(Visibility))
                return SymbolFilterReason.Visibility;

            return GetRulesReason(symbol);
        }
		/// <summary>
		///     Gets the key the <paramref name="methodSymbol" /> is stored under in the <seealso cref="_implementationMethods" />
		///     dictionary.
		/// </summary>
		/// <param name="methodSymbol">The method the key should be returned for.</param>
		private static string GetMethodKey(IMethodSymbol methodSymbol)
		{
			return String.Format("{0} {1}", methodSymbol.ContainingType.ToDisplayString(), methodSymbol.ToDisplayString());
		}
Example #31
0
 private static string GetMethodName(IMethodSymbol methodSymbol)
 {
     var format = (methodSymbol.MethodKind == MethodKind.UserDefinedOperator) ?
         _testDataOperatorKeyFormat :
         _testDataKeyFormat;
     return methodSymbol.ToDisplayString(format);
 }
        private SignatureHelpItem BuildSignature(IMethodSymbol symbol)
        {
            var signature = new SignatureHelpItem();
            signature.Documentation = symbol.GetDocumentationCommentXml();
            if (symbol.MethodKind == MethodKind.Constructor)
            {
                signature.Name = symbol.ContainingType.Name;
                signature.Label = symbol.ContainingType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
            }
            else
            {
                signature.Name = symbol.Name;
                signature.Label = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
            }

            signature.Parameters = GetParameters(symbol).Select(parameter =>
            {
                return new SignatureHelpParameter()
                {
                    Name = parameter.Name,
                    Label = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
                    Documentation = parameter.GetDocumentationCommentXml()
                };
            });
            return signature;
        }
        protected override void BuildMethodDeclaration(IMethodSymbol methodSymbol, _VSOBJDESCOPTIONS options)
        {
            BuildMemberModifiers(methodSymbol);

            if (methodSymbol.MethodKind != MethodKind.Constructor &&
                methodSymbol.MethodKind != MethodKind.Destructor &&
                methodSymbol.MethodKind != MethodKind.StaticConstructor &&
                methodSymbol.MethodKind != MethodKind.Conversion)
            {
                AddTypeLink(methodSymbol.ReturnType, LinkFlags.None);
                AddText(" ");
            }

            if (methodSymbol.MethodKind == MethodKind.Conversion)
            {
                switch (methodSymbol.Name)
                {
                    case WellKnownMemberNames.ImplicitConversionName:
                        AddName("implicit operator ");
                        break;

                    case WellKnownMemberNames.ExplicitConversionName:
                        AddName("explicit operator ");
                        break;
                }

                AddTypeLink(methodSymbol.ReturnType, LinkFlags.None);
            }
            else
            {
                var methodNameFormat = new SymbolDisplayFormat(
                    genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance);

                AddName(methodSymbol.ToDisplayString(methodNameFormat));
            }

            AddText("(");

            if (methodSymbol.IsExtensionMethod)
            {
                AddText("this ");
            }

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

            if (methodSymbol.IsGenericMethod)
            {
                BuildGenericConstraints(methodSymbol);
            }
        }
 public static string ToMinimallyQualifiedDisplayString(this IMethodSymbol symbol)
 {
     return(symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
 }
 private static void ReportDiagnostic(
     OperationAnalysisContext oaContext,
     IInvocationExpression invocationExpression,
     IMethodSymbol targetMethod,
     IMethodSymbol correctOverload)
 {
     oaContext.ReportDiagnostic(
         invocationExpression.Syntax.CreateDiagnostic(
             Rule,
             targetMethod.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
             oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
             correctOverload.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
 }
Example #36
0
 private bool IsPotentialUserInputMethod(IMethodSymbol methodSymbol)
 {
     return(potentialVulnerableMethods.Any(p => methodSymbol.ToDisplayString().StartsWith(p)));
 }