protected ClusterClientSpec(ClusterClientSpecConfig config) : base(config, typeof(ClusterClientSpec)) { _config = config; _remainingServerRoleNames = ImmutableHashSet.Create(_config.First, _config.Second, _config.Third, _config.Fourth); }
public void EnumeratorTest() { var builder = ImmutableHashSet.Create(1).ToBuilder(); ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable <int>)builder).GetEnumerator()); }
public void ClusterHeartbeatSenderState_must_init_without_self() { _emptyState.Init(ImmutableHashSet.Create <UniqueAddress>(bb, cc)).ActiveReceivers.ShouldBe(ImmutableHashSet.Create <UniqueAddress>(bb, cc)); }
/// <summary> /// TBD /// </summary> /// <param name="subscriber">TBD</param> /// <param name="persistenceId">TBD</param> public void AddPersistenceIdSubscriber(IActorRef subscriber, string persistenceId) { if (!_persistenceIdSubscribers.TryGetValue(persistenceId, out var subscriptions)) { _persistenceIdSubscribers = _persistenceIdSubscribers.Add(persistenceId, ImmutableHashSet.Create(subscriber)); } else { _persistenceIdSubscribers = _persistenceIdSubscribers.SetItem(persistenceId, subscriptions.Add(subscriber)); } }
/// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <param name="elements">TBD</param> /// <returns>TBD</returns> public static GSet <T> Create <T>(params T[] elements) => new GSet <T>(ImmutableHashSet.Create(elements));
public static void TestDebuggerAttributes_Null() { Type proxyType = DebuggerAttributes.GetProxyType(ImmutableHashSet.Create<string>()); TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null)); Assert.IsType<ArgumentNullException>(tie.InnerException); }
/// <summary> /// Invoked by <see cref="InteractiveHost"/> when a new process is being started. /// </summary> private void ProcessStarting(InteractiveHostOptions options) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => ProcessStarting(options))); return; } // Freeze all existing classifications and then clear the list of // submission buffers we have. FreezeClassifications(); _submissionBuffers.Clear(); // We always start out empty _workspace.ClearSolution(); _currentSubmissionProjectId = null; _previousSubmissionProjectId = null; var metadataService = _workspace.CurrentSolution.Services.MetadataService; ImmutableArray <string> referencePaths; // reset configuration: if (File.Exists(_responseFilePath)) { // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspArguments = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, Path.GetDirectoryName(_responseFilePath), null /* TODO: pass a valid value*/); referencePaths = rspArguments.ReferencePaths; // the base directory for references specified in the .rsp file is the .rsp file directory: var rspMetadataReferenceResolver = new GacFileResolver( referencePaths, baseDirectory: rspArguments.BaseDirectory, architectures: GacFileResolver.Default.Architectures, // TODO (tomat) preferredCulture: System.Globalization.CultureInfo.CurrentCulture); // TODO (tomat) var metadataProvider = metadataService.GetProvider(); // ignore unresolved references, they will be reported in the interactive window: var rspReferences = rspArguments.ResolveMetadataReferences(new AssemblyReferenceResolver(rspMetadataReferenceResolver, metadataProvider)) .Where(r => !(r is UnresolvedMetadataReference)); var interactiveHelpersRef = metadataService.GetReference(typeof(Script).Assembly.Location, MetadataReferenceProperties.Assembly); var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveHostObject).Assembly.Location, MetadataReferenceProperties.Assembly); _references = ImmutableHashSet.Create <MetadataReference>( interactiveHelpersRef, interactiveHostObjectRef) .Union(rspReferences); // we need to create projects for these: _rspSourceFiles = rspArguments.SourceFiles; } else { var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly); _references = ImmutableHashSet.Create <MetadataReference>(mscorlibRef); _rspSourceFiles = ImmutableArray.Create <CommandLineSourceFile>(); referencePaths = ScriptOptions.Default.SearchPaths; } // reset search paths, working directory: _metadataReferenceResolver = new GacFileResolver( referencePaths, baseDirectory: _initialWorkingDirectory, architectures: GacFileResolver.Default.Architectures, // TODO (tomat) preferredCulture: System.Globalization.CultureInfo.CurrentCulture); // TODO (tomat) _sourceSearchPaths = InteractiveHost.Service.DefaultSourceSearchPaths; // create the first submission project in the workspace after reset: if (_currentSubmissionBuffer != null) { AddSubmission(_currentTextView, _currentSubmissionBuffer); } }
private static async Task <DiagnosticAnalysisResultMap <DiagnosticAnalyzer, DiagnosticAnalysisResult> > AnalyzeOutOfProcAsync( DocumentAnalysisScope?documentAnalysisScope, Project project, CompilationWithAnalyzers compilationWithAnalyzers, RemoteHostClient client, bool forceExecuteAllAnalyzers, bool logPerformanceInfo, bool getTelemetryInfo, CancellationToken cancellationToken) { using var pooledObject = SharedPools.Default <Dictionary <string, DiagnosticAnalyzer> >().GetPooledObject(); var analyzerMap = pooledObject.Object; var ideOptions = ((WorkspaceAnalyzerOptions)compilationWithAnalyzers.AnalysisOptions.Options !).IdeOptions; var analyzers = documentAnalysisScope?.Analyzers ?? compilationWithAnalyzers.Analyzers.Where(a => forceExecuteAllAnalyzers || !a.IsOpenFileOnly(ideOptions.CleanupOptions?.SimplifierOptions)); analyzerMap.AppendAnalyzerMap(analyzers); if (analyzerMap.Count == 0) { return(DiagnosticAnalysisResultMap <DiagnosticAnalyzer, DiagnosticAnalysisResult> .Empty); } var argument = new DiagnosticArguments( compilationWithAnalyzers.AnalysisOptions.ReportSuppressedDiagnostics, logPerformanceInfo, getTelemetryInfo, documentAnalysisScope?.TextDocument.Id, documentAnalysisScope?.Span, documentAnalysisScope?.Kind, project.Id, analyzerMap.Keys.ToArray(), ideOptions); var result = await client.TryInvokeAsync <IRemoteDiagnosticAnalyzerService, SerializableDiagnosticAnalysisResults>( project.Solution, invocation : (service, solutionInfo, cancellationToken) => service.CalculateDiagnosticsAsync(solutionInfo, argument, cancellationToken), cancellationToken).ConfigureAwait(false); if (!result.HasValue) { return(DiagnosticAnalysisResultMap <DiagnosticAnalyzer, DiagnosticAnalysisResult> .Empty); } // handling of cancellation and exception var version = await DiagnosticIncrementalAnalyzer.GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false); var documentIds = (documentAnalysisScope != null) ? ImmutableHashSet.Create(documentAnalysisScope.TextDocument.Id) : null; return(new DiagnosticAnalysisResultMap <DiagnosticAnalyzer, DiagnosticAnalysisResult>( result.Value.Diagnostics.ToImmutableDictionary( entry => analyzerMap[entry.analyzerId], entry => DiagnosticAnalysisResult.Create( project, version, syntaxLocalMap: Hydrate(entry.diagnosticMap.Syntax, project), semanticLocalMap: Hydrate(entry.diagnosticMap.Semantic, project), nonLocalMap: Hydrate(entry.diagnosticMap.NonLocal, project), others: entry.diagnosticMap.Other, documentIds)), result.Value.Telemetry.ToImmutableDictionary(entry => analyzerMap[entry.analyzerId], entry => entry.telemetry))); }
public WorkItem( DocumentId documentId, string language, InvocationReasons invocationReasons, bool isLowPriority, IIncrementalAnalyzer analyzer, IAsyncToken asyncToken) : this(documentId, documentId.ProjectId, language, invocationReasons, isLowPriority, null, analyzer == null ? ImmutableHashSet.Create <IIncrementalAnalyzer>() : ImmutableHashSet.Create <IIncrementalAnalyzer>(analyzer), false, asyncToken) { }
public InternPool(IEqualityComparer <T>?comparer = null) { _set = ImmutableHashSet.Create(comparer); }
private static async Task <bool> ExceptionDeclarationCouldBeRemoved(CodeFixContext context, SyntaxNode root, ThrowStatementSyntax originalThrowStatement) { // If "ex" from "throw ex" was the only reference to "ex", then additional modification should be made // "catch(Exception ex)" should be replaced by "catch(Exception)" var throwExIdentifier = originalThrowStatement.Expression.As(x => x as IdentifierNameSyntax); Contract.Assert(throwExIdentifier != null); var model = await context.Document.GetSemanticModelAsync(); var solution = context.Document.Project.Solution; var symbol = model.GetSymbolInfo(throwExIdentifier); Contract.Assert(symbol.Symbol != null); // Not sure this is a good idea! // TODO: talk to nikov about it! If there is an optimization for locals than everything should be fine! // Otherwise - not! // Searching within one document should be fast. Still need to check! var references = await SymbolFinder.FindReferencesAsync(symbol.Symbol, solution, ImmutableHashSet.Create(context.Document)); var locations = references.SelectMany(x => x.Locations).ToArray(); var numberOfUsages = references .SelectMany(x => x.Locations) .Select(x => root.FindToken(x.Location.SourceSpan.Start)) .Count(token => token.Parent.Parent is ThrowStatementSyntax); // TODO: code duplication with GetThrowStatementFrom! // "ex" in the "Exception ex" could be removed only if there is no any other usages. Otherwise the fix will fail. // Consider following case: // There is two usages of the "ex" in two "throw ex" statemetns. // Two different fixes would be run for both warnings. // The first fix will change the code to "catch(Exception) {throw ex; throw;}" witch is not a valid C# program return(numberOfUsages == 1 && locations.Length == 1); }
/// <summary> /// Creates a new forward analysis for the given control flow graph. /// </summary> /// <param name="cfg">The control flow graph to create the forward analysis of.</param> protected ForwardFlowAnalysis(ControlFlowGraph cfg) : base(cfg.Nodes) { Flow = cfg.Edges.Select(edge => new FlowTransition(edge.From, edge.To)).ToImmutableList(); ExtremalNodes = ImmutableHashSet.Create <FlowNode>(cfg.Start); }
private void A_Cluster_must_perform_correct_transitions_when_third_joins_second() { RunOn(() => { Cluster.Join(GetAddress(_config.Second)); }, _config.Third); RunOn(() => { // gossip chat from the join will synchronize the views AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.Second, _config.Third))); }, _config.Second, _config.Third); EnterBarrier("third-joined-second"); GossipTo(_config.Second, _config.First); RunOn(() => { // gossip chat will synchronize the views AwaitMembers(GetAddress(_config.First), GetAddress(_config.Second), GetAddress(_config.Third)); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Joining); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, _config.First, _config.Second); GossipTo(_config.First, _config.Third); RunOn(() => { AwaitMembers(GetAddress(_config.First), GetAddress(_config.Second), GetAddress(_config.Third)); AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Joining); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, _config.First, _config.Second, _config.Third); EnterBarrier("convergence-joining-3"); var leader12 = Leader(_config.First, _config.Second); Log.Debug("Leader: {0}", leader12); var tmp = Roles.Where(x => x != leader12).ToList(); var other1 = tmp.First(); var other2 = tmp.Skip(1).First(); RunOn(() => { LeaderActions(); AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); }, leader12); EnterBarrier("leader-actions-3"); // leader gossipTo first non-leader GossipTo(leader12, other1); RunOn(() => { AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(leader12, Myself))); }, other1); // first non-leader gossipTo the other non-leader GossipTo(other1, other2); RunOn(() => { // send gossip Cluster.ClusterCore.Tell(new InternalClusterAction.SendGossipTo(GetAddress(other2))); }, other1); RunOn(() => { AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, other2); // first non-leader gossipTo the leader GossipTo(other1, leader12); RunOn(() => { AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, _config.First, _config.Second, _config.Third); EnterBarrier("after-3"); }
public void ClusterClient_must_report_events() { Within(15.Seconds(), () => { RunOn(() => { var c = Sys.ActorSelection("/user/client").ResolveOne(Dilated(1.Seconds())).Result; var l = Sys.ActorOf( Props.Create(() => new ClusterClientSpecConfig.TestClientListener(c)), "reporter-client-listener"); var expectedContacts = ImmutableHashSet.Create(_config.First, _config.Second, _config.Third, _config.Fourth) .Select(_ => Node(_) / "system" / "receptionist"); Within(10.Seconds(), () => { AwaitAssert(() => { var probe = CreateTestProbe(); l.Tell(ClusterClientSpecConfig.TestClientListener.GetLatestContactPoints.Instance, probe.Ref); probe.ExpectMsg <ClusterClientSpecConfig.TestClientListener.LatestContactPoints>() .ContactPoints.Should() .BeEquivalentTo(expectedContacts); }); }); }, _config.Client); EnterBarrier("reporter-client-listener-tested"); RunOn(() => { // Only run this test on a node that knows about our client. It could be that no node knows // but there isn't a means of expressing that at least one of the nodes needs to pass the test. var r = ClusterClientReceptionist.Get(Sys).Underlying; r.Tell(GetClusterClients.Instance); var cps = ExpectMsg <ClusterClients>(); if (cps.ClusterClientsList.Any(c => c.Path.Name.Equals("client"))) { Log.Info("Testing that the receptionist has just one client"); var l = Sys.ActorOf( Props.Create(() => new ClusterClientSpecConfig.TestReceptionistListener(r)), "reporter-receptionist-listener"); var c = Sys .ActorSelection(Node(_config.Client) / "user" / "client") .ResolveOne(Dilated(2.Seconds())).Result; var expectedClients = ImmutableHashSet.Create(c); Within(10.Seconds(), () => { AwaitAssert(() => { var probe = CreateTestProbe(); l.Tell(ClusterClientSpecConfig.TestReceptionistListener.GetLatestClusterClients.Instance, probe.Ref); probe.ExpectMsg <ClusterClientSpecConfig.TestReceptionistListener.LatestClusterClients>() .ClusterClients.Should() .BeEquivalentTo(expectedClients); }); }); } }, _config.First, _config.Second, _config.Third); EnterBarrier("after-5"); }); }
public NodeMetrics(Address address, long timestamp) : this(address, timestamp, ImmutableHashSet.Create <Metric>()) { }
public void ReachabilityTable_must_exclude_observations_from_specific_downed_nodes() { var r = Reachability.Empty. Unreachable(nodeC, nodeA).Reachable(nodeC, nodeA). Unreachable(nodeC, nodeB). Unreachable(nodeB, nodeA).Unreachable(nodeB, nodeC); r.IsReachable(nodeA).Should().BeFalse(); r.IsReachable(nodeB).Should().BeFalse(); r.IsReachable(nodeC).Should().BeFalse(); r.AllUnreachableOrTerminated.Should().BeEquivalentTo(ImmutableHashSet.Create(nodeA, nodeB, nodeC)); r.RemoveObservers(ImmutableHashSet.Create(nodeB)).AllUnreachableOrTerminated.Should().BeEquivalentTo(ImmutableHashSet.Create(nodeB)); }
public ImmutableHashSet <Metric> Metrics() { return(ImmutableHashSet.Create <Metric>(new [] { Processors(), SystemLoadAverage(), SystemMaxMemory(), SystemMemoryAvailable(), ClrProcessMemoryUsed() })); }
public InvocationReasons(string reason) : this(ImmutableHashSet.Create <string>(reason)) { }
public async Task DoesTransactionFollowsPolicy() { var adminPrivateKey = new PrivateKey(); var adminAddress = adminPrivateKey.ToAddress(); var activatedPrivateKey = new PrivateKey(); var activatedAddress = activatedPrivateKey.ToAddress(); var blockPolicySource = new BlockPolicySource(Logger.None); IBlockPolicy <PolymorphicAction <ActionBase> > policy = blockPolicySource.GetPolicy(10000, 100); IStagePolicy <PolymorphicAction <ActionBase> > stagePolicy = new VolatileStagePolicy <PolymorphicAction <ActionBase> >(); Block <PolymorphicAction <ActionBase> > genesis = MakeGenesisBlock( adminAddress, ImmutableHashSet.Create(activatedAddress).Add(adminAddress) ); using var store = new DefaultStore(null); using var stateStore = new TrieStateStore(new DefaultKeyValueStore(null), new DefaultKeyValueStore(null)); var blockChain = new BlockChain <PolymorphicAction <ActionBase> >( policy, stagePolicy, store, stateStore, genesis, renderers: new[] { blockPolicySource.BlockRenderer } ); Transaction <PolymorphicAction <ActionBase> > txByStranger = Transaction <PolymorphicAction <ActionBase> > .Create( 0, new PrivateKey(), genesis.Hash, new PolymorphicAction <ActionBase>[] { } ); // New private key which is not in activated addresses list is blocked. Assert.False(policy.DoesTransactionFollowsPolicy(txByStranger, blockChain)); var newActivatedPrivateKey = new PrivateKey(); var newActivatedAddress = newActivatedPrivateKey.ToAddress(); // Activate with admin account. Transaction <PolymorphicAction <ActionBase> > invitationTx = blockChain.MakeTransaction( adminPrivateKey, new PolymorphicAction <ActionBase>[] { new AddActivatedAccount(newActivatedAddress) } ); blockChain.StageTransaction(invitationTx); await blockChain.MineBlock(adminAddress); Transaction <PolymorphicAction <ActionBase> > txByNewActivated = Transaction <PolymorphicAction <ActionBase> > .Create( 0, newActivatedPrivateKey, genesis.Hash, new PolymorphicAction <ActionBase>[] { } ); // Test success because the key is activated. Assert.True(policy.DoesTransactionFollowsPolicy(txByNewActivated, blockChain)); var singleAction = new PolymorphicAction <ActionBase>[] { new DailyReward(), }; var manyActions = new PolymorphicAction <ActionBase>[] { new DailyReward(), new DailyReward(), }; Transaction <PolymorphicAction <ActionBase> > txWithSingleAction = Transaction <PolymorphicAction <ActionBase> > .Create( 0, activatedPrivateKey, genesis.Hash, singleAction ); Transaction <PolymorphicAction <ActionBase> > txWithManyActions = Transaction <PolymorphicAction <ActionBase> > .Create( 0, activatedPrivateKey, genesis.Hash, manyActions ); // Transaction with more than two actions is rejected. Assert.True(policy.DoesTransactionFollowsPolicy(txWithSingleAction, blockChain)); Assert.False(policy.DoesTransactionFollowsPolicy(txWithManyActions, blockChain)); }
public InvocationReasons With(InvocationReasons invocationReasons) { return(new InvocationReasons((_reasons ?? ImmutableHashSet.Create <string>()).Union(invocationReasons._reasons))); }
public bool TryCreate(IOperation operation, [NotNullWhen(returnValue: true)] out AnalysisEntity?analysisEntity) { if (_analysisEntityMap.TryGetValue(operation, out analysisEntity)) { return(analysisEntity != null); } analysisEntity = null; ISymbol?symbol = null; ImmutableArray <AbstractIndex> indices = ImmutableArray <AbstractIndex> .Empty; IOperation? instance = null; ITypeSymbol?type = operation.Type; switch (operation) { case ILocalReferenceOperation localReference: symbol = localReference.Local; break; case IParameterReferenceOperation parameterReference: symbol = parameterReference.Parameter; break; case IMemberReferenceOperation memberReference: instance = memberReference.Instance; GetSymbolAndIndicesForMemberReference(memberReference, ref symbol, ref indices); // Workaround for https://github.com/dotnet/roslyn/issues/22736 (IPropertyReferenceExpressions in IAnonymousObjectCreationExpression are missing a receiver). if (instance == null && symbol != null && memberReference is IPropertyReferenceOperation propertyReference) { instance = propertyReference.GetAnonymousObjectCreation(); } break; case IArrayElementReferenceOperation arrayElementReference: instance = arrayElementReference.ArrayReference; indices = CreateAbstractIndices(arrayElementReference.Indices); break; case IDynamicIndexerAccessOperation dynamicIndexerAccess: instance = dynamicIndexerAccess.Operation; indices = CreateAbstractIndices(dynamicIndexerAccess.Arguments); break; case IConditionalAccessInstanceOperation conditionalAccessInstance: IConditionalAccessOperation?conditionalAccess = conditionalAccessInstance.GetConditionalAccess(); instance = conditionalAccess?.Operation; if (conditionalAccessInstance.Parent is IMemberReferenceOperation memberReferenceParent) { GetSymbolAndIndicesForMemberReference(memberReferenceParent, ref symbol, ref indices); } break; case IInstanceReferenceOperation instanceReference: if (_getPointsToAbstractValue != null) { instance = instanceReference.GetInstance(_getIsInsideAnonymousObjectInitializer()); if (instance == null) { // Reference to this or base instance. analysisEntity = _interproceduralCallStack != null && _interproceduralCallStack.Peek().DescendantsAndSelf().Contains(instanceReference) ? _interproceduralThisOrMeInstanceForCaller : ThisOrMeInstance; } else { var instanceLocation = _getPointsToAbstractValue(instanceReference); analysisEntity = AnalysisEntity.Create(instanceReference, instanceLocation); } } break; case IConversionOperation conversion: return(TryCreate(conversion.Operand, out analysisEntity)); case IParenthesizedOperation parenthesized: return(TryCreate(parenthesized.Operand, out analysisEntity)); case IArgumentOperation argument: return(TryCreate(argument.Value, out analysisEntity)); case IFlowCaptureOperation flowCapture: var isLvalueFlowCapture = _getIsLValueFlowCapture(flowCapture); analysisEntity = GetOrCreateForFlowCapture(flowCapture.Id, flowCapture.Value.Type, flowCapture, isLvalueFlowCapture); // Store flow capture copy values for simple flow captures of non-flow captured entity. // This enables pseudo copy-analysis of values of these two entities in absence of true copy analysis, which is expensive. if (!isLvalueFlowCapture && TryCreate(flowCapture.Value, out var capturedEntity) && capturedEntity.CaptureId == null && !_captureIdCopyValueMap.ContainsKey(flowCapture.Id)) { var kind = capturedEntity.Type.IsValueType ? CopyAbstractValueKind.KnownValueCopy : CopyAbstractValueKind.KnownReferenceCopy; var copyValue = new CopyAbstractValue(ImmutableHashSet.Create(analysisEntity, capturedEntity), kind); _captureIdCopyValueMap.Add(flowCapture.Id, copyValue); } break; case IFlowCaptureReferenceOperation flowCaptureReference: analysisEntity = GetOrCreateForFlowCapture(flowCaptureReference.Id, flowCaptureReference.Type, flowCaptureReference, flowCaptureReference.IsLValueFlowCaptureReference()); break; case IDeclarationExpressionOperation declarationExpression: switch (declarationExpression.Expression) { case ILocalReferenceOperation localReference: return(TryCreateForSymbolDeclaration(localReference.Local, out analysisEntity)); case ITupleOperation tupleOperation: return(TryCreate(tupleOperation, out analysisEntity)); } break; case IVariableDeclaratorOperation variableDeclarator: symbol = variableDeclarator.Symbol; type = variableDeclarator.Symbol.Type; break; case IDeclarationPatternOperation declarationPattern: var declaredLocal = declarationPattern.DeclaredSymbol as ILocalSymbol; symbol = declaredLocal; type = declaredLocal?.Type; break; default: break; } if (symbol != null || !indices.IsEmpty) { TryCreate(symbol, indices, type !, instance, out analysisEntity); } _analysisEntityMap[operation] = analysisEntity; return(analysisEntity != null); }
static void LaunchFrontend(string[] args) { var port = args.Length > 0 ? args[0] : "0"; var config = ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port=" + port) .WithFallback(ConfigurationFactory.ParseString("akka.cluster.roles = [frontend]")) .WithFallback(_clusterConfig); var system = ActorSystem.Create("ClusterSystem", config); var backendRouter = system.ActorOf( Props.Empty.WithRouter(new ClusterRouterGroup(new ConsistentHashingGroup("/user/backend"), new ClusterRouterGroupSettings(10, false, "backend", ImmutableHashSet.Create("/user/backend"))))); var frontend = system.ActorOf(Props.Create(() => new FrontendActor(backendRouter)), "frontend"); var interval = TimeSpan.FromSeconds(12); var counter = new AtomicCounter(); system.Scheduler.Advanced.ScheduleRepeatedly(interval, interval, () => frontend.Tell(new StartCommand("hello-" + counter.GetAndIncrement()))); }
#pragma warning disable RS1026 // Enable concurrent execution public override void Initialize(AnalysisContext context) #pragma warning restore RS1026 // Enable concurrent execution { // TODO: Consider making this analyzer thread-safe. //context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(compilationStartContext => { INamedTypeSymbol eventsArgSymbol = compilationStartContext.Compilation.GetTypeByMetadataName("System.EventArgs"); // Ignore conditional methods (FxCop compat - One conditional will often call another conditional method as its only use of a parameter) INamedTypeSymbol conditionalAttributeSymbol = WellKnownTypes.ConditionalAttribute(compilationStartContext.Compilation); // Ignore methods with special serialization attributes (FxCop compat - All serialization methods need to take 'StreamingContext') INamedTypeSymbol onDeserializingAttribute = WellKnownTypes.OnDeserializingAttribute(compilationStartContext.Compilation); INamedTypeSymbol onDeserializedAttribute = WellKnownTypes.OnDeserializedAttribute(compilationStartContext.Compilation); INamedTypeSymbol onSerializingAttribute = WellKnownTypes.OnSerializingAttribute(compilationStartContext.Compilation); INamedTypeSymbol onSerializedAttribute = WellKnownTypes.OnSerializedAttribute(compilationStartContext.Compilation); INamedTypeSymbol obsoleteAttribute = WellKnownTypes.ObsoleteAttribute(compilationStartContext.Compilation); ImmutableHashSet <INamedTypeSymbol> attributeSetForMethodsToIgnore = ImmutableHashSet.Create( conditionalAttributeSymbol, onDeserializedAttribute, onDeserializingAttribute, onSerializedAttribute, onSerializingAttribute, obsoleteAttribute); UnusedParameterDictionary unusedMethodParameters = new ConcurrentDictionary <IMethodSymbol, ISet <IParameterSymbol> >(); ISet <IMethodSymbol> methodsUsedAsDelegates = new HashSet <IMethodSymbol>(); // Create a list of functions to exclude from analysis. We assume that any function that is used in an IMethodBindingExpression // cannot have its signature changed, and add it to the list of methods to be excluded from analysis. compilationStartContext.RegisterOperationAction(operationContext => { var methodBinding = (IMethodReferenceOperation)operationContext.Operation; methodsUsedAsDelegates.Add(methodBinding.Method.OriginalDefinition); }, OperationKind.MethodReference); compilationStartContext.RegisterOperationBlockStartAction(startOperationBlockContext => { // We only care about methods. if (!(startOperationBlockContext.OwningSymbol is IMethodSymbol method)) { return; } AnalyzeMethod(method, startOperationBlockContext, unusedMethodParameters, eventsArgSymbol, methodsUsedAsDelegates, attributeSetForMethodsToIgnore); foreach (var localFunctionOperation in startOperationBlockContext.OperationBlocks.SelectMany(o => o.Descendants()).OfType <ILocalFunctionOperation>()) { AnalyzeMethod(localFunctionOperation.Symbol, startOperationBlockContext, unusedMethodParameters, eventsArgSymbol, methodsUsedAsDelegates, attributeSetForMethodsToIgnore); } }); // Register a compilation end action to filter all methods used as delegates and report any diagnostics compilationStartContext.RegisterCompilationEndAction(compilationAnalysisContext => { // Report diagnostics for unused parameters. var unusedParameters = unusedMethodParameters.Where(kvp => !methodsUsedAsDelegates.Contains(kvp.Key)).SelectMany(kvp => kvp.Value); foreach (var parameter in unusedParameters) { var diagnostic = Diagnostic.Create(Rule, parameter.Locations[0], parameter.Name, parameter.ContainingSymbol.Name); compilationAnalysisContext.ReportDiagnostic(diagnostic); } }); }); }
public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.Create <string>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableHashSet.Create <int>(1, 2, 3)); }
public void FromBencodexWithActions() { var bytes = new byte[] { 0x64, 0x31, 0x3a, 0x53, 0x37, 0x30, 0x3a, 0x30, 0x44, 0x02, 0x20, 0x4c, 0xf2, 0xd4, 0xd9, 0x22, 0x97, 0xa6, 0x7f, 0xd0, 0x47, 0x69, 0xf2, 0x53, 0xe2, 0x0e, 0x62, 0x13, 0xf0, 0x63, 0xb8, 0x14, 0x2f, 0xff, 0x4c, 0xb9, 0xe9, 0xc0, 0x47, 0x33, 0xed, 0xbc, 0x16, 0x02, 0x20, 0x0e, 0xfe, 0xbb, 0x0e, 0x2a, 0x7b, 0xcf, 0x4d, 0x5c, 0x7a, 0x62, 0x8e, 0xd2, 0xe7, 0xa9, 0x1f, 0x44, 0x0a, 0xfa, 0x31, 0x19, 0x7f, 0xf6, 0x16, 0xfb, 0x32, 0xd8, 0xba, 0xda, 0xd3, 0xe9, 0xcc, 0x31, 0x3a, 0x61, 0x6c, 0x64, 0x75, 0x37, 0x3a, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x69, 0x64, 0x75, 0x36, 0x3a, 0x61, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x75, 0x36, 0x3a, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x64, 0x75, 0x36, 0x3a, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x75, 0x33, 0x3a, 0x6f, 0x72, 0x63, 0x75, 0x31, 0x34, 0x3a, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x32, 0x30, 0x3a, 0xc2, 0xa8, 0x60, 0x14, 0x07, 0x3d, 0x66, 0x2a, 0x4a, 0x9b, 0xfc, 0xf9, 0xcb, 0x54, 0x26, 0x3d, 0xfa, 0x4f, 0x5c, 0xbc, 0x75, 0x36, 0x3a, 0x77, 0x65, 0x61, 0x70, 0x6f, 0x6e, 0x75, 0x34, 0x3a, 0x77, 0x61, 0x6e, 0x64, 0x65, 0x65, 0x64, 0x75, 0x37, 0x3a, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x69, 0x64, 0x75, 0x35, 0x3a, 0x73, 0x6c, 0x65, 0x65, 0x70, 0x75, 0x36, 0x3a, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x64, 0x75, 0x37, 0x3a, 0x7a, 0x6f, 0x6e, 0x65, 0x5f, 0x69, 0x64, 0x69, 0x31, 0x30, 0x65, 0x65, 0x65, 0x65, 0x31, 0x3a, 0x6e, 0x69, 0x30, 0x65, 0x31, 0x3a, 0x70, 0x36, 0x35, 0x3a, 0x04, 0x46, 0x11, 0x5b, 0x01, 0x31, 0xba, 0xcc, 0xf9, 0x4a, 0x58, 0x56, 0xed, 0xe8, 0x71, 0x29, 0x5f, 0x6f, 0x3d, 0x35, 0x2e, 0x68, 0x47, 0xcd, 0xa9, 0xc0, 0x3e, 0x89, 0xfe, 0x09, 0xf7, 0x32, 0x80, 0x87, 0x11, 0xec, 0x97, 0xaf, 0x6e, 0x34, 0x1f, 0x11, 0x0a, 0x32, 0x6d, 0xa1, 0xbd, 0xb8, 0x1f, 0x5a, 0xe3, 0xba, 0xdf, 0x76, 0xa9, 0x0b, 0x22, 0xc8, 0xc4, 0x91, 0xae, 0xd3, 0xaa, 0xa2, 0x96, 0x31, 0x3a, 0x73, 0x32, 0x30, 0x3a, 0xc2, 0xa8, 0x60, 0x14, 0x07, 0x3d, 0x66, 0x2a, 0x4a, 0x9b, 0xfc, 0xf9, 0xcb, 0x54, 0x26, 0x3d, 0xfa, 0x4f, 0x5c, 0xbc, 0x31, 0x3a, 0x74, 0x75, 0x32, 0x37, 0x3a, 0x32, 0x30, 0x31, 0x38, 0x2d, 0x31, 0x31, 0x2d, 0x32, 0x31, 0x54, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x2e, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x31, 0x3a, 0x75, 0x6c, 0x32, 0x30, 0x3a, 0xc2, 0xa8, 0x60, 0x14, 0x07, 0x3d, 0x66, 0x2a, 0x4a, 0x9b, 0xfc, 0xf9, 0xcb, 0x54, 0x26, 0x3d, 0xfa, 0x4f, 0x5c, 0xbc, 0x65, 0x65, }; PublicKey publicKey = new PrivateKey( new byte[] { 0xcf, 0x36, 0xec, 0xf9, 0xe4, 0x7c, 0x87, 0x9a, 0x0d, 0xbf, 0x46, 0xb2, 0xec, 0xd8, 0x3f, 0xd2, 0x76, 0x18, 0x2a, 0xde, 0x02, 0x65, 0x82, 0x5e, 0x3b, 0x8c, 0x6b, 0xa2, 0x14, 0x46, 0x7b, 0x76, } ).PublicKey; Transaction <PolymorphicAction <BaseAction> > tx = Transaction <PolymorphicAction <BaseAction> > .Deserialize(bytes); Assert.Equal(publicKey, tx.PublicKey); Assert.Equal( ImmutableHashSet.Create(new Address(publicKey)), tx.UpdatedAddresses ); Assert.Equal(new Address(publicKey), tx.Signer); Assert.Equal(new DateTimeOffset(2018, 11, 21, 0, 0, 0, TimeSpan.Zero), tx.Timestamp); AssertBytesEqual( new byte[] { 0x30, 0x44, 0x02, 0x20, 0x4c, 0xf2, 0xd4, 0xd9, 0x22, 0x97, 0xa6, 0x7f, 0xd0, 0x47, 0x69, 0xf2, 0x53, 0xe2, 0x0e, 0x62, 0x13, 0xf0, 0x63, 0xb8, 0x14, 0x2f, 0xff, 0x4c, 0xb9, 0xe9, 0xc0, 0x47, 0x33, 0xed, 0xbc, 0x16, 0x02, 0x20, 0x0e, 0xfe, 0xbb, 0x0e, 0x2a, 0x7b, 0xcf, 0x4d, 0x5c, 0x7a, 0x62, 0x8e, 0xd2, 0xe7, 0xa9, 0x1f, 0x44, 0x0a, 0xfa, 0x31, 0x19, 0x7f, 0xf6, 0x16, 0xfb, 0x32, 0xd8, 0xba, 0xda, 0xd3, 0xe9, 0xcc, }, tx.Signature ); AssertBytesEqual( new TxId( new byte[] { 0x2c, 0x7d, 0x15, 0xf4, 0xc1, 0xd5, 0x36, 0xce, 0x4c, 0xa2, 0xa3, 0x59, 0xbc, 0xd8, 0x73, 0xa9, 0x4f, 0x3c, 0x65, 0x18, 0x10, 0x9f, 0xfa, 0xbc, 0xf8, 0x7e, 0x34, 0x85, 0xf3, 0x63, 0xa5, 0x34, } ), tx.Id ); Assert.Equal(2, tx.Actions.Count); Assert.IsType <Attack>(tx.Actions[0].InnerAction); var targetAddress = ((Bencodex.Types.Dictionary)tx.Actions[0].InnerAction.PlainValue) .GetValue <Binary>("target_address").Value; AssertBytesEqual( new Address(publicKey).ToByteArray(), targetAddress ); Assert.Equal( new Bencodex.Types.Dictionary(new Dictionary <IKey, IValue> { { (Text)"weapon", (Text)"wand" }, { (Text)"target", (Text)"orc" }, { (Text)"target_address", (Binary) new Address(publicKey).ToByteArray() }, }), tx.Actions[0].InnerAction.PlainValue ); Assert.IsType <Sleep>(tx.Actions[1].InnerAction); Assert.Equal( new Bencodex.Types.Dictionary(new Dictionary <IKey, IValue> { { (Text)"zone_id", (Integer)10 }, }), tx.Actions[1].InnerAction.PlainValue ); Assert.Equal(bytes.Length, tx.BytesLength); }
public OutputCompletionSource(Resource?resource) { _resources = resource == null ? ImmutableHashSet <Resource> .Empty : ImmutableHashSet.Create(resource); _taskCompletionSource = new TaskCompletionSource <OutputData <T> >(); Output = new Output <T>(_taskCompletionSource.Task); }
public void ClusterHeartbeatSenderState_must_init_with_empty() { _emptyState.Init(ImmutableHashSet.Create <UniqueAddress>()).ActiveReceivers.IsEmpty.ShouldBeTrue(); }
public static bool HasOnlyBlittableFields(this ITypeSymbol type) => HasOnlyBlittableFields(type, ImmutableHashSet.Create <ITypeSymbol>(SymbolEqualityComparer.Default));
public void ClusterHeartbeatSenderState_must_not_use_removed_members() { _emptyState.AddMember(bb).AddMember(cc).RemoveMember(bb).ActiveReceivers.ShouldBe(ImmutableHashSet.Create <UniqueAddress>(cc)); }
public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(compilationStartContext => { var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationStartContext.Compilation); INamedTypeSymbol?eventsArgSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs); // Ignore conditional methods (FxCop compat - One conditional will often call another conditional method as its only use of a parameter) INamedTypeSymbol?conditionalAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute); // Ignore methods with special serialization attributes (FxCop compat - All serialization methods need to take 'StreamingContext') INamedTypeSymbol?onDeserializingAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializingAttribute); INamedTypeSymbol?onDeserializedAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializedAttribute); INamedTypeSymbol?onSerializingAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializingAttribute); INamedTypeSymbol?onSerializedAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializedAttribute); INamedTypeSymbol?obsoleteAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); INamedTypeSymbol?serializationInfoType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationSerializationInfo); INamedTypeSymbol?streamingContextType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationStreamingContext); ImmutableHashSet <INamedTypeSymbol?> attributeSetForMethodsToIgnore = ImmutableHashSet.Create( conditionalAttributeSymbol, onDeserializedAttribute, onDeserializingAttribute, onSerializedAttribute, onSerializingAttribute, obsoleteAttribute); compilationStartContext.RegisterSymbolStartAction(symbolStartContext => { // Map from parameter to a bool indicating if the parameter is used or not. var parameterUsageMap = new ConcurrentDictionary <IParameterSymbol, bool>(); // Set of methods which are used as delegates. var methodsUsedAsDelegates = new ConcurrentDictionary <IMethodSymbol, bool>(); // Add candidate parameters for methods. symbolStartContext.RegisterOperationBlockStartAction(startOperationBlockContext => { if (startOperationBlockContext.OwningSymbol is IMethodSymbol method && ShouldAnalyzeMethod(method, startOperationBlockContext, eventsArgSymbol, attributeSetForMethodsToIgnore, serializationInfoType, streamingContextType)) { AddParameters(method, parameterUsageMap); } }); // Add candidate parameters for local functions. symbolStartContext.RegisterOperationAction( context => AddParameters(((ILocalFunctionOperation)context.Operation).Symbol, parameterUsageMap), OperationKind.LocalFunction); // Add methods used as delegates. symbolStartContext.RegisterOperationAction( context => methodsUsedAsDelegates.TryAdd(((IMethodReferenceOperation)context.Operation).Method.OriginalDefinition, true), OperationKind.MethodReference); // Mark parameters with a parameter reference as used. symbolStartContext.RegisterOperationAction( context => parameterUsageMap.AddOrUpdate( ((IParameterReferenceOperation)context.Operation).Parameter, addValue: true, updateValueFactory: ReturnTrue), OperationKind.ParameterReference); // Report unused parameters in SymbolEnd action. symbolStartContext.RegisterSymbolEndAction( context => ReportUnusedParameters(context, parameterUsageMap, methodsUsedAsDelegates)); }, SymbolKind.NamedType); }); }