public AnalyserTestData(
     AnalyzerData data,
     ImmutableSortedSet<string> usedTypes, ImmutableSortedSet<string> analyzedMethods
     )
 {
     this.data = data;
       this.usedTypes = usedTypes;
       this.analyzedMethods = analyzedMethods;
 }
Ejemplo n.º 2
0
        private EntityType AddEntityType(EntityType entityType)
        {
            var previousLength = _entities.Count;
            _entities = _entities.Add(entityType);

            if (previousLength == _entities.Count)
            {
                throw new InvalidOperationException(CoreStrings.DuplicateEntityType(entityType.Name));
            }

            return entityType;
        }
Ejemplo n.º 3
0
 public CurrentClusterState(
     ImmutableSortedSet<Member> members,
     ImmutableHashSet<Member> unreachable,
     ImmutableHashSet<Address> seenBy,
     Address leader,
     ImmutableDictionary<string, Address> roleLeaderMap)
 {
     _members = members;
     _unreachable = unreachable;
     _seenBy = seenBy;
     _leader = leader;
     _roleLeaderMap = roleLeaderMap;
 }
Ejemplo n.º 4
0
        public Gossip(ImmutableSortedSet<Member> members, GossipOverview overview, VectorClock version)
        {
            _members = members;
            _overview = overview;
            _version = version;

            _membersMap = new Lazy<ImmutableDictionary<UniqueAddress, Member>>(
                () => members.ToImmutableDictionary(m => m.UniqueAddress, m => m));

            ReachabilityExcludingDownedObservers = new Lazy<Reachability>(() =>
            {
                var downed = Members.Where(m => m.Status == MemberStatus.Down).ToList();
                return Overview.Reachability.RemoveObservers(downed.Select(m => m.UniqueAddress).ToImmutableHashSet());
            });

            if (Cluster.IsAssertInvariantsEnabled) AssertInvariants();
        }
            public Listener(TestLatch latch, ImmutableList<Address> expectedAddresses)
            {
                _latch = latch;
                _expectedAddresses = expectedAddresses;

                Receive<ClusterEvent.CurrentClusterState>(state =>
                {
                    _members = state.Members;
                });

                Receive<ClusterEvent.MemberUp>(m =>
                {
                    _members = _members.Remove(m.Member).Add(m.Member);

                    if (!_members.Select(c => c.Address).Except(_expectedAddresses).Any())
                        _latch.CountDown();
                });
            }
Ejemplo n.º 6
0
        public void A_gossip_must_merge_unreachable()
        {
            var r1 = Reachability.Empty.
                     Unreachable(b1.UniqueAddress, a1.UniqueAddress).
                     Unreachable(b1.UniqueAddress, c1.UniqueAddress);
            var g1 = new Gossip(ImmutableSortedSet.Create(a1, b1, c1), new GossipOverview(r1));
            var r2 = Reachability.Empty.Unreachable(a1.UniqueAddress, d1.UniqueAddress);
            var g2 = new Gossip(ImmutableSortedSet.Create(a1, b1, c1, d1), new GossipOverview(r2));

            var merged1 = g1.Merge(g2);

            merged1.Overview.Reachability.AllUnreachable.Should()
            .BeEquivalentTo(ImmutableHashSet.Create(a1.UniqueAddress, c1.UniqueAddress, d1.UniqueAddress));

            var merged2 = g2.Merge(g1);

            merged2.Overview.Reachability.AllUnreachable.Should()
            .BeEquivalentTo(merged1.Overview.Reachability.AllUnreachable);
        }
Ejemplo n.º 7
0
        public void ClusterMessages_must_be_serializable()
        {
            var address        = new Address("akka.tcp", "system", "some.host.org", 4711);
            var uniqueAddress  = new UniqueAddress(address, 17);
            var address2       = new Address("akka.tcp", "system", "other.host.org", 4711);
            var uniqueAddress2 = new UniqueAddress(address2, 18);

            CheckSerialization(new InternalClusterAction.Join(uniqueAddress, ImmutableHashSet.Create("foo", "bar")));
            CheckSerialization(new ClusterUserAction.Leave(address));
            CheckSerialization(new ClusterUserAction.Down(address));
            CheckSerialization(new InternalClusterAction.InitJoin());
            CheckSerialization(new InternalClusterAction.InitJoinAck(address));
            CheckSerialization(new InternalClusterAction.InitJoinNack(address));
            CheckSerialization(new ClusterHeartbeatSender.Heartbeat(address));
            CheckSerialization(new ClusterHeartbeatSender.HeartbeatRsp(uniqueAddress));

            var node1 = new VectorClock.Node("node1");
            var node2 = new VectorClock.Node("node2");
            var node3 = new VectorClock.Node("node3");
            var node4 = new VectorClock.Node("node4");
            var g1    =
                new Gossip(ImmutableSortedSet.Create(a1, b1, c1, d1)).Increment(node1)
                .Increment(node2)
                .Seen(a1.UniqueAddress)
                .Seen(b1.UniqueAddress);
            var g2            = g1.Increment(node3).Increment(node4).Seen(a1.UniqueAddress).Seen(c1.UniqueAddress);
            var reachability3 =
                Reachability.Empty.Unreachable(a1.UniqueAddress, e1.UniqueAddress)
                .Unreachable(b1.UniqueAddress, e1.UniqueAddress);
            var g3 = g2.Copy(members: ImmutableSortedSet.Create(a1, b1, c1, d1, e1),
                             overview: g2.Overview.Copy(reachability: reachability3));

            CheckSerialization(new GossipEnvelope(a1.UniqueAddress, uniqueAddress2, g1));
            CheckSerialization(new GossipEnvelope(a1.UniqueAddress, uniqueAddress2, g2));
            CheckSerialization(new GossipEnvelope(a1.UniqueAddress, uniqueAddress2, g3));

            CheckSerialization(new GossipStatus(a1.UniqueAddress, g1.Version));
            CheckSerialization(new GossipStatus(a1.UniqueAddress, g2.Version));
            CheckSerialization(new GossipStatus(a1.UniqueAddress, g3.Version));

            CheckSerialization(new InternalClusterAction.Welcome(uniqueAddress, g2));
        }
Ejemplo n.º 8
0
        public bool ParkVehicle(Vehicle vehicle, ParkingSpot parkingSpot)
        {
            if (parkedVehicles.ContainsKey(vehicle.VehicleNumber))
            {
                throw new InvalidOperationException($"Vehicle with number {vehicle.VehicleNumber} is already parked");
            }
            ParkingSpot vacantSpot = freeParkingSpots.FirstOrDefault(spot => spot.Floor == parkingSpot.Floor &&
                                                                     spot.Row == parkingSpot.Row &&
                                                                     spot.ParkingSpotTypes == parkingSpot.ParkingSpotTypes &&
                                                                     spot.StartPosition <= parkingSpot.StartPosition &&
                                                                     spot.SpotCount >= parkingSpot.SpotCount
                                                                     );

            if (vacantSpot == null)
            {
                throw new KeyNotFoundException("The spot could not be found");
            }

            freeParkingSpots = freeParkingSpots.Remove(vacantSpot);
            parkedVehicles.TryAdd(vehicle.VehicleNumber, parkingSpot);
            if (parkingSpot.StartPosition > vacantSpot.StartPosition)
            {
                var newSpot = new ParkingSpot()
                {
                    Floor = vacantSpot.Floor, ParkingSpotTypes = vacantSpot.ParkingSpotTypes, Row = vacantSpot.Row, StartPosition = vacantSpot.StartPosition
                };
                newSpot.SpotCount = parkingSpot.StartPosition - vacantSpot.StartPosition;
                freeParkingSpots  = freeParkingSpots.Add(newSpot);
            }
            if (vacantSpot.SpotCount > parkingSpot.SpotCount)
            {
                var newSpot = new ParkingSpot()
                {
                    Floor = vacantSpot.Floor, ParkingSpotTypes = vacantSpot.ParkingSpotTypes, Row = vacantSpot.Row
                };
                newSpot.StartPosition = parkingSpot.StartPosition + parkingSpot.SpotCount;
                newSpot.SpotCount     = vacantSpot.SpotCount - newSpot.StartPosition + 1;
                freeParkingSpots      = freeParkingSpots.Add(newSpot);
            }
            Interlocked.Add(ref _freeSpots, parkingSpot.SpotCount * -1);
            return(true);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Clears all orders from dictionary
        /// </summary>
        /// <returns></returns>
        public async Task ClearAsync(CancellationToken cancellationToken)
        {
            IReliableDictionary <string, Order> orders =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Order> >(this.setName);

            var retryCount = 0;
            List <Exception> exceptions = new List <Exception>();

            while (retryCount < 3)
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    await ExecuteClearAsync(orders);

                    lock (this.lockObject)
                    {
                        this.SecondaryIndex = this.SecondaryIndex.Clear();
                    }
                    return;
                }
                catch (TimeoutException ex)
                {
                    exceptions.Add(ex);
                    retryCount++;
                    continue;
                }
                catch (TransactionFaultedException ex)
                {
                    exceptions.Add(ex);
                    retryCount++;
                    continue;
                }
            }
            if (exceptions.Count > 0)
            {
                throw new AggregateException(
                          "Encounted errors while trying to clear orders",
                          exceptions);
            }
        }
Ejemplo n.º 10
0
        public void CanSerializeImmutableCollectionsReferencedThroughInterfaceInFields()
        {
            var expected = new TestClass(
                dictionary: ImmutableDictionary.CreateRange(new[]
            {
                new KeyValuePair <int, int>(2, 1),
                new KeyValuePair <int, int>(3, 2),
            }),
                list: ImmutableList.CreateRange(new[] { "c", "d" }),
                queue: ImmutableQueue.CreateRange(new[] { "e", "f" }),
                sortedSet: ImmutableSortedSet.CreateRange(new[] { "g", "h" }),
                hashSet: ImmutableHashSet.CreateRange(new[] { "i", "j" }),
                stack: ImmutableStack.CreateRange(new[] { "k", "l" }));

            Serialize(expected);
            Reset();
            var actual = Deserialize <TestClass>();

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 11
0
        public void A_gossip_must_merge_members_by_removing_removed_members()
        {
            // c3 removed
            var r1 = Reachability.Empty.Unreachable(b1.UniqueAddress, a1.UniqueAddress);
            var g1 = new Gossip(ImmutableSortedSet.Create(a1, b1), new GossipOverview(r1));
            var r2 = r1.Unreachable(b1.UniqueAddress, c3.UniqueAddress);
            var g2 = new Gossip(ImmutableSortedSet.Create(a1, b1, c3), new GossipOverview(r2));

            var merged1 = g1.Merge(g2);

            merged1.Members.Should().BeEquivalentTo(ImmutableHashSet.Create(a1, b1));
            merged1.Overview.Reachability.AllUnreachable.Should()
            .BeEquivalentTo(ImmutableHashSet.Create(a1.UniqueAddress));

            var merged2 = g2.Merge(g1);

            merged2.Overview.Reachability.AllUnreachable.Should()
            .BeEquivalentTo(merged1.Overview.Reachability.AllUnreachable);
            merged2.Members.Should().BeEquivalentTo(merged1.Members);
        }
Ejemplo n.º 12
0
            public Listener(TestLatch latch, ImmutableList <Address> expectedAddresses)
            {
                _latch             = latch;
                _expectedAddresses = expectedAddresses;

                Receive <ClusterEvent.CurrentClusterState>(state =>
                {
                    _members = state.Members;
                });

                Receive <ClusterEvent.MemberUp>(m =>
                {
                    _members = _members.Remove(m.Member).Add(m.Member);

                    if (!_members.Select(c => c.Address).Except(_expectedAddresses).Any())
                    {
                        _latch.CountDown();
                    }
                });
            }
Ejemplo n.º 13
0
        /// <inheritdoc/>
        public override void ConvertToSurrogate(ImmutableSortedSet <T> value, ref ImmutableSortedSetSurrogate <T> surrogate)
        {
            if (value is null)
            {
                surrogate = default;
                return;
            }
            else
            {
                surrogate = new ImmutableSortedSetSurrogate <T>
                {
                    Values = new List <T>(value)
                };

                if (!ReferenceEquals(value.KeyComparer, Comparer <T> .Default))
                {
                    surrogate.KeyComparer = value.KeyComparer;
                }
            }
        }
Ejemplo n.º 14
0
        private EvaluationContext(
            MethodContextReuseConstraints?methodContextReuseConstraints,
            CSharpCompilation compilation,
            MethodSymbol currentFrame,
            MethodSymbol?currentSourceMethod,
            ImmutableArray <LocalSymbol> locals,
            ImmutableSortedSet <int> inScopeHoistedLocalSlots,
            MethodDebugInfo <TypeSymbol, LocalSymbol> methodDebugInfo)
        {
            RoslynDebug.AssertNotNull(inScopeHoistedLocalSlots);
            RoslynDebug.AssertNotNull(methodDebugInfo);

            MethodContextReuseConstraints = methodContextReuseConstraints;
            Compilation          = compilation;
            _currentFrame        = currentFrame;
            _currentSourceMethod = currentSourceMethod;
            _locals = locals;
            _inScopeHoistedLocalSlots = inScopeHoistedLocalSlots;
            _methodDebugInfo          = methodDebugInfo;
        }
        public void ShouldGenerateModelFromScripts()
        {
            var testProjectDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "../../../");
            var scriptsPath          = Path.Combine(testProjectDirectory, "Scripts");

            var dbSchemaReader = new DbSchemaReader();

            var actual = dbSchemaReader.Read(scriptsPath, new TaskLoggingHelper(GetTask(), "build"));

            var brandTable = new Table("brand", ImmutableList.Create(
                                           new Column("id", "int", false, false, true),
                                           new Column("name", "string", false, false, false),
                                           new Column("logo", "string", true, false, false),
                                           new Column("archived", "bool", true, false, false),
                                           new Column("color", "string", false, false, false),
                                           new Column("external_id", "string", true, false, false)
                                           ), ImmutableSortedSet.Create("id"));

            actual.Tables.ShouldDeepEqual(ImmutableList.Create(brandTable));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="members">TBD</param>
        /// <param name="overview">TBD</param>
        /// <param name="version">TBD</param>
        /// <exception cref="ArgumentException">TBD</exception>
        public Gossip(ImmutableSortedSet <Member> members, GossipOverview overview, VectorClock version)
        {
            _members  = members;
            _overview = overview;
            _version  = version;

            _membersMap = new Lazy <ImmutableDictionary <UniqueAddress, Member> >(
                () => members.ToImmutableDictionary(m => m.UniqueAddress, m => m));

            ReachabilityExcludingDownedObservers = new Lazy <Reachability>(() =>
            {
                var downed = Members.Where(m => m.Status == MemberStatus.Down);
                return(Overview.Reachability.RemoveObservers(downed.Select(m => m.UniqueAddress).ToImmutableHashSet()));
            });

            if (Cluster.IsAssertInvariantsEnabled)
            {
                AssertInvariants();
            }
        }
        public void ShouldGenerateModelFromScripts10()
        {
            var testProjectDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "../../../");
            var scriptsPath          = Path.Combine(testProjectDirectory, "Scripts10");

            var dbSchemaReader = new DbSchemaReader();

            var actual = dbSchemaReader.Read(scriptsPath, new TaskLoggingHelper(GetTask(), "build"));

            var contract = new Table("contract", ImmutableList.Create(
                                         new Column("id", "string", false, false, false)
                                         ), ImmutableSortedSet <string> .Empty);

            var other = new Table("other", ImmutableList.Create(
                                      new Column("id", "int", false, false, true),
                                      new Column("contract_id", "int", false, false, false)
                                      ), ImmutableSortedSet.Create("id"));

            actual.Tables.ShouldDeepEqual(ImmutableList.Create(contract, other));
        }
Ejemplo n.º 18
0
        public void CanDeserialiseImmutableSortedSet(bool autoCompile)
        {
            var testClass = new ImmutableSortedSetTestClass(ImmutableSortedSet.Create("a", "b", "c"));
            var model     = RuntimeTypeModel.Create();

            model.AutoCompile = autoCompile;

            ImmutableSortedSetTestClass testClassClone;

            using (var ms = new MemoryStream())
            {
                model.Serialize(ms, testClass);
                ms.Position = 0;
#pragma warning disable CS0618
                testClassClone = (ImmutableSortedSetTestClass)model.Deserialize(ms, null, testClass.GetType());
#pragma warning restore CS0618
            }

            Assert.Equal((IEnumerable <string>)testClass.Set, (IEnumerable <string>)testClassClone.Set);
        }
Ejemplo n.º 19
0
 public static uint256 CalculateHash(
     DateTimeOffset inputRegistrationStart,
     TimeSpan inputRegistrationTimeout,
     TimeSpan connectionConfirmationTimeout,
     TimeSpan outputRegistrationTimeout,
     TimeSpan transactionSigningTimeout,
     MoneyRange allowedInputAmounts,
     ImmutableSortedSet <ScriptType> allowedInputTypes,
     MoneyRange allowedOutputAmounts,
     ImmutableSortedSet <ScriptType> allowedOutputTypes,
     Network network,
     long feePerK,
     CoordinationFeeRate coordinationFeeRate,
     int maxTransactionSize,
     long minRelayTxFeePerK,
     long maxAmountCredentialValue,
     long maxVsizeCredentialValue,
     long maxVsizeAllocationPerAlice,
     CredentialIssuerParameters amountCredentialIssuerParameters,
     CredentialIssuerParameters vsizeCredentialIssuerParameters)
 => StrobeHasher.Create(ProtocolConstants.RoundStrobeDomain)
 .Append(ProtocolConstants.RoundInputRegistrationStartStrobeLabel, inputRegistrationStart)
 .Append(ProtocolConstants.RoundInputRegistrationTimeoutStrobeLabel, inputRegistrationTimeout)
 .Append(ProtocolConstants.RoundConnectionConfirmationTimeoutStrobeLabel, connectionConfirmationTimeout)
 .Append(ProtocolConstants.RoundOutputRegistrationTimeoutStrobeLabel, outputRegistrationTimeout)
 .Append(ProtocolConstants.RoundTransactionSigningTimeoutStrobeLabel, transactionSigningTimeout)
 .Append(ProtocolConstants.RoundAllowedInputAmountsStrobeLabel, allowedInputAmounts)
 .Append(ProtocolConstants.RoundAllowedInputTypesStrobeLabel, allowedInputTypes)
 .Append(ProtocolConstants.RoundAllowedOutputAmountsStrobeLabel, allowedOutputAmounts)
 .Append(ProtocolConstants.RoundAllowedOutputTypesStrobeLabel, allowedOutputTypes)
 .Append(ProtocolConstants.RoundNetworkStrobeLabel, network.ToString())
 .Append(ProtocolConstants.RoundFeeRateStrobeLabel, feePerK)
 .Append(ProtocolConstants.RoundCoordinationFeeRateStrobeLabel, coordinationFeeRate)
 .Append(ProtocolConstants.RoundMaxTransactionSizeStrobeLabel, maxTransactionSize)
 .Append(ProtocolConstants.RoundMinRelayTxFeeStrobeLabel, minRelayTxFeePerK)
 .Append(ProtocolConstants.RoundMaxAmountCredentialValueStrobeLabel, maxAmountCredentialValue)
 .Append(ProtocolConstants.RoundMaxVsizeCredentialValueStrobeLabel, maxVsizeCredentialValue)
 .Append(ProtocolConstants.RoundMaxVsizePerAliceStrobeLabel, maxVsizeAllocationPerAlice)
 .Append(ProtocolConstants.RoundAmountCredentialIssuerParametersStrobeLabel, amountCredentialIssuerParameters)
 .Append(ProtocolConstants.RoundVsizeCredentialIssuerParametersStrobeLabel, vsizeCredentialIssuerParameters)
 .GetHash();
        private static void AnalyzeMethod(
            SyntaxNodeAnalysisContext context,
            ImmutableHashSet <string> bannedCategories,
            NUnitTypes types,
            MethodDeclarationSyntax syntax
            )
        {
            SemanticModel model = context.SemanticModel;

            IMethodSymbol method = model.GetDeclaredSymbol(syntax, context.CancellationToken);

            if (method == null)
            {
                return;
            }

            if (!IsTestMethod(types, method))
            {
                return;
            }

            ImmutableSortedSet <string> categories = GatherTestMethodCategories(types, method);

            if (!categories.Overlaps(RequiredCategories))
            {
                context.ReportDiagnostic(Diagnostic.Create(
                                             Diagnostics.NUnitCategory,
                                             syntax.Identifier.GetLocation(),
                                             $"Test must be categorized as one of [{string.Join( ", ", RequiredCategories )}], but saw [{string.Join( ", ", categories )}]. See http://docs.dev.d2l/index.php/Test_Categories."
                                             ));
            }

            if (categories.Overlaps(bannedCategories))
            {
                context.ReportDiagnostic(Diagnostic.Create(
                                             Diagnostics.NUnitCategory,
                                             syntax.Identifier.GetLocation(),
                                             $"Test is categorized as [{string.Join( ", ", categories )}]; however, the following categories are banned in this assembly: [{string.Join( ", ", bannedCategories )}]."
                                             ));
            }
        }
        /// <summary>
        /// Obtains a combined holiday calendar instance.
        /// <para>
        /// This combines the two input calendars.
        /// It is intended for up-front occasional use rather than continuous use, as it can be relatively slow.
        ///
        /// </para>
        /// </summary>
        /// <param name="cal1">  the first calendar </param>
        /// <param name="cal2">  the second calendar </param>
        /// <returns> the combined calendar </returns>
        public static ImmutableHolidayCalendar combined(ImmutableHolidayCalendar cal1, ImmutableHolidayCalendar cal2)
        {
            // do not override combinedWith(), as this is too slow
            if (cal1 == cal2)
            {
                return(ArgChecker.notNull(cal1, "cal1"));
            }
            HolidayCalendarId newId = cal1.id.combinedWith(cal2.id);

            // use slow version if lookup arrays do not overlap
            int endYear1 = cal1.startYear + cal1.lookup.Length / 12;
            int endYear2 = cal2.startYear + cal2.lookup.Length / 12;

            if (endYear1 < cal2.startYear || endYear2 < cal1.startYear)
            {
                ImmutableSortedSet <LocalDate> newHolidays = ImmutableSortedSet.copyOf(Iterables.concat(cal1.Holidays, cal2.Holidays));
                ImmutableSet <DayOfWeek>       newWeekends = ImmutableSet.copyOf(Iterables.concat(cal1.WeekendDays, cal2.WeekendDays));
                return(of(newId, newHolidays, newWeekends));
            }

            // merge calendars using bitwise operations
            // figure out which has the lower start year and use that as the base
            bool cal1Lower = cal1.startYear <= cal2.startYear;

            int[] lookup1        = cal1Lower ? cal1.lookup : cal2.lookup;
            int[] lookup2        = cal1Lower ? cal2.lookup : cal1.lookup;
            int   newStartYear   = cal1Lower ? cal1.startYear : cal2.startYear;
            int   otherStartYear = cal1Lower ? cal2.startYear : cal1.startYear;
            // copy base array and map data from the other on top
            int newSize = Math.Max(lookup1.Length, lookup2.Length + (otherStartYear - newStartYear) * 12);
            int offset  = (otherStartYear - newStartYear) * 12;

            int[] newLookup = Arrays.copyOf(lookup1, newSize);
            for (int i = 0; i < lookup2.Length; i++)
            {
                newLookup[i + offset] &= lookup2[i];         // use & because 1 = business day (not holiday)
            }
            int newWeekends = cal1.weekends | cal2.weekends; // use | because 1 = weekend day

            return(new ImmutableHolidayCalendar(newId, newWeekends, newStartYear, newLookup, false));
        }
Ejemplo n.º 22
0
        async Task CanHandleBlankAndEmptyValues()
        {
            var builder = ImmutableSortedSet.CreateBuilder <string>();

            builder.Add("");

            var blankTaggedTextElement = new TaggedFieldValue("text", builder.ToImmutableSortedSet <string>());

            builder.Clear();
            builder.Add("tag");

            var taggedBlankTextElement = new TaggedFieldValue("", builder.ToImmutableSortedSet <string>());

            var path    = Path.Combine(TestAtomFeed.Directory, "BlankAndEmptySearchResults.xml");
            var message = new HttpResponseMessage(HttpStatusCode.OK);

            message.Content = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.Read));

            using (var stream = await SearchResultStream.CreateAsync(message))
            {
                int count = 0;

                foreach (dynamic observedResult in stream)
                {
                    Assert.Equal(observedResult._raw, string.Empty);
                    Assert.Null(observedResult.SegmentedRaw);

                    Assert.Equal(observedResult.blank_tagged_text_element, blankTaggedTextElement);
                    Assert.Equal(observedResult.empty_tagged_text_element, blankTaggedTextElement);

                    Assert.Equal(observedResult.blank_text_element, string.Empty);
                    Assert.Equal(observedResult.blank_value_element, string.Empty);
                    Assert.Equal(observedResult.empty_text_element, string.Empty);

                    Assert.Equal(observedResult.tagged_blank_text_element, taggedBlankTextElement);
                    Assert.Equal(observedResult.tagged_empty_text_element, taggedBlankTextElement);

                    ++count;
                }
            }
        }
Ejemplo n.º 23
0
        private IEnumerable <IPackageInfo> GetPackagesFromRepository(string searchTerm, string repositoryUrl)
        {
            var packages = new Dictionary <string, ImmutableSortedSet <string> .Builder>(new InsensitiveStringComparer());
            var previousPackageVersions =
                ImmutableSortedSet.CreateBuilder <string>(new InsensitiveOpositeStringComparer());
            string previousPackageId = string.Empty;

            PackageSearchResource resource = BuildSearchResource(repositoryUrl);
            var searchResult = resource.SearchAsync(
                searchTerm, new SearchFilter(true, null)
            {
                OrderBy = null
            }, 0, 10,
                new Logger(texoLogger), CancellationToken.None).Result;


            foreach (IPackageSearchMetadata metadata in searchResult)
            {
                if (!string.Equals(previousPackageId, metadata.Identity.Id, StringComparison.OrdinalIgnoreCase))
                {
                    previousPackageId = metadata.Identity.Id;

                    if (!packages.TryGetValue(previousPackageId, out previousPackageVersions))
                    {
                        previousPackageVersions =
                            ImmutableSortedSet.CreateBuilder <string>(new InsensitiveOpositeStringComparer());
                        packages[previousPackageId] = previousPackageVersions;
                    }
                }

                if (metadata.Identity.HasVersion)
                {
                    previousPackageVersions.Add(metadata.Identity.Version.ToNormalizedString());
                }
            }

            foreach (var packagePair in packages)
            {
                yield return(new PackageInfo(packagePair.Key, packagePair.Value.ToImmutable()));
            }
        }
Ejemplo n.º 24
0
 protected override void OnReceive(object message)
 {
     if (message is ClusterEvent.CurrentClusterState)
     {
         var state = message as ClusterEvent.CurrentClusterState;
         Nodes = ImmutableSortedSet.Create(Member.AddressOrdering,
                                           state.Members.Where(IsAvailable).Select(x => x.Address).ToArray());
         AddRoutees();
     }
     else if (message is ClusterEvent.IMemberEvent)
     {
         var @event = message as ClusterEvent.IMemberEvent;
         if (IsAvailable(@event.Member))
         {
             AddMember(@event.Member);
         }
         else
         {
             // other events means that it is no onger interesting, such as
             // MemberExited, MemberRemoved
             RemoveMember(@event.Member);
         }
     }
     else if (message is ClusterEvent.UnreachableMember)
     {
         var member = message as ClusterEvent.UnreachableMember;
         RemoveMember(member.Member);
     }
     else if (message is ClusterEvent.ReachableMember)
     {
         var member = message as ClusterEvent.ReachableMember;
         if (IsAvailable(member.Member))
         {
             AddMember(member.Member);
         }
     }
     else
     {
         base.OnReceive(message);
     }
 }
        public void ShouldGenerateModelFromScripts8()
        {
            var testProjectDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "../../../");
            var scriptsPath          = Path.Combine(testProjectDirectory, "Scripts8");

            var dbSchemaReader = new DbSchemaReader();

            var actual = dbSchemaReader.Read(scriptsPath, new TaskLoggingHelper(GetTask(), "build"));

            var contract = new Table("contract", ImmutableList.Create(
                                         new Column("id", "int", false, false, true),
                                         new Column("code", "string", false, false, false),
                                         new Column("created_by", "string", false, false, false),
                                         new Column("creation_date", "DateTime", false, false, false),
                                         new Column("last_modified_by", "string", true, false, false),
                                         new Column("last_modification_date", "DateTime", true, false, false),
                                         new Column("pyjame", "int", true, false, false)
                                         ), ImmutableSortedSet.Create("id"));

            actual.Tables.ShouldDeepEqual(ImmutableList.Create(contract));
        }
        public void ShouldGenerateModelFromScripts6()
        {
            var testProjectDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "../../../");
            var scriptsPath          = Path.Combine(testProjectDirectory, "Scripts6");

            var dbSchemaReader = new DbSchemaReader();

            var actual = dbSchemaReader.Read(scriptsPath, new TaskLoggingHelper(GetTask(), "build"));

            var tenant = new Table("tenant", ImmutableList.Create(
                                       new Column("id", "int", false, false, true),
                                       new Column("name", "string", true, false, false),
                                       new Column("groupId", "int", false, false, false)
                                       ), ImmutableSortedSet.Create("id"));
            var userGroup = new Table("lamorosso", ImmutableList.Create(
                                          new Column("id", "int", false, true, false),
                                          new Column("name", "string", true, false, false)
                                          ), ImmutableSortedSet.Create("id"));

            actual.Tables.ShouldDeepEqual(ImmutableList.Create(userGroup, tenant));
        }
Ejemplo n.º 27
0
        private void HandleInitial(ClusterEvent.CurrentClusterState state)
        {
            // all members except Joining and WeaklyUp
            _membersByAge = state.Members
                            .Where(m => m.UpNumber != int.MaxValue && MatchingRole(m))
                            .ToImmutableSortedSet(MemberAgeOrdering.Descending);

            // If there is some removal in progress of an older node it's not safe to immediately become oldest,
            // removal of younger nodes doesn't matter. Note that it can also be started via restart after
            // ClusterSingletonManagerIsStuck.
            var selfUpNumber = state.Members
                               .Where(m => m.UniqueAddress == _cluster.SelfUniqueAddress)
                               .Select(m => (int?)m.UpNumber)
                               .FirstOrDefault() ?? int.MaxValue;

            var oldest         = _membersByAge.TakeWhile(m => m.UpNumber <= selfUpNumber).ToList();
            var safeToBeOldest = !oldest.Any(m => m.Status == MemberStatus.Down || m.Status == MemberStatus.Exiting || m.Status == MemberStatus.Leaving);
            var initial        = new InitialOldestState(oldest.Select(m => m.UniqueAddress).ToList(), safeToBeOldest);

            _changes = _changes.Enqueue(initial);
        }
        public void DomainEvents_must_be_produced_for_removed_members()
        {
            var t1 = Converge(new Gossip(ImmutableSortedSet.Create(aUp, dExiting)));
            var t2 = Converge(new Gossip(ImmutableSortedSet.Create(aUp)));

            var g1 = t1.Item1;
            var g2 = t2.Item1;
            var s2 = t2.Item2;

            ClusterEvent.DiffMemberEvents(g1, g2)
            .Should()
            .BeEquivalentTo(ImmutableList.Create <ClusterEvent.IMemberEvent>(new ClusterEvent.MemberRemoved(dRemoved, MemberStatus.Exiting)));

            ClusterEvent.DiffUnreachable(g1, g2, selfDummyAddress)
            .Should()
            .BeEquivalentTo(ImmutableList.Create <ClusterEvent.UnreachableMember>());

            ClusterEvent.DiffSeen(g1, g2, selfDummyAddress)
            .Should()
            .BeEquivalentTo(ImmutableList.Create(new ClusterEvent.SeenChanged(true, s2.Select(s => s.Address).ToImmutableHashSet())));
        }
Ejemplo n.º 29
0
        private EvaluationContext(
            ImmutableArray <MetadataBlock> metadataBlocks,
            MethodScope methodScope,
            CSharpCompilation compilation,
            MetadataDecoder metadataDecoder,
            MethodSymbol currentFrame,
            ImmutableArray <LocalSymbol> locals,
            ImmutableSortedSet <int> inScopeHoistedLocalIndices,
            MethodDebugInfo methodDebugInfo)
        {
            Debug.Assert(inScopeHoistedLocalIndices != null);

            this.MetadataBlocks         = metadataBlocks;
            this.MethodScope            = methodScope;
            this.Compilation            = compilation;
            _metadataDecoder            = metadataDecoder;
            _currentFrame               = currentFrame;
            _locals                     = locals;
            _inScopeHoistedLocalIndices = inScopeHoistedLocalIndices;
            _methodDebugInfo            = methodDebugInfo;
        }
        public void Can_serialize_GossipEnvelope()
        {
            var address        = new Address("akka.tcp", "system", "some.host.org", 4711);
            var uniqueAddress2 = new UniqueAddress(address, 18);
            var node1          = new VectorClock.Node("node1");
            var node2          = new VectorClock.Node("node2");

            var g1 = new Gossip(ImmutableSortedSet.Create(a1, b1, c1, d1)).Increment(node1)
                     .Increment(node2)
                     .Seen(a1.UniqueAddress)
                     .Seen(b1.UniqueAddress);
            var message1     = new GossipEnvelope(a1.UniqueAddress, uniqueAddress2, g1);
            var deserialized = AssertAndReturn(message1);

            message1.From.Should().Be(deserialized.From);
            message1.To.Should().Be(deserialized.To);
            message1.Gossip.Members.Should().BeEquivalentTo(deserialized.Gossip.Members);
            message1.Gossip.Overview.Seen.Should().BeEquivalentTo(deserialized.Gossip.Overview.Seen);
            message1.Gossip.Overview.Reachability.Should().Be(deserialized.Gossip.Overview.Reachability);
            message1.Gossip.Version.Versions.Should().Equal(deserialized.Gossip.Version.Versions);
        }
        public void DomainEvents_must_be_produced_for_changed_status_of_members()
        {
            var t1 = Converge(new Gossip(ImmutableSortedSet.Create(aJoining, bUp, cUp)));
            var t2 = Converge(new Gossip(ImmutableSortedSet.Create(aUp, bUp, cLeaving, eJoining)));

            var g1 = t1.Item1;
            var g2 = t2.Item1;
            var s2 = t2.Item2;

            ClusterEvent.DiffMemberEvents(g1, g2)
            .Should()
            .BeEquivalentTo(ImmutableList.Create <ClusterEvent.IMemberEvent>(new ClusterEvent.MemberUp(aUp), new ClusterEvent.MemberLeft(cLeaving), new ClusterEvent.MemberJoined(eJoining)));

            ClusterEvent.DiffUnreachable(g1, g2, selfDummyAddress)
            .Should()
            .BeEquivalentTo(ImmutableList.Create <ClusterEvent.UnreachableMember>());

            ClusterEvent.DiffSeen(g1, g2, selfDummyAddress)
            .Should()
            .BeEquivalentTo(ImmutableList.Create(new ClusterEvent.SeenChanged(true, s2.Select(s => s.Address).ToImmutableHashSet())));
        }
        /// <remarks>
        /// If the profile exists we return all the standard property names (as they are
        /// always considered defined) plus all of the defined properties supported by
        /// extenders.
        /// </remarks>
        public async Task <IEnumerable <string> > GetPropertyNamesAsync()
        {
            ILaunchSettings snapshot = await _launchSettingsProvider.WaitForFirstSnapshot();

            ILaunchProfile?profile = snapshot.Profiles.FirstOrDefault(p => StringComparers.LaunchProfileNames.Equals(p.Name, _context.ItemName));

            if (profile is null)
            {
                return(Enumerable.Empty <string>());
            }
            ImmutableDictionary <string, object> globalSettings = snapshot.GlobalSettings;

            ImmutableSortedSet <string> .Builder builder = ImmutableSortedSet.CreateBuilder <string>(StringComparers.PropertyNames);
            builder.UnionWith(s_standardPropertyNames);

            foreach ((string propertyName, LaunchProfileValueProviderAndMetadata provider) in _launchProfileValueProviders)
            {
                string propertyValue = provider.Value.OnGetPropertyValue(propertyName, profile, globalSettings, _rule);
                if (!Strings.IsNullOrEmpty(propertyValue))
                {
                    builder.Add(propertyName);
                }
            }

            foreach ((string propertyName, GlobalSettingValueProviderAndMetadata provider) in _globalSettingValueProviders)
            {
                string propertyValue = provider.Value.OnGetPropertyValue(propertyName, globalSettings, _rule);
                if (!Strings.IsNullOrEmpty(propertyValue))
                {
                    builder.Add(propertyName);
                }
            }

            foreach ((string propertyName, _) in profile.EnumerateOtherSettings())
            {
                builder.Add(propertyName);
            }

            return(builder.ToImmutable());
        }
Ejemplo n.º 33
0
        /// <summary>
        /// ParkedVehicle
        /// </summary>
        /// <param name="vehicle">Vehicle</param>
        /// <returns></returns>
        public bool UnParkedVehicle(Vehicle vehicle)
        {
            ParkedVehicles.TryRemove(vehicle.RegistrationNumber, out ParkingSpot currentSpot);

            if (currentSpot == null)
            {
                throw new ArgumentException($"Vehicle {vehicle.RegistrationNumber} is NOT parked.");
            }

            var leftSpot = FreeParkingSpots.FirstOrDefault(spot => spot.Floor == currentSpot.Floor && spot.Row == currentSpot.Row &&
                                                           spot.ParkingSpotTypes == currentSpot.ParkingSpotTypes && spot.StartPosition + spot.SpotCount == currentSpot.StartPosition);

            ParkingSpot newSpotToUpdate = new ParkingSpot()
            {
                Floor            = currentSpot.Floor,
                ParkingSpotTypes = currentSpot.ParkingSpotTypes,
                Row           = currentSpot.Row,
                StartPosition = currentSpot.StartPosition,
                SpotCount     = currentSpot.SpotCount
            };

            if (leftSpot != null)
            {
                newSpotToUpdate.StartPosition = leftSpot.StartPosition;
                newSpotToUpdate.SpotCount     = currentSpot.SpotCount + leftSpot.SpotCount;
                FreeParkingSpots = FreeParkingSpots.Remove(leftSpot);
            }

            var rightSpot = FreeParkingSpots.FirstOrDefault(spot => spot.Floor == currentSpot.Floor && spot.Row == currentSpot.Row &&
                                                            spot.ParkingSpotTypes == currentSpot.ParkingSpotTypes && spot.StartPosition == currentSpot.StartPosition + currentSpot.SpotCount);

            if (rightSpot != null)
            {
                newSpotToUpdate.SpotCount = newSpotToUpdate.SpotCount + rightSpot.SpotCount;
                FreeParkingSpots          = FreeParkingSpots.Remove(rightSpot);
            }

            FreeParkingSpots = FreeParkingSpots.Add(newSpotToUpdate);
            return(true);
        }
        public void DomainEvents_must_be_produced_for_leader_changes()
        {
            var t1 = Converge(new Gossip(ImmutableSortedSet.Create(aUp, bUp, eJoining)));
            var t2 = Converge(new Gossip(ImmutableSortedSet.Create(bUp, eJoining)));

            var g1 = t1.Item1;
            var g2 = t2.Item1;
            var s2 = t2.Item2;

            ClusterEvent.DiffMemberEvents(g1, g2)
            .Should()
            .BeEquivalentTo(ImmutableList.Create(new ClusterEvent.MemberRemoved(aRemoved, MemberStatus.Up)));
            ClusterEvent.DiffUnreachable(g1, g2, selfDummyAddress)
            .Should()
            .BeEquivalentTo(ImmutableList.Create <ClusterEvent.UnreachableMember>());
            ClusterEvent.DiffSeen(g1, g2, selfDummyAddress)
            .Should()
            .BeEquivalentTo(ImmutableList.Create(new ClusterEvent.SeenChanged(true, s2.Select(a => a.Address).ToImmutableHashSet())));
            ClusterEvent.DiffLeader(g1, g2, selfDummyAddress)
            .Should()
            .BeEquivalentTo(ImmutableList.Create(new ClusterEvent.LeaderChanged(bUp.Address)));
        }
Ejemplo n.º 35
0
        public virtual EntityType RemoveEntityType([NotNull] EntityType entityType)
        {
            Check.NotNull(entityType, "entityType");

            if (GetReferencingForeignKeys(entityType).Any())
            {
                throw new InvalidOperationException(Strings.EntityTypeInUse(entityType.Name));
            }

            var previousEntities = _entities;

            _entities = _entities.Remove(entityType);

            EntityType removedEntityType = null;

            if (previousEntities.Count != _entities.Count)
            {
                previousEntities.TryGetValue(entityType, out removedEntityType);
            }

            return(removedEntityType);
        }
Ejemplo n.º 36
0
        private EvaluationContext(
            ImmutableArray<MetadataBlock> metadataBlocks,
            MethodScope methodScope,
            CSharpCompilation compilation,
            MetadataDecoder metadataDecoder,
            MethodSymbol currentFrame,
            ImmutableArray<LocalSymbol> locals,
            ImmutableSortedSet<int> inScopeHoistedLocalIndices,
            ImmutableArray<ImmutableArray<string>> importStringGroups,
            ImmutableArray<string> externAliasStrings)
        {
            Debug.Assert(inScopeHoistedLocalIndices != null);
            Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault);

            this.MetadataBlocks = metadataBlocks;
            this.MethodScope = methodScope;
            this.Compilation = compilation;
            _metadataDecoder = metadataDecoder;
            _currentFrame = currentFrame;
            _locals = locals;
            _inScopeHoistedLocalIndices = inScopeHoistedLocalIndices;
            _importStringGroups = importStringGroups;
            _externAliasStrings = externAliasStrings;
        }
Ejemplo n.º 37
0
 public ImmutableSortedSet<Cell>[] DeleteFullLines(ImmutableSortedSet<Cell>[] mutableGameField, List<int> fullLines)
 {
     for (int i = 0; i < fullLines.Count; i++)
     {
         int lineToStart = fullLines[fullLines.Count - 1 - i];
         int lineToStop = i == fullLines.Count - 1 ? 0 : fullLines[fullLines.Count - 2 - i];
         for (int j = lineToStart; j > lineToStop; j--)
         {
             mutableGameField[j + i] = mutableGameField[j - 1];//ne fact
             //mutableLinesLength[j + i] = mutableLinesLength[j - 1];
         }
     }
     for (int i = 0; i < fullLines.Count; i++)
     {
         mutableGameField[i] = ImmutableSortedSet<Cell>.Empty;// mutableGameField[i].Clear();//null;//new Cell[mutableGameField[i].Length];
         //mutableLinesLength[i] = 0;
     }
     return mutableGameField;
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Creates a deep copy of the <see cref="CurrentClusterState"/> and optionally allows you
 /// to specify different values for the outgoing objects
 /// </summary>
 public CurrentClusterState Copy(ImmutableSortedSet<Member> members = null,
     ImmutableHashSet<Member> unreachable = null,
     ImmutableHashSet<Address> seenBy = null,
     Address leader = null,
     ImmutableDictionary<string, Address> roleLeaderMap = null)
 {
     return new CurrentClusterState(members ?? _members,
         unreachable ?? _unreachable,
         seenBy ?? _seenBy,
         leader ?? (_leader != null ? (Address)_leader.Clone() : null),
         roleLeaderMap ?? _roleLeaderMap);
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Return a mapping of captured variables (parameters, locals, and
        /// "this") to locals. The mapping is needed to expose the original
        /// local identifiers (those from source) in the binder.
        /// </summary>
        private static void GetDisplayClassVariables(
            MethodSymbol method,
            ImmutableArray<LocalSymbol> locals,
            ImmutableSortedSet<int> inScopeHoistedLocalIndices,
            out ImmutableArray<string> displayClassVariableNamesInOrder,
            out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables,
            out ImmutableHashSet<string> hoistedParameterNames)
        {
            // Calculated the shortest paths from locals to instances of display
            // classes. There should not be two instances of the same display
            // class immediately within any particular method.
            var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance();
            var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();

            // Add any display class instances from locals (these will contain any hoisted locals).
            foreach (var local in locals)
            {
                var name = local.Name;
                if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField))
                {
                    var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local);
                    displayClassTypes.Add(instance.Type);
                    displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
                }
            }

            var containingType = method.ContainingType;
            bool isIteratorOrAsyncMethod = false;
            if (IsDisplayClassType(containingType))
            {
                if (!method.IsStatic)
                {
                    // Add "this" display class instance.
                    var instance = new DisplayClassInstanceFromThis(method.ThisParameter);
                    displayClassTypes.Add(instance.Type);
                    displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
                }

                isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType;
            }

            if (displayClassInstances.Any())
            {
                // Find any additional display class instances breadth first.
                for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++)
                {
                }

                // The locals are the set of all fields from the display classes.
                var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance();
                var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance();

                var parameterNames = PooledHashSet<string>.GetInstance();
                if (isIteratorOrAsyncMethod)
                {
                    Debug.Assert(IsDisplayClassType(containingType));

                    foreach (var field in containingType.GetMembers().OfType<FieldSymbol>())
                    {
                        // All iterator and async state machine fields (including hoisted locals) have mangled names, except
                        // for hoisted parameters (whose field names are always the same as the original source parameters).
                        var fieldName = field.Name;
                        if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None)
                        {
                            parameterNames.Add(fieldName);
                        }
                    }
                }
                else
                {
                    foreach (var p in method.Parameters)
                    {
                        parameterNames.Add(p.Name);
                    }
                }

                var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance();
                foreach (var instance in displayClassInstances)
                {
                    GetDisplayClassVariables(
                        displayClassVariableNamesInOrderBuilder,
                        displayClassVariablesBuilder,
                        parameterNames,
                        inScopeHoistedLocalIndices,
                        instance,
                        pooledHoistedParameterNames);
                }

                hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>();
                pooledHoistedParameterNames.Free();
                parameterNames.Free();

                displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree();
                displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary();
                displayClassVariablesBuilder.Free();
            }
            else
            {
                hoistedParameterNames = ImmutableHashSet<string>.Empty;
                displayClassVariableNamesInOrder = ImmutableArray<string>.Empty;
                displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
            }

            displayClassTypes.Free();
            displayClassInstances.Free();
        }
Ejemplo n.º 40
0
        private static void GetDisplayClassVariables(
            ArrayBuilder<string> displayClassVariableNamesInOrderBuilder,
            Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder,
            HashSet<string> parameterNames,
            ImmutableSortedSet<int> inScopeHoistedLocalIndices,
            DisplayClassInstanceAndFields instance,
            HashSet<string> hoistedParameterNames)
        {
            // Display class instance. The display class fields are variables.
            foreach (var member in instance.Type.GetMembers())
            {
                if (member.Kind != SymbolKind.Field)
                {
                    continue;
                }

                var field = (FieldSymbol)member;
                var fieldName = field.Name;

                DisplayClassVariableKind variableKind;
                string variableName;
                GeneratedNameKind fieldKind;
                int openBracketOffset;
                int closeBracketOffset;
                GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset);

                switch (fieldKind)
                {
                    case GeneratedNameKind.DisplayClassLocalOrField:
                        // A local that is itself a display class instance.
                        Debug.Assert(!field.IsStatic);
                        continue;
                    case GeneratedNameKind.HoistedLocalField:
                        // Filter out hoisted locals that are known to be out-of-scope at the current IL offset.
                        // Hoisted locals with invalid indices will be included since more information is better
                        // than less in error scenarios.
                        int slotIndex;
                        if (GeneratedNames.TryParseSlotIndex(fieldName, out slotIndex) && !inScopeHoistedLocalIndices.Contains(slotIndex))
                        {
                            continue;
                        }

                        variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
                        variableKind = DisplayClassVariableKind.Local;
                        Debug.Assert(!field.IsStatic);
                        break;
                    case GeneratedNameKind.ThisProxyField:
                        // A reference to "this".
                        variableName = fieldName;
                        variableKind = DisplayClassVariableKind.This;
                        Debug.Assert(!field.IsStatic);
                        break;
                    case GeneratedNameKind.None:
                        // A reference to a parameter or local.
                        variableName = fieldName;
                        if (parameterNames.Contains(variableName))
                        {
                            variableKind = DisplayClassVariableKind.Parameter;
                            hoistedParameterNames.Add(variableName);
                        }
                        else
                        {
                            variableKind = DisplayClassVariableKind.Local;
                        }
                        Debug.Assert(!field.IsStatic);
                        break;
                    default:
                        continue;
                }

                if (displayClassVariablesBuilder.ContainsKey(variableName))
                {
                    // Only expecting duplicates for async state machine
                    // fields (that should be at the top-level).
                    Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1);
                    Debug.Assert(instance.Fields.Count() >= 1); // greater depth
                    Debug.Assert(variableKind == DisplayClassVariableKind.Parameter);
                }
                else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass)
                {
                    // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one.
                    // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one).
                    displayClassVariableNamesInOrderBuilder.Add(variableName);
                    displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field));
                }
            }
        }
Ejemplo n.º 41
0
 public Gossip(ImmutableSortedSet<Member> members) : this(members, new GossipOverview(), VectorClock.Create() ) {}
Ejemplo n.º 42
0
        /// <summary>
        /// Create a context to compile expressions within a method scope.
        /// Include imports if <paramref name="importStringGroups"/> is set.
        /// </summary>
        internal CompilationContext(
            CSharpCompilation compilation,
            MetadataDecoder metadataDecoder,
            MethodSymbol currentFrame,
            ImmutableArray<LocalSymbol> locals,
            ImmutableSortedSet<int> inScopeHoistedLocalIndices,
            ImmutableArray<ImmutableArray<string>> importStringGroups,
            ImmutableArray<string> externAliasStrings,
            CSharpSyntaxNode syntax)
        {
            Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax));
            Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault);

            // TODO: syntax.SyntaxTree should probably be added to the compilation,
            // but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet).
            _currentFrame = currentFrame;
            _syntax = syntax;
            _methodNotType = !locals.IsDefault;

            // NOTE: Since this is done within CompilationContext, it will not be cached.
            // CONSIDER: The values should be the same everywhere in the module, so they
            // could be cached.  
            // (Catch: what happens in a type context without a method def?)
            this.Compilation = GetCompilationWithExternAliases(compilation, externAliasStrings);
            _metadataDecoder = metadataDecoder;

            // Each expression compile should use a unique compilation
            // to ensure expression-specific synthesized members can be
            // added (anonymous types, for instance).
            Debug.Assert(this.Compilation != compilation);

            this.NamespaceBinder = CreateBinderChain(
                this.Compilation,
                currentFrame.ContainingNamespace,
                importStringGroups,
                _metadataDecoder);

            if (_methodNotType)
            {
                _locals = locals;
                ImmutableArray<string> displayClassVariableNamesInOrder;
                GetDisplayClassVariables(
                    currentFrame,
                    _locals,
                    inScopeHoistedLocalIndices,
                    out displayClassVariableNamesInOrder,
                    out _displayClassVariables,
                    out _hoistedParameterNames);
                Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
                _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
            }
            else
            {
                _locals = ImmutableArray<LocalSymbol>.Empty;
                _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
                _localsForBinding = ImmutableArray<LocalSymbol>.Empty;
            }

            // Assert that the cheap check for "this" is equivalent to the expensive check for "this".
            Debug.Assert(
                _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) ==
                _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
        }
 private void HandleInitial(ClusterEvent.CurrentClusterState state)
 {
     TrackChanges(() => _membersByAge = state.Members.Where(m => m.Status == MemberStatus.Up && MatchingRole(m)).ToImmutableSortedSet(MemberAgeOrdering.Descending));
 }
Ejemplo n.º 44
0
 public Gossip(ImmutableSortedSet<Member> members, GossipOverview overview) : this(members, overview, VectorClock.Create()) { }
Ejemplo n.º 45
0
 //Piece movedPiece
 private ImmutableSortedSet<Cell>[] GameFieldMutablePart(int minY,int maxY)
 {
     int changedArraysAmount = maxY - minY + 1;
     ImmutableSortedSet<Cell>[] changedArrays = new ImmutableSortedSet<Cell>[changedArraysAmount];
     for (int i = 0; i < changedArrays.Length; i++)
     {
         changedArrays[i] = gameField[minY + i];
         /*if (gameField[minY + i].Length == 0)
         {
             changedArrays[i] = null;
             continue;
         }
         changedArrays[i] = new Cell[gameField[minY + i].Length];
         for (int j = 0; j < changedArrays[i].Length; j++)
         {
             changedArrays[i][j] = gameField[minY + i][j];
         }*/
     }
     return changedArrays;
 }
Ejemplo n.º 46
0
 public Gossip Copy(ImmutableSortedSet<Member> members = null, GossipOverview overview = null,
     VectorClock version = null)
 {
     return new Gossip(members ?? _members, overview ?? _overview, version ?? _version);
 }
Ejemplo n.º 47
0
        public virtual EntityType RemoveEntityType([NotNull] EntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            if (FindReferencingForeignKeys(entityType).Any())
            {
                throw new InvalidOperationException(CoreStrings.EntityTypeInUse(entityType.Name));
            }

            var previousEntities = _entities;
            _entities = _entities.Remove(entityType);

            EntityType removedEntityType = null;
            if (previousEntities.Count != _entities.Count)
            {
                previousEntities.TryGetValue(entityType, out removedEntityType);
            }

            return removedEntityType;
        }
Ejemplo n.º 48
0
 public CSharpInScopeHoistedLocals(ImmutableSortedSet<int> indices)
 {
     _indices = indices;
 }
Ejemplo n.º 49
0
 private ImmutableArray<ImmutableSortedSet<Cell>> CreateGameField(int height, Piece movingPiece = null)
 {
     if (movingPiece == null)
         movingPiece = this.movingPiece != null ? this.movingPiece : pieces.GetCurrentPiece();
     ImmutableSortedSet<Cell>[] mutableGameField = new ImmutableSortedSet<Cell>[height];
     for (int i = 0; i < mutableGameField.Length;i++)
         mutableGameField[i] = ImmutableSortedSet<Cell>.Empty;
     foreach (var point in movingPiece.Cells)
     {
         mutableGameField[point.Y] = mutableGameField[point.Y].Add(point);
     }
     return ImmutableArray.Create(mutableGameField);
 }
Ejemplo n.º 50
0
 private void Add(Member member)
 {
     if (MatchingRole(member))
         TrackChanges(() => _membersByAge = _membersByAge.Add(member));
 }
Ejemplo n.º 51
0
 public HeartbeatNodeRing(UniqueAddress selfAddress, ImmutableSortedSet<UniqueAddress> nodes, int monitoredByNumberOfNodes)
 {
     MonitoredByNumberOfNodes = monitoredByNumberOfNodes;
     NodeRing = nodes;
     SelfAddress = selfAddress;
     _useAllAsReceivers = MonitoredByNumberOfNodes >= (NodeRing.Count - 1);
     MyReceivers = new Lazy<ImmutableHashSet<UniqueAddress>>(() => Receivers(SelfAddress));
 }
Ejemplo n.º 52
0
 private void Remove(Member member)
 {
     if (MatchingRole(member))
         TrackChanges(() => _membersByAge = _membersByAge.Remove(member));
 }
Ejemplo n.º 53
0
 public ImmutableArray<ImmutableSortedSet<Cell>> ReworkedGameField(ImmutableSortedSet<Cell>[] changedArrays, int minY, int maxY)
 {
     ImmutableSortedSet<Cell>[] mutableGameField = new ImmutableSortedSet<Cell>[gameField.Length];
     for (int i = 0; i < minY; i++)
     {
         mutableGameField[i] = gameField[i];
     }
     for (int i = minY; i < maxY + 1; i++)
     {
         mutableGameField[i] = changedArrays[i - minY];
     }
     for (int i = maxY + 1; i < gameField.Length; i++)
     {
         mutableGameField[i] = gameField[i];
     }
     return ImmutableArray.Create(mutableGameField);
 }
Ejemplo n.º 54
0
        private void HandleInitial(ClusterEvent.CurrentClusterState state)
        {
            _membersByAge = state.Members
                .Where(m => (m.Status == MemberStatus.Up || m.Status == MemberStatus.Leaving) && MatchingRole(m))
                .ToImmutableSortedSet(MemberAgeOrdering.Descending);

            var safeToBeOldest = !state.Members.Any(m => m.Status == MemberStatus.Down || m.Status == MemberStatus.Exiting);
            var initial = new InitialOldestState(MemberAddressOrDefault(_membersByAge.FirstOrDefault()), safeToBeOldest);
            _changes = _changes.Enqueue(initial);
        }
Ejemplo n.º 55
0
 public static Gossip Create(ImmutableSortedSet<Member> members)
 {
     if (members.IsEmpty) return Empty;
     return Empty.Copy(members: members);
 }
Ejemplo n.º 56
0
        private UniqueAddress LeaderOf(ImmutableSortedSet<Member> mbrs, UniqueAddress selfUniqueAddress)
        {
            var reachableMembers = _overview.Reachability.IsAllReachable
                ? mbrs
                : mbrs
                    .Where(m => _overview.Reachability.IsReachable(m.UniqueAddress) || m.UniqueAddress == selfUniqueAddress)
                    .ToImmutableSortedSet();

            if (!reachableMembers.Any()) return null;

            var member = reachableMembers.FirstOrDefault(m => LeaderMemberStatus.Contains(m.Status)) ??
                         reachableMembers.Min(Member.LeaderStatusOrdering);

            return member.UniqueAddress;
        }