From f5962eb16158d9ebec028b9df05ca3a06cd1340d Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:32:27 +0530 Subject: [PATCH 01/17] A right-click on a Glyphs cell inserts or applies that glyph. The menu item does what a double-click does, and stays disabled when the glyph cannot be applied. Co-authored-by: Cursor --- crates/ui-egui/src/panels/glyphs.rs | 35 +++++++- crates/ui-egui/src/panels/glyphs/tests.rs | 101 ++++++++++++++++++++++ docs/gaps.md | 2 + 3 files changed, 134 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index e639ae3ea4..4d60dd59ef 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -15,6 +15,8 @@ //! as one of its alternates in its word. A glyph no feature reaches whose name does not belong to //! another letter is applied as a glyph choice, which may not join. Other glyphs are drawn dimmed, //! and their notes say why they cannot be applied to the selection. +//! A right-click on a character offers Insert Glyph. A right-click on a glyph without a +//! character offers Apply Alternate. Both use the same text target as double-click or Enter. //! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph //! form ([`menu_rows`]). //! After the framework's categories, the Show menu lists the OpenType categories the browsed font @@ -24,10 +26,10 @@ use std::collections::HashSet; use std::sync::Arc; -use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsWords}; +use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphCellMenu, GlyphSource, GlyphsPanel, GlyphsWords}; use craft::keymap::CommandRef; -use craft::ui::contract::Bind; -use craft::ui::menu::PanelRow; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::Env; use egui::{Color32, ColorImage, Ui}; @@ -483,7 +485,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if out.font_changed { app.ui.glyphs_font = Some((family, style)); } - if let Some(cell) = out.activated { + let menu_cell = out + .menu + .as_ref() + .filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)) + .map(|menu| menu.cell); + if let Some(cell) = menu_cell.or(out.activated) { activate(app, cell); } if let Some(pick) = out.alternate { @@ -491,6 +498,26 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Offer the action for the clicked cell using the grid's face and text context for this pass. +fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphCellMenu) -> bool { + let Some(face) = &source.face else { return false }; + let (label, enabled) = match menu.cell { + GlyphCell::Char(c) => (tl!("Insert Glyph"), source.listing.is_none() && gid_of(face, c).is_some()), + GlyphCell::Glyph(gid) => { + let applies = match &source.listing { + Some(listing) => listing.variants.iter().any(|variant| variant.gid == gid), + None => source.fit.as_ref().is_some_and(|fit| fit.pick(face, gid).is_some()), + }; + (tl!("Apply Alternate"), applies) + } + _ => return false, + }; + Menu::context(label, &menu.opener) + .show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran) + .inner + .unwrap_or(false) +} + /// A double-click or Enter on `cell`: insert the character (its letter for an Arabic presentation /// form), or put the glyph on the selected character. pub(crate) fn activate(app: &mut VectorcraftApp, cell: GlyphCell) { diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index 0886975276..a4f6635324 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -1102,3 +1102,104 @@ fn the_grid_lists_the_same_cells_from_the_character_list_read_once() { assert!(list.iter().all(|c| matches!(c, GlyphCell::Glyph(_))), "no character is listed"); assert!(!list.is_empty(), "the glyphs are listed by glyph id"); } + +/// The name a glyph-id cell shows, as the grid names it. +fn glyph_cell_name(face: &vectorcraft_text::FontFace, gid: u32) -> String { + let name = face.glyph_name(gid).unwrap_or_else(|| format!("gid {gid}")); + format!("{name}, glyph {gid}") +} + +/// A right-click on an encoded cell offers Insert Glyph, and choosing it inserts that character in one undo step. +#[test] +fn right_clicking_a_glyph_cell_offers_insert_glyph() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let (mut app, id) = editing("a"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": ALIASED_JOINING_FAMILY})).unwrap(); + select(&mut app, 1, 1); + crate::panels::character::end_typing(&mut app); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(panel.menu_item_enabled("Insert Glyph")); + assert!(!panel.shows("Apply Alternate"), "a character cell offers Insert Glyph"); + panel.click_menu_item("Insert Glyph"); + { + let mut app = panel.app(); + crate::panels::character::end_typing(&mut app); + } + let app = panel.app(); + assert_eq!(plain_of(&app, id), "aB"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(plain_of(&panel.app(), id), "a"); +} + +#[test] +fn insert_glyph_is_disabled_without_a_text_target() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(!panel.menu_item_enabled("Insert Glyph")); +} + +/// In Alternates for Selection a right-click offers Apply Alternate in one undo step. +#[test] +fn right_clicking_an_alternate_cell_offers_apply_alternate() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 2, 4); + show_category(&mut app, "Alternates for Selection"); + let list = listed(&mut app, "Alternates for Selection"); + let GlyphCell::Glyph(gid) = list[2] else { panic!("an alternate is a glyph") }; + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let name = glyph_cell_name(&face, gid); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(panel.menu_item_enabled("Apply Alternate")); + assert!(!panel.shows("Insert Glyph"), "an alternate cell offers Apply Alternate"); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(glyph_ids(&app, &json!(id)), [g('B'), g('x'), g('M')]); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&panel.app(), &json!(id)), [g('B'), g('u'), g('M')]); +} + +/// A glyph a double-click would only explain has a disabled menu item, and choosing it changes nothing. +#[test] +fn a_glyph_that_cannot_be_applied_disables_the_menu_item() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let (mut app, id) = editing("\u{0627}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 0, 2); + show_category(&mut app, "stylisticAlternates"); + let gid = u32::from(source_sans_gid('w').expect("a glyph")); + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + assert!(cell_info(&mut app, GlyphCell::Glyph(gid)).dimmed, "w is not an alternate of alef"); + let name = glyph_cell_name(&face, gid); + let (undo, status, plain) = (undo_len(&app), app.ui.status.clone(), glyph_ids(&app, &json!(id))); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(!panel.menu_item_enabled("Apply Alternate")); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(glyph_ids(&app, &json!(id)), plain); + assert_eq!(undo_len(&app), undo); + assert_eq!(app.ui.status, status); +} diff --git a/docs/gaps.md b/docs/gaps.md index 35587afab4..02049a64b7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -551,6 +551,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- Glyphs cells have an item context menu. A character offers **Insert Glyph** at the Type caret or in selected text. A glyph without a mapped character offers **Apply Alternate** for the character selected with the Type tool. The menu uses the same actions as Enter and double-click and disables the item when its text target cannot accept the glyph. + - **Implemented and tested (2026-11-21):** Properties panel Quick Actions follow every selected object. Ungroup (`object.ungroup`) is offered when any selected object is a group, including several groups, a group selected after a path, and a group that holds another group. Isolate Group (`object.isolate`) is offered only when that one group is the whole selection. Unite (`object.pathfinder.unite`) appears only for selections of at least two objects, each a non-guide path or a compound path. It appears alongside Group and Make Clipping Mask. Headless regressions: `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group` and `several_paths_offer_group_clipping_mask_and_unite`. Other G12 gaps remain; scores and estimates unchanged. - **Implemented and tested (2026-11-21):** Document Info's panel menu Selection Only (`ui.docInfo.selectionOnly`; kept in memory for the session, not stored) asks `document.info` for the selection: object counts cover the selected nodes and their descendants, and with no artwork selected it shows `(No artwork selected)` instead of the document's counts, while artboards the Artboard tool has selected still show under Document. With the item off, counts stay for the whole document. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard` and `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. From 010367e39efd0b05b9b425b00b9e13629657f02c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:46:09 -0800 Subject: [PATCH 02/17] Tests: allow the 26 Windows and macOS tests that CI never runs Each test that a cfg limits to Windows, macOS or a case-insensitive file system gets a `test-lint: allow never-run` line naming its platform, so `cargo xtask test-lint` no longer reports them. The tests are unchanged and still run on their own platform. --- apps/vectorcraft-cli/src/perf.rs | 2 ++ apps/vectorcraft/src/mac_color_space.rs | 3 +++ apps/vectorcraft/src/mac_fonts.rs | 2 ++ apps/vectorcraft/src/open_documents.rs | 1 + crates/color/src/cms/tests.rs | 1 + crates/engine/src/file_access.rs | 2 ++ crates/engine/src/tests/fontfiles.rs | 1 + crates/engine/src/tests/link_paths.rs | 3 +++ crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_io.rs | 3 +++ crates/engine/src/tests/store.rs | 1 + crates/pdf/tests/gradient_forms.rs | 3 +++ crates/text/src/tests/sysfonts.rs | 3 +++ 13 files changed, 26 insertions(+) diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index e533d00b73..47686f6c2f 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -629,6 +629,7 @@ mod tests { /// On Windows `busy_cores` gives a number between 0 and the cores. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_how_many_cores_are_busy() { let cores = std::thread::available_parallelism().map_or(1, |c| c.get()); @@ -639,6 +640,7 @@ mod tests { /// On Windows `rss_mb` gives this process's working set: more than 0 MB and less than /// 10,000 MB. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_the_working_set() { let mb = rss_mb().map(|(mb, _)| mb); diff --git a/apps/vectorcraft/src/mac_color_space.rs b/apps/vectorcraft/src/mac_color_space.rs index 3fa1394804..ccdb340ec2 100644 --- a/apps/vectorcraft/src/mac_color_space.rs +++ b/apps/vectorcraft/src/mac_color_space.rs @@ -99,6 +99,7 @@ mod tests { } /// A layer without a color space is tagged sRGB once; the second call leaves it as it is. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn an_untagged_layer_becomes_srgb() { let layer = CAMetalLayer::new(); @@ -110,6 +111,7 @@ mod tests { } /// A layer with a color space of its own keeps it. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_layer_with_a_color_space_keeps_it() { let layer = CAMetalLayer::new(); @@ -121,6 +123,7 @@ mod tests { /// The Metal layer is found as the view's layer or as one of its sublayers, and only Metal /// layers are returned. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn metal_layers_are_found_under_the_view_layer() { let metal = CAMetalLayer::new(); diff --git a/apps/vectorcraft/src/mac_fonts.rs b/apps/vectorcraft/src/mac_fonts.rs index 36223c559f..4e9f996d62 100644 --- a/apps/vectorcraft/src/mac_fonts.rs +++ b/apps/vectorcraft/src/mac_fonts.rs @@ -52,6 +52,7 @@ mod tests { use objc2_core_text::{CTFontManagerRegisterFontsForURL, CTFontManagerScope, CTFontManagerUnregisterFontsForURL}; /// CoreText lists the installed fonts, by their files' full paths. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn coretext_lists_the_installed_font_files() { let files = super::font_files(); @@ -61,6 +62,7 @@ mod tests { /// A font registered with CoreText from another folder, as apps and font managers register /// fonts, is listed while it is registered. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn fonts_registered_from_other_folders_are_listed() { let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap(); diff --git a/apps/vectorcraft/src/open_documents.rs b/apps/vectorcraft/src/open_documents.rs index 67f409b0e8..a126618ee0 100644 --- a/apps/vectorcraft/src/open_documents.rs +++ b/apps/vectorcraft/src/open_documents.rs @@ -94,6 +94,7 @@ mod tests { use super::*; /// Files queue until the UI takes them; URLs that aren't files are left out. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn opened_files_wait_for_the_ui() { let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.svg")).unwrap(); diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 761a121191..a6552029b2 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -323,6 +323,7 @@ fn bad_icc_rejected() { } #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn loads_system_cmyk_icc() { let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc"); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index ce6023fb4e..7daa75e0ae 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -1390,6 +1390,7 @@ mod tests { } #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_ignores_case_and_refuses_devices() { let (base, roots) = folders("case"); @@ -1471,6 +1472,7 @@ mod tests { } #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_refuses_a_stream_inside_a_write_root() { let (base, roots) = folders("streams"); diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index 52a8ff08a3..e90aec1df9 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -417,6 +417,7 @@ fn a_search_skips_font_files_too_large_to_add() { /// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its /// resource fork, which only macOS keeps. A search finds it, and Add Fonts copies it with its fork. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn suitcase_fonts_are_found_and_copied_with_their_fork() { use vectorcraft_testkit::fonts::{renamed, suitcase_fork}; diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index e39cf66896..ebc2b5d1c6 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -189,6 +189,7 @@ fn a_path_on_a_mapped_drive_is_on_the_share_behind_it() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_a_mapped_drives_share_are_followed() { use crate::cmd::fileio::{document_path_with, share_of}; @@ -208,6 +209,7 @@ fn links_on_a_mapped_drives_share_are_followed() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_a_drive_mapped_to_another_share_are_not_followed() { use crate::cmd::fileio::{document_path_on, drive_share_of, share_of}; @@ -228,6 +230,7 @@ fn links_on_a_drive_mapped_to_another_share_are_not_followed() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_the_documents_share_or_this_computer_are_followed() { use crate::cmd::fileio::{document_path_on, drive_share_of, share_of}; diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 836daf8b05..f2858aec25 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4110,6 +4110,7 @@ fn a_removal_deletes_only_folders_it_marked() { /// Windows keeps a file another program holds open without delete sharing, so the last grant can't /// be removed by deleting `grants.json`. #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { use std::os::windows::fs::OpenOptionsExt; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 1e2823aaa4..b5d7fe7ded 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1020,6 +1020,7 @@ fn script_file_alias_is_not_left_behind_a_folder_replaced_by_a_link() { /// Where a hidden file is not one whose name starts with a dot, setting `hidden` and `createAlias` /// set `error` and change nothing. #[cfg(not(unix))] +// test-lint: allow never-run Windows only (not Unix); CI runs tests on Linux and FreeBSD #[test] fn script_file_hidden_and_aliases_are_refused_off_unix() { let base = folder("hiddenoff"); @@ -1637,6 +1638,7 @@ fn script_file_rename_does_not_take_the_settings_folders_name() { /// Where case does not matter, a folder named in another case is still the folder that holds the /// settings folder, or the settings folder itself: it is not renamed or removed. #[cfg(any(windows, target_os = "macos"))] +// test-lint: allow never-run needs a case-insensitive file system (Windows, macOS); CI runs tests on Linux and FreeBSD #[test] fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() { let base = folder("moveupcase"); @@ -1660,6 +1662,7 @@ fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() /// Where case does not matter, a folder renamed under its name in another case still moves the open /// objects of the files in it: changes are written under the new name, not lost at the old one. #[cfg(any(windows, target_os = "macos"))] +// test-lint: allow never-run needs a case-insensitive file system (Windows, macOS); CI runs tests on Linux and FreeBSD #[test] fn script_file_rename_of_a_folder_named_in_another_case_moves_its_open_files() { let base = folder("renamecase"); diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index dfc603dc59..380126535f 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -79,6 +79,7 @@ fn file_names(dir: &std::path::Path) -> Vec { /// Windows does not allow replacing a read-only file or writing into it, so the write fails. #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn a_rename_that_only_changes_case_and_cannot_be_written_keeps_the_old_file() { let root = fresh_dir("rename-case-fails"); diff --git a/crates/pdf/tests/gradient_forms.rs b/crates/pdf/tests/gradient_forms.rs index 7373ec8494..a904935fe5 100644 --- a/crates/pdf/tests/gradient_forms.rs +++ b/crates/pdf/tests/gradient_forms.rs @@ -159,6 +159,7 @@ mod quartz { } /// Quartz places RGB and CMYK radial centres, edges and masks with their translated art. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_off_centre_radials_in_transparency_and_layer_forms() { for mode in [ColorMode::Rgb, ColorMode::Cmyk] { @@ -179,6 +180,7 @@ mod quartz { } /// Quartz retains the linear ramp's direction inside forms on a translated artboard. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_linear_gradient_directions_in_forms() { for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Mask | Form::Knockout)) { @@ -190,6 +192,7 @@ mod quartz { } /// A gradient's stop-opacity mask remains aligned with its colour through nested forms. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_gradient_stop_opacity_aligned_inside_nested_forms() { let (mut d, opts) = fixture(Form::Nested, GradientKind::Radial, ColorMode::Rgb, Point::ORIGIN); diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 261cc1c54c..32cb04c30c 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -805,6 +805,7 @@ fn a_resource_fork_gives_up_its_font_files() { /// Office's fonts: a file with nothing in it but a resource fork holding the fonts, named /// without an extension. Only macOS keeps a resource fork in a file. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn the_scan_reads_suitcase_fonts() { let dir = font_dir("suitcase"); @@ -1011,6 +1012,7 @@ fn a_search_reads_at_most_its_share_of_a_font_file() { /// A search reads a suitcase font only when its whole resource fork fits in the 8 MB a search reads /// of one file. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_search_reads_a_suitcase_font_only_within_its_share() { use crate::fontdb::file_face_names_within; @@ -1036,6 +1038,7 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { /// A suitcase font read for one search (Retype) is read no further than one byte past the limit, /// and the bytes read are counted. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); From e7715d880be808cce91626a1937c4c053ac776c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:21:01 -0800 Subject: [PATCH 03/17] xtask: test-lint round trips, mod scopes, never-run allows and doc names - census: a lookup counts as a round trip only when its arguments read the loop entry, so `lookup("baseline") == expected` is a real check. - never-run: a `mod child;` inside an inline `mod platform { ... }` loads platform/child.rs, so it no longer gives its cfg to src/child.rs. - never-run: an allow covers only the test it sits above; a module cfg no longer stretches it over the next test in the module. - exact-pixel: document geometry is matched by identifier (`doc`, `document`, `doc_*`, `*_doc`), so `dock_rect` is checked. --- xtask/src/test_lint.rs | 70 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 61 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index a5fc3e4bbc..9b1f2f2d14 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -240,6 +240,10 @@ pub struct Hit { /// only near `line`. pub first: usize, pub last: usize, + /// The first line an allow comment may sit on to exempt the hit, when it differs from `first`: + /// a `never-run` hit spans an enclosing module's `cfg`, but only an allow at the test's own + /// attributes exempts it. + pub allow_from: Option, } impl Hit { @@ -1183,7 +1187,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, allow_from: None } } fn test_at(&self, pos: usize) -> &str { @@ -1223,7 +1227,7 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { hits.extend(reads_source_hits(&file)); let allows = allows(src, &file.m); hits.retain(|h| { - let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.allow_from.unwrap_or(h.first) }; !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) }); hits.sort(); @@ -1612,7 +1616,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { 1 => args.first().is_some_and(|a| weak_predicate(a)), 2 if name.ends_with("_ne") => false, 2 => match args { - [a, b, ..] => (round_trip_call(a) && is_entry(b, var)) || (round_trip_call(b) && is_entry(a, var)), + [a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)), _ => false, }, _ => false, @@ -1621,8 +1625,10 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { /// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole /// name and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so -/// the operand is the parsed or looked-up entry itself and not a value derived from it. -fn round_trip_call(op: &str) -> bool { +/// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's +/// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is +/// not a round trip of the entry. +fn round_trip_call(op: &str, var: &str) -> bool { let mut op = op.trim_start_matches(['&', '*']); loop { let wraps = |w: &&str| op.starts_with(*w) && matching(op.as_bytes(), w.len() - 1) == Some(op.len() - 1); @@ -1636,11 +1642,21 @@ 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) - && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) + && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) }) }) } +/// Whether `s` contains the identifier `var` as a whole word. +fn reads_ident(s: &str, var: &str) -> bool { + let b = s.as_bytes(); + !var.is_empty() + && s.match_indices(var).any(|(at, _)| { + let end = at + var.len(); + !(at > 0 && is_ident(b[at - 1])) && !b.get(end).copied().is_some_and(is_ident) + }) +} + /// Whether a (whitespace-free) call suffix only unwraps or copies the call's result. fn only_unwraps(mut rest: &str) -> bool { const UNWRAPS: &[&str] = &[".unwrap()", ".ok()", ".copied()", ".cloned()", ".clone()", ".as_ref()", ".as_deref()", "?"]; @@ -3283,7 +3299,7 @@ fn declared_cfgs(src: &str, name: &str) -> Option> { let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') + &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') && !in_inline_mod(&m, at) })?; let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let mut out = vec![]; @@ -3298,6 +3314,20 @@ fn declared_cfgs(src: &str, name: &str) -> Option> { Some(out) } +/// Whether `at` in the masked text `m` is inside an inline `mod { … }`, where a `mod x;` +/// loads a file under that module's directory instead of a sibling file. +fn in_inline_mod(m: &[u8], at: usize) -> bool { + m[..at].iter().enumerate().filter(|&(_, &c)| c == b'{').any(|(open, _)| { + if !matching(m, open).is_some_and(|close| close > at) { + return false; + } + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident) + }) +} + /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { @@ -3335,6 +3365,7 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { 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(", "))); if let Some(at) = first_attr { + hit.allow_from = Some(hit.first); hit.first = hit.first.min(v.file.lines.of(at)); } return Some(hit); @@ -3363,7 +3394,11 @@ const RECT_PARTS: &[&str] = &[ /// [`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)) { + if ["artboard", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { + return false; + } + let document = |w: &str| w == "doc" || w == "document" || w.starts_with("doc_") || w.ends_with("_doc"); + if op.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(document) { return false; } let b = op.as_bytes(); @@ -3459,6 +3494,15 @@ mod tests { assert_eq!(hits(mixed), [(3, "all-unguarded")]); } + #[test] + fn census_round_trips_look_up_the_entry() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n"; + assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); + let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(derived), [(2, "census")]); + } + #[test] fn census_loops_over_whole_tables_are_reported() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -5041,7 +5085,11 @@ mod tests { 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_cfgs(block, "child"), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfgs(block, "child"), None, "that `mod child;` loads platform/child.rs"); + let both = "#[cfg(windows)]\nmod platform {\n mod child;\n}\nmod child;\n"; + assert_eq!(declared_cfgs(both, "child"), Some(vec![]), "the root declaration, not the one in platform"); + let gated = "#[cfg(windows)]\nconst _: () = {\n mod child;\n};\n"; + assert_eq!(declared_cfgs(gated, "child"), Some(vec!["windows".to_owned()]), "a gated block that is not a module"); assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); } @@ -5052,6 +5100,9 @@ mod tests { let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line)); assert_eq!(hit, Some((1, 4))); assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let two = "#[cfg(target_os = \"macos\")]\nmod mac {\n // test-lint: allow never-run checks the macOS menu bar\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n"; + let left: Vec = lint_file("crates/x/src/tests.rs", two, &ctx()).iter().filter(|h| h.rule == Rule::NeverRun).map(|h| h.line).collect(); + assert_eq!(left, [9], "an allow above one test leaves the next one reported"); } #[test] @@ -5067,6 +5118,7 @@ mod tests { 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!(dock_rect.width(), 120.0);"), [(4, "exact-pixel")], "a name that only starts with doc"); 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"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; From 2c1278280b374bfad13d86c458633825668f42bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:55:37 -0800 Subject: [PATCH 04/17] xtask: test-lint cfg_attr, #[path] and inline-module gates, changed parent declarations - never-run reads cfg(...) nested in cfg_attr, and blanks comments in cfg predicates. - A file's inherited gates come from the mod declaration that loads it: #[path] overrides are resolved, and a declaration inside an inline module gates the file under that module's directory. Several declarations of one file join with any(...). - In changed-files mode, a change to a parent mod declaration or its cfg counts for the never-run hits of the files it loads, including files that did not change. - Round trips reject arithmetic before the lookup (1 + lookup(k)). - reads-source ignores Rust paths that occur only in comments. - if let and while let bindings shadow outer bindings only inside their body. - The mirror allow test now starts from an assertion that is reported. --- xtask/src/test_lint.rs | 394 ++++++++++++++++++++++++++++++++++------- 1 file changed, 327 insertions(+), 67 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 9b1f2f2d14..168dd8ff79 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -262,6 +262,15 @@ pub struct Ctx { pub module_cfgs: HashMap>, } +/// Whether a parent file's changed lines touch a `mod` declaration or `cfg` attribute that `gates` +/// came from. +fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap>>) -> bool { + gates + .into_iter() + .flat_map(|g| &g.sources) + .any(|(parent, lines)| changed.get(parent).is_some_and(|c| c.as_ref().is_none_or(|set| lines.iter().any(|l| set.contains(l))))) +} + /// 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); @@ -287,18 +296,36 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { 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 present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - let module_cfgs = module_cfgs(&present, &|p| read_small(root, p)); + // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn + // their tests off without a change to them. + let module_dirs: Vec = present + .iter() + .map(|p| { + let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); + if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } + }) + .collect(); + let below: Vec = + files.iter().filter(|p| !changed.contains_key(*p) && module_dirs.iter().any(|d| p.starts_with(d.as_str()))).cloned().collect(); + let gated: Vec = present.iter().chain(&below).cloned().collect(); + let gates = module_gates(&gated, &|p| read_small(root, p)); + let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { + let parent_changed = gate_changed(gates.get(&path), &changed); for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed) { counted.push(hit); } else { older += 1; } } } + for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + let Some(src) = read_small(root, path) else { continue }; + counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun)); + } finish(&counted, older, present.len(), &base) } @@ -1624,7 +1651,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { } /// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole -/// name and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so +/// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so /// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's /// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is /// not a round trip of the entry. @@ -1642,6 +1669,7 @@ fn round_trip_call(op: &str, var: &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) + && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',']) && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) }) }) @@ -2930,6 +2958,8 @@ fn reads_source_hits(file: &File) -> Vec { return vec![]; } let m = &file.m; + // The source with comments blanked and literals kept: a path in a comment is not read. + let code = mask_parts(&String::from_utf8_lossy(file.src), true, false); let mut out = vec![]; let words_and_notes = [ (&b"include_str"[..], "includes a .rs file as text"), @@ -2940,7 +2970,7 @@ fn reads_source_hits(file: &File) -> Vec { 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]); + let arg = norm(&code[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); @@ -3109,6 +3139,20 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option before || block_close(body, at) < before { continue; @@ -3130,6 +3174,22 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option<(usize, usize)> { + let mut depth = 0usize; + for (i, &c) in body.iter().enumerate().skip(from) { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth = depth.saturating_sub(1), + b'{' if depth == 0 => return matching(body, i).map(|close| (i, close)), + b';' | b'}' if depth == 0 => return None, + _ => {} + } + } + None +} + /// 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; @@ -3240,23 +3300,67 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } -/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with -/// the offset of its attribute. `m` is the masked text of `src`. +/// A `cfg` attribute found by [`cfg_attrs`]. +struct CfgAttr { + pred: String, + /// The offset of the attribute's `cfg` or `cfg_attr`. + at: usize, + /// The offset of its closing `]`. + end: usize, + inner: bool, +} + +/// The `#[cfg(…)]`, `#![cfg(…)]` and `#[cfg_attr(, cfg(…))]` attributes in `m[from..to]`, +/// sorted by offset. A nested `cfg` becomes `any(not(),)`: it removes the item +/// only when the condition holds. `m` is the masked text of `src`. +fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + for (word, nested) in [(&b"cfg"[..], false), (&b"cfg_attr"[..], true)] { + for at in words(m, word, from, to) { + 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 + word.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 text = pred_text(&src[open + 1..close]); + if !nested { + out.push(CfgAttr { pred: text, at, end, inner }); + continue; + } + let cuts = top_level_at(&text, ","); + let Some(&first) = cuts.first() else { continue }; + let cond = &text[..first]; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + if let Some(p) = text.get(start..cut).and_then(|p| p.strip_prefix("cfg(")).and_then(|p| p.strip_suffix(')')) { + out.push(CfgAttr { pred: format!("any(not({cond}),{p})"), at, end, inner }); + } + start = cut + 1; + } + } + } + out.sort_by_key(|a| a.at); + out +} + +/// A `cfg` predicate's source text without whitespace or comments. Masking would also blank the +/// string literals `target_os = "macos"` needs, so only comments are blanked. +fn pred_text(src: &[u8]) -> String { + norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) +} + +/// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the +/// offset of its attribute. `m` is the masked text of `src`. fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, 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; - } + for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { // An inner attribute covers the file (or the module) it opens. let enclosing = m[..at].iter().rposition(|&c| c == b'{'); @@ -3270,8 +3374,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - // The source text: masking blanks the string literals `target_os = "macos"` needs. - out.push((norm(&src[open + 1..close]), at)); + out.push((pred, at)); } } out @@ -3292,58 +3395,168 @@ fn module_parent(path: &str) -> Option<(&str, Vec)> { 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. -fn declared_cfgs(src: &str, name: &str) -> Option> { - let m = mask(src); - let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { - let start = skip_ws(&m, at + 3); - let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') && !in_inline_mod(&m, at) - })?; - let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let mut out = 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() { - out.push(norm(&src.as_bytes()[open + 1..close])); - } - } - out.extend(cfgs_over(&m, src.as_bytes(), decl).into_iter().map(|(p, _)| p)); - Some(out) +/// Where a module file is loaded from: the file `path`, the name `name` it declares by default and +/// the inline modules `chain` (outermost first) its declaration must sit in. +struct Loaded<'a> { + path: &'a str, + name: &'a str, + chain: &'a [String], } -/// Whether `at` in the masked text `m` is inside an inline `mod { … }`, where a `mod x;` -/// loads a file under that module's directory instead of a sibling file. -fn in_inline_mod(m: &[u8], at: usize) -> bool { - m[..at].iter().enumerate().filter(|&(_, &c)| c == b'{').any(|(open, _)| { - if !matching(m, open).is_some_and(|close| close > at) { - return false; +/// The `cfg` predicates under which `src`, the file `parent`, loads `want`: those on the +/// `mod ;` declarations that load it (by name, or through a `#[path]` override) and on the +/// items, inline modules and file around them, with the 1-based lines of those declarations and +/// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None` +/// when `src` loads no such file. +fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Vec)> { + let m = mask(src); + let lines = Lines::new(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let (mut each, mut at_lines) = (vec![], vec![]); + for at in words(&m, b"mod", 0, m.len()) { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, at) != want.chain { + continue; } - let head = m[..open].trim_ascii_end(); - let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); - let before = head[..head.len() - name].trim_ascii_end(); - name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident) + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let loads = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => { + // A `#[path]` outside inline modules is relative to the file's directory; inside them, + // to the inline modules' directory under the file's module. + let mut base = dir.to_owned(); + if !want.chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in want.chain { + base = join_path(&base, seg); + } + join_path(&base, &rel) == want.path + } + None => &m[start..end] == want.name.as_bytes(), + }; + if !loads { + continue; + } + // Inner attributes cover the file, and [`cfgs_over`] reads them. + let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); + at_lines.push(lines.of(at)); + at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); + let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); + for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + preds.push(p); + at_lines.push(lines.of(a)); + } + each.push(preds); + } + let preds = match each.len() { + 0 => return None, + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::>().join(","))], + }; + Some((preds, at_lines)) +} + +/// The string value of a `#[path = "…"]` attribute in `m[from..to]`. +fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { + words(m, b"path", from, to).into_iter().find_map(|at| { + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + let eq = skip_ws(m, at + 4); + let q = skip_ws(m, eq + 1); + if !attr || m.get(eq) != Some(&b'=') || m.get(q) != Some(&b'"') { + return None; + } + let close = find(m, b"\"", q + 1)?; + Some(String::from_utf8_lossy(&src[q + 1..close]).into_owned()) }) } +/// `rel` joined to the directory `base`, with `.` and `..` resolved. +fn join_path(base: &str, rel: &str) -> String { + let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); + for seg in rel.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +/// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost +/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. +fn inline_mods(m: &[u8], at: usize) -> Vec { + m[..at] + .iter() + .enumerate() + .filter(|&(open, &c)| c == b'{' && matching(m, open).is_some_and(|close| close > at)) + .filter_map(|(open, _)| { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + (name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident)) + .then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()) + }) + .collect() +} + /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() +} + +/// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares +/// them, the lines of those declarations and attributes. +#[derive(Default)] +struct Gates { + preds: Vec, + sources: Vec<(String, Vec)>, +} + +/// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that +/// may declare its module and, when none does, in the files above them through inline modules +/// (`mod platform { mod child; }` loads `platform/child.rs`). +fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut preds, mut at) = (vec![], path.clone()); - for _ in 0..16 { - let Some((name, candidates)) = module_parent(&at) else { break }; - let Some((parent, found)) = candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, name)).map(|f| (c, f))) else { + let (mut gates, mut at) = (Gates::default(), path.clone()); + 'up: for _ in 0..16 { + let Some((name, mut candidates)) = module_parent(&at) else { break }; + let name = name.to_owned(); + let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { break; }; - preds.extend(found); - at = parent; + let mut chain: Vec = vec![]; + for _ in 0..4 { + let want = Loaded { path: &at, name: &name, chain: &chain }; + if let Some((parent, (preds, lines))) = + candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, &c, &want)).map(|f| (c, f))) + { + gates.preds.extend(preds); + gates.sources.push((parent.clone(), lines)); + at = parent; + continue 'up; + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + break; } - if !preds.is_empty() { - out.insert(path.clone(), preds); + if !gates.preds.is_empty() { + out.insert(path.clone(), gates); } } out @@ -3501,6 +3714,8 @@ mod tests { assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; assert_eq!(census(derived), [(2, "census")]); + let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n"; + assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip"); } #[test] @@ -4997,9 +5212,8 @@ mod tests { 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 both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; - assert_eq!(only("mirror", allowed), []); + let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror scaling is linear by definition\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; + assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); } #[test] @@ -5029,6 +5243,8 @@ mod tests { 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"); + let if_let = "#[test]\nfn t() {\n let x = 0;\n if let Some(x) = compute() {\n assert_eq!(x, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); } #[test] @@ -5082,15 +5298,57 @@ mod tests { #[test] fn never_run_follows_the_cfg_around_the_mod_declaration() { + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want).map(|(p, _)| p); let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; - assert_eq!(declared_cfgs(inner, "child"), Some(vec!["target_os=\"macos\"".to_owned()])); + assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; - assert_eq!(declared_cfgs(block, "child"), None, "that `mod child;` loads platform/child.rs"); + assert_eq!(declared(block, &child), None, "that `mod child;` loads platform/child.rs"); + let platform = ["platform".to_owned()]; + let nested = Loaded { path: "src/platform/child.rs", name: "child", chain: &platform }; + assert_eq!(declared(block, &nested), Some(vec!["windows".to_owned()]), "the gate on the inline module"); let both = "#[cfg(windows)]\nmod platform {\n mod child;\n}\nmod child;\n"; - assert_eq!(declared_cfgs(both, "child"), Some(vec![]), "the root declaration, not the one in platform"); + assert_eq!(declared(both, &child), Some(vec![]), "the root declaration, not the one in platform"); let gated = "#[cfg(windows)]\nconst _: () = {\n mod child;\n};\n"; - assert_eq!(declared_cfgs(gated, "child"), Some(vec!["windows".to_owned()]), "a gated block that is not a module"); - assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); + assert_eq!(declared(gated, &child), Some(vec!["windows".to_owned()]), "a gated block that is not a module"); + assert_eq!(declared("mod child;\n", &child), Some(vec![])); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\nmod child;\n"; + assert_eq!(declared(commented, &child), Some(vec!["target_os=\"linux\"".to_owned()]), "a comment in the predicate"); + let paths = "#[cfg(windows)]\n#[path = \"windows.rs\"]\nmod imp;\n#[cfg(not(windows))]\nmod imp;\n"; + let imp = Loaded { path: "src/imp.rs", name: "imp", chain: &[] }; + assert_eq!(declared(paths, &imp), Some(vec!["not(windows)".to_owned()]), "the declaration that loads imp.rs"); + let win = Loaded { path: "src/windows.rs", name: "windows", chain: &[] }; + assert_eq!(declared(paths, &win), Some(vec!["windows".to_owned()]), "the `#[path]` override"); + let twice = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(target_os = \"linux\")]\n#[path = \"child.rs\"]\nmod other;\n"; + assert_eq!(declared(twice, &child), Some(vec!["any(all(target_os=\"macos\"),all(target_os=\"linux\"))".to_owned()])); + let attr = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\nmod child;\n"; + assert_eq!(declared(attr, &child), Some(vec!["any(not(unix),target_os=\"macos\")".to_owned()])); + } + + #[test] + fn never_run_reads_cfg_attr_and_commented_predicates() { + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "Linux runs it"); + 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 nested = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", nested), [(3, "never-run")], "unix holds on every CI target, so the nested cfg applies"); + let unknown = "#[cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unknown), [], "a condition that may not hold"); + } + + #[test] + fn a_changed_parent_declaration_counts_for_the_child_tests() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "mod plain;\n#[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 gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + let lib = |lines: &[usize]| -> BTreeMap>> { + [("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))].into_iter().collect() + }; + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); + assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); } #[test] @@ -5131,5 +5389,7 @@ mod tests { 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 comment = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"input.rs\" */ \"data.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); } } From 44c8e3451307c62f644eb1cae158d4005ba6b0ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:42:46 -0800 Subject: [PATCH 05/17] xtask: test-lint review fixes for spans, cfg_attr, shared roots and bindings - A negated .contains(...) check forbids a value and is no longer treated as a presence check; !items.is_empty() still is. - reads-source matches the last path literal of a read_to_string argument, and its span runs through the argument's closing paren. - A for pattern binding shadows an outer let inside the loop body. - Nested cfg_attr conditions are combined before the inner cfg applies. - A never-run hit counts edits to the enclosing cfg lines and to the test, not to code between them. - A parent declaration edit counts against a child's test only when the test still ran in CI at the base. - A module loaded by several roots is off only when every root leaves it out. - docs/development.md lists reads-source and never-run as failing rules. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 190 +++++++++++++++++++++++++++++++++-------- 2 files changed, 154 insertions(+), 38 deletions(-) diff --git a/docs/development.md b/docs/development.md index a1ceccaf59..c833a400e8 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` keeps out of every CI test build (`never-run`). 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, and an environment variable that no CI leg sets. 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/test_lint.rs b/xtask/src/test_lint.rs index 168dd8ff79..5384b51e4c 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -235,15 +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, - /// The first line an allow comment may sit on to exempt the hit, when it differs from `first`: - /// a `never-run` hit spans an enclosing module's `cfg`, but only an allow at the test's own - /// attributes exempts it. - pub allow_from: Option, + /// Lines outside `first..=last` that also count as changes to the hit: the enclosing `cfg` + /// attributes of a `never-run` test. An allow comment there does not exempt it. + pub gates: Vec, } impl Hit { @@ -311,11 +310,20 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let gates = module_gates(&gated, &|p| read_small(root, p)); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; + // The gates the parent declarations gave at the base: a parent edit counts against a child's + // test only when the test ran in CI before it. + let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); + let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; + let newly_off = + |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { let parent_changed = gate_changed(gates.get(&path), &changed); for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) + || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) + { counted.push(hit); } else { older += 1; @@ -324,7 +332,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { let Some(src) = read_small(root, path) else { continue }; - counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun)); + counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } finish(&counted, older, present.len(), &base) } @@ -575,7 +583,7 @@ 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()) + changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some() || hit.gates.iter().any(|l| lines.contains(l))) } // ---- What CI sets ---- @@ -1214,7 +1222,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, allow_from: None } + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, gates: vec![] } } fn test_at(&self, pos: usize) -> &str { @@ -1254,7 +1262,7 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { hits.extend(reads_source_hits(&file)); let allows = allows(src, &file.m); hits.retain(|h| { - let first = if h.rule == Rule::AllUnguarded { h.line } else { h.allow_from.unwrap_or(h.first) }; + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) }); hits.sort(); @@ -1624,7 +1632,12 @@ fn weak_predicate(pred: &str) -> bool { if let Some(at) = boolean_split(pred) { return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); } + let negated = pred.starts_with('!'); let pred = pred.trim_start_matches('!'); + // A negated membership or presence check forbids a value; only `!….is_empty()` stays a presence check. + if negated && !pred.ends_with(".is_empty()") { + return false; + } if let Some(list) = pred.strip_suffix(".len()>0") { return !list.contains(['=', '<', '>']); } @@ -2976,18 +2989,29 @@ fn reads_source_hits(file: &File) -> Vec { let literal = raw.unwrap_or(&arg); let rs = match word { b"ends_with" => literal == "\".rs\"", - // A path literal anywhere in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`. - b"read_to_string" => arg.contains(".rs\""), + // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, + // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. + b"read_to_string" => last_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())); + let mut hit = file.hit(at, Rule::ReadsSource, file.test_at(at), note.into()); + // The span runs through the argument, so a change to a path on a later line counts. + hit.last = file.lines.of(close); + out.push(hit); } } } out } +/// The last string literal in a (whitespace-free) expression, quotes included. +fn last_literal(arg: &str) -> Option<&str> { + let close = arg.rfind('"')?; + let open = arg[..close].rfind('"')?; + Some(&arg[open..=close]) +} + // ---- Mirrors, echoes, never-run tests and exact pixels ---- /// Names a `mirror` comparison may call on both sides: builders, conversions and accessors. @@ -3133,6 +3157,24 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { /// 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 found = let_init(body, name, before); + // A `for` pattern binds its names inside the loop body only, to values the loop produces. + let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| { + let Some((open, close)) = let_body(body, at + 3) else { return false }; + let head = String::from_utf8_lossy(&body[at + 3..open]); + let Some((pattern, _)) = head.split_once(" in ") else { return false }; + let pattern = norm(pattern.as_bytes()); + open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() + }); + match (loop_at, &found) { + (Some(l), Some((_, at))) if *at > l => found.map(|(init, _)| init), + (Some(_), _) => Some(None), + (None, _) => found.map(|(init, _)| init), + } +} + +/// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. +fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { let mut found = None; for at in words(body, b"let", 0, before) { let start = skip_ws(body, at + 3); @@ -3148,7 +3190,7 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option 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 }); + found = Some((if is_mut { None } else { init }, at)); } 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); + found = Some((None, at)); } } } @@ -3334,15 +3376,8 @@ fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec { out.push(CfgAttr { pred: text, at, end, inner }); continue; } - let cuts = top_level_at(&text, ","); - let Some(&first) = cuts.first() else { continue }; - let cond = &text[..first]; - let mut start = first + 1; - for cut in cuts[1..].iter().copied().chain([text.len()]) { - if let Some(p) = text.get(start..cut).and_then(|p| p.strip_prefix("cfg(")).and_then(|p| p.strip_suffix(')')) { - out.push(CfgAttr { pred: format!("any(not({cond}),{p})"), at, end, inner }); - } - start = cut + 1; + for pred in cfg_attr_preds(&text, None) { + out.push(CfgAttr { pred, at, end, inner }); } } } @@ -3350,6 +3385,30 @@ fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec { out } +/// The `cfg` predicates inside the arguments of a `cfg_attr(, …)`, each made +/// `any(not(),)`. A nested `cfg_attr` adds its condition to the enclosing +/// ones: `cfg_attr(unix, cfg_attr(test, cfg(p)))` gives `any(not(all(unix,test)),p)`. +fn cfg_attr_preds(text: &str, outer: Option<&str>) -> Vec { + let cuts = top_level_at(text, ","); + let Some(&first) = cuts.first() else { return vec![] }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut out = vec![]; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(p) = arg.strip_prefix("cfg(").and_then(|p| p.strip_suffix(')')) { + out.push(format!("any(not({cond}),{p})")); + } else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) { + out.extend(cfg_attr_preds(n, Some(&cond))); + } + start = cut + 1; + } + out +} + /// A `cfg` predicate's source text without whitespace or comments. Masking would also blank the /// string literals `target_os = "macos"` needs, so only comments are blanked. fn pred_text(src: &[u8]) -> String { @@ -3539,11 +3598,18 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> Hash let mut chain: Vec = vec![]; for _ in 0..4 { let want = Loaded { path: &at, name: &name, chain: &chain }; - if let Some((parent, (preds, lines))) = - candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, &c, &want)).map(|f| (c, f))) - { - gates.preds.extend(preds); - gates.sources.push((parent.clone(), lines)); + // Every file that loads the module is another way in (a library and a binary root + // can both load it): its tests are off only when every one of them leaves them out. + let found: Vec<_> = + candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); + if let Some(parent) = found.first().map(|(p, _)| p.clone()) { + if let [(_, (preds, _))] = found.as_slice() { + gates.preds.extend(preds.iter().cloned()); + } else { + let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); + gates.preds.push(format!("any({})", each.join(","))); + } + gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); at = parent; continue 'up; } @@ -3566,7 +3632,7 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> Hash fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); // A change to an attribute that turns the test off counts as a change to the test. - let first_attr = local.iter().map(|&(_, at)| at).min(); + let attr_lines: Vec = local.iter().map(|&(_, at)| v.file.lines.of(at)).collect(); let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { @@ -3577,10 +3643,9 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { 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(", "))); - if let Some(at) = first_attr { - hit.allow_from = Some(hit.first); - hit.first = hit.first.min(v.file.lines.of(at)); - } + // Enclosing attributes count as separate lines, so an edit to code between them and the + // test does not count. + hit.gates = attr_lines.into_iter().filter(|&l| l < hit.first).collect(); return Some(hit); } None @@ -5355,9 +5420,14 @@ mod tests { 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((1, 4))); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line, h.gates.clone())); + assert_eq!(hit, Some((3, 4, vec![1]))); assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let helper = + "#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\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 module cfg and the test"); let two = "#[cfg(target_os = \"macos\")]\nmod mac {\n // test-lint: allow never-run checks the macOS menu bar\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n"; let left: Vec = lint_file("crates/x/src/tests.rs", two, &ctx()).iter().filter(|h| h.rule == Rule::NeverRun).map(|h| h.line).collect(); assert_eq!(left, [9], "an allow above one test leaves the next one reported"); @@ -5391,5 +5461,51 @@ mod tests { assert_eq!(only("reads-source", data), []); let comment = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"input.rs\" */ \"data.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); + let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + let found = lint_file("crates/x/src/tests.rs", split, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); + assert_eq!((hit.line, hit.last), (3, 5), "the span runs through the path on the next line"); + assert!(touches(hit, Some(&[4].into_iter().collect()))); + } + + #[test] + fn negated_membership_checks_are_not_presence_checks() { + assert!(!weak_predicate("!errors_for(c).contains(&Error::Unexpected)")); + assert!(!weak_predicate("!map.contains_key(&k)")); + assert!(weak_predicate("!items.is_empty()")); + assert!(weak_predicate("errors_for(c).contains(&Error::Expected)")); + } + + #[test] + fn a_for_binding_shadows_the_outer_one_in_its_body() { + let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", looped), []); + let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); + } + + #[test] + fn nested_cfg_attr_gates_apply() { + let nested = "#[cfg_attr(unix, cfg_attr(test, cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", nested), [(3, "never-run")]); + let unknown = "#[cfg_attr(unix, cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unknown), []); + } + + #[test] + fn a_module_loaded_by_two_roots_runs_if_either_runs_it() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod shared;\n"), + ("crates/x/src/main.rs", "mod shared;\n"), + ("crates/x/src/shared.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } } From 579fa0c247c7d0f11773d930771946d0b2ef831a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:31:47 -0800 Subject: [PATCH 06/17] xtask: test-lint mirror leaves out reads at two entries and shared arithmetic - Two calls that differ only in the entry they name (a string or integer literal, a local, a field or an indexed element) relate two entries, as in at("B") == at("A") + 1 or bounds(&s, copy) == bounds(&s, id) + dv, and are no longer reported. - The same arithmetic on both sides (rotate_deg(-270.0) * v == rotate_deg(90.0) * v) checks that two inputs agree and is no longer reported. On main, test-lint --all reports 1 mirror hit instead of 14. --- xtask/src/test_lint.rs | 72 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..baf93450e6 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -48,7 +48,9 @@ //! 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; +//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same +//! arithmetic on both sides and two reads that differ only in the entry they name (a string or +//! integer literal, a local or an indexed element); //! * `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 @@ -3066,22 +3068,59 @@ fn head_call(op: &str) -> Option<&str> { } } -/// `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. +/// The offset of the first top-level `+`, `-`, `*` or `/` in a whitespace-free operand. +fn first_arithmetic(op: &str) -> Option { + ["+", "-", "*", "/"].iter().flat_map(|o| top_level_at(op, o)).min() +} + +/// The whitespace-free source text of the arguments of the call an operand starts with, read from +/// the unmasked source so string literals keep their text. +fn head_args(f: &File, (from, to): (usize, usize)) -> Option> { + let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; + let close = matching(&f.m, open)?; + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(&f.src[a..b])).collect()) +} + +/// An argument that names an entry rather than a quantity: a string or integer literal, or a local, +/// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). +fn key_like(arg: &str) -> bool { + let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); + match arg.as_bytes().first() { + Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), + Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), + None => false, + } +} + +/// `assert_eq!(f(a), f(b) …)`: the expected side derives its value from a second call of the +/// same function with arithmetic, so a fault in `f` can move both sides together. Identical sides +/// are `self-compare`'s. Left out: the same arithmetic on both sides (`f(a) * v == f(b) * v` +/// checks that two inputs agree, as a periodicity check does), and two reads at different entries +/// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries. 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 (lr, rr) = (*a.args.first()?, *a.args.get(1)?); + let (l, r) = (norm(&v.file.m[lr.0..lr.1]), norm(&v.file.m[rr.0..rr.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()); + // Two calls compared as they are check that two inputs agree, which is a real check. + let derived = match (first_arithmetic(l), first_arithmetic(r)) { + (_, None) => false, + (Some(i), Some(j)) => l[i..] != r[j..], + (None, Some(_)) => true, + }; 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))) + if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) { + return None; + } + let (la, ra) = (head_args(v.file, lr)?, head_args(v.file, rr)?); + let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); + let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); + (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) }) .collect() } @@ -5279,6 +5318,21 @@ mod tests { assert_eq!(only("mirror", ne), [], "two inputs that must differ"); let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror scaling is linear by definition\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); + let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n"; + assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry"); + } + + #[test] + fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() { + let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n"; + assert_eq!(only("mirror", order), [], "positions of two entries in one list"); + let offset = + "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; + assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); + let period = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * v);\n}\n"; + assert_eq!(only("mirror", period), [], "the same arithmetic on both sides"); + let tails = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * w);\n}\n"; + assert_eq!(only("mirror", tails), [(3, "mirror")], "different arithmetic on each side still derives one from the other"); } #[test] From 07acf0bf370b7e1631a8e039997ac2898d5f4069 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:50:07 +0530 Subject: [PATCH 07/17] Keep Glyphs menus open across unrelated font changes --- crates/ui-egui/src/panels/glyphs.rs | 51 +++++++++++++---------- crates/ui-egui/src/panels/glyphs/tests.rs | 10 ++++- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 4d60dd59ef..ad1bc48c1f 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -24,6 +24,7 @@ //! as Entire Font shows them. use std::collections::HashSet; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphCellMenu, GlyphSource, GlyphsPanel, GlyphsWords}; @@ -299,11 +300,11 @@ fn insert(app: &mut VectorcraftApp, ch: char) -> bool { /// character, all read when it is made, so it borrows nothing from the app. Every method uses the /// held face whatever family and style it is given: the face of the canvas row or of the selected /// text can be an instance of variable axes that no family and style name reaches. -pub(crate) struct VcGlyphs<'a> { - db: &'a FontDb, +pub(crate) struct VcGlyphs { family: String, style: String, face: Option>, + revision: u64, /// What a glyph no character maps can do to the selected character; none for a face without one /// and in Alternates for Selection. fit: Option, @@ -313,7 +314,7 @@ pub(crate) struct VcGlyphs<'a> { empty: Option, } -impl VcGlyphs<'static> { +impl VcGlyphs { /// The source of the panel: the browsed face, or the face of the selected character's alternates /// in Alternates for Selection. pub(crate) fn of(app: &mut VectorcraftApp) -> Self { @@ -321,44 +322,42 @@ impl VcGlyphs<'static> { if app.ui.glyphs_panel.category == ALTERNATES { return match alternates_listing(app) { Ok(listing) => VcGlyphs { - db: FontDb::global(), family: listing.face.family.clone(), style: listing.face.style.clone(), face: Some(listing.face.clone()), + revision: listing.revision(), fit: None, listing: Some(listing), empty: None, }, - Err(note) => VcGlyphs { db: FontDb::global(), family, style, face: None, fit: None, listing: None, empty: Some(note) }, + Err(note) => VcGlyphs { family, style, face: None, revision: 0, fit: None, listing: None, empty: Some(note) }, }; } let fit = face.as_ref().map(|f| Fit::of(app, f)); let empty = face.is_none().then(|| tl!("No fonts are available.").to_string()); - VcGlyphs { db: FontDb::global(), family, style, face, fit, listing: None, empty } + let revision = face.as_ref().map_or(0, |face| u64::from(face.id())); + VcGlyphs { family, style, face, revision, fit, listing: None, empty } } /// The source of `face` alone: it draws glyphs and describes nothing about the selection. fn bare(face: Arc) -> Self { VcGlyphs { - db: FontDb::global(), family: face.family.clone(), style: face.style.clone(), + revision: u64::from(face.id()), face: Some(face), fit: None, listing: None, empty: None, } } -} - -impl VcGlyphs<'_> { /// The family and style the panel shows. fn font(&self) -> (&str, &str) { (&self.family, &self.style) } } -impl GlyphSource for VcGlyphs<'_> { +impl GlyphSource for VcGlyphs { fn cells(&self, _family: &str, _style: &str, category: &str) -> Vec { let Some(face) = &self.face else { return vec![] }; if category == ALTERNATES { @@ -398,7 +397,9 @@ impl GlyphSource for VcGlyphs<'_> { } fn revision(&self) -> u64 { - self.db.generation() + // The grid uses this for both cached cells and open glyph-ID menus. Changes + // elsewhere in the font catalog leave the displayed face and its glyph IDs valid. + self.revision } fn categories(&self, _family: &str, _style: &str) -> Vec<(String, String)> { @@ -485,11 +486,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if out.font_changed { app.ui.glyphs_font = Some((family, style)); } - let menu_cell = out - .menu - .as_ref() - .filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)) - .map(|menu| menu.cell); + let menu_cell = out.menu.as_ref().filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)).map(|menu| menu.cell); if let Some(cell) = menu_cell.or(out.activated) { activate(app, cell); } @@ -499,7 +496,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// Offer the action for the clicked cell using the grid's face and text context for this pass. -fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphCellMenu) -> bool { +fn cell_menu(ui: &mut Ui, source: &VcGlyphs, can_insert: bool, menu: &GlyphCellMenu) -> bool { let Some(face) = &source.face else { return false }; let (label, enabled) = match menu.cell { GlyphCell::Char(c) => (tl!("Insert Glyph"), source.listing.is_none() && gid_of(face, c).is_some()), @@ -512,10 +509,7 @@ fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphC } _ => return false, }; - Menu::context(label, &menu.opener) - .show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran) - .inner - .unwrap_or(false) + Menu::context(label, &menu.opener).show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran).inner.unwrap_or(false) } /// A double-click or Enter on `cell`: insert the character (its letter for an Arabic presentation @@ -648,6 +642,17 @@ struct Listing { } impl Listing { + /// The visible alternates can change at another text target in the same face. + fn revision(&self) -> u64 { + let mut revision = DefaultHasher::new(); + (self.face.id(), self.id, self.bytes, self.variants.len()).hash(&mut revision); + for variant in &self.variants { + variant.gid.hash(&mut revision); + } + // Face-only revisions are u32 IDs. Keep a listing in a separate range. + revision.finish() | (1 << 63) + } + /// Draw the character with glyph `gid` of the listing, as one undo step. fn apply(&self, app: &mut VectorcraftApp, gid: u32) { if let Some(variant) = self.variants.iter().find(|v| v.gid == gid) { @@ -775,7 +780,7 @@ impl OnCanvas { } /// The source that draws the offered glyphs ([`Self::face`]). - pub fn source(&self) -> VcGlyphs<'static> { + pub fn source(&self) -> VcGlyphs { VcGlyphs::bare(self.face.clone()) } diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index a4f6635324..8a797f4fec 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -43,7 +43,7 @@ fn browsed(app: &VectorcraftApp) -> (String, String) { } /// The panel's cell source, as the panel builds it. -fn source(app: &mut VectorcraftApp) -> VcGlyphs<'static> { +fn source(app: &mut VectorcraftApp) -> VcGlyphs { VcGlyphs::of(app) } @@ -1153,7 +1153,7 @@ fn insert_glyph_is_disabled_without_a_text_target() { /// In Alternates for Selection a right-click offers Apply Alternate in one undo step. #[test] fn right_clicking_an_alternate_cell_offers_apply_alternate() { - use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid, thai_font}; FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); @@ -1170,6 +1170,12 @@ fn right_clicking_an_alternate_cell_offers_apply_alternate() { panel.secondary_click(&name); assert!(panel.menu_item_enabled("Apply Alternate")); assert!(!panel.shows("Insert Glyph"), "an alternate cell offers Apply Alternate"); + // Registering a different family between the menu's opening and the click + // must leave its glyph-ID target valid. + let unrelated = thai_font("VectorCraft Glyph Menu Unrelated Fixture", true).expect("the unrelated test font builds"); + assert!(FontDb::global().add_font(unrelated) > 0); + panel.frame(); + assert!(panel.menu_item_enabled("Apply Alternate")); panel.click_menu_item("Apply Alternate"); let app = panel.app(); assert_eq!(undo_len(&app), undo + 1, "one undo step"); From d61d946a3df86a41ff24b6fb2648c5b725e29533 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:59:45 +0530 Subject: [PATCH 08/17] Color Themes: add a context menu to saved theme rows --- crates/ui-egui/src/panels/color_themes.rs | 106 ++++++++++++++++------ docs/target-app-parity.md | 1 + 2 files changed, 80 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index 3d1b32f037..7ba34fe65a 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -10,7 +10,7 @@ // framework crates' layout (racheck-fw); none of them is imported anywhere else in the app yet. use std::borrow::Cow; -use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange}; +use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange, keyed}; use craft::color_ui::ui::{ChannelRow, ColorPanelMode, HarmonyWheel}; use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; @@ -19,7 +19,7 @@ use craft::ui::choice::{SwatchSpacing, SwatchTable}; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; use craft::ui::pickers::Select; use craft::ui::primitives::IconSpec; @@ -592,44 +592,45 @@ fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { } else if rows.is_empty() { Notice::new(Tone::Neutral, tl!("No matches.")).show(ui); } else { - let names: Vec = rows.iter().map(|(n, _)| n.clone()).collect(); - let mut selection = app - .ui - .color_themes_panel - .picked - .as_ref() - .and_then(|p| names.iter().position(|n| n == p)) - .map_or_else(Selection::default, Selection::single); - let out = List::new(tl!("My Themes")).select(craft::ui::contract::SelectMode::Single).selection(Bind::bound(&mut selection)).show_items( - ui, - &Names(&names), - &mut |key, _| { - let colors = rows.get(*key).map(|(_, c)| c.clone()).unwrap_or_default(); - let name = names.get(*key).cloned().unwrap_or_default(); - ListRow::new(name).thumb(ThumbSize::Small, move |cx, rect| { + let document = app.session.active().map(|st| st.uid); + let selection = picked(app).map_or_else(Selection::default, Selection::single); + let out = List::new(tl!("My Themes")) + .id(ui.scope_id().with(("my-themes", document))) + .select(craft::ui::contract::SelectMode::Single) + .selection(Bind::given(selection)) + .row_menu() + .show_items(ui, &keyed(&rows, |(name, _)| name.clone()), &mut |name, icx| { + let colors = rows[icx.at].1.clone(); + ListRow::new(name.clone()).thumb(ThumbSize::Small, move |cx, rect| { let w = rect.width() / colors.len().max(1) as f32; cx.data_shapes(colors.iter().enumerate().map(|(i, c)| { egui::Shape::rect_filled(Rect::from_min_size(rect.min + vec2(i as f32 * w, 0.0), vec2(w, rect.height())), 0.0, c32(c)) })); }) - }, - ); + }); for event in out.events { match event { CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => { - if let Some(name) = keys.last().and_then(|k| names.get(*k)) { - app.ui.color_themes_panel.picked = Some(name.clone()); - } + app.ui.color_themes_panel.picked = keys.last().cloned(); } + CollectionEvent::ContextMenu(request) => app.ui.color_themes_panel.picked = Some(request.key), // Enter and a double click edit the theme. - CollectionEvent::Activate(key) => { - if let Some(name) = names.get(key) { - edit_saved(app, name); - } - } + CollectionEvent::Activate(name) => edit_saved(app, &name), _ => {} } } + if let Some(request) = out.menu + && app.ui.color_themes_panel.tab == MY_THEMES + && app.ui.color_themes_panel.picked.as_ref() == Some(&request.key) + { + Menu::context(request.key, &out.response).show(ui, |ui, _| { + for (id, label) in [(EDIT, tl!("Edit Theme")), (ADD_TO_SWATCHES, tl!("Add to Swatches")), (DELETE, tl!("Delete Theme"))] { + if MenuItem::new(label).enabled(enabled(app, id)).show(ui).ran { + run(app, id, &Value::Null); + } + } + }); + } } let labels = vec![Label::from(tl!("Delete theme")), Label::from(tl!("Add to Swatches")), Label::from(tl!("Edit theme"))]; footer(app, ui, &[DELETE, ADD_TO_SWATCHES, EDIT], &["trash-2", "dc-folder", "pencil"], labels); @@ -831,6 +832,57 @@ mod tests { assert_eq!(picked(&app), None); } + #[test] + fn the_theme_menu_follows_its_row_when_the_list_is_filtered() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + app.ui.color_themes_panel.picked = Some("Forest".into()); + let mut panel = Panel::new(app, show); + panel.secondary_click("Harvest"); + assert_eq!(picked(&panel.app()).as_deref(), Some("Harvest")); + panel.app().ui.color_themes_panel.find = "vest".into(); + panel.frame(); + panel.click_menu_item("Delete Theme"); + assert_eq!(themes(&panel.app()).iter().map(|t| t.name.as_str()).collect::>(), ["Harbor", "Forest"]); + } + + #[test] + fn keyboard_theme_menu_uses_the_focused_row_without_a_document() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + assert!(app.session.close_document(0)); + let mut panel = Panel::new(app, show); + panel.click("Forest"); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + assert!(panel.menu_item_enabled("Edit Theme")); + assert!(panel.menu_item_enabled("Delete Theme")); + assert!(!panel.menu_item_enabled("Add to Swatches")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + assert!(panel.focused("Forest")); + } + + #[test] + fn the_theme_menu_closes_when_its_row_disappears_or_the_document_changes() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(three_themes(""), show); + panel.secondary_click("Harbor"); + assert!(panel.menu_item_enabled("Edit Theme")); + panel.app().ui.color_themes_panel.find = "Forest".into(); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + panel.secondary_click("Forest"); + assert!(panel.menu_item_enabled("Add to Swatches")); + panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap(); + panel.frame(); + assert!(!panel.shows_role("Add to Swatches", Role::MENU_ITEM)); + } + /// The find field lists the themes whose names hold its text, in any letter case, anywhere in /// the name, in their saved order; it reads names only, and its text is plain text. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5f5f9644d5..1eac724072 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2203,6 +2203,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (), which ships unmodified: the measured paper, solids and overprints, a tone curve fitted to each ink's ramp, and a smoothed Lab correction lattice fitted to all 1,617 patches. The models reproduce the patches within a mean ΔE2000 of 0.04 (largest 0.37), and patches left out of the fit within 0.15 to 0.17 (largest 1.67). A PDF/X output intent made with one embeds the profile; with the condition identifier left blank it names `FOGRA51` or `FOGRA52`, in the `http://www.color.org` registry unless the settings give a registry, and an identifier the settings give is written as given. The 300% ink limit and black generation are VectorCraft's own values. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **My Themes row menu:** Opening a saved theme's row menu selects it and offers Edit Theme, Add to Swatches and Delete Theme. Add to Swatches requires an active document. - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. - **Color Themes sliders:** on the Color Themes panel's Create tab, a Color Mode menu (CMYK, RGB, Lab and HSB) shows a rail and a number field for each component of the selected theme color, beside its hex field; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221) describes changing the selected color's values in these color systems or as hex while making a theme. VectorCraft's own rules: the menu starts in the selected color's own model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color; the ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127), a number past the range sets its end and text that is not a number changes nothing; a CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, while RGB and HSB edits make it RGB, and the theme saves and goes to Swatches in those models; an edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. Tests: `the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders`, `a_slider_edit_changes_only_the_selected_custom_color`, `the_sliders_keep_the_numbers_they_set`, `with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color` and `cmyk_and_lab_slider_edits_keep_their_models` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. From 3d2b663b9e61206d2ef31b6ad4f75f2af0719c62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:27:27 -0800 Subject: [PATCH 09/17] xtask: test-lint never-run follows #[path] modules and multiline gates never-run now finds the files that load a module through `#[path]`, including a sibling such as `graphics.rs` loading `tests_graphics.rs`, and follows them in both `--all` and changed-file mode. A changed file now reaches every file it loads, directly or through other modules, so a `cfg` added to its `mod` declaration flags the unchanged child's tests. - Every route to a module counts: inline-module routes, `#[path]` routes and several routes from one file are joined, each with its own ancestors, and a crate root keeps its own route. - A default `mod x;` matches only the file it really loads. - Every line of a multiline `cfg` attribute counts as a gate line, for the test's own gates and for the parent declarations. - The base comparison reads `#[path]` declarations from the base tree, so a moved declaration is not reported as newly off. --- xtask/src/test_lint.rs | 675 +++++++++++++++++++++++++++++++++++------ 1 file changed, 579 insertions(+), 96 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index baf93450e6..dc10c00fe7 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -81,7 +81,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. -use std::cell::OnceCell; +use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -272,20 +272,43 @@ fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap, + base_gates: Option<&Gates>, + base_overrides: &Overrides, + changed: &BTreeMap>>, +) -> bool { + gate_changed(gates, changed) + || base_gates.is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent))) + || base_overrides.get(path).is_some_and(|routes| routes.iter().any(|(parent, _)| changed.contains_key(parent))) +} + /// 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() } +/// Cache successful and missing reads for one source tree. +fn cached_read(read: impl Fn(&str) -> Option) -> impl Fn(&str) -> Option { + let cache = RefCell::new(HashMap::>::new()); + move |path| cache.borrow_mut().entry(path.to_owned()).or_insert_with(|| read(path)).clone() +} + pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let opts = Options::parse(args)?; + let read_work = cached_read(|p| read_small(root, p)); let repo = crate::repo_files(root)?; let ci_env = ci_env(root, &repo)?; let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + let overrides = path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))); + let module_cfgs = module_cfgs(&files, &read_work, &overrides); let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); @@ -297,31 +320,27 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { 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 present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn - // their tests off without a change to them. - let module_dirs: Vec = present - .iter() - .map(|p| { - let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); - if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } - }) - .collect(); - let below: Vec = - files.iter().filter(|p| !changed.contains_key(*p) && module_dirs.iter().any(|d| p.starts_with(d.as_str()))).cloned().collect(); + // Files that load a module through `#[path]`, found with `git grep` (untracked files included) + // instead of reading the tree. + let overrides = discover_path_overrides(root, None, &read_work); + let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); + let base_overrides = discover_path_overrides(root, Some(&base), &read_base); + // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` + // declaration can turn their tests off without a change to them. + let below: Vec = descendants(&present, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); - let gates = module_gates(&gated, &|p| read_small(root, p)); + let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; // The gates the parent declarations gave at the base: a parent edit counts against a child's // test only when the test ran in CI before it. - let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + let base_gates = module_gates(&gated, &read_base, &base_overrides); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); + let newly_off = |path: &str, src: &str, hit: &Hit| !already_off(&lint_file(path, src, &base_ctx), hit); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) @@ -332,13 +351,50 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { - let Some(src) = read_small(root, path) else { continue }; + for path in below.iter().filter(|p| route_gate_changed(p, gates.get(*p), base_gates.get(*p), &base_overrides, &changed)) { + let Some(src) = read_work(path) else { continue }; counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } finish(&counted, older, present.len(), &base) } +/// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the +/// test of `hit`. Tests of one name in different inline modules are told apart by their line. +fn already_off(base: &[Hit], hit: &Hit) -> bool { + base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +} + +/// The directory holding the modules that the file `p` declares by name: its own directory for +/// `mod.rs`, `lib.rs` and `main.rs`, and the directory named after it otherwise. +fn module_dir(p: &str) -> String { + let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); + if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } +} + +/// The files of `files` that the files `start` load, directly or through modules in between: the +/// files under their module directories and the files their current or base `#[path]` declarations load. +fn descendants(start: &[String], files: &[String], overrides: &Overrides, base_overrides: &Overrides) -> Vec { + let mut seen: BTreeSet = start.iter().cloned().collect(); + let mut frontier: Vec = start.to_vec(); + let mut out = vec![]; + while !frontier.is_empty() { + let dirs: Vec = frontier.iter().map(|p| module_dir(p)).collect(); + let next: Vec = files + .iter() + .filter(|p| !seen.contains(*p)) + .filter(|p| { + dirs.iter().any(|d| p.starts_with(d.as_str())) + || overrides.get(*p).into_iter().chain(base_overrides.get(*p)).flatten().any(|(parent, _)| frontier.contains(parent)) + }) + .cloned() + .collect(); + seen.extend(next.iter().cloned()); + out.extend(next.iter().cloned()); + frontier = next; + } + out +} + /// The command line: `--all`, `--base `. #[derive(Debug, Default, PartialEq)] struct Options { @@ -3365,6 +3421,8 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { + let arg = arg.trim(); + let arg = arg.strip_suffix(',').unwrap_or(arg).trim_end(); return cfg_value(arg, t).map(|v| !v); } // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. @@ -3455,8 +3513,8 @@ fn pred_text(src: &[u8]) -> String { } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the -/// offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// offsets where its attribute starts and ends. `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 CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { @@ -3472,7 +3530,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - out.push((pred, at)); + out.push((pred, at, end)); } } out @@ -3480,10 +3538,12 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { /// 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`). +/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `src` holds modules, not test targets. 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)); + let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); + let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin"); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } @@ -3511,6 +3571,10 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, let lines = Lines::new(src); let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let mut default_dir = if mod_rs { dir.to_owned() } else { join_path(dir, file.strip_suffix(".rs").unwrap_or(file)) }; + for seg in want.chain { + default_dir = join_path(&default_dir, seg); + } let (mut each, mut at_lines) = (vec![], vec![]); for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); @@ -3520,19 +3584,11 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => { - // A `#[path]` outside inline modules is relative to the file's directory; inside them, - // to the inline modules' directory under the file's module. - let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { - base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); - } - for seg in want.chain { - base = join_path(&base, seg); - } - join_path(&base, &rel) == want.path + Some(rel) => override_path(dir, file, mod_rs, want.chain, &rel) == want.path, + None => { + &m[start..end] == want.name.as_bytes() + && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } - None => &m[start..end] == want.name.as_bytes(), }; if !loads { continue; @@ -3540,11 +3596,12 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); at_lines.push(lines.of(at)); - at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); + // Every line of a multiline attribute counts: an edit inside its predicate changes it. + at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); - for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); - at_lines.push(lines.of(a)); + at_lines.extend(lines.of(a)..=lines.of(e)); } each.push(preds); } @@ -3556,6 +3613,90 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Some((preds, at_lines)) } +/// The file a `#[path = ""]` declaration in the file `dir/file` loads. Outside inline modules +/// `rel` is relative to the file's directory; inside them (`chain`, outermost first), to the inline +/// modules' directory under the file's module. +fn override_path(dir: &str, file: &str, mod_rs: bool, chain: &[String], rel: &str) -> String { + let mut base = dir.to_owned(); + if !chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + +/// The files that `#[path]` declarations in `src`, the file `parent`, load, each with the inline +/// modules its declaration sits in. +fn path_children(src: &str, parent: &str) -> Vec<(String, Vec)> { + let m = mask(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let mut out = vec![]; + for at in words(&m, b"mod", 0, m.len()) { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + continue; + } + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + let chain = inline_mods(&m, at); + out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); + } + } + out +} + +/// The files that load a module file through `#[path]`, keyed by the file they load: a sibling such +/// as `graphics.rs` loading `tests_graphics.rs` is not among the files [`module_parent`] names. +type Overrides = HashMap)>>; + +/// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources. +fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { + let with_path = match base { + Some(base) => git(root, &["grep", "-l", "-w", "path", base, "--", "*.rs"]), + None => git(root, &["grep", "--untracked", "-l", "-w", "path", "--", "*.rs"]), + } + .unwrap_or_default(); + listed_path_overrides(&with_path, base, read) +} + +/// Read paths from `git grep -l`, removing the revision prefix for a base-tree listing. +fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { + let prefix = base.map(|b| format!("{b}:")); + let sources: Vec<(String, String)> = list + .lines() + .filter_map(|p| match &prefix { + Some(prefix) => p.strip_prefix(prefix), + None => Some(p), + }) + .filter(|p| is_scanned(p)) + .filter_map(|p| read(p).map(|s| (p.to_owned(), s))) + .collect(); + path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))) +} + +/// [`Overrides`] for the files `sources`, as `(path, source)` pairs. +fn path_overrides<'a>(sources: impl IntoIterator) -> Overrides { + let mut out: Overrides = HashMap::new(); + for (parent, src) in sources { + if !src.contains("path") { + continue; + } + for (child, chain) in path_children(src, parent) { + // One entry per parent and inline modules: [`declared_cfgs`] joins the declarations of + // one file in one module. + let routes = out.entry(child).or_default(); + if !routes.iter().any(|(p, c)| p == parent && *c == chain) { + routes.push((parent.to_owned(), chain)); + } + } + } + out +} + /// The string value of a `#[path = "…"]` attribute in `m[from..to]`. fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { words(m, b"path", from, to).into_iter().find_map(|at| { @@ -3604,8 +3745,8 @@ fn inline_mods(m: &[u8], at: usize) -> Vec { /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. -fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { - module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option, overrides: &Overrides) -> HashMap> { + module_gates(paths, read, overrides).into_iter().map(|(p, g)| (p, g.preds)).collect() } /// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares @@ -3617,62 +3758,85 @@ struct Gates { } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that -/// may declare its module and, when none does, in the files above them through inline modules -/// (`mod platform { mod child; }` loads `platform/child.rs`). -fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { - let mut out = HashMap::new(); - for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } - if !gates.preds.is_empty() { - out.insert(path.clone(), gates); - } +/// may declare its module and in the files above them through inline modules +/// (`mod platform { mod child; }` loads `platform/child.rs`), and in the files of `overrides` that +/// load it through `#[path]`. +fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option, overrides: &Overrides) -> HashMap { + let read = cached_read(read); + paths + .iter() + .filter_map(|path| { + let gates = module_gate(path, &read, overrides, 0); + (!gates.preds.is_empty()).then(|| (path.clone(), gates)) + }) + .collect() +} + +/// Resolve each route's ancestors before joining routes, with a bound for cyclic module paths. +fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Overrides, depth: usize) -> Gates { + let mut gates = Gates::default(); + if depth >= 16 { + return gates; } - out + let by_path = overrides.get(at).map_or(&[][..], Vec::as_slice); + // A crate root runs independently of any module declarations that also load it. + let Some((name, mut candidates)) = module_parent(at) else { return gates }; + let name = name.to_owned(); + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + return gates; + }; + let mut chain: Vec = vec![]; + let mut found = vec![]; + for _ in 0..4 { + let want = Loaded { path: at, name: &name, chain: &chain }; + // Every file that loads the module is another way in (a library and a binary root + // can both load it): its tests are off only when every one of them leaves them out. + found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + if chain.is_empty() { + for (c, inline) in by_path { + // A candidate was read with no inline modules; another route through the + // same file still counts. + if inline.is_empty() && candidates.contains(c) { + continue; + } + let want = Loaded { path: at, name: &name, chain: inline }; + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))); + } + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + let mut each = vec![]; + for (parent, (mut preds, lines)) in found { + let ancestors = module_gate(&parent, read, overrides, depth + 1); + preds.extend(ancestors.preds); + gates.sources.push((parent, lines)); + gates.sources.extend(ancestors.sources); + each.push(preds); + } + gates.preds = match each.len() { + 0 => vec![], + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::>().join(","))], + }; + gates } /// 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); - // A change to an attribute that turns the test off counts as a change to the test. - let attr_lines: Vec = local.iter().map(|&(_, at)| v.file.lines.of(at)).collect(); - let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); + // A change to an attribute that turns the test off counts as a change to the test, on any line + // of a multiline attribute. + let attr_lines: Vec = local.iter().flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect(); + let mut preds: Vec = local.into_iter().map(|(p, _, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -5366,6 +5530,18 @@ mod tests { assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); } + #[test] + fn never_run_accepts_trailing_commas_in_cfg_predicates() { + for pred in ["not(unix,)", "not( unix , )", "all(not(unix,),)", "any(not(unix,),)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [(3, "never-run")], "{pred}"); + } + for pred in ["all(unix,)", "any(unix,)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [], "{pred}"); + } + } + #[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"; @@ -5391,6 +5567,27 @@ mod tests { assert_eq!(only("never-run", other), [], "a cfg on another item"); } + #[test] + fn module_gates_reads_each_candidate_once() { + let paths: Vec = (0..32).map(|i| format!("crates/x/src/parent/child{i}.rs")).collect(); + let parent = (0..32).map(|i| format!("mod child{i};\n")).collect::(); + let files = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n"), ("crates/x/src/parent.rs", parent.as_str())]; + let reads = RefCell::new(HashMap::::new()); + let read = |p: &str| { + *reads.borrow_mut().entry(p.to_owned()).or_default() += 1; + files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()) + }; + let gates = module_gates(&paths, &read, &Overrides::new()); + assert_eq!(gates.len(), paths.len(), "every child inherits the parent gate"); + let reads = reads.borrow(); + assert_eq!(reads.get("crates/x/src/lib.rs"), Some(&1), "a shared ancestor"); + assert_eq!(reads.get("crates/x/src/parent.rs"), Some(&1), "a shared parent"); + assert_eq!(reads.get("crates/x/src/parent/mod.rs"), Some(&1), "a missing candidate"); + for (path, count) in reads.iter() { + assert_eq!(*count, 1, "candidate {path}"); + } + } + #[test] fn never_run_follows_the_cfg_of_the_mod_declaration() { let files: HashMap<&str, &str> = [ @@ -5405,7 +5602,7 @@ mod tests { .into_iter() .map(String::from) .collect(); - let cfgs = module_cfgs(&paths, &read); + let cfgs = module_cfgs(&paths, &read, &Overrides::new()); 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")); @@ -5461,13 +5658,299 @@ mod tests { let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod plain;\n#[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 gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); let lib = |lines: &[usize]| -> BTreeMap>> { [("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))].into_iter().collect() }; assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); + let multiline: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod child;\nmod plain;\n"), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| multiline.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "a line inside a multiline predicate"); + assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[6])), "another declaration"); + let enclosing: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod platform {\n mod child;\n}\nmod plain;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| enclosing.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[3])), "a line inside the inline module's predicate"); + assert!(!gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[8])), "a declaration outside the inline module"); + } + + #[test] + fn never_run_follows_a_path_override_in_a_sibling_file() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod solids;\n"), + ("crates/x/src/solids/mod.rs", "mod graphics;\n"), + ("crates/x/src/solids/graphics.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"tests_graphics.rs\"]\nmod tests;\n"), + ("crates/x/src/solids/tests_graphics.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/solids/tests_graphics.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&child), &read, &overrides); + assert_eq!(gates.get(&child).map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + let changed: BTreeMap>> = + [("crates/x/src/solids/graphics.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(&child), &changed), "a cfg added to the sibling's declaration"); + } + + #[test] + fn never_run_keeps_crate_roots_independent_of_path_overrides() { + for child in [ + "crates/x/tests/shared.rs", + "crates/x/src/lib.rs", + "crates/x/src/main.rs", + "crates/x/src/bin/tool.rs", + "crates/x/examples/demo.rs", + "crates/x/benches/speed.rs", + "crates/x/build.rs", + ] { + let declaration = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod shared;\n", child.strip_prefix("crates/x/").unwrap()); + let files = [("crates/x/other.rs", declaration.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the crate root runs independently: {child}"); + let gated = format!("#[cfg(target_os = \"macos\")]\n{test}"); + assert_eq!(hits_in(child, &gated, &ctx), [(3, "never-run")], "the root's own cfg still applies: {child}"); + } + } + + #[test] + fn a_namesake_already_off_does_not_hide_a_newly_off_test() { + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let path = "crates/x/src/child.rs"; + let base = lint_file(path, src, &ctx()); + let now = + lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, h)).map(|h| h.line).collect(); + assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); + } + + #[test] + fn never_run_follows_a_tests_module_directory_under_src() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod tests;\n"), ("crates/x/src/tests.rs", "mod fonts;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/tests/fonts.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets"); + assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src"); + } + + #[test] + fn path_override_discovery_accepts_attribute_whitespace_in_both_trees() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-path-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let files = [ + ("crates/x/src/a.rs", "#[cfg(target_os = \"macos\")]\n#[ path = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[\npath = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/decoy.rs", "// path is not a module attribute\nmod other;\n"), + ]; + for (path, src) in files { + std::fs::write(root.join(path), src).unwrap(); + } + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + for revision in [None, Some(base.as_str())] { + let read = |p: &str| match revision { + Some(base) => git(&root, &["show", &format!("{base}:{p}")]).ok(), + None => read_small(&root, p), + }; + let overrides = discover_path_overrides(&root, revision, &read); + let child = "crates/x/src/shared.rs"; + let parents: BTreeSet<&str> = overrides.get(child).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, [files[0].0, files[1].0].into_iter().collect(), "both whitespace forms: {revision:?}"); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [(2, "never-run")], "the discovered gates apply: {revision:?}"); + } + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn never_run_joins_inline_and_override_routes() { + for (lib, child) in [ + ("mod platform { mod child; }\nmod a;\n", "crates/x/src/platform/child.rs"), + ("mod platform { mod nested { mod child; } }\nmod a;\n", "crates/x/src/platform/nested/child.rs"), + ] { + let a = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod other;\n", child.strip_prefix("crates/x/src/").unwrap_or(child)); + let files = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", a.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the ungated inline route runs it"); + for parent in ["crates/x/src/lib.rs", "crates/x/src/a.rs"] { + let changed = [(parent.to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "both routes contribute their source lines: {parent}"); + } + } + } + + #[test] + fn never_run_keeps_default_and_override_files_separate() { + let files = [ + ("crates/x/src/lib.rs", "mod a;\n"), + ("crates/x/src/a.rs", "mod shared;\n#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod other;\n"), + ]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let paths = ["crates/x/src/shared.rs".to_owned(), "crates/x/src/a/shared.rs".to_owned()]; + let gates = module_gates(&paths, &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&paths[0], test, &ctx), [(2, "never-run")], "only the macOS override loads this file"); + assert_eq!(hits_in(&paths[1], test, &ctx), [], "the default declaration loads the file under a/"); + let changed = [("crates/x/src/a.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(!gate_changed(gates.get(&paths[0]), &changed), "the default declaration belongs to the other file"); + } + + #[test] + fn never_run_resolves_every_routes_ancestors() { + for (a, b, child) in [ + ("#[path = \"shared.rs\"]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n", "crates/x/src/shared.rs"), + ("mod shared;\n", "#[path = \"a/shared.rs\"]\nmod s;\n", "crates/x/src/a/shared.rs"), + ] { + for target in ["linux", "macos"] { + let lib = format!("#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"{target}\")]\nmod b;\n"); + let files = [("crates/x/src/lib.rs", lib.as_str()), ("crates/x/src/a.rs", a), ("crates/x/src/b.rs", b)]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let expected = if target == "linux" { vec![] } else { vec![(2, "never-run")] }; + assert_eq!(hits_in(child, test, &ctx), expected, "the second route's ancestors decide whether Linux runs it"); + for (parent, line) in [ + ("crates/x/src/a.rs", if a.starts_with("#[path") { 2 } else { 1 }), + ("crates/x/src/b.rs", 2), + ("crates/x/src/lib.rs", 2), + ("crates/x/src/lib.rs", 4), + ] { + let changed = [(parent.to_owned(), Some([line].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "every route and its ancestors: {parent}:{line}"); + } + } + } + } + + #[test] + fn removed_module_routes_count_only_newly_off_tests() { + let a = "crates/x/src/a.rs"; + let child = "crates/x/src/shared.rs"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let mac = "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"; + let work_files = [("crates/x/src/lib.rs", "mod a;\nmod b;\n"), (a, ""), ("crates/x/src/b.rs", mac)]; + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(work_files); + let paths = [child.to_owned()]; + let gates = module_gates(&paths, &read_work, &overrides); + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let hit = lint_file(child, test, &work_ctx).into_iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + for (before, ran) in [(declaration, true), (mac, false)] { + let base_files = [("crates/x/src/lib.rs", work_files[0].1), (a, before), ("crates/x/src/b.rs", mac)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = path_overrides(base_files); + let base_gates = module_gates(&paths, &read_base, &base_overrides); + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::>(); + assert!( + descendants(&[a.to_owned()], &files, &overrides, &base_overrides).contains(&child.to_owned()), + "the removed route still reaches the shared tests" + ); + for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { + let changed = [(a.to_owned(), lines)].into_iter().collect(); + assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); + let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); + assert!(parent_changed, "deletions and shifted lines still change a base route"); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), &hit), ran); + assert!( + route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), + "a base route parent counts even without inherited predicates" + ); + } + let changed = [("crates/x/src/lib.rs".to_owned(), Some([20].into_iter().collect()))].into_iter().collect(); + assert!( + route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed), + "an edited base ancestor counts even when its old line numbers do not match" + ); + } + } + + #[test] + fn base_path_overrides_follow_declarations_before_a_move() { + let a = "crates/x/src/a.rs"; + let b = "crates/x/src/b.rs"; + let child = "crates/x/src/shared.rs"; + let lib = "#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let base_files = [("crates/x/src/lib.rs", lib), (a, declaration), (b, "")]; + let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = listed_path_overrides(&format!("before:{a}\n"), Some("before"), &read_base); + let work_overrides = listed_path_overrides(&format!("{b}\n"), None, &read_work); + let paths = [child.to_owned()]; + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &work_ctx), [(2, "never-run")]); + assert_eq!(hits_in(child, test, &base_ctx), [(2, "never-run")], "the test was already off before the equally gated declaration moved"); + } + + #[test] + fn never_run_joins_two_inline_routes_from_one_file() { + let a = "#[cfg(target_os = \"macos\")]\nmod m {\n #[path = \"../shared.rs\"]\n mod s;\n}\nmod n {\n #[path = \"../shared.rs\"]\n mod s;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", a)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/src/a/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it"); + } + + #[test] + fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() { + let files: Vec = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"] + .into_iter() + .map(String::from) + .collect(); + let overrides = path_overrides([ + ("src/solids/graphics.rs", "#[path = \"map_art.rs\"]\nmod art;\n"), + ("src/solids/map_art.rs", "#[path = \"tests_map_art.rs\"]\nmod tests;\n"), + ]); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new()); + assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); + } + + #[test] + fn never_run_counts_every_line_of_a_multiline_test_gate() { + let src = + "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\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).unwrap(); + assert!(touches(hit, Some(&[3].into_iter().collect())), "an edit inside the predicate"); } #[test] @@ -5558,7 +6041,7 @@ mod tests { .into_iter() .collect(); let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read), ..ctx() }; + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read, &Overrides::new()), ..ctx() }; let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } From e1c1b04f25f1979ff5be4b2b3a182534a41d1a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:27:46 -0800 Subject: [PATCH 10/17] xtask: test-lint follows deleted and detached routes and decoded cfg values - A deleted file stays in the changed set and seeds the descendant walk, so a module it loaded through #[path] is checked for a lost CI route. - A parent file that no crate target loads (its mod line removed) no longer counts as an ungated route to the module it declares. - #[path] on an inline module sets the directory of the modules inside it. - git grep lists #[path] parents with -z, so non-ASCII paths are read verbatim in both trees. - cfg string values are compared decoded ("\x6cinux" is linux); raw strings stay as written. - mirror reports arithmetic on either side of the equality, and ignores comments beside lookup keys. - reads-source does not take a format! argument as the file name. - The base never-run hits are computed once per file. --- xtask/src/test_lint.rs | 253 +++++++++++++++++++++++++++++++++++------ 1 file changed, 217 insertions(+), 36 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f70326e737..0c7d793c0f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -327,7 +327,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_overrides = discover_path_overrides(root, Some(&base), &read_base); // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` // declaration can turn their tests off without a change to them. - let below: Vec = descendants(&present, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); + // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. + let seeds: Vec = changed.keys().cloned().collect(); + let below: Vec = descendants(&seeds, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); @@ -337,7 +339,15 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = |path: &str, src: &str, hit: &Hit| !already_off(&lint_file(path, src, &base_ctx), hit); + // The base's `never-run` hits, computed once per file on its first parent-attributed hit. + let base_off: RefCell>> = RefCell::new(HashMap::new()); + let newly_off = |path: &str, src: &str, hit: &Hit| { + let mut cache = base_off.borrow_mut(); + let off = cache.entry(path.to_owned()).or_insert_with(|| { + lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() + }); + !off.contains(&(hit.test.clone(), hit.line)) + }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); @@ -360,6 +370,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { /// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the /// test of `hit`. Tests of one name in different inline modules are told apart by their line. +#[cfg(test)] fn already_off(base: &[Hit], hit: &Hit) -> bool { base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) } @@ -570,15 +581,21 @@ fn parse_diff(diff: &str) -> BTreeMap>> { let mut current: Option = None; // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. let (mut header, mut new_file) = (false, false); + let mut old: Option = None; for line in diff.lines() { if line.starts_with("diff --git ") { - (header, new_file) = (true, false); + (header, new_file, old) = (true, false, None); } else if header && line.starts_with("new file mode") { new_file = true; + } else if let Some(path) = line.strip_prefix("--- ").filter(|_| header) { + old = patch_path(path).and_then(|p| p.strip_prefix("a/").map(str::to_owned)); } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); if let Some(p) = ¤t { out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } else if let Some(p) = old.take().filter(|_| path == "/dev/null") { + // A deleted file is kept, wholly changed: it may have been a route that loaded a module. + out.insert(p, None); } } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { header = false; @@ -3082,10 +3099,30 @@ fn reads_source_hits(file: &File) -> Vec { out } -/// The last string literal in a (whitespace-free) expression, quotes included. +/// The last string literal in a (whitespace-free) expression, quotes included. Inside a +/// `format!`-family call, an argument is not the file name, so the format string is returned +/// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. fn last_literal(arg: &str) -> Option<&str> { let close = arg.rfind('"')?; let open = arg[..close].rfind('"')?; + let b = arg.as_bytes(); + let mut depth = 0usize; + for i in (0..open).rev() { + match b[i] { + b')' => depth += 1, + b'(' if depth > 0 => depth -= 1, + b'(' => { + let head = arg[..i].strip_suffix('!').unwrap_or(""); + let name = head.rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).next().unwrap_or(""); + if matches!(name, "format" | "format_args") { + let first = arg[i + 1..].strip_prefix('"')?; + let end = first.find('"')?; + return Some(&arg[i + 1..i + 2 + end + 1]); + } + } + _ => {} + } + } Some(&arg[open..=close]) } @@ -3149,11 +3186,12 @@ fn first_arithmetic(op: &str) -> Option { } /// The whitespace-free source text of the arguments of the call an operand starts with, read from -/// the unmasked source so string literals keep their text. -fn head_args(f: &File, (from, to): (usize, usize)) -> Option> { +/// `code` (the source with comments blanked and string literals kept), so a comment beside a key +/// is not part of it. +fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option> { let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; let close = matching(&f.m, open)?; - Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(&f.src[a..b])).collect()) + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) } /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, @@ -3174,6 +3212,7 @@ fn key_like(arg: &str) -> bool { /// checks that two inputs agree, as a periodicity check does), and two reads at different entries /// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries. fn mirrors(v: &View) -> Vec { + let code = std::cell::OnceCell::new(); v.asserts .iter() .filter(|a| a.name.ends_with("_eq")) @@ -3183,16 +3222,18 @@ fn mirrors(v: &View) -> Vec { let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); let name = head_call(l)?; // Two calls compared as they are check that two inputs agree, which is a real check. + // Arithmetic on exactly one side, in either order, derives that side from the other call. let derived = match (first_arithmetic(l), first_arithmetic(r)) { - (_, None) => false, + (None, None) => false, (Some(i), Some(j)) => l[i..] != r[j..], - (None, Some(_)) => true, + _ => true, }; let last = name.rsplit("::").next().unwrap_or(name); if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) { return None; } - let (la, ra) = (head_args(v.file, lr)?, head_args(v.file, rr)?); + let code: &Vec = code.get_or_init(|| mask_parts(&String::from_utf8_lossy(v.file.src), true, false)); + let (la, ra) = (head_args(v.file, code, lr)?, head_args(v.file, code, rr)?); let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) @@ -3417,6 +3458,46 @@ fn windows_runs(path: &str) -> bool { path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs" } +/// The value of the contents of an ordinary Rust string literal: `\x`, `\u{…}` and the single-character +/// escapes decoded. An escape it cannot read is kept as written. +fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('0') => out.push('\0'), + Some(c @ ('\\' | '"' | '\'')) => out.push(c), + Some('x') => { + let hex: String = chars.by_ref().take(2).collect(); + match u8::from_str_radix(&hex, 16) { + Ok(v) if v < 0x80 => out.push(char::from(v)), + _ => out.push_str(&format!("\\x{hex}")), + } + } + Some('u') if chars.peek() == Some(&'{') => { + let body: String = chars.by_ref().take_while(|&c| c != '}').collect(); + match u32::from_str_radix(&body[1..].replace('_', ""), 16).ok().and_then(char::from_u32) { + Some(v) => out.push(v), + None => out.push_str(&format!("\\u{body}}}")), + } + } + Some(other) => { + out.push('\\'); + out.push(other); + } + None => out.push('\\'), + } + } + out +} + /// 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 { @@ -3445,7 +3526,13 @@ fn cfg_value(p: &str, t: &Target) -> Option { 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 ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's + // contents are kept as written. + let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { + Some(raw) => (k, raw.trim_matches('#').trim_matches('"').to_owned()), + None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), + }); + let value = value.as_str(); match key { "test" => Some(true), "unix" => Some(t.family == "unix"), @@ -3598,7 +3685,7 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, at) != want.chain { + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, src.as_bytes(), at) != want.chain { continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); @@ -3661,7 +3748,7 @@ fn path_children(src: &str, parent: &str) -> Vec<(String, Vec)> { } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { - let chain = inline_mods(&m, at); + let chain = inline_mods(&m, src.as_bytes(), at); out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); } } @@ -3675,18 +3762,20 @@ type Overrides = HashMap)>>; /// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources. fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { let with_path = match base { - Some(base) => git(root, &["grep", "-l", "-w", "path", base, "--", "*.rs"]), - None => git(root, &["grep", "--untracked", "-l", "-w", "path", "--", "*.rs"]), + // `-z` lists each path verbatim, NUL-terminated: without it Git quotes a non-ASCII path. + Some(base) => git(root, &["grep", "-z", "-l", "-w", "path", base, "--", "*.rs"]), + None => git(root, &["grep", "-z", "--untracked", "-l", "-w", "path", "--", "*.rs"]), } .unwrap_or_default(); listed_path_overrides(&with_path, base, read) } -/// Read paths from `git grep -l`, removing the revision prefix for a base-tree listing. +/// Read paths from `git grep -z -l` (NUL-separated), removing the revision prefix for a base-tree listing. fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { let prefix = base.map(|b| format!("{b}:")); let sources: Vec<(String, String)> = list - .lines() + .split('\0') + .filter(|p| !p.is_empty()) .filter_map(|p| match &prefix { Some(prefix) => p.strip_prefix(prefix), None => Some(p), @@ -3745,21 +3834,25 @@ fn join_path(base: &str, rel: &str) -> String { parts.join("/") } -/// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost -/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. -fn inline_mods(m: &[u8], at: usize) -> Vec { - m[..at] - .iter() - .enumerate() - .filter(|&(open, &c)| c == b'{' && matching(m, open).is_some_and(|close| close > at)) - .filter_map(|(open, _)| { - let head = m[..open].trim_ascii_end(); - let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); - let before = head[..head.len() - name].trim_ascii_end(); - (name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident)) - .then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()) - }) - .collect() +/// The directory segments of the inline `mod { … }` blocks around `at` in the masked text +/// `m` (`src` unmasked), outermost first. A `mod x;` inside them loads a file under their directory +/// instead of a sibling file. A block's directory is its name, or the value of a `#[path]` on it +/// (`#[path = "platform_impl"] mod platform { mod child; }` loads `platform_impl/child.rs`). +fn inline_mods(m: &[u8], src: &[u8], at: usize) -> Vec { + let mut dir = String::new(); + for open in (0..at).filter(|&open| m[open] == b'{' && matching(m, open).is_some_and(|close| close > at)) { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + if name == 0 || !before.ends_with(b"mod") || before[..before.len() - 3].last().copied().is_some_and(is_ident) { + continue; + } + let kw = before.len() - 3; + let item = m[..kw].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let seg = path_attr(m, src, item, kw).unwrap_or_else(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()); + dir = join_path(&dir, &seg); + } + dir.split('/').filter(|s| !s.is_empty()).map(str::to_owned).collect() } /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the @@ -3774,6 +3867,8 @@ fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option, override struct Gates { preds: Vec, sources: Vec<(String, Vec)>, + /// Whether a crate target loads the file through at least one route. + reached: bool, } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that @@ -3799,7 +3894,10 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over } let by_path = overrides.get(at).map_or(&[][..], Vec::as_slice); // A crate root runs independently of any module declarations that also load it. - let Some((name, mut candidates)) = module_parent(at) else { return gates }; + let Some((name, mut candidates)) = module_parent(at) else { + gates.reached = true; + return gates; + }; let name = name.to_owned(); let file = at.rsplit_once('/').map_or(at, |(_, f)| f); let Some(mut module_dir) = (if file == "mod.rs" { @@ -3807,15 +3905,23 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over } else { at.rsplit_once('/').map(|(d, _)| d.to_owned()) }) else { + gates.reached = true; return gates; }; let mut chain: Vec = vec![]; let mut found = vec![]; + // Whether a file that could declare the module exists: when none does, the module's parent is + // unknown and the file counts as reached. + let mut parent_read = false; for _ in 0..4 { let want = Loaded { path: at, name: &name, chain: &chain }; // Every file that loads the module is another way in (a library and a binary root // can both load it): its tests are off only when every one of them leaves them out. - found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + found.extend( + candidates + .iter() + .filter_map(|c| read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))), + ); if chain.is_empty() { for (c, inline) in by_path { // A candidate was read with no inline modules; another route through the @@ -3834,8 +3940,15 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over module_dir = up; } let mut each = vec![]; + gates.reached = found.is_empty() && !parent_read; for (parent, (mut preds, lines)) in found { let ancestors = module_gate(&parent, read, overrides, depth + 1); + // A parent that no crate target loads (a file left on disk after its `mod` line was + // removed) is not a route, so it cannot stand in for an ungated one. + if !ancestors.reached { + continue; + } + gates.reached = true; preds.extend(ancestors.preds); gates.sources.push((parent, lines)); gates.sources.extend(ancestors.sources); @@ -5537,12 +5650,16 @@ mod tests { assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n"; assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry"); + let swapped = "#[test]\nfn t() {\n assert_eq!(scale(p, 1.0) * 2.0, scale(p, 2.0));\n}\n"; + assert_eq!(only("mirror", swapped), [(3, "mirror")], "the arithmetic on the left side"); } #[test] fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() { let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n"; assert_eq!(only("mirror", order), [], "positions of two entries in one list"); + let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", commented), [], "a comment beside a key"); let offset = "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); @@ -5961,8 +6078,8 @@ mod tests { let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)]; let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); - let base_overrides = listed_path_overrides(&format!("before:{a}\n"), Some("before"), &read_base); - let work_overrides = listed_path_overrides(&format!("{b}\n"), None, &read_work); + let base_overrides = listed_path_overrides(&format!("before:{a}\0"), Some("before"), &read_base); + let work_overrides = listed_path_overrides(&format!("{b}\0"), None, &read_work); let paths = [child.to_owned()]; let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() }; @@ -5983,6 +6100,65 @@ mod tests { assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it"); } + #[test] + fn a_detached_module_is_not_an_ungated_route() { + let decl = "#[path = \"shared.rs\"]\nmod s;\n"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let shared = "crates/x/src/shared.rs".to_owned(); + for (lib, off) in [("#[cfg(target_os = \"macos\")]\nmod b;\n", true), ("mod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n", false)] { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", decl), ("crates/x/src/b.rs", decl)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let want: &[(usize, &str)] = if off { &[(2, "never-run")] } else { &[] }; + assert_eq!(hits_in(&shared, test, &ctx), want, "{lib}"); + } + } + + #[test] + fn a_path_on_an_inline_module_sets_its_directory() { + let lib = "#[cfg(target_os = \"macos\")]\n#[path = \"platform_impl\"]\nmod platform {\n mod child;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/platform_impl/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]); + } + + #[test] + fn cfg_values_compare_decoded_strings() { + let linux = &CI_TARGETS[0]; + assert_eq!(cfg_value("target_os=\"\\x6cinux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + } + + #[test] + fn path_override_listings_are_nul_separated() { + let files: HashMap<&str, &str> = + [("crates/x/src/a.rs", "#[path = \"s.rs\"]\nmod s;\n"), ("crates/x/src/caf\u{e9}.rs", "#[path = \"t.rs\"]\nmod t;\n")] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let got = listed_path_overrides("base:crates/x/src/a.rs\0base:crates/x/src/caf\u{e9}.rs\0", Some("base"), &read); + assert!(got.contains_key("crates/x/src/s.rs"), "{got:?}"); + assert!(got.contains_key("crates/x/src/t.rs"), "{got:?}"); + } + + #[test] + fn deleted_files_are_kept_as_changed() { + let diff = "diff --git a/crates/x/src/bin/tool.rs b/crates/x/src/bin/tool.rs\ndeleted file mode 100644\n--- a/crates/x/src/bin/tool.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-#[path = \"../shared.rs\"]\n-mod shared;\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/src/bin/tool.rs"), Some(&None), "{got:?}"); + let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); + let seeds: Vec = got.keys().cloned().collect(); + let files = ["crates/x/src/shared.rs".to_owned()]; + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base), ["crates/x/src/shared.rs"]); + } + #[test] fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() { let files: Vec = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"] @@ -6053,6 +6229,11 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read"); + let format_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", format_rs), [(3, "reads-source")], "a format string that names a .rs file"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); From 68a104ba8f2305839a3f1dd278fb3ef41152f4d5 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:00:18 +0530 Subject: [PATCH 11/17] Add item context menus to resource library panels --- crates/ui-egui/src/panels/library_panel.rs | 14 ++++++-- .../ui-egui/src/panels/library_panel/tests.rs | 36 +++++++++++++++++++ docs/ui-parity.md | 1 + 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index e9fc506ec0..1cd5502a2b 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -22,7 +22,7 @@ use std::collections::HashMap; use craft::behavior::{IconId, Selection, SelectionModel}; use craft::host::PickRequest; use craft::theme::variant::Tone; -use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; +use craft::ui::contract::{Bind, Entry, 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::{ @@ -675,7 +675,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { let title = library_name(id, &name).to_string(); // The footer stays under the browser, which scrolls in the room left above it. let footer_out = RefCell::new(None); - let any = !selection.items.is_empty() && can_add(app, K::KIND); + let can_add = can_add(app, K::KIND); + let any = !selection.items.is_empty() && can_add; let mut shown = Panel::new(title.clone()) .collection_body() .footer(|ui, _| *footer_out.borrow_mut() = Some(footer_bar::(any).show_footer(ui))) @@ -686,7 +687,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { .select(SelectMode::Multi) .selection(Bind::given(selection.clone())) .empty(tl!("This library is empty.")) - .row_menu(PresetRowMenu::Off) + .row_menu(PresetRowMenu::Host) + .row_items(move |_: &LibraryKey| vec![Entry::new("ui.libraryPanel.add".to_owned(), K::ADD).enabled(can_add)]) + .host_version(u64::from(can_add)) .drags(K::drags()) .show(ui) }); @@ -696,6 +699,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { for event in events { match event { PresetEvent::Selection(change) => chosen.apply(change), + PresetEvent::Menu { target, command, .. } if command == "ui.libraryPanel.add" && can_add => { + let names = + if chosen.items.contains(&target) { chosen.items.iter().map(|key| key.name.clone()).collect() } else { vec![target.name] }; + K::add(app, id, names); + } // A plain click on an item also adds and applies it; folders and modifier clicks only select. PresetEvent::Select { key, mods, .. } if !key.folder && !mods.shift && !mods.cmd => clicked = Some(key.name), _ => {} diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..58b0effd84 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -182,6 +182,42 @@ fn modifier_clicks_select_and_add_to_swatches_adds_the_selection() { assert!(selected_names(&app, "library:swatches:brights").is_empty()); } +#[test] +fn library_item_menu_adds_the_target_or_its_selection_without_applying_paint() { + for view in ["smallList", "smallThumb"] { + for target in ["Clay 1", "Clay 3"] { + 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": view})).unwrap(); + click(&mut app, &ctx, "Clay 1", Modifiers::COMMAND, 0.0); + click(&mut app, &ctx, "Clay 2", Modifiers::COMMAND, 1.0); + let paint = app.session.paint.fill.clone(); + let undo = undo_len(&app); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let (_, at) = control(&mut app, &ctx, &draw, target); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; + draw_frame(&mut app, &ctx, &draw, vec![Event::PointerMoved(at)]); + draw_frame(&mut app, &ctx, &draw, vec![button(true)]); + draw_frame(&mut app, &ctx, &draw, vec![button(false)]); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + let (_, row) = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::MenuItem && n.label() == Some("Add to Swatches")).unwrap(); + let bounds = row.bounds().unwrap(); + assert_eq!(undo_len(&app), undo, "opening the item menu must not edit the drawing"); + let expected = if target == "Clay 1" { vec!["Clay 1", "Clay 2"] } else { vec!["Clay 3"] }; + assert_eq!(selected_names(&app, &panel), expected); + click_at(&mut app, &ctx, &draw, Pos2::new((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5)); + for name in ["Clay 1", "Clay 2", "Clay 3"] { + assert_eq!(app.session.doc().unwrap().doc.swatch(name).is_some(), expected.contains(&name), "{view}: {target}: {name}"); + } + assert_eq!(app.session.paint.fill, paint); + } + } +} + #[test] fn adding_selected_library_items_requires_an_open_drawing() { let mut app = app(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8bb6c7b87a..775f91c648 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -526,6 +526,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fifteen built-in libraries (original, generated in code) | +| Swatch, Brush, Symbol and Graphic Style Library item menus | done | In list and thumbnail views, the item menu offers the same Add to action as the footer. It adds the current selection when the target is selected or the target alone otherwise. The action requires an open drawing. | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its fill or stroke (solid, gradient or pattern) and the Transparency panel setting its opacity and blend, is on canvas (#6308); `.ai` editing data keeps dynamic symbols and their instance changes when VectorCraft writes and reads it (#8747); on-canvas editing beyond fill, stroke, opacity and blend, and reading other apps' dynamic symbol records, remain | From 8ff9f4cba2ff5d99f4585f249fe8658dc7cecc83 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 1 Dec 2026 23:33:48 +0530 Subject: [PATCH 12/17] .ai import: a visibility variable on hidden styled type binds the group that hides it Since #9228 hidden styled type whose look has its own transparency comes in as a group of the look and the type, and the group holds the hidden and locked state. A visibility variable bound to the type's XML id still bound the type, so showing it left the type hidden. The reader now records the text slot each such group wraps, and a visibility binding on that slot binds the group; text bindings stay on the type. --- crates/eps/src/import/ai/read.rs | 10 ++++--- crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ai/read/ops.rs | 6 ++--- crates/eps/src/import/native/build.rs | 17 +++++++++--- crates/eps/src/import/tests_native.rs | 32 +++++++++++++++++++++++ 5 files changed, 56 insertions(+), 10 deletions(-) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 17d9896ab9..8a29eec63e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -248,6 +248,9 @@ pub struct Structure { /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an /// id two objects have. pub xml_ids: HashMap>, + /// The group of a styled text object and its look, by the text object's slot id. The group, + /// not the type in it, is hidden or locked where the text object was. + pub text_looks: HashMap, /// The objects the variable library binds to its variables, by their XML ids: the importer /// binds those it keeps. pub bindings: Vec, @@ -664,8 +667,9 @@ struct Reader<'a> { ruler_guides: HashMap, /// Legacy compound member groups, even when followed by the generic `9 () XW` marker. compound_groups: HashSet, - /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look. - text_looks: HashSet, + /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look, each + /// with the text object's slot id. + text_looks: HashMap, /// Objects followed by samples of the pen (`(…) Xt n XD`), which aren't read: such an object /// whose style has a Calligraphic brush that varies with the pen keeps its drawn look (see /// [`Self::style_marker`]). @@ -911,7 +915,7 @@ impl<'a> Reader<'a> { looks: HashSet::new(), ruler_guides: HashMap::new(), compound_groups: HashSet::new(), - text_looks: HashSet::new(), + text_looks: HashMap::new(), pen_samples: HashSet::new(), group_ended: false, mesh_ended: false, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 20102b29c4..ec14b864d9 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1485,6 +1485,7 @@ impl<'a> Reader<'a> { canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, + text_looks: self.text_looks.into_iter().map(|(group, slot)| (slot, group)).collect(), bindings, bindings_skipped, warnings, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index bb5343e4f4..1b9d6aa20b 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -822,7 +822,7 @@ impl<'a> Reader<'a> { // The look is a group of paths, or one image where an effect (a blur, a shadow) rasterizes it. if !self.hidden_ids.contains(&object.id) || self.hidden_ids.contains(&look.id) != hidden - || self.text_looks.contains(&look.id) + || self.text_looks.contains_key(&look.id) || !matches!(look.kind, NodeKind::Group { clip: false, .. } | NodeKind::Image(_)) { return; @@ -978,7 +978,7 @@ impl<'a> Reader<'a> { let Some(mut look) = f.children.pop() else { return }; let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); - let (visible, locked) = (object.visible, object.locked); + let (visible, locked, slot) = (object.visible, object.locked, object.id); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); object.visible = true; object.locked = false; @@ -986,7 +986,7 @@ impl<'a> Reader<'a> { (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; group.visible = visible; group.locked = locked; - self.text_looks.insert(group.id); + self.text_looks.insert(group.id, slot); if let Some(f) = self.frames.last_mut() { f.children.push(group); } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 0637e8e079..9daa57bfd8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -350,6 +350,7 @@ pub(super) fn build_weighing( canvas_scale, symbols_own_size, xml_ids, + text_looks, bindings, bindings_skipped, warped_type, @@ -653,7 +654,7 @@ pub(super) fn build_weighing( None => unmark(&mut doc.layers, true, true, &mut vec![]), } doc.limit_depth_noting(&mut notes); - bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); + bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &text_looks, &mut notes); if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) { notes.push(ai::LINKED_PREVIEWS.to_string()); } @@ -731,7 +732,9 @@ fn to_placed_documents( /// Bind the objects of `doc` to the variables of its library that `bindings` binds them to, each /// object named by its XML id (`ids`: the object read with that id, or what `filled` made of a text /// object's slot: for a visibility variable every object that took the slot's place, for a text -/// variable the one text object among them). An object is bound when it is of the variable's kind: +/// variable the one text object among them). A visibility variable binds a styled text object's +/// group with its look (`text_looks`, by slot) in place of the type: the group is what is hidden or +/// shown. An object is bound when it is of the variable's kind: /// type for a text variable, a linked image for an image variable, any object for a visibility /// variable. Locked and hidden objects, objects in locked or hidden layers and groups, and objects /// on locked artboards keep their bindings. Graph variables and @@ -743,6 +746,7 @@ fn bind_variables( skipped: usize, ids: &std::collections::HashMap>, filled: &std::collections::HashMap, + text_looks: &std::collections::HashMap, notes: &mut Vec, ) { let mut skipped = skipped; @@ -753,7 +757,12 @@ fn bind_variables( let mut bound = vec![]; for b in bindings { let kind = doc.variables.variable(&b.variable).map(|v| v.kind); - let targets = match (b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()), kind) { + let target = b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()); + let target = match kind { + Some(VariableKind::Visibility) => target.map(|id| text_looks.get(&id).copied().unwrap_or(id)), + _ => target, + }; + let targets = match (target, kind) { (Some(id), Some(kind)) => match filled.get(&id) { Some(f) if kind == VariableKind::Visibility => f.objects.clone(), Some(f) => match f.text.as_slice() { @@ -2819,7 +2828,7 @@ mod candidate_tests { bind("v_graph", "path"), ]; let mut notes = vec![]; - bind_variables(&mut doc, &refs, 3, &ids, &filled, &mut notes); + bind_variables(&mut doc, &refs, 3, &ids, &filled, &Default::default(), &mut notes); let sorted = |mut v: Vec| { v.sort(); v diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index c5b6b61d58..d51573877a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2240,6 +2240,38 @@ fn ai_variable_bindings_bind_the_objects_they_name() { assert!(!r.warnings.iter().any(|w| w.contains("variable library")), "{:?}", r.warnings); } +/// Hidden, locked type whose style comes in as a group of its drawn look and the type (the look has +/// its own transparency) is hidden and locked on that group. A visibility variable bound to the +/// type binds the group, so showing it shows the type; a text variable still binds the type. +#[test] +fn a_visibility_variable_on_hidden_styled_type_binds_the_group_that_hides_it() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let declare = |name: &str, t: &str| { + let uid = "/XMLUIDREF : (type_x5F_1) ;"; + let attributes = [("trait", XmlValue::Str(t)), ("varName", XmlValue::Unicode(name)), ("docRef", XmlValue::Raw(uid))]; + xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }; + let declared = vec![declare("v_shown", "visibility"), declare("v_text", "textcontent")]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf"; + // The look at half opacity; the type hidden (`1 Xw`) and locked (`1 A`), with its XML id. + let look = format!("0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{drawing}\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n"); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let styled = format!("{look}1 Xw\n1 A\n{own}{}1 (Unlisted) XW\n0 Xw\n0 A\n", named("type_x5F_1")); + let art = native_with_text(&(library + &layer("Art", true, &styled)), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let a = d.layers[0].children().unwrap(); + let [group] = a.as_slice() else { panic!("one group of the look and the type: {a:#?} {notes:?}") }; + assert!(matches!(group.kind, NodeKind::Group { .. }) && !group.visible && group.locked, "{group:#?}"); + let type_id = group.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id); + assert!(type_id.is_some(), "{group:#?}"); + let vars = &d.variables; + assert_eq!(vars.objects_of("v_shown"), [group.id], "the hidden group, not the type in it: {notes:?}"); + assert_eq!(vars.objects_of("v_text").first().copied(), type_id, "{notes:?}"); +} + /// An EPS whose editing data can't be used, a palette with no layers among others, comes in as its /// page with the swatches and color groups of that palette in place of the defaults. #[test] From 82cb6ef291580f4a897998b8eabf7ed14e5d0aa5 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 1 Dec 2026 23:46:40 +0530 Subject: [PATCH 13/17] .ai import: hold the page type's word searches to their own budget #9228 let a file with many text objects whose type is made be weighed by where its pieces of type lie, up to four times the comparisons word matching may make. The page's type lying where made type draws was still searched word by word in every made text object there, and in the lines of hidden made type, so those searches could run to the larger limit. They are now counted on their own, up to MAX_PAIRS. Past it, type where made type that shows draws is taken as that type, type over hidden made type only stays on the page, and the page's type is noted as unchecked. The letters of hidden made type's lines are worked out once. --- crates/eps/src/import/native/plan.rs | 183 +++++++++++++++++++++++---- 1 file changed, 160 insertions(+), 23 deletions(-) diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index a23e8ea324..a15c272222 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -154,8 +154,19 @@ pub(super) fn made_only( if looks && infos.len().saturating_mul(shown.len()) <= MAX_PAIRS { let spelled: Vec = content.iter().map(|c| if let Content::Made(node, ..) = c { spelling(&plain_text(node)) } else { String::new() }).collect(); - let made_type = |o: &[Arc]| covered(o, &content, |_| true) && has_made_words(o, &content, &spelled); + // Past the word searches, type where made type draws is taken to be that type. + let (mut checks, mut unchecked) = (WordChecks::new(), false); + let mut made_type = |o: &[Arc]| { + covered(o, &content, |_| true) + && has_made_words(o, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }) + }; let mut spare: Vec>> = shown.iter().filter(|o| !made_type(o)).cloned().collect(); + if unchecked { + note_unchecked(warn); + } fill_look_slots(infos, &mut content, &mut spare); for c in &content { if let Content::Page(parts) = c { @@ -173,7 +184,7 @@ pub(super) fn made_only( match see_page_type(&mut content, untaken) { Some(0) => {} Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()), - None => warn.push(PAGE_TYPE_UNCHECKED.into()), + None => note_unchecked(warn), } drop_look_slots(infos, &mut content); fill_hidden(infos, stories, &mut content, hidden); @@ -274,17 +285,64 @@ fn fill_look_slots(infos: &[SlotInfo], content: &mut [Content], spare: &mut Vec< drop_look_slots(infos, content); } +/// How many more times a word of the page's type may be looked for in a text object's type. The +/// page's type is weighed against where every text object lies up to `MAX_PLACE_PAIRS` pairs, a box +/// against a box, but each text object a piece of it lies on can be searched for each of its words: +/// those searches are held to `MAX_PAIRS` of their own. +struct WordChecks(usize); + +impl WordChecks { + fn new() -> Self { + WordChecks(MAX_PAIRS) + } + + /// One more search, if any are left. + fn spend(&mut self) -> Option<()> { + self.0 = self.0.checked_sub(1)?; + Some(()) + } + + /// Are no searches left? + fn spent(&self) -> bool { + self.0 == 0 + } +} + /// Has made type that shows and draws where the page's text object `object` lies every word of it -/// ([`spelling`], each slot's in `spelled`), in any order? -fn has_made_words(object: &[Arc], content: &[Content], spelled: &[String]) -> bool { - let Some(r) = extent(object) else { return true }; +/// ([`spelling`], each slot's in `spelled`), in any order? `None` once `checks` runs out before +/// that is known. +fn has_made_words(object: &[Arc], content: &[Content], spelled: &[String], checks: &mut WordChecks) -> Option { + let Some(r) = extent(object) else { return Some(true) }; + if checks.spent() { + return None; + } let near: Vec<&String> = content .iter() .zip(spelled) .filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area())) .map(|(_, s)| s) .collect(); - object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str()))) + for w in object_words(object) { + let mut found = false; + for s in &near { + checks.spend()?; + if s.contains(w.as_str()) { + found = true; + break; + } + } + if !found { + return Some(false); + } + } + Some(true) +} + +/// Note once in `warn` that some of the page's type wasn't checked against the text objects. +fn note_unchecked(warn: &mut Vec) { + if !warn.iter().any(|w| w == PAGE_TYPE_UNCHECKED) { + warn.push(PAGE_TYPE_UNCHECKED.into()); + } } /// The text slots for type that a look draws and that have nothing have no type of their own to hold @@ -438,9 +496,16 @@ pub(super) fn plan( let made_stories: std::collections::BTreeSet = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect(); let open: Vec = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect(); let owner = match_page_objects(infos, &lines, &open, shown); - // Where the made type that doesn't show lies, by slot. - let hidden_at: Vec<(usize, Rect)> = - infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); + // Where the made type that doesn't show lies, and the letters of its lines (it has lines). + let hidden_at: Vec<(Rect, Vec)> = infos + .iter() + .zip(&made) + .enumerate() + .filter_map(|(k, (info, m))| { + let place = m.as_ref().filter(|_| !info.shown)?.1?; + Some((place, lines.get(k)?.as_ref()?.iter().map(|(text, _)| letters(text)).collect())) + }) + .collect(); // Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box // stays that of type without a layout here: with text objects whose type isn't made stacked on // made type that has their words (the copies of an outlined heading), the page's pieces in the @@ -448,17 +513,34 @@ pub(super) fn plan( let mut content = made_content(infos, made, false); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) - let hidden_type = |object: &[Arc]| { - let Some(r) = extent(object) else { return false }; + // `None` once `checks` runs out before that is known. + let hidden_type = |object: &[Arc], checks: &mut WordChecks| -> Option { + let Some(r) = extent(object) else { return Some(false) }; let texts: Vec> = object.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text())) } else { None }).collect(); - hidden_at.iter().any(|(k, place)| { - place.intersect(r).area() >= 0.5 * r.area().max(1e-9) - && lines.get(*k).and_then(Option::as_ref).is_some_and(|l| { - !texts.is_empty() - && texts.iter().all(|ws| !ws.is_empty() && ws.iter().all(|w| l.iter().any(|(text, _)| letters(text).contains(w.as_str())))) - }) - }) + if texts.is_empty() || texts.iter().any(Vec::is_empty) { + return Some(false); + } + for (place, l) in &hidden_at { + if place.intersect(r).area() < 0.5 * r.area().max(1e-9) { + continue; + } + let mut all = true; + 'words: for w in texts.iter().flatten() { + for text in l { + checks.spend()?; + if text.contains(w.as_str()) { + continue 'words; + } + } + all = false; + break; + } + if all { + return Some(true); + } + } + Some(false) }; // The letters and digits of each slot's made type that shows, in any script, in lower case. let spelled: Vec = content @@ -472,6 +554,10 @@ pub(super) fn plan( }) .collect(); let mut spare: Vec>> = vec![]; + // The word searches below are held to their own budget: past it, type where made type that shows + // draws is taken to be that type (made type is there either way), and type where only made type + // that doesn't show lies stays on the page (it would not show otherwise). + let (mut checks, mut unchecked) = (WordChecks::new(), false); for (j, object) in shown.iter().enumerate() { match owner.get(j).copied().flatten() { Some(k) => match content.get_mut(k) { @@ -479,13 +565,28 @@ pub(super) fn plan( Some(c) => *c = Content::Page(object.clone()), None => {} }, - // What lies where made type draws, with its words, is that type as the page draws it (in - // another font, maybe, and in any script). - None if covered(object, &content, |_| true) && has_made_words(object, &content, &spelled) => {} - None if hidden_type(object) => {} - None => spare.push(object.clone()), + None => { + // What lies where made type draws, with its words, is that type as the page draws it + // (in another font, maybe, and in any script). + let theirs = covered(object, &content, |_| true) + && has_made_words(object, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }); + let hidden = !theirs + && hidden_type(object, &mut checks).unwrap_or_else(|| { + unchecked = true; + false + }); + if !theirs && !hidden { + spare.push(object.clone()); + } + } } } + if unchecked { + note_unchecked(warn); + } // The page's type that no made type takes is the spare type below. let _ = see_page_type(&mut content, shown); for (k, c) in content.iter_mut().enumerate() { @@ -600,3 +701,39 @@ fn fill_hidden(infos: &[SlotInfo], stories: &[Option>], content: &mut } } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{CharStyle, TextObject}; + + fn text(id: u64, s: &str) -> Node { + let style = CharStyle { size: 12.0, ..CharStyle::default() }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(100.0, 100.0), s, style)))) + } + + /// The page's type is searched for in every made text object that draws where it lies, word by + /// word: those searches stop when their budget runs out, saying they didn't finish, however many + /// made text objects lie there. A word is searched for only until a text object has it. + #[test] + fn word_searches_of_the_page_s_type_stop_when_their_budget_runs_out() { + let everywhere = Rect::new(-1e4, -1e4, 1e4, 1e4); + let slots = 50; + let content: Vec = (0..slots).map(|k| Content::Made(Box::new(text(k, "Other type")), Some(everywhere), false)).collect(); + let spelled: Vec = + content.iter().map(|c| if let Content::Made(n, ..) = c { spelling(&plain_text(n)) } else { String::new() }).collect(); + // A word no made type has is searched for in each of them. + let missing = vec![Arc::new(text(1000, "Alpha beta"))]; + let one_word_everywhere = slots as usize; + let mut short = WordChecks(one_word_everywhere - 1); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut short), None, "past the budget the answer isn't known"); + assert!(short.spent()); + let mut enough = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut enough), Some(false)); + // Words that the first made type has are found there, without searching the others. + let present = vec![Arc::new(text(1001, "other TYPE"))]; + let mut few = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true)); + assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0); + } +} From 186e6db9bae18223917fe6cbb24dccbaaa68f864 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:34:08 -0800 Subject: [PATCH 14/17] xtask: test-lint reads renames, cfg_attr paths, casts and arm bindings - changed mode diffs with --no-renames, so an exact rename lists the old path as deleted and the new path as added, and both seed the route walk. - census reads a cast of the loop binding (k as usize) as the entry, and no longer reads a field or path segment named like it (config.k, m::k). - reads-source takes the file name from the final .join(...) component; a final component that is not a literal is an unknown file. - mirror keeps whitespace inside string literals when it compares lookup keys, so "A B" and "AB" are different entries. - fixture-only resolves a name bound by a match arm's pattern to that arm, not to an outer let; a guard still reads the outer binding. - never-run follows #[cfg_attr(, path = "...")] overrides: the selected path is loaded where the condition holds, and the default path elsewhere. - never-run treats tests//mod.rs as loaded by the test targets beside it, like a crate root. - exact-pixel no longer reports two rects compared by their difference (a.width() - b.width()). --- xtask/src/test_lint.rs | 266 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 245 insertions(+), 21 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 0c7d793c0f..0e3baa802e 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -343,9 +343,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_off: RefCell>> = RefCell::new(HashMap::new()); let newly_off = |path: &str, src: &str, hit: &Hit| { let mut cache = base_off.borrow_mut(); - let off = cache.entry(path.to_owned()).or_insert_with(|| { - lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() - }); + let off = cache + .entry(path.to_owned()) + .or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()); !off.contains(&(hit.test.clone(), hit.line)) }; let (mut counted, mut older) = (vec![], 0usize); @@ -560,6 +560,8 @@ fn changed_lines(root: &Path, base: &str) -> Result bool { }) } -/// Whether `s` contains the identifier `var` as a whole word. +/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or +/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`). fn reads_ident(s: &str, var: &str) -> bool { + const PRIMITIVES: &[&str] = + &["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"]; let b = s.as_bytes(); + let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident); !var.is_empty() && s.match_indices(var).any(|(at, _)| { let end = at + var.len(); - !(at > 0 && is_ident(b[at - 1])) && !b.get(end).copied().is_some_and(is_ident) + let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); + let path = at > 1 && &b[at - 2..at] == b"::"; + let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends))); + !(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast) }) } @@ -3084,8 +3093,12 @@ fn reads_source_hits(file: &File) -> Vec { let rs = match word { b"ends_with" => literal == "\".rs\"", // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, - // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. A final + // component that is not a literal (`.join(name)`) names an unknown file. + b"read_to_string" => { + let last = arg.rfind(".join(").and_then(|at| matching(arg.as_bytes(), at + 5).map(|close| &arg[at + 6..close])); + last_literal(last.unwrap_or(&arg)).is_some_and(|l| l.ends_with(".rs\"")) + } _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3191,7 +3204,35 @@ fn first_arithmetic(op: &str) -> Option { fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option> { let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; let close = matching(&f.m, open)?; - Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm_outside_literals(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) +} + +/// [`norm`] that keeps whitespace inside string literals: `"A B"` and `"AB"` are different keys. +fn norm_outside_literals(b: &[u8]) -> String { + let mut out = Vec::with_capacity(b.len()); + let mut in_str = false; + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + out.push(c); + if c == b'\\' { + if let Some(&n) = b.get(i + 1) { + out.push(n); + i += 1; + } + } else if c == b'"' { + in_str = false; + } + } else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) { + in_str = true; + out.push(c); + } else if !c.is_ascii_whitespace() { + out.push(c); + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() } /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, @@ -3321,13 +3362,67 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), (None, _) => found.map(|(init, _)| init), } } +/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body +/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not. +fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { + let mut found = None; + for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") { + // The pattern runs back to the `{` or `,` that opens the arm. + let mut depth = 0usize; + let mut start = arrow; + while start > 0 { + match body[start - 1] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => break, + b'(' | b'[' | b'{' => depth -= 1, + b',' if depth == 0 => break, + _ => {} + } + start -= 1; + } + // A guard (`Some(x) if x == n`) reads names; it does not bind them. + let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); + let pattern = norm(&body[start..guard]); + if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + continue; + } + // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. + let from = skip_ws(body, arrow + 2); + let end = match body.get(from) { + Some(b'{') => matching(body, from), + _ => { + let mut depth = 0usize; + (from..body.len()).find(|&i| match body[i] { + b'(' | b'[' | b'{' => { + depth += 1; + false + } + b')' | b']' | b'}' if depth == 0 => true, + b')' | b']' | b'}' => { + depth -= 1; + false + } + b',' => depth == 0, + _ => false, + }) + } + }; + if end.is_some_and(|end| before < end) { + found = Some(arrow); + } + } + found +} + /// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { let mut found = None; @@ -3644,13 +3739,20 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { /// 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` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `examples` beside a crate's `src`, or a file directly in `src/bin`), and for a `mod.rs` one +/// directory below those, which their roots load (`tests/common/mod.rs`). A `tests` directory under /// `src` holds modules, not test targets. fn module_parent(path: &str) -> Option<(&str, Vec)> { let (dir, file) = path.rsplit_once('/')?; - let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); - let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin"); - if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { + let is_root_dir = |dir: &str| { + let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); + ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin") + }; + let root_dir = is_root_dir(dir); + // `tests/common/mod.rs` is loaded by the target roots beside it (`tests/smoke.rs` with + // `mod common;`), which are not listed here, so it counts as reached like a root. + let beside_roots = file == "mod.rs" && dir.rsplit_once('/').is_some_and(|(up, _)| is_root_dir(up)); + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") || beside_roots { return None; } let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; @@ -3689,22 +3791,38 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => override_path(dir, file, mod_rs, want.chain, &rel) == want.path, + // A `cfg_attr` override loads its path where its condition holds, and the default (or a + // plain `#[path]`) elsewhere. + let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); + let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; + let fallback = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => overrides_here(&rel), None => { &m[start..end] == want.name.as_bytes() && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } }; - if !loads { - continue; - } + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let route = match (fallback, selected.is_empty(), conditional.is_empty()) { + (true, _, true) => None, + (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::>().join(","))), + (true, false, false) => { + let others: Vec<&str> = conditional.iter().filter(|(_, rel)| !overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + (!others.is_empty()).then(|| format!("not(any({}))", others.join(","))) + } + (false, true, _) => continue, + (false, false, _) => Some(format!("any({})", selected.join(","))), + }; // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); at_lines.push(lines.of(at)); // Every line of a multiline attribute counts: an edit inside its predicate changes it. at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); + if let Some(route) = route { + preds.push(route); + at_lines.extend(lines.of(skip_ws(&m, item))..=lines.of(at)); + } for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); at_lines.extend(lines.of(a)..=lines.of(e)); @@ -3747,7 +3865,9 @@ fn path_children(src: &str, parent: &str) -> Vec<(String, Vec)> { continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + let rels = + path_attr(&m, src.as_bytes(), item, at).into_iter().chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, r)| r)); + for rel in rels { let chain = inline_mods(&m, src.as_bytes(), at); out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); } @@ -3819,6 +3939,31 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { }) } +/// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and +/// path. +fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { + let mut out = vec![]; + for at in words(m, b"cfg_attr", from, to) { + if !m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) { + continue; + } + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let text = pred_text(&src[open + 1..close]); + let cuts = top_level_at(&text, ","); + let Some(&first) = cuts.first() else { continue }; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(rel) = arg.strip_prefix("path=\"").and_then(|r| r.strip_suffix('"')) { + out.push((text[..first].to_owned(), rel.to_owned())); + } + start = cut + 1; + } + } + out +} + /// `rel` joined to the directory `base`, with `.` and `..` resolved. fn join_path(base: &str, rel: &str) -> String { let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); @@ -4028,8 +4173,14 @@ fn names_rect(op: &str) -> bool { if b.get(after) == Some(&b'(') { after = matching(b, after).map_or(b.len(), |c| c + 1); } - let rest = &op[after..]; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + // The rect and its parts make up the whole operand: `a.width() - b.width()` compares two + // rects, not one with a number. + let mut rest = &op[after..]; + while let Some(r) = RECT_PARTS.iter().chain(&[".x", ".y"]).find_map(|p| rest.strip_prefix(p)) { + rest = r; + } + let lead = op[..i].trim_start_matches(['&', '*', '(']); + if rest.trim_start_matches(')').is_empty() && !lead.contains(['+', '-', '*', '/', '%', ',']) { return true; } } @@ -4112,6 +4263,13 @@ mod tests { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n"; assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); + let cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(k as usize), k);\n }\n}\n"; + assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); + let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; + assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let field = + "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; + assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; assert_eq!(census(derived), [(2, "census")]); let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n"; @@ -5660,6 +5818,10 @@ mod tests { assert_eq!(only("mirror", order), [], "positions of two entries in one list"); let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; + assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); + let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; + assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not"); let offset = "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); @@ -5678,6 +5840,10 @@ mod tests { 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 arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", arm), [], "a match arm binds its own n"); + let outer = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) if m == n => assert_eq!(n, 0),\n _ => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", outer), [(2, "fixture-only")], "a guard reads the outer n"); 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"; @@ -5921,6 +6087,18 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets"); assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src"); + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/common/mod.rs\"]\nmod common;\n"), + ("crates/x/tests/smoke.rs", "mod common;\n"), + ("crates/x/tests/common/mod.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/tests/common/mod.rs".to_owned(); + let shared_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &shared_ctx), [], "a test target beside it loads the shared module on every target"); } #[test] @@ -5955,6 +6133,45 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn never_run_follows_a_path_selected_by_cfg_attr() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"live.rs\")]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n"), + ("crates/x/src/live.rs", ""), + ("crates/x/src/platform.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let live = "crates/x/src/live.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..ctx() }; + assert_eq!(hits_in(&live, test, &ctx), [], "Linux loads live.rs through the cfg_attr path"); + let platform = "crates/x/src/platform.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides); + assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere"); + } + + #[test] + fn changed_lines_lists_both_paths_of_an_exact_rename() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-rename-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n"; + std::fs::write(root.join("crates/x/src/bin/tool.rs"), src).unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::create_dir_all(root.join("crates/x/src/disabled")).unwrap(); + std::fs::rename(root.join("crates/x/src/bin/tool.rs"), root.join("crates/x/src/disabled/tool.rs")).unwrap(); + git(&root, &["add", "-A"]).unwrap(); + let changed = changed_lines(&root, &base).unwrap(); + assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted"); + assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn never_run_joins_inline_and_override_routes() { for (lib, child) in [ @@ -6208,6 +6425,8 @@ mod tests { 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!(left_rect.width() - right_rect.width(), 0.0);"), [], "two rects compared by their difference"); + assert_eq!(px("assert_eq!(left_rect.width(), 120.0);"), [(4, "exact-pixel")]); 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"); @@ -6229,6 +6448,11 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let unknown = "#[test]\nfn t() {\n let name = \"data.json\";\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(name)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", unknown), [], "a final component that is not a literal"); + let joined = + "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read"); let format_rs = From a7654fc63850be4ca7a0c42f05acbb0077e6aa2a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:17:26 -0800 Subject: [PATCH 15/17] xtask: test-lint matches base tests by place and keeps route kinds apart - never-run in changed mode lints the file as it was at the base and matches a test by its name and its place among tests of that name, so a test that was already off is not counted again when lines move. - A file reached by name inherits only the gates of named declarations, and one reached through #[path] only those of #[path] declarations. - The changed-file walk also reads the base child declarations of a #[path]-loaded file, so a removed `mod child;` still reaches the child. - reads-source classifies the outer path step, not a join nested in its argument. - mirror treats complete raw string literals as keys. - A raw cfg value keeps the quotes inside it (r#""unix""# is not unix). - census keeps word boundaries, so `k as usize` reads `k` and the local `kasusize` does not. - fixture-only finds a for loop's `in` across line breaks. --- xtask/src/test_lint.rs | 243 +++++++++++++++++++++++++++++++++-------- 1 file changed, 197 insertions(+), 46 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index fe0090fa33..40ac3b2f25 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -330,7 +330,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. let seeds: Vec = changed.keys().cloned().collect(); let below: Vec = - descendants(&seeds, &files, &overrides, &base_overrides, &read_work).into_iter().filter(|p| !changed.contains_key(p)).collect(); + descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); @@ -340,14 +340,17 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - // The base's `never-run` hits, computed once per file on its first parent-attributed hit. - let base_off: RefCell>> = RefCell::new(HashMap::new()); + // The base's `never-run` hits on the file as it was at the base (the current source when the + // file is new or moved), computed once per file on its first parent-attributed hit. + let base_off: RefCell)>> = RefCell::new(HashMap::new()); let newly_off = |path: &str, src: &str, hit: &Hit| { let mut cache = base_off.borrow_mut(); - let off = cache - .entry(path.to_owned()) - .or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()); - !off.contains(&(hit.test.clone(), hit.line)) + let (base_src, off) = cache.entry(path.to_owned()).or_insert_with(|| { + let base_src = read_base(path).unwrap_or_else(|| src.to_owned()); + let off = lint_file(path, &base_src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + (base_src, off) + }); + !already_off(off, base_src, src, hit) }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { @@ -369,11 +372,21 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { finish(&counted, older, present.len(), &base) } -/// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the -/// test of `hit`. Tests of one name in different inline modules are told apart by their line. -#[cfg(test)] -fn already_off(base: &[Hit], hit: &Hit) -> bool { - base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +/// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test +/// of `hit` in `src`. A test is matched by its name and its place among the tests of that name, so +/// lines that moved still match and tests of one name in different inline modules stay apart. +fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { + let place = test_place(src, &hit.test, hit.line); + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match place { + Some(place) => test_place(base_src, &h.test, h.line) == Some(place), + None => h.line == hit.line, + }) +} + +/// The index of the test `name` whose `fn` is on `line` among the tests of that name in `src`. +fn test_place(src: &str, name: &str, line: usize) -> Option { + let lines = Lines::new(src); + tests_in(&mask(src)).iter().filter(|t| t.name == name).position(|t| lines.of(t.fn_at) == line) } /// The directory holding the modules that the file `p` declares by name: its own directory for @@ -387,13 +400,15 @@ fn module_dir(p: &str) -> String { /// The files of `files` that the files `start` load, directly or through modules in between: the /// files under their module directories and the files their current or base `#[path]` declarations load. /// A file loaded through `#[path]` also loads the modules it declares by name from its own directory -/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read`. +/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read` and, for the +/// declarations a change removed, through `read_base`. fn descendants( start: &[String], files: &[String], overrides: &Overrides, base_overrides: &Overrides, read: &dyn Fn(&str) -> Option, + read_base: &dyn Fn(&str) -> Option, ) -> Vec { let mut seen: BTreeSet = start.iter().cloned().collect(); let mut frontier: Vec = start.to_vec(); @@ -404,7 +419,12 @@ fn descendants( return vec![]; } let dir = p.rsplit_once('/').map_or("", |(d, _)| d); - read(p).map_or(vec![], |src| declared_names(&src).into_iter().flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]).collect()) + [read(p), read_base(p)] + .into_iter() + .flatten() + .flat_map(|src| declared_names(&src)) + .flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]) + .collect() }; let dirs: Vec = frontier.iter().map(|p| module_dir(p)).chain(frontier.iter().flat_map(beside)).collect(); let next: Vec = files @@ -973,6 +993,25 @@ fn norm(b: &[u8]) -> String { String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() } +/// [`norm`], except that whitespace between two identifier characters becomes one space, so +/// `k as usize` stays three words and `kasusize` stays one. Removing the spaces gives [`norm`]. +fn norm_words(b: &[u8]) -> String { + let mut out = vec![]; + let mut gap = false; + for &c in b { + if c.is_ascii_whitespace() { + gap = true; + continue; + } + if gap && is_ident(c) && out.last().copied().is_some_and(is_ident) { + out.push(b' '); + } + gap = false; + out.push(c); + } + String::from_utf8_lossy(&out).into_owned() +} + /// Line starts, to turn byte offsets into 1-based lines. struct Lines(Vec); @@ -1545,7 +1584,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { helpers_in(from, to).is_empty() && !rejects(body) && !inside.is_empty() - && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) + && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::>(), var)) }; for at in words(m, b"for", v.t.open, v.t.close) { let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue }; @@ -1788,10 +1827,10 @@ fn weak_predicate_within(pred: &str, depth: usize) -> bool { } /// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares -/// a lookup or parse with the entry itself. +/// a lookup or parse with the entry itself. `args` are written as [`norm_words`] gives them. fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { match guard_arg_count(name) { - 1 => args.first().is_some_and(|a| weak_predicate(a)), + 1 => args.first().is_some_and(|a| weak_predicate(&a.replace(' ', ""))), 2 if name.ends_with("_ne") => false, 2 => match args { [a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)), @@ -1801,7 +1840,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { } } -/// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole +/// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole /// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so /// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's /// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is @@ -1826,20 +1865,16 @@ fn round_trip_call(op: &str, var: &str) -> bool { }) } -/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or -/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`). +/// Whether `s`, written as [`norm_words`] gives it, reads the binding `var`: a whole word that is not +/// a field or path segment (`config.k`, `m::k`), alone or cast (`k as usize`). `kasusize` is one word. fn reads_ident(s: &str, var: &str) -> bool { - const PRIMITIVES: &[&str] = - &["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"]; let b = s.as_bytes(); - let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident); !var.is_empty() && s.match_indices(var).any(|(at, _)| { let end = at + var.len(); let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); let path = at > 1 && &b[at - 2..at] == b"::"; - let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends))); - !(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast) + !(at > 0 && is_ident(b[at - 1])) && !field && !path && !b.get(end).copied().is_some_and(is_ident) }) } @@ -3137,10 +3172,11 @@ fn reads_source_hits(file: &File) -> Vec { // The final path step names the file read: the last literal of `root.join("src/lib.rs")` // or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the // extension of a final `.with_extension("json")`. A final step whose argument is not a - // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. + // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on + // the outer path count: a `.join` inside another step's argument does not. b"read_to_string" => { let step = |s: &'static str| { - arg.rfind(s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + rfind_outer(&arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) }; match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { Some((_, ".with_extension(", ext)) => ext.trim_start_matches('r').trim_matches('#') == "\"rs\"", @@ -3161,6 +3197,35 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// The offset of the last `pat` in `expr` outside every bracket and string literal. +fn rfind_outer(expr: &str, pat: &str) -> Option { + let b = expr.as_bytes(); + let (mut depth, mut in_str, mut found) = (0usize, false, None); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + if depth == 0 && b[i..].starts_with(pat.as_bytes()) { + found = Some(i); + } + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + _ => {} + } + } + i += 1; + } + found +} + /// The last string literal in a (whitespace-free) expression, quotes included. Inside a /// `format!`-family call, an argument is not the file name, so the format string is returned /// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. @@ -3284,12 +3349,22 @@ fn norm_outside_literals(b: &[u8]) -> String { String::from_utf8_lossy(&out).into_owned() } +/// The contents of a complete raw string literal written after its `r`: `"a"` and `#"a"#` give `a`, +/// and `#""a""#` gives `"a"`. `None` when `s` is not one whole literal. +fn raw_literal_body(s: &str) -> Option<&str> { + let hashes = s.len() - s.trim_start_matches('#').len(); + let close = format!("\"{}", "#".repeat(hashes)); + let body = s[hashes..].strip_prefix('"')?.strip_suffix(close.as_str())?; + (!body.contains(close.as_str())).then_some(body) +} + /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, /// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). fn key_like(arg: &str) -> bool { let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); match arg.as_bytes().first() { Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), None => false, @@ -3406,9 +3481,9 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option { // An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's // contents are kept as written. let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { - Some(raw) => (k, raw.trim_matches('#').trim_matches('"').to_owned()), + Some(raw) => (k, raw_literal_body(raw).unwrap_or(raw).to_owned()), None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), }); let value = value.as_str(); @@ -3960,8 +4035,9 @@ struct Loaded<'a> { /// items, inline modules and file around them, with the 1-based lines of those declarations and /// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None` /// when `src` loads no such file. `owns_dir` reads `parent` as loaded through `#[path]`, which -/// declares its modules in its own directory, as a `mod.rs` or a crate root does. -fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Option<(Vec, Vec)> { +/// declares its modules in its own directory, as a `mod.rs` or a crate root does. `via` keeps only +/// the declarations that load `want` by name (`Named`) or through `#[path]` (`Path`). +fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool, via: Via) -> Option<(Vec, Vec)> { let m = mask(src); let lines = Lines::new(src); let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); @@ -3993,13 +4069,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Opti let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; let fallback = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => overrides_here(&rel), + Some(rel) => via != Via::Named && overrides_here(&rel), None => { - &m[start..end] == want.name.as_bytes() + via != Via::Path + && &m[start..end] == want.name.as_bytes() && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } }; - let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| via != Via::Named && overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); let route = match (fallback, selected.is_empty(), conditional.is_empty()) { (true, _, true) => None, (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::>().join(","))), @@ -4294,7 +4371,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over // can both load it): its tests are off only when every one of them leaves them out. if via != Via::Path { found.extend(candidates.iter().filter_map(|c| { - read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, named(c))) + read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, named(c))) })); } if chain.is_empty() { @@ -4305,7 +4382,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over continue; } let want = Loaded { path: at, name: &name, chain: inline }; - found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, Via::Any))); + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, Via::Any))); } // A file loaded through `#[path]` owns its directory like a `mod.rs`: its `mod child;` // loads the `child.rs` beside it (`impl/platform.rs` loads `impl/child.rs`). @@ -4313,7 +4390,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over .keys() .filter(|k| via != Via::Path && k.as_str() != at && !owns_its_dir(k) && k.rsplit_once('/').is_some_and(|(d, _)| d == module_dir)); for owner in path_loaded { - found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true)).map(|f| (owner.clone(), f, Via::Path))); + found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true, via)).map(|f| (owner.clone(), f, Via::Path))); } } if via == Via::Path || beside_roots(at) { @@ -4519,6 +4596,8 @@ mod tests { assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let one_word = "#[test]\nfn t() {\n let kasusize = 3;\n for k in KEYS {\n assert_eq!(lookup(kasusize), k);\n }\n}\n"; + assert_eq!(census(one_word), [], "a fixed local spelled like a cast of the entry"); let field = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); @@ -6084,6 +6163,8 @@ mod tests { assert_eq!(only("mirror", order), [], "positions of two entries in one list"); let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let raw = "#[test]\nfn t() {\n assert_eq!(at(r#\"B\"#), at(r#\"A\"#) + 1);\n assert_eq!(at(r\"B\"), at(r\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", raw), [], "raw string keys"); let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; @@ -6217,7 +6298,7 @@ mod tests { #[test] fn never_run_follows_the_cfg_around_the_mod_declaration() { let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; - let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false).map(|(p, _)| p); + let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false, Via::Any).map(|(p, _)| p); let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; @@ -6339,10 +6420,25 @@ mod tests { let base = lint_file(path, src, &ctx()); let now = lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); - let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, h)).map(|h| h.line).collect(); + let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.line).collect(); assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); } + #[test] + fn a_test_off_at_the_base_is_matched_in_the_base_source() { + // At the base an inline module gate turned the test off; the change removes that gate and + // gates the parent instead, which also moves the test up a line. + let path = "crates/x/src/child.rs"; + let before = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<&str> = + now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.test.as_str()).collect(); + assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); + } + #[test] fn never_run_follows_a_tests_module_directory_under_src() { let files: HashMap<&str, &str> = @@ -6430,7 +6526,56 @@ mod tests { assert_eq!(hits_in(&below, test, &ctx), [], "the path-loaded file does not load impl/platform/child.rs"); let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; let all: Vec = files.keys().map(|p| (*p).to_owned()).collect(); - assert!(descendants(&seeds, &all, &overrides, &Overrides::new(), &read).contains(&child), "a change to platform.rs reaches child.rs"); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child), + "a change to platform.rs reaches child.rs" + ); + } + + #[test] + fn a_named_route_takes_only_the_gates_of_named_declarations() { + // `parent.rs` is loaded by name on macOS and through `#[path]` on Linux. Only the named route + // loads `parent/child.rs`; the `#[path]` route loads `child.rs` beside `parent.rs`. + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n#[cfg(target_os = \"linux\")]\n#[path = \"parent.rs\"]\nmod p2;\n"), + ("crates/x/src/parent.rs", "mod child;\n"), + ("crates/x/src/parent/child.rs", ""), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + for (child, expected) in [("crates/x/src/parent/child.rs", vec![(2, "never-run")]), ("crates/x/src/child.rs", vec![])] { + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(child, test, &ctx), expected, "{child}"); + } + } + + #[test] + fn a_removed_child_declaration_still_reaches_the_child() { + let work: HashMap<&str, &str> = [ + ( + "crates/x/src/lib.rs", + "#[path = \"impl/platform.rs\"]\nmod platform;\n#[cfg(target_os = \"macos\")]\n#[path = \"impl/child.rs\"]\nmod child;\n", + ), + ("crates/x/src/impl/platform.rs", ""), + ("crates/x/src/impl/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| work.get(p).map(|s| (*s).to_owned()); + let read_base = |p: &str| if p == "crates/x/src/impl/platform.rs" { Some("mod child;\n".to_owned()) } else { read(p) }; + let overrides = path_overrides(work.iter().map(|(p, s)| (*p, *s))); + let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; + let all: Vec = work.keys().map(|p| (*p).to_owned()).collect(); + let child = "crates/x/src/impl/child.rs".to_owned(); + assert!(!descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child)); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &read_base).contains(&child), + "the base `mod child;` that the change removed still leads to child.rs" + ); } #[test] @@ -6594,7 +6739,7 @@ mod tests { let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::>(); assert!( - descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None).contains(&child.to_owned()), + descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None, &|_| None).contains(&child.to_owned()), "the removed route still reaches the shared tests" ); for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { @@ -6602,7 +6747,7 @@ mod tests { assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); assert!(parent_changed, "deletions and shifted lines still change a base route"); - assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), &hit), ran); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), test, test, &hit), ran); assert!( route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), "a base route parent counts even without inherited predicates" @@ -6683,6 +6828,8 @@ mod tests { assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + assert_eq!(cfg_value("target_family=r#\"unix\"#", linux), Some(true)); + assert_eq!(cfg_value("target_family=r#\"\"unix\"\"#", linux), Some(false), "quotes inside a raw string are part of the value"); } #[test] @@ -6705,7 +6852,7 @@ mod tests { let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); let seeds: Vec = got.keys().cloned().collect(); let files = ["crates/x/src/shared.rs".to_owned()]; - assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None), ["crates/x/src/shared.rs"]); + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None, &|_| None), ["crates/x/src/shared.rs"]); } #[test] @@ -6720,7 +6867,7 @@ mod tests { ]; let overrides = path_overrides(sources); let read = |p: &str| sources.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); - let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read, &|_| None); assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); } @@ -6817,6 +6964,8 @@ mod tests { let joined = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); + let nested = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(if root.join(\"config.rs\").exists() { \"a.json\" } else { \"b.json\" })).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", nested), [], "a join inside the outer join's argument"); let extension = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(\"json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", extension), [], "a final extension that is not rs"); let to_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"lib.txt\").with_extension(\"rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; @@ -6856,6 +7005,8 @@ mod tests { fn a_for_binding_shadows_the_outer_one_in_its_body() { let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n"; assert_eq!(only("fixture-only", looped), []); + let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); } From e19e96f810de7342f8c5bd3e6d693a9ee9a83f6e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 17:06:07 -0800 Subject: [PATCH 16/17] xtask: test-lint reads base roots, module scopes and whole literals - Changed mode builds the base's target-root routes from the base tree, so a deleted tests/.rs still counts as loading tests/common/mod.rs. - A base test is matched by its name, its inline modules and its place among same-named tests in them, so removing `mod a` does not let `a::t` hide a newly off `b::t`. - reads-source looks through grouping around the read path and names a file only from a complete literal, a format!/concat! call or Path::new/PathBuf::from; `"data.json".trim_end_matches(".rs")` no longer counts as a .rs file. - mirror keys keep a raw literal whole up to its own delimiter, and a key must be one complete string literal. - for, if let, while let, let and match patterns keep word boundaries (`mut n` binds `n`), and a struct pattern's braces are not taken as the loop or if-let body. - #[path] and cfg_attr path values accept raw string literals. --- xtask/src/test_lint.rs | 320 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 289 insertions(+), 31 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 40ac3b2f25..449885209f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -293,6 +293,12 @@ fn read_small(root: &Path, path: &str) -> Option { (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } +/// The scanned files of the tree at `base`, or `None` when Git cannot list it. +fn base_files(root: &Path, base: &str) -> Option> { + let list = git(root, &["ls-tree", "-r", "-z", "--name-only", base]).ok()?; + Some(list.split('\0').filter(|p| !p.is_empty() && is_scanned(p)).map(str::to_owned).collect()) +} + /// Cache successful and missing reads for one source tree. fn cached_read(read: impl Fn(&str) -> Option) -> impl Fn(&str) -> Option { let cache = RefCell::new(HashMap::>::new()); @@ -324,7 +330,10 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // instead of reading the tree, and the target roots beside a shared `tests//mod.rs`. let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files); let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); - let base_overrides = with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &files); + // The base's target roots come from the base tree: a root the change deleted still loaded the + // shared module beside it. + let base_overrides = + with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &base_files(root, &base).unwrap_or_else(|| files.clone())); // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` // declaration can turn their tests off without a change to them. // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. @@ -373,20 +382,49 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } /// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test -/// of `hit` in `src`. A test is matched by its name and its place among the tests of that name, so -/// lines that moved still match and tests of one name in different inline modules stay apart. +/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place +/// among the tests of that name in those modules, so lines that moved still match and tests of one +/// name in different inline modules stay apart, even when a change removes one of the modules. fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { let place = test_place(src, &hit.test, hit.line); - base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match place { - Some(place) => test_place(base_src, &h.test, h.line) == Some(place), + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match &place { + Some(place) => test_place(base_src, &h.test, h.line).as_ref() == Some(place), None => h.line == hit.line, }) } -/// The index of the test `name` whose `fn` is on `line` among the tests of that name in `src`. -fn test_place(src: &str, name: &str, line: usize) -> Option { +/// The inline modules around the test `name` whose `fn` is on `line` in `src` (outermost first), +/// and its index among the tests of that name in the same modules. +fn test_place(src: &str, name: &str, line: usize) -> Option<(Vec, usize)> { let lines = Lines::new(src); - tests_in(&mask(src)).iter().filter(|t| t.name == name).position(|t| lines.of(t.fn_at) == line) + let m = mask(src); + let named: Vec<(Vec, usize)> = + tests_in(&m).iter().filter(|t| t.name == name).map(|t| (inline_modules(&m, t.fn_at), lines.of(t.fn_at))).collect(); + let (scope, _) = named.iter().find(|(_, l)| *l == line)?; + let index = named.iter().filter(|(s, _)| s == scope).position(|(_, l)| *l == line)?; + Some((scope.clone(), index)) +} + +/// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost +/// first. +fn inline_modules(m: &[u8], at: usize) -> Vec { + let mut open: Vec> = vec![]; + for (i, &c) in m.iter().enumerate().take(at) { + match c { + b'{' => { + let head = m[..i].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + let keyword = name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident); + open.push(keyword.then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned())); + } + b'}' => { + open.pop(); + } + _ => {} + } + } + open.into_iter().flatten().collect() } /// The directory holding the modules that the file `p` declares by name: its own directory for @@ -3175,13 +3213,15 @@ fn reads_source_hits(file: &File) -> Vec { // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on // the outer path count: a `.join` inside another step's argument does not. b"read_to_string" => { + // Grouping around the whole argument hides no step: `(root.join(…))`. + let arg = ungroup(arg.strip_suffix(',').unwrap_or(&arg)); let step = |s: &'static str| { - rfind_outer(&arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + rfind_outer(arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) }; match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { - Some((_, ".with_extension(", ext)) => ext.trim_start_matches('r').trim_matches('#') == "\"rs\"", - Some((_, _, last)) => last_literal(last).is_some_and(|l| l.ends_with(".rs\"")), - None => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + Some((_, ".with_extension(", ext)) => file_literal(ext) == Some("\"rs\""), + Some((_, _, last)) => file_literal(last).is_some_and(|l| l.ends_with(".rs\"")), + None => file_literal(arg).is_some_and(|l| l.ends_with(".rs\"")), } } _ => arg.trim_end_matches('#').ends_with(".rs\""), @@ -3226,6 +3266,81 @@ fn rfind_outer(expr: &str, pat: &str) -> Option { found } +/// The offset of the `)` that closes the `(` at `open` in `expr`, skipping string literals. +fn outer_close(expr: &str, open: usize) -> Option { + let b = expr.as_bytes(); + let (mut depth, mut in_str) = (0usize, false); + let mut i = open; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(i); + } + } + _ => {} + } + } + i += 1; + } + None +} + +/// A whitespace-free expression without the references and parentheses around all of it: +/// `&(root.join("a"))` gives `root.join("a")`. +fn ungroup(mut expr: &str) -> &str { + loop { + let inner = expr.trim_start_matches('&'); + match inner.strip_prefix('(') { + Some(_) if outer_close(inner, 0) == Some(inner.len() - 1) => expr = &inner[1..inner.len() - 1], + _ => return inner, + } + } +} + +/// `s` when it is one complete ordinary string literal (`"a.rs"`, not `"a"+"b"`), or the body of +/// one complete raw string literal in quotes (`r#"a.rs"#` gives `"a.rs"`). +fn whole_literal(s: &str) -> Option<&str> { + if s.starts_with('"') { + return (s.len() > 1 && string_end(s.as_bytes(), 1) == s.len() && s.ends_with('"')).then_some(s); + } + let rest = s.strip_prefix('r')?; + let hashes = rest.len() - rest.trim_start_matches('#').len(); + raw_literal_body(rest).map(|_| &rest[hashes..rest.len() - hashes]) +} + +/// The literal that names the file of a whitespace-free path expression, quotes included: one +/// complete string literal, the file literal of a `format!`-family or `concat!` call +/// ([`last_literal`]), or the same inside `Path::new(…)` or `PathBuf::from(…)`. `None` for any +/// other expression: `"data.json".trim_end_matches(".rs")` names `data.json`, not its last literal. +fn file_literal(expr: &str) -> Option<&str> { + let e = ungroup(expr.strip_suffix(',').unwrap_or(expr)); + if let Some(l) = whole_literal(e) { + return Some(l); + } + let open = e.find('(')?; + if outer_close(e, open) != Some(e.len() - 1) { + return None; + } + let head = e[..open].trim_start_matches("std::").trim_start_matches("path::"); + match head { + "format!" | "format_args!" | "concat!" => last_literal(e), + "Path::new" | "PathBuf::from" => file_literal(&e[open + 1..e.len() - 1]), + _ => None, + } +} + /// The last string literal in a (whitespace-free) expression, quotes included. Inside a /// `format!`-family call, an argument is not the file name, so the format string is returned /// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. @@ -3341,6 +3456,13 @@ fn norm_outside_literals(b: &[u8]) -> String { } else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) { in_str = true; out.push(c); + } else if c == b'r' && !(i > 0 && is_ident(b[i - 1])) && matches!(b[i + 1..].iter().find(|&&h| h != b'#'), Some(b'"')) { + // A raw literal runs to its own closing delimiter: the `"` in `r#"A" B"#` does not end it. + let mut sink = vec![]; + let end = after_ident(b, &mut sink, i, false); + out.extend_from_slice(&b[i..end]); + i = end; + continue; } else if !c.is_ascii_whitespace() { out.push(c); } @@ -3363,7 +3485,7 @@ fn raw_literal_body(s: &str) -> Option<&str> { fn key_like(arg: &str) -> bool { let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); match arg.as_bytes().first() { - Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(b'"') => whole_literal(arg).is_some(), Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), @@ -3480,10 +3602,12 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option { } // A guard (`Some(x) if x == n`) reads names; it does not bind them. let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); - let pattern = norm(&body[start..guard]); + let pattern = norm_words(&body[start..guard]); if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { continue; } @@ -3609,9 +3733,8 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u [&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); if keyword.is_some() { // `if let` and `while let` bind the pattern's names inside their body only. - if let Some((open, close)) = let_body(body, n0) { - let pattern = norm(&body[n0..open]); - let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); + if let Some((eq, open, close)) = let_body(body, n0) { + let pattern = norm_words(&body[n0..eq]); if open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { found = Some((None, at)); } @@ -3629,7 +3752,7 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u found = Some((if is_mut { None } else { init }, at)); } else if !plain { // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). - let pattern = norm(&body[n0..stop]); + let pattern = norm_words(&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, at)); @@ -3639,9 +3762,44 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u found } -/// The braces of the body of an `if let` or `while let` whose pattern starts at `from`: the first -/// `{` outside parentheses and brackets, and its match. -fn let_body(body: &[u8], from: usize) -> Option<(usize, usize)> { +/// The `=` that ends the pattern of an `if let` or `while let` starting at `from`, and the braces of +/// its body after the scrutinee ([`block_after`]). The `=` sits outside every bracket, so the braces +/// of a struct pattern (`if let Row { n } = …`) are part of the pattern, and it is not part of `==`, +/// `=>`, `..=`, `<=`, `>=` or `!=`. +fn let_body(body: &[u8], from: usize) -> Option<(usize, usize, usize)> { + let mut depth = 0usize; + for (i, &c) in body.iter().enumerate().skip(from) { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' if depth == 0 => return None, + b')' | b']' | b'}' => depth -= 1, + b';' if depth == 0 => return None, + b'=' if depth == 0 + && !matches!(body.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| body[j]), Some(b'=' | b'.' | b'<' | b'>' | b'!')) => + { + return block_after(body, i + 1).map(|(open, close)| (i, open, close)); + } + _ => {} + } + } + None +} + +/// The depth of the brackets left open at the end of `b`. +fn bracket_depth(b: &[u8]) -> isize { + b.iter() + .map(|&c| match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }) + .sum() +} + +/// The braces of the block that follows an expression starting at `from`: the first `{` outside +/// parentheses and brackets, and its match. +fn block_after(body: &[u8], from: usize) -> Option<(usize, usize)> { let mut depth = 0usize; for (i, &c) in body.iter().enumerate().skip(from) { match c { @@ -4202,20 +4360,37 @@ fn path_overrides<'a>(sources: impl IntoIterator) -> out } -/// The string value of a `#[path = "…"]` attribute in `m[from..to]`. +/// The string value of a `#[path = "…"]` attribute in `m[from..to]`, written as an ordinary or a +/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { words(m, b"path", from, to).into_iter().find_map(|at| { let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); let eq = skip_ws(m, at + 4); - let q = skip_ws(m, eq + 1); - if !attr || m.get(eq) != Some(&b'=') || m.get(q) != Some(&b'"') { + let mut q = skip_ws(m, eq + 1); + if !attr || m.get(eq) != Some(&b'=') { return None; } - let close = find(m, b"\"", q + 1)?; - Some(String::from_utf8_lossy(&src[q + 1..close]).into_owned()) + let hashes = if m.get(q) == Some(&b'r') { + let h = m[q + 1..].iter().take_while(|&&c| c == b'#').count(); + q += 1 + h; + h + } else { + 0 + }; + if m.get(q) != Some(&b'"') { + return None; + } + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(m, &close, q + 1)?; + Some(String::from_utf8_lossy(&src[q + 1..end]).into_owned()) }) } +/// The value of a whitespace-free `path=` argument, for an ordinary or a raw string literal. +fn path_arg(arg: &str) -> Option<&str> { + whole_literal(arg.strip_prefix("path=")?).map(|l| &l[1..l.len() - 1]) +} + /// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and /// path. fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { @@ -4232,7 +4407,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, let mut start = first + 1; for cut in cuts[1..].iter().copied().chain([text.len()]) { let arg = text.get(start..cut).unwrap_or(""); - if let Some(rel) = arg.strip_prefix("path=\"").and_then(|r| r.strip_suffix('"')) { + if let Some(rel) = path_arg(arg) { out.push((text[..first].to_owned(), rel.to_owned())); } start = cut + 1; @@ -6167,6 +6342,10 @@ mod tests { assert_eq!(only("mirror", raw), [], "raw string keys"); let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); + let raw_quote = "#[test]\nfn t() {\n assert_eq!(at(r#\"A\" B\"#), at(r#\"A\"B\"#) + 1);\n}\n"; + assert_eq!(only("mirror", raw_quote), [], "a quote inside a raw key does not end it"); + let computed = "#[test]\nfn t() {\n assert_eq!(label(\"A\".to_owned() + \"B\"), label(\"C\") + 1);\n}\n"; + assert_eq!(only("mirror", computed), [(3, "mirror")], "a computed string is not an entry key"); let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not"); let offset = @@ -6211,6 +6390,13 @@ mod tests { assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one"); let if_let = "#[test]\nfn t() {\n let x = 0;\n if let Some(x) = compute() {\n assert_eq!(x, 2);\n }\n}\n"; assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); + let struct_pattern = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", struct_pattern), [], "the braces of a struct pattern are not the body"); + let else_branch = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n consume(n);\n } else {\n assert_eq!(n, 0);\n }\n}\n"; + assert_eq!(only("fixture-only", else_branch), [(2, "fixture-only")], "the `else` branch sees the outer binding"); + let mut_pattern = + "#[test]\nfn t() {\n let n = 0;\n if let Some(mut n) = compute() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mut_pattern), [], "`mut n` in an `if let` binds `n`"); } #[test] @@ -6439,6 +6625,20 @@ mod tests { assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); } + #[test] + fn a_removed_namesake_module_does_not_hide_a_newly_off_test() { + // `a::t` was off at the base and `b::t` ran; the change deletes `mod a` and gates the parent, + // so `b::t` is now the only `t` in the file. + let path = "crates/x/src/child.rs"; + let before = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.line).collect(); + assert_eq!(off, [3], "`b::t` is newly off"); + } + #[test] fn never_run_follows_a_tests_module_directory_under_src() { let files: HashMap<&str, &str> = @@ -6610,6 +6810,27 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn base_root_routes_come_from_the_base_tree() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-roots-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/tests/common")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + std::fs::write(root.join("crates/x/tests/smoke.rs"), "mod common;\n").unwrap(); + std::fs::write(root.join("crates/x/tests/common/mod.rs"), "").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::remove_file(root.join("crates/x/tests/smoke.rs")).unwrap(); + let shared = "crates/x/tests/common/mod.rs"; + let now = vec![shared.to_owned()]; + assert!(with_root_routes(Overrides::new(), &now).get(shared).is_none_or(|r| r.is_empty()), "no root loads it now"); + let then = base_files(&root, &base).unwrap(); + let routes = with_root_routes(Overrides::new(), &then); + let parents: Vec<&str> = routes.get(shared).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, ["crates/x/tests/smoke.rs"], "the deleted root loaded it at the base"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn never_run_follows_a_path_selected_by_cfg_attr() { let files: HashMap<&str, &str> = [ @@ -6977,6 +7198,15 @@ mod tests { let format_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", format_rs), [(3, "reads-source")], "a format string that names a .rs file"); + let grouped_ext = "#[test]\nfn t() {\n let s = fs::read_to_string((root.join(\"sample.rs\").with_extension(ext))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", grouped_ext), [], "grouping around the argument hides no step"); + let grouped_rs = + "#[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", grouped_rs), [(3, "reads-source")], "a grouped join that names a .rs file"); + let computed = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\".trim_end_matches(\".rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", computed), [], "a computed file name is not its last literal"); + let wrapped = "#[test]\nfn t() {\n let s = fs::read_to_string(Path::new(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", wrapped), [(3, "reads-source")], "a literal inside Path::new"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); @@ -7009,6 +7239,12 @@ mod tests { assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); + let mutable = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mutable), [], "`mut n` binds `n`"); + let destructured = "#[test]\nfn t() {\n let n = 0;\n for Row { n } in rows() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", destructured), [], "the braces of a struct pattern are not the loop body"); + let mut_after = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", mut_after), [(2, "fixture-only")], "the outer binding after a `mut` loop"); } #[test] @@ -7033,6 +7269,28 @@ mod tests { assert_eq!(only("never-run", comma), [], "a comma inside the condition's value"); let src = "#[cfg_attr(unix, path = \"a,b.rs\")]\nmod x;\n"; assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "a,b.rs".to_owned())]); + let raw = "#[cfg_attr(unix, path = r#\"a.rs\"#)]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "a.rs".to_owned())]); + } + + #[test] + fn path_attributes_accept_raw_strings() { + for src in ["#[path = r\"shared.rs\"]\nmod s;\n", "#[path = r#\"shared.rs\"#]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n"] { + assert_eq!(path_attr(&mask(src), src.as_bytes(), 0, src.len()).as_deref(), Some("shared.rs"), "{src}"); + } + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod a;\nmod b;\n"), + ("crates/x/src/a.rs", "#[path = r\"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/src/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux"); } #[test] From 450a821ae4dfc2bc75123ec6bef7ccf0ec8f96bf Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 2 Dec 2026 07:35:21 +0530 Subject: [PATCH 17/17] .ai import: say where unchecked page type over hidden type goes --- crates/eps/src/import/native/plan.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index a15c272222..f2dfba3377 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -556,7 +556,9 @@ pub(super) fn plan( let mut spare: Vec>> = vec![]; // The word searches below are held to their own budget: past it, type where made type that shows // draws is taken to be that type (made type is there either way), and type where only made type - // that doesn't show lies stays on the page (it would not show otherwise). + // that doesn't show lies is spare type, as any type no text object takes: it goes into a slot + // or with another text object's type, else it is left out with a note (taken as the hidden + // type, it would be dropped unnoted). let (mut checks, mut unchecked) = (WordChecks::new(), false); for (j, object) in shown.iter().enumerate() { match owner.get(j).copied().flatten() {