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