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