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