Inheritance: MessageBase
 private LocalState ResetState(LocalState state)
 {
     bool unreachable = !state.Reachable;
     state = ReachableState();
     if (unreachable)
     {
         state.Assign(0);
     }
     return state;
 }
        protected override void VisitCatchBlock(
            BoundCatchBlock catchBlock,
            ref LocalState finallyState
            )
        {
            if (IsInside)
            {
                var local = catchBlock.Locals.FirstOrDefault();

                if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable)
                {
                    _variablesDeclared.Add(local);
                }
            }

            base.VisitCatchBlock(catchBlock, ref finallyState);
        }
        public override void RemoveSelectionFromSender(string args)
        {
            var client   = JsonConvert.DeserializeObject <dynamic>(args);
            var myStream = LocalState.FirstOrDefault(st => st.StreamId == (string)client.streamId);
            var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)client._id);

            var selectionIds = CurrentDoc.Selection.GetElementIds().Select(id => CurrentDoc.Document.GetElement(id).UniqueId);
            var removed      = 0;

            foreach (var revitUniqueId in selectionIds)
            {
                var index = myStream.Objects.FindIndex(o => (string)o.Properties["revitUniqueId"] == revitUniqueId);
                if (index == -1)
                {
                    continue;
                }
                myStream.Objects.RemoveAt(index);
                removed++;
            }

            myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects));

            // Persist state and clients to revit file
            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Adding Speckle Receiver"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();

            if (removed != 0)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = client._id,
                    expired = true,
                    objects = myClient.objects,
                    message = String.Format("You have removed {0} objects from this sender.", removed)
                }));
            }
        }
Exemple #4
0
 public override void TraceBlockInput(
     LocalState <ValueSet <SingleValue> > normalState,
     LocalState <ValueSet <SingleValue> >?exceptionState,
     LocalState <ValueSet <SingleValue> >?exceptionFinallyState
     )
 {
     if (trace && showStates)
     {
         WriteIndented("--- before transfer ---", 1);
         WriteIndented("normal state:", 1);
         WriteIndented(normalState.ToString(), 2);
         WriteIndented("exception state:", 1);
         WriteIndented(exceptionState?.ToString(), 2);
         WriteIndented("finally exception state:", 1);
         WriteIndented(exceptionFinallyState?.ToString(), 2);
     }
 }
Exemple #5
0
        protected override (LocalState initialState, LocalState afterSwitchState) VisitSwitchStatementDispatch(BoundSwitchStatement node)
        {
            // first, learn from any null tests in the patterns
            int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression);

            if (slot > 0)
            {
                var originalInputType = node.Expression.Type;
                foreach (var section in node.SwitchSections)
                {
                    foreach (var label in section.SwitchLabels)
                    {
                        LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern);
                    }
                }
            }

            // visit switch header
            var        expressionState = VisitRvalueWithState(node.Expression);
            LocalState initialState    = this.State.Clone();

            DeclareLocals(node.InnerLocals);
            foreach (var section in node.SwitchSections)
            {
                // locals can be alive across jumps in the switch sections, so we declare them early.
                DeclareLocals(section.Locals);
            }

            var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, ref initialState);

            foreach (var section in node.SwitchSections)
            {
                foreach (var label in section.SwitchLabels)
                {
                    var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state : UnreachableState(), believedReachable : false);
                    SetState(labelResult.state);
                    PendingBranches.Add(new PendingBranch(label, this.State, label.Label));
                }
            }

            var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState();

            labelStateMap.Free();
            return(initialState, afterSwitchState);
        }
        public BrowserStackLocal(string binaryPath, string binaryArguments)
        {
            if (binaryPath == null && binaryPath.Trim() == "")
            {
                throw new Exception("The required binary path cannot be empty.");
            }
            if (binaryArguments == null)
            {
                binaryArguments = "";
            }

            this.basePath       = binaryPath;
            this.zipAbsolute    = Path.Combine(binaryPath, zipName);
            this.binaryAbsolute = Path.Combine(binaryPath, binaryName);

            this.localState      = LocalState.Idle;
            this.output          = new StringBuilder();
            this.binaryArguments = binaryArguments;
        }
Exemple #7
0
        private void ProcessState(
            HashSet <Symbol> definitelyAssigned,
            LocalState state1,
            LocalState?state2opt
            )
#endif
        {
            foreach (var slot in state1.Assigned.TrueBits())
            {
                if (
                    slot < variableBySlot.Count &&
                    state2opt?.IsAssigned(slot) != false &&
                    variableBySlot[slot].Symbol is { } symbol &&
                    symbol.Kind != SymbolKind.Field
                    )
                {
                    definitelyAssigned.Add(symbol);
                }
            }
        }
Exemple #8
0
        //void QueroColocarEsse()
        //{
        //    if (OnSelectPet != null)
        //        OnSelectPet(transform.GetSiblingIndex() - 1);
        //    else
        //        Debug.LogError("A função hedeira não foi setada corretamente");
        //}

        public void QueroColocarEsse(int qual)
        {
            MessageAgregator <MsgRequestReplacePet> .Publish(new MsgRequestReplacePet()
            {
                dono         = mDoDono.gameObject,
                replaceIndex = true,
                newIndex     = qual - 1
            });

            thisState = LocalState.emEspera;
            lPet.FinishHud();

            //manager.Dados.CriatureSai = qual - 1;
            //fase = FaseDaDerrota.entrandoUmNovo;
            //replace = new ReplaceManager(manager, manager.CriatureAtivo.transform, FluxoDeRetorno.criature);

            Debug.LogError("Elementos de Hud");
            //GameController.g.HudM.EntraCriatures.FinalizarHud();
            //GameController.g.HudM.Painel.EsconderMensagem();
        }
        public override void AddSender(string args)
        {
            var client = JsonConvert.DeserializeObject <dynamic>(args);

            ClientListWrapper.clients.Add(client);

            // TODO: Add stream to LocalState (do we actually need to??? hm...).
            var myStream = new SpeckleStream()
            {
                StreamId = (string)client.streamId, Objects = new List <SpeckleObject>()
            };

            //foreach( dynamic obj in client.objects )
            //{
            //  var SpkObj = new SpeckleObject() { };
            //  SpkObj.Properties[ "revitUniqueId" ] = obj.id.ToString();
            //  SpkObj.Properties[ "__type" ] = "Sent Object";
            //  myStream.Objects.Add( SpkObj );
            //}

            LocalState.Add(myStream);

            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Adding Speckle Sender"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();


            ISelectionFilter filter = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(client.filter), GetFilterType(client.filter.Type.ToString()));

            GetSelectionFilterObjects(filter, client._id.ToString(), client.streamId.ToString());

            SpeckleTelemetry.RecordStreamCreated("Revit");
        }
Exemple #10
0
        private void UpdateText(LocalState s)
        {
            var confirmedStateText = string.Join("\n", s.ConfirmedState);

            if (this.ConfirmedState.Text != confirmedStateText)
            {
                this.ConfirmedState.Text = confirmedStateText;
            }
            var unconfirmedupdates = string.Join("\n", s.UnconfirmedEvents);

            if (this.UnconfirmedUpdates.Text != unconfirmedupdates)
            {
                this.UnconfirmedUpdates.Text = unconfirmedupdates;
            }
            var tentativestate = string.Join("\n", s.TentativeState);

            if (this.TentativeState.Text != tentativestate)
            {
                this.TentativeState.Text = tentativestate;
            }
        }
        // Update is called once per frame
        void Update()
        {
            if (LocalState.RBTracking == localState && rb.velocity.magnitude == 0)
            {
                localState = LocalState.Resting;
                rotation.ClearReceivedMessages();
                rotation.enabled = true;
                if (transformPosition != null)
                {
                    transformPosition.ClearReceivedMessages();
                    transformPosition.enabled = true;
                }

                if (sendTransform != null)
                {
                    MessageListSend.RemoveSendBase(sendTransform);
                }
                MessageListSend.RemoveSendBase(sendRotation);
                sendTracking.SendMultipleMessages(false);
            }
        }
Exemple #12
0
 /// <summary>
 /// Called when this movement is losing control. In this case we want to play the undeply animation.
 /// </summary>
 /// <returns>true</returns>
 /// <c>false</c>
 override public bool LosingControl()
 {
     currentTarget = null;
     if (state != LocalState.UNDEPLOYED)
     {
         if (state == LocalState.UNDEPLOYING)
         {
             if (deployTimer <= 0.0f)
             {
                 state = LocalState.UNDEPLOYED;
                 return(false);
             }
         }
         else
         {
             deployTimer = deployTime;
             state       = LocalState.UNDEPLOYING;
         }
         return(true);
     }
     return(false);
 }
 /// <summary>
 /// Called when this movement is losing control. In this case we want to play the deploy animation to bring us back to ready state.
 /// </summary>
 /// <returns>true</returns>
 /// <c>false</c>
 override public bool LosingControl()
 {
     if (state != LocalState.DEPLOYED)
     {
         if (state == LocalState.DEPLOYING)
         {
             if (deployTimer <= 0.0f)
             {
                 state = LocalState.DEPLOYED;
                 // Re-enable hitboxes before we lose control
                 if (disableHurtBox)
                 {
                     hurtCollider.enabled = true;
                 }
                 if (removeHazards)
                 {
                     StartCoroutine(EnableHazardAfterDelay());
                 }
                 return(false);
             }
         }
         else
         {
             deployTimer = deployTime;
             state       = LocalState.DEPLOYING;
         }
         return(true);
     }
     // Re-enable hitboxes before we lose control
     if (disableHurtBox)
     {
         hurtCollider.enabled = true;
     }
     if (removeHazards)
     {
         StartCoroutine(EnableHazardAfterDelay());
     }
     return(false);
 }
    public void Initialise(int numPlayers)
    {
        var localStates = new Dictionary <int, LocalState>();

        for (var i = 0; i < numPlayers; i++)
        {
            localStates[i] = new LocalState {
                PlayerState = new PlayerState {
                    Position    = new Vector2(0, 0),
                    Orientation = Direction.Up,
                    HP          = 100f
                }
            };
            var player = Instantiate(PlayerPrefab, new Vector3(), new Quaternion());
            player.GetComponent <Player>().State = localStates[i].PlayerState;
            players[i] = player.GetComponent <Player>();
        }
        GlobalState = new GlobalState {
            LocalStates  = localStates,
            BulletStates = new Dictionary <string, BulletState>()
        };
    }
Exemple #15
0
        private async Task ReturnToPrimaryDisplay(string?releaseDesktopName = null)
        {
            if (releaseDesktopName != null)
            {
                var client = await workspaceNetwork.GetClientDesktop(releaseDesktopName);

                if (client != null)
                {
                    await client.RelinquishControl();
                }
            }

            var primaryDisplay = selfDesktop.PrimaryDisplay !.Value;

            DebugMessage("unblocking local input");
            inputManager.BlockInput(false);
            DebugMessage($"moving to local display {primaryDisplay}");
            var localPoint = new Point(primaryDisplay.Width / 2, primaryDisplay.Height / 2);
            await inputManager.MouseController.MoveMouse(localPoint);

            localState = new LocalState.Uncontrolled(primaryDisplay, selfDesktop.PrimaryDisplay !.Value);
        }
        /// <summary>
        /// Moves the character.
        /// </summary>
        override public bool DoMove()
        {
            if (!disableHurtBox && makeInvulnerable)
            {
                enemy.MakeInvulnerable(float.MaxValue);
            }
            if (state == LocalState.DEPLOYED)
            {
                deployTimer = deployTime;
                state       = LocalState.UNDEPLOYING;
                if (disableHurtBox)
                {
                    hurtCollider.enabled = false;
                }
                if (removeHazards)
                {
                    hazardCollider.enabled = false;
                }
            }

            return(false);
        }
        private BoundNode VisitLocalFunctionOrLambda(BoundBlock body)
        {
            var        oldPending = SavePending(); // We do not support branches *into* a lambda.
            LocalState finalState = this.State;

            this.State = TopState();
            var oldPending2 = SavePending();

            VisitAlways(body);
            RestorePending(oldPending2); // process any forward branches within the lambda body
            ImmutableArray <PendingBranch> pendingReturns = RemoveReturns();

            RestorePending(oldPending);
            Join(ref finalState, ref this.State);
            foreach (PendingBranch returnBranch in pendingReturns)
            {
                this.State = returnBranch.State;
                Join(ref finalState, ref this.State);
            }

            this.State = finalState;
            return(null);
        }
        // Control flow analysis does not normally scan the body of a lambda, but region analysis does.
        public override BoundNode VisitLambda(BoundLambda node)
        {
            var        oldPending = SavePending(); // We do not support branches *into* a lambda.
            LocalState finalState = this.State;

            this.State = ReachableState();
            var oldPending2 = SavePending();

            VisitAlways(node.Body);
            RestorePending(oldPending2); // process any forward branches within the lambda body
            ImmutableArray <PendingBranch> pendingReturns = RemoveReturns();

            RestorePending(oldPending);
            IntersectWith(ref finalState, ref this.State);
            foreach (PendingBranch returnBranch in pendingReturns)
            {
                this.State = returnBranch.State;
                IntersectWith(ref finalState, ref this.State);
            }

            this.State = finalState;
            return(null);
        }
        public PlayerTurnState(Game game, int playerNum) : base(game)
        {
            this.playerNum = playerNum;

            state = LocalState.WaitForButton;

            playerSprite = new PlayerSprite(game);

            playerSprite.Sound     = true;
            playerSprite.Direction = SpriteDirection.S;
            PlayerSprite.Small     = true;
            playerSprite.X         =
                game.MapWidth / 2 -
                Graphics.SMALLPLAYERWIDTH / 2;
            playerSprite.Y =
                game.MapHeight / 2 -
                Graphics.SMALLPLAYERHEIGHT / 2 -
                Graphics.MAPSTOREOFFSET;

            muleSprite  = new MuleSprite(game);
            lastMuleDir = SpriteDirection.S;

            game.Players[playerNum].Highlight = false;

            smallScale      = 100 / Graphics.STOREWIDTH * game.Graphics.MapScale;
            storeScale      = smallScale;
            deptBottomActed = false;
            deptTopActed    = false;

            storeTransLoc = StoreTransLoc.Middle;

            ticker         = new Ticker(game, 100d);
            ticker.TimeUp += new TimeUpHandler(ticker_TimeUp);

            stateTimer.Change(750, 750);
        }
        protected override void LeaveRegion()
        {
            if (this.IsConditionalState)
            {
                // If the region is in a condition, then the state will be split and state.Assigned will
                // be null.  Merge to get sensible results.
                _endOfRegionState = StateWhenTrue.Clone();
                Join(ref _endOfRegionState, ref StateWhenFalse);
            }
            else
            {
                _endOfRegionState = this.State.Clone();
            }

            foreach (var branch in base.PendingBranches)
            {
                if (branch.Branch != null && RegionContains(branch.Branch.Syntax.Span) && !_labelsInside.Contains(branch.Label))
                {
                    Join(ref _endOfRegionState, ref branch.State);
                }
            }

            base.LeaveRegion();
        }
        public void Kill()
        {
            try
            {
                foreach (Process p in processes)
                {
                    if (!p.HasExited)
                    {
                        p.Kill();
                    }
                }

                processes.Clear();

                foreach (Job j in jobs)
                {
                    j.Close();
                }

                jobs.Clear();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error killing: " + e.Message);
            }
            finally
            {
                if (localState != LocalState.Disconnected)
                {
                    TunnelStateChanged(localState, LocalState.Disconnected);
                }

                localState = LocalState.Disconnected;
                Console.WriteLine("TunnelState: " + localState.ToString());
            }
        }
    private void OnEnable()
    {
        var gameObjectEntity = GetComponent <GameObjectEntity>();
        var entityManager    = gameObjectEntity.EntityManager;
        var abilityEntity    = gameObjectEntity.Entity;

        // Default components
        entityManager.AddComponentData(abilityEntity, new CharacterAbility());
        entityManager.AddComponentData(abilityEntity, new AbilityControl());

        // Ability components
        var localState = new LocalState
        {
            rayQueryId = -1
        };
        var predictedState = new PredictedState
        {
            phase      = Phase.Idle,
            ammoInClip = settings.clipSize,
            COF        = settings.minCOF,
        };

        entityManager.AddComponentData(abilityEntity, settings);
        entityManager.AddComponentData(abilityEntity, localState);
        entityManager.AddComponentData(abilityEntity, predictedState);
        entityManager.AddComponentData(abilityEntity, new InterpolatedState());

        // Setup replicated ability
        var replicatedAbility = entityManager.GetComponentObject <ReplicatedAbility>(abilityEntity);

        replicatedAbility.predictedHandlers       = new IPredictedDataHandler[2];
        replicatedAbility.predictedHandlers[0]    = new PredictedEntityHandler <AbilityControl>(entityManager, abilityEntity);
        replicatedAbility.predictedHandlers[1]    = new PredictedEntityHandler <PredictedState>(entityManager, abilityEntity);
        replicatedAbility.interpolatedHandlers    = new IInterpolatedDataHandler[1];
        replicatedAbility.interpolatedHandlers[0] = new InterpolatedEntityHandler <InterpolatedState>(entityManager, abilityEntity);
    }
Exemple #23
0
        /// <summary>
        /// Changes the state of the Client State Machine.
        /// Intended to be PROTECTED - only the Client States should be able to call this from their encapsulated transition methods.
        /// Changes the internal state of the Client State Machine based on the given state type Enum.
        /// </summary>
        /// <param name="stateType">The new state type to be changed to.</param>
        /// <param name="optionalData">Optional data to be passed to the transitioning state.</param>
        public void ChangeState(StateEnum stateType, object optionalData = null)
        {
            if (currentState != null)
            {
                // Only time when the current state will be null is when the client starts.
                currentState.Exit();
                currentState.enabled = false;
            }

            try
            {
                switch (stateType)
                {
                case StateEnum.Intermission: currentState = GetComponent <ClientIntermissionState>(); break;

                case StateEnum.Race: currentState = GetComponent <ClientRaceState>(); break;

                case StateEnum.ClientSpectate: currentState = GetComponent <ClientSpectateState>(); break;

                case StateEnum.ClientStartMenu: currentState = GetComponent <ClientStartMenuState>(); break;

                case StateEnum.ClientDeath: currentState = GetComponent <ClientDeathState>(); break;

                default: throw new InvalidOperationException("Invalid Client ChangeState attempt: " + stateType.ToString());
                }
                SentrySdk.AddBreadcrumb($"Client State Machine for { LocalPlayer?.PlayerName } changed state from { StateType } to { stateType }.");
                StateType = stateType;
            }
            catch (InvalidOperationException e)
            {
                Debug.LogError(e);
            }

            currentState.enabled = true;
            currentState.Enter(optionalData);
        }
 public void Kill()
 {
     if (process != null)
       {
     process.Close();
     process.Kill();
     process = null;
     localState = LocalState.Disconnected;
       }
 }
	void Start () {
		state = LocalState.RegularState;
	}
        protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState)
        {
            if (IsInside)
            {
                var local = catchBlock.LocalOpt;

                if ((object)local != null)
                {
                    Debug.Assert(local.DeclarationKind == LocalDeclarationKind.CatchVariable);
                    _variablesDeclared.Add(local);
                }
            }

            base.VisitCatchBlock(catchBlock, ref finallyState);
        }
Exemple #27
0
 public LocalFunctionState(LocalState unreachableState)
     : base(unreachableState)
 {
 }
Exemple #28
0
 public void StopWithRememberedState()
 {
     rememberedState = State;
     State           = LocalState.stopped;
 }
Exemple #29
0
 internal void UpdateFileTime(string canonicalName, LocalState.FileTimestamp ft, bool? present)
 {
     lock (this)
     {
         LocalState.FileTimestamp prior = null;
         if (!present.HasValue || present.Value == true)
             prior = Find<LocalState.FileTimestamp>(x => x.CanonicalName == canonicalName);
         if (prior == null)
         {
             prior = new FileTimestamp() { CanonicalName = canonicalName, LastSeenTime = ft.LastSeenTime, DataIdentifier = ft.DataIdentifier };
             Insert(prior);
         }
         else
         {
             prior.LastSeenTime = ft.LastSeenTime;
             prior.DataIdentifier = ft.DataIdentifier;
             Update(prior);
         }
     }
 }
	public void StopMeditation (){
		state = LocalState.RegularState;
	}
        protected override void LeaveRegion()
        {
            if (this.IsConditionalState)
            {
                // If the region is in a condition, then the state will be split and state.Assigned will
                // be null.  Merge to get sensible results.
                _endOfRegionState = StateWhenTrue.Clone();
                IntersectWith(ref _endOfRegionState, ref StateWhenFalse);
            }
            else
            {
                _endOfRegionState = this.State.Clone();
            }

            foreach (var branch in base.PendingBranches)
            {
                if (branch.Branch != null && RegionContains(branch.Branch.Syntax.Span) && !_labelsInside.Contains(branch.Label))
                {
                    IntersectWith(ref _endOfRegionState, ref branch.State);
                }
            }

            base.LeaveRegion();
        }
        protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState)
        {
            if (IsInside)
            {
                var local = catchBlock.Locals.FirstOrDefault();

                if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable)
                {
                    _variablesDeclared.Add(local);
                }
            }

            base.VisitCatchBlock(catchBlock, ref finallyState);
        }
        protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState)
        {
            if (IsInside)
            {
                if ((object)catchBlock.LocalOpt != null)
                {
                    variablesDeclared.Add(catchBlock.LocalOpt);
                }
            }

            base.VisitCatchBlock(catchBlock, ref finallyState);
        }
        private bool RecordChangedVars(ref LocalState oldWrites,
                                       ref LocalState newWrites,
                                       ref BitVector oldReads,
                                       ref BitVector newReads)
        {
            bool anyChanged = IntersectWith(ref oldWrites, ref newWrites);

            anyChanged |= RecordCapturedChanges(ref oldReads, ref newReads);

            return anyChanged;
        }
Exemple #35
0
 internal void RemoveStageOperation(LocalState.StageOperation ss)
 {
     lock (this)
     {
         BeginTransaction();
         try
         {
             Delete(ss);
             Commit();
         }
         catch (Exception e)
         {
             Rollback();
             throw new Exception("Unable to remove stage operation!", e);
         }
     }
 }
Exemple #36
0
 internal void AddStageOperation(LocalState.StageOperation ss)
 {
     lock (this)
     {
         BeginTransaction();
         try
         {
             Insert(ss);
             Commit();
         }
         catch (Exception e)
         {
             Rollback();
             throw new Exception("Unable to stage operation!", e);
         }
     }
 }
Exemple #37
0
 protected override string Dump(LocalState state)
 {
     return("[alive: " + state.Alive + "; reported: " + state.Reported + "]");
 }
 public PostGetMessagesRequest(int accountId, string propertyHref, string idfaStatus, string requestUUID, CampaignsPostGetMessagesRequest campaigns, LocalState localState, IncludeDataPostGetMessagesRequest includeData)
 {
     this.accountId    = accountId;
     this.propertyHref = propertyHref;
     this.idfaStatus   = idfaStatus;
     this.requestUUID  = requestUUID;
     this.campaigns    = campaigns;
     this.localState   = localState;
     this.includeData  = includeData;
 }
        LearnFromDecisionDag(
            SyntaxNode node,
            BoundDecisionDag decisionDag,
            BoundExpression expression,
            TypeWithState expressionType,
            ref LocalState initialState)
        {
            // We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are
            // not copying the input to evaluate the patterns.  In this way we infer non-nullability of the original
            // variable's parts based on matched pattern parts.  Mutations in `when` clauses can show the inaccuracy
            // of analysis based on this choice.
            var rootTemp          = BoundDagTemp.ForOriginalInput(expression);
            int originalInputSlot = MakeSlot(expression);

            if (originalInputSlot <= 0)
            {
                originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(), rootTemp);
                initialState[originalInputSlot] = expressionType.State;
            }

            var tempMap = PooledDictionary <BoundDagTemp, (int slot, TypeSymbol type)> .GetInstance();

            Debug.Assert(originalInputSlot > 0);
            tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type));

            var nodeStateMap = PooledDictionary <BoundDecisionDagNode, (LocalState state, bool believedReachable)> .GetInstance();

            nodeStateMap.Add(decisionDag.RootNode, (state: initialState.Clone(), believedReachable: true));

            var labelStateMap = PooledDictionary <LabelSymbol, (LocalState state, bool believedReachable)> .GetInstance();

            foreach (var dagNode in decisionDag.TopologicallySortedNodes)
            {
                bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable);
                Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes
                (LocalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable;
                SetState(nodeState);

                switch (dagNode)
                {
                case BoundEvaluationDecisionDagNode p:
                {
                    var evaluation = p.Evaluation;
                    (int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable;
                    Debug.Assert(inputSlot > 0);
                    var inputState = this.State[inputSlot];

                    switch (evaluation)
                    {
                    case BoundDagDeconstructEvaluation e:
                    {
                        // https://github.com/dotnet/roslyn/issues/34232
                        // We may need to recompute the Deconstruct method for a deconstruction if
                        // the receiver type has changed (e.g. its nested nullability).
                        var method         = e.DeconstructMethod;
                        int extensionExtra = method.IsStatic ? 1 : 0;
                        for (int i = 0; i < method.ParameterCount - extensionExtra; i++)
                        {
                            var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations;
                            var output        = new BoundDagTemp(e.Syntax, parameterType.Type, e, i);
                            int outputSlot    = makeDagTempSlot(parameterType, output);
                            Debug.Assert(outputSlot > 0);
                            addToTempMap(output, outputSlot, parameterType.Type);
                        }
                        break;
                    }

                    case BoundDagTypeEvaluation e:
                    {
                        var output = new BoundDagTemp(e.Syntax, e.Type, e);
                        HashSet <DiagnosticInfo> discardedDiagnostics = null;
                        int outputSlot;
                        switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedDiagnostics).Kind)
                        {
                        case ConversionKind.Identity:
                        case ConversionKind.ImplicitReference:
                        case ConversionKind.NoConversion:
                        case ConversionKind.ExplicitReference:
                            outputSlot = inputSlot;
                            break;

                        case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _):
                            outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true);

                            if (outputSlot < 0)
                            {
                                goto default;
                            }
                            break;

                        default:
                            outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output);
                            break;
                        }
                        State[outputSlot] = NullableFlowState.NotNull;
                        var outputType = TypeWithState.Create(e.Type, inputState);
                        addToTempMap(output, outputSlot, outputType.Type);
                        break;
                    }

                    case BoundDagFieldEvaluation e:
                    {
                        Debug.Assert(inputSlot > 0);
                        var field      = (FieldSymbol)AsMemberOfType(inputType, e.Field);
                        int outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true);
                        Debug.Assert(outputSlot > 0);
                        var type   = field.Type;
                        var output = new BoundDagTemp(e.Syntax, type, e);
                        addToTempMap(output, outputSlot, type);
                        break;
                    }

                    case BoundDagPropertyEvaluation e:
                    {
                        Debug.Assert(inputSlot > 0);
                        var property   = (PropertySymbol)AsMemberOfType(inputType, e.Property);
                        var type       = property.TypeWithAnnotations;
                        var output     = new BoundDagTemp(e.Syntax, type.Type, e);
                        int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true);
                        if (outputSlot <= 0)
                        {
                            // This is needed due to https://github.com/dotnet/roslyn/issues/29619
                            outputSlot = makeDagTempSlot(type, output);
                        }
                        Debug.Assert(outputSlot > 0);
                        addToTempMap(output, outputSlot, type.Type);
                        break;
                    }

                    case BoundDagIndexEvaluation e:
                    {
                        var type       = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated);
                        var output     = new BoundDagTemp(e.Syntax, type.Type, e);
                        int outputSlot = makeDagTempSlot(type, output);
                        Debug.Assert(outputSlot > 0);
                        addToTempMap(output, outputSlot, type.Type);
                        break;
                    }

                    default:
                        throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind);
                    }
                    gotoNode(p.Next, this.State, nodeBelievedReachable);
                    break;
                }

                case BoundTestDecisionDagNode p:
                {
                    var  test      = p.Test;
                    bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType);
                    Debug.Assert(foundTemp);

                    (int inputSlot, TypeSymbol inputType) = slotAndType;
                    var inputState = this.State[inputSlot];
                    Split();
                    switch (test)
                    {
                    case BoundDagTypeTest t:
                        if (inputSlot > 0)
                        {
                            learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
                        }
                        gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
                        gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
                        break;

                    case BoundDagNonNullTest t:
                        if (inputSlot > 0)
                        {
                            learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
                        }
                        gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
                        gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputState.MayBeNull());
                        break;

                    case BoundDagExplicitNullTest t:
                        if (inputSlot > 0)
                        {
                            LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue);
                            learnFromNonNullTest(inputSlot, ref this.StateWhenFalse);
                        }
                        gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
                        gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
                        break;

                    case BoundDagValueTest t:
                        Debug.Assert(t.Value != ConstantValue.Null);
                        if (inputSlot > 0)
                        {
                            learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
                        }
                        gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
                        gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
                        break;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(test.Kind);
                    }
                    break;
                }

                case BoundLeafDecisionDagNode d:
                    // We have one leaf decision dag node per reachable label
                    labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable));
                    break;

                case BoundWhenDecisionDagNode w:
                    // bind the pattern variables, inferring their types as well
                    foreach (var binding in w.Bindings)
                    {
                        var variableAccess = binding.VariableAccess;
                        var tempSource     = binding.TempContainingValue;
                        var foundTemp      = tempMap.TryGetValue(tempSource, out var tempSlotAndType);
                        Debug.Assert(foundTemp);
                        var(tempSlot, tempType) = tempSlotAndType;
                        var tempState = this.State[tempSlot];
                        if (variableAccess is BoundLocal {
                            LocalSymbol: SourceLocalSymbol {
                                IsVar: true
                            } local
                        })
                        {
                            var inferredType = TypeWithState.Create(tempType, tempState).ToTypeWithAnnotations();
                            if (_variableTypes.TryGetValue(local, out var existingType))
                            {
                                // merge inferred nullable annotation from different branches of the decision tree
                                _variableTypes[local] = TypeWithAnnotations.Create(existingType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation));
                            }
                            else
                            {
                                _variableTypes[local] = inferredType;
                            }

                            int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true);
                            this.State[localSlot] = tempState;
                        }
Exemple #40
0
        protected override void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref LocalState tryState)
        {
            if (node.CatchBlocks.IsEmpty)
            {
                base.VisitTryBlock(tryBlock, node, ref tryState);
                return;
            }

            var oldPending = SavePending(); // we do not support branches into a try block

            base.VisitTryBlock(tryBlock, node, ref tryState);
            RestorePending(oldPending);
        }
 public BrowserStackTunnel()
 {
     localState = LocalState.Idle;
       output = new StringBuilder();
 }
Exemple #42
0
 protected override void Meet(ref LocalState self, ref LocalState other)
 {
     self.Alive    &= other.Alive;
     self.Reported &= other.Reported;
     Debug.Assert(!self.Alive || !self.Reported);
 }
 public LocalFuncUsages(LocalState unreachableState)
 {
     // If we have yet to analyze the local function
     // definition, assume it definitely assigns everything
     WrittenVars = unreachableState;
 }
        protected override void VisitFinallyBlock(BoundStatement finallyBlock, ref LocalState unsetInFinally)
        {
            if (_seenYieldInCurrentTry)
            {
                // Locals cannot be used to communicate between the finally block and the rest of the method.
                // So we just capture any outside variables that are used inside.
                new OutsideVariablesUsedInside(this, this.topLevelMethod).Visit(finallyBlock);
            }

            base.VisitFinallyBlock(finallyBlock, ref unsetInFinally);
        }
	public void StartMeditation (){
		state = LocalState.MeditationState;
	}
 internal Snapshot(LocalState variableState, int sharedStateIndex)
 {
     VariableState    = variableState;
     SharedStateIndex = sharedStateIndex;
 }
 private void TunnelStateChanged(LocalState prevState, LocalState state)
 {
 }