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


C# ISymbol.Equals方法代码示例

本文整理汇总了C#中ISymbol.Equals方法的典型用法代码示例。如果您正苦于以下问题:C# ISymbol.Equals方法的具体用法?C# ISymbol.Equals怎么用?C# ISymbol.Equals使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ISymbol的用法示例。


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

示例1: HasCheckForNullThatReturns

 private static bool HasCheckForNullThatReturns(InvocationExpressionSyntax invocation, SemanticModel semanticModel, ISymbol symbol)
 {
     var method = invocation.FirstAncestorOfKind(SyntaxKind.MethodDeclaration) as MethodDeclarationSyntax;
     if (method != null && method.Body != null)
     {
         var ifs = method.Body.Statements.OfKind(SyntaxKind.IfStatement);
         foreach (IfStatementSyntax @if in ifs)
         {
             if ([email protected]?.IsKind(SyntaxKind.EqualsExpression) ?? true) continue;
             var equals = (BinaryExpressionSyntax)@if.Condition;
             if (equals.Left == null || equals.Right == null) continue;
             if (@if.GetLocation().SourceSpan.Start > invocation.GetLocation().SourceSpan.Start) return false;
             ISymbol identifierSymbol;
             if (equals.Right.IsKind(SyntaxKind.NullLiteralExpression) && equals.Left.IsKind(SyntaxKind.IdentifierName))
                 identifierSymbol = semanticModel.GetSymbolInfo(equals.Left).Symbol;
             else if (equals.Left.IsKind(SyntaxKind.NullLiteralExpression) && equals.Right.IsKind(SyntaxKind.IdentifierName))
                 identifierSymbol = semanticModel.GetSymbolInfo(equals.Right).Symbol;
             else continue;
             if (!symbol.Equals(identifierSymbol)) continue;
             if (@if.Statement == null) continue;
             if (@if.Statement.IsKind(SyntaxKind.Block))
             {
                 var ifBlock = (BlockSyntax)@if.Statement;
                 if (ifBlock.Statements.OfKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement).Any()) return true;
             }
             else
             {
                 if (@if.Statement.IsAnyKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement)) return true;
             }
         }
     }
     return false;
 }
开发者ID:julianosaless,项目名称:code-cracker,代码行数:33,代码来源:UseInvokeMethodToFireEventAnalyzer.cs

示例2: FindImplementationForAbstractMember

        public static ISymbol FindImplementationForAbstractMember(this INamedTypeSymbol type, ISymbol symbol)
        {
            if (symbol.IsAbstract)
            {
                return type.GetBaseTypesAndThis().SelectMany(t => t.GetMembers(symbol.Name))
                                                 .FirstOrDefault(s => symbol.Equals(GetOverriddenMember(s)));
            }

            return null;
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:10,代码来源:INamedTypeSymbolExtensions.cs

示例3: IsAccessed

        private bool IsAccessed(
            SemanticModel semanticModel,
            ISymbol outSymbol, 
            BlockSyntax enclosingBlockOfLocalStatement,
            LocalDeclarationStatementSyntax localStatement, 
            ArgumentSyntax argumentNode,
            CancellationToken cancellationToken)
        {
            var localStatementStart = localStatement.Span.Start;
            var argumentNodeStart = argumentNode.Span.Start;
            var variableName = outSymbol.Name;

            // Walk the block that the local is declared in looking for accesses.
            // We can ignore anything prior to the actual local declaration point,
            // and we only need to check up until we reach the out-argument.
            foreach (var descendentNode in enclosingBlockOfLocalStatement.DescendantNodes())
            {
                var descendentStart = descendentNode.Span.Start;
                if (descendentStart <= localStatementStart)
                {
                    // This node is before the local declaration.  Can ignore it entirely as it could
                    // not be an access to the local.
                    continue;
                }

                if (descendentStart >= argumentNodeStart)
                {
                    // We reached the out-var.  We can stop searching entirely.
                    break;
                }

                if (descendentNode.IsKind(SyntaxKind.IdentifierName))
                {
                    // See if this looks like an accessor to the local variable syntactically.
                    var identifierName = (IdentifierNameSyntax)descendentNode;
                    if (identifierName.Identifier.ValueText == variableName)
                    {
                        // Confirm that it is a access of the local.
                        var symbol = semanticModel.GetSymbolInfo(identifierName, cancellationToken).Symbol;
                        if (outSymbol.Equals(symbol))
                        {
                            // We definitely accessed the local before the out-argument.  We 
                            // can't inline this local.
                            return true;
                        }
                    }
                }
            }

            // No accesses detected
            return false;
        }
开发者ID:otawfik-ms,项目名称:roslyn,代码行数:52,代码来源:CSharpInlineDeclarationDiagnosticAnalyzer.cs

示例4: FlowsIntoTarget

        /// <summary>
        /// Returns true if the given symbol flows into the target symbol.
        /// </summary>
        /// <param name="symbol">Symbol</param>
        /// <param name="target">Target</param>
        /// <param name="syntaxNode">SyntaxNode</param>
        /// <param name="cfgNode">ControlFlowGraphNode</param>
        /// <param name="targetSyntaxNode">Target syntaxNode</param>
        /// <param name="targetCfgNode">Target controlFlowGraphNode</param>
        /// <returns>Boolean</returns>
        internal static bool FlowsIntoTarget(ISymbol symbol, ISymbol target, SyntaxNode syntaxNode,
            ControlFlowGraphNode cfgNode, SyntaxNode targetSyntaxNode, ControlFlowGraphNode targetCfgNode)
        {
            Dictionary<ISymbol, HashSet<ISymbol>> dataFlowMap = null;
            if (!targetCfgNode.Summary.DataFlowMap.TryGetMapForSyntaxNode(targetSyntaxNode,
                targetCfgNode, out dataFlowMap) || !dataFlowMap.ContainsKey(symbol))
            {
                return false;
            }

            if (symbol.Equals(target) && cfgNode.Summary.DataFlowMap.DoesSymbolReset(
                symbol, syntaxNode, cfgNode, targetSyntaxNode, targetCfgNode))
            {
                return false;
            }

            Dictionary<ISymbol, HashSet<ISymbol>> reachabilityMap = null;
            if (targetCfgNode.Summary.DataFlowMap.TryGetReachabilityMapForSyntaxNode(targetSyntaxNode,
                targetCfgNode, out reachabilityMap) && reachabilityMap.ContainsKey(symbol))
            {
                foreach (var field in reachabilityMap[symbol])
                {
                    foreach (var reference in dataFlowMap[field])
                    {
                        dataFlowMap[symbol].Add(reference);
                    }
                }
            }

            foreach (var reference in dataFlowMap[symbol])
            {
                if (reference.Equals(target))
                {
                    return true;
                }
            }

            if (dataFlowMap.ContainsKey(target))
            {
                foreach (var reference in dataFlowMap[target])
                {
                    if (!cfgNode.Summary.DataFlowMap.DoesSymbolReset(symbol, syntaxNode,
                        cfgNode, targetSyntaxNode, targetCfgNode))
                    {
                        if (reference.Equals(symbol))
                        {
                            return true;
                        }

                        foreach (var symbolRef in dataFlowMap[symbol])
                        {
                            if (reference.Equals(symbolRef))
                            {
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }
开发者ID:huangpf,项目名称:PSharp,代码行数:72,代码来源:DataFlowAnalysis.cs

示例5: MapRefToSymbol

        /// <summary>
        /// Maps the given reference to the given symbol.
        /// </summary>
        /// <param name="reference">Reference</param>
        /// <param name="symbol">Symbol</param>
        /// <param name="syntaxNode">SyntaxNode</param>
        /// <param name="cfgNode">CfgNode</param>
        /// <param name="markReset">Should mark symbol as reset</param>
        internal void MapRefToSymbol(ISymbol reference, ISymbol symbol, SyntaxNode syntaxNode,
            ControlFlowGraphNode cfgNode, bool markReset = true)
        {
            if (!this.Map.ContainsKey(cfgNode))
            {
                this.Map.Add(cfgNode, new Dictionary<SyntaxNode, Dictionary<ISymbol, HashSet<ISymbol>>>());
                this.Map[cfgNode].Add(syntaxNode, new Dictionary<ISymbol, HashSet<ISymbol>>());
            }
            else if (!this.Map[cfgNode].ContainsKey(syntaxNode))
            {
                this.Map[cfgNode].Add(syntaxNode, new Dictionary<ISymbol, HashSet<ISymbol>>());
            }

            HashSet<ISymbol> additionalRefs = new HashSet<ISymbol>();
            if (this.Map[cfgNode][syntaxNode].ContainsKey(reference))
            {
                foreach (var r in this.Map[cfgNode][syntaxNode][reference])
                {
                    if (!reference.Equals(r))
                    {
                        additionalRefs.Add(r);
                    }
                }
            }

            if (this.Map[cfgNode][syntaxNode].ContainsKey(symbol) && additionalRefs.Count > 0)
            {
                this.Map[cfgNode][syntaxNode][symbol] = new HashSet<ISymbol>();
            }
            else if (additionalRefs.Count > 0)
            {
                this.Map[cfgNode][syntaxNode].Add(symbol, new HashSet<ISymbol>());
            }
            else if (this.Map[cfgNode][syntaxNode].ContainsKey(symbol))
            {
                this.Map[cfgNode][syntaxNode][symbol] = new HashSet<ISymbol> { reference };
            }
            else
            {
                this.Map[cfgNode][syntaxNode].Add(symbol, new HashSet<ISymbol> { reference });
            }

            foreach (var r in additionalRefs)
            {
                this.Map[cfgNode][syntaxNode][symbol].Add(r);
            }

            if (markReset)
            {
                this.MarkSymbolReassignment(symbol, syntaxNode, cfgNode);
            }
        }
开发者ID:jerickmsft,项目名称:PSharp,代码行数:60,代码来源:DataFlowMap.cs

示例6: IsInterfaceImplementation

        private static bool IsInterfaceImplementation(ISymbol symbol)
        {
            var containingType = symbol.ContainingType;

            return containingType.AllInterfaces
                .SelectMany(interf => interf.GetMembers().OfType<IMethodSymbol>())
                .Any(interfaceMember => symbol.Equals(containingType.FindImplementationForInterfaceMember(interfaceMember)));
        }
开发者ID:OsirisTerje,项目名称:sonarlint-vs,代码行数:8,代码来源:MethodOrPropertyWithoutInstanceData.cs

示例7: GetRenamableReferenceLocationsAsync

            internal static async Task<IEnumerable<RenameLocation>> GetRenamableReferenceLocationsAsync(ISymbol referencedSymbol, ISymbol originalSymbol, ReferenceLocation location, Solution solution, CancellationToken cancellationToken)
            {
                var shouldIncludeSymbol = await ShouldIncludeSymbolAsync(referencedSymbol, originalSymbol, solution, true, cancellationToken).ConfigureAwait(false);
                if (!shouldIncludeSymbol)
                {
                    return SpecializedCollections.EmptyEnumerable<RenameLocation>();
                }

                // Implicit references are things like a foreach referencing GetEnumerator. We don't
                // want to consider those as part of the set
                if (location.IsImplicit)
                {
                    return SpecializedCollections.EmptyEnumerable<RenameLocation>();
                }

                var results = new List<RenameLocation>();

                // If we were originally naming an alias, then we'll only use the location if was
                // also bound through the alias
                if (originalSymbol.Kind == SymbolKind.Alias)
                {
                    if (originalSymbol.Equals(location.Alias))
                    {
                        results.Add(new RenameLocation(location, location.Document.Id));

                        // We also need to add the location of the alias
                        // itself
                        var aliasLocation = location.Alias.Locations.Single();
                        results.Add(new RenameLocation(aliasLocation, solution.GetDocument(aliasLocation.SourceTree).Id));
                    }
                }
                else
                {
                    // If we bound through an alias, we'll only rename if the alias's name matches
                    // the name of symbol it points to. We do this because it's common to see things
                    // like "using Foo = System.Foo" where people want to import a single type
                    // rather than a whole namespace of stuff.
                    if (location.Alias != null)
                    {
                        if (location.Alias.Name == referencedSymbol.Name)
                        {
                            results.Add(new RenameLocation(location.Location, location.Document.Id,
                                isCandidateLocation: location.IsCandidateLocation, isRenamableAliasUsage: true, isWrittenTo: location.IsWrittenTo));

                            // We also need to add the location of the alias itself
                            var aliasLocation = location.Alias.Locations.Single();
                            results.Add(new RenameLocation(aliasLocation, solution.GetDocument(aliasLocation.SourceTree).Id));
                        }
                    }
                    else
                    {
                        // The simple case, so just the single location and we're done
                        results.Add(new RenameLocation(
                            location.Location,
                            location.Document.Id,
                            isWrittenTo: location.IsWrittenTo,
                            isCandidateLocation: location.IsCandidateLocation,
                            isMethodGroupReference: location.IsCandidateLocation && location.CandidateReason == CandidateReason.MemberGroup,
                            isRenamableAccessor: await IsPropertyAccessorOrAnOverride(referencedSymbol, solution, cancellationToken).ConfigureAwait(false)));
                    }
                }

                return results;
            }
开发者ID:tralivali1234,项目名称:roslyn,代码行数:64,代码来源:RenameLocation.ReferenceProcessing.cs

示例8: ShouldIncludeSymbolAsync

            private static async Task<bool> ShouldIncludeSymbolAsync(
                ISymbol referencedSymbol, ISymbol originalSymbol, Solution solution, bool considerSymbolReferences, CancellationToken cancellationToken)
            {
                if (referencedSymbol.IsPropertyAccessor())
                {
                    return considerSymbolReferences;
                }

                if (referencedSymbol.Equals(originalSymbol))
                {
                    return true;
                }

                // Parameters of properties and methods can cascade to each other in
                // indexer scenarios.
                if (originalSymbol.Kind == SymbolKind.Parameter && referencedSymbol.Kind == SymbolKind.Parameter)
                {
                    return true;
                }

                // If the original symbol is a property, cascade to the backing field
                if (referencedSymbol.Kind == SymbolKind.Field && originalSymbol.Equals(((IFieldSymbol)referencedSymbol).AssociatedSymbol))
                {
                    return true;
                }

                // If the symbol doesn't actually exist in source, we never want to rename it
                if (referencedSymbol.IsImplicitlyDeclared)
                {
                    return considerSymbolReferences;
                }

                // We can cascade from members to other members only if the names match. The example
                // where the names might be different is explicit interface implementations in
                // Visual Basic and VB's identifiers are case insensitive. 
                // Do not cascade to symbols that are defined only in metadata.
                if (referencedSymbol.Kind == originalSymbol.Kind &&
                    string.Compare(TrimNameToAfterLastDot(referencedSymbol.Name), TrimNameToAfterLastDot(originalSymbol.Name), StringComparison.OrdinalIgnoreCase) == 0 &&
                    referencedSymbol.Locations.Any(loc => loc.IsInSource))
                {
                    return true;
                }

                // If the original symbol is an alias, then the referenced symbol will be where we
                // actually see references.
                if (originalSymbol.Kind == SymbolKind.Alias)
                {
                    var target = ((IAliasSymbol)originalSymbol).Target;

                    return target.TypeSwitch(
                        (INamedTypeSymbol nt) => nt.ConstructedFrom.Equals(referencedSymbol),
                        (INamespaceOrTypeSymbol s) => s.Equals(referencedSymbol));
                }

                // cascade from property accessor to property (someone in C# renames base.get_X, or the accessor override)
                if (await IsPropertyAccessorOrAnOverride(referencedSymbol, solution, cancellationToken).ConfigureAwait(false) ||
                    await IsPropertyAccessorOrAnOverride(originalSymbol, solution, cancellationToken).ConfigureAwait(false))
                {
                    return true;
                }

                if (referencedSymbol.ContainingSymbol != null &&
                    referencedSymbol.ContainingSymbol.Kind == SymbolKind.NamedType &&
                    ((INamedTypeSymbol)referencedSymbol.ContainingSymbol).TypeKind == TypeKind.Interface &&
                    !originalSymbol.ExplicitInterfaceImplementations().Any(s => s.Equals(referencedSymbol)))
                {
                    return true;
                }

                return false;
            }
开发者ID:tralivali1234,项目名称:roslyn,代码行数:71,代码来源:RenameLocation.ReferenceProcessing.cs

示例9: IsConditionThatChecksForNull

 private static bool IsConditionThatChecksForNull(ExpressionSyntax condition, SemanticModel semanticModel, ISymbol symbol, SyntaxKind binarySyntaxKind)
 {
     if (condition == null) return false;
     if (!condition.IsKind(binarySyntaxKind)) return false;
     var equals = (BinaryExpressionSyntax)condition;
     if (equals.Left == null || equals.Right == null) return false;
     ISymbol identifierSymbol;
     if (equals.Right.IsKind(SyntaxKind.NullLiteralExpression) && equals.Left.IsKind(SyntaxKind.IdentifierName))
         identifierSymbol = semanticModel.GetSymbolInfo(equals.Left).Symbol;
     else if (equals.Left.IsKind(SyntaxKind.NullLiteralExpression) && equals.Right.IsKind(SyntaxKind.IdentifierName))
         identifierSymbol = semanticModel.GetSymbolInfo(equals.Right).Symbol;
     else return false;
     if (symbol.Equals(identifierSymbol)) return true;
     return false;
 }
开发者ID:julianosaless,项目名称:code-cracker,代码行数:15,代码来源:UseInvokeMethodToFireEventAnalyzer.cs

示例10: IsImplementingAnInterfaceMember

        /// <summary>
        /// Returns whether or not a member is implementing an interface member.
        /// </summary>
        /// <remarks>
        /// This method does only check the interfaces the containing type is implementing directly.
        /// If a derived class is implementing an interface and this member is required for it
        /// this method will still return false.
        /// </remarks>
        /// <param name="memberSymbol">The member symbol that should be analyzed.</param>
        /// <returns>true if the member is implementing an interface member, otherwise false.</returns>
        internal static bool IsImplementingAnInterfaceMember(ISymbol memberSymbol)
        {
            if (memberSymbol.IsStatic)
            {
                return false;
            }

            IMethodSymbol methodSymbol;
            IPropertySymbol propertySymbol;
            IEventSymbol eventSymbol;
            bool isImplementingExplicitly;

            // Only methods, properties and events can implement an interface member
            if ((methodSymbol = memberSymbol as IMethodSymbol) != null)
            {
                // Check if the member is implementing an interface explicitly
                isImplementingExplicitly = methodSymbol.ExplicitInterfaceImplementations.Any();
            }
            else if ((propertySymbol = memberSymbol as IPropertySymbol) != null)
            {
                // Check if the member is implementing an interface explicitly
                isImplementingExplicitly = propertySymbol.ExplicitInterfaceImplementations.Any();
            }
            else if ((eventSymbol = memberSymbol as IEventSymbol) != null)
            {
                // Check if the member is implementing an interface explicitly
                isImplementingExplicitly = eventSymbol.ExplicitInterfaceImplementations.Any();
            }
            else
            {
                return false;
            }

            if (isImplementingExplicitly)
            {
                return true;
            }

            var typeSymbol = memberSymbol.ContainingType;

            return typeSymbol != null && typeSymbol.AllInterfaces
                .SelectMany(m => m.GetMembers(memberSymbol.Name))
                .Select(typeSymbol.FindImplementationForInterfaceMember)
                .Any(x => memberSymbol.Equals(x));
        }
开发者ID:nvincent,项目名称:StyleCopAnalyzers,代码行数:55,代码来源:NamedTypeHelpers.cs

示例11: IsInsideANullCheck

 private static bool IsInsideANullCheck(InvocationExpressionSyntax invocation, SemanticModel semanticModel, ISymbol symbol)
 {
     var ifs = invocation.Ancestors().OfType<IfStatementSyntax>();
     foreach (IfStatementSyntax @if in ifs)
     {
         if ([email protected]?.IsKind(SyntaxKind.NotEqualsExpression) ?? true) continue;
         var equals = (BinaryExpressionSyntax)@if.Condition;
         if (equals.Left == null || equals.Right == null) continue;
         ISymbol identifierSymbol;
         if (equals.Right.IsKind(SyntaxKind.NullLiteralExpression) && equals.Left.IsKind(SyntaxKind.IdentifierName))
             identifierSymbol = semanticModel.GetSymbolInfo(equals.Left).Symbol;
         else if (equals.Left.IsKind(SyntaxKind.NullLiteralExpression) && equals.Right.IsKind(SyntaxKind.IdentifierName))
             identifierSymbol = semanticModel.GetSymbolInfo(equals.Right).Symbol;
         else continue;
         if (symbol.Equals(identifierSymbol)) return true;
     }
     return false;
 }
开发者ID:jhancock93,项目名称:code-cracker,代码行数:18,代码来源:UseInvokeMethodToFireEventAnalyzer.cs

示例12: WouldCauseDefiniteAssignmentErrors

        private bool WouldCauseDefiniteAssignmentErrors(
            SemanticModel semanticModel, VariableDeclaratorSyntax localDeclarator, 
            BlockSyntax enclosingBlock, ISymbol outSymbol, CancellationToken cancellationToken)
        {
            // See if we have something like:
            //
            //      int i = 0;
            //      if (Foo() || Bar(out i))
            //      {
            //          Console.WriteLine(i);
            //      }
            //
            // In this case, inlining the 'i' would cause it to longer be definitely
            // assigned in the WriteLine invocation.

            if (localDeclarator.Initializer == null)
            {
                // Don't need to examine this unless the variable has an initializer.
                return false;
            }

            // Find all the current read-references to the local.
            var query = from t in enclosingBlock.DescendantTokens()
                        where t.Kind() == SyntaxKind.IdentifierToken
                        where t.ValueText == outSymbol.Name
                        let id = t.Parent as IdentifierNameSyntax
                        where id != null
                        where !id.IsOnlyWrittenTo()
                        let symbol = semanticModel.GetSymbolInfo(id).GetAnySymbol()
                        where outSymbol.Equals(symbol)
                        select id;

            var references = query.ToImmutableArray<SyntaxNode>();

            var root = semanticModel.SyntaxTree.GetCompilationUnitRoot(cancellationToken);

            // Ensure we can track the references and the local variable as we make edits
            // to the tree.
            var rootWithTrackedNodes = root.TrackNodes(references.Concat(localDeclarator).Concat(enclosingBlock));

            // Now, take the local variable and remove it's initializer.  Then go to all
            // the locations where we read from it.  If they're definitely assigned, then
            // that means the out-var did it's work and assigned the variable across all
            // paths. If it's not definitely assigned, then we can't inline this variable.
            var currentLocalDeclarator = rootWithTrackedNodes.GetCurrentNode(localDeclarator);
            var rootWithoutInitializer = rootWithTrackedNodes.ReplaceNode(
                currentLocalDeclarator,
                currentLocalDeclarator.WithInitializer(null));

            // Fork the compilation so we can do this analysis.
            var newCompilation = semanticModel.Compilation.ReplaceSyntaxTree(
                root.SyntaxTree, rootWithoutInitializer.SyntaxTree);
            var newSemanticModel = newCompilation.GetSemanticModel(rootWithoutInitializer.SyntaxTree);

            // NOTE: there is no current compiler API to determine if a variable is definitely
            // assigned or not.  So, for now, we just get diagnostics for this block and see if
            // we get any definite assigment errors where we have a reference to the symbol. If
            // so, then we don't offer the fix.

            var currentBlock = rootWithoutInitializer.GetCurrentNode(enclosingBlock);
            var diagnostics = newSemanticModel.GetDiagnostics(currentBlock.Span, cancellationToken);

            var diagnosticSpans = diagnostics.Where(d => d.Id == CS0165)
                                             .Select(d => d.Location.SourceSpan)
                                             .Distinct();

            var newReferenceSpans = rootWithoutInitializer.GetCurrentNodes<SyntaxNode>(references)
                                                          .Select(n => n.Span)
                                                          .Distinct();

            return diagnosticSpans.Intersect(newReferenceSpans).Any();
        }
开发者ID:TyOverby,项目名称:roslyn,代码行数:72,代码来源:CSharpInlineDeclarationDiagnosticAnalyzer.cs

示例13: DoesBlockContainCertainInitializer

        /// <summary>
        /// This method can be used to determine if the specified block of
        /// statements contains an initializer for the specified symbol.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="symbol">The symbol.</param>
        /// <param name="statements">The statements.</param>
        /// <returns>
        /// The initializer state found
        /// </returns>
        /// <remarks>
        /// Code blocks that might not always be called are:
        /// - An if or else statement.
        /// - The body of a for, while or for-each loop.
        /// - Switch statements
        ///
        /// The following exceptions are taken into account:
        /// - If both if and else statements contain a certain initialization.
        /// - If all cases in a switch contain a certain initialization (this means a default case must exist as well).
        ///
        /// Please note that this is a recursive function so we can check a block of code in an if statement for example.
        /// </remarks>
        private static InitializerState DoesBlockContainCertainInitializer(SyntaxNodeAnalysisContext context, ISymbol symbol, IEnumerable<StatementSyntax> statements)
        {
            // Keep track of the current initializer state. This can only be None
            // or Initializer, WayToSkipInitializer will always be returned immediately.
            // Only way to go back from Initializer to None is if there is an assignment
            // to null after a previous assignment to a non-null value.
            var currentState = InitializerState.None;

            foreach (var statement in statements)
            {
                if (statement.IsKind(SyntaxKind.ReturnStatement) && currentState == InitializerState.None)
                {
                    return InitializerState.WayToSkipInitializer;
                }
                else if (statement.IsKind(SyntaxKind.Block))
                {
                    var blockResult = DoesBlockContainCertainInitializer(context, symbol, ((BlockSyntax)statement).Statements);
                    if (CanSkipInitializer(blockResult, currentState))
                        return InitializerState.WayToSkipInitializer;
                    if (blockResult == InitializerState.Initializer)
                        currentState = blockResult;
                }
                else if (statement.IsKind(SyntaxKind.UsingStatement))
                {
                    var blockResult = DoesBlockContainCertainInitializer(context, symbol, new[] { ((UsingStatementSyntax)statement).Statement });
                    if (CanSkipInitializer(blockResult, currentState))
                        return InitializerState.WayToSkipInitializer;
                    if (blockResult == InitializerState.Initializer)
                        currentState = blockResult;
                }
                else if (statement.IsKind(SyntaxKind.ExpressionStatement))
                {
                    var expression = ((ExpressionStatementSyntax)statement).Expression;
                    if (expression.IsKind(SyntaxKind.SimpleAssignmentExpression))
                    {
                        var assignmentExpression = (AssignmentExpressionSyntax)expression;
                        var identifier = assignmentExpression.Left;
                        if (identifier != null)
                        {
                            var right = assignmentExpression.Right;
                            if (right != null)
                            {
                                if (right.IsKind(SyntaxKind.NullLiteralExpression))
                                    currentState = InitializerState.None;
                                else if (symbol.Equals(context.SemanticModel.GetSymbolInfo(identifier).Symbol))
                                    currentState = InitializerState.Initializer;
                            }
                        }
                    }
                }
                else if (statement.IsKind(SyntaxKind.SwitchStatement))
                {
                    var switchStatement = (SwitchStatementSyntax)statement;
                    if (switchStatement.Sections.Any(s => s.Labels.Any(l => l.IsKind(SyntaxKind.DefaultSwitchLabel))))
                    {
                        var sectionInitializerStates = switchStatement.Sections.Select(s => DoesBlockContainCertainInitializer(context, symbol, s.Statements)).ToList();
                        if (sectionInitializerStates.All(sectionInitializerState => sectionInitializerState == InitializerState.Initializer))
                            currentState = InitializerState.Initializer;
                        else if (sectionInitializerStates.Any(sectionInitializerState => CanSkipInitializer(sectionInitializerState, currentState)))
                            return InitializerState.WayToSkipInitializer;
                    }
                }
                else if (statement.IsKind(SyntaxKind.IfStatement))
                {
                    var ifStatement = (IfStatementSyntax)statement;

                    var ifResult = DoesBlockContainCertainInitializer(context, symbol, new[] { ifStatement.Statement });
                    if (ifStatement.Else != null)
                    {
                        var elseResult = DoesBlockContainCertainInitializer(context, symbol, new[] { ifStatement.Else.Statement });

                        if (ifResult == InitializerState.Initializer && elseResult == InitializerState.Initializer)
                            currentState = InitializerState.Initializer;
                        if (CanSkipInitializer(elseResult, currentState))
                            return InitializerState.WayToSkipInitializer;
                    }
                    if (CanSkipInitializer(ifResult, currentState))
                    {
//.........这里部分代码省略.........
开发者ID:michaelsync,项目名称:code-cracker,代码行数:101,代码来源:CopyEventToVariableBeforeFireAnalyzer.cs

示例14: CheckDefiniteAssignment

        private void CheckDefiniteAssignment(
            SemanticModel semanticModel, ISymbol localVariable, SyntaxNode node,
            out bool isAssigned, out bool isAccessedBeforeAssignment,
            CancellationToken cancellationToken)
        {
            if (node != null)
            {
                foreach (var id in node.DescendantNodes().OfType<IdentifierNameSyntax>())
                {
                    var symbol = semanticModel.GetSymbolInfo(id, cancellationToken).GetAnySymbol();
                    if (localVariable.Equals(symbol))
                    {
                        isAssigned = id.IsOnlyWrittenTo();
                        isAccessedBeforeAssignment = !isAssigned;
                        return;
                    }
                }
            }

            isAssigned = false;
            isAccessedBeforeAssignment = false;
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:22,代码来源:CSharpAsAndNullCheckDiagnosticAnalyzer.cs

示例15: IsAmbiguous

            bool IsAmbiguous(ISymbol typeSymbol, SyntaxNode initializer, ITypeSymbol initializerSymbol)
            {
                if (!typeSymbol.Equals(initializerSymbol))
                {
                    // An implicit conversion or something similar is at play - using an implicit declaration will
                    // have a semantic change.  Consequently, we consider the declaration ambiguous.
                    return true;
                }

                if (initializer is LiteralExpressionSyntax)
                {
                    // A literal initializer is not ambiguous per C# style guidelines.
                    return false;
                }

                var ambiguityDetector = new InitializerAmbiguityDetector(this.semanticModel, typeSymbol);
                ambiguityDetector.Visit(initializer);
                return ambiguityDetector.IsAmbiguous;
            }
开发者ID:nicholjy,项目名称:stylize,代码行数:19,代码来源:AmbiguousImplicitVariableStyleRule.cs


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