コード例 #1
0
        /// <summary>
        ///     TBD
        /// </summary>
        /// <param name="allowed">TBD</param>
        /// <param name="other">TBD</param>
        /// <returns>TBD</returns>
        public Reachability Merge(IImmutableSet <UniqueAddress> allowed, Reachability other)
        {
            var recordBuilder = ImmutableList.CreateBuilder <Record>();
            //TODO: Size hint somehow?
            var newVersions = Versions;

            foreach (var observer in allowed)
            {
                var observerVersion1 = CurrentVersion(observer);
                var observerVersion2 = other.CurrentVersion(observer);

                var rows1 = ObserverRows(observer);
                var rows2 = other.ObserverRows(observer);

                if (rows1 != null && rows2 != null)
                {
                    var rows = observerVersion1 > observerVersion2 ? rows1 : rows2;
                    foreach (var record in rows.Values.Where(r => allowed.Contains(r.Subject)))
                    {
                        recordBuilder.Add(record);
                    }
                }

                if (rows1 != null && rows2 == null)
                {
                    if (observerVersion1 > observerVersion2)
                    {
                        foreach (var record in rows1.Values.Where(r => allowed.Contains(r.Subject)))
                        {
                            recordBuilder.Add(record);
                        }
                    }
                }
                if (rows1 == null && rows2 != null)
                {
                    if (observerVersion2 > observerVersion1)
                    {
                        foreach (var record in rows2.Values.Where(r => allowed.Contains(r.Subject)))
                        {
                            recordBuilder.Add(record);
                        }
                    }
                }

                if (observerVersion2 > observerVersion1)
                {
                    newVersions = newVersions.SetItem(observer, observerVersion2);
                }
            }

            newVersions = ImmutableDictionary.CreateRange(newVersions.Where(p => allowed.Contains(p.Key)));

            return(new Reachability(recordBuilder.ToImmutable(), newVersions));
        }
コード例 #2
0
ファイル: Graph.cs プロジェクト: arlm/CSharpTo2600
        public ImmutableGraph <T> AddNode(T node)
        {
            if (Nodes.Contains(node))
            {
                throw new ArgumentException($"Graph already contains node: {node}");
            }

            var newNodes = Nodes.Add(node);

            return(new ImmutableGraph <T>(newNodes, Edges));
        }
コード例 #3
0
 private void HandleGracefulShutdownRequest(GracefulShutdownRequest request)
 {
     if (!_gracefullShutdownInProgress.Contains(request.ShardRegion))
     {
         if (_currentState.Regions.TryGetValue(request.ShardRegion, out var shards))
         {
             Log.Debug("Graceful shutdown of region [{0}] with shards [{1}]", request.ShardRegion, string.Join(", ", shards));
             _gracefullShutdownInProgress = _gracefullShutdownInProgress.Add(request.ShardRegion);
             ContinueRebalance(shards.ToImmutableHashSet());
         }
     }
 }
コード例 #4
0
        private void HandleGetShardHome(GetShardHome getShardHome)
        {
            var shard = getShardHome.Shard;

            if (_rebalanceInProgress.Contains(shard))
            {
                Log.Debug("GetShardHome [{0}] request ignored, because rebalance is in progress for this shard.", shard);
            }
            else if (!HasAllRegionsRegistered())
            {
                Log.Debug("GetShardHome [{0}] request ignored, because not all regions have registered yet.", shard);
            }
            else
            {
                if (_currentState.Shards.TryGetValue(shard, out var region))
                {
                    if (_regionTerminationInProgress.Contains(region))
                    {
                        Log.Debug("GetShardHome [{0}] request ignored, due to region [{1}] termination in progress.", shard, region);
                    }
                    else
                    {
                        Sender.Tell(new ShardHome(shard, region));
                    }
                }
                else
                {
                    var activeRegions = _currentState.Regions.RemoveRange(_gracefullShutdownInProgress);
                    if (activeRegions.Count != 0)
                    {
                        var getShardHomeSender = Sender;
                        var regionTask         = AllocationStrategy.AllocateShard(getShardHomeSender, shard, activeRegions);

                        // if task completed immediately, just continue
                        if (regionTask.IsCompleted && !regionTask.IsFaulted)
                        {
                            ContinueGetShardHome(shard, regionTask.Result, getShardHomeSender);
                        }
                        else
                        {
                            regionTask.ContinueWith(t => !(t.IsFaulted || t.IsCanceled)
                                ? new AllocateShardResult(shard, t.Result, getShardHomeSender)
                                : new AllocateShardResult(shard, null, getShardHomeSender), TaskContinuationOptions.ExecuteSynchronously)
                            .PipeTo(Self);
                        }
                    }
                }
            }
        }
コード例 #5
0
        public void DeserializeHashSetInterface()
        {
            string json = @"[
  ""One"",
  ""II"",
  ""3""
]";

            IImmutableSet <string> data = JsonSerializer.Deserialize <IImmutableSet <string> >(json);

            Assert.Equal(3, data.Count);
            Assert.True(data.Contains("3"));
            Assert.True(data.Contains("II"));
            Assert.True(data.Contains("One"));
        }
        public void DeserializeHashSetInterface()
        {
            string json = @"[
  ""One"",
  ""II"",
  ""3""
]";

            IImmutableSet <string> l = JsonConvert.DeserializeObject <IImmutableSet <string> >(json);

            Assert.AreEqual(3, l.Count());
            Assert.IsTrue(l.Contains("3"));
            Assert.IsTrue(l.Contains("II"));
            Assert.IsTrue(l.Contains("One"));
        }
コード例 #7
0
        protected override Task <IEnumerable <Document> > DetermineDocumentsToSearchAsync(
            TSymbol symbol,
            Project project,
            IImmutableSet <Document> documents,
            CancellationToken cancellationToken)
        {
            var location = symbol.Locations.FirstOrDefault();

            if (location == null || !location.IsInSource)
            {
                return(SpecializedTasks.EmptyEnumerable <Document>());
            }

            var document = project.GetDocument(location.SourceTree);

            if (document == null)
            {
                return(SpecializedTasks.EmptyEnumerable <Document>());
            }

            if (documents != null && !documents.Contains(document))
            {
                return(SpecializedTasks.EmptyEnumerable <Document>());
            }

            return(Task.FromResult(SpecializedCollections.SingletonEnumerable <Document>(document)));
        }
コード例 #8
0
        public override void BeforeAddOrUpdate(
            ITargetFramework targetFramework,
            IDependency dependency,
            IReadOnlyDictionary <string, IProjectDependenciesSubTreeProvider> subTreeProviderByProviderType,
            IImmutableSet <string>?projectItemSpecs,
            AddDependencyContext context)
        {
            if (projectItemSpecs != null &&                                           // must have data
                !dependency.Implicit &&                                               // explicit
                dependency.Resolved &&                                                // resolved
                dependency.Flags.Contains(DependencyTreeFlags.GenericDependency) &&   // generic dependency
                !dependency.Flags.Contains(DependencyTreeFlags.SharedProjectDependency) && // except for shared projects
                !projectItemSpecs.Contains(dependency.OriginalItemSpec) &&            // is not a known item spec
                subTreeProviderByProviderType.TryGetValue(dependency.ProviderType, out IProjectDependenciesSubTreeProvider provider) &&
                provider is IProjectDependenciesSubTreeProviderInternal internalProvider)
            {
                // Obtain custom implicit icon
                ImageMoniker implicitIcon = internalProvider.ImplicitIcon;

                // Obtain a pooled icon set with this implicit icon
                DependencyIconSet implicitIconSet = DependencyIconSetCache.Instance.GetOrAddIconSet(
                    implicitIcon,
                    implicitIcon,
                    dependency.IconSet.UnresolvedIcon,
                    dependency.IconSet.UnresolvedExpandedIcon);

                context.Accept(
                    dependency.SetProperties(
                        iconSet: implicitIconSet,
                        isImplicit: true));
                return;
            }

            context.Accept(dependency);
        }
        private void AnalyzeSimpleBaseType(
            SyntaxNodeAnalysisContext context,
            IImmutableSet <INamedTypeSymbol> disallowedTypes
            )
        {
            SimpleBaseTypeSyntax baseTypeSyntax = (SimpleBaseTypeSyntax)context.Node;
            SymbolInfo           baseTypeSymbol = context.SemanticModel.GetSymbolInfo(baseTypeSyntax.Type);

            INamedTypeSymbol baseSymbol = (baseTypeSymbol.Symbol as INamedTypeSymbol);

            if (baseSymbol.IsNullOrErrorType())
            {
                return;
            }

            if (!disallowedTypes.Contains(baseSymbol))
            {
                return;
            }

            Diagnostic diagnostic = Diagnostic.Create(
                Diagnostics.EventHandlerDisallowed,
                baseTypeSyntax.GetLocation(),
                baseSymbol.ToDisplayString()
                );

            context.ReportDiagnostic(diagnostic);
        }
コード例 #10
0
        private void ProcessResult(IImmutableSet <TopicPartition> partitionsToFetch, ConsumeResult <K, V> consumedMessage)
        {
            if (consumedMessage == null)
            {
                return;
            }

            var fetchedTopicPartition = consumedMessage.TopicPartition;

            if (!partitionsToFetch.Contains(fetchedTopicPartition))
            {
                throw  new ArgumentException($"Unexpected records polled. Expected one of {partitionsToFetch.JoinToString(", ")}," +
                                             $"but consumed result is {consumedMessage.ToJson()}, consumer assignment: {_consumer.Assignment.ToJson()}");
            }

            foreach (var(stageActorRef, request) in _requests.ToTuples())
            {
                // If requestor is interested in consumed topic, send him consumed result
                if (request.Topics.Contains(consumedMessage.TopicPartition))
                {
                    var messages = ImmutableList <ConsumeResult <K, V> > .Empty.Add(consumedMessage);

                    stageActorRef.Tell(new KafkaConsumerActorMetadata.Internal.Messages <K, V>(request.RequestId, messages));
                    _requests = _requests.Remove(stageActorRef);
                }
            }
        }
コード例 #11
0
ファイル: JsonVisitor.cs プロジェクト: he-dev/reusable
 protected override JProperty VisitProperty(JProperty property)
 {
     return
         (_propertyNames.Contains(property.Name)
             ? base.VisitProperty(property)
             : throw DynamicException.Create("UnknownPropertyName", $"Property '{property.Name}' is not allowed."));
 }
コード例 #12
0
        protected override Task <ImmutableArray <Document> > DetermineDocumentsToSearchAsync(
            TSymbol symbol,
            Project project,
            IImmutableSet <Document> documents,
            FindReferencesSearchOptions options,
            CancellationToken cancellationToken)
        {
            var location = symbol.Locations.FirstOrDefault();

            if (location == null || !location.IsInSource)
            {
                return(SpecializedTasks.EmptyImmutableArray <Document>());
            }

            var document = project.GetDocument(location.SourceTree);

            if (document == null)
            {
                return(SpecializedTasks.EmptyImmutableArray <Document>());
            }

            if (documents != null && !documents.Contains(document))
            {
                return(SpecializedTasks.EmptyImmutableArray <Document>());
            }

            return(Task.FromResult(ImmutableArray.Create(document)));
        }
コード例 #13
0
        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, T value)
        {
            var bsonWriter = context.Writer;
            var type       = typeof(T);
            var fields     = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
            var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .Where(property => property.CanWrite);

            bsonWriter.WriteStartDocument();

            foreach (var property in _properties)
            {
                bsonWriter.WriteName(property.Name);
                BsonSerializer.Serialize(bsonWriter, property.PropertyType, property.GetValue(value, null));
            }

            foreach (var property in properties)
            {
                Assert(!_properties.Contains(property));

                bsonWriter.WriteName(property.Name);
                BsonSerializer.Serialize(bsonWriter, property.PropertyType, property.GetValue(value, null));
            }

            foreach (var field in fields)
            {
                bsonWriter.WriteName(field.Name);
                BsonSerializer.Serialize(bsonWriter, field.FieldType, field.GetValue(value));
            }

            bsonWriter.WriteEndDocument();
        }
コード例 #14
0
ファイル: Remotiatr.cs プロジェクト: FuncLun/RemotiatR
        public async Task <Stream> Handle(Stream message, Action <IServiceProvider>?configureServices, CancellationToken cancellationToken = default)
        {
            using var scope = _serviceProvider.CreateScope();

            configureServices?.Invoke(scope.ServiceProvider);

            var messageSerializer = scope.ServiceProvider.GetRequiredService <IMessageSerializer>();
            var messageHandlers   = scope.ServiceProvider.GetRequiredService <IEnumerable <IMessagePipelineHandler> >();
            var mediator          = scope.ServiceProvider.GetRequiredService <IMediator>();

            var data = await messageSerializer.Deserialize(message);

            if (_canHandleNotificationTypes.Contains(data.GetType()))
            {
                var handler = BuildNotificationHandler(mediator, messageHandlers, cancellationToken);

                await handler(data);

                return(new MemoryStream());
            }

            if (_canHandleRequestTypes.Contains(data.GetType()))
            {
                var handler = BuildRequestHandler(mediator, messageHandlers, cancellationToken);

                var response = await handler(data);

                return(await messageSerializer.Serialize(response));
            }

            throw new InvalidOperationException($"Type {data.GetType()} is neither a {typeof(INotification).FullName} nor an {nameof(IRequest)}");
        }
コード例 #15
0
        public async Task <IReadOnlyCollection <ChallengeMatch> > GetMatchesAsync(
            PlayerId playerId,
            DateTime?startedAt,
            DateTime?endedAt,
            IImmutableSet <string> matchIds
            )
        {
            var matchList = await _leagueOfLegendsService.Match.GetMatchListAsync(
                Region.Na,
                playerId,
                beginTime : startedAt,
                endTime : endedAt);

            var matches = new List <ChallengeMatch>();

            foreach (var reference in matchList.Matches.Where(
                         match => !matchIds.Contains(match.GameId.ToString()) && match.Queue == 420 /* 5v5 Ranked Solo games */))
            {
                var match = await _leagueOfLegendsService.Match.GetMatchAsync(Region.Na, reference.GameId);

                var stats = match.Participants.Single(
                    participant => participant.ParticipantId ==
                    match.ParticipantIdentities.Single(identity => identity.Player.AccountId == playerId).ParticipantId)
                            .Stats;

                matches.Add(
                    new ChallengeMatch(
                        match.GameId.ToString(),
                        new DateTimeProvider(match.GameCreation),
                        match.GameDuration,
                        stats.GetType().GetProperties().ToDictionary(property => property.Name, property => Convert.ToDouble(property.GetValue(stats)))));
            }

            return(matches);
        }
コード例 #16
0
        protected async Task<ImmutableArray<Document>> FindDocumentsAsync(Project project, IImmutableSet<Document> scope, Func<Document, CancellationToken, Task<bool>> predicateAsync, CancellationToken cancellationToken)
        {
            // special case for HR
            if (scope != null && scope.Count == 1)
            {
                var document = scope.First();
                if (document.Project == project)
                {
                    return scope.ToImmutableArray();
                }

                return ImmutableArray<Document>.Empty;
            }

            var documents = ArrayBuilder<Document>.GetInstance();
            foreach (var document in project.Documents)
            {
                if (scope != null && !scope.Contains(document))
                {
                    continue;
                }

                if (await predicateAsync(document, cancellationToken).ConfigureAwait(false))
                {
                    documents.Add(document);
                }
            }

            return documents.ToImmutableAndFree();
        }
コード例 #17
0
        private void AnalyzeMethodInvocation(
            SyntaxNodeAnalysisContext context,
            InvocationExpressionSyntax invocation,
            INamedTypeSymbol eventAttributeType,
            IImmutableSet <ISymbol> genericPublishMethods
            )
        {
            ISymbol expessionSymbol = context.SemanticModel
                                      .GetSymbolInfo(invocation.Expression)
                                      .Symbol;

            if (expessionSymbol.IsNullOrErrorType())
            {
                return;
            }

            if (!(expessionSymbol is IMethodSymbol methodSymbol))
            {
                return;
            }

            if (!methodSymbol.IsGenericMethod)
            {
                return;
            }

            if (!genericPublishMethods.Contains(methodSymbol.OriginalDefinition))
            {
                return;
            }

            ITypeSymbol eventTypeSymbol = methodSymbol.TypeArguments[0];

            if (eventTypeSymbol.IsNullOrErrorType())
            {
                return;
            }

            bool hasEventAttr = eventTypeSymbol
                                .GetAttributes()
                                .Any(attr => attr.AttributeClass.Equals(eventAttributeType, SymbolEqualityComparer.Default));

            if (hasEventAttr)
            {
                return;
            }

            if (eventTypeSymbol.TypeKind == TypeKind.TypeParameter)
            {
                return;
            }

            Diagnostic diagnostic = Diagnostic.Create(
                Diagnostics.EventTypeMissingEventAttribute,
                invocation.GetLocation(),
                eventTypeSymbol.ToDisplayString()
                );

            context.ReportDiagnostic(diagnostic);
        }
コード例 #18
0
        private static bool IsRunInvocation(
            SemanticModel model,
            IImmutableSet <IMethodSymbol> ILoggingExecutionContextScopeBuilderRunSymbols,
            InvocationExpressionSyntax invocationSyntax,
            CancellationToken ct
            )
        {
            SymbolInfo methodSymbolInfo = model.GetSymbolInfo(
                invocationSyntax,
                ct
                );

            if (methodSymbolInfo.Symbol != null)
            {
                if (ILoggingExecutionContextScopeBuilderRunSymbols.Contains(
                        methodSymbolInfo.Symbol.OriginalDefinition
                        ))
                {
                    return(true);
                }

                return(false);
            }

            if (methodSymbolInfo
                .CandidateSymbols
                .Select(s => s.OriginalDefinition)
                .Any(ILoggingExecutionContextScopeBuilderRunSymbols.Contains)
                )
            {
                return(true);
            }

            return(false);
        }
コード例 #19
0
ファイル: Replicator.cs プロジェクト: ziez/akka.net
        private void SetData(string key, DataEnvelope envelope)
        {
            ByteString digest;

            if (_subscribers.ContainsKey(key) && !_changed.Contains(key))
            {
                var oldDigest = GetDigest(key);
                var dig       = Digest(envelope);
                if (dig != oldDigest)
                {
                    _changed = _changed.Add(key);
                }

                digest = dig;
            }
            else if (envelope.Data is DeletedData)
            {
                digest = DeletedDigest;
            }
            else
            {
                digest = LazyDigest;
            }

            _dataEntries = _dataEntries.SetItem(key, Tuple.Create(envelope, digest));
        }
コード例 #20
0
        private static bool IsAwaitable(
            IImmutableSet <INamedTypeSymbol> taskTypeBuiltins,
            INamedTypeSymbol AsyncMethodBuilderAttribute,
            ITypeSymbol type
            )
        {
            type = type.OriginalDefinition;

            if (taskTypeBuiltins.Contains(type))
            {
                return(true);
            }

            IEnumerable <AttributeData> typeAttributes = type.GetAttributes();
            bool typeIsCustomAwaitable = typeAttributes.Any(
                a => a.AttributeClass.OriginalDefinition.Equals(AsyncMethodBuilderAttribute, SymbolEqualityComparer.Default)
                );

            if (typeIsCustomAwaitable)
            {
                return(true);
            }

            return(false);
        }
コード例 #21
0
            public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data)
            {
                var functionId = (string)data[0];

                if (!_set.Contains(functionId))
                {
                    return;
                }

                switch (id)
                {
                case LogEventId:
                    AddLog($"(Log) [{functionId}] [{(string)data[1] ?? "N/A"}]");
                    break;

                case StartEventId:
                    AddLog($"(Start [{(int)data[1]}]) [{functionId}]");
                    break;

                case EndEventId:
                    AddLog($"(End   [{(int)data[1]}]) [{functionId}] cancellation:{(bool)data[2]}, delta:{(int)data[3]}, [{(string)data[4] ?? "N/A"}]");
                    break;

                default:
                    throw new NotSupportedException("shouldn't reach here");
                }
            }
コード例 #22
0
 private static IEnumerable <SyntaxToken> GetAsyncOrAwaitTokens(SyntaxNode node)
 {
     return(from token in node.DescendantTokens()
            where token.IsKind(SyntaxKind.IdentifierToken) &&
            AsyncOrAwait.Contains(token.ToString())
            select token);
 }
コード例 #23
0
 private static IEnumerable <SyntaxToken> GetAsyncOrAwaitTokens(SyntaxNode node)
 {
     return(node.DescendantTokens()
            .Where(token =>
                   token.IsKind(SyntaxKind.IdentifierToken) &&
                   AsyncOrAwait.Contains(token.ToString())));
 }
コード例 #24
0
        protected async Task <ImmutableArray <Document> > FindDocumentsAsync(Project project, IImmutableSet <Document> scope, Func <Document, CancellationToken, Task <bool> > predicateAsync, CancellationToken cancellationToken)
        {
            // special case for HR
            if (scope != null && scope.Count == 1)
            {
                var document = scope.First();
                if (document.Project == project)
                {
                    return(scope.ToImmutableArray());
                }

                return(ImmutableArray <Document> .Empty);
            }

            var documents = ArrayBuilder <Document> .GetInstance();

            foreach (var document in project.Documents)
            {
                if (scope != null && !scope.Contains(document))
                {
                    continue;
                }

                if (await predicateAsync(document, cancellationToken).ConfigureAwait(false))
                {
                    documents.Add(document);
                }
            }

            return(documents.ToImmutableAndFree());
        }
コード例 #25
0
        private void AnalyzePropertyAccess(
            SyntaxNodeAnalysisContext context,
            IImmutableSet <ISymbol> dangerousProperties
            )
        {
            ISymbol propertySymbol = context.SemanticModel
                                     .GetSymbolInfo(context.Node)
                                     .Symbol;

            if (propertySymbol.IsNullOrErrorType())
            {
                return;
            }

            if (propertySymbol.Kind != SymbolKind.Property)
            {
                return;
            }

            bool isDangerousProperty = IsDangerousMemberSymbol(propertySymbol, dangerousProperties);

            if (!isDangerousProperty)
            {
                return;
            }

            bool isAllowedType = m_allowedTypes.Contains(context.ContainingSymbol.ContainingType.ToString());

            if (isAllowedType)
            {
                return;
            }

            ReportDiagnostic(context, propertySymbol, DiagnosticDescriptor);
        }
コード例 #26
0
        static ImmutableArray <IViewItem> CreateViewItems(
            IEnumerable <IBookmark> bookmarks,
            IImmutableSet <IBookmark> selected,
            ImmutableArray <Color> threadColors,
            ColoringMode coloring
            )
        {
            var      resultBuilder         = ImmutableArray.CreateBuilder <IViewItem>();
            DateTime?prevTimestamp         = null;
            DateTime?prevSelectedTimestamp = null;
            bool     multiSelection        = selected.Count >= 2;
            int      index = 0;

            foreach (IBookmark bmk in bookmarks)
            {
                var ts         = bmk.Time.ToUniversalTime();
                var ls         = bmk.GetLogSource();
                var isEnabled  = ls != null && ls.Visible;
                var isSelected = selected.Contains(bmk);
                var deltaBase  = multiSelection ? (isSelected ? prevSelectedTimestamp : null) : prevTimestamp;
                var delta      = deltaBase != null ? ts - deltaBase.Value : new TimeSpan?();
                var altDelta   = prevTimestamp != null ? ts - prevTimestamp.Value : new TimeSpan?();
                int?colorIndex = null;
                var thread     = bmk.Thread;
                if (coloring == Settings.Appearance.ColoringMode.Threads)
                {
                    if (!thread.IsDisposed)
                    {
                        colorIndex = thread.ThreadColorIndex;
                    }
                }
                if (coloring == Settings.Appearance.ColoringMode.Sources)
                {
                    if (!thread.IsDisposed && !thread.LogSource.IsDisposed)
                    {
                        colorIndex = thread.LogSource.ColorIndex;
                    }
                }
                resultBuilder.Add(new ViewItem()
                {
                    bookmark     = bmk,
                    key          = bmk.GetHashCode().ToString(),
                    text         = bmk.ToString(),
                    delta        = TimeUtils.TimeDeltaToString(delta),
                    altDelta     = TimeUtils.TimeDeltaToString(altDelta),
                    isSelected   = isSelected,
                    isEnabled    = isEnabled,
                    contextColor = threadColors.GetByIndex(colorIndex),
                    index        = index
                });
                prevTimestamp = ts;
                if (isSelected)
                {
                    prevSelectedTimestamp = ts;
                }
                ++index;
            }
            return(resultBuilder.ToImmutable());
        }
コード例 #27
0
ファイル: SymGraph.cs プロジェクト: pmq20/mono_forked
 private static bool VisitedBefore(SymValue sv2,
                                   IImmutableSet <SymValue> backwardManifested,
                                   IImmutableMap <SymValue, SymValue> backward,
                                   out SymValue sv1)
 {
     sv1 = backward [sv2];
     return(sv1 != null || backwardManifested.Contains(sv2));
 }
            static bool TryGetLinqMethodsThatDoNotReturnEnumerables(INamedTypeSymbol enumerableType, out ImmutableArray <IMethodSymbol> linqMethods)
            {
                using var _ = ArrayBuilder <IMethodSymbol> .GetInstance(out var linqMethodSymbolsBuilder);

                foreach (var method in enumerableType.GetMembers().OfType <IMethodSymbol>())
                {
                    if (s_nonEnumerableReturningLinqMethodNames.Contains(method.Name) &&
                        method.Parameters is { Length: 1 })
コード例 #29
0
 void logMessageHandlerThreaded(string message, string stackTrace, LogType type)
 {
     if (!handledTypes.Contains(type))
     {
         return;
     }
     lock (this) logMessageHandler(message, stackTrace, type);
 }
コード例 #30
0
 private static void EnsureVRIsSupported(string vrCode)
 {
     if (!SupportedVRCodes.Contains(vrCode))
     {
         throw new CustomTagEntryValidationException(
                   string.Format(CultureInfo.InvariantCulture, DicomCoreResource.UnsupportedVRCode, vrCode));
     }
 }
コード例 #31
0
        /***************************************************************************/

        private static void AssertDependencies(IImmutableSet <PropertyInfo> dependencies, params PropertyInfo[] propertyInfos)
        {
            Assert.AreEqual(propertyInfos.Length, dependencies.Count);
            foreach (var propertyInfo in propertyInfos)
            {
                Assert.IsTrue(dependencies.Contains(propertyInfo));
            }
        }
コード例 #32
0
ファイル: IncludeBlocksBlock.cs プロジェクト: andgein/uLearn
		public override IEnumerable<SlideBlock> BuildUp(BuildUpContext context, IImmutableSet<string> filesInProgress)
		{
			if (filesInProgress.Contains(File))
				throw new Exception("Cyclic dependency");

			var xmlStream = new StringReader(context.FileSystem.GetContent(File));
			var serializer = new XmlSerializer(typeof(SlideBlock[]));
			var slideBlocks = (SlideBlock[])serializer.Deserialize(xmlStream);
			var newInProgress = filesInProgress.Add(File);
			return slideBlocks.SelectMany(b => b.BuildUp(context, newInProgress));
		}
コード例 #33
0
ファイル: ImplementerFinder.cs プロジェクト: CAPCHIK/roslyn
        protected override async Task SearchWorkerAsync(ISymbol symbol, Project project, ICallHierarchySearchCallback callback, IImmutableSet<Document> documents, CancellationToken cancellationToken)
        {
            var implementations = await SymbolFinder.FindImplementationsAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false);

            foreach (var implementation in implementations)
            {
                var sourceLocations = implementation.DeclaringSyntaxReferences.Select(d => project.Solution.GetDocument(d.SyntaxTree)).WhereNotNull();
                var bestLocation = sourceLocations.FirstOrDefault(d => documents == null || documents.Contains(d));
                if (bestLocation != null)
                {
                    var item = await Provider.CreateItem(implementation, bestLocation.Project, SpecializedCollections.EmptyEnumerable<Location>(), cancellationToken).ConfigureAwait(false);
                    callback.AddResult(item);
                    cancellationToken.ThrowIfCancellationRequested();
                }
            }
        }
コード例 #34
0
        private async Task<IEnumerable<DocumentHighlights>> CreateSpansAsync(
            Solution solution,
            ISymbol symbol,
            IEnumerable<ReferencedSymbol> references,
            IEnumerable<Location> additionalReferences,
            IImmutableSet<Document> documentToSearch,
            CancellationToken cancellationToken)
        {
            var spanSet = new HashSet<ValueTuple<Document, TextSpan>>();
            var tagMap = new MultiDictionary<Document, HighlightSpan>();
            bool addAllDefinitions = true;

            // Add definitions
            if (symbol.Kind == SymbolKind.Alias &&
                symbol.Locations.Length > 0)
            {
                // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition.
                await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, true, cancellationToken).ConfigureAwait(false);
                addAllDefinitions = false;
            }

            // Add references and definitions
            foreach (var reference in references)
            {
                if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition))
                {
                    foreach (var location in reference.Definition.Locations)
                    {
                        if (location.IsInSource && documentToSearch.Contains(solution.GetDocument(location.SourceTree)))
                        {
                            await AddLocationSpan(location, solution, spanSet, tagMap, true, cancellationToken).ConfigureAwait(false);
                        }
                    }
                }

                foreach (var referenceLocation in reference.Locations)
                {
                    await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, false, cancellationToken).ConfigureAwait(false);
                }
            }

            // Add additional references
            foreach (var location in additionalReferences)
            {
                await AddLocationSpan(location, solution, spanSet, tagMap, false, cancellationToken).ConfigureAwait(false);
            }

            var list = new List<DocumentHighlights>(tagMap.Count);
            foreach (var kvp in tagMap)
            {
                var spans = new List<HighlightSpan>(kvp.Value.Count);
                foreach (var span in kvp.Value)
                {
                    spans.Add(span);
                }

                list.Add(new DocumentHighlights(kvp.Key, spans));
            }

            return list;
        }
コード例 #35
0
        private async Task<IEnumerable<DocumentHighlights>> CreateSpansAsync(
            Solution solution,
            ISymbol symbol,
            IEnumerable<ReferencedSymbol> references,
            IEnumerable<Location> additionalReferences,
            IImmutableSet<Document> documentToSearch,
            CancellationToken cancellationToken)
        {
            var spanSet = new HashSet<ValueTuple<Document, TextSpan>>();
            var tagMap = new MultiDictionary<Document, HighlightSpan>();
            bool addAllDefinitions = true;

            // Add definitions
            // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages.
            if (symbol.Kind == SymbolKind.Alias &&
                symbol.Locations.Length > 0)
            {
                addAllDefinitions = false;

                if (symbol.Locations.First().IsInSource)
                {
                    // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition.
                    await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
                }
            }

            // Add references and definitions
            foreach (var reference in references)
            {
                if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition))
                {
                    foreach (var location in reference.Definition.Locations)
                    {
                        if (location.IsInSource)
                        {
                            var document = solution.GetDocument(location.SourceTree);

                            // GetDocument will return null for locations in #load'ed trees.
                            // TODO:  Remove this check and add logic to fetch the #load'ed tree's
                            // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed.
                            if (document == null)
                            {
                                Debug.Assert(solution.Workspace.Kind == "Interactive");
                                continue;
                            }

                            if (documentToSearch.Contains(document))
                            {
                                await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
                            }
                        }
                    }
                }

                foreach (var referenceLocation in reference.Locations)
                {
                    var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference;
                    await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false);
                }
            }

            // Add additional references
            foreach (var location in additionalReferences)
            {
                await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false);
            }

            var list = new List<DocumentHighlights>(tagMap.Count);
            foreach (var kvp in tagMap)
            {
                var spans = new List<HighlightSpan>(kvp.Value.Count);
                foreach (var span in kvp.Value)
                {
                    spans.Add(span);
                }

                list.Add(new DocumentHighlights(kvp.Key, spans));
            }

            return list;
        }
コード例 #36
0
        private static void ExcludePrivateFieldsBasedOnReferences(
            IImmutableDictionary<ISymbol, PrivateField> privateFields,
            IDictionary<ISymbol, IDictionary<SyntaxNode, ISymbol>> referencesByEnclosingSymbol,
            IImmutableSet<ISymbol> classMethods)
        {
            var referencedAtLeastOnceFromClassMethod = new HashSet<ISymbol>();

            foreach (var references in referencesByEnclosingSymbol)
            {
                if (!classMethods.Contains(references.Key))
                {
                    foreach (var reference in references.Value)
                    {
                        privateFields[reference.Value].Excluded = true;
                    }

                    continue;
                }

                foreach (var reference in references.Value)
                {
                    referencedAtLeastOnceFromClassMethod.Add(reference.Value);

                    if (!IsReferenceToSingleFieldValue(reference))
                    {
                        privateFields[reference.Value].Excluded = true;
                    }
                }
            }

            foreach (var privateField in privateFields.Values)
            {
                if (!referencedAtLeastOnceFromClassMethod.Contains(privateField.Symbol))
                {
                    privateField.Excluded = true;
                }
            }
        }