当前位置: 首页>>代码示例>>C#>>正文


C# SymbolAnalysisContext类代码示例

本文整理汇总了C#中SymbolAnalysisContext的典型用法代码示例。如果您正苦于以下问题:C# SymbolAnalysisContext类的具体用法?C# SymbolAnalysisContext怎么用?C# SymbolAnalysisContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SymbolAnalysisContext类属于命名空间,在下文中一共展示了SymbolAnalysisContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Analyze

        public override void Analyze(SymbolAnalysisContext context, List<IncludeAttributeData> includeTags, List<ProtobufAttributeData> memberTags, List<ContractAttributeData> contractAttributes)
        {
            var grouped = memberTags.GroupBy(t => t.Symbol);

            foreach (var tagPerSymbol in grouped)
            {
                var list = tagPerSymbol.ToList();
                var protoMemberAttributes = list.Where(a => a is ProtoMemberAttributeData).Cast<ProtoMemberAttributeData>().ToList();
                var dataMemberAttributes = list.Where(a => a is DataMemberAttributeData).Cast<DataMemberAttributeData>().ToList();

                foreach (var protoMemberTag in protoMemberAttributes)
                {
                    foreach (var mismatchedDataMember in dataMemberAttributes.Where(d => d.Tag != protoMemberTag.Tag))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(
                            GetDescriptor(), 
                            protoMemberTag.GetLocation(),
                            protoMemberTag.Symbol.Name,
                            protoMemberTag.Tag,
                            mismatchedDataMember.Tag));
                        context.ReportDiagnostic(Diagnostic.Create(
                            GetDescriptor(),
                            mismatchedDataMember.GetLocation(),
                            mismatchedDataMember.Symbol.Name,
                            protoMemberTag.Tag,
                            mismatchedDataMember.Tag));
                    }
                }
            }
        }
开发者ID:julienadam,项目名称:Protobuf.CodeFixes,代码行数:30,代码来源:ProtoMemberDataMemberTagMismatchDiagnosticAnalyzer.cs

示例2: AnalyzeSymbol

        private void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;

            var members = namedTypeSymbol.GetMembers().Where(x => !x.IsImplicitlyDeclared && x.CanBeReferencedByName).ToArray();

            var orderedMembers = members.OrderBy(x => x.DeclaredAccessibility).ThenBy(x => x.Kind).ThenBy(x => x.Name).ToArray();

            var alphabetized = true;

            for (var i = 0; i < members.Length; i++)
            {
                if(orderedMembers[i] != members[i])
                {
                    alphabetized = false;
                }
            }

            if (!alphabetized)
            {
                var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);

                context.ReportDiagnostic(diagnostic);
            }
        }
开发者ID:Ophlan,项目名称:Ophlan.Analyzers,代码行数:25,代码来源:OrganizeMembersAnalyzer.cs

示例3: GetNamedSymbol

        /// <summary>
        /// Returns the first symbol matching the specified <paramref name="type"/>.
        /// </summary>
        /// <param name="type">
        /// The <see cref="T:System.Type"/> for the symbol to match.
        /// </param>
        /// <param name="context">
        /// The context to use to find the symbol.
        /// </param>
        /// <returns>
        /// The symbol if found; otherwise null.
        /// </returns>
        public static INamedTypeSymbol GetNamedSymbol(this Type type, SymbolAnalysisContext context)
        {
            foreach (var reference in context.Compilation.References)
            {
                if(reference == null)
                {
                    continue;
                }

                var assembly = context.Compilation.GetAssemblyOrModuleSymbol(reference) as IAssemblySymbol;
                if (assembly == null)
                {
                    continue;
                }

                if (!assembly.Name.Equals(type.GetTypeInfo().Assembly.GetName().Name, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                var namedTypeSymbol = assembly.GetTypeByMetadataName(type.FullName);
                if(namedTypeSymbol == null)
                {
                    continue;
                }

                return namedTypeSymbol;
            }

            return null;
        }
开发者ID:UnityContrib,项目名称:code-analysis,代码行数:43,代码来源:Common.cs

示例4: AnalyzeType

        protected void AnalyzeType(SymbolAnalysisContext context)
        {
            var potentialController = (INamedTypeSymbol)context.Symbol;
            if (potentialController.AllInterfaces.Length == 0) return;

            var controllerTechnology = DetermineWebTechnology(potentialController.AllInterfaces);
            if (controllerTechnology == WebTechnology.None) return;

            var controllerAttributes = potentialController.GetAttributes();
            foreach (var controllerAttribute in controllerAttributes)
            {
                var attributeTechnology = DetermineWebTechnology(controllerAttribute.AttributeClass.AllInterfaces);
                if (attributeTechnology != WebTechnology.None && attributeTechnology != controllerTechnology)
                    context.ReportDiagnostic(Diagnostic.Create(webTechMixDiagnosticDescriptor, potentialController.Locations[0], 
                        controllerAttribute.AttributeClass.Name, attributeTechnology, potentialController.Name, controllerTechnology));
            }

            foreach (var method in potentialController.GetMembers().Where(m => m.Kind == SymbolKind.Method))
            {
                foreach (var methodAttribute in method.GetAttributes())
                {
                    var attributeTechnology = DetermineWebTechnology(methodAttribute.AttributeClass.AllInterfaces);
                    if (attributeTechnology != WebTechnology.None && attributeTechnology != controllerTechnology)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(webTechMixDiagnosticDescriptor, method.Locations[0],
                            methodAttribute.AttributeClass.Name,
                            attributeTechnology, potentialController.Name, controllerTechnology));
                        break;
                    }
                }
            }
        }
开发者ID:damieng,项目名称:CSharpCodeFixes,代码行数:32,代码来源:WrongAttributeOnControllerAnalyzer.cs

示例5: HandleMethodDeclaration

        private void HandleMethodDeclaration(SymbolAnalysisContext context)
        {
            IMethodSymbol symbol = (IMethodSymbol)context.Symbol;
            if (symbol.IsAsync)
                return;

            if (!symbol.Name.EndsWith("Async", StringComparison.Ordinal))
                return;

            if (symbol.Locations.IsDefaultOrEmpty)
                return;

            Location location = symbol.Locations[0];
            if (!location.IsInSource || location.SourceTree.IsGeneratedDocument(context.CancellationToken))
                return;

            if (!symbol.ReturnsVoid)
            {
                if (string.Equals(nameof(Task), symbol.ReturnType?.Name, StringComparison.Ordinal)
                    && string.Equals(typeof(Task).Namespace, symbol.ReturnType?.ContainingNamespace?.ToString(), StringComparison.Ordinal))
                {
                    return;
                }
            }

            if (symbol.IsOverride)
                return;

            context.ReportDiagnostic(Diagnostic.Create(Descriptor, symbol.Locations[0], symbol.Name));
        }
开发者ID:ChrSteinert,项目名称:AsyncUsageAnalyzers,代码行数:30,代码来源:AvoidAsyncSuffixAnalyzer.cs

示例6: Analyze

        private static void Analyze(SymbolAnalysisContext context)
        {
            if (context.IsGenerated()) return;
            var symbol = (INamedTypeSymbol)context.Symbol;
            if (symbol.TypeKind != TypeKind.Class) return;
            if (!symbol.Interfaces.Any(i => i.SpecialType == SpecialType.System_IDisposable)) return;
            if (symbol.IsSealed && !ContainsUserDefinedFinalizer(symbol)) return;
            if (!ContainsNonPrivateConstructors(symbol)) return;
            var disposeMethod = FindDisposeMethod(symbol);
            if (disposeMethod == null) return;
            var syntaxTree = disposeMethod.DeclaringSyntaxReferences[0]?.GetSyntax();

            var statements = ((MethodDeclarationSyntax)syntaxTree)?.Body?.Statements.OfType<ExpressionStatementSyntax>();
            if (statements != null)
            {
                foreach (var statement in statements)
                {
                    var invocation = statement.Expression as InvocationExpressionSyntax;
                    var method = invocation?.Expression as MemberAccessExpressionSyntax;
                    var identifierSyntax = method?.Expression as IdentifierNameSyntax;
                    if (identifierSyntax != null && identifierSyntax.Identifier.ToString() == "GC" && method.Name.ToString() == "SuppressFinalize")
                        return;
                }
            }
            context.ReportDiagnostic(Diagnostic.Create(Rule, disposeMethod.Locations[0], symbol.Name));
        }
开发者ID:Bemjamin,项目名称:code-cracker,代码行数:26,代码来源:DisposablesShouldCallSuppressFinalizeAnalyzer.cs

示例7: AnalyzeSymbol

        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));
        }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:30,代码来源:EnumStorageShouldBeInt32.cs

示例8: ContainingTypeImplementsIDisposableAndCallsItOnTheField

 private static bool ContainingTypeImplementsIDisposableAndCallsItOnTheField(SymbolAnalysisContext context, IFieldSymbol fieldSymbol)
 {
     var containingType = fieldSymbol.ContainingType;
     if (containingType == null) return false;
     var iDisposableInterface = containingType.AllInterfaces.FirstOrDefault(i => i.ToString() == "System.IDisposable");
     if (iDisposableInterface == null) return false;
     var disposableMethod = iDisposableInterface.GetMembers("Dispose").OfType<IMethodSymbol>().First(d => d.Arity == 0);
     var disposeMethodSymbol = containingType.FindImplementationForInterfaceMember(disposableMethod) as IMethodSymbol;
     if (disposeMethodSymbol == null) return false;
     if (disposeMethodSymbol.IsAbstract) return true;
     foreach (MethodDeclarationSyntax disposeMethod in disposeMethodSymbol.DeclaringSyntaxReferences.Select(sr => sr.GetSyntax()))
     {
         if (disposeMethod == null) return false;
         var semanticModel = context.Compilation.GetSemanticModel(disposeMethod.SyntaxTree);
         if (CallsDisposeOnField(fieldSymbol, disposeMethod, semanticModel)) return true;
         var invocations = disposeMethod.DescendantNodes().OfKind<InvocationExpressionSyntax>(SyntaxKind.InvocationExpression);
         foreach (var invocation in invocations)
         {
             var invocationExpressionSymbol = semanticModel.GetSymbolInfo(invocation.Expression).Symbol;
             if (invocationExpressionSymbol == null
                 || invocationExpressionSymbol.Kind != SymbolKind.Method
                 || invocationExpressionSymbol.Locations.Any(l => l.Kind != LocationKind.SourceFile)
                 || !invocationExpressionSymbol.ContainingType.Equals(containingType)) continue;
             foreach (MethodDeclarationSyntax method in invocationExpressionSymbol.DeclaringSyntaxReferences.Select(sr => sr.GetSyntax()))
                 if (CallsDisposeOnField(fieldSymbol, method, semanticModel)) return true;
         }
     }
     return false;
 }
开发者ID:jhancock93,项目名称:code-cracker,代码行数:29,代码来源:DisposableFieldNotDisposedAnalyzer.cs

示例9: AnalyzeSymbol

        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));
            }
        }
开发者ID:nevinclement,项目名称:roslyn,代码行数:32,代码来源:EquatableAnalyzer.cs

示例10: AnalyzeSymbol

        private void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            var symbol = (IMethodSymbol)context.Symbol;
            if (CommonFunctions.SkipSymbolAnalysisIgnoringAttributes(symbol, _settingsHandler)) return;

            var ignoredVariables = CommonFunctions.ItemsToIgnoreFromAttributes(symbol, SuppressionAttributes).ToList();
            var syntax = symbol.DeclaringSyntaxReferences[0].GetSyntaxAsync().Result;

            var identifiers = syntax.DescendantNodes()
                                    .Where(node => node.IsKind(SyntaxKind.VariableDeclarator))
                                    .Cast<VariableDeclaratorSyntax>()
                                    .Select(variable => variable.Identifier.Value.ToString()).ToList();


            foreach (var reassignment in GetAllNonIgnoredMutations(syntax, ignoredVariables, identifiers))
            {
                context.ReportDiagnostic(Diagnostic.Create(AnalyzerRule,
                                                           reassignment.Location,
                                                           reassignment.Name));
            }

            foreach (var ignoredSyntaxInfo in NonExistantIgnoredVariables(ignoredVariables, identifiers))
            {
                context.ReportDiagnostic(Diagnostic.Create(SuppressionMisuseRule,
                                                           ignoredSyntaxInfo.Location,
                                                           ignoredSyntaxInfo.Name));
            }
        }
开发者ID:DavidArno,项目名称:Arnolyzer,代码行数:28,代码来源:AA1301VariablesShouldBeAssignedOnceOnlyAnalyzer.cs

示例11: CheckClassWithOnlyUnusedPrivateConstructors

        private static void CheckClassWithOnlyUnusedPrivateConstructors(SymbolAnalysisContext context)
        {
            var namedType = context.Symbol as INamedTypeSymbol;
            if (!namedType.IsClass() ||
                namedType.IsStatic)
            {
                return;
            }

            var members = namedType.GetMembers();
            var constructors = GetConstructors(members).ToList();

            if (!constructors.Any() ||
                HasNonPrivateConstructor(constructors) ||
                HasOnlyStaticMembers(members.Except(constructors).ToList()))
            {
                return;
            }

            var classDeclarations = new RemovableDeclarationCollector(namedType, context.Compilation).ClassDeclarations;

            if (!IsAnyConstructorCalled(namedType, classDeclarations))
            {
                var message = constructors.Count > 1
                    ? "at least one of its constructors"
                    : "its constructor";

                foreach (var classDeclaration in classDeclarations)
                {
                    context.ReportDiagnosticIfNonGenerated(Diagnostic.Create(Rule, classDeclaration.SyntaxNode.Identifier.GetLocation(),
                        message));
                }
            }
        }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:34,代码来源:ClassNotInstantiatable.cs

示例12: CheckForDecreasedVisibility

        private void CheckForDecreasedVisibility(SymbolAnalysisContext context)
        {
            ISymbol symbol = context.Symbol;

            // Only look for methods hiding others (not overriding). Overriding with a different visibility is already a compiler error
            if (symbol.IsOverride)
            {
                return;
            }

            // Bail out if the member is publicly accessible, or sealed, or on a sealed type
            if (IsVisibleOutsideAssembly(symbol) || symbol.IsSealed || (symbol.ContainingType?.IsSealed ?? true))
            {
                return;
            }

            // Event accessors cannot have visibility modifiers, so don't analyze them
            if ((symbol as IMethodSymbol)?.AssociatedSymbol as IEventSymbol != null)
            {
                return;
            }

            // Find members on base types that share the member's name
            System.Collections.Generic.IEnumerable<INamedTypeSymbol> ancestorTypes = symbol?.ContainingType?.GetBaseTypes() ?? Enumerable.Empty<INamedTypeSymbol>();
            System.Collections.Generic.IEnumerable<ISymbol> hiddenOrOverriddenMembers = ancestorTypes.SelectMany(t => t.GetMembers(symbol.Name));

            if (hiddenOrOverriddenMembers.Any(IsVisibleOutsideAssembly))
            {
                context.ReportDiagnostic(symbol.CreateDiagnostic(Rule));
            }
        }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:31,代码来源:DoNotDecreaseInheritedMemberVisibility.cs

示例13: AnalyzeField

        private static void AnalyzeField(SymbolAnalysisContext symbolAnalysisContext)
        {
            var fieldDeclarationSyntax = (IFieldSymbol)symbolAnalysisContext.Symbol;
            if (!IsFieldPrivate(fieldDeclarationSyntax) &&
                !IsStaticReadonly(fieldDeclarationSyntax) &&
                IsParentAClass(fieldDeclarationSyntax) &&
                !fieldDeclarationSyntax.IsConst)
            {
                foreach (var location in symbolAnalysisContext.Symbol.Locations)
                {
                    if (!location.IsInSource)
                    {
                        // assume symbols not defined in a source document are "out of reach"
                        return;
                    }

                    if (location.SourceTree.IsGeneratedDocument(symbolAnalysisContext.Compilation, symbolAnalysisContext.CancellationToken))
                    {
                        return;
                    }
                }

                symbolAnalysisContext.ReportDiagnostic(Diagnostic.Create(Descriptor, fieldDeclarationSyntax.Locations[0]));
            }
        }
开发者ID:Noryoko,项目名称:StyleCopAnalyzers,代码行数:25,代码来源:SA1401FieldsMustBePrivate.cs

示例14: AnalyzeSymbol

        /// <summary>
        /// Implementation for CA1044: Properties should not be write only
        /// </summary>
        private static void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            var property = context.Symbol as IPropertySymbol;
            if (property == null)
            {
                return;
            }
            
            // not raising a violation for when: 
            //     property is overridden because the issue can only be fixed in the base type 
            //     property is the implementaton of any interface member 
            if (property.IsOverride || property.IsImplementationOfAnyInterfaceMember())
            {
                return;
            }

            // If property is not visible outside the assembly
            if (property.GetResultantVisibility() != SymbolVisibility.Public)
            {
                return;
            }

            // We handled the non-CA1044 cases earlier.  Now, we handle CA1044 cases
            // If there is no getter then it is not accessible
            if (property.IsWriteOnly)
            {
                context.ReportDiagnostic(property.CreateDiagnostic(AddGetterRule, property.Name));
            }
            // Otherwise if there is a setter, check for its relative accessibility
            else if (!(property.IsReadOnly) && (property.GetMethod.DeclaredAccessibility < property.SetMethod.DeclaredAccessibility))
            {
                context.ReportDiagnostic(property.CreateDiagnostic(MakeMoreAccessibleRule, property.Name));
            }
        }
开发者ID:bkoelman,项目名称:roslyn-analyzers,代码行数:37,代码来源:PropertiesShouldNotBeWriteOnly.cs

示例15: AnalyzeSymbol

        private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol equatableType)
        {
            var namedType = context.Symbol as INamedTypeSymbol;
            if (namedType == null || !(namedType.TypeKind == TypeKind.Struct || namedType.TypeKind == TypeKind.Class))
            {
                return;
            }

            bool overridesObjectEquals = namedType.OverridesEquals();

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

            if (overridesObjectEquals && !implementsEquatable && namedType.TypeKind == TypeKind.Struct)
            {
                context.ReportDiagnostic(namedType.CreateDiagnostic(s_implementIEquatableDescriptor, namedType));
            }

            if (!overridesObjectEquals && implementsEquatable)
            {
                context.ReportDiagnostic(namedType.CreateDiagnostic(s_overridesObjectEqualsDescriptor, namedType));
            }
        }
开发者ID:bkoelman,项目名称:roslyn-analyzers,代码行数:27,代码来源:EquatableAnalyzer.cs


注:本文中的SymbolAnalysisContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。