Пример #1
0
 public ProductionItem(
     MarkedProduction markedProduction,
     IReadOnlySet <Terminal <TTokenKind> > lookaheads)
 {
     MarkedProduction = markedProduction;
     Lookaheads       = lookaheads ?? Set <Terminal <TTokenKind> > .Empty;
 }
        internal AsyncMethodToStateMachineRewriter(
            MethodSymbol method,
            int methodOrdinal,
            AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
            SyntheticBoundNodeFactory F,
            FieldSymbol state,
            FieldSymbol builder,
            IReadOnlySet <Symbol> hoistedVariables,
            IReadOnlyDictionary <Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
            DiagnosticBag diagnostics)
            : base(F, method, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics, useFinalizerBookkeeping: false)
        {
            _method = method;
            _asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection;
            _asyncMethodBuilderField            = builder;
            _exprReturnLabel = F.GenerateLabel("exprReturn");
            _exitLabel       = F.GenerateLabel("exitLabel");

            _exprRetValue = method.IsGenericTaskReturningAsync(F.Compilation)
                ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, syntax: F.Syntax, kind: SynthesizedLocalKind.AsyncMethodReturnValue)
                : null;

            _dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal);
            _awaiterFields  = new Dictionary <TypeSymbol, FieldSymbol>(TypeSymbol.EqualsIgnoringDynamicAndTupleNamesComparer);
            _nextAwaiterId  = slotAllocatorOpt?.PreviousAwaiterSlotCount ?? 0;
        }
Пример #3
0
        public BoolResult UpdateAll(IReadOnlyList <MachineId> activeMachines, IReadOnlySet <MachineId> inactiveMachines)
        {
            try
            {
                lock (_lockObject)
                {
                    // Remove active machines that became inactive or disappeared.
                    var machinesToRemove = _machinesToBinsMap.Keys.Except(activeMachines).ToList();

                    foreach (var machine in activeMachines)
                    {
                        AddLocation(machine);
                    }

                    foreach (var machine in inactiveMachines.Concat(machinesToRemove))
                    {
                        RemoveLocation(machine);
                    }
                }

                return(BoolResult.Success);
            }
            catch (Exception e)
            {
                return(new BoolResult(e, $"{nameof(BinManager)}.{nameof(UpdateAll)} failed."));
            }
        }
        internal AsyncMethodToStateMachineRewriter(
            MethodSymbol method,
            int methodOrdinal,
            AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
            SyntheticBoundNodeFactory F,
            FieldSymbol state,
            FieldSymbol builder,
            IReadOnlySet<Symbol> hoistedVariables,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
            DiagnosticBag diagnostics)
            : base(F, method, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics, useFinalizerBookkeeping: false)
        {
            _method = method;
            _asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection;
            _asyncMethodBuilderField = builder;
            _exprReturnLabel = F.GenerateLabel("exprReturn");
            _exitLabel = F.GenerateLabel("exitLabel");

            _exprRetValue = method.IsGenericTaskReturningAsync(F.Compilation)
                ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, syntax: F.Syntax, kind: SynthesizedLocalKind.AsyncMethodReturnValue)
                : null;

            _dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal);
            _awaiterFields = new Dictionary<TypeSymbol, FieldSymbol>(TypeSymbol.EqualsIgnoringDynamicComparer);
            _nextAwaiterId = slotAllocatorOpt?.PreviousAwaiterSlotCount ?? 0;
        }
Пример #5
0
        public Rule(IEnumerable <Chain> chains, NonTerminalSymbol target)
        {
            if (chains == null)
            {
                throw new ArgumentNullException(nameof(chains));
            }

            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            Chains = chains.ToSortedSet().AsReadOnly();

            if (!Chains.Any())
            {
                throw new ArgumentException("Rule must contain at least one chain.");
            }

            if (Chains.AnyNull())
            {
                throw new ArgumentException("At least one null chain was found.");
            }

            Alphabet = Chains.SelectMany(chain => chain.Alphabet).ToSortedSet().AsReadOnly();
            Target   = target;
            ISet <NonTerminalSymbol> nonTerminals = Chains.SelectMany(chain => chain.NonTerminals).ToSortedSet();

            nonTerminals.Add(Target);
            NonTerminals = nonTerminals.AsReadOnly();
        }
Пример #6
0
        private async Task <bool> EvaluateAllFilesAsync(IReadOnlySet <AbsolutePath> evaluationGoals, QualifierId qualifierId)
        {
            // TODO: consider revisiting this and keeping track of individually evaluated projects, so partial
            // evaluation is possible
            Contract.Assert(m_rushWorkspaceResolver.ComputedProjectGraph.Succeeded);

            RushGraphResult result = m_rushWorkspaceResolver.ComputedProjectGraph.Result;

            // TODO add support for qualifiers
            IReadOnlySet <RushProject> filteredBuildFiles = result.RushGraph.Projects
                                                            .Where(project => evaluationGoals.Contains(project.ProjectPath(m_context.PathTable)))
                                                            .ToReadOnlySet();

            var pipConstructor = new RushPipConstructor(m_context,
                                                        m_host,
                                                        result.ModuleDefinition,
                                                        m_rushResolverSettings,
                                                        m_rushWorkspaceResolver.UserDefinedEnvironment,
                                                        m_rushWorkspaceResolver.UserDefinedPassthroughVariables);

            var graphConstructor = new ProjectGraphToPipGraphConstructor <RushProject>(pipConstructor, m_host.Configuration.FrontEnd.MaxFrontEndConcurrency());

            var scheduleResult = await graphConstructor.TrySchedulePipsForFilesAsync(filteredBuildFiles, qualifierId);

            return(scheduleResult.Succeeded);
        }
Пример #7
0
        protected BoundStatement Rewrite()
        {
            if (this.body.HasErrors)
            {
                return(this.body);
            }

            F.OpenNestedType(stateMachineType);

            GenerateControlFields();

            // fields for the initial values of all the parameters of the method
            if (PreserveInitialParameterValues)
            {
                initialParameters = new Dictionary <Symbol, CapturedSymbolReplacement>();
            }

            // fields for the captured variables of the method
            var variablesToHoist = IteratorAndAsyncCaptureWalker.Analyze(F.Compilation, method, body, diagnostics);

            CreateNonReusableLocalProxies(variablesToHoist, out this.nonReusableLocalProxies, out this.nextFreeHoistedLocalSlot);

            this.hoistedVariables = variablesToHoist;

            GenerateMethodImplementations();

            // Return a replacement body for the kickoff method
            return(GenerateKickoffMethodBody());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AbstractAreaOfInterest{TKey, TInterest}" /> class.
        /// </summary>
        /// <param name="map">The interest map to add and remove interests from.</param>
        /// <param name="interest">The interest to add and remove.</param>
        /// <param name="observableOrigin">The origin of the area of interest to follow.</param>
        /// <param name="keys">The keys of the cells to apply interests to.</param>
        public AbstractAreaOfInterest(
            IInterestMap <TKey, TInterest> map,
            TInterest interest,
            IObservable <TKey> observableOrigin,
            IReadOnlySet <TKey> keys)
        {
            Contracts.Requires.That(map != null);
            Contracts.Requires.That(observableOrigin != null);
            Contracts.Requires.That(keys != null);

            this.map      = map;
            this.interest = interest;
            this.keys     = keys;

            IObservable <TKey> firstKey, lastKey;
            var pairKeys = observableOrigin.TakeUntil(this.disposed).PairWithPrevious(out firstKey, out lastKey);

            this.subscriptions = new AggregateDisposable(
                pairKeys.Subscribe(
                    origin => this.map.UpdateInterests(
                        this.interest,
                        addTo: this.GetKeys(origin.Next),
                        removeFrom: this.GetKeys(origin.Previous))),
                firstKey.Subscribe(
                    origin => this.map.AddInterests(this.interest, this.GetKeys(origin))),
                lastKey.Subscribe(
                    origin => this.map.RemoveInterests(this.interest, this.GetKeys(origin)),
                    () => this.Dispose()));
        }
Пример #9
0
        internal AsyncIteratorMethodToStateMachineRewriter(MethodSymbol method,
                                                           int methodOrdinal,
                                                           AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
                                                           AsyncIteratorInfo asyncIteratorInfo,
                                                           SyntheticBoundNodeFactory F,
                                                           FieldSymbol state,
                                                           FieldSymbol builder,
                                                           IReadOnlySet <Symbol> hoistedVariables,
                                                           IReadOnlyDictionary <Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
                                                           SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
                                                           ArrayBuilder <StateMachineStateDebugInfo> stateMachineStateDebugInfoBuilder,
                                                           VariableSlotAllocator slotAllocatorOpt,
                                                           int nextFreeHoistedLocalSlot,
                                                           BindingDiagnosticBag diagnostics)
            : base(method, methodOrdinal, asyncMethodBuilderMemberCollection, F,
                   state, builder, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals,
                   stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics)
        {
            Debug.Assert(asyncIteratorInfo != null);

            _asyncIteratorInfo    = asyncIteratorInfo;
            _currentDisposalLabel = _exprReturnLabel;
            _exprReturnLabelTrue  = F.GenerateLabel("yieldReturn");

            _iteratorStateAllocator = new ResumableStateMachineStateAllocator(
                slotAllocatorOpt,
                firstState: StateMachineStates.FirstResumableAsyncIteratorState,
                increasing: false);
        }
Пример #10
0
        protected BoundStatement Rewrite()
        {
            if (this.body.HasErrors)
            {
                return(this.body);
            }

            F.OpenNestedType(stateMachineType);

            GenerateControlFields();

            // fields for the initial values of all the parameters of the method
            if (PreserveInitialParameterValues)
            {
                initialParameters = new Dictionary <Symbol, CapturedSymbolReplacement>();
            }

            // fields for the captured variables of the method
            var variablesCaptured = IteratorAndAsyncCaptureWalker.Analyze(compilationState.ModuleBuilderOpt.Compilation, method, body);

            this.nonReusableLocalProxies = CreateNonReusableLocalProxies(variablesCaptured);
            this.variablesCaptured       = variablesCaptured;

            GenerateMethodImplementations();

            // Return a replacement body for the original method
            return(ReplaceOriginalMethod());
        }
Пример #11
0
        public MetaTransition(
            IEnumerable <Label> metaCurrentRequiredStates,
            IEnumerable <Label> metaCurrentOptionalStates,
            char symbol,
            IEnumerable <Label> metaNextStates)
        {
            if (metaCurrentRequiredStates == null)
            {
                throw new ArgumentNullException(nameof(metaCurrentRequiredStates));
            }

            if (metaCurrentOptionalStates == null)
            {
                throw new ArgumentNullException(nameof(metaCurrentOptionalStates));
            }

            if (metaNextStates == null)
            {
                throw new ArgumentNullException(nameof(metaNextStates));
            }

            CurrentOptionalStates = metaCurrentOptionalStates.ToSortedSet().AsReadOnly();
            CurrentRequiredStates = metaCurrentRequiredStates.ToSortedSet().AsReadOnly();
            NextStates            = metaNextStates.ToSortedSet().AsReadOnly();
            Symbol = symbol;
        }
Пример #12
0
 public ErrorState(
     IReadOnlySet <object> previousState,
     IEnumerable <Exception> errors)
 {
     State  = previousState;
     Errors = errors;
 }
Пример #13
0
        private static IReadOnlySet <Point> FlipTiles(IReadOnlySet <Point> tiles)
        {
            var newTiles   = new HashSet <Point>();
            var neighbours = CalculateNeighbours(tiles);

            foreach (var tile in tiles)
            {
                var allNeighbours    = neighbours[tile];
                var activeNeighbours = allNeighbours.Intersect(tiles).Count();

                if (activeNeighbours != 0 && activeNeighbours <= 2)
                {
                    newTiles.Add(tile);
                }
            }

            foreach (var tile in neighbours.SelectMany(x => x.Value).Distinct().Except(tiles))
            {
                if (tiles.Count(tile.IsNeighbour) == 2)
                {
                    newTiles.Add(tile);
                }
            }

            return(newTiles);
        }
Пример #14
0
        static int CountNeighbors(IReadOnlySet <HyperCube> actives, int x, int y, int z, int w)
        {
            int count = 0;

            for (int xx = x - 1; xx <= x + 1; xx++)
            {
                for (int yy = y - 1; yy <= y + 1; yy++)
                {
                    for (int zz = z - 1; zz <= z + 1; zz++)
                    {
                        for (int ww = w - 1; ww <= w + 1; ww++)
                        {
                            if (x == xx & y == yy && z == zz && w == ww)
                            {
                                continue;
                            }

                            if (actives.Contains(new HyperCube(xx, yy, zz, ww)))
                            {
                                count++;
                            }
                        }
                    }
                }
            }

            return(count);
        }
Пример #15
0
        public MethodToStateMachineRewriter(
            SyntheticBoundNodeFactory F,
            MethodSymbol originalMethod,
            FieldSymbol state,
            IReadOnlySet <Symbol> variablesCaptured,
            IReadOnlyDictionary <Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            DiagnosticBag diagnostics,
            bool useFinalizerBookkeeping)
            : base(F.CompilationState, diagnostics)
        {
            Debug.Assert(F != null);
            Debug.Assert(originalMethod != null);
            Debug.Assert(state != null);
            Debug.Assert(nonReusableLocalProxies != null);
            Debug.Assert(diagnostics != null);
            Debug.Assert(variablesCaptured != null);

            this.F                       = F;
            this.stateField              = state;
            this.cachedState             = F.SynthesizedLocal(F.SpecialType(SpecialType.System_Int32), kind: SynthesizedLocalKind.StateMachineCachedState);
            this.useFinalizerBookkeeping = useFinalizerBookkeeping;
            this.hasFinalizerState       = useFinalizerBookkeeping;
            this.originalMethod          = originalMethod;
            this.variablesCaptured       = variablesCaptured;

            foreach (var proxy in nonReusableLocalProxies)
            {
                this.proxies.Add(proxy.Key, proxy.Value);
            }
        }
Пример #16
0
 private static void SetIfSelected(string sectionName, IReadOnlySet <string> sections, Action setDashboardAction)
 {
     if (sections.Contains(sectionName))
     {
         setDashboardAction();
     }
 }
Пример #17
0
        private Task <bool> EvaluateAllFilesAsync(IReadOnlySet <AbsolutePath> evaluationGoals, QualifierId qualifierId)
        {
            Contract.Assert(m_msBuildWorkspaceResolver.ComputedProjectGraph.Succeeded);

            ProjectGraphResult result = m_msBuildWorkspaceResolver.ComputedProjectGraph.Result;

            GlobalProperties qualifier = MsBuildResolverUtils.CreateQualifierAsGlobalProperties(qualifierId, m_context);

            IReadOnlySet <ProjectWithPredictions> filteredBuildFiles = result.ProjectGraph.ProjectNodes
                                                                       .Where(project => evaluationGoals.Contains(project.FullPath))
                                                                       .Where(project => ProjectMatchesQualifier(project, qualifier))
                                                                       .ToReadOnlySet();

            var graphConstructor = new PipGraphConstructor(
                m_context,
                m_host,
                result.ModuleDefinition,
                m_msBuildResolverSettings,
                result.MsBuildLocation,
                result.DotNetExeLocation,
                m_frontEndName,
                m_msBuildWorkspaceResolver.UserDefinedEnvironment,
                m_msBuildWorkspaceResolver.UserDefinedPassthroughVariables);

            return(graphConstructor.TrySchedulePipsForFilesAsync(filteredBuildFiles, qualifierId));
        }
Пример #18
0
        /*********
        ** Private methods
        *********/
        /// <summary>Draw borders for each unconnected edge of a tile.</summary>
        /// <param name="spriteBatch">The sprite batch being drawn.</param>
        /// <param name="group">The machine group.</param>
        /// <param name="tile">The group tile.</param>
        /// <param name="color">The border color.</param>
        private void DrawEdgeBorders(SpriteBatch spriteBatch, IMachineGroup group, Vector2 tile, Color color)
        {
            int   borderSize = 3;
            float screenX    = tile.X * Game1.tileSize - Game1.viewport.X;
            float screenY    = tile.Y * Game1.tileSize - Game1.viewport.Y;
            float tileSize   = Game1.tileSize;

            IReadOnlySet <Vector2> tiles = group.GetTiles(this.LocationKey);

            // top
            if (!tiles.Contains(new Vector2(tile.X, tile.Y - 1)))
            {
                spriteBatch.DrawLine(screenX, screenY, new Vector2(tileSize, borderSize), color); // top
            }
            // bottom
            if (!tiles.Contains(new Vector2(tile.X, tile.Y + 1)))
            {
                spriteBatch.DrawLine(screenX, screenY + tileSize, new Vector2(tileSize, borderSize), color); // bottom
            }
            // left
            if (!tiles.Contains(new Vector2(tile.X - 1, tile.Y)))
            {
                spriteBatch.DrawLine(screenX, screenY, new Vector2(borderSize, tileSize), color); // left
            }
            // right
            if (!tiles.Contains(new Vector2(tile.X + 1, tile.Y)))
            {
                spriteBatch.DrawLine(screenX + tileSize, screenY, new Vector2(borderSize, tileSize), color); // right
            }
        }
 public DependencyResolutionModel(IEnumerable <IVh <IDependencyHandler2> > handlerChainSource = default)
 {
     if (handlerChainSource is null)
     {
         _handlerChain     = new IVh <IDependencyHandler2> [0];
         _handlerUniqueSet = SetReadOnlyWrap <IDependencyHandler2> .Empty;
     }
     else
     {
         var effectiveHandlerChain = new List <IVh <IDependencyHandler2> >();
         var handlerUniqueSet      = new HashSet <IDependencyHandler2>(comparer: ReferenceEqualityComparer <IDependencyHandler2> .Instance);
         var indexCounter          = -1;
         foreach (var handlerVh in handlerChainSource)
         {
             indexCounter++;
             var handler = handlerVh.Arg($"{nameof(handlerChainSource)}[{indexCounter:d}]").EnsureSelfAndValueNotNull().Value.Value;
             if (handlerUniqueSet.Add(item: handler))
             {
                 effectiveHandlerChain.Add(handlerVh);
             }
         }
         _handlerChain     = effectiveHandlerChain.ToArray();
         _handlerUniqueSet = new SetReadOnlyWrap <IDependencyHandler2>(set: handlerUniqueSet);
     }
 }
Пример #20
0
 /// <summary>
 /// Constructs a constraint that will enforce that the given <paramref name="squares"/> are
 /// magic squares based on the rows, columns, and, optionally, the diagonals.
 /// </summary>
 /// <param name="possibleValues">
 /// The possible values that can be in the magic squares.
 /// </param>
 /// <param name="squares">
 /// The locations of the magic squares.
 /// </param>
 /// <param name="includeDiagonals">
 /// If true, values along the diagonals of the square must also sum to the magic number.
 /// </param>
 /// <exception cref="ArgumentException">
 /// If the any of the given <paramref name="squares"/>' sizes are not compatible with the
 /// length of <paramref name="possibleValues"/>.
 /// </exception>
 public MagicSquaresConstraint(ReadOnlySpan <int> possibleValues, IEnumerable <Box> squares, bool includeDiagonals = true)
 {
     _size             = possibleValues.Length;
     _magicSquares     = squares.ToArray();
     _squareSize       = Boxes.IntSquareRoot(_size);
     _includeDiagonals = includeDiagonals;
     if (_magicSquares.Any(
             b =>
             b.TopLeft.Row < 0 || b.TopLeft.Column < 0 ||
             b.TopLeft.Row + b.Size > _size || b.TopLeft.Column + b.Size > _size ||
             b.Size != _squareSize))
     {
         throw new ArgumentException(
                   $"Based on the {nameof(possibleValues)}, {nameof(squares)} must fit in a puzzle of size {_size} and have size {_squareSize}.");
     }
     _allPossibleValues = new BitVector();
     for (int i = 0; i < possibleValues.Length; ++i)
     {
         if (_allPossibleValues.IsBitSet(possibleValues[i]))
         {
             throw new ArgumentException("Values must be unique.");
         }
         _allPossibleValues.SetBit(possibleValues[i]);
     }
     _possibleSets = MagicSquares.ComputeSets(possibleValues, _squareSize, _allPossibleValues);
 }
Пример #21
0
        public SCG.IReadOnlyDictionary <Guid, bool> TestPacketIdsAreNew(IReadOnlySet <Guid> queryIds)
        {
            return(queryIds.ToDictionary(
                       q => q,
                       seenIds.TryAdd));

//         var results = new SCG.Dictionary<Guid, bool>();
//
//         HashSet<Guid> newIdCandidates = new HashSet<Guid>();
//         foreach (var queryId in queryIds) {
//            if (seenIds.Contains(queryId)) {
//               results[queryId] = false;
//            } else {
//               newIdCandidates.Add(queryId);
//            }
//         }
//
//         lock (synchronization) {
//            var nextSeenIds = new HashSet<Guid>(seenIds);
//            foreach (var queryId in newIdCandidates) {
//               results[queryId] = nextSeenIds.Add(queryId);
//            }
//            seenIds = nextSeenIds;
//         }
//
//         return results;
        }
Пример #22
0
        public Task <SCG.IReadOnlyDictionary <K, Entry <K, V> > > GetManyAsync(IReadOnlySet <K> keys)
        {
            return(ExecCommandAsync(async cmd => {
                // Retrieve all rows
                cmd.CommandText = $"SELECT * FROM {tableName} WHERE id=ANY(@ids)";
                var idParameter = cmd.CreateParameter();
                idParameter.ParameterName = "ids";
                idParameter.Value = keys.ToArray();
                cmd.Parameters.Add(idParameter);

                using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) {
                    var results = new SCG.Dictionary <K, Entry <K, V> >();
                    while (await reader.ReadAsync().ConfigureAwait(false))
                    {
                        var entry = ReadToEntry(reader);
                        results[entry.Key] = entry;
                    }
                    foreach (var key in keys)
                    {
                        if (!results.ContainsKey(key))
                        {
                            results[key] = Entry <K, V> .CreateNonexistant(key);
                        }
                    }
                    return (SCG.IReadOnlyDictionary <K, Entry <K, V> >)results;
                }
            }));
        }
 internal IteratorMethodToStateMachineRewriter(
     SyntheticBoundNodeFactory F,
     MethodSymbol originalMethod,
     FieldSymbol state,
     FieldSymbol current,
     IReadOnlySet <Symbol> hoistedVariables,
     IReadOnlyDictionary <Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
     SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
     VariableSlotAllocator slotAllocatorOpt,
     int nextFreeHoistedLocalSlot,
     BindingDiagnosticBag diagnostics
     )
     : base(
         F,
         originalMethod,
         state,
         hoistedVariables,
         nonReusableLocalProxies,
         synthesizedLocalOrdinals,
         slotAllocatorOpt,
         nextFreeHoistedLocalSlot,
         diagnostics,
         useFinalizerBookkeeping: false
         )
 {
     _current = current;
 }
        public MethodToStateMachineRewriter(
            SyntheticBoundNodeFactory F,
            MethodSymbol originalMethod,
            FieldSymbol state,
            IReadOnlySet<Symbol> variablesCaptured,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            DiagnosticBag diagnostics,
            bool useFinalizerBookkeeping)
            : base(F.CompilationState, diagnostics)
        {
            Debug.Assert(F != null);
            Debug.Assert(originalMethod != null);
            Debug.Assert(state != null);
            Debug.Assert(nonReusableLocalProxies != null);
            Debug.Assert(diagnostics != null);
            Debug.Assert(variablesCaptured != null);

            this.F = F;
            this.stateField = state;
            this.cachedState = F.SynthesizedLocal(F.SpecialType(SpecialType.System_Int32), kind: SynthesizedLocalKind.StateMachineCachedState);
            this.useFinalizerBookkeeping = useFinalizerBookkeeping;
            this.hasFinalizerState = useFinalizerBookkeeping;
            this.originalMethod = originalMethod;
            this.variablesCaptured = variablesCaptured;

            foreach (var proxy in nonReusableLocalProxies)
            {
                this.proxies.Add(proxy.Key, proxy.Value);
            }
        }
        internal AsyncMethodToStateMachineRewriter(
            MethodSymbol method,
            int methodOrdinal,
            AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
            SyntheticBoundNodeFactory F,
            FieldSymbol state,
            FieldSymbol builder,
            IReadOnlySet <Symbol> hoistedVariables,
            IReadOnlyDictionary <Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            ArrayBuilder <StateMachineStateDebugInfo> stateMachineStateDebugInfoBuilder,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
            BindingDiagnosticBag diagnostics)
            : base(F, method, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics)
        {
            _method = method;
            _asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection;
            _asyncMethodBuilderField            = builder;
            _exprReturnLabel = F.GenerateLabel("exprReturn");
            _exitLabel       = F.GenerateLabel("exitLabel");

            _exprRetValue = method.IsAsyncEffectivelyReturningGenericTask(F.Compilation)
                ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, syntax: F.Syntax, kind: SynthesizedLocalKind.AsyncMethodReturnValue)
                : null;

            _dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal);
            _awaiterFields  = new Dictionary <TypeSymbol, FieldSymbol>(Symbols.SymbolEqualityComparer.IgnoringDynamicTupleNamesAndNullability);
            _nextAwaiterId  = slotAllocatorOpt?.PreviousAwaiterSlotCount ?? 0;

            _placeholderMap = new Dictionary <BoundValuePlaceholderBase, BoundExpression>();
        }
Пример #26
0
        private async Task <EvaluationResult> CollectProjectOutputsAsync(IReadOnlySet <AbsolutePath> evaluationGoals, QualifierId qualifierId, ResolvedJavaScriptExport export, IEvaluationScheduler scheduler)
        {
            // Make sure all project files are evaluated before collecting their outputs
            if (!await EvaluateAllFilesOnceAsync(evaluationGoals, qualifierId, scheduler))
            {
                return(EvaluationResult.Error);
            }

            var processOutputs = export.ExportedProjects.SelectMany(project => {
                if (!m_scheduledProcessOutputs.TryGetValue(project, out var projectOutputs))
                {
                    // The requested project was not scheduled. This can happen when a filter gets applied, so even
                    // though the export points to a valid project (which is already validated), the project is not part
                    // of the graph. In this case just log an informational message.
                    Tracing.Logger.Log.RequestedExportIsNotPresent(
                        Context.LoggingContext,
                        m_resolverSettings.Location(Context.PathTable),
                        export.FullSymbol.ToString(Context.SymbolTable),
                        project.Name,
                        project.ScriptCommandName);
                }

                return(projectOutputs);
            });

            // Let's put together all output directories for all pips under this project
            var sealedDirectories = processOutputs.SelectMany(process => process.GetOutputDirectories().Select(staticDirectory => new EvaluationResult(staticDirectory))).ToArray();

            return(new EvaluationResult(new EvaluatedArrayLiteral(sealedDirectories, default, m_javaScriptWorkspaceResolver.ExportsFile)));
Пример #27
0
 internal Pseudograph(
     IReadOnlySet <T> vertices,
     IReadOnlyCollection <E> edges)
 {
     this.Vertices = vertices;
     this.Edges    = edges;
 }
Пример #28
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CharacterClass"/> class.
		/// </summary>
		/// <param name="characters">The characters in the character set.</param>
		public CharacterClass(IReadOnlySet<Character> characters)
		{
			#region Contract
			Contract.Requires<ArgumentNullException>(characters != null);
			#endregion
			this.Characters = characters;
		}
Пример #29
0
        public void ThrowIfIllegal(IReadOnlySet <Argument> arguments)
        {
            HashSet <char> characters = new HashSet <char>();

            foreach (Argument argument in arguments)
            {
                if (argument.ShortNames.Count < 1)
                {
                    throw new ArgumentException(
                              "POSIX-style parsing requires that arguments have at least one short name.");
                }

                foreach (string shortName in argument.ShortNames)
                {
                    if (shortName.Length > 1)
                    {
                        throw new ArgumentException(
                                  "POSIX-style parsing requires that short names be only one character long.");
                    }

                    char character = shortName[0];
                    if (character == '-')
                    {
                        throw new ArgumentException(
                                  "POSIX-style parsing requires short names not start with '-'.");
                    }

                    if (!characters.Add(character))
                    {
                        throw new ArgumentException(
                                  "POSIX-style parsing requires that short names have a unique first character.");
                    }
                }
            }
        }
Пример #30
0
        public void CalculationTest(IReadOnlySet <object> result, string expression, Parser parser)
        {
            var tokens = expression.Split().Append(string.Empty);
            var set    = new StateMachine(parser).Calculate(tokens);

            Assert.True(result.SetEquals(set));
        }
Пример #31
0
 public ParseResult Parse(
     IReadOnlySet <Argument> arguments,
     IReadOnlyList <string> values) => MsBuildParser
 .StateMachine
 .Run(() => new SharedState(arguments, values))
 .Results
 .ToParseResult();
Пример #32
0
        public async Task <bool> GrantRolesAsync(ulong userId, IReadOnlySet <DiscordRole> discordRoles)
        {
            DiscordGuild guild = await _guildProvider.GetCurrentGuildAsync();

            List <DRole> roles = new();

            foreach (DiscordRole discordRole in discordRoles)
            {
                DRole?role = guild.GetRole(discordRole.RoleId);
                if (role == null)
                {
                    _logger.LogWarning("Couldn't map all roles. Please verify your config file");
                    return(false);
                }

                roles.Add(role);
            }

            // TODO: job queue
            Task _ = Task.Run(async() =>
            {
                DiscordMember member = await guild.GetMemberAsync(userId);
                foreach (DRole role in roles)
                {
                    await member.GrantRoleAsync(role, "Auth");
                }
            });

            return(true);
        }
        /// <nodoc />
        public SandboxedProcessPipExecutionResult(
            SandboxedProcessPipExecutionStatus status,
            SortedReadOnlyArray <ObservedFileAccess, ObservedFileAccessExpandedPathComparer> observedFileAccesses,
            IReadOnlyDictionary <AbsolutePath, IReadOnlyCollection <FileArtifactWithAttributes> > sharedDynamicDirectoryWriteAccesses,
            Tuple <AbsolutePath, Encoding> encodedStandardOutput,
            Tuple <AbsolutePath, Encoding> encodedStandardError,
            int numberOfWarnings,
            FileAccessReportingContext unexpectedFileAccesses,
            ProcessTimes primaryProcessTimes,
            JobObject.AccountingInformation?jobAccountingInformation,
            int exitCode,
            long sandboxPrepMs,
            long processSandboxedProcessResultMs,
            long processStartTime,
            IReadOnlyList <ReportedFileAccess> allReportedFileAccesses,
            IReadOnlyList <ProcessDetouringStatusData> detouringStatuses,
            long maxDetoursHeapSize,
            ContainerConfiguration containerConfiguration,
            Dictionary <string, int> pipProperties,
            bool timedOut,
            IReadOnlySet <AbsolutePath> createdDirectories,
            RetryInfo retryInfo = null)
        {
            Contract.Requires(!ProcessCompletedExecution(status) || observedFileAccesses.IsValid);
            Contract.Requires(!ProcessCompletedExecution(status) || unexpectedFileAccesses != null);
            Contract.Requires(!ProcessCompletedExecution(status) || primaryProcessTimes != null);
            Contract.Requires(encodedStandardOutput == null || (encodedStandardOutput.Item1.IsValid && encodedStandardOutput.Item2 != null));
            Contract.Requires(encodedStandardError == null || (encodedStandardError.Item1.IsValid && encodedStandardError.Item2 != null));
            Contract.Requires(numberOfWarnings >= 0);
            Contract.Requires(containerConfiguration != null);
            Contract.Requires(retryInfo == null || status != SandboxedProcessPipExecutionStatus.Succeeded);

            // Protect against invalid combinations of RetryLocation and RetryReason
            Contract.Requires(!retryInfo.CanBeRetriedInlineOrFalseIfNull() || retryInfo.RetryReason != RetryReason.ResourceExhaustion);
            Contract.Requires(!retryInfo.CanBeRetriedInlineOrFalseIfNull() || retryInfo.RetryReason != RetryReason.ProcessStartFailure);
            Contract.Requires(!retryInfo.CanBeRetriedInlineOrFalseIfNull() || retryInfo.RetryReason != RetryReason.TempDirectoryCleanupFailure);
            Contract.Requires(!retryInfo.CanBeRetriedInlineOrFalseIfNull() || retryInfo.RetryReason != RetryReason.StoppedWorker);

            Status = status;
            ObservedFileAccesses     = observedFileAccesses;
            UnexpectedFileAccesses   = unexpectedFileAccesses;
            EncodedStandardOutput    = encodedStandardOutput;
            EncodedStandardError     = encodedStandardError;
            NumberOfWarnings         = numberOfWarnings;
            PrimaryProcessTimes      = primaryProcessTimes;
            JobAccountingInformation = jobAccountingInformation;
            ExitCode      = exitCode;
            SandboxPrepMs = sandboxPrepMs;
            ProcessSandboxedProcessResultMs = processSandboxedProcessResultMs;
            ProcessStartTimeMs                  = processStartTime;
            AllReportedFileAccesses             = allReportedFileAccesses;
            DetouringStatuses                   = detouringStatuses;
            MaxDetoursHeapSizeInBytes           = maxDetoursHeapSize;
            SharedDynamicDirectoryWriteAccesses = sharedDynamicDirectoryWriteAccesses;
            ContainerConfiguration              = containerConfiguration;
            PipProperties      = pipProperties;
            TimedOut           = timedOut;
            RetryInfo          = retryInfo;
            CreatedDirectories = createdDirectories ?? CollectionUtilities.EmptySet <AbsolutePath>();
        }
Пример #34
0
      public SCG.IReadOnlyDictionary<Guid, bool> TestPacketIdsAreNew(IReadOnlySet<Guid> queryIds) {
         return queryIds.ToDictionary(
            q => q,
            seenIds.TryAdd);

//         var results = new SCG.Dictionary<Guid, bool>();
//
//         HashSet<Guid> newIdCandidates = new HashSet<Guid>();
//         foreach (var queryId in queryIds) {
//            if (seenIds.Contains(queryId)) {
//               results[queryId] = false;
//            } else {
//               newIdCandidates.Add(queryId);
//            }
//         }
//
//         lock (synchronization) {
//            var nextSeenIds = new HashSet<Guid>(seenIds);
//            foreach (var queryId in newIdCandidates) {
//               results[queryId] = nextSeenIds.Add(queryId);
//            }
//            seenIds = nextSeenIds;
//         }
//
//         return results;
      }
        private int nextFinalizeState = StateMachineStates.FinishedStateMachine - 1;  // -3

        internal IteratorMethodToStateMachineRewriter(
            SyntheticBoundNodeFactory F,
            MethodSymbol originalMethod,
            FieldSymbol state,
            FieldSymbol current,
            IReadOnlySet<Symbol> variablesCaptured,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> initialProxies,
            DiagnosticBag diagnostics)
            : base(F, originalMethod, state, variablesCaptured, initialProxies, diagnostics, useFinalizerBookkeeping: false)
        {
            this.current = current;
        }
        private int _nextFinalizeState = StateMachineStates.FinishedStateMachine - 1;  // -3

        internal IteratorMethodToStateMachineRewriter(
            SyntheticBoundNodeFactory F,
            MethodSymbol originalMethod,
            FieldSymbol state,
            FieldSymbol current,
            IReadOnlySet<Symbol> hoistedVariables,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
            DiagnosticBag diagnostics)
            : base(F, originalMethod, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics, useFinalizerBookkeeping: false)
        {
            _current = current;
        }
Пример #37
0
        public CommonCompiler(CommandLineParser parser, string responseFile, string[] args, string clientDirectory, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader)
        {
            IEnumerable<string> allArgs = args;
            _clientDirectory = clientDirectory;

            Debug.Assert(null == responseFile || PathUtilities.IsAbsolute(responseFile));
            if (!SuppressDefaultResponseFile(args) && File.Exists(responseFile))
            {
                allArgs = new[] { "@" + responseFile }.Concat(allArgs);
            }

            this.Arguments = parser.Parse(allArgs, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories);
            this.MessageProvider = parser.MessageProvider;
            this.AssemblyLoader = assemblyLoader;
            this.EmbeddedSourcePaths = GetEmbedddedSourcePaths(Arguments);

            if (Arguments.ParseOptions.Features.ContainsKey("debug-determinism"))
            {
                EmitDeterminismKey(Arguments, args, baseDirectory, parser);
            }
        }
        internal AsyncMethodToStateMachineRewriter(
            MethodSymbol method,
            AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
            SyntheticBoundNodeFactory F,
            FieldSymbol state,
            FieldSymbol builder,
            IReadOnlySet<Symbol> variablesCaptured,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            DiagnosticBag diagnostics)
            : base(F, method, state, variablesCaptured, nonReusableLocalProxies, diagnostics, useFinalizerBookkeeping: false)
        {
            this.method = method;
            this.asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection;
            this.asyncMethodBuilderField = builder;
            this.exprReturnLabel = F.GenerateLabel("exprReturn");
            this.exitLabel = F.GenerateLabel("exitLabel");

            this.exprRetValue = method.IsGenericTaskReturningAsync(F.Compilation)
                ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, kind: SynthesizedLocalKind.AsyncMethodReturnValue)
                : null;

            this.dynamicFactory = new LoweredDynamicOperationFactory(F);
        }
        // new:
        public MethodToStateMachineRewriter(
            SyntheticBoundNodeFactory F,
            MethodSymbol originalMethod,
            FieldSymbol state,
            IReadOnlySet<Symbol> hoistedVariables,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
            DiagnosticBag diagnostics,
            bool useFinalizerBookkeeping)
            : base(slotAllocatorOpt, F.CompilationState, diagnostics)
        {
            Debug.Assert(F != null);
            Debug.Assert(originalMethod != null);
            Debug.Assert(state != null);
            Debug.Assert(nonReusableLocalProxies != null);
            Debug.Assert(diagnostics != null);
            Debug.Assert(hoistedVariables != null);
            Debug.Assert(nextFreeHoistedLocalSlot >= 0);

            this.F = F;
            this.stateField = state;
            this.cachedState = F.SynthesizedLocal(F.SpecialType(SpecialType.System_Int32), syntax: F.Syntax, kind: SynthesizedLocalKind.StateMachineCachedState);
            _useFinalizerBookkeeping = useFinalizerBookkeeping;
            _hasFinalizerState = useFinalizerBookkeeping;
            this.OriginalMethod = originalMethod;
            _hoistedVariables = hoistedVariables;
            _synthesizedLocalOrdinals = synthesizedLocalOrdinals;
            _nextFreeHoistedLocalSlot = nextFreeHoistedLocalSlot;

            foreach (var proxy in nonReusableLocalProxies)
            {
                this.proxies.Add(proxy.Key, proxy.Value);
            }

            // create cache local for reference type "this" in Release
            var thisParameter = originalMethod.ThisParameter;
            CapturedSymbolReplacement thisProxy;
            if ((object)thisParameter != null && 
                thisParameter.Type.IsReferenceType &&
                proxies.TryGetValue(thisParameter, out thisProxy) &&
                F.Compilation.Options.OptimizationLevel == OptimizationLevel.Release)
            {
                BoundExpression thisProxyReplacement = thisProxy.Replacement(F.Syntax, frameType => F.This());
                this.cachedThis = F.SynthesizedLocal(thisProxyReplacement.Type, syntax: F.Syntax, kind: SynthesizedLocalKind.FrameCache);
            }
        }
      public async Task<IRyuContainer> CreateAsync(IReadOnlySet<ITransportFactory> transportFactories, Guid? forceId = null) {
         var container = root.CreateChildContainer();
         var proxyGenerator = container.GetOrDefault<ProxyGenerator>() ?? new ProxyGenerator();
         var shutdownCancellationTokenSource = new CancellationTokenSource();

         // Auditing Subsystem
         var auditService = new AuditService(shutdownCancellationTokenSource.Token);
         auditService.Initialize();

         // management tier containers
         var mobContextContainer = new MobContextContainer();
         var mobContextFactory = new MobContextFactory(auditService);
         var mobOperations = new MobOperations(mobContextFactory, mobContextContainer);

         // Other Courier Stuff
         var identity = Identity.Create(forceId);
         var routingTable = new RoutingTable();
         var peerDiscoveryEventBus = new AsyncBus<PeerDiscoveryEvent>();
         var peerTable = new PeerTable(container, (table, peerId) => new PeerContext(table, peerId, peerDiscoveryEventBus));

         var inboundMessageRouter = new InboundMessageRouter();
         var inboundMessageDispatcher = new InboundMessageDispatcher(identity, peerTable, inboundMessageRouter);

         var transports = new ConcurrentSet<ITransport>();
         foreach (var transportFactory in transportFactories) {
            var transport = await transportFactory.CreateAsync(mobOperations, identity, routingTable, peerTable, inboundMessageDispatcher, auditService).ConfigureAwait(false);
            transports.TryAdd(transport);
         }

         var messenger = new Messenger(identity, transports, routingTable);

         container.Set(identity);
         container.Set(routingTable);
         container.Set(peerTable);
         container.Set(inboundMessageRouter);
         container.Set(messenger);

         //----------------------------------------------------------------------------------------
         // Service Tier - Service Discovery, Remote Method Invocation
         //----------------------------------------------------------------------------------------
         var localServiceRegistry = new LocalServiceRegistry(identity, messenger);
         var remoteServiceInvoker = new RemoteServiceInvoker(identity, messenger);
         var remoteServiceProxyContainer = new RemoteServiceProxyContainer(proxyGenerator, remoteServiceInvoker);
         inboundMessageRouter.RegisterHandler<RmiRequestDto>(localServiceRegistry.HandleInvocationRequestAsync);
         inboundMessageRouter.RegisterHandler<RmiResponseDto>(remoteServiceInvoker.HandleInvocationResponse);
         container.Set(localServiceRegistry);
         container.Set(remoteServiceProxyContainer);

         //----------------------------------------------------------------------------------------
         // Management Tier - DMI - Services
         //----------------------------------------------------------------------------------------
         var managementObjectService = new ManagementObjectService(mobContextContainer, mobOperations);
         localServiceRegistry.RegisterService<IManagementObjectService>(managementObjectService);
         container.Set(mobOperations);
         container.Set(managementObjectService);

         var facade = new CourierFacade(transports, container);
         container.Set(facade);

         return container;
      }
 public ProcessSuspensionComponent(IReadOnlySet<string> processNames)
 {
     this.processNames = processNames;
 }
 public void Deserialize(IPofReader reader)
 {
     processNames = reader.ReadCollection<string, HashSet<string>>(0);
 }
        protected BoundStatement Rewrite()
        {
            if (this.body.HasErrors)
            {
                return this.body;
            }

            F.OpenNestedType(stateMachineClass);

            GenerateControlFields();

            // fields for the initial values of all the parameters of the method
            if (PreserveInitialParameterValues)
            {
                initialParameters = new Dictionary<Symbol, CapturedSymbolReplacement>();
            }

            // fields for the captured variables of the method
            var variablesCaptured = IteratorAndAsyncCaptureWalker.Analyze(compilationState.ModuleBuilderOpt.Compilation, method, body);
            this.nonReusableLocalProxies = CreateNonReusableLocalProxies(variablesCaptured);
            this.variablesCaptured = variablesCaptured;

            GenerateMethodImplementations();

            // Return a replacement body for the original method
            return ReplaceOriginalMethod();
        }
Пример #44
0
        protected BoundStatement Rewrite()
        {
            if (this.body.HasErrors)
            {
                return this.body;
            }

            F.OpenNestedType(stateMachineType);

            GenerateControlFields();

            // fields for the initial values of all the parameters of the method
            if (PreserveInitialParameterValues)
            {
                initialParameters = new Dictionary<Symbol, CapturedSymbolReplacement>();
            }

            // fields for the captured variables of the method
            var variablesToHoist = IteratorAndAsyncCaptureWalker.Analyze(F.Compilation, method, body, diagnostics);

            CreateNonReusableLocalProxies(variablesToHoist, out this.nonReusableLocalProxies, out this.nextFreeHoistedLocalSlot);

            this.hoistedVariables = variablesToHoist;

            GenerateMethodImplementations();

            // Return a replacement body for the kickoff method
            return GenerateKickoffMethodBody();
        }
 public ElectionVoteDto(Guid cacheId, Guid nominee, IReadOnlySet<Guid> followers) : base(cacheId) {
    this.Nominee = nominee;
    this.Followers = followers;
 }
 protected override void Deserialize(IPofReader reader, int baseSlot) {
    Nominee = reader.ReadGuid(baseSlot + 0);
    Followers = reader.ReadCollection<Guid, ItzWarty.Collections.HashSet<Guid>>(baseSlot + 1);
 }
Пример #47
0
        // new:
        public MethodToStateMachineRewriter(
            SyntheticBoundNodeFactory F,
            MethodSymbol originalMethod,
            FieldSymbol state,
            IReadOnlySet<Symbol> hoistedVariables,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
            DiagnosticBag diagnostics,
            bool useFinalizerBookkeeping)
            : base(slotAllocatorOpt, F.CompilationState, diagnostics)
        {
            Debug.Assert(F != null);
            Debug.Assert(originalMethod != null);
            Debug.Assert(state != null);
            Debug.Assert(nonReusableLocalProxies != null);
            Debug.Assert(diagnostics != null);
            Debug.Assert(hoistedVariables != null);
            Debug.Assert(nextFreeHoistedLocalSlot >= 0);

            this.F = F;
            this.stateField = state;
            this.cachedState = F.SynthesizedLocal(F.SpecialType(SpecialType.System_Int32), syntax: F.Syntax, kind: SynthesizedLocalKind.StateMachineCachedState);
            _useFinalizerBookkeeping = useFinalizerBookkeeping;
            _hasFinalizerState = useFinalizerBookkeeping;
            this.OriginalMethod = originalMethod;
            _hoistedVariables = hoistedVariables;
            _synthesizedLocalOrdinals = synthesizedLocalOrdinals;
            _nextFreeHoistedLocalSlot = nextFreeHoistedLocalSlot;

            foreach (var proxy in nonReusableLocalProxies)
            {
                this.proxies.Add(proxy.Key, proxy.Value);
            }
        }