Skip to main content

kui_core/
diag.rs

1//! Warnings as data: misconfigurations the core notices, drained through
2//! [`crate::Core::take_warnings`].
3//!
4//! A grow weight with nothing to split against, a transition on a
5//! positional key under a changing sibling list, two nodes sharing one
6//! key: all of these fail silently and look like "the feature is broken"
7//! from the outside. The core can see them, so it reports each as a
8//! [`Warning`] with a stable `code` (the constants in this module), the
9//! node it is about and a message for people. Windowed runners print
10//! them; a headless test asserts on them, or on their absence.
11//!
12//! ```rust
13//! use kui_core::{Core, NodeSpec, Size};
14//!
15//! let mut core = Core::new();
16//! let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
17//! ui.leaf_keyed("a", NodeSpec::row());
18//! ui.leaf_keyed("a", NodeSpec::row()); // the same key twice
19//! ui.finish();
20//!
21//! let warnings = core.take_warnings();
22//! assert!(warnings.iter().any(|w| w.code == kui_core::diag::DUPLICATE_KEY));
23//! ```
24//!
25//! Each distinct (code, node) pair is reported once per core, so a
26//! condition that persists across frames costs one line, not a stream.
27//! The tree checks run on the first two frames and then every 16 frames.
28//! A bare `Core` runs them; runners turn them off for release builds
29//! through [`crate::Core::set_diagnostics`].
30//!
31//! Not every code comes from the tree walk. A prop name nothing claims
32//! ([`UNKNOWN_PROP`]) is raised by the binding that dropped it, through
33//! [`crate::Core::warn`]; the window codes ([`DUPLICATE_WINDOW_CONFIG`],
34//! [`WINDOW_DECLARED_WHILE_CLOSED`], [`UNKNOWN_WINDOW_KIND`]) come from the
35//! declared window set and are keyed by the window's name; a handle from
36//! another session ([`FOREIGN_RESOURCE`]) is noticed wherever it resolves;
37//! and the two about sounds ([`TRUNCATED_PLAYBACK`], [`PLAYBACK_REFUSED`])
38//! are answered by the driver, since only the audio device knows, through
39//! `Core::audio_truncated` and `Core::audio_refused`.
40
41use rustc_hash::{FxHashMap, FxHashSet};
42
43use crate::access::{self, Role};
44use crate::edit::EditStore;
45use crate::key::Key;
46use crate::resources::Foreign;
47use crate::schema;
48use crate::spec::{Dir, Sizing};
49use crate::text::TextSystem;
50use crate::tree::{NIL, Tree};
51
52/// A silent misconfiguration the core noticed while finishing a frame.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct Warning {
55    /// A stable identifier for the kind of problem: one of the constants
56    /// in this module. Match on it; the message is for people.
57    pub code: &'static str,
58    /// The node the warning is about — the parent, for
59    /// [`TRANSITION_AUTO_KEY`]; the shared key, for [`DUPLICATE_KEY`].
60    pub key: Key,
61    pub message: String,
62}
63
64impl Warning {
65    /// `{code, key, message}`, the key spelled by `h`.
66    pub fn to_value(&self, h: crate::value::Handles) -> crate::value::Value {
67        use crate::value::Value;
68        Value::map([
69            ("code", Value::str(self.code)),
70            ("key", (h.key)(self.key)),
71            ("message", Value::Str(self.message.clone())),
72        ])
73    }
74}
75
76/// One warning code and what it means, for the tables the bindings
77/// generate from the core (`docs/props.md`, the Node `WarningCode` union).
78/// `doc` is the const's own doc comment, so there is one text to edit.
79pub struct WarningDef {
80    pub code: &'static str,
81    pub doc: &'static str,
82}
83
84/// Declares the codes as the `pub const`s they have always been *and* the
85/// [`WARNINGS`] table from the same tokens: the doc comment on each const
86/// is the table's `doc`. A code added outside this block compiles, but
87/// `every_code_is_in_the_table_and_vice_versa` fails, so the two cannot
88/// drift.
89macro_rules! warnings {
90    ($( $(#[doc = $doc:literal])+ pub const $name:ident: &str = $code:literal; )*) => {
91        $( $(#[doc = $doc])+ pub const $name: &str = $code; )*
92        /// Every warning code with its description, in declaration order.
93        pub const WARNINGS: &[WarningDef] = &[
94            $( WarningDef { code: $code, doc: concat!($($doc, "\n"),+) }, )*
95        ];
96    };
97}
98
99warnings! {
100    /// A grow weight other than 1 on the only grow child of its parent (the
101    /// weight splits space between grow siblings, so alone it changes nothing)
102    /// or across the parent's main axis (cross-axis grow fills the parent
103    /// whatever its weight).
104    pub const GROW_WEIGHT_IGNORED: &str = "grow-weight-ignored";
105    /// The child count of a node changed while one of its children carries a
106    /// transition under an auto-assigned key. Auto keys are sibling positions,
107    /// so the children that shifted became new nodes and snapped instead of
108    /// easing. Give list items a key.
109    pub const TRANSITION_AUTO_KEY: &str = "transition-auto-key";
110    /// Two nodes in one frame share a key: everything retained per key
111    /// (transitions, scroll offsets, editors, layout events, hover state) is
112    /// mixed between them. Siblings need distinct keys.
113    pub const DUPLICATE_KEY: &str = "duplicate-key";
114    /// A label resolved by name (`focus("beta")` in Node, `env.set_focus("beta")`
115    /// in Lua, `kui_key_of` in C) is declared by more than one node in the
116    /// frame, under different parents, so they have distinct keys and the name
117    /// picked the first in tree order. Labels are unique among siblings, not
118    /// across a tree. An extension asking from inside a fill is answered
119    /// from the nodes that fill opened and no one else's — not even its own
120    /// other slots' — and the host from its own first; so this is a clash
121    /// among the asker's own. Give the node meant a label nothing else
122    /// declares, or pass the hex key an event carried.
123    /// Two nodes with the *same* key are `duplicate-key`.
124    pub const AMBIGUOUS_KEY: &str = "ambiguous-key";
125    /// A lookup by accessible name (`Core::key_named`, `ctx.keyNamed`,
126    /// `kui_key_named`) found more than one node with that name in the
127    /// last frame — two buttons both read as "Delete" — and used the first
128    /// in tree order. A reader hears the same name twice too: give each a
129    /// `label` that says which, or look the one meant up by its key label.
130    /// When one of them is static text and another is not — a caption
131    /// under the button it repeats — the message says so: a caption a
132    /// reader need not hear is decorative, and `role="none"` on the box
133    /// around it takes it out of the tree (backlog F140).
134    pub const AMBIGUOUS_NAME: &str = "ambiguous-name";
135    /// A `focusRegion(name)` (`Core::focus_region`, `env.focus_region`,
136    /// `kui_focus_region`) named a node the frame after it did not declare
137    /// as a `focusRegion` — no node under the label, or a node without the
138    /// row — so nothing was entered and focus stayed where it was. The call
139    /// is resolved against the frame it lands on, so an `update` that
140    /// toggles a dock on and enters it in one go is fine; this is that
141    /// call with the view half missing, with a name the view spells
142    /// differently, or naming a node that is not a region.
143    pub const FOCUS_REGION_WITHOUT_NODE: &str = "focus-region-without-node";
144    /// A `reveal` or `setScroll` by label (`env.reveal("rows")`,
145    /// `win.reveal("rows")`, `Core::reveal_label`) named a label the frame
146    /// it resolved against did not declare, so nothing moved. A label is
147    /// resolved when the frame finishes, so a view may name a node it is
148    /// declaring right now, or one the next frame declares; this is the
149    /// name spelled differently from the `key` that declares it, or the
150    /// node not declared at all.
151    pub const LABEL_WITHOUT_NODE: &str = "label-without-node";
152    /// A text's `family` named a family no installed or loaded font has,
153    /// so it shaped as sans. `sans`, `serif` and `mono` are
154    /// kui's own; any other name is matched as `addSystemFont` matches it,
155    /// and `systemFonts()` lists the names a machine has.
156    pub const UNKNOWN_FAMILY: &str = "unknown-family";
157    /// A `selectable` node inside another `selectable` node. Selection
158    /// scopes do not nest: the innermost one owns every run under it, so
159    /// the outer scope selects only the text outside the inner one — and
160    /// a drag that crosses the boundary stops there, which reads as a
161    /// selection that will not extend. Declare the scope once, on the
162    /// container whose text should select as one.
163    pub const NESTED_SELECTION_SCOPE: &str = "nested-selection-scope";
164    /// An image with no `label`: assistive technology has nothing to say
165    /// for it. Decorative images take `role="none"`.
166    pub const IMAGE_WITHOUT_LABEL: &str = "image-without-label";
167    /// A `slider` whose `valueNow` lies outside its own `valueMin` /
168    /// `valueMax`, or whose `valueMin` is above its `valueMax`. The row is
169    /// advertised verbatim, so a screen reader reads a value the range
170    /// says is impossible; the app that clamps in its own `update` keeps the
171    /// range in two places with nothing tying them, and this is the tie.
172    /// Declare the range the value is really held to, or clamp where the
173    /// view declares it.
174    pub const SLIDER_VALUE_OUT_OF_RANGE: &str = "slider-value-out-of-range";
175    /// `Core::add_fragment` was given WGSL that does not compile, so no
176    /// handle was minted and nothing will draw. The message carries naga's
177    /// own error with the line numbers moved into the app's source.
178    /// The source is rejected here rather than at the first
179    /// frame that shows it, so a headless test sees it too.
180    pub const FRAGMENT_REJECTED: &str = "fragment-rejected";
181    /// A `fragment` node declared more than sixteen `params`. The shader
182    /// takes four `vec4<f32>` and no more, so the extra numbers were
183    /// dropped; pass fewer, or pack what the fragment needs into the
184    /// sixteen it has.
185    pub const FRAGMENT_PARAMS_TRUNCATED: &str = "fragment-params-truncated";
186    /// A `polygon` declared more than eight points: the stock fragment
187    /// takes eight vertices in the sixteen params it has, so the rest
188    /// were dropped. Two polygons, or a `path`, which takes any outline.
189    pub const POLYGON_POINTS_TRUNCATED: &str = "polygon-points-truncated";
190    /// A `path`'s `d` did not parse: the message names the byte and what
191    /// was expected there (a number, a command letter, an arc flag). Or
192    /// the path holds a number that is not finite - a NaN or an infinity,
193    /// which `1e99` in `d` is - among its coordinates or in its turn. The
194    /// node draws nothing. Raised once per key.
195    pub const PATH_MALFORMED: &str = "path-malformed";
196    /// A `path`'s mask is wider or taller than a texture the device can
197    /// hold, so it draws nothing: the message names the size and the
198    /// limit. Draw it smaller, or as several paths.
199    pub const PATH_TOO_LARGE: &str = "path-too-large";
200    /// The frame's modal surface is not in a float, and content painted after
201    /// it is drawn on top of it: everything the user can see over the modal is
202    /// inert, which looks like inert-behind is broken. A modal that has to
203    /// cover the app is a float (`float="viewport"`). Also raised for a modal that *is*
204    /// a float when another float from outside its scope stacks over it:
205    /// a HUD
206    /// opened after the dialog is the same inert surface over it.
207    pub const MODAL_BEHIND_CONTENT: &str = "modal-behind-content";
208    /// A control (a button, link, tab, checkbox, slider, editor) with no
209    /// computable name: no `label`, and no text inside it. Icon buttons and
210    /// editors need a `label`.
211    pub const CONTROL_WITHOUT_NAME: &str = "control-without-name";
212    /// A focusable node inside a composite's *item* — a button inside a list
213    /// row, a link inside a tab. The item is one roving stop of a composite,
214    /// so the Tab ring
215    /// stops at the item and nothing reaches what is inside it: declared, and
216    /// impossible, which is what `modal-behind-content` set the precedent
217    /// for. A focusable node inside the *container* but outside every item —
218    /// a "+" at the end of a tab bar — is reachable and is not reported.
219    pub const FOCUSABLE_INSIDE_ITEM: &str = "focusable-inside-item";
220    /// A `radio` with no `radioGroup` above it, or a `tab` with no
221    /// `tabList` — the stock `<radio>` included. Outside its container an
222    /// item is no composite's:
223    /// each one is a Tab stop of its own, the arrows, Home and End do not
224    /// move the choice, and a screen reader announces no "2 of 3". Wrap the
225    /// set in the container, labelled with what the choice is. A `menuItem`
226    /// or `listItem` on its own is not reported: the menus build their own
227    /// container, and a row outside a list is only a looser reading.
228    pub const ITEM_OUTSIDE_CONTAINER: &str = "item-outside-container";
229    /// A `modal` surface with no `label`. A dialog is not named by the text
230    /// inside it (it is not one of ARIA's name-from-content roles), so a
231    /// screen reader announces it as an unnamed dialog — the same silent
232    /// defect `control-without-name` catches, on the node that just took
233    /// the user's focus. Only the derived dialog role is checked: a modal
234    /// that says what it is with an explicit `role` says it with a `label`
235    /// too, or means something naming works differently for.
236    pub const MODAL_WITHOUT_NAME: &str = "modal-without-name";
237    /// A node declares `live` but carries no `label` and holds no text, so
238    /// nothing it ever does can be announced: every platform derives the
239    /// spoken string from a name, and there is none to derive. The same
240    /// silent defect `image-without-label` catches, on the node that was
241    /// meant to speak.
242    pub const LIVE_REGION_WITHOUT_NAME: &str = "live-region-without-name";
243    /// The same announcement text was queued on two consecutive frames.
244    /// That is what an unguarded `announce` in a frame builder looks like
245    /// — a view runs every frame, so the message is said every frame —
246    /// and it is never what an app means: a message genuinely repeated is
247    /// repeated across frames the user did something in between. The
248    /// announcement still goes through; this names the builder that is
249    /// shouting.
250    pub const ANNOUNCEMENT_REPEATED: &str = "announcement-repeated";
251    /// `wrapChildren` on a container that cannot break lines: a column, a
252    /// row whose main axis scrolls, or a row of a table, whose children are
253    /// the table's columns. All lay out exactly as if the flag were absent,
254    /// which reads as "wrapping is broken"; see `LayoutSpec::wrap` for why
255    /// a column cannot have it.
256    pub const WRAP_IGNORED: &str = "wrap-ignored";
257    /// An alignment declared where it means nothing: a spread
258    /// (`spaceBetween` / `spaceAround` / `spaceEvenly`) on `crossAlign`,
259    /// `baseline` on `mainAlign` or on a column's `crossAlign`, or either
260    /// as a float's attach point. Each lays out as `start` — the two
261    /// centring spreads as `center` — which reads as "the value is
262    /// broken" when it is the axis that is wrong.
263    pub const ALIGN_IGNORED: &str = "align-ignored";
264    /// An `aspectRatio` with nothing it can set: both axes are
265    /// declared, or the width is `fit` under a `grow` or percent height,
266    /// which is resolved only after every width is. The ratio sizes a fit
267    /// height from the width, or a fit width from a fixed height.
268    pub const ASPECT_IGNORED: &str = "aspect-ignored";
269    /// A `backdropBlur` under an opaque `bg` of the node's own: the
270    /// background paints over the whole blur, so nothing of it shows and
271    /// the copy and the passes are spent for nothing. Give the `bg` some
272    /// transparency (`#ffffff40`) — frosted glass is a translucent fill
273    /// over a blur (backlog F129).
274    pub const BACKDROP_BLUR_HIDDEN: &str = "backdrop-blur-hidden";
275    /// A text node sits more than four levels below the `line` row above
276    /// it, which is as far as a text's place remembers its ancestors — so
277    /// `textHit` / `caretRect` asked by that row's key cannot find the run,
278    /// and a press inside it reports `byte: 0`. Flatten the wrappers between
279    /// the row and its text, or ask by a nearer key.
280    pub const TEXT_BEYOND_LINE: &str = "text-beyond-line";
281    /// One frame removed more nodes declaring `exit` than the exit store
282    /// will hold (4096, `depart::MAX_NODES`), so none of that frame's removal
283    /// animated: every departing node of it vanished at once, as a node with
284    /// no `exit` does, rather than some sliding out and the rest blinking.
285    /// Correct, and
286    /// invisible from the outside, which is the whole reason it is a line
287    /// here: a list that drops a thousand rows wants `exit` on the list, not
288    /// on every row. A removal that fits the budget but finds earlier exits
289    /// still in flight evicts those, oldest first, and is not this warning.
290    pub const EXIT_BUDGET: &str = "exit-budget";
291    /// A prop name nothing claims: not a schema row, not a composite, not one of
292    /// the element's own props (see `schema::known_prop`). The binding threw the
293    /// declaration away — `hoverBg` in a Lua table, `onclick` in JSX — so unlike
294    /// every other code here this one is raised by the frontend that saw it,
295    /// through `Core::warn`: by the time a frame is a tree the name is
296    /// gone. The message names the likely spelling. Also raised for a key
297    /// a menu row map carried that no row reads — `disabled` on a select's
298    /// option, where the key is `enabled` — by the binding that read the
299    /// row.
300    pub const UNKNOWN_PROP: &str = "unknown-prop";
301    /// The process has spelled 65 536 distinct size expressions — the most
302    /// the table every window shares keeps, and never lets go of — and one
303    /// more was declared: that prop is left at its default (a `width` is
304    /// fit, a clamp none) instead of failing the frame, and so is every new
305    /// expression after it; the ones kept still resolve. A view that makes
306    /// a new expression per frame reaches it — a `{ max: [dragX, { percent:
307    /// 30 }] }` fed a splitter's fractional drag, a `format!` of the
308    /// pointer — where one expression per layout, with the moving part a px
309    /// size beside it, would not. Raised once per core; the message names
310    /// the last expression refused.
311    pub const SIZE_EXPRESSIONS_FULL: &str = "size-expressions-full";
312    /// One name declared with two different window configs on the frame it
313    /// opened. The config is read on the opening edge only, and on that edge
314    /// the lowest declaring window wins (the first declaration within one
315    /// frame), so the pick is deterministic — but two places in the app
316    /// disagree about what `"palette"` is, and only one of them is right.
317    pub const DUPLICATE_WINDOW_CONFIG: &str = "duplicate-window-config";
318    /// A window the user closed is still declared, so it stays closed: a
319    /// declaration reopens a window only when it *starts*, and this one never
320    /// stopped. The first version of every multi-window app does this — it
321    /// declares the window unconditionally — and from outside it looks like
322    /// `windows` being ignored. Handle the `{kind:"window", phase:"closed"}`
323    /// event, stop declaring the name, and declare it again to reopen.
324    pub const WINDOW_DECLARED_WHILE_CLOSED: &str = "window-declared-while-closed";
325    /// A window declared with a `KUI_WINDOW_KIND_*` this build does not
326    /// have — `KUI_WINDOW_KIND_NORMAL` and `KUI_WINDOW_KIND_POPUP` are the
327    /// two there are. Only a C host can reach this: JSX and Lua name a kind
328    /// by string, so an unknown one is refused where it is written rather
329    /// than reported a frame later. The window still opens, as a normal
330    /// one, so a host built against a later header degrades to a window
331    /// rather than to nothing; this line is what keeps that from being
332    /// silent.
333    pub const UNKNOWN_WINDOW_KIND: &str = "unknown-window-kind";
334
335    /// A `setEditText` (`Core::set_edit_text`, `kui_edit_set_text`) named a
336    /// key or a label, the text was held for the frame that would declare
337    /// it, and the frame after the call declared no editor under that name
338    /// — so nothing was ever seeded and the text is dropped. The call is
339    /// meant to run from an `update` that also opens the editor, one frame
340    /// ahead of the view that declares it; this is the same call with the
341    /// view half missing, or with a name the view spells differently. Pass
342    /// the label the editor's `key` prop declares — the spelling that
343    /// needs nothing to exist yet — or the hex key an event carried.
344    /// `keyOf`/`kui_key_of` turns a label into that key, but only for an
345    /// editor some frame declared (Lua's verbs take the label itself). An editor that already
346    /// exists takes the text where the call is made and never reaches
347    /// this.
348    pub const EDIT_TEXT_WITHOUT_EDITOR: &str = "edit-text-without-editor";
349
350    /// A one-shot `audio` node went away — or changed its `src` — while
351    /// the sound it started was still playing, so the user heard it cut
352    /// off. Almost always a duration guessed short: the view keeps the
353    /// node declared for a constant it picked, and the asset is longer.
354    /// Ask for the sound instead of the guess —
355    /// `finish` (`AudioSpec::finish`, `finish` in JSX and Lua) releases the
356    /// playback on removal so it plays itself out, and a `tag` reports
357    /// `{kind:"sound", phase:"ended"}` when it gets there. A view that
358    /// means to cut the sound off says so by stopping what it started
359    /// (`Core::stop`), which is not reported, and a `looped` playback
360    /// never is: it has no end to be short of.
361    ///
362    /// Only a driver with a real device raises it, because only a device
363    /// knows the sound was still running: the core queues the `stop` and
364    /// the driver answers `Core::audio_truncated` for the ones its handle
365    /// found still playing. A headless `Ctx` therefore never raises it —
366    /// nothing plays — and the assertion point there is the other end of
367    /// the same fact: `audioCommands()` holding a `stop` for the node,
368    /// where the suite expected none.
369    pub const TRUNCATED_PLAYBACK: &str = "truncated-playback";
370
371    /// A `FontId` / `ImageId` / `SoundId` registered in one `Session` and used
372    /// through a core of another. Handles are unique to the process, so it
373    /// cannot resolve to somebody else's resource; it behaves as a removed
374    /// handle does (draws nothing, shapes as sans-serif, plays nothing), which
375    /// from outside looks like the resource never registered. Two
376    /// `Core::new()`s are two sessions; windows that share resources are built
377    /// with `Core::new_in` against one `Session`.
378    pub const FOREIGN_RESOURCE: &str = "foreign-resource";
379
380    /// An extension names a slot no host declared this frame, so it drew
381    /// nothing. A slot is a position the host declares in its own view by
382    /// full name, `ui.slot("ns/name")` — the namespace the host gave the
383    /// extension, then the name the extension lists; one listing none fills
384    /// `"ns/root"` after the host's view. Declare the slot, or drop the name
385    /// from the extension's list.
386    pub const UNKNOWN_SLOT: &str = "unknown-slot";
387    /// A colour or length prop named a token — `bg = "$peach"` — that
388    /// nothing declared and that is no theme or metrics role, or named one
389    /// of the other kind (a length in a colour slot). The slot is left at
390    /// the row's default, as if the prop had not been written — no `bg`,
391    /// a fit width, the theme's foreground for a text's `color` — never an
392    /// explicit transparent or zero, which would hide the node a typo was
393    /// on; the same in every binding and in every place a `$name` can go,
394    /// a keyframe stop and an entrance included, and what
395    /// `ui.token_color` / `token_length` answer `None` for in Rust. Raised
396    /// by the binding that lowered the reference, through
397    /// `Core::warn_unknown_token`, once per name, since the name is gone
398    /// by the time the frame is a tree. Also
399    /// raised at the declaration for a derived token whose source — the
400    /// `from`, or the colour a `mix` or `readable` names — is no colour
401    /// token declared before it and no theme role: that token is dropped,
402    /// the message names both, and the rest of the table lands.
403    pub const UNKNOWN_TOKEN: &str = "unknown-token";
404    /// A declared token took a theme or metrics role's name (`surface`,
405    /// `radius`) and was dropped: the roles are the corpus's contract and
406    /// `$surface` always means the theme's, so an app cannot shadow one.
407    /// Rename the token.
408    pub const RESERVED_TOKEN: &str = "reserved-token";
409    /// A slot name declared twice in one frame. The second declaration was
410    /// ignored: a fill is keyed by the slot's full name, so two fills of one
411    /// name would share every key. Two places for one extension are two
412    /// names.
413    pub const DUPLICATE_SLOT: &str = "duplicate-slot";
414    /// An extension returned from `view` with nodes still open. The core
415    /// closed them at the depth the fill began, so the host's tree is what
416    /// the host declared; outside the guard, the rest of the host's view
417    /// would have landed inside the extension's last open node. The
418    /// extension has an `open` without its `close`.
419    pub const UNBALANCED_EXTENSION: &str = "unbalanced-extension";
420    /// An extension's `view` returned an error. The message is drawn in
421    /// red where the fill would have been, and reported here once per
422    /// extension and slot rather than once per frame.
423    pub const EXTENSION_VIEW_ERROR: &str = "extension-view-error";
424    /// An extension declared one of its *own* slots while it was drawing,
425    /// so filling it would have meant calling it inside itself. The slot
426    /// is left empty. An extension may host extensions (`Fill::add`), and
427    /// may declare their slots — what it cannot do is be its own guest.
428    pub const RECURSIVE_SLOT: &str = "recursive-slot";
429
430    /// The device refused a play: its voices are all held, or the sound
431    /// did not decode. A released playback (`finish`) holds one of the
432    /// device's 128 voices until its file ends, so a view that releases
433    /// faster than its sounds finish reaches the limit and the 129th play
434    /// is refused. The refusal is not left silent because the playback
435    /// never starts and so never ends: a `tag`ged node waiting for
436    /// `ended` would wait forever. It gets
437    /// `{kind:"sound", phase:"refused"}` instead, and this line says why.
438    /// Stop what the view no longer needs rather than releasing it, or
439    /// release shorter sounds.
440    pub const PLAYBACK_REFUSED: &str = "playback-refused";
441    /// A devtools tab name declared twice in one frame: two `devtools_tab` /
442    /// `devtools_tab_with` calls, a host
443    /// form and an extension form of one name, or an extension declaring
444    /// from its fill under a name the host took. The first declaration
445    /// stands and the second is ignored; give the second tab its own name.
446    pub const DUPLICATE_TAB: &str = "duplicate-tab";
447    /// A `devtoolsTab` declaration a binding could not read as either
448    /// form: a child that is not a function, both a
449    /// `slot` and a child, or a `view` that is not a function in Lua. The
450    /// tab was not declared. A tab names a slot for an extension to fill,
451    /// or carries a function the binding calls only when the tab is shown.
452    pub const BAD_DEVTOOLS_TAB: &str = "bad-devtools-tab";
453    /// A select's `current` names no option the field can show: an index
454    /// past its options, or a separator's. The field is drawn as if none
455    /// were in force — an empty description, no row checked — rather than
456    /// blank with a check on a divider; the options are drawn as declared.
457    /// A `current` the view computes from a list it also filters is how
458    /// this happens; the index is into the options as passed, separators
459    /// counted. Raised once per field.
460    pub const SELECT_CURRENT_IGNORED: &str = "select-current-ignored";
461}
462
463/// The [`DUPLICATE_TAB`] warning for one name. Keyed by the name, the way
464/// `duplicate_slot` is: a tab is not a node.
465pub fn duplicate_tab(name: &str) -> Warning {
466    Warning {
467        code: DUPLICATE_TAB,
468        key: Key::ROOT.str(DUPLICATE_TAB).str(name),
469        message: format!(
470            "devtools tab {name:?} was declared twice in one frame; the second was ignored — \
471             give it its own name"
472        ),
473    }
474}
475
476/// The [`BAD_DEVTOOLS_TAB`] warning for one declaration, with what was
477/// wrong with it.
478pub fn bad_devtools_tab(name: &str, why: &str) -> Warning {
479    Warning {
480        code: BAD_DEVTOOLS_TAB,
481        key: Key::ROOT.str(BAD_DEVTOOLS_TAB).str(name),
482        message: format!("devtools tab {name:?} was not declared: {why}"),
483    }
484}
485
486/// The [`TEXT_BEYOND_LINE`] warning for one text node under `line`.
487/// Keyed by the text's node.
488pub fn text_beyond_line(text: Key, line: Key, reach: usize) -> Warning {
489    Warning {
490        code: TEXT_BEYOND_LINE,
491        key: text,
492        message: format!(
493            "the text ({:016x}) is more than {reach} levels below its `line` row ({:016x}), further than a              place remembers, so a hit asked by the row's key answers byte 0; flatten the wrappers              between them, or ask by a nearer key",
494            text.0, line.0
495        ),
496    }
497}
498
499/// The [`UNKNOWN_SLOT`] warning for one extension and slot. Keyed by the
500/// full name: there is no node, and one line per slot is the useful
501/// count however many frames repeat it.
502pub fn unknown_slot(extension: &str, namespace: &str, slot: &str) -> Warning {
503    let full = crate::slot::full_name(namespace, slot);
504    Warning {
505        code: UNKNOWN_SLOT,
506        key: Key::ROOT.str(UNKNOWN_SLOT).str(&full),
507        message: format!(
508            "extension `{extension}` (namespace `{namespace}`) fills slot {slot:?}, which no view \
509             declared this frame, so it drew nothing; declare `ui.slot({full:?})` where it \
510             should go, or drop the name from the extension's `slots`"
511        ),
512    }
513}
514
515/// The [`DUPLICATE_SLOT`] warning for one name. Keyed by the name: a slot
516/// is not a node, and the conflict is between two declarations of it.
517pub fn duplicate_slot(slot: &str) -> Warning {
518    Warning {
519        code: DUPLICATE_SLOT,
520        key: Key::ROOT.str(DUPLICATE_SLOT).str(slot),
521        message: format!(
522            "slot {slot:?} was declared twice in one frame; the second was ignored, since a \
523             fill is keyed by the slot's name — two places want two names"
524        ),
525    }
526}
527
528/// The [`UNBALANCED_EXTENSION`] warning for one fill. Keyed by the slot,
529/// which names the extension through its namespace, so a plugin that
530/// never closes costs one line.
531pub fn unbalanced_extension(slot: &str, slot_key: Key, open: usize) -> Warning {
532    Warning {
533        code: UNBALANCED_EXTENSION,
534        key: slot_key.str(UNBALANCED_EXTENSION),
535        message: format!(
536            "the extension filling slot {slot:?} returned from view with {open} node{} still \
537             open; they were closed for it — it has an `open` without its `close`",
538            if open == 1 { "" } else { "s" }
539        ),
540    }
541}
542
543/// The [`EXTENSION_VIEW_ERROR`] warning for one extension in one slot.
544/// Keyed by both, so an error that repeats every frame costs one line.
545pub fn extension_view_error(extension: &str, slot: &str, slot_key: Key, err: &str) -> Warning {
546    Warning {
547        code: EXTENSION_VIEW_ERROR,
548        key: slot_key.str(extension).str(EXTENSION_VIEW_ERROR),
549        message: format!("extension `{extension}` failed to build slot {slot:?}: {err}"),
550    }
551}
552
553/// The [`RECURSIVE_SLOT`] warning for one fill. Keyed by the slot, the
554/// same way `unbalanced-extension` is: the conflict is a name, and one
555/// line per name is the useful count however many frames repeat it.
556pub fn recursive_slot(extension: &str, slot: &str, slot_key: Key) -> Warning {
557    Warning {
558        code: RECURSIVE_SLOT,
559        key: slot_key.str(RECURSIVE_SLOT),
560        message: format!(
561            "extension `{extension}` declared slot {slot:?} while it was drawing, which is its \
562             own; it was left empty, since filling it would mean calling `{extension}` inside \
563             itself. An extension may declare the slots of extensions it loaded — not its own"
564        ),
565    }
566}
567
568/// The [`FOREIGN_RESOURCE`] warning for one handle. Keyed by kind and
569/// handle: there is no node — an image node, a text style and a `play`
570/// call can all carry the same handle — and one line per handle is the
571/// useful count however many frames repeat it.
572pub fn foreign_resource(f: &Foreign) -> Warning {
573    Warning {
574        code: FOREIGN_RESOURCE,
575        key: Key::ROOT
576            .str(FOREIGN_RESOURCE)
577            .str(f.kind.name())
578            .index(f.raw),
579        message: f.message(),
580    }
581}
582
583/// The [`SIZE_EXPRESSIONS_FULL`] warning, if the table has refused an
584/// expression: one key for the process's one table, so a core says it
585/// once.
586pub fn size_expressions_full() -> Option<Warning> {
587    let (n, last) = crate::calc::refused();
588    (n > 0).then(|| Warning {
589        code: SIZE_EXPRESSIONS_FULL,
590        key: Key::ROOT.str(SIZE_EXPRESSIONS_FULL),
591        message: format!(
592            "{} size expressions are kept, and {n} more were refused, the last \"{last}\": each \
593             is laid out as if undeclared — declare one per layout, not one per frame",
594            crate::calc::MAX_CALCS
595        ),
596    })
597}
598
599/// The [`EDIT_TEXT_WITHOUT_EDITOR`] warning for one label. Keyed by
600/// `Key::ROOT.str(label)` — not a node's key, since no node took the
601/// name, but one key per label all the same, so two unclaimed labels in
602/// a frame are two lines under the once-per-(code, key) dedup.
603pub fn edit_text_without_editor_label(label: &str) -> Warning {
604    Warning {
605        code: EDIT_TEXT_WITHOUT_EDITOR,
606        key: Key::ROOT.str(label),
607        message: format!(
608            "`set_edit_text` named label {label:?}, and the frame after it declared no editor \
609             under that name, so the text was dropped; the label is the one an editor's `key` \
610             prop declares, and the call is held for one frame — for the view that draws the \
611             editor the same `update` opened — not longer"
612        ),
613    }
614}
615
616/// The [`PLAYBACK_REFUSED`] warning for one playback. Keyed by the node
617/// that asked for the sound — the tagged node, the `audio` element, or
618/// the origin's root for an imperative `play` — so a view that keeps
619/// asking past the device's limit costs one line rather than one per
620/// refusal, which is the whole point of the dedup.
621pub fn playback_refused(key: crate::key::Key, playback: crate::audio::PlaybackId) -> Warning {
622    Warning {
623        code: PLAYBACK_REFUSED,
624        key,
625        message: format!(
626            "the audio device refused playback {} — its voices are all held, or the sound did \
627             not decode; a released (`finish`) playback holds one of the device's 128 voices \
628             until its file ends, so releasing faster than the sounds finish reaches the limit. \
629             The playback never started and will never report `ended`; a tagged one is told so \
630             with `phase: \"refused\"`",
631            playback.0
632        ),
633    }
634}
635
636/// The [`EDIT_TEXT_WITHOUT_EDITOR`] warning for one key. Keyed by the
637/// editor's own key, so a view that never declares it reports once, the
638/// way every node-shaped code does.
639/// [`MODAL_BEHIND_CONTENT`], the float-stack case: raised from emission,
640/// where the stack exists, rather than from the tree walk.
641pub(crate) fn modal_under_layer(key: Key) -> Warning {
642    Warning {
643        code: MODAL_BEHIND_CONTENT,
644        key,
645        message: "a float from outside this modal's scope opened after it and paints on top \
646                  of it: everything drawn over a modal is inert, which reads as a broken \
647                  dialog (declare it inside the modal, or close it while the modal is up)"
648            .to_string(),
649    }
650}
651
652pub fn edit_text_without_editor(key: Key) -> Warning {
653    Warning {
654        code: EDIT_TEXT_WITHOUT_EDITOR,
655        key,
656        message: format!(
657            "`set_edit_text` named key {:#x}, and the frame after it declared no editor under \
658             that key, so the text was dropped; the call is held for one frame — for the view \
659             that draws the editor the same `update` opened — not longer",
660            key.0
661        ),
662    }
663}
664
665/// The [`TRUNCATED_PLAYBACK`] warning for one cut-off playback. Keyed by
666/// the `audio` node, so a view that truncates the same chime every time it
667/// runs costs one line; `at` is where the playback was, in seconds, which
668/// is the half of "how much was lost" a device can actually report.
669pub fn truncated_playback(key: Key, why: crate::audio::Why, at: f64) -> Warning {
670    Warning {
671        code: TRUNCATED_PLAYBACK,
672        key,
673        message: format!(
674            "the `audio` node at key {:#x} was {} {:.2}s into its sound, cutting it off; keep \
675             the node declared until its `ended` event, or add `finish` so the playback is \
676             released to play itself out",
677            key.0,
678            why.verb(),
679            at
680        ),
681    }
682}
683
684/// The [`ANNOUNCEMENT_REPEATED`] warning for one text. Keyed by the text:
685/// there is no node behind an announcement, and one line per repeated
686/// message is the useful count however many frames repeat it.
687pub fn announcement_repeated(text: &str) -> Warning {
688    Warning {
689        code: ANNOUNCEMENT_REPEATED,
690        key: Key::ROOT.str(ANNOUNCEMENT_REPEATED).str(text),
691        message: format!(
692            "the announcement {text:?} was queued on two consecutive frames: `announce` says \
693             something once, and a view runs every frame, so a call made from a frame builder \
694             needs a guard the app clears (announce from the event handler, or keep a field the \
695             handler sets and the view clears)"
696        ),
697    }
698}
699
700/// The [`DUPLICATE_WINDOW_CONFIG`] warning for one window name. Keyed by
701/// the name: there is no node, and the conflict is between declarations,
702/// however many frames repeat it.
703pub fn duplicate_window_config(name: &str) -> Warning {
704    Warning {
705        code: DUPLICATE_WINDOW_CONFIG,
706        key: Key::ROOT.str(DUPLICATE_WINDOW_CONFIG).str(name),
707        message: format!(
708            "window `{name}` was declared with two different configs on the frame it opened; \
709             the lowest declaring window's first declaration won, and a live window's config is \
710             never re-read, so the other one never applies — make them agree"
711        ),
712    }
713}
714
715/// The [`WINDOW_DECLARED_WHILE_CLOSED`] warning for one window name. Keyed
716/// by the name, and raised on the core whose frame declared it, so an app
717/// that keeps asking every frame reads one line.
718pub fn window_declared_while_closed(name: &str) -> Warning {
719    Warning {
720        code: WINDOW_DECLARED_WHILE_CLOSED,
721        key: Key::ROOT.str(WINDOW_DECLARED_WHILE_CLOSED).str(name),
722        message: format!(
723            "window `{name}` is still declared after the user closed it, so it stays closed: a \
724             declaration reopens a window only when it starts — handle the \
725             `{{kind:\"window\", phase:\"closed\"}}` event, stop declaring `{name}`, and declare \
726             it again to reopen"
727        ),
728    }
729}
730
731/// The [`UNKNOWN_WINDOW_KIND`] warning for one declaration. Keyed by the
732/// window name and the kind, the way the other two window codes are keyed by
733/// a name and not a node: a declaration is not a node, and one line per
734/// (window, kind) is the useful count however many frames repeat it.
735pub fn unknown_window_kind(name: &str, kind: u32) -> Warning {
736    Warning {
737        code: UNKNOWN_WINDOW_KIND,
738        key: Key::ROOT
739            .str(UNKNOWN_WINDOW_KIND)
740            .str(name)
741            .index(kind as u64),
742        message: format!(
743            "window `{name}` was declared with kind {kind}, which this build does not have; \
744             `KUI_WINDOW_KIND_NORMAL` (0) and `KUI_WINDOW_KIND_POPUP` (1) are the ones there \
745             are, so it opened as a normal window"
746        ),
747    }
748}
749
750/// The [`FOCUS_REGION_WITHOUT_NODE`] warning for a `focus_region` the frame
751/// could not resolve. Keyed by the key or the label's hash, so a call
752/// repeated every frame costs one line.
753pub(crate) fn focus_region_without_node(target: &crate::runtime::RegionTarget) -> Warning {
754    use crate::runtime::RegionTarget;
755    let (key, named) = match target {
756        RegionTarget::Main => (Key::ROOT, "the main ring".to_string()),
757        RegionTarget::Key(k) => (*k, format!("key {:016x}", k.0)),
758        RegionTarget::Label(label) => (Key::ROOT.str(label), format!("label {label:?}")),
759    };
760    Warning {
761        code: FOCUS_REGION_WITHOUT_NODE,
762        key,
763        message: format!(
764            "`focus_region` named {named}, and the frame after it declared no `focusRegion` node \
765             there, so nothing was entered; the name is the label the region's `key` prop \
766             declares, on a node that carries the `focusRegion` row"
767        ),
768    }
769}
770
771/// The [`LABEL_WITHOUT_NODE`] warning for a deferred `verb` by `label`.
772/// Keyed by the verb and the label, so a call repeated every frame costs
773/// one line, and a `reveal` and a `set_scroll` of one typo are two.
774pub(crate) fn label_without_node(verb: &str, label: &str) -> Warning {
775    Warning {
776        code: LABEL_WITHOUT_NODE,
777        key: Key::ROOT.str(verb).str(label),
778        message: format!(
779            "`{verb}` named the label {label:?}, and the frame it resolved against declared no              node under it, so nothing moved; the name is the label a node's `key` declares"
780        ),
781    }
782}
783
784/// The [`AMBIGUOUS_KEY`] warning for one label `Core::key_of` found `count`
785/// nodes under. Keyed by the node the name resolved to, so a label asked
786/// for every frame costs one line.
787pub fn ambiguous_key(label: &str, first: Key, count: usize) -> Warning {
788    Warning {
789        code: AMBIGUOUS_KEY,
790        key: first,
791        message: format!(
792            "{count} nodes are keyed {label:?} under different parents; the first in tree order \
793             ({:016x}) was used — give the one meant a label nothing else declares, or pass its \
794             hex key",
795            first.0
796        ),
797    }
798}
799
800/// [`ambiguous_name`] when one of the nodes is static text and another is
801/// not: a caption beside the control it repeats (backlog F140). The
802/// message names the decorative door as well as the `label` one.
803pub fn ambiguous_caption(name: &str, first: Key, count: usize) -> Warning {
804    Warning {
805        code: AMBIGUOUS_NAME,
806        key: first,
807        message: format!(
808            "{count} nodes are named {name:?} to a reader, and one is text beside a control              with the same name; the first in tree order ({:016x}) was used — a caption a              reader need not hear is decorative: put `role=\"none\"` on the box around it              and it leaves the tree; or give the control a `label` that says what it does",
809            first.0
810        ),
811    }
812}
813
814/// The [`AMBIGUOUS_NAME`] warning for one accessible name `Core::key_named`
815/// found on `count` nodes. Keyed by the node it resolved to.
816pub fn ambiguous_name(name: &str, first: Key, count: usize) -> Warning {
817    Warning {
818        code: AMBIGUOUS_NAME,
819        key: first,
820        message: format!(
821            "{count} nodes are named {name:?} to a reader; the first in tree order ({:016x}) \
822             was used — give the one meant a `label` that says which, or look it up by its key \
823             label",
824            first.0
825        ),
826    }
827}
828
829/// The [`SELECT_CURRENT_IGNORED`] warning for one field: `current` was
830/// `index` over `count` options and `separator` says whether it landed on
831/// one rather than past the end. Keyed by the field, so a view that draws
832/// it that way every frame costs one line.
833pub fn select_current_ignored(
834    key: Key,
835    label: &str,
836    index: usize,
837    count: usize,
838    separator: bool,
839) -> Warning {
840    let why = if separator {
841        "which is a separator".to_string()
842    } else {
843        format!(
844            "and the field has {count} option{}",
845            if count == 1 { "" } else { "s" }
846        )
847    };
848    Warning {
849        code: SELECT_CURRENT_IGNORED,
850        key,
851        message: format!(
852            "`current` of select {label:?} names option {index} counted from 0, {why}, so the \
853             field shows no choice and no row is checked — pass an index of an option, or none"
854        ),
855    }
856}
857
858/// The [`UNKNOWN_PROP`] warning for a key a menu row map carried that
859/// [`crate::MenuItem::from_value`] does not read — `disabled` for
860/// `enabled: false` — so the row was built without it.
861/// Keyed by the name, as [`unknown_prop`]'s are: one line per spelling.
862/// `items` is a row's key, so it arrives here only from a select's option
863/// ([`crate::MenuItem::stray_option_keys`]), and says so.
864pub fn unknown_menu_item_key(name: &str) -> Warning {
865    let key = Key::ROOT
866        .str(UNKNOWN_PROP)
867        .str(crate::MenuItem::NAME)
868        .str(name);
869    if name == "items" {
870        return Warning {
871            code: UNKNOWN_PROP,
872            key,
873            message: "`items` on a select's option is dropped: an option is chosen, never \
874                      opened, so it has no submenu"
875                .into(),
876        };
877    }
878    let keys = crate::MenuItem::KEYS
879        .iter()
880        .map(|k| format!("`{k}`"))
881        .collect::<Vec<_>>()
882        .join(", ");
883    // The one misspelling with a meaning of its own gets the value it was
884    // after; the rest the nearest key by letters, as `schema::suggest` does.
885    let squash = |s: &str| s.replace('_', "").to_ascii_lowercase();
886    let hint = if name == "disabled" {
887        " (did you mean `enabled: false`?)".to_string()
888    } else {
889        match crate::MenuItem::KEYS
890            .iter()
891            .find(|k| squash(k) == squash(name))
892        {
893            Some(near) => format!(" (did you mean `{near}`?)"),
894            None => String::new(),
895        }
896    };
897    Warning {
898        code: UNKNOWN_PROP,
899        key,
900        message: format!(
901            "`{name}` is not a key of a menu item: a row takes {keys}, so this declaration is \
902             dropped{hint}"
903        ),
904    }
905}
906
907/// The [`UNKNOWN_PROP`] warning for one dropped name, with the nearest
908/// legitimate spelling when there is an obvious one. The key is derived from
909/// the element and the name rather than from a node, so a misspelling costs
910/// one line however many nodes carry it and however many frames draw them.
911/// `element` [`crate::MenuItem::NAME`] is a menu row's key rather than a
912/// node's prop, and takes [`unknown_menu_item_key`]'s wording.
913pub fn unknown_prop(element: &str, name: &str, spelling: schema::Spelling) -> Warning {
914    if element == crate::MenuItem::NAME {
915        return unknown_menu_item_key(name);
916    }
917    // A real row on an element that reads only some of them is not a
918    // misspelling, and the nearest spelling would be the row itself; the
919    // warning says which rows the element does read instead.
920    let message = match schema::element_rows(element, spelling) {
921        Some(rows) if schema::shared_prop(name, spelling) => {
922            let takes = if rows.is_empty() {
923                "none of them".to_string()
924            } else {
925                format!(
926                    "only {}",
927                    rows.iter()
928                        .map(|r| format!("`{r}`"))
929                        .collect::<Vec<_>>()
930                        .join(", ")
931                )
932            };
933            format!(
934                "`{name}` is a prop, but not one {element} reads: its look is its own, and it \
935                 takes {takes}, so this declaration is dropped — a box with `role` set takes \
936                 every row"
937            )
938        }
939        _ => {
940            let hint = match schema::suggest(element, name, spelling) {
941                Some(near) => format!(" (did you mean `{near}`?)"),
942                None => String::new(),
943            };
944            format!(
945                "`{name}` is not a prop of {element}: no binding reads it, so this declaration \
946                 is dropped{hint}"
947            )
948        }
949    };
950    Warning {
951        code: UNKNOWN_PROP,
952        key: Key::ROOT.str(UNKNOWN_PROP).str(element).str(name),
953        message,
954    }
955}
956
957/// Pending warnings are capped so a host that never drains them cannot
958/// grow the queue without bound.
959const MAX_PENDING: usize = 256;
960/// The checks run on the first two frames and every this many after.
961pub(crate) const CHECK_EVERY: u64 = 16;
962
963pub(crate) struct Diagnostics {
964    pub(crate) enabled: bool,
965    pending: Vec<Warning>,
966    /// Everything that ever reached `pending`, kept after the drain: the
967    /// warnings of a core's whole life, for a reader that is not the
968    /// driver (a dev overlay showing what the runner printed). Bounded
969    /// the way `warned` is, since each (code, key) lands here once.
970    log: Vec<Warning>,
971    warned: FxHashSet<(&'static str, Key)>,
972    /// Child count at the last check, for parents with an auto-keyed child
973    /// that carries a transition.
974    child_counts: FxHashMap<Key, u32>,
975    scratch: Vec<u64>,
976}
977
978impl Default for Diagnostics {
979    fn default() -> Self {
980        Self {
981            enabled: true,
982            pending: Vec::new(),
983            log: Vec::new(),
984            warned: FxHashSet::default(),
985            child_counts: FxHashMap::default(),
986            scratch: Vec::new(),
987        }
988    }
989}
990
991impl Diagnostics {
992    pub(crate) fn take(&mut self) -> Vec<Warning> {
993        std::mem::take(&mut self.pending)
994    }
995
996    /// Every warning raised so far, drained or not, oldest first.
997    pub(crate) fn raised(&self) -> &[Warning] {
998        &self.log
999    }
1000
1001    /// A warning built elsewhere — by a binding, for what it saw before the
1002    /// tree existed. Same gate and same once-per-(code, key) dedup as the
1003    /// checks below, so a frontend can raise one per node per frame and the
1004    /// host still reads one line.
1005    pub(crate) fn raise(&mut self, w: Warning) {
1006        if !self.enabled
1007            || self.pending.len() >= MAX_PENDING
1008            || !self.warned.insert((w.code, w.key))
1009        {
1010            return;
1011        }
1012        self.log.push(w.clone());
1013        self.pending.push(w);
1014    }
1015
1016    fn warn(&mut self, code: &'static str, key: Key, message: impl FnOnce() -> String) {
1017        if self.pending.len() >= MAX_PENDING || !self.warned.insert((code, key)) {
1018            return;
1019        }
1020        let w = Warning {
1021            code,
1022            key,
1023            message: message(),
1024        };
1025        self.log.push(w.clone());
1026        self.pending.push(w);
1027    }
1028
1029    /// Runs every check over the finished frame's tree, on the frames the
1030    /// cadence picks (see the module docs).
1031    pub(crate) fn check(
1032        &mut self,
1033        tree: &Tree,
1034        text: &TextSystem,
1035        edit: &EditStore,
1036        frame_no: u64,
1037    ) {
1038        if !self.enabled || tree.is_empty() {
1039            return;
1040        }
1041        if frame_no > 2 && !frame_no.is_multiple_of(CHECK_EVERY) {
1042            return;
1043        }
1044        self.check_grow_weights(tree);
1045        self.check_wrap(tree);
1046        self.check_align(tree);
1047        if tree.any_backdrop_blur {
1048            self.check_backdrop_blur(tree);
1049        }
1050        self.check_auto_keyed_transitions(tree);
1051        self.check_duplicate_keys(tree);
1052        self.check_modal(tree);
1053        self.check_selection_scopes(tree);
1054        self.check_composites(tree);
1055        self.check_lone_items(tree);
1056        self.check_access(tree, text, edit);
1057        self.check_live_regions(tree, text);
1058    }
1059
1060    /// A modal painted under content it makes inert. Paint order is
1061    /// preorder with floating subtrees last, so anything after the modal's
1062    /// subtree — or any float outside it — draws over it; a modal that is
1063    /// itself inside a float is already on top of both.
1064    /// A selection scope inside another one. Cheap to skip:
1065    /// the tree says whether any node declared one at all.
1066    fn check_selection_scopes(&mut self, tree: &Tree) {
1067        if !tree.any_selectable {
1068            return;
1069        }
1070        // Parents precede children, so one forward pass carries the
1071        // nearest enclosing scope down without a stack.
1072        self.scratch.clear();
1073        self.scratch.resize(tree.len(), 0);
1074        for i in 0..tree.len() {
1075            let inside = match tree.parent[i] {
1076                NIL => 0,
1077                p => self.scratch[p as usize],
1078            };
1079            let here = tree.specs[i].interact().selectable;
1080            if here && inside == 1 {
1081                self.warn(NESTED_SELECTION_SCOPE, tree.keys[i], || {
1082                    "a `selectable` node inside another one: selection scopes do not nest, so the inner one owns the text under it and the outer selects only what is outside it".to_string()
1083                });
1084            }
1085            self.scratch[i] = u64::from(here || inside == 1);
1086        }
1087    }
1088
1089    fn check_modal(&mut self, tree: &Tree) {
1090        let Some(i) = (0..tree.len())
1091            .rev()
1092            .find(|&i| tree.specs[i].events().modal.is_some())
1093        else {
1094            return;
1095        };
1096        let end = tree.subtree_end(i);
1097        // In a layer over the in-flow one: a float root, or under one.
1098        // Read through `Tree::opens_layer`, not the float bit — a `line`
1099        // in its parent's box floats for the room alone and paints in
1100        // the parent's layer (F123), so one in a bar declared before the
1101        // modal is under it, not content over it (RG120).
1102        let floating = |mut j: usize| {
1103            loop {
1104                if tree.opens_layer(j) {
1105                    return true;
1106                }
1107                match tree.parent[j] {
1108                    NIL => return false,
1109                    p => j = p as usize,
1110                }
1111            }
1112        };
1113        if floating(i) {
1114            return;
1115        }
1116        let over = (0..tree.len())
1117            .filter(|j| !(i..end).contains(j))
1118            .any(|j| j >= end || floating(j));
1119        if !over {
1120            return;
1121        }
1122        self.warn(MODAL_BEHIND_CONTENT, tree.keys[i], || {
1123            "this modal is not in a float, and content declared after it paints on top of it: \
1124             everything drawn over a modal is inert, which reads as a broken dialog (float it \
1125             with `float=\"viewport\"`)"
1126                .to_string()
1127        });
1128    }
1129
1130    /// Focusable nodes buried inside a composite's items, which nothing
1131    /// can reach (see [`FOCUSABLE_INSIDE_ITEM`]). One walk per composite,
1132    /// on the same cadence as every other check here.
1133    fn check_composites(&mut self, tree: &Tree) {
1134        let mut items: Vec<usize> = Vec::new();
1135        for c in 0..tree.len() {
1136            let Some(item) = tree.specs[c]
1137                .access()
1138                .role
1139                .and_then(crate::composite::item_role)
1140            else {
1141                continue;
1142            };
1143            crate::composite::items(tree, c, item, &mut items);
1144            if !crate::composite::is_composite(tree, c, &items) {
1145                continue;
1146            }
1147            for &i in &items {
1148                let end = tree.subtree_end(i);
1149                for j in i + 1..end {
1150                    if !access::focusable(tree, j) {
1151                        continue;
1152                    }
1153                    let what = item.name();
1154                    self.warn(FOCUSABLE_INSIDE_ITEM, tree.keys[j], || {
1155                        format!(
1156                            "this node is focusable but sits inside a `{what}`, which is one \
1157                             roving Tab stop of a composite: the ring stops at the item, so \
1158                             nothing reaches this node (move it outside the item, or drop its \
1159                             focusable behaviour)"
1160                        )
1161                    });
1162                }
1163            }
1164        }
1165    }
1166
1167    /// A `radio` or `tab` with no container of its pair above it (see
1168    /// [`ITEM_OUTSIDE_CONTAINER`]). The pairs are `composite::PAIRS`, less
1169    /// the menu's and the list's. Parents precede children, so one forward
1170    /// pass carries down a bit per pair for the containers above each node,
1171    /// as the selection-scope check carries its one.
1172    fn check_lone_items(&mut self, tree: &Tree) {
1173        use crate::composite::PAIRS;
1174        const CHECKED: [Role; 2] = [Role::Radio, Role::Tab];
1175        self.scratch.clear();
1176        self.scratch.resize(tree.len(), 0);
1177        for i in 0..tree.len() {
1178            let above = match tree.parent[i] {
1179                NIL => 0,
1180                p => self.scratch[p as usize],
1181            };
1182            let mut here = above;
1183            if let Some(role) = tree.specs[i].access().role {
1184                for (bit, (container, item)) in PAIRS.iter().enumerate() {
1185                    if role == *container {
1186                        here |= 1 << bit;
1187                    } else if role == *item && CHECKED.contains(item) && above & (1 << bit) == 0 {
1188                        let (item, container) = (item.name(), container.name());
1189                        self.warn(ITEM_OUTSIDE_CONTAINER, tree.keys[i], || {
1190                            format!(
1191                                "this `{item}` has no `{container}` above it, so it is a Tab \
1192                                 stop of its own: the arrows do not move the choice and a \
1193                                 screen reader announces no position in the set (wrap the \
1194                                 set in a `{container}` with a `label`)"
1195                            )
1196                        });
1197                    }
1198                }
1199            }
1200            self.scratch[i] = here;
1201        }
1202    }
1203
1204    /// Images without a label, controls without a computable name and
1205    /// modals without one, by the same derivation the access tree uses
1206    /// (see `access::semantic`).
1207    fn check_access(&mut self, tree: &Tree, text: &TextSystem, edit: &EditStore) {
1208        let mut skip_until = 0usize;
1209        for i in 0..tree.len() {
1210            if i < skip_until {
1211                continue;
1212            }
1213            let Some(sem) = access::semantic(tree, text, edit, None, i) else {
1214                continue;
1215            };
1216            if sem.role == Role::None || sem.presentational {
1217                skip_until = tree.subtree_end(i);
1218            }
1219            if sem.role == Role::Slider {
1220                self.check_slider_range(tree, i);
1221            }
1222            if sem.name.is_some() || sem.role == Role::None {
1223                continue;
1224            }
1225            let key = tree.keys[i];
1226            if sem.role == Role::Image {
1227                self.warn(IMAGE_WITHOUT_LABEL, key, || {
1228                    "this image has no label: assistive technology has nothing to say for it \
1229                     (give it a `label`, or `role=\"none\"` if it is decoration)"
1230                        .to_string()
1231                });
1232            } else if sem.role == Role::Dialog && tree.specs[i].events().modal.is_some() {
1233                self.warn(MODAL_WITHOUT_NAME, key, || {
1234                    "this modal has no accessible name: a dialog is named by its `label`, never \
1235                     by the text inside it — a screen reader announces an unnamed dialog to the \
1236                     user it has just moved focus to (give it a `label`)"
1237                        .to_string()
1238                });
1239            } else if sem.role.is_control() {
1240                let what = sem.role.name();
1241                self.warn(CONTROL_WITHOUT_NAME, key, || {
1242                    format!(
1243                        "this {what} has no accessible name: no `label`, and no text inside it \
1244                         — a screen reader announces an unnamed {what} (give it a `label`)"
1245                    )
1246                });
1247            }
1248        }
1249    }
1250
1251    /// A slider's declared value against its declared range (see
1252    /// [`SLIDER_VALUE_OUT_OF_RANGE`]). Only the rows it declares are
1253    /// compared: a slider with no `valueMin` has no floor to fall under.
1254    fn check_slider_range(&mut self, tree: &Tree, i: usize) {
1255        let ax = tree.specs[i].access();
1256        let (now, min, max) = (ax.value_now, ax.value_min, ax.value_max);
1257        let reason = match (now, min, max) {
1258            (_, Some(lo), Some(hi)) if lo > hi => {
1259                format!("valueMin {lo} is above valueMax {hi}, so no value is in range")
1260            }
1261            (Some(v), Some(lo), _) if v < lo => {
1262                format!("valueNow {v} is below valueMin {lo}")
1263            }
1264            (Some(v), _, Some(hi)) if v > hi => {
1265                format!("valueNow {v} is above valueMax {hi}")
1266            }
1267            _ => return,
1268        };
1269        self.warn(SLIDER_VALUE_OUT_OF_RANGE, tree.keys[i], || {
1270            format!(
1271                "this slider's value and its declared range disagree: {reason} — the rows are \
1272                 read to a screen reader exactly as declared, so a value the app clamps \
1273                 somewhere else is announced unclamped (declare the range the value is really \
1274                 held to, or clamp where the view declares it)"
1275            )
1276        });
1277    }
1278
1279    /// Live regions that can never say anything: `live` declared with no
1280    /// `label` and no text inside. Its own walk rather than a branch in
1281    /// [`Self::check_access`], because that one skips the subtree of a
1282    /// presentational role and a live region can sit inside one.
1283    fn check_live_regions(&mut self, tree: &Tree, text: &TextSystem) {
1284        for i in 0..tree.len() {
1285            let spec = &tree.specs[i];
1286            if spec.access().live == access::Live::Off
1287                || spec.access().role == Some(Role::None)
1288                || access::live_region_speaks(tree, text, i)
1289            {
1290                continue;
1291            }
1292            self.warn(LIVE_REGION_WITHOUT_NAME, tree.keys[i], || {
1293                "this node is a live region but has no accessible name: no `label`, and no text \
1294                 inside it — every platform reads a live region by its name, so nothing this \
1295                 node ever does can be announced (put `live` on the node that holds the message)"
1296                    .to_string()
1297            });
1298        }
1299    }
1300
1301    fn check_grow_weights(&mut self, tree: &Tree) {
1302        for p in 0..tree.len() {
1303            if tree.first_child[p] == NIL {
1304                continue;
1305            }
1306            let row = tree.specs[p].layout.dir == Dir::Row;
1307            let mut grow_children = 0u32;
1308            let mut lone: Option<(u32, f32)> = None;
1309            for c in tree.children(p as u32) {
1310                let layout = tree.specs[c as usize].layout;
1311                if layout.float.is_some() {
1312                    continue;
1313                }
1314                let (main, cross) = if row {
1315                    (layout.width, layout.height)
1316                } else {
1317                    (layout.height, layout.width)
1318                };
1319                if let Sizing::Grow(f) = main {
1320                    grow_children += 1;
1321                    lone = Some((c, f));
1322                }
1323                if let Sizing::Grow(f) = cross
1324                    && f != 1.0
1325                {
1326                    let axis = if row { "height" } else { "width" };
1327                    let parent_axis = if row { "row" } else { "column" };
1328                    self.warn(GROW_WEIGHT_IGNORED, tree.keys[c as usize], || {
1329                        format!(
1330                            "{axis} grow {f} has no effect: across a {parent_axis}'s main axis a \
1331                             grow child fills the parent whatever its weight (use maxWidth / \
1332                             maxHeight to cap it)"
1333                        )
1334                    });
1335                }
1336            }
1337            if grow_children == 1
1338                && let Some((c, f)) = lone
1339                && f != 1.0
1340            {
1341                let axis = if row { "width" } else { "height" };
1342                self.warn(GROW_WEIGHT_IGNORED, tree.keys[c as usize], || {
1343                    format!(
1344                        "{axis} grow {f} has no effect: it is the only grow child of its parent, \
1345                         and a weight only splits free space between grow siblings — alone it \
1346                         takes all of it (cap it with max{}, or give a sibling a grow too)",
1347                        if row { "Width" } else { "Height" }
1348                    )
1349                });
1350            }
1351        }
1352    }
1353
1354    /// Alignments and ratios with nothing to act on: see
1355    /// [`ALIGN_IGNORED`] and [`ASPECT_IGNORED`].
1356    fn check_align(&mut self, tree: &Tree) {
1357        use crate::spec::Align;
1358        let spread = |a: Align| {
1359            matches!(
1360                a,
1361                Align::SpaceBetween | Align::SpaceAround | Align::SpaceEvenly
1362            )
1363        };
1364        let odd = |a: Align| spread(a) || a == Align::Baseline;
1365        for i in 0..tree.len() {
1366            let l = &tree.specs[i].layout;
1367            let reason = if l.main_align == Align::Baseline {
1368                Some("mainAlign baseline: a baseline lines children up across a row, not along it (use crossAlign)".to_string())
1369            } else if spread(l.cross_align) {
1370                Some(format!(
1371                    "crossAlign {}: a spread deals free space out between children, and there is one child per line across the axis (use mainAlign)",
1372                    l.cross_align.name()
1373                ))
1374            } else if l.cross_align == Align::Baseline && l.dir == Dir::Column {
1375                Some("crossAlign baseline on a column: a column's cross axis is horizontal, where a baseline is not a line (lay the text out in a row)".to_string())
1376            } else {
1377                l.float.and_then(|f| {
1378                    let pts = [
1379                        f.anchor_point.0,
1380                        f.anchor_point.1,
1381                        f.self_point.0,
1382                        f.self_point.1,
1383                    ];
1384                    pts.into_iter().find(|&a| odd(a)).map(|a| {
1385                        format!(
1386                            "a float attaches at start, center or end, not {} (it lays out as {})",
1387                            a.name(),
1388                            if matches!(a, Align::SpaceAround | Align::SpaceEvenly) {
1389                                "center"
1390                            } else {
1391                                "start"
1392                            }
1393                        )
1394                    })
1395                })
1396            };
1397            if let Some(reason) = reason {
1398                self.warn(ALIGN_IGNORED, tree.keys[i], || {
1399                    format!("{reason}; it has no effect here")
1400                });
1401            }
1402            if l.aspect > 0.0 && !l.aspect_height() && l.aspect_width().is_none() {
1403                let why = if l.width == Sizing::Fit {
1404                    "the width is fit, and a grow or percent height is resolved only after every width is (give the height a fixed size, or let the height be the fit axis)"
1405                } else {
1406                    "both axes are declared, so there is no fit axis for the ratio to size (leave one of them fit)"
1407                };
1408                self.warn(ASPECT_IGNORED, tree.keys[i], || {
1409                    format!("aspectRatio {} has no effect: {why}", l.aspect)
1410                });
1411            }
1412        }
1413    }
1414
1415    /// A backdrop blur its own background hides: see
1416    /// [`BACKDROP_BLUR_HIDDEN`]. Asked only on a frame that has one.
1417    fn check_backdrop_blur(&mut self, tree: &Tree) {
1418        for i in 0..tree.len() {
1419            let spec = &tree.specs[i];
1420            let blur = spec.interact().backdrop_blur;
1421            if blur <= 0.0 || spec.style.bg.a < 1.0 || spec.style.opacity < 1.0 {
1422                continue;
1423            }
1424            self.warn(BACKDROP_BLUR_HIDDEN, tree.keys[i], || {
1425                format!(
1426                    "backdropBlur {blur} is hidden: the node's own bg is opaque and paints over \
1427                     the whole blur (give the bg some transparency, #ffffff40, for frosted glass)"
1428                )
1429            });
1430        }
1431    }
1432
1433    /// `wrapChildren` where nothing can break: see [`WRAP_IGNORED`].
1434    fn check_wrap(&mut self, tree: &Tree) {
1435        for i in 0..tree.len() {
1436            let layout = tree.specs[i].layout;
1437            if !layout.wrap {
1438                continue;
1439            }
1440            let reason = if layout.dir != Dir::Row {
1441                "a column's main size is not resolved until after the pass that would have to \
1442                 sum the lines, so only a row wraps (turn the container into a row, or give the \
1443                 items a fixed size and lay them out yourself)"
1444            } else if layout.scroll_x {
1445                "a scrollX row's main axis is unbounded, and an axis with no bound has nothing \
1446                 to break against (drop scrollX, or drop wrapChildren and let it scroll)"
1447            } else if layout.float.is_none()
1448                && tree.parent[i] != NIL
1449                && tree.specs[tree.parent[i] as usize].layout.is_table()
1450            {
1451                "a table's row cannot wrap: its children are the table's columns, one each \
1452                 (put the wrapping row inside a cell)"
1453            } else {
1454                continue;
1455            };
1456            self.warn(WRAP_IGNORED, tree.keys[i], || {
1457                format!("wrapChildren has no effect here: {reason}")
1458            });
1459        }
1460    }
1461
1462    fn check_auto_keyed_transitions(&mut self, tree: &Tree) {
1463        let mut counts: FxHashMap<Key, u32> = FxHashMap::default();
1464        for p in 0..tree.len() {
1465            if tree.first_child[p] == NIL {
1466                continue;
1467            }
1468            let parent_key = tree.keys[p];
1469            let mut n = 0u32;
1470            let mut auto_keyed_transition = false;
1471            for (i, c) in tree.children(p as u32).enumerate() {
1472                n += 1;
1473                // An auto key is the parent's key mixed with the sibling
1474                // index; a labeled key never collides with one.
1475                if tree.specs[c as usize].transition.is_some()
1476                    && tree.keys[c as usize] == parent_key.index(i as u64)
1477                {
1478                    auto_keyed_transition = true;
1479                }
1480            }
1481            if auto_keyed_transition {
1482                counts.insert(parent_key, n);
1483            }
1484        }
1485        for (&parent, &n) in &counts {
1486            if let Some(&prev) = self.child_counts.get(&parent)
1487                && prev != n
1488            {
1489                self.warn(TRANSITION_AUTO_KEY, parent, || {
1490                    format!(
1491                        "this node went from {prev} to {n} children while a child without a key \
1492                         carries a transition: an auto key is the child's position, so the \
1493                         children that shifted became new nodes and snapped instead of easing \
1494                         (and inserting before them will again) — give them a key"
1495                    )
1496                });
1497            }
1498        }
1499        self.child_counts = counts;
1500    }
1501
1502    fn check_duplicate_keys(&mut self, tree: &Tree) {
1503        let mut keys = std::mem::take(&mut self.scratch);
1504        keys.clear();
1505        keys.extend(tree.keys.iter().map(|k| k.0));
1506        keys.sort_unstable();
1507        for w in keys.windows(2) {
1508            if w[0] == w[1] {
1509                self.warn(DUPLICATE_KEY, Key(w[0]), || {
1510                    "two nodes share this key in one frame: state retained per key (transitions, \
1511                     scroll offsets, editors, layout events, hover) is mixed between them — \
1512                     siblings need distinct labels"
1513                        .to_string()
1514                });
1515            }
1516        }
1517        self.scratch = keys;
1518    }
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523    use super::*;
1524
1525    /// The drain hands a warning to the driver once; the log keeps it for
1526    /// anyone else, and a repeat of the same (code, key) is neither.
1527    #[test]
1528    fn the_log_outlives_the_drain() {
1529        let mut d = Diagnostics::default();
1530        let w = Warning {
1531            code: "test-code",
1532            key: Key::ROOT,
1533            message: "once".into(),
1534        };
1535        d.raise(w.clone());
1536        d.raise(w.clone());
1537        assert_eq!(d.take(), vec![w.clone()]);
1538        assert!(d.take().is_empty(), "drained");
1539        assert_eq!(d.raised(), &[w]);
1540    }
1541
1542    /// The `pub const NAME: &str = "code";` lines of this file, read back
1543    /// from the source: a code declared outside the `warnings!` block would
1544    /// compile and be missing from the table, and this is what notices.
1545    fn codes_in_source() -> Vec<&'static str> {
1546        include_str!("diag.rs")
1547            .lines()
1548            .filter_map(|line| {
1549                let rest = line.trim_start().strip_prefix("pub const ")?;
1550                let (_name, rest) = rest.split_once(": &str = \"")?;
1551                let (code, tail) = rest.split_once('"')?;
1552                (tail == ";").then_some(code)
1553            })
1554            .collect()
1555    }
1556
1557    #[test]
1558    fn every_code_is_in_the_table_and_vice_versa() {
1559        let in_source = codes_in_source();
1560        let in_table: Vec<&str> = WARNINGS.iter().map(|w| w.code).collect();
1561        assert!(
1562            in_source.len() >= 13,
1563            "the scan missed the consts: {in_source:?}"
1564        );
1565        assert_eq!(in_source, in_table);
1566        for (i, code) in in_table.iter().enumerate() {
1567            assert!(!in_table[i + 1..].contains(code), "duplicate code {code}");
1568            assert!(
1569                code.bytes().all(|b| b == b'-' || b.is_ascii_lowercase()),
1570                "{code}: codes are kebab-case"
1571            );
1572        }
1573    }
1574
1575    /// A menu row's dropped key takes the row's wording, whichever door
1576    /// raises it: `unknown_prop` under `MENU_ITEM` is `unknown_menu_item_key`.
1577    /// One hint for the key with a meaning of its own, the
1578    /// letters' nearest for the rest, none for anything fuzzier.
1579    #[test]
1580    fn a_menu_rows_unknown_key_is_named_as_one() {
1581        let name = crate::MenuItem::NAME;
1582        let w = unknown_prop(name, "disabled", schema::Spelling::Camel);
1583        assert_eq!(w, unknown_menu_item_key("disabled"));
1584        assert_eq!(w.code, UNKNOWN_PROP);
1585        assert_eq!(w.key, Key::ROOT.str(UNKNOWN_PROP).str(name).str("disabled"));
1586        assert!(
1587            w.message.contains("`disabled` is not a key of a menu item")
1588                && w.message
1589                    .contains("`label`, `role`, `enabled`, `checked`, `id`, `accel`")
1590                && w.message.ends_with("(did you mean `enabled: false`?)"),
1591            "{}",
1592            w.message
1593        );
1594        assert!(
1595            unknown_menu_item_key("Label")
1596                .message
1597                .ends_with("(did you mean `label`?)")
1598        );
1599        assert!(unknown_menu_item_key("lable").message.ends_with("dropped"));
1600        assert!(
1601            unknown_prop("box", "disabled", schema::Spelling::Camel)
1602                .message
1603                .starts_with("`disabled` is"),
1604            "an element's is the element's"
1605        );
1606    }
1607
1608    #[test]
1609    fn every_row_has_a_doc() {
1610        for w in WARNINGS {
1611            assert!(
1612                w.doc.split_whitespace().count() > 5,
1613                "{}: no description",
1614                w.code
1615            );
1616            assert!(
1617                !w.doc.contains("[`"),
1618                "{}: rustdoc link syntax leaks into the bindings' docs",
1619                w.code
1620            );
1621        }
1622    }
1623}