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