Skip to content
water-rsPublic

About

WaterUI-specific lints: a dylint library that catches the silent reactivity, localization, layout and accessibility mistakes rustc cannot

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

lints

WaterUI-specific lints, packaged as a dylint library.

WaterUI views are plain Rust, so rustc and clippy already catch the mechanical mistakes. What they cannot see is the class of bug that compiles clean and behaves wrong: a .get() that freezes a signal into a snapshot, a watch that rebuilds a subtree the author meant to update, a format! that walks around the translation catalog, an .opacity(0.0) that hides a button from sight but not from the screen reader. These lints run inside the compiler on the expanded, type-resolved HIR, which is the only place those facts are known.

The lint catalog and its status live in this repository's issues. Each lint has a UI test under ui/ and is documented in the crate's README table once it lands.

Using

cargo install cargo-dylint dylint-link

Then, in the project's Cargo.toml — releases are not tagged yet, so pin a revision:

[workspace.metadata.dylint]
libraries = [{ git = "https://github.com/water-rs/lints", rev = "4c24f503a93c0f085b2aa93789bbb4392830b52c" }]

and cargo dylint --all. The water CLI will front this as water lint (water-rs/waterui#735).

Lints

Lint Group Description Autofix
binding_parameter_by_value waterui_style (warn) Flags a function/method parameter typed Binding<T> by value — any non-private signature, or a private one whose callers already pass f(b.clone()) — Binding is a cheap handle, so the signature is &Binding<T>; rewrites the parameter, turns f(b.clone()) call sites into f(&b), and adds .clone() where the body moves the parameter (a move closure capture, a field initialiser, a return); trait impl methods, extern/no_mangle/export_name functions stay silent Yes
blocking_in_ui_context waterui_suspicious (warn) Flags calls that block the UI thread's executor — std::fs::*, std::net::*, std::process::Command::{output,status}/Child::wait, futures/smol/async_io block_on, reqwest::blocking::*, Mutex::lock, RwLock::{read,write} — inside a Handler closure, an async block/async fn body, View::body, or GpuView::render; the path list is extendable via dylint.toml's blocking_in_ui_context_paths; move the work to waterui::task::spawn and await it No
clone_refcell_field waterui_suspicious (warn) Flags a bare RefCell<_>/Cell<_>/OnceCell<_> field on a #[derive(Clone)] struct when a sibling already shares state through Rc<RefCell<_>>/Rc<Cell<_>> — derived Clone copies the bare cell, so each clone forks the state the sibling shares; share it as Rc<cell>; hand-written Clone impls stay silent No
collection_item_snapshot waterui_suspicious (warn) Flags a non-signal field of a for_each item read into an IntoSignal/IntoComputed/IntoSignalF32 parameter — for_each diffs by id, so the snapshot never re-renders; derive a Computed or keep a Binding on the item No
computed_parameter waterui_style (warn) Flags a function/method parameter typed Computed<T> or &Computed<T> — any non-private signature, or a private one whose callers erase a signal at more than one call site — impl IntoComputed<T> takes any signal or a plain T; rewrites the parameter and inserts let x = x.into_computed();, importing IntoComputed when needed; trait impl methods, extern/no_mangle/export_name functions stay silent Yes
default_binding_constructor waterui_style (warn) Flags binding(..)/Binding::container(..) seeded with T's default — T::default(), the std new that is the Default (String::new(), Vec::new(), vec![], HashMap::new(), …), or None — Binding<T> is already Default; rewrites to Binding::<T>::default() (bare Binding::default() when no source spells T), spelling T from the argument path, call turbofish, or a : Binding<T> annotation it then drops Yes
discarded_wait_result waterui_correctness (deny) Flags a Query::wait_for_*/SemanticApp::wait_for_* bool result that is dropped — let _ =, a bare statement, or a binding never read — so the wait can never fail the test; suggests assert!(..) for the unbound shapes Yes
empty_label_literal waterui_a11y (allow) Flags an empty/whitespace-only string literal in an IntoLabel parameter (button(""), toggle, slider, field, …) or .a11y_label("") — the mandatory label is how screen readers and waterui-testing find the control; name it, or hide it with .hide_label()/LabelDisplayMode::IconOnly No
fixed_children_in_vec waterui_pedantic (allow) Flags a literal vec![..] passed as stack contents (vstack(vec![..]), VStack::new(.., vec![..]), …) — a tuple is the framework's shape for a fixed set of children; suggests (a, b, c) Yes
format_in_text waterui_suspicious (warn) Flags a format!(..) with letters in its template reaching an IntoText/IntoLabel parameter (through .to_string()/String::from/Str::from/.into()/Text::verbatim) — the result is untranslatable Text::verbatim; suggests the text! rewrite when every slot is a simple path Yes
handler_captures_binding waterui_style (warn) Flags a closure in a Handler/HandlerOnce position (action, on_tap, gesture, …) that captures a Binding, Computed, or ReactiveList — including the clone-then-move block { let b = b.clone(); move || … }, whose let lines are labelled for deletion — inject it with .state(&b) and take State<Binding<T>> so the handler can be a named function No
hardcoded_theme_value waterui_pedantic (allow) Flags all-literal Color::srgb*/p3/oklch/Srgb::* constructors and Text/Font/StyledStr::size calls inside -> impl View functions and View::body — literals do not adapt to the color scheme or type scale; use theme tokens (AccentColor, …) and semantic fonts (.font(Title), …) or a named constant No
if_else_view waterui_style (warn) Flags if/else that produce views — when(cond, || ..).otherwise(|| ..) needs no AnyView erasure and stays reactive; conditions that .get() a signal are flagged as one-shot snapshots Yes
image_without_label waterui_a11y (allow) Flags a Photo/Image/Svg whose modifier chain carries no .a11y_label(..) and no .a11y_hidden(true) — images have no label parameter, so they enter the accessibility tree unannounced; name the image or mark it decorative, #[allow] covers labels set by an ancestor No
list_in_scroll waterui_suspicious (warn) Flags scroll(..)/scroll_horizontal(..) and ScrollView::vertical(..)/horizontal(..) whose content is a List/ListBuilder, bare or under Metadata modifiers — the list is laid out with unbounded height, realises every row, and fights the scroll view for the gesture; drop the wrapper or use Lazy::for_each No
literal_color_components waterui_style (warn) Flags Srgb::new/new_u8/from_u32 and Color::srgb/srgb_f32/srgb_u32 calls whose components are all numeric literals — a color nobody can read back; rewrites to Srgb::from_hex("#RRGGBB")/Color::srgb_hex(..) (exact for u8 components and on-grid floats, MaybeIncorrect otherwise), defers to manual_color_erasure at Into<Color>/IntoBackground parameters, and suggests a const when the color repeats; variable or expression components stay silent Yes
localized_concat waterui_pedantic (allow) Flags + on Text whose left operand is localized — a text! expansion, a Text::localized* call, or a text(..)/Text::new(..)/.into_text()/.into() of a &'static str — since concatenated fragments cannot be translated as a unit; make it one text! key with slots No
long_text_key waterui_pedantic (allow) Flags a text!("..") literal or Text::localized/localized_or key over long_text_key_words words (dylint.toml, default 12) — the whole literal is the lookup key, so a copy edit orphans every translation; use a short "$about_blurb"-style key and put the prose in i18n/<locale>.toml No
manual_binding_mutation waterui_style (warn) Flags a Binding mutation or conversion written by hand where Binding has the named method — with_mut(|v| *v op= x)/*b.get_mut() op= x→<op>_assign/append, v.push(x)/push_str/extend(once(x))-in-with_mut→append, *v = !*v→toggle, *v = x/*b.get_mut() = x→set, b.set(x.into())/from/from_static/to_string/to_owned→set_from Yes
manual_color_erasure waterui_style (warn) Flags Color::srgb_f32/srgb/srgb_hex/srgb_u32/p3 constructors and e.into()/Into::into(e)/Color::from(e)/Color::new(e) wrappers on colorspace values at Into<Color>/IntoBackground parameters (incl. a let-bound constructor later passed to one) — the parameter converts for you; pass the Srgb/P3 value Yes
manual_computed waterui_style (warn) Flags the hand-written Computed erasure — Computed::new(e), Computed::from(e)/From::from(e), e.into()/Into::into(e) typed Computed<T>, e.into_computed() — where e is a signal with Output = T; rewrites to e.computed() (s.computed() when e is s.clone() over a place s) Yes
manual_edge_insets waterui_style (warn) Flags EdgeInsets::all/symmetric/new with literal-or-path operands at an impl Into<EdgeInsets>/impl IntoComputed<EdgeInsets> parameter — the parameter converts for you; rewrites all(x)→x, symmetric(v, h)→(v, h) (a zero axis in .padding_with→padding_horizontal/padding_vertical), new(t, b, l, r)→[t, b, l, r] Yes
manual_identifiable waterui_style (warn) Flags impl Identifiable whose id returns a field verbatim and use_id/self_id wrappers on local structs — #[derive(Identifiable)] plus #[id] on the field covers both Yes
manual_list_mutation waterui_style (warn) Flags a List snapshot–mutate–replace round trip where List has the method — let mut v = list.snapshot(); v.push(x); list.replace(v) (and the argument-block spelling)→list.push(x), likewise pop/insert/remove/clear/sort, and replace(Vec::new())/vec![]/Default::default()→list.clear() Yes
manual_muted_foreground waterui_style (warn) Flags .foreground(MutedForeground) under any spelling — MutedForeground, theme_color::MutedForeground, waterui::theme::color::MutedForeground — ViewExt::muted() is that exact call; rewrites to .muted(), any other argument (Foreground included) stays silent Yes
manual_signal_combinator waterui_style (warn) Flags signal.map(|v| ..) whose closure restates a named SignalExt combinator — !v→.not(), v ==/!=/>/</… e→.equal_to(e)/.equal_to(e).not()/.gt/.lt/…, v == 0→.is_zero(), v >/< 0→.is_positive()/.is_negative(), -v/v.abs()→.negate()/.abs(), Option/Result predicates and unwrap_or/unwrap_or_else/map/and_then/map_err→.unwrap_or*/.map_some/.and_then_some/.map_ok/.map_err, v == Some(e)→.some_equal_to(e), v.flatten()/ok()/err(), v.is_empty()/len()/contains(e)→.str_*, if v {a} else {b}/v.then_some(a)→.select(a, b)/.then_some(a), v.into()/From::from(v)→.map_into(), v/v.clone()→s.clone() — the combinator keeps the canonical fn-item signal identity Yes
manual_signal_zip_op waterui_style (warn) Flags a.zip(&b).map(|(x, y)| x op y) that restates a named signal operation — x && y→a.and(&b), x || y→a.or(&b), x +/-/*/… y→a op b (place operands spelled .clone()), the t.0/t.1 spelling included; swapped or non-pair bodies and Iterator/Option zip stay silent Yes
manual_string_signal waterui_style (warn) Flags .map(|v| ..) — closure or named fn — that builds a String/Str signal by hand (format!, +/push_str concatenation, from/to_string of a converted value) outside text positions — s! formats the signals directly; plain v.to_string()/Str::from(v) conversions and literal-only branches stay silent No
manual_text_map waterui_style (warn) Flags .map(|v| format!(..))/.to_string() over signals whose result only feeds a text position — text! formats the signal itself and keeps the template translatable Yes
missing_translation waterui_pedantic (allow) Flags a text!("..")/Text::localized/localized_or key absent from one or more i18n/<locale>.toml catalogs — that locale silently renders the key itself No
needless_anyview waterui_style (warn) Flags AnyView::new/.anyview() erasure where impl View is already accepted — AnyView is only needed for AnyView fields, -> AnyView signatures, Vec<AnyView>, and mixed-type branches Yes
needless_computed waterui_style (warn) Flags .computed()/.into_computed()/Computed::new(..) whose result only reaches parameters that accept any signal (IntoComputed/IntoSignal/Signal/IntoSignalF32) — directly or through a local whose every use is one; the un-erased signal serves the same consumers Yes
needless_list_snapshot waterui_style (warn) Flags list.snapshot() consumed by .len()/.is_empty()/.get(i).cloned()/.first().cloned()/.into_iter()/a for head — the reads copy the vector for what List answers directly; the iteration forms are spelled list.iter() Yes
needless_signal_cast waterui_style (warn) Flags signal.map(..) whose argument is a pure numeric conversion to f32 — |v| v as f32, f32::from, |v| v.into()→f32, IntoF32::into_f32, |v| v.to_f32().unwrap() — when the produced signal only reaches impl IntoSignalF32 parameters (directly, through .with(..)/.cached()/.computed(), or via a let whose every use is one) — the parameter performs the conversion itself Yes
needless_signal_clone waterui_style (warn) Flags x.clone().<method>(..) where <method> is a SignalExt combinator or an inherent Binding/Computed/List method taking &self — the method clones the cheap handle internally Yes
needless_state_wrapper waterui_style (warn) Flags a State<T> closure parameter (action, use_env, …) whose T already implements Extractor or is a local Clone struct/enum — the bare T extracts directly; rewrites State(name)/s parameters and s.0 uses, marking local types #[state] and importing waterui::state when needed Yes
non_reactive_ui_state waterui_suspicious (warn) Flags a handler closure (action, on_tap, gesture, …) mutating a captured RefCell/Cell/Mutex/RwLock/atomic or touching static mut/thread_local!, and such fields on View types — the mutation never notifies the reactive graph; keep UI state in a Binding<T> No
on_change_derives_binding waterui_pedantic (allow) Flags .on_change(&a, |v| b.set(f(v))) — the copy lags the source by one update and is a second source of truth; derive it once with a.map(f) and read the Computed No
on_tap_on_control waterui_suspicious (warn) Flags .on_tap/.on_tap_gesture*/.on_tap_haptic*/.gesture(TapGesture, ..) on a control with its own activation (Button, Toggle, Slider, Stepper, TextField, ListItem, Picker, NavigationLink, Menu) — the gesture and the control's action compete for the same tap; use .action(..) No
opacity_as_visibility waterui_suspicious (warn) Flags .opacity(0.0), sig.select(1.0, 0.0), and sig.map(|b| if b { 1.0 } else { 0.0 }) used to hide a view — .visible(..) also marks it accessibility-hidden and non-hittable Yes
orphan_translation waterui_pedantic (allow) Flags an i18n/<locale>.toml key no text! or Text::localized literal in the crate uses — dead catalog entries keep the file misleading about what the app shows No
plural_bypass waterui_suspicious (warn) Flags the format_in_text case that also splices an integer into prose — the number skips CLDR plural categories; {#count} in a text! key is the only channel that yields correct plural forms per locale No
positional_state_ambiguity waterui_suspicious (warn) Flags a handler (action, on_tap, gesture, …) with two State<T> parameters of the same T — they bind to .state(..) calls by position, not name, so the handler can silently take the wrong binding; put both values in one Clone struct injected once No
push_loop_seed waterui_pedantic (allow) Flags ReactiveList::new() followed in the same block by a for loop whose body is a single list.push(..) over a local sequence — ReactiveList::from(vec) seeds in one move No
qualified_alignment waterui_style (warn) Flags .alignment(X::CONST) on VStack/HStack/ZStack/Frame/Grid/Overlay and X::CONST arguments at other Into<Alignment>/Into<HorizontalAlignment>/Into<VerticalAlignment> parameters — rewrites to the container's position method (.leading(), .top_leading(), …) or the bare token (Leading), importing the token when needed Yes
qualified_waterui_path waterui_style (warn) Flags waterui::…/nami::… paths (incl. text!/debug! macros) written qualified instead of imported — suggests use plus qualifier strip, or an as alias on a name collision Yes
redundant_anyview waterui_style (warn) Flags AnyView::new/.anyview()/ViewExt::anyview on a value that is already AnyView — the second wrapper is dead code Yes
s_macro_in_text waterui_suspicious (warn) Flags an s!(..) flowing into an IntoText/IntoLabel parameter — text(..), Text::new(..), button(..) — directly or through a let: the signal's String renders as untranslatable verbatim text; rewrites to text!(..) with named slots Yes
set_with_own_get waterui_style (warn) Flags b.set(expr(b.get())) — a set whose argument reads the same binding back through .get(); suggests the named in-place method (b.add_assign(x) and the other <op>_assigns, b.append(x), b.toggle()), falling back to *b.get_mut() op= x and b.with_mut(|v| ..) Yes
signal_get_in_view waterui_correctness (deny) Flags .get() snapshots passed to reactive/view parameters (IntoSignal, IntoComputed, IntoText, IntoLabel, View, ViewBuilder) — the view freezes at the first read Yes
spacer_in_zstack waterui_suspicious (warn) Flags a Spacer element in the contents tuple of zstack((..))/ZStack::new(.., (..)) — a spacer expands along the stack axis and a Z stack has none, so the child is inert; position with .alignment(..) on the zstack or use absolute((..)) for an edge-anchored overlay No
spawn_local_in_app waterui_correctness (deny) Flags waterui::task::spawn_local — or spawn of a !Send future — in the body of fn app(Environment) -> App or in a function it calls directly — runners install the local executor at mount, so the call panics "Local executor not set"; move startup async work into .task(..), .on_appear, or a handler body No
state_created_in_rebuilt_scope waterui_suspicious (warn) Flags binding(..)/Binding::…/ReactiveList::… constructors inside watch/when/.or/.otherwise closures — the scope rebuilds on every change and the state resets; own it one level up and move it in No
state_created_in_row_builder waterui_pedantic (allow) Flags the same state constructors inside ForEach::new/Lazy::for_each/List::for_each/stack for_each row builders — row-local state is sometimes intended, so the lint is opt-in No
tappable_without_role waterui_a11y (allow) Flags .on_tap/.on_tap_gesture*/.on_tap_haptic*/.gesture(TapGesture, ..) on a non-control view whose chain has no .a11y_role or .a11y_label — the tap target is invisible to assistive tech and waterui-testing queries; add a role + label or use button(..) No
task_handle_dropped waterui_correctness (deny) Flags a task::spawn/spawn_local handle dropped at once — a bare spawn(..); statement, let _ = spawn(..);, or a let t = spawn(..); never read in its block — the handle cancels the task on drop; suggests .detach() for the unbound shapes Yes
thread_sleep_in_ui waterui_correctness (deny) Flags std::thread::sleep inside a Handler closure, async scope, View::body, or GpuView::render — it parks the executor thread outright; await waterui::task::sleep(..) in an .action_async/.task(..) future No
thread_sleep_in_test waterui_correctness (deny) Flags std::thread::sleep inside a #[waterui::test]/#[waterui::bench] body — the animation clock advances with pumped frames, so the sleep freezes it and a transition snapshot silently shows its end state; use app.pump_for(..) or Query::wait_for_* No
unwrap_in_signal_map waterui_suspicious (warn) Flags an Option/Result unwrap/expect/unwrap_unchecked on the parameter inside a SignalExt::map closure (a zip(..).map(..) included) — the derived signal panics the first time the source is None/Err; suggests unwrap_or*/unwrap_or*_result or map_some/map_ok No
verbatim_text_literal waterui_suspicious (warn) Flags a string literal reaching an IntoText/IntoLabel parameter through to_string()/to_owned()/String::from/Str::from(_static)/.into()/Text::verbatim — &'static str resolves through the localization catalog, String/Str never translate; pass the literal itself Yes
watch_for_reactive_value waterui_suspicious (warn) Flags watch/Dynamic::watch whose single-expression closure reads the value only through carriers into signal-taking parameters (IntoSignal, IntoComputed, IntoSignalF32, IntoText, IntoLabel) — pass the signal itself so only that property updates and the subtree keeps its state No
watch_ignores_value waterui_suspicious (warn) Flags watch/Dynamic::watch whose closure never reads the watched value — every change rebuilds an identical subtree; .visible/when/.on_change fit better No
watch_over_collection waterui_suspicious (warn) Flags watch/Dynamic::watch over a Collection value (Vec, reactive::collection::List, SignalCollection, …) — every change rebuilds every row; Lazy::for_each/List::for_each/VStack::for_each or SignalCollection fit better No

Lint groups: waterui_correctness (deny), waterui_suspicious (warn), waterui_style (warn), waterui_pedantic (allow), waterui_a11y (allow). waterui_a11y holds the lints whose checked property is the accessibility surface — labels, roles, and hidden markers — so a style-focused run stays quiet and an accessibility audit opts in with -W waterui_a11y. Lint and group names are plain identifiers, so #[allow(signal_get_in_view)] and -W waterui_pedantic work as with any rustc lint; a waterui::-scoped spelling would need the linted crate to #![register_tool(waterui)], which is unstable.

Developing

Lint behavior is verified with UI tests. Each lint has a fixture package under ui/<lint>/ (its own Cargo.toml and main.rs) and expected diagnostics in ui/<lint>/main.stderr.

Run all UI tests with:

cargo test

or a single fixture with:

WATERUI_LINTS_UI_EXAMPLE=<lint> cargo test

To build the lint library and run it against a fixture manually (the DYLINT_LIBRARY_PATH points --lib at the freshly built library in target/debug):

cargo build
DYLINT_LIBRARY_PATH="$PWD/target/debug" \
    cargo dylint --lib waterui_lints --manifest-path ui/<lint>/Cargo.toml

To create or update ("bless") expected diagnostics, run the cargo dylint command above, review its output carefully, and write the stderr: diagnostics into ui/<lint>/main.stderr (matching rustc's output format). Alternatively, run cargo test; on a mismatch the harness prints an Actual stderr saved to ... path that can be copied over main.stderr after review.

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

About

WaterUI-specific lints: a dylint library that catches the silent reactivity, localization, layout and accessibility mistakes rustc cannot

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages