The guard sees feed writes a call reads and events queued for the tick (#2782)

The guard counted only the live-read families' frame-final reads. A feed that rewrote, once a frame, state that a call or a handler reads inside a packet went unseen, as did a call that queued an event for the tick. After the flip, a listener would read such state a frame stale with no row saying so.

Changed:
- The BETWEEN/AFTER check now counts as read the whole call host's state and READ_ONLY_TO_HANDLERS, and it fails naming the writer.
- A new source scan lists every call that queues onto the tick's pending events, held against `QUEUED_FOR_THE_TICK`.
- Each hit is filed as a row naming the reference's place and its piece. Among them, WORLD_MAP_UPDATE comes from the explored-bits field watcher (`0x4a6430` → `0x4a6ce4`).

No behaviour changes. flip_readiness goes from 54 to 65 rows.

Tests: deleting a new row fails naming it, and a synthetic test covers the scanner.

Part of #2168.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sam Sung
2026-10-29 03:40:16 +07:00
committed by GitHub
parent cdebda36fb
commit ff89a59ed2
4 changed files with 495 additions and 29 deletions
+122 -7
View File
@@ -462,7 +462,7 @@ pub(super) const BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE: &[(&str, &[&str], &
/// as a read: the error keys a refusal pushes, the tutorial banks a watcher fires, the close
/// counts a window's core adds to and what a session verb posts. The lanes and the host's two
/// other sinks (the message sounds and the unit edits, which raise no event) are not queues here.
const FILLED_THROUGH_A_READ: &[&str] = &[
pub(super) const FILLED_THROUGH_A_READ: &[&str] = &[
// The account-data sections, which the download's handler stores through `&self`.
"::account_data::AccountData",
"::ui_action::errors::UiErrorKeys",
@@ -475,18 +475,20 @@ const FILLED_THROUGH_A_READ: &[&str] = &[
];
/// Every other resource a handler reads and does not write: state, tables and caches it
/// consults, none of them a queue a feed takes. A new one fails until it is placed here or in
/// consults, none of them a queue a feed takes. A system between the dispatch and the drain that
/// writes one has its row in `host_read_tests`'s lists, as a feed that rewrites what a handler
/// reads would hand it the frame before's. A new one fails until it is placed here or in
/// [`FILLED_THROUGH_A_READ`]. The list is kept by hand: an entry a handler in fact fills through a
/// shared reference leaves that queue out of [`handler_queues`], so a feed that takes it and fires
/// in system order, or a system that pushes onto a lane off it at its own place, passes every
/// check here unseen.
const READ_ONLY_TO_HANDLERS: &[&str] = &[
pub(super) const READ_ONLY_TO_HANDLERS: &[&str] = &[
// The character's language skills and word pools, which a page's show rewrites it by
// (`0x4e3856`). Not read-only in substance: `feed_language_skills` recomputes the skills
// every frame, after the dispatch, from the skill lines the handlers write, where the
// reference reads the skill live at the show (`0x4e3837` → `GetIndexedSpellSkill`). A show
// inside a packet reads them as the last frame left them: a frame-final read the flip must
// make live (#2168), which no list here measures, a handler's read of a feed's output.
// make live (#2168), its row in `BETWEEN_THE_DISPATCH_AND_THE_DRAIN`.
"::ui_chat::language::ChatLanguages",
// The usable stationery list, whose first paper the list parse gives a row with none
// (`0x4ad565`); the paper callback's handler writes it, through its own `ResMut`.
@@ -668,7 +670,7 @@ const READ_ONLY_TO_HANDLERS: &[&str] = &[
];
/// Every lane's queue, by type: what a handler fills there fires in the packets' order.
fn lane_types() -> [TypeId; 39] {
pub(super) fn lane_types() -> [TypeId; 39] {
[
// The views lane: what each packet changed in the stores.
TypeId::of::<crate::ui_unit::views::ViewLog>(),
@@ -827,7 +829,7 @@ fn lane_queue_owners() -> [(&'static str, TypeId); 39] {
}
/// Whether `id` names a `Messages<T>` buffer, which a reader takes from through a read.
fn is_messages(world: &World, id: ComponentId) -> bool {
pub(super) fn is_messages(world: &World, id: ComponentId) -> bool {
name(world, id).contains("Messages<")
}
@@ -838,7 +840,7 @@ pub(super) fn name(world: &World, id: ComponentId) -> String {
.map_or_else(|| "?".to_string(), |n| n.to_string())
}
fn ends_with_any(name: &str, rows: &[&str]) -> bool {
pub(super) fn ends_with_any(name: &str, rows: &[&str]) -> bool {
rows.iter().any(|s| name.ends_with(s))
}
@@ -1972,3 +1974,116 @@ fn every_lane_reads_of_what_a_handler_writes_is_listed() {
wrong.join("\n ")
);
}
/// The calls that queue an event on the VM's own lane for its next tick
/// ([`crate::ui_script::fire_scan::host_queue_writers`]), by a suffix of the calling function's
/// `path::fn` and the method it calls, with why. The tick fires that lane after the drain, behind
/// every packet's events, whichever system or lane the call ran in, so no call is exempt; where
/// the reference signals the event in place, inside the packet or the input that caused it, the
/// row is remaining work. The flip leaves their order as it is: each fires behind every packet
/// before it and after it. A new call fails until it has its row, and a row whose call is gone
/// fails as stale.
pub(super) const QUEUED_FOR_THE_TICK: &[(&str, &str, &str)] = &[
(
"capture/fixtures.rs::seed_ui_fixture",
"set_world_map_explored",
"a capture's fixture, dev tooling outside any session: no packet raises it",
),
(
"capture/probe_service.rs::service_probe",
"take_cursor_item_for_sale",
"a probe's scripted sale, dev tooling outside any session",
),
(
"target/click.rs::talk",
"take_cursor_item_for_sale",
"the vendor arm's sale clears the cursor outside a verb segment, so its `CURSOR_UPDATE` \
waits for the tick, where the interact ladder's `ClearCursor(0, 1)` signals inside the \
click (`0x5df5d0`, `0x5df5fc` → `0x495190`), ahead of the packets (I2, #1988)",
),
(
"ui_world_map.rs::feed_landmarks",
"set_world_map_landmark_sources",
"rebuilds the landmark list once a frame off its inputs and queues `WORLD_MAP_UPDATE` on a \
change, where the reference rebuilds and signals in `0x4a67a0` (`0x4a6ce4`) at each \
input's place: the explored bits' watcher (`0x4a6477`) in the update packet's notify \
pass, the gossip marker's set in its handler (`0x4e2840` → `0x6dac10`, `0x6dac93`) and \
its expiry in the minimap's frame update (`0x6d9411`)",
),
(
"ui_world_map.rs::feed_world_map",
"set_world_map_explored",
"pushes the explored bits once a frame and queues `WORLD_MAP_UPDATE` on a change, where \
the reference's mirror watcher on the bytes (`0x4a6430` arms \
`ClntObjMgrSetObjectMirrorHandler(4, 0xe6c, player, 0x100, 0x4a6460)`) runs inside the \
update packet's notify pass and its `0x4a6477` → `0x4a67a0` signals there (`0x4a6ce4`): \
a callback on the field callbacks' lane",
),
(
"ui_world_map.rs::feed_world_map",
"sync_world_map_to_player_zone",
"the first world enter's selection, queued for the next tick (the module's deviation), \
where the zone updater selects (`0x4947ac` → `0x4a6650` → `0x4a67a0`) and signals in \
place (`0x4a6ce4`)",
),
(
"ui_world_map.rs::install_world_loc_projector",
"set_world_loc_projector",
"installs benilla's own projection at a VM's first frame, whose first landmark list \
queues `WORLD_MAP_UPDATE`; no reference fact, as the reference projects inside \
`0x4a67a0`",
),
(
"ui_world_map.rs::seed_world_map_catalog",
"set_world_map_catalog",
"the catalog's push at the interface load, ahead of the session's packets; its \
`WORLD_MAP_UPDATE` is benilla's own, as the reference's build (`0x4a5d00`, from \
`0x48f5d1`) signals nothing",
),
(
"ui_world_map.rs::seed_world_map_catalog",
"set_world_map_direct_areas",
"the instance maps' push beside the catalog, from the same walk (`0x4a5d00`); its \
`WORLD_MAP_UPDATE` is benilla's own",
),
];
/// Every call that queues an event on the VM's lane for its next tick has its row in
/// [`QUEUED_FOR_THE_TICK`], so a feed that raises off state it compares cannot hide behind the
/// tick.
#[test]
fn every_call_that_queues_for_the_tick_is_listed() {
let writers = crate::ui_script::fire_scan::host_queue_writers();
let row = |w: &crate::ui_script::fire_scan::QueueWriter| {
QUEUED_FOR_THE_TICK
.iter()
.find(|(f, m, _)| w.writer.ends_with(&format!("/{f}")) && w.method == *m)
};
let unlisted: Vec<String> = writers
.iter()
.filter(|w| row(w).is_none())
.map(|w| format!("{} calls {} at {}", w.writer, w.method, w.at))
.collect();
assert!(
unlisted.is_empty(),
"these queue an event for the VM's next tick, behind every packet's: signal it in place, \
or give the call its row in QUEUED_FOR_THE_TICK:\n {}",
unlisted.join("\n ")
);
let stale: Vec<String> = QUEUED_FOR_THE_TICK
.iter()
.filter(|(f, m, _)| {
!writers
.iter()
.any(|w| w.writer.ends_with(&format!("/{f}")) && w.method == *m)
})
.map(|(f, m, _)| format!("{f} {m}"))
.collect();
assert!(stale.is_empty(), "stale rows: {stale:?}");
let empty: Vec<&str> = QUEUED_FOR_THE_TICK
.iter()
.filter(|(_, _, why)| why.is_empty())
.map(|(f, _, _)| *f)
.collect();
assert!(empty.is_empty(), "rows with no reason: {empty:?}");
}
+133 -21
View File
@@ -10,10 +10,12 @@
//! reference too makes outside every packet is
//! [`super::guard_tests::BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE`]'s, which stays.
//! - [`BETWEEN_THE_DISPATCH_AND_THE_DRAIN`]: the systems after the dispatch and ahead of the drain
//! that write what the host's live reads read, or push a view the drain waits for, where the
//! reference writes inside a packet. A listener fired inside the dispatch would read each as the
//! frame before left it. The writers the reference too runs after the packets, and those no
//! listener can see, are [`AFTER_THE_PACKETS_IN_THE_REFERENCE`]'s, which stays.
//! that write what a call or a handler reads inside a packet (the host's live reads, the rest of
//! the call host's state, and what the handlers read without writing), or push a view the drain
//! waits for, where the reference writes inside a packet. A listener fired inside the dispatch
//! would read each as the frame before left it. The writers the reference too runs after the
//! packets, and those no listener can see, are [`AFTER_THE_PACKETS_IN_THE_REFERENCE`]'s, which
//! stays.
//! - [`super::guard_tests::NOT_YET_ON_A_LANE`]: what fires off a handler's queue or edge from a
//! feed, ahead of every lane. Once the lanes fire inside the dispatch, each such event moves
//! from ahead of every packet event of its frame to behind them all.
@@ -26,6 +28,8 @@
//! [`super::guard_tests::LANE_READS_FRAME_FINAL`] empties at the flip itself, which makes the
//! world a lane firing reads its packet's, and every entry of
//! [`super::guard_tests::HOST_HELD_UNREAD`] is read first, as quiet or as a row of its own.
//! [`super::guard_tests::QUEUED_FOR_THE_TICK`] holds the calls that queue an event for the VM's
//! next tick, which fires behind every packet's events before the flip and after it.
use std::any::TypeId;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
@@ -43,8 +47,11 @@ const FRAME_FINAL_FEEDS: usize = 19;
const FRAME_FINAL_INPUTS: usize = 115;
/// The systems that may run after the dispatch (`apply_net_updates`) and run ahead of the drain
/// (`fire_in_order`), by a suffix of the system's name, with what each writes of the host's live
/// reads ([`crate::script_calls::live::LiveReads`]), by its name in the crate, and why: the
/// (`fire_in_order`), by a suffix of the system's name, with what each writes of the state a
/// listener's call or a handler reads inside a packet, by its name in the crate, and why: the
/// host's live reads ([`crate::script_calls::live::LiveReads`]), the rest of the call host's
/// state, which its verbs read, and what the handlers read without writing
/// ([`super::guard_tests::READ_ONLY_TO_HANDLERS`]), the queues apart. These are the
/// obstacles to the flip, each a write the reference makes inside a packet, or a view pushed in
/// its place. A listener fired inside the dispatch would read each of these as the frame before
/// left it. The writers the reference also runs after the packets are
@@ -61,27 +68,81 @@ const BETWEEN_THE_DISPATCH_AND_THE_DRAIN: &[(&str, &[&str], &str)] = &[
"copies the group's roster, which the relation reads take, once the packets are in"),
("::transport::compose_riders", &["Transform", "net::motion::remote::RemoteMotion"],
"the arrival snap `0x7c6420` (`0x618dfc`) is written inside the packet"),
("::ui_action::feed::feed_actions", &["ui_action::PlayerActions"],
"clears the bar's re-resolve flag; the known spells the book and the talents read are \
the learn handlers' alone"),
("::ui_action::feed::feed_actions", &["ui_action::ActionSlots", "ui_action::PlayerActions"],
"clears the book's and the bar's re-resolve flags; the known spells the book and the \
talents read are the learn handlers' alone"),
("::ui_action::ranks::normalize_action_ranks", &["ui_action::ActionSlots"],
"re-points the bar's spell slots at their chain's top rank on a book or bar change (its \
`Deviation:`), which the reference re-points inside the supersede's handler \
(`ReplaceActionSpell` `0x4e5e60`)"),
("::ui_action::track_learned_abilities", &["ui_action::LearnedAbilities"],
"rebuilds the learned-ability latches the world click's cursor reads in its call off the \
book, which the reference stores at the learn (`0x4b25e0`, `SetFeedPetSpell` `0x6ea1d0` \
from `0x5e9e49`) and clears at the unlearn (`0x4b2c50`), inside the spell packets"),
("::ui_action::state::feed_action_state", &["spell::cooldowns::Cooldowns",
"ui_action::state::ActionStateMemory"],
"keeps the frame's `GetTime` clock the cooldown reads map each start through, and \
writes the list as it walks the slots"),
("::ui_action::unlearn::clear_unlearned_slots", &["ui_action::PlayerActions"],
"drains the unlearned spells the bar clears; the known spells are the handlers' alone"),
("::ui_char::feed_char", &["UiScript"], "a field event's listeners read its push"),
("::ui_action::unlearn::clear_unlearned_slots", &["ui_action::ActionSlots",
"ui_action::PlayerActions"],
"drains the unlearned spells and clears their bar slots, which the reference clears \
inside the unlearn's handler (`ClearSpellSlots` `0x4e5e20` from `0x5ea253`); the known \
spells are the handlers' alone"),
("::ui_cast::feed_cast_reports", &["ui_action::cast_lines::CastFailRedisplays"],
"holds the refusals that wait on their item's record, which it tests to queue the cast \
lane's retry behind the frame's packets, where the reference shows each in the record's \
callback (`ShowItemCastFailure` `0x6e29b0`), inside `ItemCacheReceive` `0x55bdb0` in the \
answer's handler"),
("::ui_char::feed_char", &["UiScript", "ui_char::AmmoRecordHits"],
"a field event's listeners read its push, and it takes the ammo getters' record hits, a \
`UNIT_INVENTORY_CHANGED` each behind it, where the reference's hit registers no callback \
and the call reads the record itself (`0x4c83bc`, `0x4c89cf`)"),
("::ui_chat::language::feed_language_skills", &["ui_chat::language::ChatLanguages"],
"recomputes the language skills off the book and the skill lines, which a page's show \
reads inside its packet (`0x4e3856`), where the reference reads the skill live at the \
show (`0x4e3837`)"),
("::ui_craft::feed_craft", &["ui_craft::CraftItemWaits"],
"spends the craft getters' record waits as their records land and rebuilds the list, \
where the reference runs each callback (`OnCraftItemRecord` `0x4f7710`) in \
`ItemCacheReceive` `0x55bdb0`, inside the answer's handler (`0x555140`, `0x555160`)"),
("::ui_follow::feed_follow", &["ui_follow::FollowFeed"],
"fires the engine's follow transitions off the followee memo the host's `FollowUnit` \
tells too, where the reference signals inside the move's start and end (`0x611130`, \
`0x60fb60`)"),
("::ui_item_text::apply_reads", &["ui_item_text::ItemTextOpen"],
"a click's or a bag use's read, queued in its input or its call, which the reference \
opens inside them (`0x5f58c0`, `0x4e32e0`), ahead of the packets (`0x420d23`)"),
("::ui_instance::track_instance_state", &["ui_instance::InstanceState"],
"latches the dungeon just left once the map the transfer lands on is known, which the \
reference latches inside the map load and the packet (`0x464ff0`, `0x49e6ac`)"),
("::ui_macro::rebind_macro_spells", &["ui_action::PlayerActions"],
"drains the superseded ranks the bar's macros take; the known spells are the handlers' \
alone"),
("::ui_logout::feed_logout", &["ui_logout::LogoutState"],
"fires and clears the signals the logout replies queue, which the session verbs read in \
their calls, where the reference's handlers signal in place (`0x5aaef0`, `0x5aaf60`)"),
("::ui_macro::load_macros", &["ui_action::ActionSlots"],
"the macro reader (`LoadMacroFiles` `0x4f0600`), run as its sections settle, moves a \
character's buttons off benilla's older numbering through the bar verbs, a move with no \
reference fact; the reference runs the reader inside the account-data settle \
(`0x5afaca`, `0x5afd19`)"),
("::ui_macro::rebind_macro_spells", &["ui_action::PlayerActions",
"ui_macro::MacroBoundSpells"],
"drains the superseded ranks the bar's macros take and copies out the bound spells the \
bar's states read, derived once after the frame's last pet spell list, where the \
reference derives at each list's handler (`0x4bdae0` into \
`DeriveUnresolvedBoundSpells` `0x4f0ce0`); the known spells are the handlers' alone"),
("::ui_party::feed::feed_party", &["UiScript"], "a field event's listeners read its push"),
("::ui_pet::unit::feed_pet_unit", &["UiScript"], "a field event's listeners read its push"),
("::ui_session::feed_interact_npc", &["ui_session::InteractNpc"],
"copies the interaction latch into the `npc` unit the token lookups read, where the \
reference's `npc` is the latch itself (`0x515c00`), set inside the handlers through \
`SetInteractionTarget` `0x4930d0`"),
("::ui_tradeskill::feed_trade_skill", &["ui_tradeskill::TradeSkillItemWaits"],
"spends the profession getters' record waits as their records land and rebuilds the \
list, where the reference runs each callback (`OnTradeSkillItemRecord` `0x4fdc30`) in \
`ItemCacheReceive` `0x55bdb0`, inside the answer's handler (`0x555140`, `0x555160`)"),
("::ui_tradeskill::open_trade_skill", &["ui_craft::CraftOpen", "ui_tradeskill::TradeSkillOpen",
"ui_tradeskill::TradeSkillOpens"],
"opens the profession windows a cast intercepted (`0x6e4bd7`), which the reference opens \
inside the cast (`ToggleTradeSkill` `0x4fc910`, `ToggleCraftWindow` `0x4f6000`)"),
];
/// The systems between the dispatch and the drain that write what the host's live reads read,
@@ -128,6 +189,11 @@ const AFTER_THE_PACKETS_IN_THE_REFERENCE: &[(&str, &[&str], &str)] = &[
&["ui_pet::PetBar"],
"drops the pet's cooldown log, run only while no in-game interface \
is up, so no listener exists; it goes with the log"),
("::ui_chat::language::load_language_words", &["ui_chat::language::ChatLanguages"],
"loads `LanguageWords.dbc` once, the first frame the install is open, ahead of every \
world packet, as the reference loads it at startup (`StaticDBLoadAll` `0x53f8b0` → \
`0x548990`, from `ClientDBInitialize` `0x53f4f0`): no listener reads the pools before \
it"),
("::ui_mail::step_pending_mail", &["ui_mail::pending::MailPending"],
"steps the pending-mail time in the world frame's update (its slot `0x38`, `0x4818d0` → \
`0x4ade60`), which the frame pass runs after the packets (`0x420d6a` after `0x420d55`)"),
@@ -149,8 +215,8 @@ const AFTER_THE_PACKETS_IN_THE_REFERENCE: &[(&str, &[&str], &str)] = &[
];
/// The systems [`BETWEEN_THE_DISPATCH_AND_THE_DRAIN`] and [`AFTER_THE_PACKETS_IN_THE_REFERENCE`]
/// hold to, with what each writes of the host's live reads, by suffix; see the first's doc for the
/// kinds.
/// hold to, with what each writes of the state a call or a handler reads, by suffix; see the
/// first's doc for that state and the kinds.
fn writers_between(app: &mut App) -> Option<BTreeMap<String, BTreeSet<String>>> {
let world = app.world_mut();
use bevy::ecs::system::System;
@@ -165,6 +231,47 @@ fn writers_between(app: &mut App) -> Option<BTreeMap<String, BTreeSet<String>>>
.to_vec();
let mut read_resources = HashSet::new();
let mut read_components = HashSet::new();
// What a listener inside the dispatch reads past the live families: every resource and
// component a call's verbs touch through the host, and what the handlers read without writing
// ([`super::guard_tests::READ_ONLY_TO_HANDLERS`]), each a read made inside a packet in the
// reference. The queues are not state: the lanes, the message buffers and what a handler fills
// through a shared reference.
crate::net::handlers::measure(world);
let queues: HashSet<ComponentId> = super::guard_tests::lane_types()
.into_iter()
.filter_map(|t| world.components().get_resource_id(t))
.collect();
let is_state = |world: &World, id: ComponentId| {
let n = super::guard_tests::name(world, id);
!queues.contains(&id)
&& !super::guard_tests::is_messages(world, id)
&& !super::guard_tests::ends_with_any(&n, super::guard_tests::FILLED_THROUGH_A_READ)
};
let handlers = world.resource::<crate::net::handlers::NetHandlers>();
let mut handler_reads = HashSet::new();
for (_, access) in handlers.accesses() {
let access = access.combined_access();
handler_reads.extend(
access
.resource_reads()
.filter(|id| !access.has_resource_write(*id)),
);
}
read_resources.extend(handler_reads.into_iter().filter(|id| is_state(world, *id)));
for fa in &host {
read_resources.extend(
fa.access()
.resource_reads_and_writes()
.filter(|id| is_state(world, *id)),
);
if let Ok(kinds) = fa.access().try_iter_component_access() {
read_components.extend(kinds.map(|k| match k {
ComponentAccessKind::Archetypal(id)
| ComponentAccessKind::Shared(id)
| ComponentAccessKind::Exclusive(id) => id,
}));
}
}
for fa in &live {
read_resources.extend(fa.access().resource_reads_and_writes());
if let Ok(kinds) = fa.access().try_iter_component_access() {
@@ -303,9 +410,9 @@ fn rows_between(
.chain(AFTER_THE_PACKETS_IN_THE_REFERENCE)
}
/// Every system between the dispatch and the drain that writes what the host's live reads read
/// has its row, in one of the two lists, as it stands, and a row whose system no longer does is
/// stale.
/// Every system between the dispatch and the drain that writes what a call or a handler reads has
/// its row, in one of the two lists, as it stands, and a row whose system no longer does is stale:
/// a feed that rewrites once a frame what a listener's call reads inside its packet cannot hide.
#[test]
fn every_writer_between_the_dispatch_and_the_drain_is_listed() {
let mut app = crate::game_plugins::schedule_tests::headless_client();
@@ -350,7 +457,7 @@ fn every_writer_between_the_dispatch_and_the_drain_is_listed() {
.collect();
assert!(
wrong.is_empty(),
"these run between the dispatch and the drain and write what the host's live reads read: \
"these run between the dispatch and the drain and write what a call or a handler reads: \
move the write into its handler, or give each its row as it stands: in \
AFTER_THE_PACKETS_IN_THE_REFERENCE when the reference too writes it after the packets, \
else in BETWEEN_THE_DISPATCH_AND_THE_DRAIN:\n {}",
@@ -429,6 +536,11 @@ fn flip_readiness() {
g::BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE.len(),
String::new(),
),
(
"QUEUED_FOR_THE_TICK (behind every packet, flip or not)",
g::QUEUED_FOR_THE_TICK.len(),
String::new(),
),
];
let left: usize = needs.iter().map(|(_, n, _)| n).sum();
let mut out = format!("flip readiness: {left} rows to empty\n");
@@ -1000,6 +1000,201 @@ fn build(sources: Vec<Src>) -> Scan {
}
}
/// A call from benilla-app's shipped code of a benilla-ui method that queues an event on the
/// host's lane ([`host_queue_methods`]): the event fires at the next tick, behind every lane.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct QueueWriter {
/// The calling function, as `path::fn`: `crates/benilla-app/src/f.rs::feed`.
pub writer: String,
/// The benilla-ui method it calls.
pub method: String,
/// Where the call sits.
pub at: String,
}
/// The byte ranges of `src`'s `verb(…)` calls, whose events fire before the verb returns
/// (`benilla_ui::script::tick::verb`): a raise inside one does not queue.
fn verb_ranges(src: &Src) -> Vec<(usize, usize)> {
let (code, lit) = (src.code.as_bytes(), &src.lit);
let mut out = Vec::new();
let mut from = 0;
while let Some(p) = src.code[from..].find("verb(") {
let at = from + p;
from = at + "verb(".len();
if (at > 0 && is_ident(code[at - 1])) || lit[at] {
continue;
}
out.push((at, close_of(code, lit, from)));
}
out
}
/// Every call `name(` in `src` within `range`, outside `skip`, as `(position, name, qualifier)`:
/// the qualifier is the path segment before `::name`, or `.` for a method call, or empty.
fn calls_in(
src: &Src,
range: (usize, usize),
skip: &[(usize, usize)],
) -> Vec<(usize, String, String)> {
let (code, lit) = (src.code.as_bytes(), &src.lit);
let mut out = Vec::new();
let mut k = range.0;
while k < range.1.min(code.len()) {
if lit[k] || !is_ident(code[k]) || (k > 0 && is_ident(code[k - 1])) {
k += 1;
continue;
}
let end = (k..code.len())
.find(|&e| !is_ident(code[e]))
.unwrap_or(code.len());
let name = &src.code[k..end];
let after = src.code[end..].trim_start();
let before = src.code[..k].trim_end();
let is_fn = before.ends_with("fn")
&& !before[..before.len() - 2].ends_with(|c: char| c.is_alphanumeric() || c == '_');
if after.starts_with('(') && !is_fn && !skip.iter().any(|&(a, b)| a <= k && k <= b) {
let qualifier = if before.ends_with('.') {
".".to_string()
} else if let Some(path) = before.strip_suffix("::") {
path.rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
.next()
.unwrap_or("")
.to_string()
} else {
String::new()
};
out.push((k, name.to_string(), qualifier));
}
k = end;
}
out
}
/// The `pub fn`s of benilla-ui that queue an event on the host's lane
/// (`Model::pending_events`), which fires at the next tick: each that pushes onto it, calls
/// `queue_event`, or raises (`Model::raise`) outside a `verb(…)` segment, or calls a function
/// of its own file that does. A call is followed by name only within its file: followed across
/// the crate, `load`, `tick` or `drain` would name every function so called, and every caller of
/// each would queue. So a raise reached across modules, such as a held cursor write made again
/// outside a segment (`cursor::write`), is not seen here.
fn host_queue_methods(scan: &Scan) -> BTreeSet<String> {
let ui: Vec<&Src> = scan
.sources
.iter()
.filter(|s| s.path.starts_with("crates/benilla-ui/src/"))
.collect();
let defs: Vec<Vec<Def>> = ui.iter().map(|s| defs_of(s)).collect();
// Each def by its file and place, with its calls outside verb segments and whether it queues
// itself.
struct Node {
file: usize,
def: usize,
calls: Vec<(String, String)>,
queues: bool,
}
let mut nodes: Vec<Node> = Vec::new();
for (f, (src, ds)) in ui.iter().zip(&defs).enumerate() {
let verbs = verb_ranges(src);
let pushes: Vec<usize> = pushes(src, "pending_events")
.into_iter()
.map(|(at, _)| at)
.collect();
for (i, d) in ds.iter().enumerate() {
// A sink is not its own caller.
if d.name == "raise" || d.name == "queue_event" {
continue;
}
let body = (d.start + 3, d.end);
let calls = calls_in(src, body, &verbs);
let outside = |at: usize| {
body.0 <= at && at < body.1 && !verbs.iter().any(|&(a, b)| a <= at && at <= b)
};
let queues = pushes.iter().any(|&at| outside(at))
|| calls
.iter()
.any(|(_, n, q)| n == "queue_event" || (n == "raise" && q == "."));
nodes.push(Node {
file: f,
def: i,
calls: calls.into_iter().map(|(_, n, q)| (n, q)).collect(),
queues,
});
}
}
let mut queuing: BTreeSet<(usize, usize)> = nodes
.iter()
.filter(|n| n.queues)
.map(|n| (n.file, n.def))
.collect();
loop {
let names: Vec<(usize, &str)> = queuing
.iter()
.map(|&(f, i)| (f, defs[f][i].name.as_str()))
.collect();
let grew: Vec<(usize, usize)> = nodes
.iter()
.filter(|n| !queuing.contains(&(n.file, n.def)))
.filter(|n| {
n.calls.iter().any(|(name, q)| {
names.iter().any(|&(g, callee)| {
callee == name && g == n.file && (q.is_empty() || q == "." || q == "self")
})
})
})
.map(|n| (n.file, n.def))
.collect();
if grew.is_empty() {
break;
}
queuing.extend(grew);
}
queuing
.iter()
.filter(|&&(f, i)| {
let src = ui[f];
src.code[..defs[f][i].start].trim_end().ends_with("pub")
})
.map(|&(f, i)| defs[f][i].name.clone())
.collect()
}
/// Every call from benilla-app's shipped code of a [`host_queue_methods`] method, by its calling
/// function.
pub(crate) fn host_queue_writers() -> Vec<QueueWriter> {
queue_writers_of(scan())
}
fn queue_writers_of(s: &Scan) -> Vec<QueueWriter> {
let methods = host_queue_methods(s);
let mut out = Vec::new();
for src in s
.sources
.iter()
.filter(|s| s.path.starts_with("crates/benilla-app/src/"))
{
let ds = defs_of(src);
for (at, name, q) in calls_in(src, (0, src.code.len()), &[]) {
if q != "." || !methods.contains(&name) {
continue;
}
let Some(writer) = ds
.iter()
.filter(|d| d.start <= at && at < d.end)
.min_by_key(|d| d.end - d.start)
else {
continue;
};
out.push(QueueWriter {
writer: format!("{}::{}", src.path, writer.name),
method: name,
at: format!("{}:{}", src.path, line_of(&src.code, at)),
});
}
}
out.sort();
out
}
#[test]
fn the_firing_functions_are_found_by_their_signature() {
let s = scan();
@@ -1242,3 +1437,47 @@ fn a_forwarder_the_scan_cannot_trace_is_unaccounted() {
names.sort();
assert_eq!(names, ["H_ONE", "H_TWO"]);
}
/// A feed's call of a setter that queues for the tick is a writer, through a helper of the
/// setter's own file; a raise inside a verb segment and a crate-private setter are not.
#[test]
fn a_call_of_a_queueing_setter_is_a_writer() {
let ui = r#"
impl UiScript {
pub fn set_thing(&mut self) {
push_it(&mut self.model_mut());
}
pub fn in_place(&mut self) {
super::tick::verb(&self.lua, |model| model.raise("A_B", Vec::new()));
}
pub(crate) fn inner(&mut self) {
self.model_mut().pending_events.push(("X_Y".to_string(), Vec::new()));
}
}
fn push_it(model: &mut Model) {
model.raise("C_D", Vec::new());
}
"#;
let app = r#"
fn feed(script: &mut UiScript) {
script.set_thing();
script.in_place();
script.inner();
}
"#;
let s = scan_of(&[
("crates/benilla-ui/src/script/m.rs", ui),
("crates/benilla-app/src/f.rs", app),
]);
let found: Vec<(String, String)> = queue_writers_of(&s)
.into_iter()
.map(|w| (w.writer, w.method))
.collect();
assert_eq!(
found,
[(
"crates/benilla-app/src/f.rs::feed".to_string(),
"set_thing".to_string()
)]
);
}
+1 -1
View File
@@ -1139,7 +1139,7 @@ mod surface_gate;
/// The reader of every fire site, for the event gates.
#[cfg(test)]
mod fire_scan;
pub(crate) mod fire_scan;
/// The event argument-shape gate: every fire site against `reference/event_args.tsv`.
#[cfg(test)]