diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index e533d00b73..ca0108f955 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -654,8 +654,7 @@ mod tests { let held = rss_mb(); drop(buffer); let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else { - eprintln!("no memory reading (Linux without `ps`): nothing to check"); - return; + panic!("rss_mb gave no memory reading"); }; assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}"); } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index db34010c22..d0e4939e8e 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { use vectorcraft_doc::text::{CharStyle, TextObject}; let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); - if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } + assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths"); let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); let b = baked(g); assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); @@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec) -> Node { n } +/// Whether the face of the default character style is installed, so that type lays out glyphs. +/// When it is, `type_node`'s type must outline to paths. +fn fonts() -> bool { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { + return false; + } + assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family); + true +} + /// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square /// centered on its origin. fn instance(id: u64, effects: Vec) -> (Node, Node) { @@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec) -> (Node, Node) { /// image and the instance are checked. #[test] fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() { - let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0); + let fonts = fonts(); if !fonts { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); } @@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef /// listed before that effect, as the canvas draws it, rather than staying type under one shadow. #[test] fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() { - if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } @@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() { n }; let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; - if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index ffa8e83f40..7ae627e546 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -445,11 +445,13 @@ fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() { let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}})); - let before = render(&s); - if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { eprintln!("skipped: built without a font that draws the type"); return; } + let before = render(&s); + assert!((0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])), "the type draws in red"); // The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow. let red = (100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0); diff --git a/crates/js/tests/json2.rs b/crates/js/tests/json2.rs index af408a4fef..521040373e 100644 --- a/crates/js/tests/json2.rs +++ b/crates/js/tests/json2.rs @@ -68,20 +68,16 @@ problem; #[test] fn json2_polyfill_round_trips_with_the_built_in_json() { + let mut realm = Realm::new(); + match realm.run(NEEDS) { + Ok(JsValue::Bool(true)) => {} + other => panic!("json2: the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses: {other:?}"), + } let Some(path) = json2_file() else { println!("json2: SKIPPED (no json2.js; run cargo xtask test262)"); return; }; let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let mut realm = Realm::new(); - match realm.run(NEEDS) { - Ok(JsValue::Bool(true)) => {} - Ok(JsValue::Bool(false)) => { - println!("json2: SKIPPED (the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses)"); - return; - } - other => panic!("json2: the built-in check failed: {other:?}"), - } match realm.run(&format!("{BEFORE}\n{source}\n{ROUND_TRIP}")) { Ok(JsValue::String(s)) if s == "ok" => println!("json2: the polyfill and the built-in JSON agree on every sample"), other => panic!("json2: {other:?}"), diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index f6a2e8229b..b60f426834 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -503,13 +503,13 @@ fn arabic_ligatures_keep_their_letters_in_order() { let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style); vectorcraft_text::layout(db, &t).glyphs.len() == 1 }; - // An installed Arabic font with a lam-alef ligature whose glyphs come back as live type. + // An installed Arabic font with a lam-alef ligature. The test checks that its type comes + // back, so the choice of font does not depend on the import. let Some(face) = preferred .iter() .chain(&db.families()) .filter_map(|f| db.face(f, "Regular")) - .filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) - .find(|f| !imported_texts(f, "بب").is_empty()) + .find(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) else { return; // No such font on this host. }; diff --git a/crates/pdf/src/tests/realtext.rs b/crates/pdf/src/tests/realtext.rs index 7fcd06dd56..5f4ef0205f 100644 --- a/crates/pdf/src/tests/realtext.rs +++ b/crates/pdf/src/tests/realtext.rs @@ -202,8 +202,7 @@ fn line_break_hyphens_of_right_to_left_lines_are_written_as_text_where_the_canva /// The kashidas of justified Arabic type (Insert Kashidas), which stand for no character either, /// are drawn as paths: reopened, the type holds its letters and no hyphen or tatweel. Skipped -/// without an OpenType font that covers Arabic and the tatweel, when the layout adds no kashida, -/// or when PDF text import returns no strings on this platform. +/// without an OpenType font that covers Arabic and the tatweel. #[test] fn kashidas_are_not_written_as_hyphens() { let db = FontDb::global(); @@ -221,20 +220,17 @@ fn kashidas_are_not_written_as_hyphens() { t.para.justify = vectorcraft_doc::Justify::JustifyAll; t.para.kashida = vectorcraft_doc::text::Kashida::Medium; let tatweel = face.glyph_for('\u{0640}'); - if !vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel) { - return; - } + assert!( + vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel), + "{}: justified layout inserts a kashida", + face.family + ); let back = texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text)); - if back.is_empty() { - return; - } + assert!(!back.is_empty(), "{}: the PDF's type comes back", face.family); assert!(!back.concat().contains(['-', '\u{2010}', '\u{0640}']), "{back:?}"); // Every letter comes back, at least as often as the text holds it (the justified words may // come back as type objects of their own). let all = back.concat(); - if all.is_empty() { - return; - } let count = |s: &str, c: char| s.chars().filter(|&x| x == c).count(); for c in text.chars().filter(|c| c.is_alphabetic()) { assert!(count(&all, c) >= count(text, c), "{c}: {back:?}"); diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 225e58a053..5164dd1998 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -228,11 +228,10 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels); let mut shaped = Vec::new(); shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &[], &OtFeatures::default(), levels, &mut shaped); - let Some(first) = shaped.first() else { return }; + let first = shaped.first().expect("the text shapes to glyphs"); let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count(); - if first.byte != 0 || first_end < 2 || first_end >= shaped.len() { - return; - } + assert_eq!(first.byte, 0, "{}: the first cluster starts the text: {shaped:?}", face.family); + assert!(first_end >= 2 && first_end < shaped.len(), "{}: the base and its mark are one cluster of two glyphs: {shaped:?}", face.family); // Pick a narrow width that fits glyphs before one positive-advance glyph but not that next // glyph. This ensures the old per-glyph loop would have returned inside the first cluster. let mut prefix = shaped.first().map_or(0.0, |g| g.adv); @@ -245,6 +244,7 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { None } }); + // A face whose mark has no advance gives no width that splits the cluster. let Some(width) = width else { return }; let mut object = TextObject::point(Point::ZERO, text, style); diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index c6211550b3..ac4355e3a2 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -183,12 +183,7 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { let split_width: f64 = hindi_glyphs.iter().filter(|g| g.byte == split).map(|g| g.advance).sum(); assert!(prefix_width.is_finite() && prefix_width > 0.0, "setup: prefix has positive finite advance"); assert!(split_width.is_finite(), "setup: the internal raw-group advance is finite"); - if split_width <= 0.0 { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the selected face has no positive-advance raw group at internal byte {split}" - ); - return; - } + assert!(split_width > 0.0, "setup: {} lays out a positive-advance raw group at internal byte {split}", face.family); let width = prefix_width + split_width * 0.5; assert!(width.is_finite() && width > prefix_width && width < prefix_width + split_width, "setup: one measured width separates the raw groups"); @@ -205,12 +200,6 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { assert_eq!(edit::prev_cluster(text, hindi.len()), second, "setup: logical cluster start is 6"); assert_eq!(edit::prev_cluster(text, split), second, "setup: raw line endpoint 12 is inside the grapheme"); assert_eq!(edit::next_cluster(text, split), hindi.len(), "setup: raw line endpoint 12 is not its end"); - if lay.lines.len() < 2 || (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start) != (0, split, split) { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the measured frame does not expose adjacent wrapped endpoints at internal byte {split}" - ); - return; - } assert!(lay.lines.len() >= 2, "setup: actual wrapping occurred"); assert_eq!( (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start), diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs index 154972dec7..3239ca6f00 100644 --- a/crates/ui-egui/src/addons/image/tests.rs +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -248,6 +248,5 @@ fn properties_and_the_control_bar_remove_the_background_at_once() { assert!(closed(&app), "it runs at once"); assert_eq!(steps(&app), n + 1, "one undo step"); // The defaults (tolerance and softness 10): the white goes, the near-white ring fades. - let [corner, ring, block] = alphas(&app); - assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app)); + assert_eq!(alphas(&app), [0, 95, 255]); } diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index b712b589d9..402a2b1922 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -84,13 +84,14 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() { let name = "10 pt. Oval"; app.run("brush.apply", json!({"name": name})).unwrap(); let before = app.session.active().unwrap().history.undo.len(); + let width = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap().width; ask(&mut app, json!({"name": name}), true); answer::(&mut app, choice, pump); assert_eq!(open_question(&app), None); assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice.is_some())); let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); assert_eq!(stroke.brush.as_deref(), choice.is_none().then_some(name)); - assert!(stroke.width > 0.0); + assert_eq!(stroke.width, width, "the stroke keeps its width"); } } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 8c64b06a80..110c124717 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -437,8 +437,8 @@ mod tests { confirm(&mut app, &ctx); assert!(!app.session.in_interaction()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); - let lighter = vectorcraft_color::Color::from_hex(&fill_hex(&app, id)).unwrap().to_rgb()[0]; - assert!(lighter > 0.6, "{lighter}"); + // #808080 holds less than 50% black, so taking 50% away leaves none. + assert_eq!(fill_hex(&app, id), "#ffffff"); } #[test] diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index dcff2191a4..d5f31df6c3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -22,6 +22,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { | "blend" | "character" | "color" + | "docInfo" | "magicWand" | "openType" | "paragraph" diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index d8075d4c66..aaccca637b 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -884,6 +884,9 @@ impl LibraryKind for BrushLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.brush_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Rc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|b| Row { name: b.name(), item: Some(b) }).collect() } diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 5cb45f666a..13749667b9 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -950,7 +950,7 @@ mod tests { app.canvas.doc_info.clone().unwrap().1 }; let all = shown(&mut app, ""); - assert!(all["pathArea"].as_f64().is_some_and(|a| a > 0.0), "{}", all["pathArea"]); + assert!(all["pathArea"].as_f64().is_some_and(|a| (a - 200.0).abs() < 1e-6), "{}", all["pathArea"]); assert!(Arc::ptr_eq(&all, &shown(&mut app, "objects")), "Objects reuses All Categories' result"); for category in ["document", "fonts"] { let other = shown(&mut app, category); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d9250ad7ee..e6668323a8 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1004,6 +1004,9 @@ impl LibraryKind for GraphicStyleLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.style_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|s| Row { name: &s.style().name, item: Some(s) }).collect() } diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index e9fc506ec0..529671ccce 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -15,9 +15,11 @@ //! Library… (`ui.libraryPanel.locate`). The find text is the browser's; the selection is panel state //! (`UiState::library_selection`). +use std::any::Any; use std::borrow::Cow; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::HashMap; +use std::rc::Rc; use craft::behavior::{IconId, Selection, SelectionModel}; use craft::host::PickRequest; @@ -25,9 +27,7 @@ use craft::theme::variant::Tone; use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::{Notice, NoticeAction, NoticeLayout}; -use craft::ui::patterns::presets::{ - PresetBrowser, PresetEvent, PresetFns, PresetKind, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView, -}; +use craft::ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView}; use craft::ui::primitives::{ContentPainterCx, IconSpec}; use craft::ui::runtime::access::PopupKind; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; @@ -122,7 +122,7 @@ pub(crate) trait LibraryKind { /// The view a panel shows until another is picked. const VIEW: View = View::MediumThumb; /// A library's contents, cheap to clone. - type Lib; + type Lib: Clone + 'static; type Item: Sync; /// What the thumbnails paint with besides each item (a panel setting, the documents a library's patterns come /// from); `()` for nothing. @@ -135,6 +135,9 @@ pub(crate) trait LibraryKind { fn find(app: &VectorcraftApp, key: &str) -> Found; /// The file library `id` was read from, if any. fn path(app: &VectorcraftApp, id: &str) -> Option; + /// Whether `a` and `b` are the same contents, not only equal ones: the panel reuses the browser rows it built for + /// `a` while [`get`](Self::get) returns `b`. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool; /// The rows of library `id`; the browser's search filters what it shows (by the shown name and /// [`PresetRow::search_name`]). fn rows<'a>(lib: &'a Self::Lib, id: &str) -> Vec>; @@ -608,6 +611,7 @@ fn saved_view(view: PresetView, zoom: f64) -> View { /// The browser rows of library `id`'s `rows`, flat: a folder is a row of its own before its items, which a click /// selects as it selects an item (production's folder tiles neither opened nor closed). fn browser_rows(panel: &str, id: &str, rows: &[Row]) -> Vec> { + BUILDS.with(|n| n.set(n.get() + 1)); rows.iter() .map(|r| { let label = K::label(id, r.name); @@ -624,22 +628,73 @@ fn browser_rows(panel: &str, id: &str, rows: &[Row]) -> .collect() } +/// A library panel's browser rows, built for one library's contents in one UI language. +struct BuiltRows { + /// The contents the rows were built from, held so that [`LibraryKind::same`] does not match other contents + /// later stored at the same address. + lib: L, + lang: crate::i18n::Lang, + /// Different for every build, so the browser's memo key changes with the rows. + build: u64, + rows: Rc>>, + /// Each item row's position in [`LibraryKind::rows`], by stored name. + items: Rc>, +} + +thread_local! { + /// Each library panel's [`BuiltRows`], by panel id. + static BUILT_ROWS: RefCell>> = RefCell::new(HashMap::new()); + /// How many times [`browser_rows`] has run, for tests. + static BUILDS: Cell = const { Cell::new(0) }; +} + +/// How many times the panels have built browser rows on this thread. +#[cfg(test)] +pub(crate) fn row_builds() -> u64 { + BUILDS.with(Cell::get) +} + +/// [`BuiltRows::build`], [`BuiltRows::rows`] and [`BuiltRows::items`]. +type Built = (u64, Rc>>, Rc>); + +/// Panel `panel`'s browser rows of `lib`: the ones built before while the panel shows the same contents in the same +/// language, otherwise built now. Building drops the rows of the panels that are no longer open in `ui`. +fn built_rows(ui: &UiState, panel: &str, id: &str, lib: &K::Lib) -> Built { + let lang = crate::i18n::current(); + BUILT_ROWS.with(|cache| { + let mut cache = cache.borrow_mut(); + if let Some(b) = cache.get(panel).and_then(|b| b.downcast_ref::>()) + && b.lang == lang + && K::same(&b.lib, lib) + { + return (b.build, b.rows.clone(), b.items.clone()); + } + let flat = K::rows(lib, id); + let rows = Rc::new(browser_rows::(panel, id, &flat)); + let items = Rc::new(flat.iter().enumerate().filter(|(_, r)| r.item.is_some()).map(|(i, r)| (r.name.to_string(), i)).collect()); + let build = BUILDS.with(Cell::get); + let built = BuiltRows { lib: lib.clone(), lang, build, rows: rows.clone(), items: Rc::clone(&items) }; + cache.retain(|p, _| is_open(ui, p)); + cache.insert(panel.to_string(), Box::new(built)); + (build, rows, items) + }) +} + /// What a library's browser shows: its rows, the items their thumbnails paint and what those paint with. struct Shown<'a, K: LibraryKind> { + /// [`BuiltRows::build`] of `rows`. + build: u64, rows: &'a [PresetRow], - items: HashMap<&'a str, &'a K::Item>, + flat: &'a [Row<'a, K::Item>], + items: &'a HashMap, thumbs: K::Thumbs, } -/// By the rows (each names its library and item, whose look a library keeps) and what the thumbnails paint with. +/// By the build of the rows (each names its library and item, whose look a library keeps) and what the thumbnails +/// paint with. impl MemoProps for Shown<'_, K> { fn key(&self, key: &mut MemoKey) { - for row in self.rows { - row.key.key(key); - row.label.key(key); - row.depth.key(key); - (row.kind == PresetKind::Item).key(key); - } + self.build.key(key); self.rows.len().key(key); self.thumbs.key(key); } @@ -658,15 +713,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { }; let panel = panel_id(K::KIND, id); let (view, hide_find) = settings(&app.ui, K::KIND, id).map_or((K::VIEW, false), |s| (s.view.unwrap_or(K::VIEW), s.hide_find)); + let (build, rows, items) = built_rows::(&app.ui, &panel, id, &lib); let flat = K::rows(&lib, id); - let rows = browser_rows::(&panel, id, &flat); - let items = flat.iter().filter_map(|r| r.item.map(|i| (r.name, i))).collect(); let fns = PresetFns::new(|shown: &Shown<'_, K>, _| shown.rows.to_vec()).thumb(|shown, cx, rect, info| { - if let Some(item) = shown.items.get(info.key.name.as_str()) { + if let Some(item) = shown.items.get(info.key.name.as_str()).and_then(|&i| shown.flat.get(i)).and_then(|r| r.item) { K::thumb(&shown.thumbs, cx, rect, item); } }); - let source = PresetSource::new(Shown:: { rows: &rows, items, thumbs: K::thumbs(app, &lib) }, fns); + let source = PresetSource::new(Shown:: { build, rows: &rows, flat: &flat, items: &items, thumbs: K::thumbs(app, &lib) }, fns); let selection = selected(app, &panel); // The search text and the open groups are the browser's; the view is the panel's setting. let state_id = egui::Id::unique(("library-panel-state", &panel)); diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..679bd5f983 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -786,3 +786,27 @@ fn built_in_library_swatches_are_listed_in_the_ui_language() { assert!(app.session.doc().unwrap().doc.swatch("Clay 1").is_some(), "added under its own name"); crate::i18n::set_current(crate::i18n::Lang::EN); } + +/// A library panel builds its browser rows once for the library it shows, not on every frame, and builds them again +/// when the UI language changes the names it lists. +#[test] +fn library_panel_builds_its_rows_once_per_library_and_language() { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = shown(&app); + app.run("ui.libraryPanel", json!({"panel": panel, "view": "smallList"})).unwrap(); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let before = row_builds(); + for _ in 0..4 { + draw_frame(&mut app, &ctx, &draw, vec![]); + } + assert_eq!(row_builds() - before, 1, "four frames of an unchanged library build its rows once"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered")); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(row_builds() - before, 2, "a new UI language builds the rows again, once"); + let painted = crate::tests_labels::shapes_text(&out); + assert!(painted.lines().any(|l| l == "Argile 1"), "the rebuilt rows are in the new language: {painted}"); +} diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 8715d02401..d61efcb289 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -855,7 +855,38 @@ mod tests { let mut app = selected_text(); let Some((st, _)) = text_style(&app) else { panic!("no text style") }; let sets = set_entries(&app, &st); - // Builds without the bundled fonts have no face that offers sets. + // With the bundled fonts, the text's face offers sets. Without them, an installed face may. + assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets"); + // The submenu lists the `ss01` to `ss20` sets that the text's face offers, read here from + // the face itself, so the test returns early only when the face offers none. + let db = FontDb::global(); + let available = db.has_family(&db.canonical(&st.font_family, &st.font_style).0); + let face_sets = if available { db.style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default() } else { Vec::new() }; + let expected: Vec = face_sets.iter().filter(|set| (1..=20).contains(&set.number)).map(|set| format!("ss{:02}", set.number)).collect(); + let listed: Vec = sets.iter().map(|(_, flag, _)| flag.tag().unwrap_or_default().to_string()).collect(); + assert_eq!(listed, expected, "the submenu lists the stylistic sets of the text's face"); + let rows = menu_rows(&app); + if expected.is_empty() { + assert!(!rows.iter().any(|row| matches!(row, PanelRow::Submenu(..))), "the submenu is left out when the face offers no sets"); + } else { + let submenu = rows.iter().find_map(|row| match row { + PanelRow::Submenu(_, sub) if (1..=20).any(|number| has_row(sub, &toggle_ref(&format!("ss{number:02}")))) => Some(sub), + _ => None, + }); + let actual: Vec<&str> = submenu + .expect("the menu has a Stylistic Sets submenu") + .iter() + .filter_map(|row| match row { + PanelRow::Command(c) if c.id == TOGGLE => Some(c.params["tag"].as_str().expect("a toggle has a tag")), + _ => None, + }) + .collect(); + assert_eq!(actual, expected, "the submenu toggle tags match the face's sets in order"); + } + for tag in &expected { + let r = toggle_ref(tag); + assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}"); + } let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 4f16980b9a..c14d6cb040 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -106,6 +106,9 @@ impl LibraryKind for SwatchLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.swatch_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } /// Ungrouped swatches, then each colour group's folder and swatches, as in the Swatches panel; the browser's Find /// narrows them. fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { @@ -135,7 +138,7 @@ impl LibraryKind for SwatchLibraries { row } fn thumbs(app: &VectorcraftApp, lib: &Self::Lib) -> PatternSources { - PatternSources(lib.iter().filter_map(|w| Some((w.name.clone(), swatchlib::pattern_source(&app.session, w)?))).collect()) + PatternSources(lib.iter().filter_map(|w| swatchlib::pattern_source(&app.session, w).map(|d| (w.name.clone(), d))).collect()) } /// A pattern library's pattern, or a loaded library's, drawn from the library. fn thumb(sources: &PatternSources, cx: &ContentPainterCx<'_>, rect: Rect, w: &Swatch) { diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 63edfcb53b..c9179cfa06 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -981,6 +981,10 @@ impl LibraryKind for SymbolLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.symbol_libraries.path(id).map(str::to_string) } + /// [`get`](LibraryKind::get) wraps the library anew each time: by the library the symbols are in. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + a.len() == b.len() && a.first().zip(b.first()).is_none_or(|(a, b)| Arc::ptr_eq(&a.lib, &b.lib)) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|s| Row { name: s.name(), item: Some(s) }).collect() } diff --git a/crates/ui-egui/src/panels/tests_blend.rs b/crates/ui-egui/src/panels/tests_blend.rs index 6aeaaeda67..1653488b5a 100644 --- a/crates/ui-egui/src/panels/tests_blend.rs +++ b/crates/ui-egui/src/panels/tests_blend.rs @@ -217,10 +217,10 @@ fn ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options() { assert_eq!(undo_depth(&p.app()), depth + 1, "one undo step for both blends"); // The value typed goes to both; each keeps its own spacing, type and the other value. if name == "Ramp:" { - assert!(after_a.ease.ramp > 0.0 && after_a.ease.ramp == after_b.ease.ramp, "{after_a:?} {after_b:?}"); + assert!((after_a.ease.ramp - 0.75).abs() < 1e-9 && (after_b.ease.ramp - 0.75).abs() < 1e-9, "{after_a:?} {after_b:?}"); assert_eq!((after_a.color_shift, after_b.color_shift), (before_a.color_shift, before_b.color_shift)); } else { - assert!(after_a.color_shift > 0.0 && after_a.color_shift == after_b.color_shift, "{after_a:?} {after_b:?}"); + assert_eq!((after_a.color_shift, after_b.color_shift), (75.0, 75.0), "{after_a:?} {after_b:?}"); assert_eq!((after_a.ease.ramp, after_b.ease.ramp), (before_a.ease.ramp, before_b.ease.ramp)); } assert_eq!((after_a.spacing, after_b.spacing), (BlendSpacing::Steps(3), BlendSpacing::Distance(12.0))); @@ -238,7 +238,7 @@ fn ramp_is_dimmed_while_a_selected_blend_has_no_spine() { assert!(!p.enabled("Ramp:") && p.enabled("Shift:")); p.type_into("Shift:", "75"); let app = p.app(); - assert!(spec(&app, a).color_shift > 0.0 && spec(&app, b).color_shift == spec(&app, a).color_shift); + assert_eq!((spec(&app, a).color_shift, spec(&app, b).color_shift), (75.0, 75.0)); } #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e2c5a62b80..5c1920d8c4 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -452,7 +452,7 @@ fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() { quick_click(&mut p, rail.rect.center()); let (hex, opacity) = first_stop(&p); assert_eq!(hex, "#336699", "the text applies"); - assert!(opacity > 0.2 && opacity < 0.8, "the press sets the opacity: {opacity}"); + assert!((opacity - 0.5).abs() < 0.005, "the press sets the opacity: {opacity}"); } /// A press on the opacity slider that takes the focus from an edited field applies the text and diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 507b8280e2..f3b5ca6a47 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -94,7 +94,7 @@ fn the_row_shows_under_the_box_view() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); } /// A value this build does not read keeps the rest of the preferences and reads as the default. @@ -122,7 +122,7 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); let labels = undo_labels(&p.app()); assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); assert_eq!(crate::panels::current_paints(&p.app()).0.color().unwrap().to_hex(), "#ff0000"); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index d22d8e9eb6..9b441b1f67 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1838,6 +1838,9 @@ fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() { // the key is still running when Cancel stops it, however long the frames take. let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build()); + // The clock stands still: the run's progress window, which opens once the run is old enough + // and takes the keys, stays closed however slowly the frames run. + app.now_override = Some(0.0); app.session.allow_plugin_grants_from_requests(); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks"); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 92b79b7e0e..64cc5373b8 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -23,6 +23,7 @@ mod numfields; mod overprint; mod paintchips; pub(crate) mod panel_harness; +mod panel_scroll; mod pastechords; mod pathtype; mod pdfoutput; diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 60e6bd2182..0b9fa40f9f 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -383,6 +383,20 @@ impl Panel { seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0) } + /// The named control the latest frame lays out lowest, where its name finds that control: the control a reader + /// reaches last. + pub(crate) fn lowest(&self) -> Option { + let mut names = self.names(); + names.sort(); + names.dedup(); + names + .into_iter() + .filter_map(|name| self.fixture.by_label(&name).map(|t| (name, t.rect.bottom()))) + .filter(|(_, bottom)| bottom.is_finite()) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(name, _)| name) + } + /// Whether the control named `name` takes input. pub(crate) fn enabled(&self, name: &str) -> bool { !self.fixture.tree().is_disabled_key(self.look(name).node) diff --git a/crates/ui-egui/src/tests/panel_scroll.rs b/crates/ui-egui/src/tests/panel_scroll.rs new file mode 100644 index 0000000000..0fbc73e271 --- /dev/null +++ b/crates/ui-egui/src/tests/panel_scroll.rs @@ -0,0 +1,61 @@ +//! Every panel in a dock group shorter than its contents scrolls to its last control (#10262). + +use std::cell::RefCell; + +use egui::{Ui, pos2, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; + +thread_local! { + /// The panel the harness draws. + static SHOWN: RefCell = const { RefCell::new(String::new()) }; +} + +fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + let id = SHOWN.with(|s| s.borrow().clone()); + crate::dock::panel_body(app, ui, &id); +} + +/// The panels whose last control a short dock group hides and the wheel does not bring into view. +fn unreachable_panels(room_height: f32) -> Vec { + let mut stuck = Vec::new(); + for (id, _) in crate::state::all_panels() { + SHOWN.with(|s| *s.borrow_mut() = id.to_owned()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + if let Err(e) = app.run("file.new", json!({"width": 200, "height": 200})) { + panic!("file.new: {e}"); + } + // A selected path, so the panels that edit a selection show their controls. + if let Err(e) = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})) { + panic!("shape.rectangle: {e}"); + } + let mut panel = Panel::new(app, draw); + let Some(last) = panel.lowest() else { continue }; + panel.room(vec2(300.0, room_height)); + panel.frame(); + panel.frame(); + if !panel.shows(&last) || panel.in_view(&last) { + continue; + } + for _ in 0..60 { + panel.scroll_at(pos2(150.0, room_height / 2.0), -120.0); + if panel.in_view(&last) { + break; + } + } + if !panel.in_view(&last) { + stuck.push(format!("{id}: {last:?}")); + } + } + stuck +} + +#[test] +fn every_panel_in_a_short_dock_group_scrolls_to_its_last_control() { + let mut stuck = unreachable_panels(120.0); + stuck.extend(unreachable_panels(60.0)); + assert!(stuck.is_empty(), "panels whose last control the wheel cannot reach: {stuck:?}"); +} diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 6dc9853a2a..351efaec28 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -215,8 +215,10 @@ fn filter_dialog_previews_and_commits_one_undo_step() { set_field(&mut h, "amount", json!(50)).unwrap(); step(&mut h); assert!(h.state().session.in_interaction(), "previewing"); - let [r, g, _] = fill_rgb(h.state(), id); - assert!(r < 1.0 && g > 0.0, "half desaturated on the canvas: {r} {g}"); + let [r, g, b] = fill_rgb(h.state(), id); + for (got, want) in [(r, 0.6063), (g, 0.1063), (b, 0.1063)] { + assert!((got - want).abs() < 1e-4, "half desaturated on the canvas: {r} {g} {b}"); + } step(&mut h); let (shown, _) = h.state().canvas.shown.as_ref().expect("a rendered canvas frame"); let shown_fill = shown.node(id).unwrap().appearance.fill_paint().color().unwrap().to_rgb_uncalibrated(); diff --git a/crates/ui-egui/src/thumb_worker.rs b/crates/ui-egui/src/thumb_worker.rs index e9898a078f..5e7c48758c 100644 --- a/crates/ui-egui/src/thumb_worker.rs +++ b/crates/ui-egui/src/thumb_worker.rs @@ -214,7 +214,7 @@ mod tests { #[test] fn jobs_come_back_newest_last_per_slot() { - let Some(w) = ThumbWorker::::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; for k in 1..=3 { assert!(w.submit(0, k, job(k))); @@ -238,7 +238,7 @@ mod tests { #[test] fn discarded_jobs_do_not_run_and_the_running_one_finishes() { - let Some(w) = ThumbWorker::::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; // A job that holds the thread until it is let go, so the others queue behind it. let (started, running) = channel::<()>(); diff --git a/docs/development.md b/docs/development.md index a1ceccaf59..4244e28738 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 83360ad388..ce60771034 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -35,8 +35,9 @@ commands: cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] weak tests in the lines changed since the base: fail on self-compares, reasonless - #[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion, - early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit + #[ignore], sleeps, reads of Rust source and tests no CI target runs; list only + is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env + gates, constant echoes, exact pixels... (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5cc0a180aa..f1667d2cb0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -37,14 +37,27 @@ //! string literals, `echo` or `printf` output that is not written to `$GITHUB_ENV`, and variable //! reads do not; //! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; -//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk -//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]; +//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, +//! `read_to_string` of a path with a `.rs` literal, or a walk that keeps files ending in `.rs`), +//! outside the source audits in [`SOURCE_AUDITS`]; //! * `census`: a test that loops over a whole table (a `SCREAMING_CASE` constant, `Type::ALL`, //! `Type::iter()`, or a call named `all`, `catalog`, `registry`, `presets`, `swatches`, //! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of //! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`, //! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or -//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! * `mirror`: `assert_eq!(f(a), f(b) …)`, where the expected side derives its value from a +//! second call of the same function (same path) with arithmetic, so a fault in `f` moves both +//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out; +//! * `constant-echo`: every assertion of the test compares only constants, literals and enum +//! variants; +//! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the +//! test bound (in scope) to such values, so nothing the code under test returned is checked; +//! * `never-run`: a test that the `cfg` attributes on it, on the items around it or on the `mod` +//! declarations above its file leave out of every target CI runs tests on (Linux and FreeBSD on +//! x86_64, and Windows for the app and the UI crate's print tests); +//! * `exact-pixel`: in a file that uses egui, an assertion that a screen rect (an identifier `rect`, +//! `rect_…` or `…_rect`, whole or through a corner, edge or size) equals numbers written out. //! //! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or //! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]` or `#[cfg(all(test, …))]`, @@ -58,8 +71,9 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason` and `sleep` in -//! the lines and tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason`, `sleep`, +//! `reads-source` and `never-run` in the lines and tests changed since a base, and lists the other +//! rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -127,10 +141,15 @@ pub enum Rule { Sleep, ReadsSource, Census, + Mirror, + ConstantEcho, + FixtureOnly, + NeverRun, + ExactPixel, } impl Rule { - pub const ALL: [Rule; 11] = [ + pub const ALL: [Rule; 16] = [ Rule::AllUnguarded, Rule::OnlyWeak, Rule::SelfCompare, @@ -142,6 +161,11 @@ impl Rule { Rule::Sleep, Rule::ReadsSource, Rule::Census, + Rule::Mirror, + Rule::ConstantEcho, + Rule::FixtureOnly, + Rule::NeverRun, + Rule::ExactPixel, ]; pub fn id(self) -> &'static str { @@ -157,6 +181,11 @@ impl Rule { Rule::Sleep => "sleep", Rule::ReadsSource => "reads-source", Rule::Census => "census", + Rule::Mirror => "mirror", + Rule::ConstantEcho => "constant-echo", + Rule::FixtureOnly => "fixture-only", + Rule::NeverRun => "never-run", + Rule::ExactPixel => "exact-pixel", } } @@ -173,12 +202,19 @@ impl Rule { Rule::Sleep => "wait on a handshake (channel, barrier) or a controllable clock", Rule::ReadsSource => "test the behavior, or add the file to SOURCE_AUDITS in xtask/src/test_lint.rs if it audits the source tree", Rule::Census => "test one or a few representative entries and the edge cases (or generate inputs), not every entry of the table", + Rule::Mirror => "compare with an expected value written out, not with a second call of the same function", + Rule::ConstantEcho => "assert what the code under test returns, not a constant or literal the test or crate states", + Rule::FixtureOnly => "assert on what the code under test returns or changes, not on the input the test built", + Rule::NeverRun => "make the test build on a target CI runs (Linux, FreeBSD), or run it in a CI leg for its target", + Rule::ExactPixel => { + "assert relationships (inside its container, not overlapping, order, gap at least a spacing token), not a rect equal to numbers" + } } } /// Whether a hit on a changed line fails the command. The other rules only report. pub fn fails(self) -> bool { - matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) + matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep | Rule::ReadsSource | Rule::NeverRun) } fn from_id(id: &str) -> Option { @@ -199,11 +235,14 @@ pub struct Hit { /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's - /// `]` for `ignore-without-reason`, else `line`. This span + /// `]` for `ignore-without-reason`, through the call's `)` for `reads-source`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. pub first: usize, pub last: usize, + /// Other lines whose change counts as a change to the hit, by file: the `cfg` attributes that + /// turn a `never-run` test off, on its module or on a `mod` declaration in another file. + pub also: Vec<(String, usize, usize)>, } impl Hit { @@ -213,10 +252,31 @@ impl Hit { } } -/// What the rules need beyond the file: asserting helper names by crate and the variables CI sets. +/// What the rules need beyond the file: asserting helper names by crate, the variables CI sets, and +/// the `cfg` predicates each file's module inherits from the `mod` declarations above it. +#[derive(Default)] pub struct Ctx { pub helpers: HashMap>, pub ci_env: HashSet, + pub module_cfgs: HashMap>, + /// Where the attributes of [`Ctx::module_cfgs`] are. + pub module_sites: HashMap>, +} + +/// [`Ctx::module_cfgs`] and [`Ctx::module_sites`] for `paths`. +fn module_ctx(paths: &[String], read: &dyn Fn(&str) -> Option) -> (HashMap>, HashMap>) { + let (mut cfgs, mut sites) = (HashMap::new(), HashMap::new()); + for (path, (preds, at)) in module_walk(paths, read) { + cfgs.insert(path.clone(), preds); + sites.insert(path, at); + } + (cfgs, sites) +} + +/// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. +fn read_small(root: &Path, path: &str) -> Option { + let full = root.join(path); + (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { @@ -226,7 +286,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let (module_cfgs, module_sites) = module_ctx(&files, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs, module_sites }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); return Ok(()); @@ -236,18 +297,31 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); - let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + // Every file whose module a changed `mod` declaration governs is linted too, so a `cfg` added to + // `mod child;` counts against the tests in `child.rs`. + let cache: std::cell::RefCell>> = Default::default(); + let read = |p: &str| cache.borrow_mut().entry(p.to_owned()).or_insert_with(|| read_small(root, p)).clone(); + let (module_cfgs, module_sites) = module_ctx(&files, &read); + let governed: Vec = module_sites + .iter() + .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _, _)| changed.contains_key(decl))) + .map(|(p, _)| p.clone()) + .collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs, module_sites }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + if touches_in(&hit, &changed) { counted.push(hit); } else { older += 1; } } } + for (path, src) in read_all(root, &governed)? { + counted.extend(lint_file(&path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && touches_in(h, &changed))); + } finish(&counted, older, present.len(), &base) } @@ -497,7 +571,14 @@ fn hunk_range(hunk: &str) -> Option<(usize, usize)> { /// Whether `hit` covers a changed line (`None`: the whole file is new). fn touches(hit: &Hit, changed: Option<&BTreeSet>) -> bool { - changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) + let within = |lines: &BTreeSet, a: usize, b: usize| lines.range(a..=b).next().is_some(); + changed.is_none_or(|lines| within(lines, hit.first, hit.last) || hit.also.iter().any(|(p, a, b)| *p == hit.path && within(lines, *a, *b))) +} + +/// [`touches`] across files: the hit's own lines, or its [`Hit::also`] lines in any changed file. +fn touches_in(hit: &Hit, changed: &BTreeMap>>) -> bool { + let in_file = |p: &str, a: usize, b: usize| changed.get(p).is_some_and(|c| c.as_ref().is_none_or(|l| l.range(a..=b).next().is_some())); + changed.get(&hit.path).is_some_and(|c| touches(hit, c.as_ref())) || hit.also.iter().any(|(p, a, b)| in_file(p, *a, *b)) } // ---- What CI sets ---- @@ -1133,7 +1214,7 @@ struct File<'a> { impl File<'_> { fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { let line = self.lines.of(at); - Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, also: vec![] } } fn test_at(&self, pos: usize) -> &str { @@ -1238,7 +1319,9 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits.extend(early_returns(&v)); hits.extend(env_gates(&v, ctx)); hits.extend(census(&v, helpers)); - hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten()); + hits.extend(mirrors(&v)); + hits.extend(exact_pixels(&v)); + hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v), echoes(&v), never_run(&v, ctx)].into_iter().flatten()); hits } @@ -1556,12 +1639,21 @@ const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from /// Whether every operand of a (whitespace-free) condition or closure is a presence check alone. fn weak_predicate(pred: &str) -> bool { + weak_predicate_within(pred, 0) +} + +/// [`weak_predicate`] for at most 64 levels of nesting; deeper conditions are not judged, as in +/// [`census_condition`]. +fn weak_predicate_within(pred: &str, depth: usize) -> bool { + if depth > 64 { + return false; + } let pred = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body); if pred.starts_with('(') && matching(pred.as_bytes(), 0) == Some(pred.len() - 1) { - return weak_predicate(&pred[1..pred.len() - 1]); + return weak_predicate_within(&pred[1..pred.len() - 1], depth + 1); } if let Some(at) = boolean_split(pred) { - return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); + return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1); } let negated = (pred.len() - pred.trim_start_matches('!').len()) % 2 == 1; let pred = pred.trim_start_matches('!'); @@ -1611,6 +1703,8 @@ fn round_trip_call(op: &str) -> bool { op.match_indices(&format!("{r}(")).any(|(at, _)| { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) + // Only a path or receiver before the call: `offset + lookup(n)` is a derived value. + && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '=', '!', ',', '&']) && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) }) }) @@ -2884,35 +2978,750 @@ fn sleep_hits(file: &File) -> Vec { .collect() } +/// The contents of the last string literal in `s`, without its quotes. +fn last_literal(s: &str) -> Option<&str> { + let close = s.rfind('"')?; + let open = s[..close].rfind('"')?; + Some(&s[open + 1..close]) +} + +/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call that ends the path, since +/// its arguments fill placeholders inside it, otherwise the last string literal. A literal after the `format!(…)` +/// call (`PathBuf::from(format!(…)).join("lib.rs")`) ends the path instead. +fn path_literal(arg: &str) -> Option<&str> { + let Some(at) = arg.find("format!(") else { return last_literal(arg) }; + let rest = &arg[at + "format!(".len()..]; + let b = rest.as_bytes(); + let (mut depth, mut i, mut end) = (0usize, 0, None); + while i < b.len() { + match b[i] { + b'"' => { + i += 1; + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + } + b'(' => depth += 1, + b')' if depth == 0 => { + end = Some(i); + break; + } + b')' => depth -= 1, + _ => {} + } + i += 1; + } + let call = &rest[..end.unwrap_or(rest.len())]; + if let Some(tail) = end.map(|e| &rest[e + 1..]).filter(|t| t.contains('"')) { + return path_literal(tail); + } + let open = call.find('"')?; + let close = call[open + 1..].find('"')? + open + 1; + Some(&call[open + 1..close]) +} + fn reads_source_hits(file: &File) -> Vec { if SOURCE_AUDITS.contains(&file.path) { return vec![]; } let m = &file.m; let mut out = vec![]; - for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + let words_and_notes = [ + (&b"include_str"[..], "includes a .rs file as text"), + (&b"ends_with"[..], "keeps files ending in .rs"), + (&b"read_to_string"[..], "reads a .rs file as text"), + ]; + for (word, note) in words_and_notes { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let arg = norm(&file.src[open + 1..close]); + // Comments dropped, so `/* "src/lib.rs" */` beside a JSON path is not a hit. + let arg = file.src_norm((open + 1, close)); // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); - let rs = if word == b"ends_with" { literal == "\".rs\"" } else { arg.trim_end_matches('#').ends_with(".rs\"") }; + let rs = match word { + b"ends_with" => literal == "\".rs\"", + // The last path literal in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`, but not + // `root.join("fixtures.rs").join("input.json")` or `format!("{}/input.json", "fixtures.rs")`. + b"read_to_string" => path_literal(&arg).is_some_and(|l| l.ends_with(".rs")), + _ => arg.trim_end_matches('#').ends_with(".rs\""), + }; if rs { - out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + // Through the call's `)`, so a change to a path on a later line is a change to the hit. + let mut hit = file.hit(at, Rule::ReadsSource, file.test_at(at), note.into()); + hit.last = file.lines.of(close); + out.push(hit); } } } out } +// ---- Mirrors, echoes, never-run tests and exact pixels ---- + +/// Names a `mirror` comparison may call on both sides: builders, conversions and accessors. +const MIRROR_NEUTRAL: &[&str] = &[ + "new", + "from", + "into", + "default", + "clone", + "to_string", + "to_owned", + "to_vec", + "iter", + "into_iter", + "collect", + "unwrap", + "expect", + "len", + "get", + "as_str", + "as_ref", + "as_slice", + "format", + "vec", + "Some", + "Ok", + "Err", + "Box", + "String", + "Vec", + "map", + "cloned", + "copied", +]; + +/// The function a whitespace-free operand starts by calling, with its path: `f` in `f(x).g()`, +/// `Kind::parse` in `Kind::parse(s)`. A method call on a value (`doc.node(id)`) is not one: two reads of the same +/// accessor compare two different things. +fn head_call(op: &str) -> Option<&str> { + let b = op.as_bytes(); + let mut i = 0; + loop { + let end = i + b.get(i..)?.iter().take_while(|&&c| is_ident(c)).count(); + if end == i || b[i].is_ascii_digit() { + return None; + } + match b.get(end) { + Some(b':') if b.get(end + 1) == Some(&b':') => i = end + 2, + Some(b'(') => return Some(&op[..end]), + _ => return None, + } + } +} + +/// `assert_eq!(f(a), f(b))`: both sides start by calling the same function, so a fault in `f` can +/// move both sides together. Identical sides are `self-compare`'s. +fn mirrors(v: &View) -> Vec { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq")) + .filter_map(|a| { + let (l, r) = (norm(&v.file.m[a.args.first()?.0..a.args.first()?.1]), norm(&v.file.m[a.args.get(1)?.0..a.args.get(1)?.1])); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let name = head_call(l)?; + // The expected side derives its value from a second call with arithmetic; two calls + // compared as they are check that two inputs agree, which is a real check. + let derived = ["+", "-", "*", "/"].iter().any(|op| !top_level_at(r, op).is_empty()); + let last = name.rsplit("::").next().unwrap_or(name); + (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)) + .then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + }) + .collect() +} + +/// Methods that only read a value the test built itself. +const FIXTURE_READS: &[&str] = &["len", "is_empty", "clone", "to_string", "to_owned", "as_str", "as_ref", "as_slice", "to_vec", "into"]; + +/// Lowercase names that are types or keywords, not locals. +const PLAIN_NAMES: &[&str] = &[ + "true", "false", "as", "f32", "f64", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "bool", "char", + "str", +]; + +fn screaming_or_camel(name: &str) -> bool { + name.as_bytes().first().is_some_and(u8::is_ascii_uppercase) +} + +/// Whether a (whitespace-free, masked) operand reads only literals, constants, enum variants and the +/// test's own locals bound to such values: `Some(true)` when it reads such a local, `Some(false)` +/// when it reads none, `None` when it calls or reads anything else. +fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { + let b = op.as_bytes(); + let mut reads_local = false; + let mut i = 0; + while i < b.len() { + if !is_ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && is_ident(b[i - 1])) { + // Number suffixes (`1.0f32`, `2_u8`) are part of the literal. + if b[i].is_ascii_digit() { + i += b[i..].iter().take_while(|&&c| is_ident(c)).count(); + continue; + } + i += 1; + continue; + } + let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let name = &op[i..end]; + let after = &op[end..]; + let method = op[..i].ends_with('.') && !op[..i].ends_with(".."); + let path_tail = op[..i].ends_with("::"); + if method { + if after.starts_with('(') && !FIXTURE_READS.contains(&name) { + return None; + } + } else if after.starts_with("::") || PLAIN_NAMES.contains(&name) { + } else if after.starts_with('!') && !after.starts_with("!=") { + // `format!` can read locals inside its string (`"{got:?}"`), which masking hides. + if name != "vec" { + return None; + } + } else if after.starts_with('(') { + let builder = ["Some", "Ok", "Err"].contains(&name) + || (path_tail && ["Box::new", "String::from", "Vec::new"].iter().any(|p| op[..end].ends_with(p))) + || (!path_tail && screaming_or_camel(name)); + if !builder { + return None; + } + } else if after.starts_with(':') || screaming_or_camel(name) { + // A field name in a struct literal, a constant or a variant. + } else if path_tail { + return None; + } else { + match local(name) { + Some(true) => reads_local = true, + _ => return None, + } + } + i = end; + } + Some(reads_local) +} + +/// The initializer of the last immutable `let = …;` in `body[..before]`: `None` when there is +/// none, `Some(None)` when the reaching binding is `mut`, a pattern or has no initializer. The +/// initializer comes with the offset of its `let`, where the names it reads are resolved. +fn reaching_init(body: &[u8], name: &str, before: usize) -> Option> { + let mut found = None; + for at in words(body, b"let", 0, before) { + let start = skip_ws(body, at + 3); + let is_mut = body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace); + let n0 = if is_mut { skip_ws(body, start + 3) } else { start }; + let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c)).count(); + let stop = statement_end(body, n1); + if stop > before || block_close(body, at) < before { + continue; + } + let rest = norm(&body[n1..stop]); + let plain = n1 > n0 && (rest.is_empty() || rest.starts_with(':') || rest.starts_with('=')); + if plain && &body[n0..n1] == name.as_bytes() { + let init = rest.split_once('=').filter(|(ty, _)| ty.is_empty() || ty.starts_with(':')).map(|(_, init)| (init.to_owned(), at)); + found = Some(if is_mut { None } else { init }); + } else if !plain { + // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). + let pattern = norm(&body[n0..stop]); + let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); + if !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + found = Some(None); + } + } + } + // A nearer `for in` binding of the name, whose block holds `before`, shadows the + // `let`: its value is unknown. + let found_at = match &found { + Some(Some((_, at))) => Some(*at), + _ => None, + }; + let shadows = |kw: &[u8], sep: &[u8]| { + words(body, kw, 0, before).into_iter().any(|at| { + let head = at + kw.len(); + let Some(open) = body[head..before].iter().position(|&c| c == b'{').map(|p| p + head) else { return false }; + let Some(split) = find(&body[..open], sep, head) else { return false }; + let pattern = &body[head..split]; + !words(pattern, name.as_bytes(), 0, pattern.len()).is_empty() + && matching(body, open).is_some_and(|close| open < before && before < close) + && found_at.is_none_or(|l| at > l) + }) + }; + if shadows(b"for", b" in ") { + return Some(None); + } + found +} + +/// Where the innermost block holding `at` closes: its `}`, or the end of `body`. +fn block_close(body: &[u8], at: usize) -> usize { + let mut depth = 0usize; + for i in (0..at).rev() { + match body[i] { + b'}' => depth += 1, + b'{' if depth == 0 => return matching(body, i).unwrap_or(body.len()), + b'{' => depth -= 1, + _ => {} + } + } + body.len() +} + +/// `inert` for an operand of the test at `pos`, resolving locals through their initializers. +fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option { + let local = |name: &str| -> Option { + if depth > 8 { + return None; + } + let (init, at) = reaching_init(body, name, pos)??; + inert_at(body, &init, at, depth + 1).map(|_| true) + }; + inert(op, &local) +} + +/// `constant-echo` and `fixture-only`: every assertion of the test reads only constants and +/// literals, or the test's own locals bound to them, so no result of the code under test is checked. +fn echoes(v: &View) -> Option { + if v.asserts.is_empty() || v.delegates || v.should_panic { + return None; + } + let body = v.body_without_messages(); + if contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err(") { + return None; + } + let mut reads_local = false; + for a in &v.asserts { + let n = guard_arg_count(&a.name); + if n == 0 { + return None; + } + for &(from, to) in a.args.iter().take(n) { + let op = norm(&body[from - v.t.open..to - v.t.open]); + reads_local |= inert_at(&body, &op, from - v.t.open, 0)?; + } + } + Some(if reads_local { + v.whole(Rule::FixtureOnly, "every assertion reads only locals the test bound to literals or constants".into()) + } else { + v.whole(Rule::ConstantEcho, "every assertion compares only constants and literals".into()) + }) +} + +/// A target CI builds and runs the tests on. +struct Target { + os: &'static str, + family: &'static str, + arch: &'static str, +} + +/// The shared gate (Linux) and the FreeBSD workflow run every test. +const CI_TARGETS: &[Target] = &[Target { os: "linux", family: "unix", arch: "x86_64" }, Target { os: "freebsd", family: "unix", arch: "x86_64" }]; + +/// The printing workflow also runs the app's tests and the UI crate's print tests on Windows. +const WINDOWS_TARGET: Target = Target { os: "windows", family: "windows", arch: "x86_64" }; + +fn windows_runs(path: &str) -> bool { + path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs" +} + +/// Whether a (whitespace-free) `cfg` predicate holds on `t`: `None` when it depends on something +/// else (a feature, `debug_assertions`, an unknown key). +fn cfg_value(p: &str, t: &Target) -> Option { + for (head, all) in [("all(", true), ("any(", false)] { + if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) { + let mut parts = vec![]; + let mut start = 0; + for at in top_level_at(args, ",").into_iter().chain([args.len()]) { + if at > start { + parts.push(cfg_value(&args[start..at], t)); + } + start = at + 1; + } + return if parts.contains(&Some(!all)) { + Some(!all) + } else if parts.iter().all(Option::is_some) { + Some(all) + } else { + None + }; + } + } + if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { + return cfg_value(arg, t).map(|v| !v); + } + // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. + let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + // An escape in an ordinary string (`"lin\x75x"`) is not decoded, so its value is unknown. + if p.split_once('=').is_some_and(|(_, v)| !v.starts_with('r') && v.contains('\\')) { + return None; + } + match key { + "test" => Some(true), + "unix" => Some(t.family == "unix"), + "windows" => Some(t.family == "windows"), + "target_os" => Some(t.os == value), + "target_family" => Some(t.family == value), + "target_arch" => Some(t.arch == value), + "target_pointer_width" => Some(value == "64"), + _ => None, + } +} + +/// The text of a `cfg(…)` predicate without whitespace and comments; string literals keep their text. +fn cfg_text(src: &[u8]) -> String { + norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) +} + +/// The 1-based line of a byte offset. +fn line_at(b: &[u8], at: usize) -> usize { + b[..at.min(b.len())].iter().filter(|&&c| c == b'\n').count() + 1 +} + +/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with +/// the offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { + let mut out = vec![]; + for at in words(m, b"cfg", 0, m.len()) { + let before = m[..at].trim_ascii_end(); + let Some(hash) = before.strip_suffix(b"[").map(<[u8]>::trim_ascii_end) else { continue }; + let inner = hash.ends_with(b"#!"); + if !inner && !hash.ends_with(b"#") { + continue; + } + let open = skip_ws(m, at + "cfg".len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') { + continue; + } + let span = if inner { + // An inner attribute covers the file (or the module) it opens. + let enclosing = m[..at].iter().rposition(|&c| c == b'{'); + enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) + } else { + // Later attributes can hold `;` (`#[test_case(1; "one")]`); skip them whole, as `fn_after` does. + let mut after = end + 1; + while m[skip_ws(m, after)..].starts_with(b"#[") { + let Some(close) = matching(m, skip_ws(m, after) + 1) else { break }; + after = close + 1; + } + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + match (m[open], matching(m, open)) { + (b'{', Some(close)) => (at, close), + _ => continue, + } + }; + if span.0 <= pos && pos <= span.1 { + // The source text: masking blanks the string literals `target_os = "macos"` needs. + out.push((cfg_text(&src[open + 1..close]), at, end)); + } + } + out +} + +/// A file that may declare a module, and the inline module it must be declared in, if any. +type Candidate = (String, Option); +/// The predicates on a `mod` declaration and the first and last line of each attribute, with the +/// predicate that attribute contributes. +type Declared = (Vec, Vec<(usize, usize, String)>); +/// A file that declares a module, whether it does so in an inline module, and what it declares. +type Owner = (String, bool, Declared); + +/// The module name a file declares and the files that may declare it with `mod ;`, or `None` +/// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or +/// `examples`). A candidate that comes with a module name declares it inside that inline module +/// (`mod platform { mod child; }` in `src/lib.rs` for `src/platform/child.rs`); those come last. +fn module_parent(path: &str) -> Option<(&str, Vec)> { + let (dir, file) = path.rsplit_once('/')?; + let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { + return None; + } + let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; + let files_of = |dir: &str| -> Vec { + let mut c: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{dir}/{f}")).collect(); + c.push(format!("{dir}.rs")); + c + }; + let mut candidates: Vec = files_of(parent).into_iter().map(|c| (c, None)).collect(); + if let Some((grand, inline)) = parent.rsplit_once('/') { + candidates.extend(files_of(grand).into_iter().map(|c| (c, Some(inline.to_owned())))); + } + Some((name, candidates)) +} + +/// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src` and on the +/// items and file around it, or `None` when `src` declares no such module. +#[cfg(test)] +fn declared_cfgs(src: &str, name: &str) -> Option> { + declared_cfg_spans(src, name, None).map(|(preds, _)| preds) +} + +/// [`declared_cfgs`] with the first and last line of each attribute. With `within`, only a +/// declaration inside the inline module of that name counts. +fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option { + let m = mask(src); + let named = |at: usize, word: &str, next: u8| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + (&m[start..end] == word.as_bytes() && m.get(skip_ws(&m, end)) == Some(&next)).then(|| skip_ws(&m, end)) + }; + let blocks: Option> = within.map(|w| { + words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() + }); + // Every inline `mod { … }`: a declaration counts only when its innermost enclosing inline + // module is the one `within` names (or, without `within`, when it has none), since a declaration + // nested deeper loads a file under that other module's directory. + let inline: Vec<(usize, usize)> = words(&m, b"mod", 0, m.len()) + .into_iter() + .filter_map(|at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + let o = skip_ws(&m, end); + (end > start && m.get(o) == Some(&b'{')).then(|| matching(&m, o).map(|c| (o, c))).flatten() + }) + .collect(); + let innermost = |at: usize| inline.iter().filter(|&&(o, c)| o < at && at < c).max_by_key(|&&(o, _)| o).copied(); + let decls: Vec = words(&m, b"mod", 0, m.len()) + .into_iter() + .filter(|&at| { + named(at, name, b';').is_some() + && match (&blocks, innermost(at)) { + (None, inner) => inner.is_none(), + (Some(bs), Some(inner)) => bs.contains(&inner), + (Some(_), None) => false, + } + }) + .collect(); + let mut each = decls.iter().map(|&decl| decl_cfg_spans(&m, src, decl)); + let first = each.next()?; + let rest: Vec = each.collect(); + if rest.iter().all(|(p, _)| *p == first.0) { + let mut lines = first.1; + lines.extend(rest.into_iter().flat_map(|(_, l)| l)); + return Some((first.0, lines)); + } + // Declarations under different `cfg`s (`#[cfg(windows)] mod child;` and `#[cfg(unix)] mod child;`): + // the module is compiled where any of them holds. + let (mut alts, mut spans) = (vec![], vec![]); + for (p, l) in std::iter::once(first).chain(rest) { + alts.push(format!("all({})", p.join(","))); + spans.extend(l.into_iter().map(|(a, b, _)| (a, b))); + } + let any = format!("any({})", alts.join(",")); + let lines = spans.into_iter().map(|(a, b)| (a, b, any.clone())).collect(); + Some((vec![any], lines)) +} + +/// The predicates of the `#[cfg(…)]` attributes on the `mod` declaration at `decl` of masked `m` +/// and on the items and file around it, with the first and last line of each attribute. +fn decl_cfg_spans(m: &[u8], src: &str, decl: usize) -> Declared { + let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let (mut preds, mut lines) = (vec![], vec![]); + for at in words(m, b"cfg", item, decl) { + let open = skip_ws(m, at + 3); + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() { + let p = cfg_text(&src.as_bytes()[open + 1..close]); + lines.push((line_at(m, at), line_at(m, close), p.clone())); + preds.push(p); + } + } + for (p, at, end) in cfgs_over(m, src.as_bytes(), decl) { + lines.push((line_at(m, at), line_at(m, end), p.clone())); + preds.push(p); + } + (preds, lines) +} + +/// Where a module's `cfg` attributes are: the declaring file, the attribute's first and last line, +/// and its predicate. +pub type CfgSite = (String, usize, usize, String); + +/// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the +/// modules above it, read through `read`, with where those attributes are. When several files +/// declare a module (`lib.rs` and `main.rs`) with different attributes, the walk stops there and +/// the module's ownership is unknown. +fn module_walk(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap, Vec)> { + let mut out = HashMap::new(); + for path in paths { + let (mut preds, mut sites, mut at) = (vec![], vec![], path.clone()); + for _ in 0..16 { + let Some((name, candidates)) = module_parent(&at) else { break }; + let found: Vec = candidates + .into_iter() + .filter_map(|(c, within)| read(&c).and_then(|s| declared_cfg_spans(&s, name, within.as_deref())).map(|f| (c, within.is_some(), f))) + .collect(); + let direct = found.iter().any(|(_, inline, _)| !inline); + let owners: Vec<&Owner> = found.iter().filter(|(_, inline, _)| !inline || !direct).collect(); + let Some(first) = owners.first() else { break }; + let sorted = |p: &[String]| { + let mut p = p.to_vec(); + p.sort(); + p + }; + let base = sorted(&first.2.0); + if !owners.iter().all(|o| sorted(&o.2.0) == base) { + break; + } + preds.extend(first.2.0.iter().cloned()); + for o in &owners { + sites.extend(o.2.1.iter().map(|(a, b, p)| (o.0.clone(), *a, *b, p.clone()))); + } + at = first.0.clone(); + } + if !preds.is_empty() { + out.insert(path.clone(), (preds, sites)); + } + } + out +} + +/// The predicates of [`module_walk`] alone. +#[cfg(test)] +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + module_walk(paths, read).into_iter().map(|(p, (preds, _))| (p, preds)).collect() +} + +/// A test that a `cfg` compiles out on every target CI runs tests on. +fn never_run(v: &View, ctx: &Ctx) -> Option { + let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); + let mut preds: Vec = local.iter().map(|(p, _, _)| p.clone()).collect(); + preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); + if preds.is_empty() { + return None; + } + let windows = windows_runs(v.file.path).then_some(&WINDOWS_TARGET); + let off = |t: &Target| preds.iter().any(|p| cfg_value(p, t) == Some(false)); + if CI_TARGETS.iter().chain(windows).all(off) { + let shown: Vec = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); + let mut hit = v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", "))); + // A change to an attribute that turns the test off counts as a change to the test; the + // lines between that attribute and the test do not. + let lines = &v.file.lines; + // An attribute whose predicate holds on every target CI tests on (`unix` without Windows) + // does not turn the test off. + let excludes = |p: &str| !CI_TARGETS.iter().chain(windows).all(|t| cfg_value(p, t) == Some(true)); + hit.also.extend(local.iter().filter(|(p, _, _)| excludes(p)).map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); + hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().filter(|s| excludes(&s.3)).map(|(f, a, b, _)| (f.clone(), *a, *b))); + return Some(hit); + } + None +} + +/// What may follow a screen rect in an exact-pixel comparison: a corner, an edge or a size. +const RECT_PARTS: &[&str] = &[ + ".min", + ".max", + ".left_top()", + ".right_bottom()", + ".center()", + ".size()", + ".width()", + ".height()", + ".left()", + ".right()", + ".top()", + ".bottom()", +]; + +/// Whether a whitespace-free operand reads a screen rect: an identifier `rect`, or one that starts +/// with `rect_` or ends with `_rect` (a call to one included), taken whole or through +/// [`RECT_PARTS`]. Document geometry (artboards, `x0`/`y0` corners, a document's nodes) and a rect +/// passed on as an argument do not count. +fn names_rect(op: &str) -> bool { + if ["artboard", "doc", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { + return false; + } + // A ratio or a scaled value (`a.width() / b.width()`) is not a pixel size. + if op.trim_start_matches(['&', '*']).contains(['/', '*']) { + return false; + } + let b = op.as_bytes(); + let mut i = 0; + while i < b.len() { + if !is_ident(b[i]) || (i > 0 && is_ident(b[i - 1])) { + i += 1; + continue; + } + let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let w = &op[i..end]; + if w == "rect" || w.starts_with("rect_") || w.ends_with("_rect") { + let mut after = end; + if b.get(after) == Some(&b'(') { + after = matching(b, after).map_or(b.len(), |c| c + 1); + } + let rest = &op[after..]; + // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` + // is a ratio, not a pixel size. + // A `)` or `,` must belong to a tuple group: in `column_for_x(rect.min.x)` and + // `f(rect.min.x, 2)` it is part of a call's arguments. + let ends = |r: &str| { + let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); + r.is_empty() || r.starts_with(']') || (r.starts_with([')', ',']) && !closes_call(b, op.len() - r.len())) + }; + if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { + return true; + } + } + i = end; + } + false +} + +/// Whether the `)` or `,` at `close` is in the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) +/// rather than in a tuple or a parenthesized group. +fn closes_call(b: &[u8], close: usize) -> bool { + let mut depth = 0i32; + for i in (0..close).rev() { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth > 0 => depth -= 1, + b'(' => return i > 0 && (is_ident(b[i - 1]) || b[i - 1] == b'!' || b[i - 1] == b'>'), + b'[' | b'{' => return false, + _ => {} + } + } + false +} + +/// Whether a whitespace-free operand is only numbers, alone or in `pos2`, `vec2` or `Rect` builders. +fn only_numbers(op: &str) -> bool { + let mut rest = op.trim_start_matches('&').replace("egui::", "").replace("emath::", ""); + for builder in ["Rect::from_min_max", "Rect::from_min_size", "Rect::from_center_size", "Pos2::new", "Vec2::new", "pos2", "vec2", "Some"] { + rest = rest.replace(builder, ""); + } + let rest = rest.replace("f32", ""); + rest.bytes().any(|c| c.is_ascii_digit()) && rest.bytes().all(|c| c.is_ascii_digit() || b".,()-+_".contains(&c)) +} + +/// An assertion in a UI test that a rect, or a coordinate or size of one, equals numbers written out. +fn exact_pixels(v: &View) -> Vec { + if !contains(&v.file.m, b"egui") { + return vec![]; + } + v.asserts + .iter() + .filter_map(|a| { + let arg = |i: usize| a.args.get(i).map(|&(f, t)| norm(&v.file.m[f..t])); + let (l, r) = if a.name.ends_with("_eq") { + (arg(0)?, arg(1)?) + } else if PLAIN_ASSERTS.contains(&a.name.as_str()) { + let cond = arg(0)?; + let at = *top_level_at(&cond, "==").first()?; + (cond[..at].to_owned(), cond[at + 2..].to_owned()) + } else { + return None; + }; + let pixel = (names_rect(&l) && only_numbers(&r)) || (names_rect(&r) && only_numbers(&l)); + pixel.then(|| v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; fn ctx() -> Ctx { - Ctx { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + Ctx { ci_env: ["SET_IN_CI".to_owned()].into_iter().collect(), ..Ctx::default() } } /// The rule ids of `src`'s hits, as `(line, rule)`. @@ -3004,6 +3813,18 @@ mod tests { assert_eq!(census(subsets), [], "subset adapters pick a few entries"); } + #[test] + fn census_skips_derived_lookups_and_deep_nesting() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let offset = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(offset + lookup(n).unwrap(), n);\n }\n}\n"; + assert_eq!(census(offset), [], "an operator before the lookup derives a value"); + let qualified = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; + assert_eq!(census(qualified), [(2, "census")]); + let deep = + format!("#[test]\nfn t() {{\n for c in COLORS {{\n assert!({}c.is_some(){});\n }}\n}}\n", "(".repeat(66), ")".repeat(66)); + assert_eq!(census(&deep), [], "nesting deeper than the limit is not judged"); + } + #[test] fn census_skips_loops_bounded_by_zip_or_flat_map() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -3946,12 +4767,12 @@ mod tests { let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); - let ctx = Ctx { helpers, ci_env: HashSet::new() }; + let ctx = Ctx { helpers, ..Ctx::default() }; assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); assert_eq!(hits_in("crates/y/tests/it.rs", src, &ctx), [(8, "no-assertion")], "another crate's helper does not count"); let kit = asserting_helpers(&[("crates/testkit/src/lib.rs".to_owned(), src.to_owned()), ("crates/y/src/lib.rs".to_owned(), String::new())]); assert!(kit["crates/y"].contains("twice"), "testkit helpers count in every crate: {kit:?}"); - assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx::default()), [(8, "no-assertion")]); } #[test] @@ -3973,7 +4794,7 @@ mod tests { assert!(helpers["crates/x"].contains("same")); assert!(helpers["crates/x"].contains("twice")); assert!(!helpers["crates/x"].contains("idle")); - let ctx = Ctx { helpers, ci_env: HashSet::new() }; + let ctx = Ctx { helpers, ..Ctx::default() }; for call in ["same::(a, b)", "twice::>>(x)"] { let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); @@ -4201,7 +5022,9 @@ mod tests { #[test] fn only_failing_rules_fail_the_check() { let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); - assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep"]); + assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep", "reads-source", "never-run"]); + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn mac() {\n assert_eq!(f(), 1);\n}\n"; + assert!(finish(&lint_file("crates/x/src/tests.rs", mac, &ctx()), 0, 1, "base").is_err(), "never-run fails the check"); let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n"; @@ -4267,11 +5090,11 @@ mod tests { fn workflow_mentions_do_not_suppress_unset_gates() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + let ctx = Ctx { ci_env: upper_words(workflow).collect(), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "env-gate-unset")], "{workflow}"); } for workflow in ["env:\n MY_SAMPLES: fixtures", "run: |\n export MY_SAMPLES=fixtures", "with:\n env: |\n MY_SAMPLES=fixtures"] { - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + let ctx = Ctx { ci_env: upper_words(workflow).collect(), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); } } @@ -4313,10 +5136,10 @@ mod tests { let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); assert!(!helpers["crates/x"].contains("exercise"), "{helpers:?}"); - assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ci_env: HashSet::new() }), [(8, "no-assertion")]); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ..Ctx::default() }), [(8, "no-assertion")]); let both = src.replace("{ f(); }", "{ assert!(f()); }"); let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), both.clone())]); - assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ci_env: HashSet::new() }), []); + assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ..Ctx::default() }), []); } #[test] @@ -4385,7 +5208,7 @@ mod tests { fn single_letter_variables_set_in_ci_count() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n"; assert_eq!(hits(src), [(3, "env-gate-unset")]); - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() }; + let ctx = Ctx { ci_env: upper_words("env:\n X: 1\n").collect(), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); } @@ -4449,4 +5272,272 @@ mod tests { assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); } + + fn only(rule: &'static str, src: &str) -> Vec<(usize, &'static str)> { + hits(src).into_iter().filter(|h| h.1 == rule).collect() + } + + #[test] + fn mirrors_call_the_same_function_on_both_sides() { + let bad = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; + assert_eq!(only("mirror", bad), [(3, "mirror")]); + let written = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), Point::new(2.0, 4.0));\n}\n"; + assert_eq!(only("mirror", written), []); + let builders = "#[test]\nfn t() {\n assert_eq!(Some(area(a)), Some(4.0));\n assert_eq!(a.to_string(), b.to_string());\n}\n"; + assert_eq!(only("mirror", builders), [], "a builder or conversion on both sides"); + let same = "#[test]\nfn t() {\n assert_eq!(scale(p), scale(p));\n}\n"; + assert_eq!(only("mirror", same), [], "identical sides are self-compare's"); + let oracle = "#[test]\nfn t() {\n assert_eq!(actual::area(s), reference::area(s) * 2.0);\n}\n"; + assert_eq!(only("mirror", oracle), [], "two functions of the same name in different paths"); + let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; + assert_eq!(only("mirror", ne), [], "two inputs that must differ"); + let allowed = + "#[test]\nfn t() {\n // test-lint: allow mirror doubling is linear here\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; + assert_eq!(only("mirror", allowed), []); + } + + #[test] + fn echoes_check_only_constants_or_the_fixture() { + let constant = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert!(Kind::A != Kind::B);\n}\n"; + assert_eq!(only("constant-echo", constant), [(2, "constant-echo")]); + let fixture = + "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let n = 3;\n let _ = process(&input);\n assert_eq!(input.len(), n);\n}\n"; + assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); + let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; + assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let shadowed = "#[test]\nfn t() {\n let n = 1;\n for n in results() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", shadowed), [], "a loop binding that shadows the fixture"); + let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; + assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); + let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; + assert_eq!(only("fixture-only", borrowed), [], "an immutable binding of a mutable reference"); + let pattern = "#[test]\nfn t() {\n let (a, b) = split(4);\n assert_eq!(a, 2);\n assert_eq!(b, 2);\n}\n"; + assert_eq!(only("fixture-only", pattern), [], "a pattern binding of a result"); + let mixed = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert_eq!(zoom_in(1.0), 2.0);\n}\n"; + assert_eq!(only("constant-echo", mixed), [], "one real assertion keeps the test"); + let shadowed = "#[test]\nfn t() {\n let x = 1;\n let x = double(x);\n assert_eq!(x, 2);\n}\n"; + assert_eq!(only("fixture-only", shadowed), [], "the reaching binding is a call"); + let helper = "#[test]\nfn t() {\n assert_eq!(MAX, 4);\n check_all();\n}\n"; + assert_eq!(only("constant-echo", helper), [], "an asserting helper"); + let printed = "#[test]\nfn t() {\n let got = sample(1.0);\n assert_eq!(format!(\"{got:?}\"), \"1\");\n}\n"; + assert_eq!(hits(printed), [], "format! reads a local inside its string"); + let scoped = "#[test]\nfn t() {\n let result = compute();\n {\n let result = 0;\n consume(result);\n }\n assert_eq!(result, 1);\n}\n"; + assert_eq!(hits(scoped), [], "a binding in a block that has ended"); + let later = "#[test]\nfn t() {\n let x = compute();\n let y = x;\n let x = 0;\n assert_eq!(y, 2);\n assert_eq!(x, 0);\n}\n"; + assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one"); + } + + #[test] + fn never_run_tests_are_compiled_out_on_every_ci_target() { + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", mac), [(3, "never-run")]); + let module = "#[cfg(all(test, windows))]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", module, &ctx()).into_iter().filter(|h| h.1 == "never-run").count(), 1); + let file = "#![cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", file), [(3, "never-run")]); + let unix = "#[cfg(unix)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unix), [], "Linux runs it"); + let not_mac = "#[cfg(not(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", not_mac), []); + let raw = "#[cfg(target_os = r\"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", raw), [], "a raw string value"); + let feature = "#[cfg(feature = \"gpu\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", feature), [], "a feature CI may enable"); + let any = "#[cfg(any(target_os = \"macos\", target_os = \"linux\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", any), []); + let win = "#[cfg(windows)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("apps/vectorcraft/src/printing/tests.rs", win, &ctx()), [], "the printing workflow runs it on Windows"); + assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); + let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", other), [], "a cfg on another item"); + let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); + } + + #[test] + fn reads_source_spans_reach_a_path_on_a_later_line() { + let src = "#[test]\nfn t() {\n let s = fs::read_to_string(\n root.join(\"src/lib.rs\"),\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::ReadsSource).collect(); + assert_eq!(found.iter().map(|h| (h.line, h.first, h.last)).collect::>(), [(3, 3, 5)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the path alone"); + } + + #[test] + fn never_run_follows_the_cfg_of_the_mod_declaration() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod mac;\nmod plain;\n"), + ("crates/x/src/mac.rs", "mod inner;\n"), + ("crates/x/src/mac/inner.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec = ["crates/x/src/mac.rs", "crates/x/src/mac/inner.rs", "crates/x/src/plain.rs", "crates/x/tests/it.rs"] + .into_iter() + .map(String::from) + .collect(); + let cfgs = module_cfgs(&paths, &read); + assert_eq!(cfgs.get("crates/x/src/mac.rs").map(Vec::as_slice), Some(&["target_os=\"macos\"".to_owned()][..])); + assert!(cfgs.contains_key("crates/x/src/mac/inner.rs"), "inherited through mac.rs"); + assert!(!cfgs.contains_key("crates/x/src/plain.rs") && !cfgs.contains_key("crates/x/tests/it.rs")); + let ctx = Ctx { module_cfgs: cfgs, ..ctx() }; + let test = "#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + assert_eq!(hits_in("crates/x/src/mac/inner.rs", test, &ctx), [(4, "never-run")]); + assert_eq!(hits_in("crates/x/src/plain.rs", test, &ctx), []); + } + + #[test] + fn never_run_follows_the_cfg_around_the_mod_declaration() { + let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; + assert_eq!(declared_cfgs(inner, "child"), Some(vec!["target_os=\"macos\"".to_owned()])); + let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; + assert_eq!(declared_cfg_spans(block, "child", Some("platform")).map(|(p, _)| p), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfgs(block, "child"), None, "the nested declaration loads platform/child.rs"); + let nested = "#[cfg(windows)]\nmod child;\nmod other {\n mod child;\n}\n"; + assert_eq!(declared_cfgs(nested, "child"), Some(vec!["windows".to_owned()]), "other/child.rs is another file"); + assert_eq!(declared_cfg_spans(nested, "child", Some("other")).map(|(p, _)| p), Some(vec![])); + assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); + } + + #[test] + fn never_run_hits_cover_the_attribute_that_turns_the_test_off() { + let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line)); + assert_eq!(hit, Some((3, 4))); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let helper = + "#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\n\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", helper, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[3].into_iter().collect())), "a helper between the cfg and the test"); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "a comment inside the predicate"); + } + + #[test] + fn never_run_counts_a_changed_mod_declaration_in_another_file() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let ctx = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/child.rs", test, &ctx); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + let changed = |lines: &[usize]| BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))]); + assert!(touches_in(hit, &changed(&[1])), "the cfg on the declaration changed"); + assert!(!touches_in(hit, &changed(&[2])), "only the declaration line changed"); + } + + #[test] + fn never_run_resolves_inline_parents_and_several_owners() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(windows)]\nmod platform {\n mod child;\n}\n#[cfg(target_os = \"macos\")]\nmod shared;\n"), + ("crates/x/src/main.rs", "mod shared;\n"), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec = ["crates/x/src/platform/child.rs", "crates/x/src/shared.rs"].into_iter().map(String::from).collect(); + let cfgs = module_cfgs(&paths, &read); + assert_eq!(cfgs.get("crates/x/src/platform/child.rs").map(Vec::as_slice), Some(&["windows".to_owned()][..])); + assert!(!cfgs.contains_key("crates/x/src/shared.rs"), "main.rs compiles it on every target"); + } + + #[test] + fn exact_pixels_compare_a_rect_with_numbers() { + let ui = |body: &str| format!("use egui::Rect;\n#[test]\nfn t() {{\n {body}\n}}\n"); + let px = |body: &str| only("exact-pixel", &ui(body)); + assert_eq!(px("assert_eq!(button_rect.min.x, 12.0);"), [(4, "exact-pixel")]); + assert_eq!(px("assert_eq!(resp.rect, Rect::from_min_size(pos2(0.0, 20.0), vec2(80.0, 24.0)));"), [(4, "exact-pixel")]); + assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); + assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); + assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio"); + assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); + assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); + assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); + assert_eq!(px("assert_eq!(doc.artboards[1].rect.width(), 100.0);"), [], "document geometry in a UI test"); + assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); + assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); + assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed on"); + assert_eq!(px("assert_eq!(cell_at(button_rect.min.x, 3), 2);"), [], "a coordinate passed on before another argument"); + assert_eq!(px("assert_eq!((button_rect.min.x, button_rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); + let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; + assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); + } + + #[test] + fn reads_source_covers_read_to_string_of_rust_files() { + let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", read), [(3, "reads-source")]); + let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", data), []); + let commented = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"src/lib.rs\" */ \"fixture.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", commented), [], "a path in a comment"); + let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", dir), [], "a directory whose name ends in .rs"); + let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/input.json\", \"fixtures.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [], "a format argument that ends in .rs"); + let formatted_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted_rs), [(3, "reads-source")]); + let joined_json = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures.rs\", root)).join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined_json), [], "a join after the format call ends the path"); + let joined_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures\", root)).join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined_rs), [(3, "reads-source")]); + } + + #[test] + fn weak_predicates_keep_the_polarity_of_a_negation() { + assert!(weak_predicate("parse(input).is_ok()")); + assert!(weak_predicate("!xs.is_empty()")); + assert!(!weak_predicate("!parse(input).is_ok()"), "a rejection"); + assert!(!weak_predicate("!x.is_some()"), "an absence"); + assert!(weak_predicate("!!x.is_some()")); + } + + #[test] + fn never_run_reads_escaped_values_as_unknown() { + let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", escaped), []); + } + + #[test] + fn never_run_takes_every_declaration_of_a_module() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n#[cfg(unix)]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let both = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/child.rs", test, &both), [], "the unix declaration builds it on Linux"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let windows = Ctx { module_cfgs, module_sites, ..ctx() }; + assert_eq!(hits_in("crates/x/src/child.rs", test, &windows), [(2, "never-run")]); + } + + #[test] + fn never_run_does_not_count_a_cfg_true_on_every_target() { + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(unix)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let unix = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/child.rs", test, &unix); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + let changed = BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some([1].into_iter().collect()))]); + assert!(!touches_in(hit, &changed), "cfg(unix) holds on Linux and FreeBSD"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let mac = Ctx { module_cfgs, module_sites, ..ctx() }; + let found = lint_file("crates/x/src/child.rs", test, &mac); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches_in(hit, &changed), "a macOS-only module cfg"); + } }