Пример #1
0
        public void RemoveDuplicates()
        {
            var set = PooledHashSet <T> .GetInstance();

            int j = 0;

            for (int i = 0; i < Count; i++)
            {
                if (set.Add(this[i]))
                {
                    this[j] = this[i];
                    j++;
                }
            }

            Clip(j);
            set.Free();
        }
Пример #2
0
            public static Analysis Analyze(
                BoundNode node,
                MethodSymbol method,
                int topLevelMethodOrdinal,
                MethodSymbol substitutedSourceMethod,
                VariableSlotAllocator slotAllocatorOpt,
                TypeCompilationState compilationState,
                ArrayBuilder <ClosureDebugInfo> closureDebugInfo,
                DiagnosticBag diagnostics
                )
            {
                var methodsConvertedToDelegates = PooledHashSet <MethodSymbol> .GetInstance();

                var scopeTree = ScopeTreeBuilder.Build(
                    node,
                    method,
                    methodsConvertedToDelegates,
                    diagnostics
                    );

                Debug.Assert(scopeTree != null);

                var analysis = new Analysis(
                    scopeTree,
                    methodsConvertedToDelegates,
                    method,
                    topLevelMethodOrdinal,
                    slotAllocatorOpt,
                    compilationState
                    );

                analysis.MakeAndAssignEnvironments();
                analysis.ComputeLambdaScopesAndFrameCaptures();
                if (
                    compilationState.Compilation.Options.OptimizationLevel
                    == OptimizationLevel.Release
                    )
                {
                    // This can affect when a variable is in scope whilst debugging, so only do this in release mode.
                    analysis.MergeEnvironments();
                }
                analysis.InlineThisOnlyEnvironments();
                return(analysis);
            }
Пример #3
0
        /// <summary>
        /// Return the constant value dependencies. Compute the dependencies
        /// if necessary by evaluating the constant value but only persist the
        /// constant value if there were no dependencies. (If there are dependencies,
        /// the constant value will be re-evaluated after evaluating dependencies.)
        /// </summary>
        internal ImmutableHashSet <SourceFieldSymbolWithSyntaxReference> GetConstantValueDependencies(bool earlyDecodingWellKnownAttributes)
        {
            var value = this.GetLazyConstantValue(earlyDecodingWellKnownAttributes);

            if (value != Microsoft.CodeAnalysis.ConstantValue.Unset)
            {
                // Constant value already determined. No need to
                // compute dependencies since the constant values
                // of all dependencies should be evaluated as well.
                return(ImmutableHashSet <SourceFieldSymbolWithSyntaxReference> .Empty);
            }

            ImmutableHashSet <SourceFieldSymbolWithSyntaxReference> dependencies;
            var builder = PooledHashSet <SourceFieldSymbolWithSyntaxReference> .GetInstance();

            var diagnostics = DiagnosticBag.GetInstance();

            value = MakeConstantValue(builder, earlyDecodingWellKnownAttributes, diagnostics);

            // Only persist if there are no dependencies and the calculation
            // completed successfully. (We could probably persist in other
            // scenarios but it's probably not worth the added complexity.)
            if ((builder.Count == 0) &&
                (value != null) &&
                !value.IsBad &&
                (value != Microsoft.CodeAnalysis.ConstantValue.Unset) &&
                diagnostics.IsEmptyWithoutResolution)
            {
                this.SetLazyConstantValue(
                    value,
                    earlyDecodingWellKnownAttributes,
                    diagnostics,
                    startsCycle: false);
                dependencies = ImmutableHashSet <SourceFieldSymbolWithSyntaxReference> .Empty;
            }
            else
            {
                dependencies = ImmutableHashSet <SourceFieldSymbolWithSyntaxReference> .Empty.Union(builder);
            }

            diagnostics.Free();
            builder.Free();
            return(dependencies);
        }
Пример #4
0
        protected override TAnalysisData GetMergedAnalysisDataForPossibleThrowingOperation(TAnalysisData?existingData, IOperation operation)
        {
            // Get tracked entities.
            using var entitiesBuilder = PooledHashSet <AnalysisEntity> .GetInstance();

            AddTrackedEntities(entitiesBuilder);

            // Only non-child entities are tracked for now.
            var resultAnalysisData = GetTrimmedCurrentAnalysisData(entitiesBuilder.Where(e => !e.IsChildOrInstanceMember && HasAbstractValue(e)));

            if (existingData != null)
            {
                var mergedAnalysisData = MergeAnalysisData(resultAnalysisData, existingData);
                resultAnalysisData.Dispose();
                resultAnalysisData = mergedAnalysisData;
            }

            return(resultAnalysisData);
        }
Пример #5
0
            public void MergeThrowLocations(BoundBlockWithExceptions block)
            {
                foreach (var item in block.ThrowLocations)
                {
                    var throwType = item.Key;
                    PooledHashSet <SyntaxNode> nodes;
                    if (!ThrowLocations.TryGetValue(throwType, out nodes))
                    {
                        nodes = PooledHashSet <SyntaxNode> .GetInstance();

                        ThrowLocations.Add(throwType, nodes);
                    }

                    foreach (var syntax in item.Value)
                    {
                        nodes.Add(syntax);
                    }
                }
            }
            private void ReportInitializedNotUsedNotInitializedUsedLocalVars(
                CodeBlockAnalysisContext context)
            {
                PooledHashSet <IdentifierNameSyntax> instance1 = PooledHashSet <IdentifierNameSyntax> .GetInstance();

                PooledHashSet <IdentifierNameSyntax> instance2 = PooledHashSet <IdentifierNameSyntax> .GetInstance();

                try
                {
                    this.CollectInitializedNotUsedNotInitializedUsedLocalVars((HashSet <IdentifierNameSyntax>)instance1, (HashSet <IdentifierNameSyntax>)instance2);
                    VariableInitializationUsageAnalyzer.ReportInitializedNotUsedVariables(new Action <Diagnostic>(context.ReportDiagnostic), instance1);
                    VariableInitializationUsageAnalyzer.ReportNotInitializedVariables(new Action <Diagnostic>(context.ReportDiagnostic), instance2);
                }
                finally
                {
                    instance1.Free();
                    instance2.Free();
                }
            }
Пример #7
0
        protected sealed override void StopTrackingDataForParameters(ImmutableDictionary <IParameterSymbol, AnalysisEntity> parameterEntities)
        {
            if (!parameterEntities.IsEmpty)
            {
                using var allEntities = PooledHashSet <AnalysisEntity> .GetInstance();

                AddTrackedEntities(allEntities);

                foreach (var(parameter, parameterEntity) in parameterEntities)
                {
                    StopTrackingDataForEntity(parameterEntity, CurrentAnalysisData, allEntities);

                    if (parameter.IsParams)
                    {
                        StopTrackingDataForParamArrayParameterIndices(parameterEntity, CurrentAnalysisData, allEntities);
                    }
                }
            }
        }
Пример #8
0
            protected override CopyAnalysisData GetTrimmedCurrentAnalysisData(IEnumerable <AnalysisEntity> withEntities)
            {
                using var processedEntities = PooledHashSet <AnalysisEntity> .GetInstance();

                var analysisData = new CopyAnalysisData();

                foreach (var entity in withEntities)
                {
                    if (processedEntities.Add(entity))
                    {
                        var copyValue = GetAbstractValue(entity);
                        analysisData.SetAbstactValueForEntities(copyValue, entityBeingAssigned: null);
                        processedEntities.AddRange(copyValue.AnalysisEntities);
                    }
                }

                AssertValidCopyAnalysisData(analysisData);
                return(analysisData);
            }
Пример #9
0
        private static PooledDictionary<TNode, int> PredecessorCounts<TNode>(
            IEnumerable<TNode> nodes,
            Func<TNode, ImmutableArray<TNode>> successors,
            out ImmutableArray<TNode> allNodes)
        {
            var predecessorCounts = PooledDictionary<TNode, int>.GetInstance();
            var counted = PooledHashSet<TNode>.GetInstance();
            var toCount = ArrayBuilder<TNode>.GetInstance();
            var allNodesBuilder = ArrayBuilder<TNode>.GetInstance();
            toCount.AddRange(nodes);
            while (toCount.Count != 0)
            {
                var n = toCount.Pop();
                if (!counted.Add(n))
                {
                    continue;
                }

                allNodesBuilder.Add(n);
                if (!predecessorCounts.ContainsKey(n))
                {
                    predecessorCounts.Add(n, 0);
                }

                foreach (var succ in successors(n))
                {
                    toCount.Push(succ);
                    if (predecessorCounts.TryGetValue(succ, out int succPredecessorCount))
                    {
                        predecessorCounts[succ] = succPredecessorCount + 1;
                    }
                    else
                    {
                        predecessorCounts.Add(succ, 1);
                    }
                }
            }

            counted.Free();
            toCount.Free();
            allNodes = allNodesBuilder.ToImmutableAndFree();
            return predecessorCounts;
        }
        public void UpdateAddressSharedEntitiesForParameter(IParameterSymbol parameter, AnalysisEntity analysisEntity, ArgumentInfo<TAbstractAnalysisValue> assignedValueOpt)
        {
            if (parameter.RefKind != RefKind.None &&
                assignedValueOpt?.AnalysisEntityOpt != null)
            {
                var addressSharedEntities = ComputeAddressSharedEntities();
                var isReferenceCopy = !addressSharedEntities.Any(a => a.Type.IsValueType);
                var copyValue = new CopyAbstractValue(addressSharedEntities, isReferenceCopy);
                foreach (var entity in copyValue.AnalysisEntities)
                {
                    _addressSharedEntitiesBuilder[entity] = copyValue;
                }
            }

            ImmutableHashSet<AnalysisEntity> ComputeAddressSharedEntities()
            {
                var builder = PooledHashSet<AnalysisEntity>.GetInstance();
                AddIfHasKnownInstanceLocation(analysisEntity, builder);
                AddIfHasKnownInstanceLocation(assignedValueOpt.AnalysisEntityOpt, builder);

                // We need to handle multiple ref/out parameters passed the same location.
                // For example, "M(ref a, ref a);"
                if (_addressSharedEntitiesBuilder.TryGetValue(assignedValueOpt.AnalysisEntityOpt, out var existingValue))
                {
                    foreach (var entity in existingValue.AnalysisEntities)
                    {
                        AddIfHasKnownInstanceLocation(entity, builder);
                    }
                }

                // Also handle case where the passed in argument is also a ref/out parameter and has address shared entities.
                if (_addressSharedEntitiesBuilder.TryGetValue(analysisEntity, out existingValue))
                {
                    foreach (var entity in existingValue.AnalysisEntities)
                    {
                        AddIfHasKnownInstanceLocation(entity, builder);
                    }
                }

                Debug.Assert(builder.All(e => !e.HasUnknownInstanceLocation));
                return builder.ToImmutableAndFree();
            }
Пример #11
0
        static SqlSinks()
        {
            var sinkInfosBuilder = PooledHashSet <SinkInfo> .GetInstance();

            sinkInfosBuilder.AddSinkInfo(
                WellKnownTypeNames.SystemDataIDbCommand,
                SinkKind.Sql,
                isInterface: true,
                isAnyStringParameterInConstructorASink: true,
                sinkProperties: new string[] {
                "CommandText",
            },
                sinkMethodParameters: null);

            sinkInfosBuilder.AddSinkInfo(
                WellKnownTypeNames.SystemDataIDataAdapter,
                SinkKind.Sql,
                isInterface: true,
                isAnyStringParameterInConstructorASink: true,
                sinkProperties: null,
                sinkMethodParameters: null);

            sinkInfosBuilder.AddSinkInfo(
                WellKnownTypeNames.SystemWebUIWebControlsSqlDataSource,
                SinkKind.Sql,
                isInterface: false,
                isAnyStringParameterInConstructorASink: false,
                sinkProperties: new string[] {
                "ConnectionString",
                "DeleteCommand",
                "InsertCommand",
                "SelectCommand",
                "UpdateCommand",
            },
                sinkMethodParameters: null);
            sinkInfosBuilder.AddSinkInfo(
                WellKnownTypeNames.MicrosoftEntityFrameworkCoreRelationalQueryableExtensions,
                SinkKind.Sql,
                isInterface: false,
                isAnyStringParameterInConstructorASink: false,
                sinkProperties: null,
                sinkMethodParameters: new[] {
Пример #12
0
            public override (CopyAbstractValue Value, PredicateValueKind PredicateValueKind)? GetReturnValueAndPredicateKind()
            {
                // Filter out all the local symbol and flow capture entities from the return value for interprocedural analysis.
                var returnValueAndPredicateKind = base.GetReturnValueAndPredicateKind();

                if (returnValueAndPredicateKind.HasValue &&
                    returnValueAndPredicateKind.Value.Value.Kind.IsKnown() &&
                    DataFlowAnalysisContext.InterproceduralAnalysisData != null)
                {
                    using var entitiesToFilterBuilder = PooledHashSet <AnalysisEntity> .GetInstance();

                    var copyValue         = returnValueAndPredicateKind.Value.Value;
                    var copyValueEntities = copyValue.AnalysisEntities;

                    foreach (var entity in copyValueEntities)
                    {
                        if (ShouldStopTrackingEntityAtExit(entity))
                        {
                            // Stop tracking entity that is now out of scope.
                            entitiesToFilterBuilder.Add(entity);

                            // Additionally, stop tracking all the child entities if the entity type has value copy semantics.
                            if (entity.Type.HasValueCopySemantics())
                            {
                                var childEntities = copyValueEntities.Where(e => IsChildAnalysisEntity(e, ancestorEntity: entity));
                                entitiesToFilterBuilder.AddRange(childEntities);
                            }
                        }
                    }

                    if (entitiesToFilterBuilder.Count > 0)
                    {
                        copyValue = entitiesToFilterBuilder.Count == copyValueEntities.Count ?
                                    CopyAbstractValue.Unknown :
                                    copyValue.WithEntitiesRemoved(entitiesToFilterBuilder);
                    }

                    return(copyValue, returnValueAndPredicateKind.Value.PredicateValueKind);
                }

                return(returnValueAndPredicateKind);
            }
Пример #13
0
        /// <summary>
        /// IsManagedType is simple for most named types:
        ///     enums are not managed;
        ///     non-enum, non-struct named types are managed;
        ///     generic types and their nested types are managed;
        ///     type parameters are managed;
        ///     all special types have spec'd values (basically, (non-string) primitives) are not managed;
        ///
        /// Only structs are complicated, because the definition is recursive.  A struct type is managed
        /// if one of its instance fields is managed.  Unfortunately, this can result in infinite recursion.
        /// If the closure is finite, and we don't find anything definitely managed, then we return true.
        /// If the closure is infinite, we disregard all but a representative of any expanding cycle.
        ///
        /// Intuitively, this will only return true if there's a specific type we can point to that is would
        /// be managed even if it had no fields.  e.g. struct S { S s; } is not managed, but struct S { S s; object o; }
        /// is because we can point to object.
        /// </summary>
        internal static bool IsManagedType(NamedTypeSymbol type)
        {
            // If this is a type with an obvious answer, return quickly.
            switch (IsManagedTypeHelper(type))
            {
            case ThreeState.True:
                return(true);

            case ThreeState.False:
                return(false);
            }

            // Otherwise, we have to build and inspect the closure of depended-upon types.
            var hs = PooledHashSet <Symbol> .GetInstance();

            bool result = DependsOnDefinitelyManagedType(type, hs);

            hs.Free();
            return(result);
        }
        private GlobalFlowStateAnalysisValueSet WithRootParent(GlobalFlowStateAnalysisValueSet newRoot)
        {
            Debug.Assert(Kind == GlobalFlowStateAnalysisValueSetKind.Known);

            var newHeight = Height + newRoot.Height + 1;

            if (Parents.IsEmpty)
            {
                return(new GlobalFlowStateAnalysisValueSet(AnalysisValues, ImmutableHashSet.Create(newRoot), newHeight, GlobalFlowStateAnalysisValueSetKind.Known));
            }

            using var parentsBuilder = PooledHashSet <GlobalFlowStateAnalysisValueSet> .GetInstance();

            foreach (var parent in Parents)
            {
                parentsBuilder.Add(parent.WithRootParent(newRoot));
            }

            return(new GlobalFlowStateAnalysisValueSet(AnalysisValues, parentsBuilder.ToImmutable(), newHeight, GlobalFlowStateAnalysisValueSetKind.Known));
        }
        private FlightEnabledAbstractValue WithRootParent(FlightEnabledAbstractValue newRoot)
        {
            Debug.Assert(Kind == FlightEnabledAbstractValueKind.Known);

            var newHeight = Height + newRoot.Height + 1;

            if (Parents.IsEmpty)
            {
                return(new FlightEnabledAbstractValue(EnabledFlights, ImmutableHashSet.Create(newRoot), newHeight, FlightEnabledAbstractValueKind.Known));
            }

            using var parentsBuilder = PooledHashSet <FlightEnabledAbstractValue> .GetInstance();

            foreach (var parent in Parents)
            {
                parentsBuilder.Add(parent.WithRootParent(newRoot));
            }

            return(new FlightEnabledAbstractValue(EnabledFlights, parentsBuilder.ToImmutable(), newHeight, FlightEnabledAbstractValueKind.Known));
        }
Пример #16
0
        internal static BindingDiagnosticBag GetInstance(bool withDiagnostics, bool withDependencies)
        {
            if (withDiagnostics)
            {
                if (withDependencies)
                {
                    return(GetInstance());
                }

                return(new BindingDiagnosticBag(DiagnosticBag.GetInstance()));
            }
            else if (withDependencies)
            {
                return(new BindingDiagnosticBag(diagnosticBag: null, PooledHashSet <AssemblySymbol> .GetInstance()));
            }
            else
            {
                return(Discarded);
            }
        }
Пример #17
0
        private static ImmutableHashSet <INamedTypeSymbol> GetTypesToIgnore(Compilation compilation)
        {
            var builder = PooledHashSet <INamedTypeSymbol> .GetInstance();

            var xmlWriter = WellKnownTypes.XmlWriter(compilation);

            if (xmlWriter != null)
            {
                builder.Add(xmlWriter);
            }

            var webUILiteralControl = WellKnownTypes.WebUILiteralControl(compilation);

            if (webUILiteralControl != null)
            {
                builder.Add(webUILiteralControl);
            }

            var unitTestingAssert = WellKnownTypes.UnitTestingAssert(compilation);

            if (unitTestingAssert != null)
            {
                builder.Add(unitTestingAssert);
            }

            var unitTestingCollectionAssert = WellKnownTypes.UnitTestingCollectionAssert(compilation);

            if (unitTestingCollectionAssert != null)
            {
                builder.Add(unitTestingCollectionAssert);
            }

            var unitTestingCollectionStringAssert = WellKnownTypes.UnitTestingCollectionStringAssert(compilation);

            if (unitTestingCollectionStringAssert != null)
            {
                builder.Add(unitTestingCollectionStringAssert);
            }

            return(builder.ToImmutableAndFree());
        }
        public static TBlockAnalysisData Run(ControlFlowGraph controlFlowGraph, DataFlowAnalyzer <TBlockAnalysisData> analyzer, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var blocks = controlFlowGraph.Blocks;
            var continueDispatchAfterFinally = PooledDictionary <ControlFlowRegion, bool> .GetInstance();

            var dispatchedExceptionsFromRegions = PooledHashSet <ControlFlowRegion> .GetInstance();

            var firstBlockOrdinal = 0;
            var lastBlockOrdinal  = blocks.Length - 1;

            var unreachableBlocksToVisit = ArrayBuilder <BasicBlock> .GetInstance();

            if (analyzer.AnalyzeUnreachableBlocks)
            {
                for (var i = firstBlockOrdinal; i <= lastBlockOrdinal; i++)
                {
                    if (!blocks[i].IsReachable)
                    {
                        unreachableBlocksToVisit.Add(blocks[i]);
                    }
                }
            }

            var initialAnalysisData = analyzer.GetCurrentAnalysisData(blocks[0]);

            var result = RunCore(blocks, analyzer, firstBlockOrdinal, lastBlockOrdinal,
                                 initialAnalysisData,
                                 unreachableBlocksToVisit,
                                 outOfRangeBlocksToVisit: null,
                                 continueDispatchAfterFinally,
                                 dispatchedExceptionsFromRegions,
                                 cancellationToken);

            Debug.Assert(unreachableBlocksToVisit.Count == 0);
            unreachableBlocksToVisit.Free();
            continueDispatchAfterFinally.Free();
            dispatchedExceptionsFromRegions.Free();
            return(result);
        }
        private static ImmutableHashSet <INamedTypeSymbol> GetTypesToIgnore(Compilation compilation)
        {
            var builder = PooledHashSet <INamedTypeSymbol> .GetInstance();

            var xmlWriter = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlWriter);

            if (xmlWriter != null)
            {
                builder.Add(xmlWriter);
            }

            var webUILiteralControl = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebUILiteralControl);

            if (webUILiteralControl != null)
            {
                builder.Add(webUILiteralControl);
            }

            var unitTestingAssert = compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert);

            if (unitTestingAssert != null)
            {
                builder.Add(unitTestingAssert);
            }

            var unitTestingCollectionAssert = compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert);

            if (unitTestingCollectionAssert != null)
            {
                builder.Add(unitTestingCollectionAssert);
            }

            var unitTestingCollectionStringAssert = compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert);

            if (unitTestingCollectionStringAssert != null)
            {
                builder.Add(unitTestingCollectionStringAssert);
            }

            return(builder.ToImmutableAndFree());
        }
            private void ComputeLambdaScopesAndFrameCaptures()
            {
                VisitNestedFunctions(ScopeTree, (scope, function) =>
                {
                    if (function.CapturedEnvironments.Count > 0)
                    {
                        var capturedEnvs = PooledHashSet <ClosureEnvironment> .GetInstance();
                        capturedEnvs.AddAll(function.CapturedEnvironments);

                        // Find the nearest captured class environment, if one exists
                        var curScope = scope;
                        while (curScope != null)
                        {
                            var env = curScope.DeclaredEnvironment;
                            if (!(env is null) && capturedEnvs.Remove(env) && !env.IsStruct)
                            {
                                function.ContainingEnvironmentOpt = env;
                                break;
                            }
                            curScope = curScope.Parent;
                        }
Пример #21
0
                public void TrackAssignmentWithAbstractLocation(
                    IAssignmentOperation assignmentOperation,
                    AbstractLocation abstractLocation)
                {
                    if (this.AbstractLocationsToAssignments == null)
                    {
                        this.AbstractLocationsToAssignments =
                            PooledDictionary <AbstractLocation, PooledHashSet <IAssignmentOperation> > .GetInstance();
                    }

                    if (!this.AbstractLocationsToAssignments.TryGetValue(
                            abstractLocation,
                            out PooledHashSet <IAssignmentOperation> assignments))
                    {
                        assignments = PooledHashSet <IAssignmentOperation> .GetInstance();

                        this.AbstractLocationsToAssignments.Add(abstractLocation, assignments);
                    }

                    assignments.Add(assignmentOperation);
                }
Пример #22
0
        protected sealed override void StopTrackingDataForParameters(ImmutableDictionary <IParameterSymbol, AnalysisEntity> parameterEntities)
        {
            if (parameterEntities.Count > 0)
            {
                var allEntities = PooledHashSet <AnalysisEntity> .GetInstance();

                try
                {
                    AddTrackedEntities(allEntities);

                    foreach (AnalysisEntity parameterEntity in parameterEntities.Values)
                    {
                        StopTrackingDataForEntity(parameterEntity, CurrentAnalysisData, allEntities);
                    }
                }
                finally
                {
                    allEntities.Free();
                }
            }
        }
Пример #23
0
        static WebOutputSinks()
        {
            // TODO paulming: Review why InformationDisclosure and XSS sinks are different.
            var builder = PooledHashSet <SinkInfo> .GetInstance();

            SinkKind[] sinkKinds = new SinkKind[] { SinkKind.InformationDisclosure, SinkKind.Xss };

            builder.AddSinkInfo(
                WellKnownTypeNames.SystemWebUIITextControl,
                sinkKinds,
                isInterface: true,
                isAnyStringParameterInConstructorASink: false,
                sinkProperties: new[] { "Text" },
                sinkMethodParameters: null);
            builder.AddSinkInfo(
                WellKnownTypeNames.SystemWebHttpResponseBase,
                sinkKinds,
                isInterface: false,
                isAnyStringParameterInConstructorASink: false,
                sinkProperties: null,
                sinkMethodParameters: new[] {
Пример #24
0
        private static ImmutableArray <T> AddMissing <T>(ImmutableArray <T> a, IEnumerable <T> b) where T : class
        {
            var builder = ArrayBuilder <T> .GetInstance();

            var set = PooledHashSet <T> .GetInstance();

            foreach (var i in a)
            {
                set.Add(i);
                builder.Add(i);
            }
            foreach (var i in b)
            {
                if ((i != null) && !set.Contains(i))
                {
                    builder.Add(i);
                }
            }
            set.Free();
            return(builder.ToImmutableAndFree());
        }
Пример #25
0
        public static Imports FromGlobalUsings(CSharpCompilation compilation)
        {
            var usings       = compilation.Options.Usings;
            var diagnostics  = new DiagnosticBag();
            var usingsBinder = new InContainerBinder(compilation.GlobalNamespace, new BuckStopsHereBinder(compilation));
            var boundUsings  = ArrayBuilder <NamespaceOrTypeAndUsingDirective> .GetInstance();

            var uniqueUsings = PooledHashSet <NamespaceOrTypeSymbol> .GetInstance();

            foreach (string @using in usings)
            {
                if ([email protected]())
                {
                    continue;
                }

                string[]   identifiers   = @using.Split('.');
                NameSyntax qualifiedName = SyntaxFactory.IdentifierName(identifiers[0]);

                for (int j = 1; j < identifiers.Length; j++)
                {
                    qualifiedName = SyntaxFactory.QualifiedName(left: qualifiedName, right: SyntaxFactory.IdentifierName(identifiers[j]));
                }

                var imported = usingsBinder.BindNamespaceOrTypeSymbol(qualifiedName, diagnostics);
                if (uniqueUsings.Add(imported))
                {
                    boundUsings.Add(new NamespaceOrTypeAndUsingDirective(imported, null));
                }
            }

            uniqueUsings.Free();

            if (diagnostics.IsEmptyWithoutResolution)
            {
                diagnostics = null;
            }

            return(new Imports(compilation, ImmutableDictionary <string, AliasAndUsingDirective> .Empty, boundUsings.ToImmutableAndFree(), ImmutableArray <AliasAndExternAliasDirective> .Empty, diagnostics));
        }
            public bool Equals(BasicBlockAnalysisData other)
            {
                // Check if both _reachingWrites maps have same key-value pair count.
                if (other == null ||
                    other._reachingWrites.Count != _reachingWrites.Count)
                {
                    return(false);
                }

                var uniqueSymbols = PooledHashSet <ISymbol> .GetInstance();

                try
                {
                    // Check if both _reachingWrites maps have same set of keys.
                    uniqueSymbols.AddRange(_reachingWrites.Keys);
                    uniqueSymbols.AddRange(other._reachingWrites.Keys);
                    if (uniqueSymbols.Count != _reachingWrites.Count)
                    {
                        return(false);
                    }

                    // Check if both _reachingWrites maps have same set of write
                    // operations for each tracked symbol.
                    foreach (var symbol in uniqueSymbols)
                    {
                        var writes1 = _reachingWrites[symbol];
                        var writes2 = other._reachingWrites[symbol];
                        if (!writes1.SetEquals(writes2))
                        {
                            return(false);
                        }
                    }

                    return(true);
                }
                finally
                {
                    uniqueSymbols.Free();
                }
            }
        private static void ReportInitializedNotUsedNotInitializedUsedVars(
            SyntaxNodeAnalysisContext context,
            Dictionary <string, IdentifierNameSyntax> firstGlobalVarInitializerSyntax,
            Dictionary <string, IdentifierNameSyntax> firstGlobalVarUsageSyntax,
            Dictionary <string, VariableDeclarationBaseSyntax> globalVariables)
        {
            PooledHashSet <IdentifierNameSyntax> instance1 = PooledHashSet <IdentifierNameSyntax> .GetInstance();

            PooledHashSet <IdentifierNameSyntax> instance2 = PooledHashSet <IdentifierNameSyntax> .GetInstance();

            try
            {
                VariableInitializationUsageAnalyzer.CollectInitializedNotUsedNotInitializedUsedGlobalVars((HashSet <IdentifierNameSyntax>)instance2, (HashSet <IdentifierNameSyntax>)instance1, firstGlobalVarInitializerSyntax, firstGlobalVarUsageSyntax, globalVariables);
                VariableInitializationUsageAnalyzer.ReportInitializedNotUsedVariables(new Action <Diagnostic>(context.ReportDiagnostic), instance1);
                VariableInitializationUsageAnalyzer.ReportNotInitializedVariables(new Action <Diagnostic>(context.ReportDiagnostic), instance2);
            }
            finally
            {
                instance1.Free();
                instance2.Free();
            }
        }
Пример #28
0
            private void ApplyMissingCurrentAnalysisDataCore(CopyAnalysisData mergedData, Func <AnalysisEntity, bool> predicateOpt)
            {
                var processedEntities = PooledHashSet <AnalysisEntity> .GetInstance();

                try
                {
                    foreach (var kvp in CurrentAnalysisData.CoreAnalysisData)
                    {
                        var key       = kvp.Key;
                        var copyValue = kvp.Value;
                        if (mergedData.CoreAnalysisData.ContainsKey(key) ||
                            (predicateOpt != null && !predicateOpt(key)) ||
                            !processedEntities.Add(key))
                        {
                            continue;
                        }

                        if (predicateOpt != null && copyValue.AnalysisEntities.Count > 1)
                        {
                            var entitiesToRemove = copyValue.AnalysisEntities.Where(entity => key != entity && !predicateOpt(entity));
                            if (entitiesToRemove.Any())
                            {
                                copyValue = copyValue.WithEntitiesRemoved(entitiesToRemove);
                            }
                        }

                        Debug.Assert(copyValue.AnalysisEntities.Contains(key));
                        Debug.Assert(predicateOpt == null || copyValue.AnalysisEntities.All(predicateOpt));
                        mergedData.SetAbstactValueForEntities(copyValue, entityBeingAssignedOpt: null);
                        processedEntities.AddRange(copyValue.AnalysisEntities);
                    }

                    AssertValidCopyAnalysisData(mergedData);
                }
                finally
                {
                    processedEntities.Free();
                }
            }
Пример #29
0
        private static ImmutableHashSet <INamedTypeSymbol> GetDisposeOwnershipTransferLikelyTypes(Compilation compilation)
        {
            var builder = PooledHashSet <INamedTypeSymbol> .GetInstance();

            try
            {
                foreach (var typeName in s_disposeOwnershipTransferLikelyTypes)
                {
                    var typeSymbol = compilation.GetTypeByMetadataName(typeName);
                    if (typeSymbol != null)
                    {
                        builder.Add(typeSymbol);
                    }
                }

                return(builder.ToImmutableHashSet());
            }
            finally
            {
                builder.Free();
            }
        }
Пример #30
0
            PooledHashSet <ISymbol> GetCandidateSymbolsReferencedInDocComments(INamedTypeSymbol namedTypeSymbol, Compilation compilation, CancellationToken cancellationToken)
            {
                var builder = PooledHashSet <ISymbol> .GetInstance();

                foreach (var root in namedTypeSymbol.Locations.Select(l => l.SourceTree.GetRoot(cancellationToken)))
                {
                    SemanticModel lazyModel = null;
                    foreach (var node in root.DescendantNodes(descendIntoTrivia: true)
                             .OfType <TDocumentationCommentTriviaSyntax>()
                             .SelectMany(n => n.DescendantNodes().OfType <TIdentifierNameSyntax>()))
                    {
                        lazyModel = lazyModel ?? compilation.GetSemanticModel(root.SyntaxTree);
                        var symbol = lazyModel.GetSymbolInfo(node, cancellationToken).Symbol;
                        if (symbol != null && IsCandidateSymbol(symbol))
                        {
                            builder.Add(symbol);
                        }
                    }
                }

                return(builder);
            }