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.
822/// `items` is a row's key, so it arrives here only from a select's option
823/// ([`crate::MenuItem::stray_option_keys`]), and says so.
824pub fn unknown_menu_item_key(name: &str) -> Warning {
825    let key = Key::ROOT
826        .str(UNKNOWN_PROP)
827        .str(crate::MenuItem::NAME)
828        .str(name);
829    if name == "items" {
830        return Warning {
831            code: UNKNOWN_PROP,
832            key,
833            message: "`items` on a select's option is dropped: an option is chosen, never \
834                      opened, so it has no submenu"
835                .into(),
836        };
837    }
838    let keys = crate::MenuItem::KEYS
839        .iter()
840        .map(|k| format!("`{k}`"))
841        .collect::<Vec<_>>()
842        .join(", ");
843    // The one misspelling with a meaning of its own gets the value it was
844    // after; the rest the nearest key by letters, as `schema::suggest` does.
845    let squash = |s: &str| s.replace('_', "").to_ascii_lowercase();
846    let hint = if name == "disabled" {
847        " (did you mean `enabled: false`?)".to_string()
848    } else {
849        match crate::MenuItem::KEYS
850            .iter()
851            .find(|k| squash(k) == squash(name))
852        {
853            Some(near) => format!(" (did you mean `{near}`?)"),
854            None => String::new(),
855        }
856    };
857    Warning {
858        code: UNKNOWN_PROP,
859        key,
860        message: format!(
861            "`{name}` is not a key of a menu item: a row takes {keys}, so this declaration is \
862             dropped{hint}"
863        ),
864    }
865}
866
867/// The [`UNKNOWN_PROP`] warning for one dropped name, with the nearest
868/// legitimate spelling when there is an obvious one. The key is derived from
869/// the element and the name rather than from a node, so a misspelling costs
870/// one line however many nodes carry it and however many frames draw them.
871/// `element` [`crate::MenuItem::NAME`] is a menu row's key rather than a
872/// node's prop, and takes [`unknown_menu_item_key`]'s wording.
873pub fn unknown_prop(element: &str, name: &str, spelling: schema::Spelling) -> Warning {
874    if element == crate::MenuItem::NAME {
875        return unknown_menu_item_key(name);
876    }
877    // A real row on an element that reads only some of them is not a
878    // misspelling, and the nearest spelling would be the row itself; the
879    // warning says which rows the element does read instead.
880    let message = match schema::element_rows(element, spelling) {
881        Some(rows) if schema::shared_prop(name, spelling) => {
882            let takes = if rows.is_empty() {
883                "none of them".to_string()
884            } else {
885                format!(
886                    "only {}",
887                    rows.iter()
888                        .map(|r| format!("`{r}`"))
889                        .collect::<Vec<_>>()
890                        .join(", ")
891                )
892            };
893            format!(
894                "`{name}` is a prop, but not one {element} reads: its look is its own, and it \
895                 takes {takes}, so this declaration is dropped — a box with `role` set takes \
896                 every row"
897            )
898        }
899        _ => {
900            let hint = match schema::suggest(element, name, spelling) {
901                Some(near) => format!(" (did you mean `{near}`?)"),
902                None => String::new(),
903            };
904            format!(
905                "`{name}` is not a prop of {element}: no binding reads it, so this declaration \
906                 is dropped{hint}"
907            )
908        }
909    };
910    Warning {
911        code: UNKNOWN_PROP,
912        key: Key::ROOT.str(UNKNOWN_PROP).str(element).str(name),
913        message,
914    }
915}
916
917/// Pending warnings are capped so a host that never drains them cannot
918/// grow the queue without bound.
919const MAX_PENDING: usize = 256;
920/// The checks run on the first two frames and every this many after.
921pub(crate) const CHECK_EVERY: u64 = 16;
922
923pub(crate) struct Diagnostics {
924    pub(crate) enabled: bool,
925    pending: Vec<Warning>,
926    /// Everything that ever reached `pending`, kept after the drain: the
927    /// warnings of a core's whole life, for a reader that is not the
928    /// driver (a dev overlay showing what the runner printed). Bounded
929    /// the way `warned` is, since each (code, key) lands here once.
930    log: Vec<Warning>,
931    warned: FxHashSet<(&'static str, Key)>,
932    /// Child count at the last check, for parents with an auto-keyed child
933    /// that carries a transition.
934    child_counts: FxHashMap<Key, u32>,
935    scratch: Vec<u64>,
936}
937
938impl Default for Diagnostics {
939    fn default() -> Self {
940        Self {
941            enabled: true,
942            pending: Vec::new(),
943            log: Vec::new(),
944            warned: FxHashSet::default(),
945            child_counts: FxHashMap::default(),
946            scratch: Vec::new(),
947        }
948    }
949}
950
951impl Diagnostics {
952    pub(crate) fn take(&mut self) -> Vec<Warning> {
953        std::mem::take(&mut self.pending)
954    }
955
956    /// Every warning raised so far, drained or not, oldest first.
957    pub(crate) fn raised(&self) -> &[Warning] {
958        &self.log
959    }
960
961    /// A warning built elsewhere — by a binding, for what it saw before the
962    /// tree existed. Same gate and same once-per-(code, key) dedup as the
963    /// checks below, so a frontend can raise one per node per frame and the
964    /// host still reads one line.
965    pub(crate) fn raise(&mut self, w: Warning) {
966        if !self.enabled
967            || self.pending.len() >= MAX_PENDING
968            || !self.warned.insert((w.code, w.key))
969        {
970            return;
971        }
972        self.log.push(w.clone());
973        self.pending.push(w);
974    }
975
976    fn warn(&mut self, code: &'static str, key: Key, message: impl FnOnce() -> String) {
977        if self.pending.len() >= MAX_PENDING || !self.warned.insert((code, key)) {
978            return;
979        }
980        let w = Warning {
981            code,
982            key,
983            message: message(),
984        };
985        self.log.push(w.clone());
986        self.pending.push(w);
987    }
988
989    /// Runs every check over the finished frame's tree, on the frames the
990    /// cadence picks (see the module docs).
991    pub(crate) fn check(
992        &mut self,
993        tree: &Tree,
994        text: &TextSystem,
995        edit: &EditStore,
996        frame_no: u64,
997    ) {
998        if !self.enabled || tree.is_empty() {
999            return;
1000        }
1001        if frame_no > 2 && !frame_no.is_multiple_of(CHECK_EVERY) {
1002            return;
1003        }
1004        self.check_grow_weights(tree);
1005        self.check_wrap(tree);
1006        self.check_align(tree);
1007        if tree.any_backdrop_blur {
1008            self.check_backdrop_blur(tree);
1009        }
1010        self.check_auto_keyed_transitions(tree);
1011        self.check_duplicate_keys(tree);
1012        self.check_modal(tree);
1013        self.check_selection_scopes(tree);
1014        self.check_composites(tree);
1015        self.check_lone_items(tree);
1016        self.check_access(tree, text, edit);
1017        self.check_live_regions(tree, text);
1018    }
1019
1020    /// A modal painted under content it makes inert. Paint order is
1021    /// preorder with floating subtrees last, so anything after the modal's
1022    /// subtree — or any float outside it — draws over it; a modal that is
1023    /// itself inside a float is already on top of both.
1024    /// A selection scope inside another one. Cheap to skip:
1025    /// the tree says whether any node declared one at all.
1026    fn check_selection_scopes(&mut self, tree: &Tree) {
1027        if !tree.any_selectable {
1028            return;
1029        }
1030        // Parents precede children, so one forward pass carries the
1031        // nearest enclosing scope down without a stack.
1032        self.scratch.clear();
1033        self.scratch.resize(tree.len(), 0);
1034        for i in 0..tree.len() {
1035            let inside = match tree.parent[i] {
1036                NIL => 0,
1037                p => self.scratch[p as usize],
1038            };
1039            let here = tree.specs[i].interact().selectable;
1040            if here && inside == 1 {
1041                self.warn(NESTED_SELECTION_SCOPE, tree.keys[i], || {
1042                    "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()
1043                });
1044            }
1045            self.scratch[i] = u64::from(here || inside == 1);
1046        }
1047    }
1048
1049    fn check_modal(&mut self, tree: &Tree) {
1050        let Some(i) = (0..tree.len())
1051            .rev()
1052            .find(|&i| tree.specs[i].events().modal.is_some())
1053        else {
1054            return;
1055        };
1056        let end = tree.subtree_end(i);
1057        // In a layer over the in-flow one: a float root, or under one.
1058        // Read through `Tree::opens_layer`, not the float bit — a `line`
1059        // in its parent's box floats for the room alone and paints in
1060        // the parent's layer (F123), so one in a bar declared before the
1061        // modal is under it, not content over it (RG120).
1062        let floating = |mut j: usize| {
1063            loop {
1064                if tree.opens_layer(j) {
1065                    return true;
1066                }
1067                match tree.parent[j] {
1068                    NIL => return false,
1069                    p => j = p as usize,
1070                }
1071            }
1072        };
1073        if floating(i) {
1074            return;
1075        }
1076        let over = (0..tree.len())
1077            .filter(|j| !(i..end).contains(j))
1078            .any(|j| j >= end || floating(j));
1079        if !over {
1080            return;
1081        }
1082        self.warn(MODAL_BEHIND_CONTENT, tree.keys[i], || {
1083            "this modal is not in a float, and content declared after it paints on top of it: \
1084             everything drawn over a modal is inert, which reads as a broken dialog (float it \
1085             with `float=\"viewport\"`)"
1086                .to_string()
1087        });
1088    }
1089
1090    /// Focusable nodes buried inside a composite's items, which nothing
1091    /// can reach (see [`FOCUSABLE_INSIDE_ITEM`]). One walk per composite,
1092    /// on the same cadence as every other check here.
1093    fn check_composites(&mut self, tree: &Tree) {
1094        let mut items: Vec<usize> = Vec::new();
1095        for c in 0..tree.len() {
1096            let Some(item) = tree.specs[c]
1097                .access()
1098                .role
1099                .and_then(crate::composite::item_role)
1100            else {
1101                continue;
1102            };
1103            crate::composite::items(tree, c, item, &mut items);
1104            if !crate::composite::is_composite(tree, c, &items) {
1105                continue;
1106            }
1107            for &i in &items {
1108                let end = tree.subtree_end(i);
1109                for j in i + 1..end {
1110                    if !access::focusable(tree, j) {
1111                        continue;
1112                    }
1113                    let what = item.name();
1114                    self.warn(FOCUSABLE_INSIDE_ITEM, tree.keys[j], || {
1115                        format!(
1116                            "this node is focusable but sits inside a `{what}`, which is one \
1117                             roving Tab stop of a composite: the ring stops at the item, so \
1118                             nothing reaches this node (move it outside the item, or drop its \
1119                             focusable behaviour)"
1120                        )
1121                    });
1122                }
1123            }
1124        }
1125    }
1126
1127    /// A `radio` or `tab` with no container of its pair above it (see
1128    /// [`ITEM_OUTSIDE_CONTAINER`]). The pairs are `composite::PAIRS`, less
1129    /// the menu's and the list's. Parents precede children, so one forward
1130    /// pass carries down a bit per pair for the containers above each node,
1131    /// as the selection-scope check carries its one.
1132    fn check_lone_items(&mut self, tree: &Tree) {
1133        use crate::composite::PAIRS;
1134        const CHECKED: [Role; 2] = [Role::Radio, Role::Tab];
1135        self.scratch.clear();
1136        self.scratch.resize(tree.len(), 0);
1137        for i in 0..tree.len() {
1138            let above = match tree.parent[i] {
1139                NIL => 0,
1140                p => self.scratch[p as usize],
1141            };
1142            let mut here = above;
1143            if let Some(role) = tree.specs[i].access().role {
1144                for (bit, (container, item)) in PAIRS.iter().enumerate() {
1145                    if role == *container {
1146                        here |= 1 << bit;
1147                    } else if role == *item && CHECKED.contains(item) && above & (1 << bit) == 0 {
1148                        let (item, container) = (item.name(), container.name());
1149                        self.warn(ITEM_OUTSIDE_CONTAINER, tree.keys[i], || {
1150                            format!(
1151                                "this `{item}` has no `{container}` above it, so it is a Tab \
1152                                 stop of its own: the arrows do not move the choice and a \
1153                                 screen reader announces no position in the set (wrap the \
1154                                 set in a `{container}` with a `label`)"
1155                            )
1156                        });
1157                    }
1158                }
1159            }
1160            self.scratch[i] = here;
1161        }
1162    }
1163
1164    /// Images without a label, controls without a computable name and
1165    /// modals without one, by the same derivation the access tree uses
1166    /// (see `access::semantic`).
1167    fn check_access(&mut self, tree: &Tree, text: &TextSystem, edit: &EditStore) {
1168        let mut skip_until = 0usize;
1169        for i in 0..tree.len() {
1170            if i < skip_until {
1171                continue;
1172            }
1173            let Some(sem) = access::semantic(tree, text, edit, None, i) else {
1174                continue;
1175            };
1176            if sem.role == Role::None || sem.presentational {
1177                skip_until = tree.subtree_end(i);
1178            }
1179            if sem.role == Role::Slider {
1180                self.check_slider_range(tree, i);
1181            }
1182            if sem.name.is_some() || sem.role == Role::None {
1183                continue;
1184            }
1185            let key = tree.keys[i];
1186            if sem.role == Role::Image {
1187                self.warn(IMAGE_WITHOUT_LABEL, key, || {
1188                    "this image has no label: assistive technology has nothing to say for it \
1189                     (give it a `label`, or `role=\"none\"` if it is decoration)"
1190                        .to_string()
1191                });
1192            } else if sem.role == Role::Dialog && tree.specs[i].events().modal.is_some() {
1193                self.warn(MODAL_WITHOUT_NAME, key, || {
1194                    "this modal has no accessible name: a dialog is named by its `label`, never \
1195                     by the text inside it — a screen reader announces an unnamed dialog to the \
1196                     user it has just moved focus to (give it a `label`)"
1197                        .to_string()
1198                });
1199            } else if sem.role.is_control() {
1200                let what = sem.role.name();
1201                self.warn(CONTROL_WITHOUT_NAME, key, || {
1202                    format!(
1203                        "this {what} has no accessible name: no `label`, and no text inside it \
1204                         — a screen reader announces an unnamed {what} (give it a `label`)"
1205                    )
1206                });
1207            }
1208        }
1209    }
1210
1211    /// A slider's declared value against its declared range (see
1212    /// [`SLIDER_VALUE_OUT_OF_RANGE`]). Only the rows it declares are
1213    /// compared: a slider with no `valueMin` has no floor to fall under.
1214    fn check_slider_range(&mut self, tree: &Tree, i: usize) {
1215        let ax = tree.specs[i].access();
1216        let (now, min, max) = (ax.value_now, ax.value_min, ax.value_max);
1217        let reason = match (now, min, max) {
1218            (_, Some(lo), Some(hi)) if lo > hi => {
1219                format!("valueMin {lo} is above valueMax {hi}, so no value is in range")
1220            }
1221            (Some(v), Some(lo), _) if v < lo => {
1222                format!("valueNow {v} is below valueMin {lo}")
1223            }
1224            (Some(v), _, Some(hi)) if v > hi => {
1225                format!("valueNow {v} is above valueMax {hi}")
1226            }
1227            _ => return,
1228        };
1229        self.warn(SLIDER_VALUE_OUT_OF_RANGE, tree.keys[i], || {
1230            format!(
1231                "this slider's value and its declared range disagree: {reason} — the rows are \
1232                 read to a screen reader exactly as declared, so a value the app clamps \
1233                 somewhere else is announced unclamped (declare the range the value is really \
1234                 held to, or clamp where the view declares it)"
1235            )
1236        });
1237    }
1238
1239    /// Live regions that can never say anything: `live` declared with no
1240    /// `label` and no text inside. Its own walk rather than a branch in
1241    /// [`Self::check_access`], because that one skips the subtree of a
1242    /// presentational role and a live region can sit inside one.
1243    fn check_live_regions(&mut self, tree: &Tree, text: &TextSystem) {
1244        for i in 0..tree.len() {
1245            let spec = &tree.specs[i];
1246            if spec.access().live == access::Live::Off
1247                || spec.access().role == Some(Role::None)
1248                || access::live_region_speaks(tree, text, i)
1249            {
1250                continue;
1251            }
1252            self.warn(LIVE_REGION_WITHOUT_NAME, tree.keys[i], || {
1253                "this node is a live region but has no accessible name: no `label`, and no text \
1254                 inside it — every platform reads a live region by its name, so nothing this \
1255                 node ever does can be announced (put `live` on the node that holds the message)"
1256                    .to_string()
1257            });
1258        }
1259    }
1260
1261    fn check_grow_weights(&mut self, tree: &Tree) {
1262        for p in 0..tree.len() {
1263            if tree.first_child[p] == NIL {
1264                continue;
1265            }
1266            let row = tree.specs[p].layout.dir == Dir::Row;
1267            let mut grow_children = 0u32;
1268            let mut lone: Option<(u32, f32)> = None;
1269            for c in tree.children(p as u32) {
1270                let layout = tree.specs[c as usize].layout;
1271                if layout.float.is_some() {
1272                    continue;
1273                }
1274                let (main, cross) = if row {
1275                    (layout.width, layout.height)
1276                } else {
1277                    (layout.height, layout.width)
1278                };
1279                if let Sizing::Grow(f) = main {
1280                    grow_children += 1;
1281                    lone = Some((c, f));
1282                }
1283                if let Sizing::Grow(f) = cross
1284                    && f != 1.0
1285                {
1286                    let axis = if row { "height" } else { "width" };
1287                    let parent_axis = if row { "row" } else { "column" };
1288                    self.warn(GROW_WEIGHT_IGNORED, tree.keys[c as usize], || {
1289                        format!(
1290                            "{axis} grow {f} has no effect: across a {parent_axis}'s main axis a \
1291                             grow child fills the parent whatever its weight (use maxWidth / \
1292                             maxHeight to cap it)"
1293                        )
1294                    });
1295                }
1296            }
1297            if grow_children == 1
1298                && let Some((c, f)) = lone
1299                && f != 1.0
1300            {
1301                let axis = if row { "width" } else { "height" };
1302                self.warn(GROW_WEIGHT_IGNORED, tree.keys[c as usize], || {
1303                    format!(
1304                        "{axis} grow {f} has no effect: it is the only grow child of its parent, \
1305                         and a weight only splits free space between grow siblings — alone it \
1306                         takes all of it (cap it with max{}, or give a sibling a grow too)",
1307                        if row { "Width" } else { "Height" }
1308                    )
1309                });
1310            }
1311        }
1312    }
1313
1314    /// Alignments and ratios with nothing to act on: see
1315    /// [`ALIGN_IGNORED`] and [`ASPECT_IGNORED`].
1316    fn check_align(&mut self, tree: &Tree) {
1317        use crate::spec::Align;
1318        let spread = |a: Align| {
1319            matches!(
1320                a,
1321                Align::SpaceBetween | Align::SpaceAround | Align::SpaceEvenly
1322            )
1323        };
1324        let odd = |a: Align| spread(a) || a == Align::Baseline;
1325        for i in 0..tree.len() {
1326            let l = &tree.specs[i].layout;
1327            let reason = if l.main_align == Align::Baseline {
1328                Some("mainAlign baseline: a baseline lines children up across a row, not along it (use crossAlign)".to_string())
1329            } else if spread(l.cross_align) {
1330                Some(format!(
1331                    "crossAlign {}: a spread deals free space out between children, and there is one child per line across the axis (use mainAlign)",
1332                    l.cross_align.name()
1333                ))
1334            } else if l.cross_align == Align::Baseline && l.dir == Dir::Column {
1335                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())
1336            } else {
1337                l.float.and_then(|f| {
1338                    let pts = [
1339                        f.anchor_point.0,
1340                        f.anchor_point.1,
1341                        f.self_point.0,
1342                        f.self_point.1,
1343                    ];
1344                    pts.into_iter().find(|&a| odd(a)).map(|a| {
1345                        format!(
1346                            "a float attaches at start, center or end, not {} (it lays out as {})",
1347                            a.name(),
1348                            if matches!(a, Align::SpaceAround | Align::SpaceEvenly) {
1349                                "center"
1350                            } else {
1351                                "start"
1352                            }
1353                        )
1354                    })
1355                })
1356            };
1357            if let Some(reason) = reason {
1358                self.warn(ALIGN_IGNORED, tree.keys[i], || {
1359                    format!("{reason}; it has no effect here")
1360                });
1361            }
1362            if l.aspect > 0.0 && !l.aspect_height() && l.aspect_width().is_none() {
1363                let why = if l.width == Sizing::Fit {
1364                    "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)"
1365                } else {
1366                    "both axes are declared, so there is no fit axis for the ratio to size (leave one of them fit)"
1367                };
1368                self.warn(ASPECT_IGNORED, tree.keys[i], || {
1369                    format!("aspectRatio {} has no effect: {why}", l.aspect)
1370                });
1371            }
1372        }
1373    }
1374
1375    /// A backdrop blur its own background hides: see
1376    /// [`BACKDROP_BLUR_HIDDEN`]. Asked only on a frame that has one.
1377    fn check_backdrop_blur(&mut self, tree: &Tree) {
1378        for i in 0..tree.len() {
1379            let spec = &tree.specs[i];
1380            let blur = spec.interact().backdrop_blur;
1381            if blur <= 0.0 || spec.style.bg.a < 1.0 || spec.style.opacity < 1.0 {
1382                continue;
1383            }
1384            self.warn(BACKDROP_BLUR_HIDDEN, tree.keys[i], || {
1385                format!(
1386                    "backdropBlur {blur} is hidden: the node's own bg is opaque and paints over \
1387                     the whole blur (give the bg some transparency, #ffffff40, for frosted glass)"
1388                )
1389            });
1390        }
1391    }
1392
1393    /// `wrapChildren` where nothing can break: see [`WRAP_IGNORED`].
1394    fn check_wrap(&mut self, tree: &Tree) {
1395        for i in 0..tree.len() {
1396            let layout = tree.specs[i].layout;
1397            if !layout.wrap {
1398                continue;
1399            }
1400            let reason = if layout.dir != Dir::Row {
1401                "a column's main size is not resolved until after the pass that would have to \
1402                 sum the lines, so only a row wraps (turn the container into a row, or give the \
1403                 items a fixed size and lay them out yourself)"
1404            } else if layout.scroll_x {
1405                "a scrollX row's main axis is unbounded, and an axis with no bound has nothing \
1406                 to break against (drop scrollX, or drop wrapChildren and let it scroll)"
1407            } else if layout.float.is_none()
1408                && tree.parent[i] != NIL
1409                && tree.specs[tree.parent[i] as usize].layout.is_table()
1410            {
1411                "a table's row cannot wrap: its children are the table's columns, one each \
1412                 (put the wrapping row inside a cell)"
1413            } else {
1414                continue;
1415            };
1416            self.warn(WRAP_IGNORED, tree.keys[i], || {
1417                format!("wrapChildren has no effect here: {reason}")
1418            });
1419        }
1420    }
1421
1422    fn check_auto_keyed_transitions(&mut self, tree: &Tree) {
1423        let mut counts: FxHashMap<Key, u32> = FxHashMap::default();
1424        for p in 0..tree.len() {
1425            if tree.first_child[p] == NIL {
1426                continue;
1427            }
1428            let parent_key = tree.keys[p];
1429            let mut n = 0u32;
1430            let mut auto_keyed_transition = false;
1431            for (i, c) in tree.children(p as u32).enumerate() {
1432                n += 1;
1433                // An auto key is the parent's key mixed with the sibling
1434                // index; a labeled key never collides with one.
1435                if tree.specs[c as usize].transition.is_some()
1436                    && tree.keys[c as usize] == parent_key.index(i as u64)
1437                {
1438                    auto_keyed_transition = true;
1439                }
1440            }
1441            if auto_keyed_transition {
1442                counts.insert(parent_key, n);
1443            }
1444        }
1445        for (&parent, &n) in &counts {
1446            if let Some(&prev) = self.child_counts.get(&parent)
1447                && prev != n
1448            {
1449                self.warn(TRANSITION_AUTO_KEY, parent, || {
1450                    format!(
1451                        "this node went from {prev} to {n} children while a child without a key \
1452                         carries a transition: an auto key is the child's position, so the \
1453                         children that shifted became new nodes and snapped instead of easing \
1454                         (and inserting before them will again) — give them a key"
1455                    )
1456                });
1457            }
1458        }
1459        self.child_counts = counts;
1460    }
1461
1462    fn check_duplicate_keys(&mut self, tree: &Tree) {
1463        let mut keys = std::mem::take(&mut self.scratch);
1464        keys.clear();
1465        keys.extend(tree.keys.iter().map(|k| k.0));
1466        keys.sort_unstable();
1467        for w in keys.windows(2) {
1468            if w[0] == w[1] {
1469                self.warn(DUPLICATE_KEY, Key(w[0]), || {
1470                    "two nodes share this key in one frame: state retained per key (transitions, \
1471                     scroll offsets, editors, layout events, hover) is mixed between them — \
1472                     siblings need distinct labels"
1473                        .to_string()
1474                });
1475            }
1476        }
1477        self.scratch = keys;
1478    }
1479}
1480
1481#[cfg(test)]
1482mod tests {
1483    use super::*;
1484
1485    /// The drain hands a warning to the driver once; the log keeps it for
1486    /// anyone else, and a repeat of the same (code, key) is neither.
1487    #[test]
1488    fn the_log_outlives_the_drain() {
1489        let mut d = Diagnostics::default();
1490        let w = Warning {
1491            code: "test-code",
1492            key: Key::ROOT,
1493            message: "once".into(),
1494        };
1495        d.raise(w.clone());
1496        d.raise(w.clone());
1497        assert_eq!(d.take(), vec![w.clone()]);
1498        assert!(d.take().is_empty(), "drained");
1499        assert_eq!(d.raised(), &[w]);
1500    }
1501
1502    /// The `pub const NAME: &str = "code";` lines of this file, read back
1503    /// from the source: a code declared outside the `warnings!` block would
1504    /// compile and be missing from the table, and this is what notices.
1505    fn codes_in_source() -> Vec<&'static str> {
1506        include_str!("diag.rs")
1507            .lines()
1508            .filter_map(|line| {
1509                let rest = line.trim_start().strip_prefix("pub const ")?;
1510                let (_name, rest) = rest.split_once(": &str = \"")?;
1511                let (code, tail) = rest.split_once('"')?;
1512                (tail == ";").then_some(code)
1513            })
1514            .collect()
1515    }
1516
1517    #[test]
1518    fn every_code_is_in_the_table_and_vice_versa() {
1519        let in_source = codes_in_source();
1520        let in_table: Vec<&str> = WARNINGS.iter().map(|w| w.code).collect();
1521        assert!(
1522            in_source.len() >= 13,
1523            "the scan missed the consts: {in_source:?}"
1524        );
1525        assert_eq!(in_source, in_table);
1526        for (i, code) in in_table.iter().enumerate() {
1527            assert!(!in_table[i + 1..].contains(code), "duplicate code {code}");
1528            assert!(
1529                code.bytes().all(|b| b == b'-' || b.is_ascii_lowercase()),
1530                "{code}: codes are kebab-case"
1531            );
1532        }
1533    }
1534
1535    /// A menu row's dropped key takes the row's wording, whichever door
1536    /// raises it: `unknown_prop` under `MENU_ITEM` is `unknown_menu_item_key`.
1537    /// One hint for the key with a meaning of its own, the
1538    /// letters' nearest for the rest, none for anything fuzzier.
1539    #[test]
1540    fn a_menu_rows_unknown_key_is_named_as_one() {
1541        let name = crate::MenuItem::NAME;
1542        let w = unknown_prop(name, "disabled", schema::Spelling::Camel);
1543        assert_eq!(w, unknown_menu_item_key("disabled"));
1544        assert_eq!(w.code, UNKNOWN_PROP);
1545        assert_eq!(w.key, Key::ROOT.str(UNKNOWN_PROP).str(name).str("disabled"));
1546        assert!(
1547            w.message.contains("`disabled` is not a key of a menu item")
1548                && w.message
1549                    .contains("`label`, `role`, `enabled`, `checked`, `id`, `accel`")
1550                && w.message.ends_with("(did you mean `enabled: false`?)"),
1551            "{}",
1552            w.message
1553        );
1554        assert!(
1555            unknown_menu_item_key("Label")
1556                .message
1557                .ends_with("(did you mean `label`?)")
1558        );
1559        assert!(unknown_menu_item_key("lable").message.ends_with("dropped"));
1560        assert!(
1561            unknown_prop("box", "disabled", schema::Spelling::Camel)
1562                .message
1563                .starts_with("`disabled` is"),
1564            "an element's is the element's"
1565        );
1566    }
1567
1568    #[test]
1569    fn every_row_has_a_doc() {
1570        for w in WARNINGS {
1571            assert!(
1572                w.doc.split_whitespace().count() > 5,
1573                "{}: no description",
1574                w.code
1575            );
1576            assert!(
1577                !w.doc.contains("[`"),
1578                "{}: rustdoc link syntax leaks into the bindings' docs",
1579                w.code
1580            );
1581        }
1582    }
1583}