repo
string
pull_number
int64
instance_id
string
issue_numbers
list
base_commit
string
patch
string
test_patch
string
problem_statement
string
hints_text
string
created_at
string
version
string
updated_at
string
environment_setup_commit
string
FAIL_TO_PASS
list
PASS_TO_PASS
list
FAIL_TO_FAIL
list
PASS_TO_FAIL
list
source_dir
string
imsnif/bandwhich
23
imsnif__bandwhich-23
[ "16" ]
408ec397c81bb99d6727f01d5dc058e814012714
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Windows is not supported at the moment - if you'd like to contribute a windows p ### Usage ``` USAGE: - what [FLAGS] --interface <interface> + what [FLAGS] [OPTIONS] FLAGS: -h, --help Prints help information diff --git a/src/display/components/table.rs b/src/display/components/table.rs --- a/src/display/components/table.rs +++ b/src/display/components/table.rs @@ -64,7 +64,11 @@ impl<'a> Table<'a> { .iter() .map(|(connection, connection_data)| { vec![ - display_connection_string(&connection, &ip_to_host), + display_connection_string( + &connection, + &ip_to_host, + &connection_data.interface_name, + ), connection_data.process_name.to_string(), display_upload_and_download(*connection_data), ] diff --git a/src/display/ui.rs b/src/display/ui.rs --- a/src/display/ui.rs +++ b/src/display/ui.rs @@ -53,7 +53,11 @@ where write_to_stdout(format!( "connection: <{}> {} up/down Bps: {}/{} process: \"{}\"", timestamp, - display_connection_string(connection, ip_to_host), + display_connection_string( + connection, + ip_to_host, + &connection_network_data.interface_name + ), connection_network_data.total_bytes_uploaded, connection_network_data.total_bytes_downloaded, connection_network_data.process_name diff --git a/src/display/ui_state.rs b/src/display/ui_state.rs --- a/src/display/ui_state.rs +++ b/src/display/ui_state.rs @@ -20,6 +20,7 @@ pub struct ConnectionData { pub total_bytes_downloaded: u128, pub total_bytes_uploaded: u128, pub process_name: String, + pub interface_name: String, } impl Bandwidth for ConnectionData { diff --git a/src/display/ui_state.rs b/src/display/ui_state.rs --- a/src/display/ui_state.rs +++ b/src/display/ui_state.rs @@ -52,7 +53,7 @@ pub struct UIState { impl UIState { pub fn new( connections_to_procs: HashMap<Connection, String>, - network_utilization: Utilization, + mut network_utilization: Utilization, ) -> Self { let mut processes: BTreeMap<String, NetworkData> = BTreeMap::new(); let mut remote_addresses: BTreeMap<Ipv4Addr, NetworkData> = BTreeMap::new(); diff --git a/src/display/ui_state.rs b/src/display/ui_state.rs --- a/src/display/ui_state.rs +++ b/src/display/ui_state.rs @@ -60,32 +61,27 @@ impl UIState { let mut total_bytes_downloaded: u128 = 0; let mut total_bytes_uploaded: u128 = 0; for (connection, process_name) in connections_to_procs { - if let Some(connection_bandwidth_utilization) = - network_utilization.connections.get(&connection) - { + if let Some(connection_info) = network_utilization.connections.remove(&connection) { let data_for_remote_address = remote_addresses .entry(connection.remote_socket.ip) .or_default(); let connection_data = connections.entry(connection).or_default(); let data_for_process = processes.entry(process_name.clone()).or_default(); - data_for_process.total_bytes_downloaded += - &connection_bandwidth_utilization.total_bytes_downloaded; - data_for_process.total_bytes_uploaded += - &connection_bandwidth_utilization.total_bytes_uploaded; + data_for_process.total_bytes_downloaded += connection_info.total_bytes_downloaded; + data_for_process.total_bytes_uploaded += connection_info.total_bytes_uploaded; data_for_process.connection_count += 1; - connection_data.total_bytes_downloaded += - &connection_bandwidth_utilization.total_bytes_downloaded; - connection_data.total_bytes_uploaded += - &connection_bandwidth_utilization.total_bytes_uploaded; + connection_data.total_bytes_downloaded += connection_info.total_bytes_downloaded; + connection_data.total_bytes_uploaded += connection_info.total_bytes_uploaded; connection_data.process_name = process_name; + connection_data.interface_name = connection_info.interface_name; data_for_remote_address.total_bytes_downloaded += - connection_bandwidth_utilization.total_bytes_downloaded; + connection_info.total_bytes_downloaded; data_for_remote_address.total_bytes_uploaded += - connection_bandwidth_utilization.total_bytes_uploaded; + connection_info.total_bytes_uploaded; data_for_remote_address.connection_count += 1; - total_bytes_downloaded += connection_bandwidth_utilization.total_bytes_downloaded; - total_bytes_uploaded += connection_bandwidth_utilization.total_bytes_uploaded; + total_bytes_downloaded += connection_info.total_bytes_downloaded; + total_bytes_uploaded += connection_info.total_bytes_uploaded; } } UIState { diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -36,7 +36,7 @@ use structopt::StructOpt; pub struct Opt { #[structopt(short, long)] /// The network interface to listen on, eg. eth0 - interface: String, + interface: Option<String>, #[structopt(short, long)] /// Machine friendlier output raw: bool, diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -78,8 +78,8 @@ fn try_main() -> Result<(), failure::Error> { } pub struct OsInputOutput { - pub network_interface: NetworkInterface, - pub network_frames: Box<dyn DataLinkReceiver>, + pub network_interfaces: Vec<NetworkInterface>, + pub network_frames: Vec<Box<dyn DataLinkReceiver>>, pub get_open_sockets: fn() -> HashMap<Connection, String>, pub keyboard_events: Box<dyn Iterator<Item = Event> + Send>, pub dns_client: Option<dns::Client>, diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -105,7 +105,13 @@ where let raw_mode = opts.raw; - let mut sniffer = Sniffer::new(os_input.network_interface, os_input.network_frames); + let mut sniffers = os_input + .network_interfaces + .into_iter() + .zip(os_input.network_frames.into_iter()) + .map(|(iface, frames)| Sniffer::new(iface, frames)) + .collect::<Vec<Sniffer>>(); + let network_utilization = Arc::new(Mutex::new(Utilization::new())); let ui = Arc::new(Mutex::new(Ui::new(terminal_backend))); diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -196,10 +202,14 @@ where active_threads.push( thread::Builder::new() .name("sniffing_handler".to_string()) - .spawn(move || { - while running.load(Ordering::Acquire) { + .spawn(move || 'sniffing: loop { + for sniffer in sniffers.iter_mut() { if let Some(segment) = sniffer.next() { - network_utilization.lock().unwrap().update(&segment) + network_utilization.lock().unwrap().update(segment); + } + if !running.load(Ordering::Acquire) { + // Break from the outer loop and finish the thread + break 'sniffing; } } }) diff --git a/src/network/connection.rs b/src/network/connection.rs --- a/src/network/connection.rs +++ b/src/network/connection.rs @@ -52,9 +52,11 @@ pub fn display_ip_or_host(ip: Ipv4Addr, ip_to_host: &HashMap<Ipv4Addr, String>) pub fn display_connection_string( connection: &Connection, ip_to_host: &HashMap<Ipv4Addr, String>, + interface_name: &str, ) -> String { format!( - ":{} => {}:{} ({})", + "<{}>:{} => {}:{} ({})", + interface_name, connection.local_port, display_ip_or_host(connection.remote_socket.ip, ip_to_host), connection.remote_socket.port, diff --git a/src/network/sniffer.rs b/src/network/sniffer.rs --- a/src/network/sniffer.rs +++ b/src/network/sniffer.rs @@ -14,6 +14,7 @@ use ::std::net::{IpAddr, SocketAddr}; use crate::network::{Connection, Protocol}; pub struct Segment { + pub interface_name: String, pub connection: Connection, pub direction: Direction, pub data_length: u128, diff --git a/src/network/sniffer.rs b/src/network/sniffer.rs --- a/src/network/sniffer.rs +++ b/src/network/sniffer.rs @@ -81,6 +82,7 @@ impl Sniffer { } _ => return None, }; + let interface_name = self.network_interface.name.clone(); let direction = Direction::new(&self.network_interface.ips, &ip_packet); let from = SocketAddr::new(IpAddr::V4(ip_packet.get_source()), source_port); let to = SocketAddr::new(IpAddr::V4(ip_packet.get_destination()), destination_port); diff --git a/src/network/sniffer.rs b/src/network/sniffer.rs --- a/src/network/sniffer.rs +++ b/src/network/sniffer.rs @@ -90,6 +92,7 @@ impl Sniffer { Direction::Upload => Connection::new(to, source_port, protocol)?, }; Some(Segment { + interface_name, connection, data_length, direction, diff --git a/src/network/utilization.rs b/src/network/utilization.rs --- a/src/network/utilization.rs +++ b/src/network/utilization.rs @@ -3,14 +3,15 @@ use crate::network::{Connection, Direction, Segment}; use ::std::collections::HashMap; #[derive(Clone)] -pub struct TotalBandwidth { +pub struct ConnectionInfo { + pub interface_name: String, pub total_bytes_downloaded: u128, pub total_bytes_uploaded: u128, } #[derive(Clone)] pub struct Utilization { - pub connections: HashMap<Connection, TotalBandwidth>, + pub connections: HashMap<Connection, ConnectionInfo>, } impl Utilization { diff --git a/src/network/utilization.rs b/src/network/utilization.rs --- a/src/network/utilization.rs +++ b/src/network/utilization.rs @@ -23,14 +24,15 @@ impl Utilization { self.connections.clear(); clone } - pub fn update(&mut self, seg: &Segment) { - let total_bandwidth = - self.connections - .entry(seg.connection.clone()) - .or_insert(TotalBandwidth { - total_bytes_downloaded: 0, - total_bytes_uploaded: 0, - }); + pub fn update(&mut self, seg: Segment) { + let total_bandwidth = self + .connections + .entry(seg.connection) + .or_insert(ConnectionInfo { + interface_name: seg.interface_name, + total_bytes_downloaded: 0, + total_bytes_uploaded: 0, + }); match seg.direction { Direction::Download => { total_bandwidth.total_bytes_downloaded += seg.data_length; diff --git a/src/os/shared.rs b/src/os/shared.rs --- a/src/os/shared.rs +++ b/src/os/shared.rs @@ -34,11 +34,11 @@ fn get_datalink_channel( interface: &NetworkInterface, ) -> Result<Box<dyn DataLinkReceiver>, failure::Error> { let mut config = Config::default(); - config.read_timeout = Some(time::Duration::new(0, 1)); + config.read_timeout = Some(time::Duration::new(0, 2_000_000)); match datalink::channel(interface, config) { Ok(Ethernet(_tx, rx)) => Ok(rx), Ok(_) => failure::bail!("Unknown interface type"), - Err(e) => failure::bail!("Failed to listen to network interface: {}", e), + Err(e) => failure::bail!("Failed to listen on network interface: {}", e), } } diff --git a/src/os/shared.rs b/src/os/shared.rs --- a/src/os/shared.rs +++ b/src/os/shared.rs @@ -76,15 +76,27 @@ fn create_write_to_stdout() -> Box<dyn FnMut(String) + Send> { }) } -pub fn get_input(interface_name: &str, resolve: bool) -> Result<OsInputOutput, failure::Error> { - let keyboard_events = Box::new(KeyboardEvents); - let network_interface = match get_interface(interface_name) { - Some(interface) => interface, - None => { - failure::bail!("Cannot find interface {}", interface_name); +pub fn get_input( + interface_name: &Option<String>, + resolve: bool, +) -> Result<OsInputOutput, failure::Error> { + let network_interfaces = if let Some(name) = interface_name { + match get_interface(&name) { + Some(interface) => vec![interface], + None => { + failure::bail!("Cannot find interface {}", name); + } } + } else { + datalink::interfaces() }; - let network_frames = get_datalink_channel(&network_interface)?; + + let network_frames = network_interfaces + .iter() + .map(|iface| get_datalink_channel(iface)) + .collect::<Result<Vec<_>, _>>()?; + + let keyboard_events = Box::new(KeyboardEvents); let write_to_stdout = create_write_to_stdout(); let (on_winch, cleanup) = sigwinch(); let dns_client = if resolve { diff --git a/src/os/shared.rs b/src/os/shared.rs --- a/src/os/shared.rs +++ b/src/os/shared.rs @@ -96,7 +108,7 @@ pub fn get_input(interface_name: &str, resolve: bool) -> Result<OsInputOutput, f }; Ok(OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events,
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -46,14 +46,14 @@ Note that since `what` sniffs network packets, it requires root privileges - so ### raw_mode `what` also supports an easier-to-parse mode that can be piped or redirected to a file. For example, try: ``` -what -i eth0 --raw | grep firefox +what --raw | grep firefox ``` ### Contributing Contributions of any kind are very welcome. If you'd like a new feature (or found a bug), please open an issue or a PR. To set up your development environment: 1. Clone the project -2. `cargo run -- -i <network interface name>` (you can often find out the name with `ifconfig` or `iwconfig`). You might need root privileges to run this application, so be sure to use (for example) sudo. +2. `cargo run`, or if you prefer `cargo run -- -i <network interface name>` (you can often find out the name with `ifconfig` or `iwconfig`). You might need root privileges to run this application, so be sure to use (for example) sudo. To run tests: `cargo test` diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -1,5 +1,5 @@ use crate::tests::fakes::{ - create_fake_dns_client, create_fake_on_winch, get_interface, get_open_sockets, KeyboardEvents, + create_fake_dns_client, create_fake_on_winch, get_interfaces, get_open_sockets, KeyboardEvents, NetworkFrames, TestBackend, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -12,6 +12,7 @@ use ::std::net::IpAddr; use packet_builder::payload::PayloadData; use packet_builder::*; +use pnet::datalink::DataLinkReceiver; use pnet::packet::Packet; use pnet_base::MacAddr; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -65,13 +66,13 @@ fn one_packet_of_traffic() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![Some(build_tcp_packet( + let network_frames = vec![NetworkFrames::new(vec![Some(build_tcp_packet( "10.0.0.2", "1.1.1.1", 443, 12345, b"I am a fake tcp packet", - ))]); + ))]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -84,7 +85,7 @@ fn one_packet_of_traffic() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -98,7 +99,7 @@ fn one_packet_of_traffic() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -108,7 +109,7 @@ fn one_packet_of_traffic() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -125,7 +126,7 @@ fn bi_directional_traffic() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "1.1.1.1", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -140,7 +141,7 @@ fn bi_directional_traffic() { 443, b"I am a fake tcp download packet", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -153,7 +154,7 @@ fn bi_directional_traffic() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -167,7 +168,7 @@ fn bi_directional_traffic() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -177,7 +178,7 @@ fn bi_directional_traffic() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -194,7 +195,7 @@ fn multiple_packets_of_traffic_from_different_connections() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -209,7 +210,7 @@ fn multiple_packets_of_traffic_from_different_connections() { 443, b"I come from 2.2.2.2", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -224,7 +225,7 @@ fn multiple_packets_of_traffic_from_different_connections() { ); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let stdout = Arc::new(Mutex::new(Vec::new())); let write_to_stdout = Box::new({ diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -236,7 +237,7 @@ fn multiple_packets_of_traffic_from_different_connections() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, on_winch, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -246,7 +247,7 @@ fn multiple_packets_of_traffic_from_different_connections() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -263,7 +264,7 @@ fn multiple_packets_of_traffic_from_single_connection() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -278,7 +279,7 @@ fn multiple_packets_of_traffic_from_single_connection() { 443, b"I've come from 1.1.1.1 too!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -291,7 +292,7 @@ fn multiple_packets_of_traffic_from_single_connection() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -305,7 +306,7 @@ fn multiple_packets_of_traffic_from_single_connection() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -315,7 +316,7 @@ fn multiple_packets_of_traffic_from_single_connection() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -332,7 +333,7 @@ fn one_process_with_multiple_connections() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -347,7 +348,7 @@ fn one_process_with_multiple_connections() { 443, b"Funny that, I'm from 3.3.3.3", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -360,7 +361,7 @@ fn one_process_with_multiple_connections() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -374,7 +375,7 @@ fn one_process_with_multiple_connections() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -384,7 +385,7 @@ fn one_process_with_multiple_connections() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -401,7 +402,7 @@ fn multiple_processes_with_multiple_connections() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -430,7 +431,7 @@ fn multiple_processes_with_multiple_connections() { 443, b"I'm partial to 4.4.4.4", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -443,7 +444,7 @@ fn multiple_processes_with_multiple_connections() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -457,7 +458,7 @@ fn multiple_processes_with_multiple_connections() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -467,7 +468,7 @@ fn multiple_processes_with_multiple_connections() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -484,7 +485,7 @@ fn multiple_connections_from_remote_address() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -499,7 +500,7 @@ fn multiple_connections_from_remote_address() { 443, b"Me too, but on a different port", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -512,7 +513,7 @@ fn multiple_connections_from_remote_address() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -526,7 +527,7 @@ fn multiple_connections_from_remote_address() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -536,7 +537,7 @@ fn multiple_connections_from_remote_address() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -554,7 +555,7 @@ fn sustained_traffic_from_one_process() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -570,7 +571,7 @@ fn sustained_traffic_from_one_process() { 443, b"Same here, but one second later", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -583,7 +584,7 @@ fn sustained_traffic_from_one_process() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -597,7 +598,7 @@ fn sustained_traffic_from_one_process() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -607,7 +608,7 @@ fn sustained_traffic_from_one_process() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -625,7 +626,7 @@ fn sustained_traffic_from_multiple_processes() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -655,7 +656,7 @@ fn sustained_traffic_from_multiple_processes() { 443, b"I come 3.3.3.3 one second later", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -668,7 +669,7 @@ fn sustained_traffic_from_multiple_processes() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -682,7 +683,7 @@ fn sustained_traffic_from_multiple_processes() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -692,7 +693,7 @@ fn sustained_traffic_from_multiple_processes() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -710,7 +711,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "3.3.3.3", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -768,7 +769,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { 12345, b"10.0.0.2 forever!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -781,7 +782,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -795,7 +796,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -805,7 +806,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -823,7 +824,7 @@ fn traffic_with_host_names() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "3.3.3.3", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -881,7 +882,7 @@ fn traffic_with_host_names() { 12345, b"10.0.0.2 forever!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -894,7 +895,7 @@ fn traffic_with_host_names() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let mut ips_to_hostnames = HashMap::new(); ips_to_hostnames.insert( IpAddr::V4("1.1.1.1".parse().unwrap()), diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -921,7 +922,7 @@ fn traffic_with_host_names() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -931,7 +932,7 @@ fn traffic_with_host_names() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: false, }; diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -949,7 +950,7 @@ fn no_resolve_mode() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "3.3.3.3", diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -1007,7 +1008,7 @@ fn no_resolve_mode() { 12345, b"10.0.0.2 forever!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -1020,7 +1021,7 @@ fn no_resolve_mode() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let mut ips_to_hostnames = HashMap::new(); ips_to_hostnames.insert( IpAddr::V4("1.1.1.1".parse().unwrap()), diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -1047,7 +1048,7 @@ fn no_resolve_mode() { }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/raw_mode.rs b/src/tests/cases/raw_mode.rs --- a/src/tests/cases/raw_mode.rs +++ b/src/tests/cases/raw_mode.rs @@ -1057,7 +1058,7 @@ fn no_resolve_mode() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: true, no_resolve: true, }; diff --git a/src/tests/cases/snapshots/raw_mode__bi_directional_traffic.snap b/src/tests/cases/snapshots/raw_mode__bi_directional_traffic.snap --- a/src/tests/cases/snapshots/raw_mode__bi_directional_traffic.snap +++ b/src/tests/cases/snapshots/raw_mode__bi_directional_traffic.snap @@ -3,6 +3,6 @@ source: src/tests/cases/raw_mode.rs expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 49/51 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 49/51 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 49/51 process: "1" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 49/51 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__multiple_connections_from_remote_address.snap b/src/tests/cases/snapshots/raw_mode__multiple_connections_from_remote_address.snap --- a/src/tests/cases/snapshots/raw_mode__multiple_connections_from_remote_address.snap +++ b/src/tests/cases/snapshots/raw_mode__multiple_connections_from_remote_address.snap @@ -4,7 +4,7 @@ expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/44 connections: 1 process: <TIMESTAMP_REMOVED> "3" up/down Bps: 0/51 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12346 (tcp) up/down Bps: 0/51 process: "3" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12346 (tcp) up/down Bps: 0/51 process: "3" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/95 connections: 2 diff --git a/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_different_connections.snap b/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_different_connections.snap --- a/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_different_connections.snap +++ b/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_different_connections.snap @@ -4,8 +4,8 @@ expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/44 connections: 1 process: <TIMESTAMP_REMOVED> "4" up/down Bps: 0/39 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 2.2.2.2:54321 (tcp) up/down Bps: 0/39 process: "4" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 2.2.2.2:54321 (tcp) up/down Bps: 0/39 process: "4" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/44 connections: 1 remote_address: <TIMESTAMP_REMOVED> 2.2.2.2 up/down Bps: 0/39 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_single_connection.snap b/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_single_connection.snap --- a/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_single_connection.snap +++ b/src/tests/cases/snapshots/raw_mode__multiple_packets_of_traffic_from_single_connection.snap @@ -3,6 +3,6 @@ source: src/tests/cases/raw_mode.rs expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/91 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/91 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/91 process: "1" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/91 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__multiple_processes_with_multiple_connections.snap b/src/tests/cases/snapshots/raw_mode__multiple_processes_with_multiple_connections.snap --- a/src/tests/cases/snapshots/raw_mode__multiple_processes_with_multiple_connections.snap +++ b/src/tests/cases/snapshots/raw_mode__multiple_processes_with_multiple_connections.snap @@ -6,10 +6,10 @@ process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/44 connections: 1 process: <TIMESTAMP_REMOVED> "2" up/down Bps: 0/42 connections: 1 process: <TIMESTAMP_REMOVED> "4" up/down Bps: 0/53 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 0/45 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 2.2.2.2:54321 (tcp) up/down Bps: 0/53 process: "4" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/45 process: "5" -connection: <TIMESTAMP_REMOVED> :443 => 4.4.4.4:1337 (tcp) up/down Bps: 0/42 process: "2" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 2.2.2.2:54321 (tcp) up/down Bps: 0/53 process: "4" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/45 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 4.4.4.4:1337 (tcp) up/down Bps: 0/42 process: "2" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/44 connections: 1 remote_address: <TIMESTAMP_REMOVED> 2.2.2.2 up/down Bps: 0/53 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 0/45 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__no_resolve_mode.snap b/src/tests/cases/snapshots/raw_mode__no_resolve_mode.snap --- a/src/tests/cases/snapshots/raw_mode__no_resolve_mode.snap +++ b/src/tests/cases/snapshots/raw_mode__no_resolve_mode.snap @@ -4,14 +4,14 @@ expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 57/61 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 34/37 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 57/61 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 34/37 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 57/61 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 34/37 process: "5" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 57/61 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 34/37 connections: 1 process: <TIMESTAMP_REMOVED> "1" up/down Bps: 37/36 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 32/46 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 37/36 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 32/46 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 37/36 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 32/46 process: "5" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 37/36 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 32/46 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__one_packet_of_traffic.snap b/src/tests/cases/snapshots/raw_mode__one_packet_of_traffic.snap --- a/src/tests/cases/snapshots/raw_mode__one_packet_of_traffic.snap +++ b/src/tests/cases/snapshots/raw_mode__one_packet_of_traffic.snap @@ -3,6 +3,6 @@ source: src/tests/cases/raw_mode.rs expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 42/0 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 42/0 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 42/0 process: "1" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 42/0 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__one_process_with_multiple_connections.snap b/src/tests/cases/snapshots/raw_mode__one_process_with_multiple_connections.snap --- a/src/tests/cases/snapshots/raw_mode__one_process_with_multiple_connections.snap +++ b/src/tests/cases/snapshots/raw_mode__one_process_with_multiple_connections.snap @@ -4,8 +4,8 @@ expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/44 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 0/48 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/48 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/48 process: "5" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/44 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 0/48 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes.snap b/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes.snap --- a/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes.snap +++ b/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes.snap @@ -4,14 +4,14 @@ expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/44 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 0/39 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/39 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/39 process: "5" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/44 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 0/39 connections: 1 process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/61 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 0/51 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/61 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/51 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/61 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 0/51 process: "5" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/61 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 0/51 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes_bi_directional.snap b/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes_bi_directional.snap --- a/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes_bi_directional.snap +++ b/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_multiple_processes_bi_directional.snap @@ -4,14 +4,14 @@ expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 57/61 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 34/37 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 57/61 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 34/37 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 57/61 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 34/37 process: "5" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 57/61 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 34/37 connections: 1 process: <TIMESTAMP_REMOVED> "1" up/down Bps: 37/36 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 32/46 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 37/36 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => 3.3.3.3:1337 (tcp) up/down Bps: 32/46 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 37/36 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 3.3.3.3:1337 (tcp) up/down Bps: 32/46 process: "5" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 37/36 connections: 1 remote_address: <TIMESTAMP_REMOVED> 3.3.3.3 up/down Bps: 32/46 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_one_process.snap b/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_one_process.snap --- a/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_one_process.snap +++ b/src/tests/cases/snapshots/raw_mode__sustained_traffic_from_one_process.snap @@ -3,9 +3,9 @@ source: src/tests/cases/raw_mode.rs expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/44 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/44 process: "1" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/44 connections: 1 process: <TIMESTAMP_REMOVED> "1" up/down Bps: 0/51 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/51 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => 1.1.1.1:12345 (tcp) up/down Bps: 0/51 process: "1" remote_address: <TIMESTAMP_REMOVED> 1.1.1.1 up/down Bps: 0/51 connections: 1 diff --git a/src/tests/cases/snapshots/raw_mode__traffic_with_host_names.snap b/src/tests/cases/snapshots/raw_mode__traffic_with_host_names.snap --- a/src/tests/cases/snapshots/raw_mode__traffic_with_host_names.snap +++ b/src/tests/cases/snapshots/raw_mode__traffic_with_host_names.snap @@ -4,14 +4,14 @@ expression: formatted --- process: <TIMESTAMP_REMOVED> "1" up/down Bps: 57/61 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 34/37 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => one.one.one.one:12345 (tcp) up/down Bps: 57/61 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => three.three.three.three:1337 (tcp) up/down Bps: 34/37 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => one.one.one.one:12345 (tcp) up/down Bps: 57/61 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => three.three.three.three:1337 (tcp) up/down Bps: 34/37 process: "5" remote_address: <TIMESTAMP_REMOVED> one.one.one.one up/down Bps: 57/61 connections: 1 remote_address: <TIMESTAMP_REMOVED> three.three.three.three up/down Bps: 34/37 connections: 1 process: <TIMESTAMP_REMOVED> "1" up/down Bps: 37/36 connections: 1 process: <TIMESTAMP_REMOVED> "5" up/down Bps: 32/46 connections: 1 -connection: <TIMESTAMP_REMOVED> :443 => one.one.one.one:12345 (tcp) up/down Bps: 37/36 process: "1" -connection: <TIMESTAMP_REMOVED> :443 => three.three.three.three:1337 (tcp) up/down Bps: 32/46 process: "5" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => one.one.one.one:12345 (tcp) up/down Bps: 37/36 process: "1" +connection: <TIMESTAMP_REMOVED> <interface_name>:443 => three.three.three.three:1337 (tcp) up/down Bps: 32/46 process: "5" remote_address: <TIMESTAMP_REMOVED> one.one.one.one up/down Bps: 37/36 connections: 1 remote_address: <TIMESTAMP_REMOVED> three.three.three.three up/down Bps: 32/46 connections: 1 diff --git a/src/tests/cases/snapshots/ui__bi_directional_traffic-2.snap b/src/tests/cases/snapshots/ui__bi_directional_traffic-2.snap --- a/src/tests/cases/snapshots/ui__bi_directional_traffic-2.snap +++ b/src/tests/cases/snapshots/ui__bi_directional_traffic-2.snap @@ -6,7 +6,7 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 49Bps/51Bps :443 => 1.1.1.1:12345 (tcp) 1 49Bps/51Bps + 1 1 49Bps/51Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 49Bps/51Bps diff --git a/src/tests/cases/snapshots/ui__layout_full_width_under_30_height-2.snap b/src/tests/cases/snapshots/ui__layout_full_width_under_30_height-2.snap --- a/src/tests/cases/snapshots/ui__layout_full_width_under_30_height-2.snap +++ b/src/tests/cases/snapshots/ui__layout_full_width_under_30_height-2.snap @@ -6,10 +6,10 @@ expression: "&terminal_draw_events_mirror[1]" - 4 1 0Bps/53Bps :443 => 2.2.2.2:54321 (tcp) 4 0Bps/53Bps - 5 1 0Bps/45Bps :443 => 3.3.3.3:1337 (tcp) 5 0Bps/45Bps - 1 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps - 2 1 0Bps/42Bps :443 => 4.4.4.4:1337 (tcp) 2 0Bps/42Bps + 4 1 0Bps/53Bps <interface_name>:443 => 2.2.2.2:54321 (tcp) 4 0Bps/53Bps + 5 1 0Bps/45Bps <interface_name>:443 => 3.3.3.3:1337 (tcp) 5 0Bps/45Bps + 1 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + 2 1 0Bps/42Bps <interface_name>:443 => 4.4.4.4:1337 (tcp) 2 0Bps/42Bps diff --git a/src/tests/cases/snapshots/ui__layout_under_120_width_full_height-2.snap b/src/tests/cases/snapshots/ui__layout_under_120_width_full_height-2.snap --- a/src/tests/cases/snapshots/ui__layout_under_120_width_full_height-2.snap +++ b/src/tests/cases/snapshots/ui__layout_under_120_width_full_height-2.snap @@ -30,10 +30,10 @@ expression: "&terminal_draw_events_mirror[1]" - :443 => 2.2.2.2:54321 (tcp) 4 0Bps/53Bps - :443 => 3.3.3.3:1337 (tcp) 5 0Bps/45Bps - :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps - :443 => 4.4.4.4:1337 (tcp) 2 0Bps/42Bps + <interface_name>:443 => 2.2.2.2:54321 (tcp) 4 0Bps/53Bps + <interface_name>:443 => 3.3.3.3:1337 (tcp) 5 0Bps/45Bps + <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + <interface_name>:443 => 4.4.4.4:1337 (tcp) 2 0Bps/42Bps diff --git a/src/tests/cases/snapshots/ui__layout_under_150_width_full_height-2.snap b/src/tests/cases/snapshots/ui__layout_under_150_width_full_height-2.snap --- a/src/tests/cases/snapshots/ui__layout_under_150_width_full_height-2.snap +++ b/src/tests/cases/snapshots/ui__layout_under_150_width_full_height-2.snap @@ -30,10 +30,10 @@ expression: "&terminal_draw_events_mirror[1]" - :443 => 2.2.2.2:54321 (tcp) 0Bps/53Bps 2.2.2.2 0Bps/53Bps - :443 => 3.3.3.3:1337 (tcp) 0Bps/45Bps 3.3.3.3 0Bps/45Bps - :443 => 1.1.1.1:12345 (tcp) 0Bps/44Bps 1.1.1.1 0Bps/44Bps - :443 => 4.4.4.4:1337 (tcp) 0Bps/42Bps 4.4.4.4 0Bps/42Bps + <interface_name>:443 => 2.2.2.2:54321 (t 0Bps/53Bps 2.2.2.2 0Bps/53Bps + <interface_name>:443 => 3.3.3.3:1337 (tc 0Bps/45Bps 3.3.3.3 0Bps/45Bps + <interface_name>:443 => 1.1.1.1:12345 (t 0Bps/44Bps 1.1.1.1 0Bps/44Bps + <interface_name>:443 => 4.4.4.4:1337 (tc 0Bps/42Bps 4.4.4.4 0Bps/42Bps diff --git a/src/tests/cases/snapshots/ui__layout_under_150_width_under_30_height-2.snap b/src/tests/cases/snapshots/ui__layout_under_150_width_under_30_height-2.snap --- a/src/tests/cases/snapshots/ui__layout_under_150_width_under_30_height-2.snap +++ b/src/tests/cases/snapshots/ui__layout_under_150_width_under_30_height-2.snap @@ -6,10 +6,10 @@ expression: "&terminal_draw_events_mirror[1]" - 4 0Bps/53Bps :443 => 2.2.2.2:54321 (tcp) 0Bps/53Bps - 5 0Bps/45Bps :443 => 3.3.3.3:1337 (tcp) 0Bps/45Bps - 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 0Bps/44Bps - 2 0Bps/42Bps :443 => 4.4.4.4:1337 (tcp) 0Bps/42Bps + 4 0Bps/53Bps <interface_name>:443 => 2.2.2.2:54321 (t 0Bps/53Bps + 5 0Bps/45Bps <interface_name>:443 => 3.3.3.3:1337 (tc 0Bps/45Bps + 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (t 0Bps/44Bps + 2 0Bps/42Bps <interface_name>:443 => 4.4.4.4:1337 (tc 0Bps/42Bps diff --git a/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address-2.snap b/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address-2.snap --- a/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address-2.snap +++ b/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address-2.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[1]" - 3 1 0Bps/51Bps :443 => 1.1.1.1:12346 (tcp) 3 0Bps/51Bps - 1 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + 3 1 0Bps/51Bps <interface_name>:443 => 1.1.1.1:12346 (tcp) 3 0Bps/51Bps + 1 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps diff --git a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections-2.snap b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections-2.snap --- a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections-2.snap +++ b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections-2.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps - 4 1 0Bps/39Bps :443 => 2.2.2.2:54321 (tcp) 4 0Bps/39Bps + 1 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + 4 1 0Bps/39Bps <interface_name>:443 => 2.2.2.2:54321 (tcp) 4 0Bps/39Bps diff --git a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection-2.snap b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection-2.snap --- a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection-2.snap +++ b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection-2.snap @@ -6,7 +6,7 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 0Bps/91Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/91Bps + 1 1 0Bps/91Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/91Bps diff --git a/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections-2.snap b/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections-2.snap --- a/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections-2.snap +++ b/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections-2.snap @@ -6,10 +6,10 @@ expression: "&terminal_draw_events_mirror[1]" - 4 1 0Bps/53Bps :443 => 2.2.2.2:54321 (tcp) 4 0Bps/53Bps - 5 1 0Bps/45Bps :443 => 3.3.3.3:1337 (tcp) 5 0Bps/45Bps - 1 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps - 2 1 0Bps/42Bps :443 => 4.4.4.4:1337 (tcp) 2 0Bps/42Bps + 4 1 0Bps/53Bps <interface_name>:443 => 2.2.2.2:54321 (tcp) 4 0Bps/53Bps + 5 1 0Bps/45Bps <interface_name>:443 => 3.3.3.3:1337 (tcp) 5 0Bps/45Bps + 1 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + 2 1 0Bps/42Bps <interface_name>:443 => 4.4.4.4:1337 (tcp) 2 0Bps/42Bps diff --git a/src/tests/cases/snapshots/ui__no_resolve_mode-2.snap b/src/tests/cases/snapshots/ui__no_resolve_mode-2.snap --- a/src/tests/cases/snapshots/ui__no_resolve_mode-2.snap +++ b/src/tests/cases/snapshots/ui__no_resolve_mode-2.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[2]" - 5 32 46 3 3 3 3 3 7 (tcp) 5 32 46 - 1 7 6 1 1 1 1 2 45 (tcp) 1 7 6 + 5 32 46 3 3 3 3 3 7 (tcp) 5 32 46 + 1 7 6 1 1 1 1 2 45 (tcp) 1 7 6 diff --git a/src/tests/cases/snapshots/ui__no_resolve_mode.snap b/src/tests/cases/snapshots/ui__no_resolve_mode.snap --- a/src/tests/cases/snapshots/ui__no_resolve_mode.snap +++ b/src/tests/cases/snapshots/ui__no_resolve_mode.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 57Bps/61Bps :443 => 1.1.1.1:12345 (tcp) 1 57Bps/61Bps - 5 1 34Bps/37Bps :443 => 3.3.3.3:1337 (tcp) 5 34Bps/37Bps + 1 1 57Bps/61Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 57Bps/61Bps + 5 1 34Bps/37Bps <interface_name>:443 => 3.3.3.3:1337 (tcp) 5 34Bps/37Bps diff --git a/src/tests/cases/snapshots/ui__one_packet_of_traffic-2.snap b/src/tests/cases/snapshots/ui__one_packet_of_traffic-2.snap --- a/src/tests/cases/snapshots/ui__one_packet_of_traffic-2.snap +++ b/src/tests/cases/snapshots/ui__one_packet_of_traffic-2.snap @@ -6,7 +6,7 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 42Bps/0Bps :443 => 1.1.1.1:12345 (tcp) 1 42Bps/0Bps + 1 1 42Bps/0Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 42Bps/0Bps diff --git a/src/tests/cases/snapshots/ui__one_process_with_multiple_connections-2.snap b/src/tests/cases/snapshots/ui__one_process_with_multiple_connections-2.snap --- a/src/tests/cases/snapshots/ui__one_process_with_multiple_connections-2.snap +++ b/src/tests/cases/snapshots/ui__one_process_with_multiple_connections-2.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[1]" - 5 1 0Bps/48Bps :443 => 3.3.3.3:1337 (tcp) 5 0Bps/48Bps - 1 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + 5 1 0Bps/48Bps <interface_name>:443 => 3.3.3.3:1337 (tcp) 5 0Bps/48Bps + 1 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps diff --git a/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes.snap b/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes.snap --- a/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes.snap +++ b/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps - 5 1 0Bps/39Bps :443 => 3.3.3.3:1337 (tcp) 5 0Bps/39Bps + 1 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + 5 1 0Bps/39Bps <interface_name>:443 => 3.3.3.3:1337 (tcp) 5 0Bps/39Bps diff --git a/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional-2.snap b/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional-2.snap --- a/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional-2.snap +++ b/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional-2.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[2]" - 5 32 46 3 3 3 3 3 7 (tcp) 5 32 46 - 1 7 6 1 1 1 1 2 45 (tcp) 1 7 6 + 5 32 46 3 3 3 3 3 7 (tcp) 5 32 46 + 1 7 6 1 1 1 1 2 45 (tcp) 1 7 6 diff --git a/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional.snap b/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional.snap --- a/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional.snap +++ b/src/tests/cases/snapshots/ui__sustained_traffic_from_multiple_processes_bi_directional.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 57Bps/61Bps :443 => 1.1.1.1:12345 (tcp) 1 57Bps/61Bps - 5 1 34Bps/37Bps :443 => 3.3.3.3:1337 (tcp) 5 34Bps/37Bps + 1 1 57Bps/61Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 57Bps/61Bps + 5 1 34Bps/37Bps <interface_name>:443 => 3.3.3.3:1337 (tcp) 5 34Bps/37Bps diff --git a/src/tests/cases/snapshots/ui__sustained_traffic_from_one_process.snap b/src/tests/cases/snapshots/ui__sustained_traffic_from_one_process.snap --- a/src/tests/cases/snapshots/ui__sustained_traffic_from_one_process.snap +++ b/src/tests/cases/snapshots/ui__sustained_traffic_from_one_process.snap @@ -6,7 +6,7 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 0Bps/44Bps :443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps + 1 1 0Bps/44Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps/44Bps diff --git a/src/tests/cases/snapshots/ui__traffic_with_host_names-2.snap b/src/tests/cases/snapshots/ui__traffic_with_host_names-2.snap --- a/src/tests/cases/snapshots/ui__traffic_with_host_names-2.snap +++ b/src/tests/cases/snapshots/ui__traffic_with_host_names-2.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[2]" - 5 32 46 three.thre three.three:1337 (tcp) 5 32 46 - 1 7 6 one.one.on one:12345 (tcp) 1 7 6 + 5 32 46 three.thre three.three:13 5 32 46 + 1 7 6 one.one.on one:12345 (tcp 1 7 6 diff --git a/src/tests/cases/snapshots/ui__traffic_with_host_names.snap b/src/tests/cases/snapshots/ui__traffic_with_host_names.snap --- a/src/tests/cases/snapshots/ui__traffic_with_host_names.snap +++ b/src/tests/cases/snapshots/ui__traffic_with_host_names.snap @@ -6,8 +6,8 @@ expression: "&terminal_draw_events_mirror[1]" - 1 1 57Bps/61Bps :443 => one.one.one.one:12345 (tcp) 1 57Bps/61Bps - 5 1 34Bps/37Bps :443 => three.three.three.three:1337 (tcp) 5 34Bps/37Bps + 1 1 57Bps/61Bps <interface_name>:443 => one.one.one.one:12345 (tcp 1 57Bps/61Bps + 5 1 34Bps/37Bps <interface_name>:443 => three.three.three.three:13 5 34Bps/37Bps diff --git a/src/tests/cases/snapshots/ui__traffic_with_winch_event-3.snap b/src/tests/cases/snapshots/ui__traffic_with_winch_event-3.snap --- a/src/tests/cases/snapshots/ui__traffic_with_winch_event-3.snap +++ b/src/tests/cases/snapshots/ui__traffic_with_winch_event-3.snap @@ -6,7 +6,7 @@ expression: "&terminal_draw_events_mirror[2]" - 1 1 42Bps/0Bps :443 => 1.1.1.1:12345 (tcp) 1 42Bps/0Bps + 1 1 42Bps/0Bps <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 42Bps/0Bps diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1,6 +1,6 @@ use crate::tests::fakes::TerminalEvent::*; use crate::tests::fakes::{ - create_fake_dns_client, create_fake_on_winch, get_interface, get_open_sockets, KeyboardEvents, + create_fake_dns_client, create_fake_on_winch, get_interfaces, get_open_sockets, KeyboardEvents, NetworkFrames, TestBackend, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -13,6 +13,7 @@ use ::std::net::IpAddr; use packet_builder::payload::PayloadData; use packet_builder::*; +use pnet::datalink::DataLinkReceiver; use pnet::packet::Packet; use pnet_base::MacAddr; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -55,9 +56,9 @@ fn basic_startup() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ None, // sleep - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -70,14 +71,14 @@ fn basic_startup() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -87,7 +88,7 @@ fn basic_startup() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -110,13 +111,13 @@ fn one_packet_of_traffic() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![Some(build_tcp_packet( + let network_frames = vec![NetworkFrames::new(vec![Some(build_tcp_packet( "10.0.0.2", "1.1.1.1", 443, 12345, b"I am a fake tcp packet", - ))]); + ))]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -129,14 +130,14 @@ fn one_packet_of_traffic() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -146,7 +147,7 @@ fn one_packet_of_traffic() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -172,7 +173,7 @@ fn bi_directional_traffic() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "1.1.1.1", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -187,7 +188,7 @@ fn bi_directional_traffic() { 443, b"I am a fake tcp download packet", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -200,14 +201,14 @@ fn bi_directional_traffic() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let write_to_stdout = Box::new({ move |_output: String| {} }); let cleanup = Box::new(|| {}); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -217,7 +218,7 @@ fn bi_directional_traffic() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -243,7 +244,7 @@ fn multiple_packets_of_traffic_from_different_connections() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -258,7 +259,7 @@ fn multiple_packets_of_traffic_from_different_connections() { 443, b"I come from 2.2.2.2", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -273,12 +274,12 @@ fn multiple_packets_of_traffic_from_different_connections() { ); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, on_winch, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -288,7 +289,7 @@ fn multiple_packets_of_traffic_from_different_connections() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -314,7 +315,7 @@ fn multiple_packets_of_traffic_from_single_connection() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -329,7 +330,7 @@ fn multiple_packets_of_traffic_from_single_connection() { 443, b"I've come from 1.1.1.1 too!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -342,14 +343,14 @@ fn multiple_packets_of_traffic_from_single_connection() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -359,7 +360,7 @@ fn multiple_packets_of_traffic_from_single_connection() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -385,7 +386,7 @@ fn one_process_with_multiple_connections() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -400,7 +401,7 @@ fn one_process_with_multiple_connections() { 443, b"Funny that, I'm from 3.3.3.3", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -413,14 +414,14 @@ fn one_process_with_multiple_connections() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -430,7 +431,7 @@ fn one_process_with_multiple_connections() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -456,7 +457,7 @@ fn multiple_processes_with_multiple_connections() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -485,7 +486,7 @@ fn multiple_processes_with_multiple_connections() { 443, b"I'm partial to 4.4.4.4", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -498,14 +499,14 @@ fn multiple_processes_with_multiple_connections() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -515,7 +516,7 @@ fn multiple_processes_with_multiple_connections() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -541,7 +542,7 @@ fn multiple_connections_from_remote_address() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -556,7 +557,7 @@ fn multiple_connections_from_remote_address() { 443, b"Me too, but on a different port", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -569,14 +570,14 @@ fn multiple_connections_from_remote_address() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -586,7 +587,7 @@ fn multiple_connections_from_remote_address() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -613,7 +614,7 @@ fn sustained_traffic_from_one_process() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -629,7 +630,7 @@ fn sustained_traffic_from_one_process() { 443, b"Same here, but one second later", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -642,14 +643,14 @@ fn sustained_traffic_from_one_process() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -659,7 +660,7 @@ fn sustained_traffic_from_one_process() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -686,7 +687,7 @@ fn sustained_traffic_from_multiple_processes() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -716,7 +717,7 @@ fn sustained_traffic_from_multiple_processes() { 443, b"I come 3.3.3.3 one second later", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -729,14 +730,14 @@ fn sustained_traffic_from_multiple_processes() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -746,7 +747,7 @@ fn sustained_traffic_from_multiple_processes() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -773,7 +774,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "3.3.3.3", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -831,7 +832,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { 12345, b"10.0.0.2 forever!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -844,14 +845,14 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -861,7 +862,7 @@ fn sustained_traffic_from_multiple_processes_bi_directional() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -888,7 +889,7 @@ fn traffic_with_host_names() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "3.3.3.3", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -946,7 +947,7 @@ fn traffic_with_host_names() { 12345, b"10.0.0.2 forever!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -959,7 +960,7 @@ fn traffic_with_host_names() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let mut ips_to_hostnames = HashMap::new(); ips_to_hostnames.insert( IpAddr::V4("1.1.1.1".parse().unwrap()), diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -979,7 +980,7 @@ fn traffic_with_host_names() { let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -989,7 +990,7 @@ fn traffic_with_host_names() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1016,7 +1017,7 @@ fn no_resolve_mode() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "10.0.0.2", "3.3.3.3", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1074,7 +1075,7 @@ fn no_resolve_mode() { 12345, b"10.0.0.2 forever!", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1087,7 +1088,7 @@ fn no_resolve_mode() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let mut ips_to_hostnames = HashMap::new(); ips_to_hostnames.insert( IpAddr::V4("1.1.1.1".parse().unwrap()), diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1107,7 +1108,7 @@ fn no_resolve_mode() { let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1117,7 +1118,7 @@ fn no_resolve_mode() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: true, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1143,13 +1144,13 @@ fn traffic_with_winch_event() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![Some(build_tcp_packet( + let network_frames = vec![NetworkFrames::new(vec![Some(build_tcp_packet( "10.0.0.2", "1.1.1.1", 443, 12345, b"I am a fake tcp packet", - ))]); + ))]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1162,14 +1163,14 @@ fn traffic_with_winch_event() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(true); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1179,7 +1180,7 @@ fn traffic_with_winch_event() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1206,7 +1207,7 @@ fn layout_full_width_under_30_height() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1235,7 +1236,7 @@ fn layout_full_width_under_30_height() { 443, b"I'm partial to 4.4.4.4", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(190)); let terminal_height = Arc::new(Mutex::new(29)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1248,14 +1249,14 @@ fn layout_full_width_under_30_height() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1265,7 +1266,7 @@ fn layout_full_width_under_30_height() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1291,7 +1292,7 @@ fn layout_under_150_width_full_height() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1320,7 +1321,7 @@ fn layout_under_150_width_full_height() { 443, b"I'm partial to 4.4.4.4", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(149)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1333,14 +1334,14 @@ fn layout_under_150_width_full_height() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1350,7 +1351,7 @@ fn layout_under_150_width_full_height() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1376,7 +1377,7 @@ fn layout_under_150_width_under_30_height() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1405,7 +1406,7 @@ fn layout_under_150_width_under_30_height() { 443, b"I'm partial to 4.4.4.4", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(149)); let terminal_height = Arc::new(Mutex::new(29)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1418,14 +1419,14 @@ fn layout_under_150_width_under_30_height() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1435,7 +1436,7 @@ fn layout_under_150_width_under_30_height() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1461,7 +1462,7 @@ fn layout_under_120_width_full_height() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1490,7 +1491,7 @@ fn layout_under_120_width_full_height() { 443, b"I'm partial to 4.4.4.4", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(119)); let terminal_height = Arc::new(Mutex::new(50)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1503,14 +1504,14 @@ fn layout_under_120_width_full_height() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1520,7 +1521,7 @@ fn layout_under_120_width_full_height() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1546,7 +1547,7 @@ fn layout_under_120_width_under_30_height() { None, // sleep Some(Event::Key(Key::Ctrl('c'))), ])); - let network_frames = NetworkFrames::new(vec![ + let network_frames = vec![NetworkFrames::new(vec![ Some(build_tcp_packet( "1.1.1.1", "10.0.0.2", diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1575,7 +1576,7 @@ fn layout_under_120_width_under_30_height() { 443, b"I'm partial to 4.4.4.4", )), - ]); + ]) as Box<dyn DataLinkReceiver>]; let terminal_width = Arc::new(Mutex::new(119)); let terminal_height = Arc::new(Mutex::new(29)); diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1588,14 +1589,14 @@ fn layout_under_120_width_under_30_height() { terminal_width, terminal_height, ); - let network_interface = get_interface(); + let network_interfaces = get_interfaces(); let dns_client = create_fake_dns_client(HashMap::new()); let on_winch = create_fake_on_winch(false); let cleanup = Box::new(|| {}); let write_to_stdout = Box::new({ move |_output: String| {} }); let os_input = OsInputOutput { - network_interface, + network_interfaces, network_frames, get_open_sockets, keyboard_events, diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1605,7 +1606,7 @@ fn layout_under_120_width_under_30_height() { write_to_stdout, }; let opts = Opt { - interface: String::from("interface_name"), + interface: Some(String::from("interface_name")), raw: false, no_resolve: false, }; diff --git a/src/tests/fakes/fake_input.rs b/src/tests/fakes/fake_input.rs --- a/src/tests/fakes/fake_input.rs +++ b/src/tests/fakes/fake_input.rs @@ -135,14 +135,14 @@ pub fn get_open_sockets() -> HashMap<Connection, String> { open_sockets } -pub fn get_interface() -> NetworkInterface { - NetworkInterface { +pub fn get_interfaces() -> Vec<NetworkInterface> { + vec![NetworkInterface { name: String::from("interface_name"), index: 42, mac: None, ips: vec![IpNetwork::V4("10.0.0.2".parse().unwrap())], flags: 42, - } + }] } pub fn create_fake_on_winch(should_send_winch_event: bool) -> Box<OnSigWinch> {
Listen on all interfaces `what` now listens on the interface given by the `-i` flag. The default behaviour should probably be "listen on all interfaces", with the -i flag being an optional override. Things that are needed to do this: 1. The OS layer (eg. `os/linux.rs`) needs to be adjusted. 2. The `OsInputOutput` struct needs to be adjusted to get multiple network interfaces. 3. The UI needs to be adjusted to display the name of the local interface where relevant (mostly in the connections table). Maybe something like `<eth0>:12345 => 1.1.1.1:54321` *shrug emoji*
2019-12-10T22:07:27Z
0.4
2019-12-22T09:53:02Z
408ec397c81bb99d6727f01d5dc058e814012714
[ "tests::cases::ui::basic_startup", "tests::cases::ui::layout_under_120_width_under_30_height", "tests::cases::ui::layout_under_150_width_under_30_height", "tests::cases::ui::layout_full_width_under_30_height", "tests::cases::ui::layout_under_120_width_full_height", "tests::cases::raw_mode::multiple_packets_of_traffic_from_single_connection", "tests::cases::raw_mode::one_process_with_multiple_connections", "tests::cases::raw_mode::one_packet_of_traffic", "tests::cases::raw_mode::multiple_connections_from_remote_address", "tests::cases::raw_mode::bi_directional_traffic", "tests::cases::raw_mode::multiple_packets_of_traffic_from_different_connections", "tests::cases::raw_mode::multiple_processes_with_multiple_connections", "tests::cases::ui::layout_under_150_width_full_height", "tests::cases::ui::multiple_packets_of_traffic_from_different_connections", "tests::cases::ui::multiple_processes_with_multiple_connections", "tests::cases::ui::multiple_connections_from_remote_address", "tests::cases::ui::one_packet_of_traffic", "tests::cases::ui::multiple_packets_of_traffic_from_single_connection", "tests::cases::ui::bi_directional_traffic", "tests::cases::ui::one_process_with_multiple_connections", "tests::cases::ui::traffic_with_winch_event", "tests::cases::raw_mode::no_resolve_mode", "tests::cases::ui::no_resolve_mode", "tests::cases::raw_mode::traffic_with_host_names", "tests::cases::raw_mode::sustained_traffic_from_one_process", "tests::cases::raw_mode::sustained_traffic_from_multiple_processes_bi_directional", "tests::cases::raw_mode::sustained_traffic_from_multiple_processes", "tests::cases::ui::sustained_traffic_from_one_process", "tests::cases::ui::sustained_traffic_from_multiple_processes_bi_directional", "tests::cases::ui::traffic_with_host_names", "tests::cases::ui::sustained_traffic_from_multiple_processes" ]
[]
[]
[]
auto_2025-06-07
imsnif/bandwhich
118
imsnif__bandwhich-118
[ "100" ]
e6bb39a5e992498e00bc3af47d92352865e3223d
diff --git a/.gitignore b/.gitignore --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,4 @@ debian/* !debian/control !debian/copyright !debian/rules -!debian/source +!debian/source \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ## [Unreleased] +### Added +* Ability to change the window layout with <TAB> (https://github.com/imsnif/bandwhich/pull/118) - [@Louis-Lesage](https://github.com/Louis-Lesage) + ### Fixed * Add terabytes as a display unit (for cumulative mode) (https://github.com/imsnif/bandwhich/pull/168) - [@TheLostLambda](https://github.com/TheLostLambda) diff --git a/src/display/components/help_text.rs b/src/display/components/help_text.rs --- a/src/display/components/help_text.rs +++ b/src/display/components/help_text.rs @@ -9,10 +9,14 @@ pub struct HelpText { pub show_dns: bool, } -const TEXT_WHEN_PAUSED: &str = " Press <SPACE> to resume"; -const TEXT_WHEN_NOT_PAUSED: &str = " Press <SPACE> to pause"; +const FIRST_WIDTH_BREAKPOINT: u16 = 76; +const SECOND_WIDTH_BREAKPOINT: u16 = 54; + +const TEXT_WHEN_PAUSED: &str = " Press <SPACE> to resume."; +const TEXT_WHEN_NOT_PAUSED: &str = " Press <SPACE> to pause."; const TEXT_WHEN_DNS_NOT_SHOWN: &str = " (DNS queries hidden)."; const TEXT_WHEN_DNS_SHOWN: &str = " (DNS queries shown)."; +const TEXT_TAB_TIP: &str = " Use <TAB> to rearrange tables."; impl HelpText { pub fn render(&self, frame: &mut Frame<impl Backend>, rect: Rect) { diff --git a/src/display/components/help_text.rs b/src/display/components/help_text.rs --- a/src/display/components/help_text.rs +++ b/src/display/components/help_text.rs @@ -23,14 +27,22 @@ impl HelpText { TEXT_WHEN_NOT_PAUSED }; - let dns_content = if self.show_dns { + let dns_content = if rect.width <= FIRST_WIDTH_BREAKPOINT { + "" + } else if self.show_dns { TEXT_WHEN_DNS_SHOWN } else { TEXT_WHEN_DNS_NOT_SHOWN }; + let tab_text = if rect.width <= SECOND_WIDTH_BREAKPOINT { + "" + } else { + TEXT_TAB_TIP + }; + [Text::styled( - format!("{}{}", pause_content, dns_content), + format!("{}{}{}", pause_content, tab_text, dns_content), Style::default().modifier(Modifier::BOLD), )] }; diff --git a/src/display/components/layout.rs b/src/display/components/layout.rs --- a/src/display/components/layout.rs +++ b/src/display/components/layout.rs @@ -99,12 +99,12 @@ impl<'a> Layout<'a> { self.build_three_children_layout(rect) } } - pub fn render(&self, frame: &mut Frame<impl Backend>, rect: Rect) { + pub fn render(&self, frame: &mut Frame<impl Backend>, rect: Rect, ui_offset: usize) { let (top, app, bottom) = top_app_and_bottom_split(rect); let layout_slots = self.build_layout(app); for i in 0..layout_slots.len() { if let Some(rect) = layout_slots.get(i) { - if let Some(child) = self.children.get(i) { + if let Some(child) = self.children.get((i + ui_offset) % self.children.len()) { child.render(frame, *rect); } } diff --git a/src/display/ui.rs b/src/display/ui.rs --- a/src/display/ui.rs +++ b/src/display/ui.rs @@ -61,7 +61,7 @@ where display_connection_string( connection, ip_to_host, - &connection_network_data.interface_name + &connection_network_data.interface_name, ), connection_network_data.total_bytes_uploaded, connection_network_data.total_bytes_downloaded, diff --git a/src/display/ui.rs b/src/display/ui.rs --- a/src/display/ui.rs +++ b/src/display/ui.rs @@ -79,7 +79,7 @@ where )); } } - pub fn draw(&mut self, paused: bool, show_dns: bool) { + pub fn draw(&mut self, paused: bool, show_dns: bool, ui_offset: usize) { let state = &self.state; let children = self.get_tables_to_display(); self.terminal diff --git a/src/display/ui.rs b/src/display/ui.rs --- a/src/display/ui.rs +++ b/src/display/ui.rs @@ -95,7 +95,7 @@ where children, footer: help_text, }; - layout.render(&mut frame, size); + layout.render(&mut frame, size, ui_offset); }) .unwrap(); } diff --git a/src/display/ui.rs b/src/display/ui.rs --- a/src/display/ui.rs +++ b/src/display/ui.rs @@ -127,6 +127,11 @@ where } children } + + pub fn get_table_count(&self) -> usize { + self.get_tables_to_display().len() + } + pub fn update_state( &mut self, connections_to_procs: HashMap<LocalSocket, String>, diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ use os::OnSigWinch; use ::pnet::datalink::{DataLinkReceiver, NetworkInterface}; use ::std::collections::HashMap; -use ::std::sync::atomic::{AtomicBool, Ordering}; +use ::std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use ::std::sync::{Arc, Mutex}; use ::std::thread::park_timeout; use ::std::{thread, time}; diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -121,6 +121,7 @@ where { let running = Arc::new(AtomicBool::new(true)); let paused = Arc::new(AtomicBool::new(false)); + let ui_offset = Arc::new(AtomicUsize::new(0)); let dns_shown = opts.show_dns; let mut active_threads = vec![]; diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -144,11 +145,17 @@ where .spawn({ let ui = ui.clone(); let paused = paused.clone(); + let ui_offset = ui_offset.clone(); + move || { on_winch({ Box::new(move || { let mut ui = ui.lock().unwrap(); - ui.draw(paused.load(Ordering::SeqCst), dns_shown); + ui.draw( + paused.load(Ordering::SeqCst), + dns_shown, + ui_offset.load(Ordering::SeqCst), + ); }) }); } diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -162,7 +169,11 @@ where .spawn({ let running = running.clone(); let paused = paused.clone(); + let ui_offset = ui_offset.clone(); + let network_utilization = network_utilization.clone(); + let ui = ui.clone(); + move || { while running.load(Ordering::Acquire) { let render_start_time = Instant::now(); diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -185,13 +196,14 @@ where { let mut ui = ui.lock().unwrap(); let paused = paused.load(Ordering::SeqCst); + let ui_offset = ui_offset.load(Ordering::SeqCst); if !paused { ui.update_state(sockets_to_procs, utilization, ip_to_host); } if raw_mode { ui.output_text(&mut write_to_stdout); } else { - ui.draw(paused, dns_shown); + ui.draw(paused, dns_shown, ui_offset); } } let render_duration = render_start_time.elapsed(); diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -213,8 +225,11 @@ where .spawn({ let running = running.clone(); let display_handler = display_handler.thread().clone(); + move || { for evt in keyboard_events { + let mut ui = ui.lock().unwrap(); + match evt { Event::Key(Key::Ctrl('c')) | Event::Key(Key::Char('q')) => { running.store(false, Ordering::Release); diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -226,6 +241,12 @@ where paused.fetch_xor(true, Ordering::SeqCst); display_handler.unpark(); } + Event::Key(Key::Char('\t')) => { + let table_count = ui.get_table_count(); + let new = ui_offset.load(Ordering::SeqCst) + 1 % table_count; + ui_offset.store(new, Ordering::SeqCst); + ui.draw(paused.load(Ordering::SeqCst), dns_shown, new); + } _ => (), }; }
diff --git a/src/tests/cases/snapshots/ui__basic_only_addresses.snap b/src/tests/cases/snapshots/ui__basic_only_addresses.snap --- a/src/tests/cases/snapshots/ui__basic_only_addresses.snap +++ b/src/tests/cases/snapshots/ui__basic_only_addresses.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__basic_only_connections.snap b/src/tests/cases/snapshots/ui__basic_only_connections.snap --- a/src/tests/cases/snapshots/ui__basic_only_connections.snap +++ b/src/tests/cases/snapshots/ui__basic_only_connections.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__basic_only_processes.snap b/src/tests/cases/snapshots/ui__basic_only_processes.snap --- a/src/tests/cases/snapshots/ui__basic_only_processes.snap +++ b/src/tests/cases/snapshots/ui__basic_only_processes.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__basic_processes_with_dns_queries.snap b/src/tests/cases/snapshots/ui__basic_processes_with_dns_queries.snap --- a/src/tests/cases/snapshots/ui__basic_processes_with_dns_queries.snap +++ b/src/tests/cases/snapshots/ui__basic_processes_with_dns_queries.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries shown). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries shown). diff --git a/src/tests/cases/snapshots/ui__basic_startup.snap b/src/tests/cases/snapshots/ui__basic_startup.snap --- a/src/tests/cases/snapshots/ui__basic_startup.snap +++ b/src/tests/cases/snapshots/ui__basic_startup.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__bi_directional_traffic.snap b/src/tests/cases/snapshots/ui__bi_directional_traffic.snap --- a/src/tests/cases/snapshots/ui__bi_directional_traffic.snap +++ b/src/tests/cases/snapshots/ui__bi_directional_traffic.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__layout_full_width_under_30_height.snap b/src/tests/cases/snapshots/ui__layout_full_width_under_30_height.snap --- a/src/tests/cases/snapshots/ui__layout_full_width_under_30_height.snap +++ b/src/tests/cases/snapshots/ui__layout_full_width_under_30_height.snap @@ -30,5 +30,5 @@ expression: "&terminal_draw_events_mirror[0]" │ ││ │ │ ││ │ └─────────────────────────────────────────────────────────────────────────────────────────────┘└─────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__layout_under_120_width_full_height.snap b/src/tests/cases/snapshots/ui__layout_under_120_width_full_height.snap --- a/src/tests/cases/snapshots/ui__layout_under_120_width_full_height.snap +++ b/src/tests/cases/snapshots/ui__layout_under_120_width_full_height.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__layout_under_120_width_under_30_height.snap b/src/tests/cases/snapshots/ui__layout_under_120_width_under_30_height.snap --- a/src/tests/cases/snapshots/ui__layout_under_120_width_under_30_height.snap +++ b/src/tests/cases/snapshots/ui__layout_under_120_width_under_30_height.snap @@ -30,5 +30,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git /dev/null b/src/tests/cases/snapshots/ui__layout_under_50_width_under_50_height-2.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__layout_under_50_width_under_50_height-2.snap @@ -0,0 +1,54 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[1]" +--- + 98Bps + + + + 5 0Bps / 28Bps + 4 0Bps / 26Bps + 1 0Bps / 22Bps + 2 0Bps / 21Bps + + + + + + + + + + + + + + + + + + + + 3.3.3.3 0Bps / 28Bps + 2.2.2.2 0Bps / 26Bps + 1.1.1.1 0Bps / 22Bps + 4.4.4.4 0Bps / 21Bps + + + + + + + + + + + + + + + + + + + diff --git /dev/null b/src/tests/cases/snapshots/ui__layout_under_50_width_under_50_height.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__layout_under_50_width_under_50_height.snap @@ -0,0 +1,54 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[0]" +--- + Total Up / Down: 0Bps / 0Bps +┌Utilization by process name────────────────────┐ +│Process Up / Down │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +└───────────────────────────────────────────────┘ +┌Utilization by remote address──────────────────┐ +│Remote Address Up / Down │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +└───────────────────────────────────────────────┘ + Press <SPACE> to pause. + diff --git /dev/null b/src/tests/cases/snapshots/ui__layout_under_70_width_under_30_height-2.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__layout_under_70_width_under_30_height-2.snap @@ -0,0 +1,34 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[1]" +--- + 98Bps + + + + 5 1 0Bps / 28Bps + 4 1 0Bps / 26Bps + 1 1 0Bps / 22Bps + 2 1 0Bps / 21Bps + + + + + + + + + + + + + + + + + + + + + + diff --git /dev/null b/src/tests/cases/snapshots/ui__layout_under_70_width_under_30_height.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__layout_under_70_width_under_30_height.snap @@ -0,0 +1,34 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[0]" +--- + Total Up / Down: 0Bps / 0Bps +┌Utilization by process name────────────────────────────────────────┐ +│Process Connections Up / Down │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +└───────────────────────────────────────────────────────────────────┘ + Press <SPACE> to pause. Use <TAB> to rearrange tables. + diff --git a/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address.snap b/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address.snap --- a/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address.snap +++ b/src/tests/cases/snapshots/ui__multiple_connections_from_remote_address.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections.snap b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections.snap --- a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections.snap +++ b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_different_connections.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection.snap b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection.snap --- a/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection.snap +++ b/src/tests/cases/snapshots/ui__multiple_packets_of_traffic_from_single_connection.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections.snap b/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections.snap --- a/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections.snap +++ b/src/tests/cases/snapshots/ui__multiple_processes_with_multiple_connections.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__one_packet_of_traffic.snap b/src/tests/cases/snapshots/ui__one_packet_of_traffic.snap --- a/src/tests/cases/snapshots/ui__one_packet_of_traffic.snap +++ b/src/tests/cases/snapshots/ui__one_packet_of_traffic.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__one_process_with_multiple_connections.snap b/src/tests/cases/snapshots/ui__one_process_with_multiple_connections.snap --- a/src/tests/cases/snapshots/ui__one_process_with_multiple_connections.snap +++ b/src/tests/cases/snapshots/ui__one_process_with_multiple_connections.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__pause_by_space-2.snap b/src/tests/cases/snapshots/ui__pause_by_space-2.snap --- a/src/tests/cases/snapshots/ui__pause_by_space-2.snap +++ b/src/tests/cases/snapshots/ui__pause_by_space-2.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[1]" - resume (DNS queries hi den). + resume. Use <TAB> to rea range tables. (DNS queries hi den). diff --git a/src/tests/cases/snapshots/ui__pause_by_space.snap b/src/tests/cases/snapshots/ui__pause_by_space.snap --- a/src/tests/cases/snapshots/ui__pause_by_space.snap +++ b/src/tests/cases/snapshots/ui__pause_by_space.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git /dev/null b/src/tests/cases/snapshots/ui__rearranged_by_tab-2.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__rearranged_by_tab-2.snap @@ -0,0 +1,55 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[1]" +--- + 22Bps + + + + 1 1 0Bps / 22Bps 1.1.1.1 1 0Bps / 22Bps + + + + + + + + + + + + + + + + + + + + + + + + <interface_name>:443 => 1.1.1.1:12345 (tcp) 1 0Bps / 22Bps + + + + + + + + + + + + + + + + + + + + + + diff --git /dev/null b/src/tests/cases/snapshots/ui__rearranged_by_tab-3.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__rearranged_by_tab-3.snap @@ -0,0 +1,55 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[2]" +--- + + remote addr ss connection──── + Remote Address Connections Up / Down Connection Proc ss + + .1.1.1 1 0Bps / 22Bps <interface_na[..]1:12345 (tcp) + + + + + + + + + + + + + + + + + + + + + proc ss name + Proc ss Connections Up / Down + + 1 1 0Bps / 22Bps + + + + + + + + + + + + + + + + + + + + + + diff --git /dev/null b/src/tests/cases/snapshots/ui__rearranged_by_tab-4.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__rearranged_by_tab-4.snap @@ -0,0 +1,55 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[3]" +--- + 14 + + + + 14 14 + + + + + + + + + + + + + + + + + + + + + + + + 14 + + + + + + + + + + + + + + + + + + + + + + diff --git /dev/null b/src/tests/cases/snapshots/ui__rearranged_by_tab-5.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__rearranged_by_tab-5.snap @@ -0,0 +1,55 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[4]" +--- + 1 + + + + 1 1 + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + + + + + + + + + + + + + diff --git /dev/null b/src/tests/cases/snapshots/ui__rearranged_by_tab.snap new file mode 100644 --- /dev/null +++ b/src/tests/cases/snapshots/ui__rearranged_by_tab.snap @@ -0,0 +1,55 @@ +--- +source: src/tests/cases/ui.rs +expression: "&terminal_draw_events_mirror[0]" +--- + Total Up / Down: 0Bps / 0Bps +┌Utilization by process name──────────────────────────────────────────────────────────────────┐┌Utilization by remote address────────────────────────────────────────────────────────────────┐ +│Process Connections Up / Down ││Remote Address Connections Up / Down │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +│ ││ │ +└─────────────────────────────────────────────────────────────────────────────────────────────┘└─────────────────────────────────────────────────────────────────────────────────────────────┘ +┌Utilization by connection───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│Connection Process Up / Down │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). + diff --git a/src/tests/cases/snapshots/ui__traffic_with_winch_event.snap b/src/tests/cases/snapshots/ui__traffic_with_winch_event.snap --- a/src/tests/cases/snapshots/ui__traffic_with_winch_event.snap +++ b/src/tests/cases/snapshots/ui__traffic_with_winch_event.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__two_packets_only_addresses.snap b/src/tests/cases/snapshots/ui__two_packets_only_addresses.snap --- a/src/tests/cases/snapshots/ui__two_packets_only_addresses.snap +++ b/src/tests/cases/snapshots/ui__two_packets_only_addresses.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__two_packets_only_connections.snap b/src/tests/cases/snapshots/ui__two_packets_only_connections.snap --- a/src/tests/cases/snapshots/ui__two_packets_only_connections.snap +++ b/src/tests/cases/snapshots/ui__two_packets_only_connections.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__two_packets_only_processes.snap b/src/tests/cases/snapshots/ui__two_packets_only_processes.snap --- a/src/tests/cases/snapshots/ui__two_packets_only_processes.snap +++ b/src/tests/cases/snapshots/ui__two_packets_only_processes.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/snapshots/ui__two_windows_split_horizontally.snap b/src/tests/cases/snapshots/ui__two_windows_split_horizontally.snap --- a/src/tests/cases/snapshots/ui__two_windows_split_horizontally.snap +++ b/src/tests/cases/snapshots/ui__two_windows_split_horizontally.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ │ │ │ └──────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. diff --git a/src/tests/cases/snapshots/ui__two_windows_split_vertically.snap b/src/tests/cases/snapshots/ui__two_windows_split_vertically.snap --- a/src/tests/cases/snapshots/ui__two_windows_split_vertically.snap +++ b/src/tests/cases/snapshots/ui__two_windows_split_vertically.snap @@ -51,5 +51,5 @@ expression: "&terminal_draw_events_mirror[0]" │ ││ │ │ ││ │ └─────────────────────────────────────────────────────────────────────────────────────────────┘└─────────────────────────────────────────────────────────────────────────────────────────────┘ - Press <SPACE> to pause (DNS queries hidden). + Press <SPACE> to pause. Use <TAB> to rearrange tables. (DNS queries hidden). diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -91,6 +91,58 @@ fn pause_by_space() { assert_snapshot!(&terminal_draw_events_mirror[2]); } +#[test] +fn rearranged_by_tab() { + let network_frames = vec![NetworkFrames::new(vec![ + Some(build_tcp_packet( + "1.1.1.1", + "10.0.0.2", + 12345, + 443, + b"I have come from 1.1.1.1", + )), + None, // sleep + None, // sleep + None, // sleep + Some(build_tcp_packet( + "1.1.1.1", + "10.0.0.2", + 12345, + 443, + b"Same here, but one second later", + )), + ]) as Box<dyn DataLinkReceiver>]; + + // sleep for 1s, then press tab, sleep for 2s, then quit + let mut events: Vec<Option<Event>> = iter::repeat(None).take(1).collect(); + events.push(None); + events.push(Some(Event::Key(Key::Char('\t')))); + events.push(None); + events.push(None); + events.push(Some(Event::Key(Key::Ctrl('c')))); + + let events = Box::new(KeyboardEvents::new(events)); + let os_input = os_input_output_factory(network_frames, None, None, events); + let (terminal_events, terminal_draw_events, backend) = test_backend_factory(190, 50); + let opts = opts_ui(); + start(backend, os_input, opts); + let terminal_draw_events_mirror = terminal_draw_events.lock().unwrap(); + let expected_terminal_events = vec![ + Clear, HideCursor, Draw, Flush, Draw, Flush, Draw, Flush, Draw, Flush, Draw, Flush, Clear, + ShowCursor, + ]; + assert_eq!( + &terminal_events.lock().unwrap()[..], + &expected_terminal_events[..] + ); + assert_eq!(terminal_draw_events_mirror.len(), 5); + assert_snapshot!(&terminal_draw_events_mirror[0]); + assert_snapshot!(&terminal_draw_events_mirror[1]); + assert_snapshot!(&terminal_draw_events_mirror[2]); + assert_snapshot!(&terminal_draw_events_mirror[3]); + assert_snapshot!(&terminal_draw_events_mirror[4]); +} + #[test] fn basic_only_processes() { let network_frames = vec![NetworkFrames::new(vec![ diff --git a/src/tests/cases/ui.rs b/src/tests/cases/ui.rs --- a/src/tests/cases/ui.rs +++ b/src/tests/cases/ui.rs @@ -1458,3 +1510,105 @@ fn layout_under_120_width_under_30_height() { assert_snapshot!(&terminal_draw_events_mirror[0]); assert_snapshot!(&terminal_draw_events_mirror[1]); } + +#[test] +fn layout_under_50_width_under_50_height() { + let network_frames = vec![NetworkFrames::new(vec![ + Some(build_tcp_packet( + "1.1.1.1", + "10.0.0.2", + 12345, + 443, + b"I have come from 1.1.1.1", + )), + Some(build_tcp_packet( + "3.3.3.3", + "10.0.0.2", + 1337, + 4435, + b"Greetings traveller, I'm from 3.3.3.3", + )), + Some(build_tcp_packet( + "2.2.2.2", + "10.0.0.2", + 54321, + 4434, + b"You know, 2.2.2.2 is really nice!", + )), + Some(build_tcp_packet( + "4.4.4.4", + "10.0.0.2", + 1337, + 4432, + b"I'm partial to 4.4.4.4", + )), + ]) as Box<dyn DataLinkReceiver>]; + let (terminal_events, terminal_draw_events, backend) = test_backend_factory(49, 49); + let os_input = os_input_output(network_frames, 2); + let opts = opts_ui(); + start(backend, os_input, opts); + let terminal_draw_events_mirror = terminal_draw_events.lock().unwrap(); + + let expected_terminal_events = vec![ + Clear, HideCursor, Draw, Flush, Draw, Flush, Clear, ShowCursor, + ]; + assert_eq!( + &terminal_events.lock().unwrap()[..], + &expected_terminal_events[..] + ); + + assert_eq!(terminal_draw_events_mirror.len(), 2); + assert_snapshot!(&terminal_draw_events_mirror[0]); + assert_snapshot!(&terminal_draw_events_mirror[1]); +} + +#[test] +fn layout_under_70_width_under_30_height() { + let network_frames = vec![NetworkFrames::new(vec![ + Some(build_tcp_packet( + "1.1.1.1", + "10.0.0.2", + 12345, + 443, + b"I have come from 1.1.1.1", + )), + Some(build_tcp_packet( + "3.3.3.3", + "10.0.0.2", + 1337, + 4435, + b"Greetings traveller, I'm from 3.3.3.3", + )), + Some(build_tcp_packet( + "2.2.2.2", + "10.0.0.2", + 54321, + 4434, + b"You know, 2.2.2.2 is really nice!", + )), + Some(build_tcp_packet( + "4.4.4.4", + "10.0.0.2", + 1337, + 4432, + b"I'm partial to 4.4.4.4", + )), + ]) as Box<dyn DataLinkReceiver>]; + let (terminal_events, terminal_draw_events, backend) = test_backend_factory(69, 29); + let os_input = os_input_output(network_frames, 2); + let opts = opts_ui(); + start(backend, os_input, opts); + let terminal_draw_events_mirror = terminal_draw_events.lock().unwrap(); + + let expected_terminal_events = vec![ + Clear, HideCursor, Draw, Flush, Draw, Flush, Clear, ShowCursor, + ]; + assert_eq!( + &terminal_events.lock().unwrap()[..], + &expected_terminal_events[..] + ); + + assert_eq!(terminal_draw_events_mirror.len(), 2); + assert_snapshot!(&terminal_draw_events_mirror[0]); + assert_snapshot!(&terminal_draw_events_mirror[1]); +}
Option to change the default 'window' when terminal is small Is it possible to implement an option for default 'window' to display when the terminal size is small? I'd love to be able to get 'Utilization by connection' as default information, for example, instead of 'Utilization by process name'. And even more, an option to always display only that 'window'.
I'd be open to adding `--connections`, `--remote-ips` and `--processes` flags. These would have to be mutually exclusive, and picking one of them would only display that window regardless of terminal size. If anyone wants to pick this up and is unsure how to proceed, give me a ping here or privately. Hello @imsnif. I was toying around to make a proposal for this issue but I see structopt doesn't support mutually exclusive parameters out of the box. Any idea? The rest seems straightforward: pass the Opt to the UI, select the children in the layout according to the opt, but I cannot figure out how to properly design the CLI Ahh, that's too bad about structopt. I wouldn't mind just doing a normal run-of-the-mill if chain that would Error inside `try_main` if we have more than 1 of those flags. If you want to be really fancy, you can make some sort of `validate_ops` function that would do that and also give us a place for similar logic in the future. Alright then I take this issue. Before starting, are we sure we don't want something like "--window processes"? That way we can also have two and it's more flexible. Well, that would be great (maybe call it `--windows` and have it accept 1-3 windows to show?) But it sounds like a much bigger project, no? As you wish. We can also start small and go bigger in another PR. Sorry I'm a bit late to the party, but if I'm not mistaken structopt exposes all of clap functionality, are we sure we can't go with [conflicts_with](https://docs.rs/clap/2.33.0/clap/struct.Arg.html#method.conflicts_with)? @imsnif it personally doesn't seem like much of a difference to me. The input is still the opts and the output is still a list of layout children. @ebroto I will look into it. @chobeat - what I expect might be a little work is getting the windows to behave properly in different layouts (spacing between columns and such). But tbh I haven't touched that code in a while, so maybe you have more context than me. I trust your judgment. Never trust my judgement lol. I have no idea what I'm doing. Anyway I've tried the first thing you described, just to see what happens: https://github.com/imsnif/bandwhich/pull/107 The option in structopt we were looking for is `group`: https://github.com/TeXitoi/structopt/blob/master/examples/group.rs
2020-01-14T23:51:55Z
0.14
2020-05-17T20:40:05Z
e6bb39a5e992498e00bc3af47d92352865e3223d
[ "tests::cases::ui::basic_processes_with_dns_queries", "tests::cases::ui::basic_startup", "tests::cases::ui::basic_only_connections", "tests::cases::ui::basic_only_processes", "tests::cases::ui::basic_only_addresses", "tests::cases::ui::two_windows_split_vertically", "tests::cases::ui::layout_under_120_width_under_30_height", "tests::cases::ui::layout_full_width_under_30_height", "tests::cases::ui::bi_directional_traffic", "tests::cases::ui::layout_under_70_width_under_30_height", "tests::cases::ui::layout_under_50_width_under_50_height", "tests::cases::ui::two_windows_split_horizontally", "tests::cases::ui::layout_under_120_width_full_height", "tests::cases::ui::two_packets_only_processes", "tests::cases::ui::one_process_with_multiple_connections", "tests::cases::ui::multiple_packets_of_traffic_from_different_connections", "tests::cases::ui::multiple_processes_with_multiple_connections", "tests::cases::ui::two_packets_only_connections", "tests::cases::ui::two_packets_only_addresses", "tests::cases::ui::one_packet_of_traffic", "tests::cases::ui::traffic_with_winch_event", "tests::cases::ui::multiple_packets_of_traffic_from_single_connection", "tests::cases::ui::multiple_connections_from_remote_address", "tests::cases::ui::pause_by_space", "tests::cases::ui::rearranged_by_tab" ]
[ "tests::cases::raw_mode::bi_directional_traffic", "tests::cases::raw_mode::multiple_connections_from_remote_address", "tests::cases::raw_mode::multiple_packets_of_traffic_from_different_connections", "tests::cases::raw_mode::one_process_with_multiple_connections", "tests::cases::raw_mode::one_ip_packet_of_traffic", "tests::cases::raw_mode::multiple_processes_with_multiple_connections", "tests::cases::raw_mode::one_packet_of_traffic", "tests::cases::raw_mode::multiple_packets_of_traffic_from_single_connection", "tests::cases::raw_mode::sustained_traffic_from_multiple_processes_bi_directional", "tests::cases::raw_mode::sustained_traffic_from_multiple_processes", "tests::cases::raw_mode::sustained_traffic_from_one_process", "tests::cases::raw_mode::no_resolve_mode", "tests::cases::raw_mode::traffic_with_host_names", "tests::cases::ui::no_resolve_mode", "tests::cases::ui::truncate_long_hostnames", "tests::cases::ui::traffic_with_host_names", "tests::cases::ui::sustained_traffic_from_multiple_processes", "tests::cases::ui::sustained_traffic_from_multiple_processes_bi_directional_total", "tests::cases::ui::sustained_traffic_from_multiple_processes_total", "tests::cases::ui::sustained_traffic_from_multiple_processes_bi_directional", "tests::cases::ui::sustained_traffic_from_one_process_total", "tests::cases::ui::sustained_traffic_from_one_process" ]
[]
[]
auto_2025-06-07
rust-fuzz/cargo-fuzz
388
rust-fuzz__cargo-fuzz-388
[ "386" ]
a608970259c3b0d575e70b0748c1c4cf79081031
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -165,6 +165,20 @@ pub struct BuildOptions { /// and the fuzzer can store an input to the corpus at each condition that it passes; /// giving it a better chance of producing an input that reaches `res = 2;`. pub disable_branch_folding: Option<bool>, + + #[arg(long)] + /// Disable the inclusion of the `/include:main` MSVC linker argument + /// + /// The purpose of `/include:main` is to force the MSVC linker to include an + /// external reference to the symbol `main`, such that fuzzing targets built + /// on Windows are able to find LibFuzzer's `main` function. + /// + /// In certain corner cases, users may prefer to *not* build with this + /// argument. One such example: if a user is intending to build and fuzz a + /// Windows DLL, they would likely choose to enable this flag, to prevent + /// the DLL from having an extern `main` reference added to it. (DLLs/shared + /// libraries should not have any reference to `main`.) + pub no_include_main_msvc: bool, } impl stdfmt::Display for BuildOptions { diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -233,8 +233,23 @@ impl FuzzProject { if !build.release || build.debug_assertions || build.careful_mode { rustflags.push_str(" -Cdebug-assertions"); } - if build.triple.contains("-msvc") { - // The entrypoint is in the bundled libfuzzer rlib, this gets the linker to find it. + if build.triple.contains("-msvc") && !build.no_include_main_msvc { + // This forces the MSVC linker (which runs on Windows systems) to + // find the entry point (i.e. the `main` function) within the + // LibFuzzer `.rlib` file produced during the build. + // + // The `--no-include-main-msvc` argument disables the addition of + // this linker argument. In certain situations, a user may not want + // this argument included as part of the MSVC invocation. + // + // For example, if the user is attempting to build and fuzz a + // Windows DLL (shared library), adding `/include:main` will force + // the DLL to compile with an external reference to `main`. + // DLLs/shared libraries are designed to be built as a separate + // object file, intentionally left *without* knowledge of the entry + // point. So, forcing a DLL to include `main` will cause linking to + // fail. Using `--no-include-main-msvc` will allow the DLL to be + // built without issue. rustflags.push_str(" -Clink-arg=/include:main"); }
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -265,6 +279,7 @@ mod test { no_cfg_fuzzing: false, no_trace_compares: false, disable_branch_folding: None, + no_include_main_msvc: false, }; let opts = vec![
Fuzzing Windows DLL (cdylib) - Unresolved External Symbol Main Hi cargo-fuzz devs! I am working on fuzzing a Windows DLL with cargo-fuzz and have been hitting a wall with a particular linker error. I've reproduced the problem in a small & simple Cargo project to demonstrate the issue. ## Problem Description The issue arises when the to-be-fuzzed Cargo project defines its `crate-type` as `["cdylib"]`, specifically on Windows (it will compile into a DLL). The `Cargo.toml` looks something like this: ```toml [package] name = "simplelib" version = "0.1.0" edition = "2021" # ... [lib] crate-type = ["cdylib"] # ... [dependencies.windows] version = "0.58.0" features = [ "Win32" ] # ... ``` A very basic DLL `DllMain` function in `lib.rs` looks like this: ```rust use windows::Win32::Foundation::*; #[export_name = "DllMain"] extern "system" fn dll_main(_: HINSTANCE, _: u32, _: *mut ()) -> bool { true } ``` After running `cargo fuzz init` to initialize a basic fuzzing sub-project, the command `cargo fuzz build` (or `cargo fuzz run`) will fail during building with the following linker error: ``` = note: Creating library C:\Users\USERNAME\dev\simplelib\fuzz\target\x86_64-pc-windows-msvc\release\deps\simplelib.dll.lib and object C:\Users\USERNAME\dev\simplelib\fuzz\target\x86_64-pc-windows-msvc\release\deps\simplelib.dll.exp LINK : error LNK2001: unresolved external symbol main C:\Users\USERNAME\dev\simplelib\fuzz\target\x86_64-pc-windows-msvc\release\deps\simplelib.dll : fatal error LNK1120: 1 unresolved externals ``` ### Steps to Reproduce 1. On a Windows system (with Rust/Cargo installed), open PowerShell 2. `cargo init --lib ./simplelib` 3. (edit Cargo.toml to have the above information) 4. `cargo fuzz init` 5. `cargo fuzz build` ## Problem Analysis I spent time digging through the various options passed to the Rust compiler by cargo-fuzz, and found [this commit](https://github.com/rust-fuzz/cargo-fuzz/commit/34ca3fbd9d7e99c1db20abf21039f17f8fa74f5c), which adds the `/include:main` linker argument for builds using the `msvc` triple. Based on the comment left with that line of code, and reading up on the [/include option](https://learn.microsoft.com/en-us/cpp/build/reference/include-force-symbol-references), I understand the intention is to force libraries compiled on Windows to include the `main` symbol, so it can be found within LibFuzzer. I also found #281, and based on the discussion there it seems like `crate-type = ["cdylib"]` may not be supported by cargo-fuzz. If I'm thinking about this problem correctly, I understand why `cdylib` crates cause issues: DLLs/shared libraries, by nature, are loaded at runtime and don't have (don't *need*) prior knowledge of a `main` function. But, as it sits now, it appears that Cargo projects that can only build as `cdylibs` aren't able to be built by cargo-fuzz. (Please correct me if I am wrong) ## Possible Solution Would it be possible to modify the cargo-fuzz building routine to build & instrument DLLs *without* the `main` function? This would allow the DLL to be built and instrumented in the same way as the fuzzing targets, but it would then be up to the user as to where the DLL should be dropped, so it can be loaded during fuzzing. (Since the DLL would be built with Sanitizer Coverage instrumentation, LibFuzzer should still be able to detect code coverage changes when the fuzzing target loads it in at runtime and invokes the DLL's functions.) Perhaps something like this: ```rust if build.triple.contains("-msvc") && !build.crate_type.ne("cdylib") { // The entrypoint is in the bundled libfuzzer rlib, this gets the linker to find it. // (Do not do this if we're building a DLL; instead let it build & be instrumented without `main`) rustflags.push_str(" -Clink-arg=/include:main"); } ``` I've been testing this theory locally (modifying my local copy of cargo-fuzz's code by commenting out the `rustflags.push_str(" -Clink-arg=/include:main")` when building the DLL), and it's building successfully with instrumentation. After it's built, I drop it into a location where my fuzzing target can pick it up for loading, and when I run `cargo fuzz run my_fuzz_target`, LibFuzzer appears to be quickly discovering a set of cascading if-statements and a bug I inserted inside the DLL.
2024-10-16T17:58:54Z
0.12
2024-11-05T18:55:01Z
a608970259c3b0d575e70b0748c1c4cf79081031
[ "rustc_version::tests::test_parsing_future_stable", "rustc_version::tests::test_parsing_nightly", "rustc_version::tests::test_parsing_stable", "options::test::display_build_options", "help", "init_defines_correct_dependency", "init_finds_parent_project", "add_twice", "init_twice", "list", "tmin" ]
[]
[]
[]
auto_2025-06-12
rust-fuzz/cargo-fuzz
344
rust-fuzz__cargo-fuzz-344
[ "343" ]
abb7a67c5b2e1263c3e5c7abfa8c70bb4dec7796
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -126,6 +126,13 @@ pub struct BuildOptions { #[arg(long)] pub no_cfg_fuzzing: bool, + #[arg(skip = false)] + /// Add the 'cfg(fuzzing-repro)' compilation configuration. This build + /// option will be automatically used when running `cargo fuzz run <target> + /// <corpus>`. The option will not be shown to the user, which is ensured by + /// the `skip` attribute. + pub cfg_fuzzing_repro: bool, + #[arg(long)] /// Don't build with the `sanitizer-coverage-trace-compares` LLVM argument /// diff --git a/src/options/run.rs b/src/options/run.rs --- a/src/options/run.rs +++ b/src/options/run.rs @@ -37,6 +37,7 @@ pub struct Run { impl RunCommand for Run { fn run_command(&mut self) -> Result<()> { let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; + self.build.cfg_fuzzing_repro = !self.corpus.is_empty(); project.exec_fuzz(self) } } diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -177,6 +177,10 @@ impl FuzzProject { rustflags.push_str(" --cfg fuzzing"); } + if build.cfg_fuzzing_repro { + rustflags.push_str(" --cfg fuzzing_repro"); + } + if !build.strip_dead_code { rustflags.push_str(" -Clink-dead-code"); }
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -232,6 +239,7 @@ mod test { coverage: false, strip_dead_code: false, no_cfg_fuzzing: false, + cfg_fuzzing_repro: false, no_trace_compares: false, }; diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -175,6 +175,9 @@ fn run_no_crash() { use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { + #[cfg(fuzzing_repro)] + eprintln!("Reproducing a crash"); + run_no_crash::pass_fuzzing(data); }); "#, diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -188,7 +191,10 @@ fn run_no_crash() { .arg("--") .arg("-runs=1000") .assert() - .stderr(predicate::str::contains("Done 1000 runs")) + .stderr( + predicate::str::contains("Done 1000 runs") + .and(predicate::str::contains("Reproducing a crash").not()), + ) .success(); } diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -429,6 +435,9 @@ fn run_one_input() { use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { + #[cfg(fuzzing_repro)] + eprintln!("Reproducing a crash"); + assert!(data.is_empty()); }); "#, diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -444,9 +453,11 @@ fn run_one_input() { .arg(corpus.join("pass")) .assert() .stderr( - predicate::str::contains("Running 1 inputs 1 time(s) each.").and( - predicate::str::contains("Running: fuzz/corpus/run_one/pass"), - ), + predicate::str::contains("Running 1 inputs 1 time(s) each.") + .and(predicate::str::contains( + "Running: fuzz/corpus/run_one/pass", + )) + .and(predicate::str::contains("Reproducing a crash")), ) .success(); }
Detect when code is reproducing a crash vs when it is fuzzing Hi all, I have a lot of fun using `cargo fuzz` on my projects! It lowers the barrier enough that fuzzing becomes simple, so well done :+1: When I find a crash, I often need to debug it by adding extra `dbg!` or `eprintln!` calls to my code. Is there a way for me to leave this debug code in my fuzzer, but only activate it when I'm reproducing a crash? I saw the `#[cfg(fuzzing)]` flag, but it is enabled equally in both cases (as it should be since reproducing the crash could rely on it). I looked at the command line arguments, but the only difference seems to be if the last argument is a directory or not. When I run `cargo fuzz run backends_rust_generate` I see: ```rust [fuzz_targets/backends_rust_generate.rs:7] std::env::args().collect::<Vec<_>>() = [ "fuzz/target/x86_64-unknown-linux-gnu/release/backends_rust_generate", "-artifact_prefix=/home/mgeisler/src/pdl/fuzz/artifacts/backends_rust_generate/", "/home/mgeisler/src/pdl/fuzz/corpus/backends_rust_generate", ] ``` vs when reproducing a crash with `cargo fuzz run backends_rust_generate fuzz/artifacts/backends_rust_generate/crash-a3d9424297fe7b773102352b48b7bdd6b0457430`: ```rust [fuzz_targets/backends_rust_generate.rs:7] std::env::args().collect::<Vec<_>>() = [ "fuzz/target/x86_64-unknown-linux-gnu/release/backends_rust_generate", "-artifact_prefix=/home/mgeisler/src/pdl/fuzz/artifacts/backends_rust_generate/", "fuzz/artifacts/backends_rust_generate/crash-c9b96795bcb23158a324f38824d56e24f04b6426", ] ``` Ideally, there would be another `cfg` value I can use to completely compile away the debug prints when fuzzing. Does that exist?
I would be in support of a `cfg(fuzz_repro)` or something.
2023-06-16T13:28:04Z
0.11
2023-06-18T17:12:28Z
abb7a67c5b2e1263c3e5c7abfa8c70bb4dec7796
[ "options::test::display_build_options", "help", "init_finds_parent_project", "init_twice", "add_twice", "list", "tmin" ]
[]
[]
[]
auto_2025-06-12
rust-fuzz/cargo-fuzz
264
rust-fuzz__cargo-fuzz-264
[ "263" ]
2e496ca9cfe11de7cfb3d89b2299e93359ebc72f
diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -822,6 +830,10 @@ impl FuzzProject { targets: Vec::new(), }) } + + fn fuzz_dir_is_default_path(&self) -> bool { + self.fuzz_dir.ends_with(DEFAULT_FUZZ_DIR) + } } fn collect_targets(value: &toml::Value) -> Vec<String> {
diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -459,14 +459,22 @@ impl FuzzProject { eprintln!(); } + let fuzz_dir = if self.fuzz_dir_is_default_path() { + String::new() + } else { + format!(" --fuzz-dir {}", self.fuzz_dir().display()) + }; + eprintln!( - "Reproduce with:\n\n\tcargo fuzz run{options} {target} {artifact}\n", + "Reproduce with:\n\n\tcargo fuzz run{fuzz_dir}{options} {target} {artifact}\n", + fuzz_dir = &fuzz_dir, options = &run.build, target = &run.target, artifact = artifact.display() ); eprintln!( - "Minimize test case with:\n\n\tcargo fuzz tmin{options} {target} {artifact}\n", + "Minimize test case with:\n\n\tcargo fuzz tmin{fuzz_dir}{options} {target} {artifact}\n", + fuzz_dir = &fuzz_dir, options = &run.build, target = &run.target, artifact = artifact.display() diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -839,12 +839,11 @@ fn build_stripping_dead_code() { #[test] fn run_with_different_fuzz_dir() { - const FUZZ_DIR_NAME: &str = "dir_likes_to_move_it_move_it"; - - let next_root = next_root(); - let fuzz_dir = next_root.join(FUZZ_DIR_NAME); - - let project = project_with_params("project_likes_to_move_it", next_root, fuzz_dir.clone()) + let (fuzz_dir, mut project_builder) = project_with_fuzz_dir( + "project_likes_to_move_it", + Some("dir_likes_to_move_it_move_it"), + ); + let project = project_builder .with_fuzz() .fuzz_target( "you_like_to_move_it", diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -870,3 +869,56 @@ fn run_with_different_fuzz_dir() { .stderr(predicate::str::contains("Done 2 runs")) .success(); } + +#[test] +fn run_diagnostic_contains_fuzz_dir() { + let (fuzz_dir, mut project_builder) = project_with_fuzz_dir("run_with_crash", None); + let project = project_builder + .with_fuzz() + .fuzz_target( + "yes_crash", + r#" + #![no_main] + use libfuzzer_sys::fuzz_target; + + fuzz_target!(|data: &[u8]| { + run_with_crash::fail_fuzzing(data); + }); + "#, + ) + .build(); + + let run = format!( + "cargo fuzz run --fuzz-dir {} yes_crash custom_dir/artifacts/yes_crash", + &fuzz_dir + ); + + let tmin = format!( + "cargo fuzz tmin --fuzz-dir {} yes_crash custom_dir/artifacts/yes_crash", + &fuzz_dir + ); + + project + .cargo_fuzz() + .arg("run") + .arg("--fuzz-dir") + .arg(fuzz_dir) + .arg("yes_crash") + .arg("--") + .arg("-runs=1000") + .assert() + .stderr(predicates::str::contains(run).and(predicate::str::contains(tmin))) + .failure(); +} + +fn project_with_fuzz_dir( + project_name: &str, + fuzz_dir_opt: Option<&str>, +) -> (String, ProjectBuilder) { + let fuzz_dir = fuzz_dir_opt.unwrap_or("custom_dir"); + let next_root = next_root(); + let fuzz_dir_pb = next_root.join(fuzz_dir); + let fuzz_dir_sting = fuzz_dir_pb.display().to_string(); + let pb = project_with_params(project_name, next_root, fuzz_dir_pb); + (fuzz_dir_sting, pb) +}
[`fuzz run`] Bad discovered input should display custom fuzz dir Currently, when `fuzz run someTarget` discovers a bad input, it doesn't take into consideration custom `--fuzz-dir` directories. Actual: ``` RUST_BACKTRACE=1 cargo fuzz run --fuzz-dir someDirectory someTarget ... Reproduce with: cargo fuzz run someTarget someDirectory/artifacts/someTarget/crash-bleh-bleh-bleh Minimize test case with: cargo fuzz tmin someTarget someDirectory/artifacts/someTarget/crash-blah-blah-blah ``` Expected: ``` RUST_BACKTRACE=1 cargo fuzz run --fuzz-dir someDirectory someTarget ... Reproduce with: cargo fuzz run --fuzz-dir someDirectory someTarget someDirectory/artifacts/someTarget/crash-bleh-bleh-bleh Minimize test case with: cargo fuzz tmin --fuzz-dir someDirectory someTarget someDirectory/artifacts/someTarget/crash-blah-blah-blah ```
2021-05-23T01:27:42Z
0.10
2021-05-25T17:16:22Z
78965346c161a3800166c41304f61717e9d7e85c
[ "options::test::display_build_options", "help", "init_finds_parent_project", "init_twice", "add_twice", "list" ]
[]
[]
[]
auto_2025-06-12
rust-fuzz/cargo-fuzz
262
rust-fuzz__cargo-fuzz-262
[ "238" ]
089dfae55534ae29a6323b4e0368ae6ebe9b34f8
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -13,8 +13,8 @@ pub use self::{ run::Run, tmin::Tmin, }; -use std::fmt as stdfmt; use std::str::FromStr; +use std::{fmt as stdfmt, path::PathBuf}; use structopt::StructOpt; #[derive(Debug, Clone, Copy, PartialEq)] diff --git a/src/options/add.rs b/src/options/add.rs --- a/src/options/add.rs +++ b/src/options/add.rs @@ -1,16 +1,19 @@ -use crate::{project::FuzzProject, RunCommand}; +use crate::{options::FuzzDirWrapper, project::FuzzProject, RunCommand}; use anyhow::Result; use structopt::StructOpt; #[derive(Clone, Debug, StructOpt)] pub struct Add { + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, + /// Name of the new fuzz target pub target: String, } impl RunCommand for Add { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.add_target(self) } } diff --git a/src/options/build.rs b/src/options/build.rs --- a/src/options/build.rs +++ b/src/options/build.rs @@ -1,4 +1,8 @@ -use crate::{options::BuildOptions, project::FuzzProject, RunCommand}; +use crate::{ + options::{BuildOptions, FuzzDirWrapper}, + project::FuzzProject, + RunCommand, +}; use anyhow::Result; use structopt::StructOpt; diff --git a/src/options/build.rs b/src/options/build.rs --- a/src/options/build.rs +++ b/src/options/build.rs @@ -7,13 +11,16 @@ pub struct Build { #[structopt(flatten)] pub build: BuildOptions, + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, + /// Name of the fuzz target to build, or build all targets if not supplied pub target: Option<String>, } impl RunCommand for Build { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.exec_build(&self.build, self.target.as_deref().map(|s| s)) } } diff --git a/src/options/cmin.rs b/src/options/cmin.rs --- a/src/options/cmin.rs +++ b/src/options/cmin.rs @@ -1,4 +1,8 @@ -use crate::{options::BuildOptions, project::FuzzProject, RunCommand}; +use crate::{ + options::{BuildOptions, FuzzDirWrapper}, + project::FuzzProject, + RunCommand, +}; use anyhow::Result; use std::path::PathBuf; use structopt::StructOpt; diff --git a/src/options/cmin.rs b/src/options/cmin.rs --- a/src/options/cmin.rs +++ b/src/options/cmin.rs @@ -8,6 +12,9 @@ pub struct Cmin { #[structopt(flatten)] pub build: BuildOptions, + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, + /// Name of the fuzz target pub target: String, diff --git a/src/options/cmin.rs b/src/options/cmin.rs --- a/src/options/cmin.rs +++ b/src/options/cmin.rs @@ -22,7 +29,7 @@ pub struct Cmin { impl RunCommand for Cmin { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.exec_cmin(self) } } diff --git a/src/options/coverage.rs b/src/options/coverage.rs --- a/src/options/coverage.rs +++ b/src/options/coverage.rs @@ -1,4 +1,8 @@ -use crate::{options::BuildOptions, project::FuzzProject, RunCommand}; +use crate::{ + options::{BuildOptions, FuzzDirWrapper}, + project::FuzzProject, + RunCommand, +}; use anyhow::Result; use structopt::StructOpt; diff --git a/src/options/coverage.rs b/src/options/coverage.rs --- a/src/options/coverage.rs +++ b/src/options/coverage.rs @@ -7,6 +11,9 @@ pub struct Coverage { #[structopt(flatten)] pub build: BuildOptions, + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, + /// Name of the fuzz target pub target: String, diff --git a/src/options/coverage.rs b/src/options/coverage.rs --- a/src/options/coverage.rs +++ b/src/options/coverage.rs @@ -20,7 +27,7 @@ pub struct Coverage { impl RunCommand for Coverage { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; self.build.coverage = true; project.exec_coverage(self) } diff --git a/src/options/fmt.rs b/src/options/fmt.rs --- a/src/options/fmt.rs +++ b/src/options/fmt.rs @@ -1,4 +1,8 @@ -use crate::{options::BuildOptions, project::FuzzProject, RunCommand}; +use crate::{ + options::{BuildOptions, FuzzDirWrapper}, + project::FuzzProject, + RunCommand, +}; use anyhow::Result; use structopt::StructOpt; diff --git a/src/options/fmt.rs b/src/options/fmt.rs --- a/src/options/fmt.rs +++ b/src/options/fmt.rs @@ -9,6 +13,9 @@ pub struct Fmt { #[structopt(flatten)] pub build: BuildOptions, + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, + /// Name of fuzz target pub target: String, diff --git a/src/options/fmt.rs b/src/options/fmt.rs --- a/src/options/fmt.rs +++ b/src/options/fmt.rs @@ -18,7 +25,7 @@ pub struct Fmt { impl RunCommand for Fmt { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.debug_fmt_input(self) } } diff --git a/src/options/init.rs b/src/options/init.rs --- a/src/options/init.rs +++ b/src/options/init.rs @@ -1,4 +1,4 @@ -use crate::{project::FuzzProject, RunCommand}; +use crate::{options::FuzzDirWrapper, project::FuzzProject, RunCommand}; use anyhow::Result; use structopt::StructOpt; diff --git a/src/options/init.rs b/src/options/init.rs --- a/src/options/init.rs +++ b/src/options/init.rs @@ -12,11 +12,14 @@ pub struct Init { )] /// Name of the first fuzz target to create pub target: String, + + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, } impl RunCommand for Init { fn run_command(&mut self) -> Result<()> { - FuzzProject::init(self)?; + FuzzProject::init(self, self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; Ok(()) } } diff --git a/src/options/list.rs b/src/options/list.rs --- a/src/options/list.rs +++ b/src/options/list.rs @@ -1,13 +1,16 @@ -use crate::{project::FuzzProject, RunCommand}; +use crate::{options::FuzzDirWrapper, project::FuzzProject, RunCommand}; use anyhow::Result; use structopt::StructOpt; #[derive(Clone, Debug, StructOpt)] -pub struct List {} +pub struct List { + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, +} impl RunCommand for List { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.list_targets() } } diff --git a/src/options/run.rs b/src/options/run.rs --- a/src/options/run.rs +++ b/src/options/run.rs @@ -1,4 +1,8 @@ -use crate::{options::BuildOptions, project::FuzzProject, RunCommand}; +use crate::{ + options::{BuildOptions, FuzzDirWrapper}, + project::FuzzProject, + RunCommand, +}; use anyhow::Result; use structopt::StructOpt; diff --git a/src/options/run.rs b/src/options/run.rs --- a/src/options/run.rs +++ b/src/options/run.rs @@ -13,6 +17,9 @@ pub struct Run { /// Custom corpus directories or artifact files. pub corpus: Vec<String>, + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, + #[structopt( short = "j", long = "jobs", diff --git a/src/options/run.rs b/src/options/run.rs --- a/src/options/run.rs +++ b/src/options/run.rs @@ -33,7 +40,7 @@ pub struct Run { impl RunCommand for Run { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.exec_fuzz(self) } } diff --git a/src/options/tmin.rs b/src/options/tmin.rs --- a/src/options/tmin.rs +++ b/src/options/tmin.rs @@ -1,4 +1,8 @@ -use crate::{options::BuildOptions, project::FuzzProject, RunCommand}; +use crate::{ + options::{BuildOptions, FuzzDirWrapper}, + project::FuzzProject, + RunCommand, +}; use anyhow::Result; use std::path::PathBuf; use structopt::StructOpt; diff --git a/src/options/tmin.rs b/src/options/tmin.rs --- a/src/options/tmin.rs +++ b/src/options/tmin.rs @@ -8,6 +12,9 @@ pub struct Tmin { #[structopt(flatten)] pub build: BuildOptions, + #[structopt(flatten)] + pub fuzz_dir_wrapper: FuzzDirWrapper, + /// Name of the fuzz target pub target: String, diff --git a/src/options/tmin.rs b/src/options/tmin.rs --- a/src/options/tmin.rs +++ b/src/options/tmin.rs @@ -35,7 +42,7 @@ pub struct Tmin { impl RunCommand for Tmin { fn run_command(&mut self) -> Result<()> { - let project = FuzzProject::find_existing()?; + let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.exec_tmin(self) } } diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -11,22 +11,26 @@ use std::{ time, }; +const DEFAULT_FUZZ_DIR: &str = "fuzz"; + pub struct FuzzProject { - /// Path to the root cargo project - /// - /// Not the project with fuzz targets, but the project being fuzzed - root_project: PathBuf, + /// The project with fuzz targets + fuzz_dir: PathBuf, + /// The project being fuzzed + project_dir: PathBuf, targets: Vec<String>, } impl FuzzProject { + /// Creates a new instance. + // /// Find an existing `cargo fuzz` project by starting at the current /// directory and walking up the filesystem. - pub fn find_existing() -> Result<Self> { - let mut project = FuzzProject { - root_project: find_package()?, - targets: Vec::new(), - }; + /// + /// If `fuzz_dir_opt` is `None`, returns a new instance with the default fuzz project + /// path. + pub fn new(fuzz_dir_opt: Option<PathBuf>) -> Result<Self> { + let mut project = Self::manage_initial_instance(fuzz_dir_opt)?; let manifest = project.manifest()?; if !is_fuzz_manifest(&manifest) { bail!( diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -41,15 +45,13 @@ impl FuzzProject { Ok(project) } - /// Create the fuzz project structure + /// Creates the fuzz project structure and returns a new instance. /// - /// This will not clone libfuzzer-sys - pub fn init(init: &options::Init) -> Result<Self> { - let project = FuzzProject { - root_project: find_package()?, - targets: Vec::new(), - }; - let fuzz_project = project.path(); + /// This will not clone libfuzzer-sys. + /// Similar to `FuzzProject::new`, the fuzz directory will depend on `fuzz_dir_opt`. + pub fn init(init: &options::Init, fuzz_dir_opt: Option<PathBuf>) -> Result<Self> { + let project = Self::manage_initial_instance(fuzz_dir_opt)?; + let fuzz_project = project.fuzz_dir(); let root_project_name = project.root_project_name()?; // TODO: check if the project is already initialized diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -568,7 +570,7 @@ impl FuzzProject { .ok_or_else(|| anyhow!("corpus must be valid unicode"))? .to_owned(); - let tmp = tempfile::TempDir::new_in(self.path())?; + let tmp = tempfile::TempDir::new_in(self.fuzz_dir())?; let tmp_corpus = tmp.path().join("corpus"); fs::create_dir(&tmp_corpus)?; diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -704,17 +706,17 @@ impl FuzzProject { } } - fn path(&self) -> PathBuf { - self.root_project.join("fuzz") + fn fuzz_dir(&self) -> &Path { + &self.fuzz_dir } fn manifest_path(&self) -> PathBuf { - self.path().join("Cargo.toml") + self.fuzz_dir().join("Cargo.toml") } /// Returns paths to the `coverage/<target>/raw` directory and `coverage/<target>/coverage.profdata` file. fn coverage_for(&self, target: &str) -> Result<(PathBuf, PathBuf)> { - let mut coverage_data = self.path(); + let mut coverage_data = self.fuzz_dir().to_owned(); coverage_data.push("coverage"); coverage_data.push(target); let mut coverage_raw = coverage_data.clone(); diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -727,7 +729,7 @@ impl FuzzProject { } fn corpus_for(&self, target: &str) -> Result<PathBuf> { - let mut p = self.path(); + let mut p = self.fuzz_dir().to_owned(); p.push("corpus"); p.push(target); fs::create_dir_all(&p) diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -736,7 +738,7 @@ impl FuzzProject { } fn artifacts_for(&self, target: &str) -> Result<PathBuf> { - let mut p = self.path(); + let mut p = self.fuzz_dir().to_owned(); p.push("artifacts"); p.push(target); diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -751,7 +753,7 @@ impl FuzzProject { } fn fuzz_targets_dir(&self) -> PathBuf { - let mut root = self.path(); + let mut root = self.fuzz_dir().to_owned(); if root.join(crate::FUZZ_TARGETS_DIR_OLD).exists() { println!( "warning: The `fuzz/fuzzers/` directory has renamed to `fuzz/fuzz_targets/`. \ diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -787,7 +789,7 @@ impl FuzzProject { } fn root_project_name(&self) -> Result<String> { - let filename = self.root_project.join("Cargo.toml"); + let filename = self.project_dir.join("Cargo.toml"); let mut file = fs::File::open(&filename)?; let mut data = Vec::new(); file.read_to_end(&mut data)?; diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -804,6 +806,22 @@ impl FuzzProject { bail!("{} (package.name) is malformed", filename.display()); } } + + // If `fuzz_dir_opt` is `None`, returns a new instance with the default fuzz project + // path. Otherwise, returns a new instance with the inner content of `fuzz_dir_opt`. + fn manage_initial_instance(fuzz_dir_opt: Option<PathBuf>) -> Result<Self> { + let project_dir = find_package()?; + let fuzz_dir = if let Some(el) = fuzz_dir_opt { + el + } else { + project_dir.join(DEFAULT_FUZZ_DIR) + }; + Ok(FuzzProject { + fuzz_dir, + project_dir, + targets: Vec::new(), + }) + } } fn collect_targets(value: &toml::Value) -> Vec<String> {
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -186,6 +186,23 @@ impl stdfmt::Display for BuildOptions { } } +#[derive(Clone, Debug, StructOpt, PartialEq)] +pub struct FuzzDirWrapper { + /// The path to the fuzz project directory. + #[structopt(long = "fuzz-dir")] + pub fuzz_dir: Option<PathBuf>, +} + +impl stdfmt::Display for FuzzDirWrapper { + fn fmt(&self, f: &mut stdfmt::Formatter) -> stdfmt::Result { + if let Some(ref elem) = self.fuzz_dir { + write!(f, " --fuzz-dir={}", elem.display())?; + } + + Ok(()) + } +} + #[cfg(test)] mod test { use super::*; diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -836,3 +836,37 @@ fn build_stripping_dead_code() { let a_bin = build_dir.join("build_strip_a"); assert!(a_bin.is_file(), "Not a file: {}", a_bin.display()); } + +#[test] +fn run_with_different_fuzz_dir() { + const FUZZ_DIR_NAME: &str = "dir_likes_to_move_it_move_it"; + + let next_root = next_root(); + let fuzz_dir = next_root.join(FUZZ_DIR_NAME); + + let project = project_with_params("project_likes_to_move_it", next_root, fuzz_dir.clone()) + .with_fuzz() + .fuzz_target( + "you_like_to_move_it", + r#" + #![no_main] + use libfuzzer_sys::fuzz_target; + + fuzz_target!(|_data: &[u8]| { + }); + "#, + ) + .build(); + + project + .cargo_fuzz() + .arg("run") + .arg("--fuzz-dir") + .arg(fuzz_dir) + .arg("you_like_to_move_it") + .arg("--") + .arg("-runs=1") + .assert() + .stderr(predicate::str::contains("Done 2 runs")) + .success(); +} diff --git a/tests/tests/project.rs b/tests/tests/project.rs --- a/tests/tests/project.rs +++ b/tests/tests/project.rs @@ -25,12 +25,17 @@ pub fn next_root() -> PathBuf { } pub fn project(name: &str) -> ProjectBuilder { - ProjectBuilder::new(name, next_root()) + ProjectBuilder::new(name, next_root(), None) +} + +pub fn project_with_params(name: &str, root: PathBuf, fuzz_dir: PathBuf) -> ProjectBuilder { + ProjectBuilder::new(name, root, Some(fuzz_dir)) } pub struct Project { name: String, root: PathBuf, + fuzz_dir: PathBuf, } pub struct ProjectBuilder { diff --git a/tests/tests/project.rs b/tests/tests/project.rs --- a/tests/tests/project.rs +++ b/tests/tests/project.rs @@ -40,14 +45,16 @@ pub struct ProjectBuilder { } impl ProjectBuilder { - pub fn new(name: &str, root: PathBuf) -> ProjectBuilder { + pub fn new(name: &str, root: PathBuf, fuzz_dir_opt: Option<PathBuf>) -> ProjectBuilder { println!(" ============ {} =============== ", root.display()); drop(fs::remove_dir_all(&root)); fs::create_dir_all(&root).unwrap(); + let fuzz_dir = fuzz_dir_opt.unwrap_or_else(|| root.join("fuzz")); ProjectBuilder { project: Project { name: name.to_string(), root, + fuzz_dir, }, saw_manifest: false, saw_main_or_lib: false, diff --git a/tests/tests/project.rs b/tests/tests/project.rs --- a/tests/tests/project.rs +++ b/tests/tests/project.rs @@ -60,7 +67,7 @@ impl ProjectBuilder { pub fn with_fuzz(&mut self) -> &mut Self { self.file( - Path::new("fuzz").join("Cargo.toml"), + self.project.fuzz_dir.join("Cargo.toml"), &format!( r#" [package] diff --git a/tests/tests/project.rs b/tests/tests/project.rs --- a/tests/tests/project.rs +++ b/tests/tests/project.rs @@ -93,7 +100,7 @@ impl ProjectBuilder { let mut fuzz_cargo_toml = fs::OpenOptions::new() .write(true) .append(true) - .open(self.project.fuzz_dir().join("Cargo.toml")) + .open(self.project.fuzz_dir.join("Cargo.toml")) .unwrap(); write!( &mut fuzz_cargo_toml, diff --git a/tests/tests/project.rs b/tests/tests/project.rs --- a/tests/tests/project.rs +++ b/tests/tests/project.rs @@ -168,6 +175,7 @@ impl ProjectBuilder { self.default_src_lib(); } Project { + fuzz_dir: self.project.fuzz_dir.clone(), name: self.project.name.clone(), root: self.project.root.clone(), } diff --git a/tests/tests/project.rs b/tests/tests/project.rs --- a/tests/tests/project.rs +++ b/tests/tests/project.rs @@ -200,16 +208,16 @@ impl Project { .unwrap() } - pub fn fuzz_dir(&self) -> PathBuf { - self.root().join("fuzz") + pub fn fuzz_dir(&self) -> &Path { + &self.fuzz_dir } pub fn fuzz_cargo_toml(&self) -> PathBuf { - self.root().join("fuzz").join("Cargo.toml") + self.fuzz_dir.join("Cargo.toml") } pub fn fuzz_targets_dir(&self) -> PathBuf { - self.root().join("fuzz").join("fuzz_targets") + self.fuzz_dir.join("fuzz_targets") } pub fn fuzz_target_path(&self, target: &str) -> PathBuf { diff --git a/tests/tests/project.rs b/tests/tests/project.rs --- a/tests/tests/project.rs +++ b/tests/tests/project.rs @@ -219,7 +227,7 @@ impl Project { } pub fn fuzz_coverage_dir(&self, target: &str) -> PathBuf { - self.fuzz_dir().join("coverage").join(target) + self.fuzz_dir.join("coverage").join(target) } pub fn cargo_fuzz(&self) -> Command {
Support for non-standard project directories `fuzz` is currently the only possible directory name and it would be nice to have something like `cargo fuzz run --path some_fuzz_project_dir someTarget`
That the directory containing the fuzzing code _has to be_ called "fuzz" (and cannot be renamed nor moved deeper in the directory structure) is a limitation that is not documented anywhere. Is there a reason for it?
2021-05-08T19:52:56Z
0.10
2021-05-13T17:23:13Z
78965346c161a3800166c41304f61717e9d7e85c
[ "options::test::display_build_options", "help", "init_finds_parent_project", "list", "init_twice", "add_twice" ]
[]
[]
[]
auto_2025-06-12
rust-fuzz/cargo-fuzz
234
rust-fuzz__cargo-fuzz-234
[ "228" ]
9f2f36888d10504f0a219bf1a91b72837d9fba56
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -15,7 +15,7 @@ use std::fmt as stdfmt; use std::str::FromStr; use structopt::StructOpt; -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq)] pub enum Sanitizer { Address, Leak, diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -55,7 +55,7 @@ impl FromStr for Sanitizer { } } -#[derive(Clone, Debug, StructOpt)] +#[derive(Clone, Debug, StructOpt, PartialEq)] pub struct BuildOptions { #[structopt(short = "D", long = "dev", conflicts_with = "release")] /// Build artifacts in development mode, without optimizations
diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -110,3 +110,125 @@ pub struct BuildOptions { /// Unstable (nightly-only) flags to Cargo pub unstable_flags: Vec<String>, } + +impl stdfmt::Display for BuildOptions { + fn fmt(&self, f: &mut stdfmt::Formatter) -> stdfmt::Result { + if self.dev { + write!(f, " -D")?; + } + + if self.release { + write!(f, " -O")?; + } + + if self.debug_assertions { + write!(f, " -a")?; + } + + if self.verbose { + write!(f, " -v")?; + } + + if self.no_default_features { + write!(f, " --no-default-features")?; + } + + if self.all_features { + write!(f, " --all-features")?; + } + + if let Some(feature) = &self.features { + write!(f, " --features={}", feature)?; + } + + match self.sanitizer { + Sanitizer::None => write!(f, " --sanitizer=none")?, + Sanitizer::Address => {} + _ => write!(f, " --sanitizer={}", self.sanitizer)?, + } + + if self.triple != crate::utils::default_target() { + write!(f, " --target={}", self.triple)?; + } + + for flag in &self.unstable_flags { + write!(f, " -Z{}", flag)?; + } + + Ok(()) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn display_build_options() { + let default_opts = BuildOptions { + dev: false, + release: false, + debug_assertions: false, + verbose: false, + no_default_features: false, + all_features: false, + features: None, + sanitizer: Sanitizer::Address, + triple: String::from(crate::utils::default_target()), + unstable_flags: Vec::new(), + }; + + let opts = vec![ + default_opts.clone(), + BuildOptions { + dev: true, + ..default_opts.clone() + }, + BuildOptions { + release: true, + ..default_opts.clone() + }, + BuildOptions { + debug_assertions: true, + ..default_opts.clone() + }, + BuildOptions { + verbose: true, + ..default_opts.clone() + }, + BuildOptions { + no_default_features: true, + ..default_opts.clone() + }, + BuildOptions { + all_features: true, + ..default_opts.clone() + }, + BuildOptions { + features: Some(String::from("features")), + ..default_opts.clone() + }, + BuildOptions { + sanitizer: Sanitizer::None, + ..default_opts.clone() + }, + BuildOptions { + triple: String::from("custom_triple"), + ..default_opts.clone() + }, + BuildOptions { + unstable_flags: vec![String::from("unstable"), String::from("flags")], + ..default_opts + }, + ]; + + for case in opts { + assert_eq!( + case, + BuildOptions::from_clap( + &BuildOptions::clap().get_matches_from(case.to_string().split(' ')) + ) + ); + } + } +} diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -433,12 +433,14 @@ impl FuzzProject { } eprintln!( - "Reproduce with:\n\n\tcargo fuzz run {target} {artifact}\n", + "Reproduce with:\n\n\tcargo fuzz run{options} {target} {artifact}\n", + options = &run.build, target = &run.target, artifact = artifact.display() ); eprintln!( - "Minimize test case with:\n\n\tcargo fuzz tmin {target} {artifact}\n", + "Minimize test case with:\n\n\tcargo fuzz tmin{options} {target} {artifact}\n", + options = &run.build, target = &run.target, artifact = artifact.display() ); diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -356,9 +356,19 @@ fn run_with_msan_with_crash() { .arg("--") .arg("-runs=1000") .assert() - .stderr(predicate::str::contains( - "MemorySanitizer: use-of-uninitialized-value", - )) + .stderr( + predicate::str::contains("MemorySanitizer: use-of-uninitialized-value") + .and(predicate::str::contains( + "Reproduce with:\n\ + \n\ + \tcargo fuzz run --sanitizer=memory msan_with_crash fuzz/artifacts/msan_with_crash/crash-", + )) + .and(predicate::str::contains( + "Minimize test case with:\n\ + \n\ + \tcargo fuzz tmin --sanitizer=memory msan_with_crash fuzz/artifacts/msan_with_crash/crash-", + )), + ) .failure(); }
Recommended reproduction command ignores arguments When running the fuzzer with specific sanitizer, time or memory settings and an issue is found then the output for reproduction is not complete. In particular the recommended command line for reproducing the issue misses any of these parameters as well as the used `cargo` version. Abbreviated example below. ```sh $ cargo +nightly fuzz run some_fuzzer -sanitizer=memory # ... SUMMARY: MemorySanitizer: use-of-uninitialized-value (...) Exiting # ... Reproduce with: cargo fuzz run some_fuzzer fuzz/artifacts/parser/crash-hash ``` When it should instead print: ```sh Reproduce with: cargo +nightly fuzz run some_fuzzer -sanitizer=memory fuzz/artifacts/parser/crash-hash ```
Thanks for reporting! Here's the code that needs to change: https://github.com/rust-fuzz/cargo-fuzz/blob/2fb3bd85c0dd57ea7f3d5c29174c26a5550d0aa8/src/project.rs#L426-L436 We need to incorporate [the arguments](https://github.com/rust-fuzz/cargo-fuzz/blob/2fb3bd85c0dd57ea7f3d5c29174c26a5550d0aa8/src/options/run.rs#L30-L32) into the output. > Thanks for reporting! Here's the code that needs to change: > > https://github.com/rust-fuzz/cargo-fuzz/blob/2fb3bd85c0dd57ea7f3d5c29174c26a5550d0aa8/src/project.rs#L426-L436 > > We need to incorporate [the arguments](https://github.com/rust-fuzz/cargo-fuzz/blob/2fb3bd85c0dd57ea7f3d5c29174c26a5550d0aa8/src/options/run.rs#L30-L32) into the output. I think the things we actually need here are from the `BuildOptions`. `args` holds things like `-runs` but not which sanitizers were used. Unsure so far how to get the `+nightly` bit, I'll take a closer look at that tomorrow. `+nightly` comes from `rustup` wrapper, so I suspect its going to be out-of-scope for `cargo-fuzz`. But we can probably add a note to that effect? Like "note: if you're using rustup, you may need to specify `+nightly` to the cargo command". That's probably the easiest way to do it. Alternatively it looks like when you call `rustup +toolchain <...>` it sets the `RUSTUP_TOOLCHAIN` variable based on what your override was. I don't see that documented though so maybe we don't want to depend on that.
2020-07-02T12:19:45Z
0.8
2020-07-06T18:55:01Z
9f2f36888d10504f0a219bf1a91b72837d9fba56
[ "help", "init_finds_parent_project", "add_twice", "init_twice", "list" ]
[]
[]
[]
auto_2025-06-12
rust-fuzz/cargo-fuzz
231
rust-fuzz__cargo-fuzz-231
[ "230" ]
87c36a1deee8ca9b550fe034623a7445d7e8c770
diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -40,7 +40,11 @@ fuzz/fuzz_targets/, i.e. the name picked when running `cargo fuzz add`. This will run the script inside the fuzz target with varying inputs until it finds a crash, at which point it will save the crash input to the artifact directory, print some output, and exit. Unless you configure it otherwise (see -libFuzzer options below), this will run indefinitely."; +libFuzzer options below), this will run indefinitely. + +By default fuzz targets are built with optimizations equivalent to +`cargo build --release`, but with debug assertions and overflow checks enabled. +Address Sanitizer is also enabled by default."; const RUN_AFTER_HELP: &'static str = "\ diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -68,6 +72,17 @@ include: http://llvm.org/docs/LibFuzzer.html#dictionaries\ "; +const BUILD_BEFORE_HELP: &'static str = "\ +By default fuzz targets are built with optimizations equivalent to +`cargo build --release`, but with debug assertions and overflow checks enabled. +Address Sanitizer is also enabled by default."; + +const BUILD_AFTER_HELP: &'static str = "\ +Sanitizers perform checks necessary for detecting bugs in unsafe code +at the cost of some performance. For more information on sanitizers see +https://doc.rust-lang.org/unstable-book/compiler-flags/sanitizer.html\ +"; + /// A trait for running our various commands. trait RunCommand { /// Run this command! diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -94,6 +109,11 @@ enum Command { /// Add a new fuzz target Add(options::Add), + #[structopt( + template(LONG_ABOUT_TEMPLATE), + before_help(BUILD_BEFORE_HELP), + after_help(BUILD_AFTER_HELP) + )] /// Build fuzz targets Build(options::Build), diff --git a/src/options.rs b/src/options.rs --- a/src/options.rs +++ b/src/options.rs @@ -57,18 +57,22 @@ impl FromStr for Sanitizer { #[derive(Clone, Debug, StructOpt)] pub struct BuildOptions { - #[structopt(short = "O", long = "release")] + #[structopt(short = "D", long = "dev", conflicts_with = "release")] + /// Build artifacts in development mode, without optimizations + pub dev: bool, + + #[structopt(short = "O", long = "release", conflicts_with = "dev")] /// Build artifacts in release mode, with optimizations pub release: bool, + #[structopt(short = "a", long = "debug-assertions")] + /// Build artifacts with debug assertions and overflow checks enabled (default if not -O) + pub debug_assertions: bool, + /// Build target with verbose output from `cargo build` #[structopt(short = "v", long = "verbose")] pub verbose: bool, - #[structopt(short = "a", long = "debug-assertions")] - /// Build artifacts with debug assertions enabled (default if not -O) - pub debug_assertions: bool, - #[structopt(long = "no-default-features")] /// Build artifacts with default Cargo features disabled pub no_default_features: bool, diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -133,7 +133,8 @@ impl FuzzProject { // --target=<TARGET> won't pass rustflags to build scripts .arg("--target") .arg(&build.triple); - if build.release { + // we default to release mode unless debug mode is explicitly requested + if !build.dev { cmd.arg("--release"); } if build.verbose { diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -170,7 +171,7 @@ impl FuzzProject { if build.triple.contains("-linux-") { rustflags.push_str(" -Cllvm-args=-sanitizer-coverage-stack-depth"); } - if build.debug_assertions { + if !build.release || build.debug_assertions { rustflags.push_str(" -Cdebug-assertions"); }
diff --git a/src/project.rs b/src/project.rs --- a/src/project.rs +++ b/src/project.rs @@ -182,7 +183,7 @@ impl FuzzProject { // performance, we're taking a huge hit relative to actual release mode. // Local tests have once showed this to be a ~3x faster runtime where // otherwise functions like `Vec::as_ptr` aren't inlined. - if build.release { + if !build.dev { rustflags.push_str(" -C codegen-units=1"); } diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -578,7 +578,7 @@ fn build_all() { // `fuzz_build_dir()` won't panic. project.cargo_fuzz().arg("build").assert().success(); - let build_dir = project.fuzz_build_dir().join("debug"); + let build_dir = project.fuzz_build_dir().join("release"); let a_bin = build_dir.join("build_all_a"); let b_bin = build_dir.join("build_all_b"); diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -619,7 +619,7 @@ fn build_one() { // `fuzz_build_dir()` won't panic. project.cargo_fuzz().arg("build").assert().success(); - let build_dir = project.fuzz_build_dir().join("debug"); + let build_dir = project.fuzz_build_dir().join("release"); let a_bin = build_dir.join("build_one_a"); let b_bin = build_dir.join("build_one_b"); diff --git a/tests/tests/main.rs b/tests/tests/main.rs --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -641,3 +641,54 @@ fn build_one() { assert!(a_bin.is_file()); assert!(!b_bin.is_file()); } + +#[test] +fn build_dev() { + let project = project("build_dev").with_fuzz().build(); + + // Create some targets. + project + .cargo_fuzz() + .arg("add") + .arg("build_dev_a") + .assert() + .success(); + project + .cargo_fuzz() + .arg("add") + .arg("build_dev_b") + .assert() + .success(); + + // Build to ensure that the build directory is created and + // `fuzz_build_dir()` won't panic. + project + .cargo_fuzz() + .arg("build") + .arg("--dev") + .assert() + .success(); + + let build_dir = project.fuzz_build_dir().join("debug"); + + let a_bin = build_dir.join("build_dev_a"); + let b_bin = build_dir.join("build_dev_b"); + + // Remove the files we just built. + fs::remove_file(&a_bin).unwrap(); + fs::remove_file(&b_bin).unwrap(); + + assert!(!a_bin.is_file()); + assert!(!b_bin.is_file()); + + // Test that building all fuzz targets does in fact recreate the files. + project + .cargo_fuzz() + .arg("build") + .arg("--dev") + .assert() + .success(); + + assert!(a_bin.is_file()); + assert!(b_bin.is_file()); +}
Fuzzing with default settings is much slower than it needs to be `cargo fuzz run` currently defaults to debug mode with Address Sanitizer. Debug mode in Rust is needlessly slow, easily 20x slower than release mode, and for fuzzing performance is critical. It would be a much better idea to default to release mode, but with debug assertions and overflow checks enabled. The only reason to invoke actual debug mode is when reproducing the testcase and actually trying to debug it. So it'd be nice to add a flag `--debug` that forces debug mode and print it in the crash output, but this should be a non-breaking change in all other respects.
For reference, AFL already defaults to release mode with overflow checks and debug assertions: https://github.com/rust-fuzz/afl.rs/blob/d156adfb072aad655342a1a04cdbe4d9ac2ffc9e/src/bin/cargo-afl.rs#L294
2020-06-20T21:45:55Z
0.7
2020-11-11T18:48:06Z
87c36a1deee8ca9b550fe034623a7445d7e8c770
[ "help", "init_finds_parent_project", "add_twice", "init_twice", "list" ]
[]
[]
[]
auto_2025-06-12
rust-lang/chalk
75
rust-lang__chalk-75
[ "74" ]
f4f9dfa86c497aa222864fd6abc9e955ca23ce80
diff --git a/chalk-parse/src/ast.rs b/chalk-parse/src/ast.rs --- a/chalk-parse/src/ast.rs +++ b/chalk-parse/src/ast.rs @@ -177,6 +177,7 @@ pub struct Identifier { pub enum WhereClause { Implemented { trait_ref: TraitRef }, + Normalize { projection: ProjectionTy, ty: Ty }, ProjectionEq { projection: ProjectionTy, ty: Ty }, TyWellFormed { ty: Ty }, TraitRefWellFormed { trait_ref: TraitRef }, diff --git a/chalk-parse/src/parser.lalrpop b/chalk-parse/src/parser.lalrpop --- a/chalk-parse/src/parser.lalrpop +++ b/chalk-parse/src/parser.lalrpop @@ -32,6 +32,7 @@ Goal1: Box<Goal> = { <i:IfKeyword> "(" <w:Comma<WhereClause>> ")" "{" <g:Goal> "}" => Box::new(Goal::Implies(w, g, i)), "not" "{" <g:Goal> "}" => Box::new(Goal::Not(g)), <w:WhereClause> => Box::new(Goal::Leaf(w)), + "(" <Goal> ")", }; IfKeyword: bool = { diff --git a/chalk-parse/src/parser.lalrpop b/chalk-parse/src/parser.lalrpop --- a/chalk-parse/src/parser.lalrpop +++ b/chalk-parse/src/parser.lalrpop @@ -194,7 +195,10 @@ WhereClause: WhereClause = { <a:Lifetime> "=" <b:Lifetime> => WhereClause::UnifyLifetimes { a, b }, - // `T: Foo<U = Bar>` -- a normalization + // `<T as Foo>::U -> Bar` -- a normalization + "Normalize" "(" <s:ProjectionTy> "->" <t:Ty> ")" => WhereClause::Normalize { projection: s, ty: t }, + + // `T: Foo<U = Bar>` -- projection equality <s:Ty> ":" <t:Id> "<" <a:(<Comma<Parameter>> ",")?> <name:Id> <a2:Angle<Parameter>> "=" <ty:Ty> ">" => { diff --git a/src/cast.rs b/src/cast.rs --- a/src/cast.rs +++ b/src/cast.rs @@ -75,6 +75,18 @@ impl Cast<LeafGoal> for Normalize { } } +impl Cast<DomainGoal> for ProjectionEq { + fn cast(self) -> DomainGoal { + DomainGoal::ProjectionEq(self) + } +} + +impl Cast<LeafGoal> for ProjectionEq { + fn cast(self) -> LeafGoal { + LeafGoal::DomainGoal(self.cast()) + } +} + impl Cast<DomainGoal> for UnselectedNormalize { fn cast(self) -> DomainGoal { DomainGoal::UnselectedNormalize(self) diff --git a/src/cast.rs b/src/cast.rs --- a/src/cast.rs +++ b/src/cast.rs @@ -113,6 +125,13 @@ impl Cast<Goal> for Normalize { } } +impl Cast<Goal> for ProjectionEq { + fn cast(self) -> Goal { + let wcg: LeafGoal = self.cast(); + wcg.cast() + } +} + impl Cast<Goal> for UnselectedNormalize { fn cast(self) -> Goal { let wcg: LeafGoal = self.cast(); diff --git a/src/cast.rs b/src/cast.rs --- a/src/cast.rs +++ b/src/cast.rs @@ -156,6 +175,12 @@ impl Cast<Ty> for ApplicationTy { } } +impl Cast<Ty> for ProjectionTy { + fn cast(self) -> Ty { + Ty::Projection(self) + } +} + impl Cast<Parameter> for Ty { fn cast(self) -> Parameter { ParameterKind::Ty(self) diff --git a/src/coherence/solve.rs b/src/coherence/solve.rs --- a/src/coherence/solve.rs +++ b/src/coherence/solve.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use fold::shift::Shift; use itertools::Itertools; use errors::*; use ir::*; diff --git a/src/fold/mod.rs b/src/fold/mod.rs --- a/src/fold/mod.rs +++ b/src/fold/mod.rs @@ -6,12 +6,9 @@ use ir::*; use std::fmt::Debug; use std::sync::Arc; -mod shifted; -mod shifter; +crate mod shift; mod subst; -pub use self::shifted::Shifted; -pub use self::shifter::Shifter; pub use self::subst::Subst; /// A "folder" is a transformer that can be used to make a copy of diff --git a/src/fold/mod.rs b/src/fold/mod.rs --- a/src/fold/mod.rs +++ b/src/fold/mod.rs @@ -413,7 +410,7 @@ macro_rules! enum_fold { enum_fold!(PolarizedTraitRef[] { Positive(a), Negative(a) }); enum_fold!(ParameterKind[T,L] { Ty(a), Lifetime(a) } where T: Fold, L: Fold); -enum_fold!(DomainGoal[] { Implemented(a), Normalize(a), UnselectedNormalize(a), WellFormed(a), InScope(a) }); +enum_fold!(DomainGoal[] { Implemented(a), ProjectionEq(a), Normalize(a), UnselectedNormalize(a), WellFormed(a), InScope(a) }); enum_fold!(WellFormed[] { Ty(a), TraitRef(a) }); enum_fold!(LeafGoal[] { EqGoal(a), DomainGoal(a) }); enum_fold!(Constraint[] { LifetimeEq(a, b) }); diff --git a/src/fold/mod.rs b/src/fold/mod.rs --- a/src/fold/mod.rs +++ b/src/fold/mod.rs @@ -449,6 +446,7 @@ struct_fold!(TraitRef { parameters, }); struct_fold!(Normalize { projection, ty }); +struct_fold!(ProjectionEq { projection, ty }); struct_fold!(UnselectedNormalize { projection, ty }); struct_fold!(AssociatedTyValue { associated_ty_id, diff --git /dev/null b/src/fold/shift.rs new file mode 100644 --- /dev/null +++ b/src/fold/shift.rs @@ -0,0 +1,146 @@ +use fallible::*; +use ir::*; +use super::{DefaultTypeFolder, ExistentialFolder, Fold, IdentityUniversalFolder}; + +/// Methods for converting debruijn indices to move values into or out +/// of binders. +pub trait Shift: Fold { + /// Shifts debruijn indices in `self` **up**, which is used when a + /// value is being placed under additional levels of binders. + /// + /// For example, if we had some goal + /// like: + /// + /// ```notrust + /// T: Trait<?X> + /// ``` + /// + /// where `?X` refers to some inference variable (and hence has depth 3), + /// we might use `up_shift` when constructing a goal like: + /// + /// ```notrust + /// exists<U> { T = U, T: Trait<?X> } + /// ``` + /// + /// This is because, internally, the inference variable `?X` (as + /// well as the new quantified variable `U`) are going to be + /// represented by debruijn indices. So if the index of `X` is + /// zero, then while originally we might have had `T: Trait<?0>`, + /// inside the `exists` we want to represent `X` with `?1`, to + /// account for the binder: + /// + /// ```notrust + /// exists { T = ?0, T: Trait<?1> } + /// ^^ ^^ refers to `?X` + /// refers to `U` + /// ``` + fn up_shift(&self, adjustment: usize) -> Self::Result; + + /// Shifts debruijn indices in `self` **down**, hence **removing** + /// a value from binders. This will fail with `Err(NoSolution)` in + /// the case that the value refers to something from one of those + /// binders. + /// + /// Consider the final example from `up_shift`: + /// + /// ```notrust + /// exists { T = ?0, T: Trait<?1> } + /// ^^ ^^ refers to `?X` + /// refers to `U` + /// ``` + /// + /// If we `down_shift` the `T: Trait<?1>` goal by 1, + /// we will get `T: Trait<?0>`, which is what we started with. + /// In other words, we will have extracted it from the `exists` + /// binder. + /// + /// But if we try to `down_shift` the `T = ?0` goal by 1, we will + /// get `Err`, because it refers to the type bound by the + /// `exists`. + fn down_shift(&self, adjustment: usize) -> Fallible<Self::Result>; +} + +impl<T: Fold> Shift for T { + fn up_shift(&self, adjustment: usize) -> T::Result { + self.fold_with(&mut Shifter { adjustment }, 0).unwrap() + } + + fn down_shift(&self, adjustment: usize) -> Fallible<T::Result> { + self.fold_with(&mut DownShifter { adjustment }, 0) + } +} + +/// A folder that adjusts debruijn indices by a certain amount. +/// +struct Shifter { + adjustment: usize, +} + +impl Shifter { + /// Given a free variable at `depth`, shifts that depth to `depth + /// + self.adjustment`, and then wraps *that* within the internal + /// set `binders`. + fn adjust(&self, depth: usize, binders: usize) -> usize { + depth + self.adjustment + binders + } +} + +impl DefaultTypeFolder for Shifter {} + +impl ExistentialFolder for Shifter { + fn fold_free_existential_ty(&mut self, depth: usize, binders: usize) -> Fallible<Ty> { + Ok(Ty::Var(self.adjust(depth, binders))) + } + + fn fold_free_existential_lifetime( + &mut self, + depth: usize, + binders: usize, + ) -> Fallible<Lifetime> { + Ok(Lifetime::Var(self.adjust(depth, binders))) + } +} + +impl IdentityUniversalFolder for Shifter {} + +//--------------------------------------------------------------------------- + +/// A shifter that reduces debruijn indices -- in other words, which lifts a value +/// *out* from binders. Consider this example: +/// +struct DownShifter { + adjustment: usize, +} + +impl DownShifter { + /// Given a reference to a free variable at depth `depth` (appearing within `binders` internal + /// binders), attempts to lift that free variable out from `adjustment` levels of binders + /// (i.e., convert it to depth `depth - self.adjustment`). If the free variable is bound + /// by one of those internal binders (i.e., `depth < self.adjustment`) the this will + /// fail with `Err`. Otherwise, returns the variable at this new depth (but adjusted to + /// appear within `binders`). + fn adjust(&self, depth: usize, binders: usize) -> Fallible<usize> { + match depth.checked_sub(self.adjustment) { + Some(new_depth) => Ok(new_depth + binders), + None => Err(NoSolution), + } + } +} + +impl DefaultTypeFolder for DownShifter {} + +impl ExistentialFolder for DownShifter { + fn fold_free_existential_ty(&mut self, depth: usize, binders: usize) -> Fallible<Ty> { + Ok(Ty::Var(self.adjust(depth, binders)?)) + } + + fn fold_free_existential_lifetime( + &mut self, + depth: usize, + binders: usize, + ) -> Fallible<Lifetime> { + Ok(Lifetime::Var(self.adjust(depth, binders)?)) + } +} + +impl IdentityUniversalFolder for DownShifter {} diff --git a/src/fold/shifted.rs /dev/null --- a/src/fold/shifted.rs +++ /dev/null @@ -1,38 +0,0 @@ -use fallible::*; -use fold::{Fold, Folder}; -use fold::shifter::Shifter; - -/// Sometimes we wish to fold two values with a distinct deBruijn -/// depth (i.e., you want to fold `(A, B)` where A is defined under N -/// binders, and B under N+K). In that case, you can fold -/// `(Shifted::new(K, A), B)`, and we will map a var of 0 in A to a -/// var of K. This only makes sense if the first N binders of both A -/// and B are the same binders, of course. -#[derive(Debug)] -pub struct Shifted<T: Fold> { - adjustment: usize, - value: T, -} - -impl<T: Fold> Shifted<T> { - pub fn new(adjustment: usize, value: T) -> Self { - Shifted { adjustment, value } - } -} - -impl<T: Fold<Result = T>> Fold for Shifted<T> { - type Result = T; - - fn fold_with(&self, folder: &mut Folder, binders: usize) -> Fallible<Self::Result> { - // I... think this is right if binders is not zero, but not sure, - // and don't care to think about it. - assert_eq!(binders, 0); - - // First up-shift any variables. i.e., if `self.value` - // contains a free var with index 0, and `self.adjustment == - // 2`, we will translate it to a free var with index 2; then - // we will fold *that* through `folder`. - let value = self.value.fold_with(&mut Shifter::new(self.adjustment), 0)?; - value.fold_with(folder, binders) - } -} diff --git a/src/fold/shifter.rs /dev/null --- a/src/fold/shifter.rs +++ /dev/null @@ -1,79 +0,0 @@ -use fallible::*; -use ir::*; -use super::{DefaultTypeFolder, ExistentialFolder, Fold, IdentityUniversalFolder}; - -/// A folder that adjusts debruijn indices by a certain amount. -/// -/// Typically, `up_shift` is used when inserting some term T under a -/// binder (or multiple binders). So for example if we had some goal -/// like `T: Trait<?X>`, where `?X` refers to an inference variable, -/// but we wanted to construct a goal like `exists<U> { T = U, T: -/// Trait<?X> }`, we might use `up_shift`. This is because, -/// internally, the inference variable `?X` (as well as the new -/// quantified variable `U`) are going to be represented by debruijn -/// indices. So if the index of `X` is zero, then while originally we -/// might have had `T: Trait<?0>`, inside the `exists` we want to -/// represent `X` with `?1`, to account for the binder: -/// -/// ```notrust -/// exists { T = ?0, T: Trait<?1> } -/// ^^ ^^ refers to `?X` -/// refers to `U` -/// ``` -pub struct Shifter { - adjustment: usize, -} - -impl Shifter { - pub fn new(adjustment: usize) -> Shifter { - Shifter { adjustment } - } - - pub fn up_shift<T: Fold>(adjustment: usize, value: &T) -> T::Result { - value.fold_with(&mut Shifter::new(adjustment), 0).unwrap() - } - - fn adjust(&self, depth: usize, binders: usize) -> usize { - depth + binders + self.adjustment - } -} - -macro_rules! shift_method { - ($t:ty) => { - impl $t { - /// See `Shifter`. - pub fn up_shift(&self, adjustment: usize) -> Self { - if adjustment == 0 { - self.clone() - } else { - Shifter::up_shift(adjustment, self) - } - } - } - } -} - -shift_method!(Ty); -shift_method!(Parameter); -shift_method!(Lifetime); -shift_method!(TraitRef); -shift_method!(ProjectionTy); -shift_method!(DomainGoal); - -impl DefaultTypeFolder for Shifter {} - -impl ExistentialFolder for Shifter { - fn fold_free_existential_ty(&mut self, depth: usize, binders: usize) -> Fallible<Ty> { - Ok(Ty::Var(self.adjust(depth, binders))) - } - - fn fold_free_existential_lifetime( - &mut self, - depth: usize, - binders: usize, - ) -> Fallible<Lifetime> { - Ok(Lifetime::Var(self.adjust(depth, binders))) - } -} - -impl IdentityUniversalFolder for Shifter {} diff --git a/src/fold/subst.rs b/src/fold/subst.rs --- a/src/fold/subst.rs +++ b/src/fold/subst.rs @@ -1,3 +1,4 @@ +use fold::shift::Shift; use ir::*; use super::*; diff --git a/src/ir/debug.rs b/src/ir/debug.rs --- a/src/ir/debug.rs +++ b/src/ir/debug.rs @@ -152,13 +152,19 @@ impl<'a, T: Debug> Debug for Angle<'a, T> { impl Debug for Normalize { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { - write!(fmt, "{:?} ==> {:?}", self.projection, self.ty) + write!(fmt, "Normalize({:?} -> {:?})", self.projection, self.ty) + } +} + +impl Debug for ProjectionEq { + fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { + write!(fmt, "ProjectionEq({:?} = {:?})", self.projection, self.ty) } } impl Debug for UnselectedNormalize { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { - write!(fmt, "{:?} ==> {:?}", self.projection, self.ty) + write!(fmt, "UnselectedNormalize({:?} -> {:?})", self.projection, self.ty) } } diff --git a/src/ir/debug.rs b/src/ir/debug.rs --- a/src/ir/debug.rs +++ b/src/ir/debug.rs @@ -166,10 +172,11 @@ impl Debug for DomainGoal { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { match *self { DomainGoal::Normalize(ref n) => write!(fmt, "{:?}", n), + DomainGoal::ProjectionEq(ref n) => write!(fmt, "{:?}", n), DomainGoal::UnselectedNormalize(ref n) => write!(fmt, "{:?}", n), DomainGoal::Implemented(ref n) => write!( fmt, - "{:?}: {:?}{:?}", + "({:?}: {:?}{:?})", n.parameters[0], n.trait_id, Angle(&n.parameters[1..]) diff --git a/src/ir/mod.rs b/src/ir/mod.rs --- a/src/ir/mod.rs +++ b/src/ir/mod.rs @@ -2,6 +2,7 @@ use cast::Cast; use chalk_parse::ast; use fallible::*; use fold::{DefaultTypeFolder, ExistentialFolder, Fold, IdentityUniversalFolder}; +use fold::shift::Shift; use lalrpop_intern::InternedString; use solve::infer::var::InferenceVariable; use std::collections::{BTreeMap, HashMap, HashSet}; diff --git a/src/ir/mod.rs b/src/ir/mod.rs --- a/src/ir/mod.rs +++ b/src/ir/mod.rs @@ -477,6 +478,7 @@ impl PolarizedTraitRef { #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum DomainGoal { Implemented(TraitRef), + ProjectionEq(ProjectionEq), Normalize(Normalize), UnselectedNormalize(UnselectedNormalize), WellFormed(WellFormed), diff --git a/src/ir/mod.rs b/src/ir/mod.rs --- a/src/ir/mod.rs +++ b/src/ir/mod.rs @@ -495,25 +497,25 @@ impl DomainGoal { }, binders: vec![], }, - fallback_clause: false, } } /// A clause of the form (T: Foo) expands to (T: Foo), WF(T: Foo). - /// A clause of the form (T: Foo<Item = U>) expands to (T: Foo<Item = U>), WF(T: Foo). + /// A clause of the form (T: Foo<Item = U>) expands to (T: Foo<Item = U>), T: Foo, WF(T: Foo). pub fn expanded(self, program: &Program) -> impl Iterator<Item = DomainGoal> { let mut expanded = vec![]; match self { DomainGoal::Implemented(ref trait_ref) => { expanded.push(WellFormed::TraitRef(trait_ref.clone()).cast()) } - DomainGoal::Normalize(Normalize { ref projection, .. }) => { + DomainGoal::ProjectionEq(ProjectionEq { ref projection, .. }) => { let (associated_ty_data, trait_params, _) = program.split_projection(&projection); let trait_ref = TraitRef { trait_id: associated_ty_data.trait_id, parameters: trait_params.to_owned(), }; - expanded.push(WellFormed::TraitRef(trait_ref).cast()); + expanded.push(WellFormed::TraitRef(trait_ref.clone()).cast()); + expanded.push(trait_ref.cast()); } _ => (), }; diff --git a/src/ir/mod.rs b/src/ir/mod.rs --- a/src/ir/mod.rs +++ b/src/ir/mod.rs @@ -543,28 +545,41 @@ pub enum WellFormed { TraitRef(TraitRef), } +/// Proves that the given projection **normalizes** to the given +/// type. A projection `T::Foo` normalizes to the type `U` if we can +/// **match it to an impl** and that impl has a `type Foo = V` where +/// `U = V`. #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Normalize { pub projection: ProjectionTy, pub ty: Ty, } +/// Proves **equality** between a projection `T::Foo` and a type +/// `U`. Equality can be proven via normalization, but we can also +/// prove that `T::Foo = V::Foo` if `T = V` without normalizing. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ProjectionEq { + pub projection: ProjectionTy, + pub ty: Ty, +} + /// Indicates that the trait where the associated type belongs to is /// not yet known, i.e. is unselected. For example, a normal -/// `Normalize` would be of the form `<Vec<T> as Iterator>::Item ==> +/// `Normalize` would be of the form `<Vec<T> as Iterator>::Item -> /// T`. When `Iterator` is in scope, and it is the only trait in scope /// with an associated type `Item`, it suffices to write /// `Vec<T>::Item` instead of `<Vec<T> as Iterator>::Item`. The -/// corresponding `UnselectedNormalize` is `Vec<T>::Item ==> T`. +/// corresponding `UnselectedNormalize` is `Vec<T>::Item -> T`. /// /// For each associated type we encounter in an `impl`, we generate /// rules to derive an `UnselectedNormalize` from a `Normalize`. For /// example, implementing `Iterator` for `Vec<T>` yields the rule: /// /// ```text -/// Vec<T>::Item ==> T :- +/// Vec<T>::Item -> T :- /// InScope(Iterator), -/// <Vec<T> as Iterator>::Item ==> T +/// <Vec<T> as Iterator>::Item -> T /// ``` #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct UnselectedNormalize { diff --git a/src/ir/mod.rs b/src/ir/mod.rs --- a/src/ir/mod.rs +++ b/src/ir/mod.rs @@ -605,9 +620,6 @@ impl<T> Binders<T> { #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ProgramClause { pub implication: Binders<ProgramClauseImplication>, - - /// Is this a fallback clause which should get lower priority? - pub fallback_clause: bool, } /// Represents one clause of the form `consequence :- conditions` where diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -5,6 +5,7 @@ use lalrpop_intern::intern; use cast::{Cast, Caster}; use errors::*; +use fold::shift::Shift; use ir; use solve::SolverChoice; diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -429,6 +430,13 @@ impl LowerWhereClause<ir::DomainGoal> for WhereClause { WhereClause::ProjectionEq { ref projection, ref ty, + } => ir::DomainGoal::ProjectionEq(ir::ProjectionEq { + projection: projection.lower(env)?, + ty: ty.lower(env)?, + }), + WhereClause::Normalize { + ref projection, + ref ty, } => ir::DomainGoal::Normalize(ir::Normalize { projection: projection.lower(env)?, ty: ty.lower(env)?, diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -463,7 +471,9 @@ impl LowerWhereClause<ir::DomainGoal> for WhereClause { impl LowerWhereClause<ir::LeafGoal> for WhereClause { fn lower(&self, env: &Env) -> Result<ir::LeafGoal> { Ok(match *self { - WhereClause::Implemented { .. } | WhereClause::ProjectionEq { .. } => { + WhereClause::Implemented { .. } + | WhereClause::ProjectionEq { .. } + | WhereClause::Normalize { .. } => { let g: ir::DomainGoal = self.lower(env)?; g.cast() } diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -814,7 +824,6 @@ impl LowerClause for Clause { Ok(ir::ProgramClause { implication, - fallback_clause: false, }) } } diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1039,7 +1048,6 @@ impl ir::ImplDatum { .collect(), } }), - fallback_clause: false, } } } diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1085,7 +1093,6 @@ impl ir::DefaultImplDatum { }, } }), - fallback_clause: false, } } } diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1176,7 +1183,6 @@ impl ir::AssociatedTyValue { conditions: conditions.clone(), }, }, - fallback_clause: false, }; let unselected_projection = ir::UnselectedProjectionTy { diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1200,7 +1206,6 @@ impl ir::AssociatedTyValue { ], }, }, - fallback_clause: false, }; vec![normalization, unselected_normalization] diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1272,7 +1277,6 @@ impl ir::StructDatum { }, } }), - fallback_clause: false, }; vec![wf] diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1326,7 +1330,6 @@ impl ir::TraitDatum { }, } }), - fallback_clause: false, }; let mut clauses = vec![clauses]; diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1338,7 +1341,6 @@ impl ir::TraitDatum { conditions: vec![wf.clone().cast()], } }), - fallback_clause: false, }); } diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1348,9 +1350,9 @@ impl ir::TraitDatum { impl ir::AssociatedTyDatum { fn to_program_clauses(&self, program: &ir::Program) -> Vec<ir::ProgramClause> { - // For each associated type, we define a normalization "fallback" for - // projecting when we don't have constraints to say anything interesting - // about an associated type. + // For each associated type, we define the "projection + // equality" rules. There are always two; one for a successful normalization, + // and one for the "fallback" notion of equality. // // Given: // diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1358,10 +1360,33 @@ impl ir::AssociatedTyDatum { // type Assoc; // } // - // we generate: + // we generate the 'fallback' rule: // - // <?T as Foo>::Assoc ==> (Foo::Assoc)<?T> :- (?T: Foo) - // forall<U> { (?T: Foo) :- <?T as Foo>::Assoc ==> U } + // forall<T> { + // ProjectionEq(<T as Foo>::Assoc = (Foo::Assoc)<T>) :- + // T: Foo + // } + // + // and + // + // forall<T> { + // ProjectionEq(<T as Foo>::Assoc = U) :- + // Normalize(<T as Foo>::Assoc -> U) + // } + // + // We used to generate an "elaboration" rule like this: + // + // forall<T> { + // T: Foo :- + // exists<U> { ProjectionEq(<T as Foo>::Assoc = U) } + // } + // + // but this caused problems with the recursive solver. In + // particular, whenever normalization is possible, we cannot + // solve that projection uniquely, since we can now elaborate + // `ProjectionEq` to fallback *or* normalize it. So instead we + // handle this kind of reasoning by expanding "projection + // equality" predicates (see `DomainGoal::expanded`). let binders: Vec<_> = self.parameter_kinds .iter() diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1382,33 +1407,42 @@ impl ir::AssociatedTyDatum { } }; - let fallback = { + // forall<T> { + // ProjectionEq(<T as Foo>::Assoc = (Foo::Assoc)<T>) :- + // T: Foo + // } + let fallback_clause = { // Construct an application from the projection. So if we have `<T as Iterator>::Item`, // we would produce `(Iterator::Item)<T>`. let app = ir::ApplicationTy { name: ir::TypeName::AssociatedType(self.id), - parameters, + parameters, }; - let ty = ir::Ty::Apply(app); + let app_ty = ir::Ty::Apply(app); ir::ProgramClause { implication: ir::Binders { binders: binders.clone(), value: ir::ProgramClauseImplication { - consequence: ir::Normalize { + consequence: ir::ProjectionEq { projection: projection.clone(), - ty, + ty: app_ty, }.cast(), - conditions: vec![trait_ref.clone().cast()], + conditions: vec![ + trait_ref.cast(), + ], }, }, - fallback_clause: true, } }; - let elaborate = { + // forall<T> { + // ProjectionEq(<T as Foo>::Assoc = U) :- + // Normalize(<T as Foo>::Assoc -> U) + // } + let normalize_clause = { // add new type parameter U - let mut binders = binders; + let mut binders = binders.clone(); binders.push(ir::ParameterKind::Ty(())); let ty = ir::Ty::Var(binders.len() - 1); diff --git a/src/lower/mod.rs b/src/lower/mod.rs --- a/src/lower/mod.rs +++ b/src/lower/mod.rs @@ -1416,14 +1450,21 @@ impl ir::AssociatedTyDatum { implication: ir::Binders { binders, value: ir::ProgramClauseImplication { - consequence: trait_ref.cast(), - conditions: vec![ir::Normalize { projection, ty }.cast()], + consequence: ir::ProjectionEq { + projection: projection.clone(), + ty: ty.clone(), + }.cast(), + conditions: vec![ + ir::Normalize { + projection: projection.clone(), + ty, + }.cast() + ], }, }, - fallback_clause: false, } }; - vec![fallback, elaborate] + vec![fallback_clause, normalize_clause] } } diff --git a/src/macros.rs b/src/macros.rs --- a/src/macros.rs +++ b/src/macros.rs @@ -3,7 +3,20 @@ use std::cell::RefCell; lazy_static! { pub static ref DEBUG_ENABLED: bool = { use std::env; - env::var("CHALK_DEBUG").is_ok() + env::var("CHALK_DEBUG") + .ok() + .and_then(|s| s.parse::<u32>().ok()) + .map(|x| x >= 2) + .unwrap_or(false) + }; + + pub static ref INFO_ENABLED: bool = { + use std::env; + env::var("CHALK_DEBUG") + .ok() + .and_then(|s| s.parse::<u32>().ok()) + .map(|x| x >= 1) + .unwrap_or(false) }; } diff --git a/src/macros.rs b/src/macros.rs --- a/src/macros.rs +++ b/src/macros.rs @@ -19,7 +32,7 @@ const OVERFLOW_DEPTH: usize = 100; macro_rules! debug { ($($t:tt)*) => { if *::macros::DEBUG_ENABLED { - ::macros::dump(&format!($($t)*)); + ::macros::dump(&format!($($t)*), ""); } } } diff --git a/src/macros.rs b/src/macros.rs --- a/src/macros.rs +++ b/src/macros.rs @@ -28,19 +41,36 @@ macro_rules! debug_heading { ($($t:tt)*) => { let _ = &if *::macros::DEBUG_ENABLED { let string = format!($($t)*); - ::macros::dump(&string); - ::macros::Indent::new(string) + ::macros::dump(&string, " {"); + ::macros::Indent::new(true, string) } else { - ::macros::Indent::new(String::new()) + ::macros::Indent::new(false, String::new()) }; } } -pub fn dump(string: &str) { - if !*DEBUG_ENABLED { - return; +#[allow(unused_macros)] +macro_rules! info { + ($($t:tt)*) => { + if *::macros::INFO_ENABLED { + ::macros::dump(&format!($($t)*), ""); + } + } +} + +macro_rules! info_heading { + ($($t:tt)*) => { + let _ = &if *::macros::INFO_ENABLED { + let string = format!($($t)*); + ::macros::dump(&string, " {"); + ::macros::Indent::new(true, string) + } else { + ::macros::Indent::new(false, String::new()) + }; } +} +pub fn dump(string: &str, suffix: &str) { let indent = ::macros::INDENT.with(|i| i.borrow().len()); let mut first = true; for line in string.lines() { diff --git a/src/macros.rs b/src/macros.rs --- a/src/macros.rs +++ b/src/macros.rs @@ -49,22 +79,25 @@ pub fn dump(string: &str) { eprint!("| "); } } else { + eprintln!(); for _ in 0..indent { eprint!(" "); } } - eprintln!("{}", line); + eprint!("{}", line); first = false; } + + eprintln!("{}", suffix); } pub struct Indent { - _dummy: (), + enabled: bool, } impl Indent { - pub fn new(value: String) -> Self { - if *DEBUG_ENABLED { + pub fn new(enabled: bool, value: String) -> Self { + if enabled { INDENT.with(|i| { i.borrow_mut().push(value); if i.borrow().len() > OVERFLOW_DEPTH { diff --git a/src/macros.rs b/src/macros.rs --- a/src/macros.rs +++ b/src/macros.rs @@ -76,14 +109,15 @@ impl Indent { } }); } - Indent { _dummy: () } + Indent { enabled } } } impl Drop for Indent { fn drop(&mut self) { - if *DEBUG_ENABLED { + if self.enabled { INDENT.with(|i| i.borrow_mut().pop().unwrap()); + ::macros::dump("}", ""); } } } diff --git a/src/solve/infer/canonicalize.rs b/src/solve/infer/canonicalize.rs --- a/src/solve/infer/canonicalize.rs +++ b/src/solve/infer/canonicalize.rs @@ -1,5 +1,6 @@ use fallible::*; use fold::{DefaultTypeFolder, ExistentialFolder, Fold, UniversalFolder}; +use fold::shift::Shift; use ir::*; use std::cmp::max; diff --git a/src/solve/infer/invert.rs b/src/solve/infer/invert.rs --- a/src/solve/infer/invert.rs +++ b/src/solve/infer/invert.rs @@ -1,5 +1,6 @@ use fallible::*; use fold::{DefaultTypeFolder, ExistentialFolder, Fold, UniversalFolder}; +use fold::shift::Shift; use ir::*; use std::collections::HashMap; diff --git a/src/solve/infer/mod.rs b/src/solve/infer/mod.rs --- a/src/solve/infer/mod.rs +++ b/src/solve/infer/mod.rs @@ -1,5 +1,6 @@ use ena::unify as ena; use ir::*; +use fold::shift::Shift; pub mod canonicalize; pub mod ucanonicalize; diff --git a/src/solve/infer/normalize_deep.rs b/src/solve/infer/normalize_deep.rs --- a/src/solve/infer/normalize_deep.rs +++ b/src/solve/infer/normalize_deep.rs @@ -1,5 +1,6 @@ use fallible::*; use fold::{DefaultTypeFolder, ExistentialFolder, Fold, IdentityUniversalFolder}; +use fold::shift::Shift; use ir::*; use super::{InferenceTable, InferenceVariable}; diff --git a/src/solve/infer/unify.rs b/src/solve/infer/unify.rs --- a/src/solve/infer/unify.rs +++ b/src/solve/infer/unify.rs @@ -137,8 +137,7 @@ impl<'t> Unifier<'t> { Zip::zip_with(self, &apply1.parameters, &apply2.parameters) } - (proj1 @ &Ty::Projection(_), proj2 @ &Ty::Projection(_)) - | (proj1 @ &Ty::Projection(_), proj2 @ &Ty::UnselectedProjection(_)) + (proj1 @ &Ty::Projection(_), proj2 @ &Ty::UnselectedProjection(_)) | (proj1 @ &Ty::UnselectedProjection(_), proj2 @ &Ty::Projection(_)) | (proj1 @ &Ty::UnselectedProjection(_), proj2 @ &Ty::UnselectedProjection(_)) => { self.unify_projection_tys( diff --git a/src/solve/infer/unify.rs b/src/solve/infer/unify.rs --- a/src/solve/infer/unify.rs +++ b/src/solve/infer/unify.rs @@ -150,6 +149,7 @@ impl<'t> Unifier<'t> { (ty @ &Ty::Apply(_), &Ty::Projection(ref proj)) | (ty @ &Ty::ForAll(_), &Ty::Projection(ref proj)) | (ty @ &Ty::Var(_), &Ty::Projection(ref proj)) + | (&Ty::Projection(ref proj), ty @ &Ty::Projection(_)) | (&Ty::Projection(ref proj), ty @ &Ty::Apply(_)) | (&Ty::Projection(ref proj), ty @ &Ty::ForAll(_)) | (&Ty::Projection(ref proj), ty @ &Ty::Var(_)) => self.unify_projection_ty(proj, ty), diff --git a/src/solve/infer/unify.rs b/src/solve/infer/unify.rs --- a/src/solve/infer/unify.rs +++ b/src/solve/infer/unify.rs @@ -217,7 +217,7 @@ impl<'t> Unifier<'t> { fn unify_projection_ty(&mut self, proj: &ProjectionTy, ty: &Ty) -> Fallible<()> { Ok(self.goals.push(InEnvironment::new( self.environment, - Normalize { + ProjectionEq { projection: proj.clone(), ty: ty.clone(), }.cast(), diff --git a/src/solve/infer/unify.rs b/src/solve/infer/unify.rs --- a/src/solve/infer/unify.rs +++ b/src/solve/infer/unify.rs @@ -343,23 +343,11 @@ impl<'t> Zipper for Unifier<'t> { self.unify_lifetime_lifetime(a, b) } - fn zip_binders<T>(&mut self, a: &Binders<T>, b: &Binders<T>) -> Fallible<()> + fn zip_binders<T>(&mut self, _: &Binders<T>, _: &Binders<T>) -> Fallible<()> where T: Zip + Fold<Result = T>, { - { - let a = &self.table.instantiate_binders_universally(a); - let b = &self.table.instantiate_binders_existentially(b); - let () = self.sub_unify(a, b)?; - } - - { - let b = &self.table.instantiate_binders_universally(b); - let a = &self.table.instantiate_binders_existentially(a); - let () = self.sub_unify(a, b)?; - } - - Ok(()) + panic!("cannot unify things with binders (other than types)") } } diff --git a/src/solve/recursive/mod.rs b/src/solve/recursive/mod.rs --- a/src/solve/recursive/mod.rs +++ b/src/solve/recursive/mod.rs @@ -111,7 +111,7 @@ impl Solver { goal: UCanonical<InEnvironment<Goal>>, minimums: &mut Minimums, ) -> Fallible<Solution> { - debug_heading!("solve_goal({:?})", goal); + info_heading!("solve_goal({:?})", goal); // First check the cache. if let Some(value) = self.cache.get(&goal) { diff --git a/src/solve/recursive/mod.rs b/src/solve/recursive/mod.rs --- a/src/solve/recursive/mod.rs +++ b/src/solve/recursive/mod.rs @@ -148,7 +148,7 @@ impl Solver { // Return the solution from the table. let previous_solution = self.search_graph[dfn].solution.clone(); debug!( - "solve_reduced_goal: cycle detected, previous solution {:?}", + "solve_goal: cycle detected, previous solution {:?}", previous_solution ); previous_solution diff --git a/src/solve/recursive/mod.rs b/src/solve/recursive/mod.rs --- a/src/solve/recursive/mod.rs +++ b/src/solve/recursive/mod.rs @@ -182,6 +182,10 @@ impl Solver { } } + debug!( + "solve_goal: solution = {:?}", + result, + ); result } } diff --git a/src/solve/recursive/mod.rs b/src/solve/recursive/mod.rs --- a/src/solve/recursive/mod.rs +++ b/src/solve/recursive/mod.rs @@ -192,6 +196,13 @@ impl Solver { depth: StackDepth, dfn: DepthFirstNumber, ) -> Minimums { + debug_heading!( + "solve_new_subgoal(canonical_goal={:?}, depth={:?}, dfn={:?})", + canonical_goal, + depth, + dfn, + ); + // We start with `answer = None` and try to solve the goal. At the end of the iteration, // `answer` will be updated with the result of the solving process. If we detect a cycle // during the solving process, we cache `answer` and try to solve the goal again. We repeat diff --git a/src/solve/recursive/mod.rs b/src/solve/recursive/mod.rs --- a/src/solve/recursive/mod.rs +++ b/src/solve/recursive/mod.rs @@ -231,36 +242,35 @@ impl Solver { // clauses. We try each approach in turn: let InEnvironment { environment, goal } = &canonical_goal.canonical.value; - let env_clauses = environment - .clauses - .iter() - .filter(|&clause| clause.could_match(goal)) - .cloned() - .map(DomainGoal::into_program_clause); - let env_solution = - self.solve_from_clauses(&canonical_goal, env_clauses, minimums); - - let prog_clauses: Vec<_> = self.program - .program_clauses - .iter() - .filter(|clause| !clause.fallback_clause) - .filter(|&clause| clause.could_match(goal)) - .cloned() - .collect(); - let prog_solution = - self.solve_from_clauses(&canonical_goal, prog_clauses, minimums); - - // These fallback clauses are used when we're sure we'll never - // reach Unique via another route - let fallback: Vec<_> = self.program - .program_clauses - .iter() - .filter(|clause| clause.fallback_clause) - .filter(|&clause| clause.could_match(goal)) - .cloned() - .collect(); - let fallback_solution = - self.solve_from_clauses(&canonical_goal, fallback, minimums); + let env_solution = { + debug_heading!( + "env_clauses" + ); + + let env_clauses = environment + .clauses + .iter() + .filter(|&clause| clause.could_match(goal)) + .cloned() + .map(DomainGoal::into_program_clause); + self.solve_from_clauses(&canonical_goal, env_clauses, minimums) + }; + debug!("env_solution={:?}", env_solution); + + let prog_solution = { + debug_heading!( + "prog_clauses" + ); + + let prog_clauses: Vec<_> = self.program + .program_clauses + .iter() + .filter(|&clause| clause.could_match(goal)) + .cloned() + .collect(); + self.solve_from_clauses(&canonical_goal, prog_clauses, minimums) + }; + debug!("prog_solution={:?}", prog_solution); // Now that we have all the outcomes, we attempt to combine // them. Here, we apply a heuristic (also found in rustc): if we diff --git a/src/solve/recursive/mod.rs b/src/solve/recursive/mod.rs --- a/src/solve/recursive/mod.rs +++ b/src/solve/recursive/mod.rs @@ -269,12 +279,7 @@ impl Solver { // inference. The idea is that the assumptions you've explicitly // made in a given context are more likely to be relevant than // general `impl`s. - - env_solution - .merge_with(prog_solution, |env, prog| env.favor_over(prog)) - .merge_with(fallback_solution, |merged, fallback| { - merged.fallback_to(fallback) - }) + env_solution.merge_with(prog_solution, |env, prog| env.favor_over(prog)) } goal => { diff --git a/src/solve/recursive/mod.rs b/src/solve/recursive/mod.rs --- a/src/solve/recursive/mod.rs +++ b/src/solve/recursive/mod.rs @@ -381,8 +386,10 @@ impl Solver { clause: Binders<ProgramClauseImplication>, minimums: &mut Minimums, ) -> Fallible<Solution> { - debug_heading!( - "solve_via_implication(canonical_goal={:?}, clause={:?})", + info_heading!( + "solve_via_implication(\ + \n canonical_goal={:?},\ + \n clause={:?})", canonical_goal, clause ); diff --git a/src/solve/slg/mod.rs b/src/solve/slg/mod.rs --- a/src/solve/slg/mod.rs +++ b/src/solve/slg/mod.rs @@ -277,13 +277,44 @@ enum TruthValue { Unknown, } +/// A link between two tables, indicating that when an answer is +/// produced by one table, it should be fed into another table. +/// For example, if we have a clause like +/// +/// ```notrust +/// foo(?X) :- bar(?X), baz(?X) +/// ``` +/// +/// then `foo` might insert a `PendingExClause` into the table for +/// `bar`, indicating that each value of `?X` could lead to an answer +/// for `foo` (if `baz(?X)` is true). #[derive(Clone, Debug)] struct PendingExClause { + /// The `goal_depth` in the stack of `foo`, the blocked goal. + /// Note that `foo` must always be in the stack, since it is + /// actively awaiting an answer. goal_depth: StackIndex, + + /// Answer substitution that the pending ex-clause carries along + /// with it. Maps from the free variables in the table goal to the + /// final values they wind up with. subst: Substitution, + + /// The goal `bar(?X)` that `foo(?X)` was trying to solve; + /// typically equal to the table-goal in which this pending + /// ex-clause is contained, modulo the ordering of variables. This + /// is not *always* true, however, because the table goal may have + /// been truncated. selected_goal: InEnvironment<Goal>, + + /// Any delayed literals in the ex-clause we were solving + /// when we blocked on `bar`. delayed_literals: Vec<DelayedLiteral>, + + /// Constraints accumulated thus far in the ex-clause we were solving. constraints: Vec<InEnvironment<Constraint>>, + + /// Further subgoals, like `baz(?X)`, that must be solved after `foo`. subgoals: Vec<Literal>, } diff --git a/src/solve/slg/mod.rs b/src/solve/slg/mod.rs --- a/src/solve/slg/mod.rs +++ b/src/solve/slg/mod.rs @@ -702,7 +733,7 @@ impl Forest { mut ex_clause: ExClause, // Contains both A and G together. minimums: &mut Minimums, ) -> ExplorationResult { - debug_heading!( + info_heading!( "new_clause(goal_depth={:?}, ex_clause={:?}, minimums={:?}", goal_depth, self.infer.normalize_deep(&ex_clause), diff --git a/src/solve/slg/mod.rs b/src/solve/slg/mod.rs --- a/src/solve/slg/mod.rs +++ b/src/solve/slg/mod.rs @@ -1181,7 +1212,7 @@ impl Forest { ex_clause: ExClause, // Contains both A and G together. minimums: &mut Minimums, ) -> ExplorationResult { - debug_heading!( + info_heading!( "answer(goal_depth={:?}, ex_clause={:?}, minimums={:?})", goal_depth, self.infer.normalize_deep(&ex_clause), diff --git a/src/solve/slg/mod.rs b/src/solve/slg/mod.rs --- a/src/solve/slg/mod.rs +++ b/src/solve/slg/mod.rs @@ -1400,7 +1431,7 @@ impl Forest { completed_goal_depth: StackIndex, minimums: &mut Minimums, ) -> ExplorationResult { - debug_heading!( + info_heading!( "complete(completed_goal_depth={:?}, minimums={:?})", completed_goal_depth, minimums diff --git a/src/solve/slg/mod.rs b/src/solve/slg/mod.rs --- a/src/solve/slg/mod.rs +++ b/src/solve/slg/mod.rs @@ -1451,7 +1482,7 @@ impl Forest { completed_goal_depth: StackIndex, minimums: &mut Minimums, ) -> ExplorationResult { - debug!( + info!( "complete_pop(completed_goal_depth={:?}, minimums={:?}", completed_goal_depth, minimums diff --git a/src/solve/slg/mod.rs b/src/solve/slg/mod.rs --- a/src/solve/slg/mod.rs +++ b/src/solve/slg/mod.rs @@ -1549,7 +1580,7 @@ impl Forest { completed_goal_depth: StackIndex, minimums: &mut Minimums, ) -> ExplorationResult { - debug!( + info!( "complete_delay(completed_goal_depth={:?}, minimums={:?}", completed_goal_depth, minimums diff --git a/src/solve/slg/mod.rs b/src/solve/slg/mod.rs --- a/src/solve/slg/mod.rs +++ b/src/solve/slg/mod.rs @@ -2133,18 +2164,6 @@ impl DepthFirstNumber { } } -impl ExClause { - fn with_constraints<I>(mut self, constraints: I) -> Self - where - I: IntoIterator<Item = InEnvironment<Constraint>>, - { - self.constraints.extend(constraints); - self.constraints.sort(); - self.constraints.dedup(); - self - } -} - impl<T> Satisfiable<T> { fn yes(self) -> Option<T> { match self { diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -1,5 +1,10 @@ use cast::Caster; +use fallible::Fallible; +use fold::Fold; +use fold::shift::Shift; +use solve::infer::var::InferenceVariable; use super::*; +use zip::Zipper; /////////////////////////////////////////////////////////////////////////// // SLG RESOLVENTS diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -45,6 +50,16 @@ pub(super) fn resolvent_pending( answer_table_goal: &CanonicalGoal, answer_subst: &CanonicalConstrainedSubst, ) -> Satisfiable<(StackIndex, ExClause)> { + debug_heading!( + "resolvent_pending(\ + \n pending_ex_clause={:?},\ + \n answer_table_goal={:?},\ + \n answer_subst={:?})", + pending_ex_clause, + answer_table_goal, + answer_subst + ); + let PendingExClause { goal_depth, subst, diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -61,61 +76,17 @@ pub(super) fn resolvent_pending( subgoals, }; - resolvent::resolvent_answer( + let result = apply_answer_subst( infer, - &ex_clause, + ex_clause, &selected_goal, answer_table_goal, - answer_subst, - ).map(|r| (goal_depth, r)) -} + answer_subst + ).map(|r| (goal_depth, r)); -/// Applies the SLG resolvent algorithm to incorporate an answer -/// produced by the selected literal into the main X-clause, -/// producing a new X-clause that must be solved. -/// -/// # Parameters -/// -/// - `ex_clause` is the X-clause we are trying to prove, -/// with the selected literal removed from its list of subgoals -/// - `selected_goal` is the selected literal that was removed -/// - `answer` is some answer to `selected_goal` that has been found -fn resolvent_answer( - infer: &mut InferenceTable, - ex_clause: &ExClause, - selected_goal: &InEnvironment<Goal>, - answer_table_goal: &CanonicalGoal, - answer_subst: &CanonicalConstrainedSubst, -) -> Satisfiable<ExClause> { - // Relating the above describes to our parameters: - // - // - the goal G is `ex_clause` is, with `selected_goal` being - // the selected literal Li, already removed from the list. - // - the clause C is `answer.` (i.e., the answer has no conditions). + info!("resolvent = {:?}", result); - // C' is now `answer`. No variables in commmon with G. - let ConstrainedSubst { - subst: answer_subst, - constraints: answer_constraints, - } = infer.instantiate_canonical(&answer_subst); - - // Apply the substitution from the answer to the original - // table goal to yield our new `answer_goal`. This is needed - // for unifying. - let answer_goal = answer_table_goal.substitute(&answer_subst); - - // Perform the SLG resolvent unification. - let resolvent = resolvent::resolvent_unify( - infer, - ex_clause.clone(), - selected_goal, - &answer_goal, - vec![], - ); - - // We have one additional complication: we have to insert the - // region constraints. - resolvent.map(|ex_clause| ex_clause.with_constraints(answer_constraints)) + result } /// Applies the SLG resolvent algorithm to incorporate a program diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -178,6 +149,16 @@ where { let environment = &selected_goal.environment; + debug_heading!( + "resolvent_unify(\ + \n selected_goal={:?},\ + \n consequence={:?},\ + \n conditions={:?})", + selected_goal, + consequence, + conditions, + ); + // Unify the selected literal Li with C'. let UnificationResult { goals, constraints } = { match infer.unify(&selected_goal.environment, selected_goal, consequence) { diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -189,6 +170,7 @@ where goal.constraints.extend(constraints); // One (minor) complication: unification for us sometimes yields further domain goals. + info!("subgoals={:?}", goals); goal.subgoals .extend(goals.into_iter().casted().map(Literal::Positive)); diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -263,26 +245,112 @@ pub(super) fn factor_pending( subgoals, }; - resolvent::factor( + let result = apply_answer_subst( infer, - &ex_clause, + ex_clause, &selected_goal, - answer_table, answer_table_goal, answer_subst, - ).map(|c| (goal_depth, c)) + ).map(|mut ex_clause| { + // Push Li into the list of delayed literals. + ex_clause.delayed_literals.push(DelayedLiteral::Positive( + answer_table, + answer_subst.clone(), + )); + + (goal_depth, ex_clause) + }); + + debug!("factor_pending: result = {:?}", result); + + result } -fn factor( +/////////////////////////////////////////////////////////////////////////// +// apply_answer_subst +// +// Apply answer subst has the job of "plugging in" the answer to a +// query into the pending ex-clause. To see how it works, it's worth stepping +// up one level. Imagine that first we are trying to prove a goal A: +// +// A :- T: Foo<Vec<?U>>, ?U: Bar +// +// this spawns a subgoal `T: Foo<Vec<?0>>`, and it's this subgoal that +// has now produced an answer `?0 = u32`. When the goal A spawned the +// subgoal, it will also have registered a `PendingExClause` with its +// current state. At the point where *this* method has been invoked, +// that pending ex-clause has been instantiated with fresh variables and setup, +// so we have four bits of incoming information: +// +// - `ex_clause`, which is the remaining stuff to prove for the goal A. +// Here, the inference variable `?U` has been instantiated with a fresh variable +// `?X`. +// - `A :- ?X: Bar` +// - `selected_goal`, which is the thing we were trying to prove when we +// spawned the subgoal. It shares inference variables with `ex_clause`. +// - `T: Foo<Vec<?X>>` +// - `answer_table_goal`, which is the subgoal in canonical form: +// - `for<type> T: Foo<Vec<?0>>` +// - `canonical_answer_subst`, which is an answer to `answer_table_goal`. +// - `[?0 = u32]` +// +// In this case, this function will (a) unify `u32` and `?X` and then +// (b) return `ex_clause` (extended possibly with new region constraints +// and subgoals). +// +// One way to do this would be to (a) substitute +// `canonical_answer_subst` into `answer_table_goal` (yielding `T: +// Foo<Vec<u32>>`) and then (b) instantiate the result with fresh +// variables (no effect in this instance) and then (c) unify that with +// `selected_goal` (yielding, indirectly, that `?X = u32`). But that +// is not what we do: it's inefficient, to start, but it also causes +// problems because unification of projections can make new +// sub-goals. That is, even if the answers don't involve any +// projections, the table goals might, and this can create an infinite +// loop (see also #74). +// +// What we do instead is to (a) instantiate the substitution, which +// may have free variables in it (in this case, it would not, and the +// instantiation woudl have no effect) and then (b) zip +// `answer_table_goal` and `selected_goal` without having done any +// substitution. After all, these ought to be basically the same, +// since `answer_table_goal` was created by canonicalizing (and +// possibly truncating, but we'll get to that later) +// `selected_goal`. Then, whenever we reach a "free variable" in +// `answer_table_goal`, say `?0`, we go to the instantiated answer +// substitution and lookup the result (in this case, `u32`). We take +// that result and unify it with whatever we find in `selected_goal` +// (in this case, `?X`). +// +// Let's cover then some corner cases. First off, what is this +// business of instantiating the answer? Well, the answer may not be a +// simple type like `u32`, it could be a "family" of types, like +// `for<type> Vec<?0>` -- i.e., `Vec<X>: Bar` for *any* `X`. In that +// case, the instantiation would produce a substitution `[?0 := +// Vec<?Y>]` (note that the key is not affected, just the value). So +// when we do the unification, instead of unifying `?X = u32`, we +// would unify `?X = Vec<?Y>`. +// +// Next, truncation. One key thing is that the `answer_table_goal` may +// not be *exactly* the same as the `selected_goal` -- we will +// truncate it if it gets too deep. so, in our example, it may be that +// instead of `answer_table_goal` being `for<type> T: Foo<Vec<?0>>`, +// it could have been truncated to `for<type> T: Foo<?0>` (which is a +// more general goal). In that case, let's say that the answer is +// still `[?0 = u32]`, meaning that `T: Foo<u32>` is true (which isn't +// actually interesting to our original goal). When we do the zip +// then, we will encounter `?0` in the `answer_table_goal` and pair +// that with `Vec<?X>` from the pending goal. We will attempt to unify +// `Vec<?X>` with `u32` (from the substitution), which will fail. That +// failure will get propagated back up. + +fn apply_answer_subst( infer: &mut InferenceTable, - ex_clause: &ExClause, + mut ex_clause: ExClause, selected_goal: &InEnvironment<Goal>, - answer_table: TableIndex, answer_table_goal: &CanonicalGoal, canonical_answer_subst: &CanonicalConstrainedSubst, ) -> Satisfiable<ExClause> { - let mut ex_clause = ex_clause.clone(); - // C' is now `answer`. No variables in commmon with G. let ConstrainedSubst { subst: answer_subst, diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -295,24 +363,17 @@ fn factor( constraints: answer_constraints, } = infer.instantiate_canonical(&canonical_answer_subst); - let answer_goal = answer_table_goal.substitute(&answer_subst); - - // Unify the selected literal Li with C'. - let UnificationResult { goals, constraints } = { - match infer.unify(&selected_goal.environment, selected_goal, &answer_goal) { - Err(_) => return Satisfiable::No, - Ok(v) => v, - } + let (goals, constraints) = match AnswerSubstitutor::substitute( + infer, + &selected_goal.environment, + &answer_subst, + &answer_table_goal.value, + selected_goal, + ) { + Ok((goals, constraints)) => (goals, constraints), + Err(_) => return Satisfiable::No, }; - // Push Li into the list of delayed literals. - ex_clause.delayed_literals.push(DelayedLiteral::Positive( - answer_table, - canonical_answer_subst.clone(), - )); - - // We must also take into account the add'l conditions that - // arise from our unification procedure. ex_clause.constraints.extend(constraints); ex_clause.constraints.extend(answer_constraints); ex_clause diff --git a/src/solve/slg/resolvent.rs b/src/solve/slg/resolvent.rs --- a/src/solve/slg/resolvent.rs +++ b/src/solve/slg/resolvent.rs @@ -321,3 +382,186 @@ fn factor( Satisfiable::Yes(ex_clause) } + +struct AnswerSubstitutor<'t> { + table: &'t mut InferenceTable, + environment: &'t Arc<Environment>, + answer_subst: &'t Substitution, + answer_binders: usize, + pending_binders: usize, + goals: Vec<InEnvironment<DomainGoal>>, + constraints: Vec<InEnvironment<Constraint>>, +} + +impl<'t> AnswerSubstitutor<'t> { + fn substitute<T: Zip>( + table: &mut InferenceTable, + environment: &Arc<Environment>, + answer_subst: &Substitution, + answer: &T, + pending: &T, + ) -> Fallible< + ( + Vec<InEnvironment<DomainGoal>>, + Vec<InEnvironment<Constraint>>, + ), + > { + let mut this = AnswerSubstitutor { + table, + environment, + answer_subst, + answer_binders: 0, + pending_binders: 0, + goals: vec![], + constraints: vec![], + }; + Zip::zip_with(&mut this, answer, pending)?; + Ok((this.goals, this.constraints)) + } + + fn unify_free_answer_var( + &mut self, + answer_depth: usize, + pending: ParameterKind<&Ty, &Lifetime>, + ) -> Fallible<bool> { + // This variable is bound in the answer, not free, so it + // doesn't represent a reference into the answer substitution. + if answer_depth < self.answer_binders { + return Ok(false); + } + + let var = InferenceVariable::from_depth(answer_depth - self.answer_binders); + let answer_param = if let Some(param) = self.answer_subst.parameters.get(&var) { + param + } else { + // In principle, substitutions don't have to + // be complete, so we could just return now -- + // it would indicate that the SLG solver + // places no constraints on this particular + // variable. *However*, in practice we always + // return a value in the SLG solver for all + // inputs, even if that value is trivial, so + // we panic here. + panic!("answer-subst does not contain input variable `{:?}`", var) + }; + + let pending_shifted = &pending + .down_shift(self.pending_binders) + .unwrap_or_else(|_| { + panic!( + "truncate extracted a pending value that references internal binder: {:?}", + pending, + ) + }); + + let UnificationResult { goals, constraints } = + self.table + .unify(&self.environment, answer_param, pending_shifted)?; + + self.constraints.extend(constraints); + self.goals.extend(goals); + Ok(true) + } + + /// When we encounter a variable in the answer goal, we first try + /// `unify_free_answer_var`. Assuming that this fails, the + /// variable must be a bound variable in the answer goal -- in + /// that case, there should be a corresponding bound variable in + /// the pending goal. This bit of code just checks that latter + /// case. + fn assert_matching_vars(&mut self, answer_depth: usize, pending_depth: usize) -> Fallible<()> { + assert!(answer_depth < self.answer_binders); + assert!(pending_depth < self.answer_binders); + assert_eq!( + answer_depth - self.answer_binders, + pending_depth - self.pending_binders + ); + Ok(()) + } +} + +impl<'t> Zipper for AnswerSubstitutor<'t> { + fn zip_tys(&mut self, answer: &Ty, pending: &Ty) -> Fallible<()> { + // If the answer has a variable here, then this is one of the + // "inputs" to the subgoal table. We need to extract the + // resulting answer that the subgoal found and unify it with + // the value from our "pending subgoal". + if let Ty::Var(answer_depth) = answer { + if self.unify_free_answer_var(*answer_depth, ParameterKind::Ty(pending))? { + return Ok(()); + } + } + + // Otherwise, the answer and the selected subgoal ought to be a perfect match for + // one another. + match (answer, pending) { + (Ty::Var(answer_depth), Ty::Var(pending_depth)) => { + self.assert_matching_vars(*answer_depth, *pending_depth) + } + + (Ty::Apply(answer), Ty::Apply(pending)) => Zip::zip_with(self, answer, pending), + + (Ty::Projection(answer), Ty::Projection(pending)) => { + Zip::zip_with(self, answer, pending) + } + + (Ty::UnselectedProjection(answer), Ty::UnselectedProjection(pending)) => { + Zip::zip_with(self, answer, pending) + } + + (Ty::ForAll(answer), Ty::ForAll(pending)) => { + self.answer_binders += answer.num_binders; + self.pending_binders += pending.num_binders; + Zip::zip_with(self, &answer.ty, &pending.ty)?; + self.answer_binders -= answer.num_binders; + self.pending_binders -= pending.num_binders; + Ok(()) + } + + (Ty::Var(_), _) + | (Ty::Apply(_), _) + | (Ty::Projection(_), _) + | (Ty::UnselectedProjection(_), _) + | (Ty::ForAll(_), _) => panic!( + "structural mismatch between answer `{:?}` and pending goal `{:?}`", + answer, pending, + ), + } + } + + fn zip_lifetimes(&mut self, answer: &Lifetime, pending: &Lifetime) -> Fallible<()> { + if let Lifetime::Var(answer_depth) = answer { + if self.unify_free_answer_var(*answer_depth, ParameterKind::Lifetime(pending))? { + return Ok(()); + } + } + + match (answer, pending) { + (Lifetime::Var(answer_depth), Lifetime::Var(pending_depth)) => { + self.assert_matching_vars(*answer_depth, *pending_depth) + } + + (Lifetime::ForAll(answer_ui), Lifetime::ForAll(pending_ui)) => { + assert_eq!(answer_ui, pending_ui); + Ok(()) + } + + (Lifetime::Var(_), _) | (Lifetime::ForAll(_), _) => panic!( + "structural mismatch between answer `{:?}` and pending goal `{:?}`", + answer, pending, + ), + } + } + + fn zip_binders<T>(&mut self, answer: &Binders<T>, pending: &Binders<T>) -> Fallible<()> + where + T: Zip + Fold<Result = T>, + { + self.answer_binders += answer.binders.len(); + self.pending_binders += pending.binders.len(); + Zip::zip_with(self, &answer.value, &pending.value)?; + self.answer_binders -= answer.binders.len(); + self.pending_binders -= pending.binders.len(); + Ok(()) + } +} diff --git a/src/solve/truncate.rs b/src/solve/truncate.rs --- a/src/solve/truncate.rs +++ b/src/solve/truncate.rs @@ -2,6 +2,7 @@ use fallible::*; use fold::{self, Fold, IdentityExistentialFolder, IdentityUniversalFolder, TypeFolder}; +use fold::shift::Shift; use ir::*; use solve::infer::InferenceTable; diff --git a/src/zip.rs b/src/zip.rs --- a/src/zip.rs +++ b/src/zip.rs @@ -178,6 +178,7 @@ struct_zip!(UnselectedProjectionTy { parameters, }); struct_zip!(Normalize { projection, ty }); +struct_zip!(ProjectionEq { projection, ty }); struct_zip!(UnselectedNormalize { projection, ty }); struct_zip!(EqGoal { a, b }); diff --git a/src/zip.rs b/src/zip.rs --- a/src/zip.rs +++ b/src/zip.rs @@ -216,6 +217,7 @@ enum_zip!(PolarizedTraitRef { Positive, Negative }); enum_zip!(DomainGoal { Implemented, Normalize, + ProjectionEq, UnselectedNormalize, WellFormed, InScope,
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ #![cfg_attr(test, feature(test))] #![feature(conservative_impl_trait)] #![feature(catch_expr)] +#![feature(crate_visibility_modifier)] #![feature(match_default_bindings)] #![feature(specialization)] #![feature(step_trait)] diff --git a/src/lower/test.rs b/src/lower/test.rs --- a/src/lower/test.rs +++ b/src/lower/test.rs @@ -186,7 +186,7 @@ fn goal_quantifiers() { set_current_program(&program, || { assert_eq!( format!("{:?}", goal), - "ForAll<type> { Exists<type> { ForAll<type> { ?0: Foo<?1, ?2> } } }" + "ForAll<type> { Exists<type> { ForAll<type> { (?0: Foo<?1, ?2>) } } }" ); }); } diff --git a/src/lower/test.rs b/src/lower/test.rs --- a/src/lower/test.rs +++ b/src/lower/test.rs @@ -243,7 +243,7 @@ fn atc_accounting() { println!("{}", goal_text); assert_eq!( goal_text, - "ForAll<type> { ForAll<lifetime> { ForAll<type> { <?2 as Iterable>::Iter<'?1> ==> ?0 } } }" + "ForAll<type> { ForAll<lifetime> { ForAll<type> { ProjectionEq(<?2 as Iterable>::Iter<'?1> = ?0) } } }" ); }); } diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -489,14 +489,11 @@ fn normalize_basic() { goal { forall<T> { exists<U> { - Vec<T>: Iterator<Item = U> + Normalize(<Vec<T> as Iterator>::Item -> U) } } - } yields[SolverChoice::recursive()] { + } yields { "Unique; substitution [?0 := !1], lifetime constraints []" - } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver - "Ambiguous; no inference guidance" } goal { diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -510,16 +507,23 @@ fn normalize_basic() { goal { forall<T> { if (T: Iterator<Item = u32>) { + <T as Iterator>::Item = u32 + } + } + } yields { + "Unique; substitution []" + } + + goal { + forall<T> { + if (T: Iterator) { exists<U> { T: Iterator<Item = U> } } } - } yields[SolverChoice::recursive()] { - "Unique; substitution [?0 := u32]" } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver - "Ambiguous" + "Unique; substitution [?0 := (Iterator::Item)<!1>]" } goal { diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -552,10 +556,8 @@ fn normalize_basic() { } } } - } yields[SolverChoice::recursive()] { - "Unique" - } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver + } yields { + // True for `U = T`, of course, but also true for `U = Vec<T>`. "Ambiguous" } } diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -725,6 +727,7 @@ fn elaborate_transitive() { } #[test] +#[ignore] fn elaborate_normalize() { test! { program { diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -803,15 +806,12 @@ fn atc1() { forall<T> { forall<'a> { exists<U> { - Vec<T>: Iterable<Iter<'a> = U> + Normalize(<Vec<T> as Iterable>::Iter<'a> -> U) } } } - } yields[SolverChoice::recursive()] { + } yields { "Unique; substitution [?0 := Iter<'!2, !1>], lifetime constraints []" - } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver - "Ambiguous; no inference guidance" } } } diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -965,6 +965,34 @@ fn trait_wf() { } } +#[test] +fn normalize_fallback_option() { + test! { + program { + trait Iterator { type Item; } + struct Foo { } + struct Vec<T> { } + impl<T> Iterator for Vec<T> { type Item = T; } + } + + goal { + forall<T> { + if (T: Iterator) { + exists<U> { + exists<V> { + // Here, `U` could be `T` or it could be + // `Vec<Foo>`. + U: Iterator<Item = V> + } + } + } + } + } yields { + "Ambiguous" + } + } +} + #[test] fn normalize_under_binder() { test! { diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -995,40 +1023,51 @@ fn normalize_under_binder() { Ref<'a, I32>: Deref<'a, Item = U> } } - } yields[SolverChoice::recursive()] { - "Unique; substitution [?0 := I32], lifetime constraints []" - } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver + } yields { "Ambiguous" } + goal { + exists<U> { + forall<'a> { + Normalize(<Ref<'a, I32> as Deref<'a>>::Item -> U) + } + } + } yields { + "Unique; substitution [?0 := I32], lifetime constraints []" + } + goal { forall<'a> { exists<U> { Ref<'a, I32>: Id<'a, Item = U> } } - } yields[SolverChoice::recursive()] { - "Unique; substitution [?0 := Ref<'!1, I32>], lifetime constraints []" - } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver + } yields { "Ambiguous" } + goal { + forall<'a> { + exists<U> { + Normalize(<Ref<'a, I32> as Id<'a>>::Item -> U) + } + } + } yields { + "Unique; substitution [?0 := Ref<'!1, I32>], lifetime constraints []" + } + goal { exists<U> { forall<'a> { - Ref<'a, I32>: Id<'a, Item = U> + Normalize(<Ref<'a, I32> as Id<'a>>::Item -> U) } } - } yields[SolverChoice::recursive()] { + } yields { "Unique; for<?U0> { \ substitution [?0 := Ref<'?0, I32>], \ lifetime constraints [(Env([]) |- LifetimeEq('?0, '!1))] \ }" - } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver - "Ambiguous" } } } diff --git a/src/solve/test/mod.rs b/src/solve/test/mod.rs --- a/src/solve/test/mod.rs +++ b/src/solve/test/mod.rs @@ -1174,15 +1213,12 @@ fn mixed_indices_normalize_application() { exists<T> { exists<'a> { exists<U> { - <Ref<'a, T> as Foo>::T = U + Normalize(<Ref<'a, T> as Foo>::T -> U) } } } - } yields[SolverChoice::recursive()] { - "Unique" - } yields[SolverChoice::slg()] { - // FIXME -- fallback clauses not understood by SLG solver - "Ambiguous; no inference guidance" + } yields { + "Unique; for<?U0,?U0> { substitution [?0 := '?0, ?1 := ?1, ?2 := ?1], " } } }
fallback clauses considered harmful / how to handle projection equality In working on https://github.com/rust-lang-nursery/chalk/pull/73, I encountered a problem with the concept of a "fallback clause", which is currently a key part of how we handle normalization. The idea of a fallback clause is that it is a clause that we use if no other clauses apply. That seems fine but it's actually too weak: we wind up coming up with "unique" solutions that are not in fact unique. Consider this example: ``` trait Iterator { type Item; } struct Foo { } struct Vec<T> { } a ``` and this goal: ``` forall<T> { if (T: Iterator) { exists<U> { exists<V> { U: Iterator<Item = V> } } } } ``` Here, there are two values for `U` and `V`: - `exists<W> { U = Vec<W>, V = W }` - `U = T, V = T::Item` However, our current system will select the first one and be satisfied. This is because the second one is considered a "fallback" option, and hence since the first one is satisfied, it never gets considered. This is not true of the SLG solver, since I never could figure out how to integrate fallback into that solver -- for good reasons, I think. I have a branch [de-fallback](https://github.com/nikomatsakis/chalk-ndm/tree/de-fallback) that adresses this problem by removing the notion of fallback clauses. Instead, we have a new domain goal, "projection equality", which replaces normalization in a way (though normalization, as we will see, plays a role). When we attempt to unify two types T and U where at least one of those types is a projection, we "rewrite" to projection equality (really, we could rewrite all of unification into clauses, but I chose the more limited path here, since otherwise we'd have to handle higher-ranked types and substitution in the logic code). Projection equality is defined by two clauses per associated item, which are defined when lowering the trait (well, when lowering the declaration of the associated item found in the trait). The first clause is what we used to call the "fallback" rule, basically covering the "skolemized" case: ``` forall<T> { ProjectionEq(<T as Iterator>::Item = (Iterator::Item)<T>) } ``` The second clause uses a revised concept of *normalization*. Normalization in this setup is limited to applying an impl to rewrite a projection to the type found in the impl (whereas before it included the fallback case): ``` forall<T, U> { ProjectionEq(<T as Iterator>::Item = U) :- Normalizes(<T as Iterator>::Item -> U) } ``` Both of these rules are created when lowering the trait. When lowering the **impl**, we would make a rule like: ``` forall<T> { Normalizes(<Vec<T> as Iterator>::Item -> T) :- (Vec<T>: Iterator). } ``` This all seems to work pretty well. Note that `ProjectionEq` can never "guess" the right hand side unless normalization is impossible: that is `exists<X> { ProjectionEq(<Vec<i32> as Iterator>::Item = X) }` is still ambiguous. But if you want to force normalize, you can use the `Normalizes` relation (which would only be defined, in that example, wen `X = i32`). *However,* the tests are currently failing because we are running into problems with the implied bounds elaborations and the limitations of the recursive solver. (The SLG solver handles it fine.) In particular, there is a rule that looks something like this: ``` forall<T, U> { (T: Iterator) :- ProjectionEq(<T as Iterator>::Item = U) } ``` This is basically saying, if we *know* (somehow) that `T::Item` is equal to `U`, then we know that `T` must implement `Iterator`. It's reasonable, but it winds up causing us a problem. This is because, in the recursive solver, when we are doing normalization, we apply the normalization clause cited above, and then must prove that `(Vec<T>: Iterator)`. To do that, we turn to our full set of clauses, which includes a clause from the impl (which is the right one) and the clause above. The reverse elaboration clause always yields **ambiguous** -- this is because there is no unique answer to `ProjectionEq`, and `U` is unconstrained. I'm not 100% sure how to resolve this problem right now, so I thought I'd open the issue for a bit of discussion. cc @scalexm @aturon
2018-01-19T09:17:56Z
0.1
2018-01-20T12:30:20Z
154020e4884e7b9fe41a93a6970cfff78783cdcc
[ "lower::test::goal_quantifiers", "lower::test::atc_accounting", "solve::test::mixed_indices_normalize_application", "solve::test::atc1", "solve::test::normalize_fallback_option", "solve::test::normalize_basic", "solve::test::normalize_under_binder" ]
[ "lower::test::concrete_impl_and_blanket_impl", "lower::test::nonoverlapping_assoc_types", "lower::test::multiple_parameters", "solve::infer::test::universe_error", "solve::infer::test::cycle_indirect", "solve::infer::test::universe_error_indirect_1", "lower::test::multiple_nonoverlapping_impls", "lower::test::not_trait", "solve::infer::test::quantify_ty_under_binder", "lower::test::generic_vec_and_specific_vec", "lower::test::auto_trait", "solve::infer::test::quantify_bound", "solve::infer::test::lifetime_constraint_indirect", "solve::infer::test::cycle_error", "solve::slg::aggregate::vec_x_vs_vec_y", "solve::infer::test::quantify_simple", "solve::infer::test::universe_error_indirect_2", "solve::infer::test::projection_eq", "lower::test::invalid_name", "solve::slg::aggregate::vec_i32_vs_vec_u32", "lower::test::negative_impl", "solve::slg::aggregate::vec_i32_vs_vec_i32", "solve::infer::test::universe_promote", "solve::infer::test::infer", "lower::test::lower_success", "solve::infer::test::universe_promote_bad", "lower::test::local_negative_reasoning_in_coherence", "solve::slg::test::contradiction", "lower::test::overlapping_negative_positive_impls", "lower::test::assoc_tys", "lower::test::type_parameter", "lower::test::check_parameter_kinds", "solve::slg::test::cached_answers_2", "lower::test::overlapping_assoc_types", "solve::slg::test::negative_loop", "solve::slg::test::positive_cycle", "lower::test::two_impls_for_same_type", "lower::test::two_blanket_impls_open_ended", "solve::truncate::truncate_normalizes_under_binders", "solve::truncate::truncate_multiple_types", "solve::truncate::truncate_types", "solve::truncate::truncate_normalizes", "solve::slg::test::subgoal_cycle_inhabited", "lower::test::overlapping_negative_impls", "lower::test::overlapping_assoc_types_error", "solve::slg::test::cached_answers_3", "solve::test::elaborate_eq", "solve::slg::test::basic_region_constraint_from_positive_impl", "solve::slg::test::slg_from_env", "lower::test::two_blanket_impls", "solve::slg::test::basic_region_constraint_from_unification_goal", "lower::test::type_parameter_bound", "solve::test::overflow", "solve::test::higher_ranked", "solve::slg::test::example_2_2_EWFS", "solve::test::inapplicable_assumption_does_not_shadow", "solve::test::forall_equality", "solve::test::forall_projection", "solve::test::cycle_no_solution", "solve::test::deep_failure", "solve::slg::test::subgoal_cycle_uninhabited", "solve::test::partial_overlap_1", "solve::slg::test::cached_answers_1", "solve::slg::test::example_2_1_EWFS", "solve::slg::test::example_3_3_EWFS", "solve::slg::test::example_2_3_EWFS", "solve::test::cycle_unique_solution", "solve::test::elaborate_transitive", "solve::test::mixed_semantics", "solve::test::prove_infer", "solve::test::equality_binder", "solve::test::definite_guidance", "solve::test::inner_cycle", "solve::test::unselected_projection", "solve::test::struct_wf", "solve::test::auto_trait_with_impls", "solve::slg::test::subgoal_abstraction", "solve::test::negation_free_vars", "solve::test::ordering", "solve::test::cycle_many_solutions", "solve::test::normalize_rev_infer", "solve::test::mixed_indices_unify", "solve::test::mixed_indices_match_program", "solve::test::overflow_universe", "solve::test::generic_trait", "solve::test::multiple_ambiguous_cycles", "solve::test::where_clause_trumps", "solve::test::deep_negation", "solve::test::deep_success", "solve::test::region_equality", "solve::test::inscope", "solve::test::coinductive_semantics", "solve::test::unify_quantified_lifetimes", "solve::test::negation_quantifiers", "solve::test::partial_overlap_3", "solve::test::auto_trait_without_impls", "solve::test::partial_overlap_2", "solve::test::prove_clone", "solve::test::simple_negation", "solve::test::prove_forall", "solve::test::suggested_subst", "solve::test::trait_wf", "src/solve/slg/mod.rs - solve::slg::Forest (line 117)" ]
[]
[]
auto_2025-06-13
rust-lang/chalk
55
rust-lang__chalk-55
[ "25" ]
7eb0f085b86986159097da1cb34dc065f2a6c8cd
diff --git a/src/fold/instantiate.rs b/src/fold/instantiate.rs --- a/src/fold/instantiate.rs +++ b/src/fold/instantiate.rs @@ -39,7 +39,7 @@ macro_rules! subst_method { subst_method!(Goal); subst_method!(Ty); -impl<'b> Folder for Subst<'b> { +impl<'b> FolderVar for Subst<'b> { fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty> { if depth >= self.parameters.len() { Ok(Ty::Var(depth - self.parameters.len() + binders)) diff --git a/src/fold/mod.rs b/src/fold/mod.rs --- a/src/fold/mod.rs +++ b/src/fold/mod.rs @@ -12,28 +12,74 @@ pub use self::shifted::Shifted; pub use self::shifter::Shifter; pub use self::instantiate::Subst; -pub trait Folder { +pub trait FolderVar { fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty>; fn fold_free_lifetime_var(&mut self, depth: usize, binders: usize) -> Result<Lifetime>; } -impl<'f, F: Folder + ?Sized> Folder for &'f mut F { - fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty> { - (**self).fold_free_var(depth, binders) +pub trait Folder { + fn fold_ty(&mut self, ty: &Ty, binders: usize) -> Result<Ty>; + fn fold_lifetime(&mut self, lifetime: &Lifetime, binders: usize) -> Result<Lifetime>; +} + +impl<T: FolderVar> Folder for T { + fn fold_ty(&mut self, ty: &Ty, binders: usize) -> Result<Ty> { + match *ty { + Ty::Var(depth) => if depth >= binders { + self.fold_free_var(depth - binders, binders) + } else { + Ok(Ty::Var(depth)) + }, + Ty::Apply(ref apply) => Ok(Ty::Apply(apply.fold_with(self, binders)?)), + Ty::Projection(ref proj) => { + Ok(Ty::Projection(proj.fold_with(self, binders)?)) + } + Ty::ForAll(ref quantified_ty) => { + Ok(Ty::ForAll(quantified_ty.fold_with(self, binders)?)) + } + } } - fn fold_free_lifetime_var(&mut self, depth: usize, binders: usize) -> Result<Lifetime> { - (**self).fold_free_lifetime_var(depth, binders) + fn fold_lifetime(&mut self, lifetime: &Lifetime, binders: usize) -> Result<Lifetime> { + match *lifetime { + Lifetime::Var(depth) => if depth >= binders { + self.fold_free_lifetime_var(depth - binders, binders) + } else { + Ok(Lifetime::Var(depth)) + }, + Lifetime::ForAll(universe) => Ok(Lifetime::ForAll(universe)), + } } } -impl<F1: Folder, F2: Folder> Folder for (F1, F2) { - fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty> { - self.0.fold_free_var(depth, binders)?.fold_with(&mut self.1, binders) +pub struct FolderRef<'f, F> where F: 'f + ?Sized { + folder: &'f mut F, +} + +impl<'f, F: ?Sized> FolderRef<'f, F> { + pub fn new(folder: &'f mut F) -> Self { + FolderRef { + folder, + } + } +} + +impl<'f, F: Folder + ?Sized> Folder for FolderRef<'f, F> { + fn fold_ty(&mut self, ty: &Ty, binders: usize) -> Result<Ty> { + self.folder.fold_ty(ty, binders) + } + + fn fold_lifetime(&mut self, lifetime: &Lifetime, binders: usize) -> Result<Lifetime> { + self.folder.fold_lifetime(lifetime, binders) } +} - fn fold_free_lifetime_var(&mut self, depth: usize, binders: usize) -> Result<Lifetime> { - self.0.fold_free_lifetime_var(depth, binders)?.fold_with(&mut self.1, binders) +impl<F1: Folder, F2: Folder> Folder for (F1, F2) { + fn fold_ty(&mut self, ty: &Ty, binders: usize) -> Result<Ty> { + self.0.fold_ty(ty, binders)?.fold_with(&mut self.1, binders) + } + fn fold_lifetime(&mut self, lifetime: &Lifetime, binders: usize) -> Result<Lifetime> { + self.0.fold_lifetime(lifetime, binders)?.fold_with(&mut self.1, binders) } } diff --git a/src/fold/mod.rs b/src/fold/mod.rs --- a/src/fold/mod.rs +++ b/src/fold/mod.rs @@ -90,20 +136,7 @@ impl<T: Fold> Fold for Option<T> { impl Fold for Ty { type Result = Self; fn fold_with(&self, folder: &mut Folder, binders: usize) -> Result<Self::Result> { - match *self { - Ty::Var(depth) => if depth >= binders { - folder.fold_free_var(depth - binders, binders) - } else { - Ok(Ty::Var(depth)) - }, - Ty::Apply(ref apply) => Ok(Ty::Apply(apply.fold_with(folder, binders)?)), - Ty::Projection(ref proj) => { - Ok(Ty::Projection(proj.fold_with(folder, binders)?)) - } - Ty::ForAll(ref quantified_ty) => { - Ok(Ty::ForAll(quantified_ty.fold_with(folder, binders)?)) - } - } + folder.fold_ty(self, binders) } } diff --git a/src/fold/mod.rs b/src/fold/mod.rs --- a/src/fold/mod.rs +++ b/src/fold/mod.rs @@ -129,14 +162,7 @@ impl<T> Fold for Binders<T> impl Fold for Lifetime { type Result = Self; fn fold_with(&self, folder: &mut Folder, binders: usize) -> Result<Self::Result> { - match *self { - Lifetime::Var(depth) => if depth >= binders { - folder.fold_free_lifetime_var(depth - binders, binders) - } else { - Ok(Lifetime::Var(depth)) - }, - Lifetime::ForAll(universe) => Ok(Lifetime::ForAll(universe)), - } + folder.fold_lifetime(self, binders) } } diff --git a/src/fold/shifted.rs b/src/fold/shifted.rs --- a/src/fold/shifted.rs +++ b/src/fold/shifted.rs @@ -1,5 +1,5 @@ use errors::*; -use super::{Fold, Folder, Shifter}; +use super::{Fold, Folder, FolderRef, Shifter}; /// Sometimes we wish to fold two values with a distinct deBruijn /// depth (i.e., you want to fold `(A, B)` where A is defined under N diff --git a/src/fold/shifted.rs b/src/fold/shifted.rs --- a/src/fold/shifted.rs +++ b/src/fold/shifted.rs @@ -31,7 +31,7 @@ impl<T: Fold> Fold for Shifted<T> { // contains a free var with index 0, and `self.adjustment == // 2`, we will translate it to a free var with index 2; then // we will fold *that* through `folder`. - let mut new_folder = (Shifter::new(self.adjustment), folder); + let mut new_folder = (Shifter::new(self.adjustment), FolderRef::new(folder)); self.value.fold_with(&mut new_folder, binders) } } diff --git a/src/fold/shifter.rs b/src/fold/shifter.rs --- a/src/fold/shifter.rs +++ b/src/fold/shifter.rs @@ -1,6 +1,6 @@ use errors::*; use ir::*; -use super::{Fold, Folder}; +use super::{Fold, FolderVar}; pub struct Shifter { adjustment: usize diff --git a/src/fold/shifter.rs b/src/fold/shifter.rs --- a/src/fold/shifter.rs +++ b/src/fold/shifter.rs @@ -37,7 +37,7 @@ up_shift_method!(TraitRef); up_shift_method!(ProjectionTy); up_shift_method!(DomainGoal); -impl Folder for Shifter { +impl FolderVar for Shifter { fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty> { Ok(Ty::Var(depth + self.adjustment + binders)) } diff --git a/src/solve/infer/canonicalize.rs b/src/solve/infer/canonicalize.rs --- a/src/solve/infer/canonicalize.rs +++ b/src/solve/infer/canonicalize.rs @@ -1,5 +1,5 @@ use errors::*; -use fold::{Fold, Folder, Shifter}; +use fold::{Fold, FolderVar, FolderRef, Shifter}; use ir::*; use super::{InferenceTable, TyInferenceVariable, LifetimeInferenceVariable, diff --git a/src/solve/infer/canonicalize.rs b/src/solve/infer/canonicalize.rs --- a/src/solve/infer/canonicalize.rs +++ b/src/solve/infer/canonicalize.rs @@ -86,7 +86,7 @@ impl<'q> Canonicalizer<'q> { } } -impl<'q> Folder for Canonicalizer<'q> { +impl<'q> FolderVar for Canonicalizer<'q> { fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty> { let var = TyInferenceVariable::from_depth(depth); match self.table.probe_var(var) { diff --git a/src/solve/infer/canonicalize.rs b/src/solve/infer/canonicalize.rs --- a/src/solve/infer/canonicalize.rs +++ b/src/solve/infer/canonicalize.rs @@ -95,7 +95,7 @@ impl<'q> Folder for Canonicalizer<'q> { // with a quantified version of its bound value; we // also have to shift *that* into the correct binder // depth. - let mut folder = (self, Shifter::new(binders)); + let mut folder = (FolderRef::new(self), Shifter::new(binders)); ty.fold_with(&mut folder, 0) } None => { diff --git a/src/solve/infer/canonicalize.rs b/src/solve/infer/canonicalize.rs --- a/src/solve/infer/canonicalize.rs +++ b/src/solve/infer/canonicalize.rs @@ -116,7 +116,7 @@ impl<'q> Folder for Canonicalizer<'q> { match self.table.probe_lifetime_var(var) { Some(l) => { debug!("fold_free_lifetime_var: {:?} mapped to {:?}", var, l); - let mut folder = (self, Shifter::new(binders)); + let mut folder = (FolderRef::new(self), Shifter::new(binders)); l.fold_with(&mut folder, 0) } None => { diff --git a/src/solve/infer/instantiate.rs b/src/solve/infer/instantiate.rs --- a/src/solve/infer/instantiate.rs +++ b/src/solve/infer/instantiate.rs @@ -39,12 +39,12 @@ struct Instantiator { vars: Vec<ParameterInferenceVariable>, } -/// Folder: when we encounter a free variable (of any kind) with index +/// When we encounter a free variable (of any kind) with index /// `i`, we want to map anything in the first N binders to /// `self.vars[i]`. Everything else stays intact, but we have to /// subtract `self.vars.len()` to account for the binders we are /// instantiating. -impl Folder for Instantiator { +impl FolderVar for Instantiator { fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty> { if depth < self.vars.len() { Ok(self.vars[depth].as_ref().ty().unwrap().to_ty().up_shift(binders)) diff --git a/src/solve/infer/unify.rs b/src/solve/infer/unify.rs --- a/src/solve/infer/unify.rs +++ b/src/solve/infer/unify.rs @@ -1,4 +1,5 @@ use cast::Cast; +use fold::Folder; use ir::*; use std::fmt::Debug; use std::sync::Arc; diff --git a/src/solve/infer/unify.rs b/src/solve/infer/unify.rs --- a/src/solve/infer/unify.rs +++ b/src/solve/infer/unify.rs @@ -232,7 +233,7 @@ impl<'t> Unifier<'t> { InferenceValue::Bound(_) => panic!("`unify_var_apply` invoked on bound var"), }; - let ty1 = OccursCheck::new(self, var, universe_index).check_ty(ty)?; + let ty1 = OccursCheck::new(self, var, universe_index).fold_ty(ty, 0)?; self.table.ty_unify.unify_var_value(var, InferenceValue::Bound(ty1.clone())).unwrap(); debug!("unify_var_ty: var {:?} set to {:?}", var, ty1); diff --git a/src/solve/infer/unify.rs b/src/solve/infer/unify.rs --- a/src/solve/infer/unify.rs +++ b/src/solve/infer/unify.rs @@ -334,155 +335,164 @@ impl<'u, 't> OccursCheck<'u, 't> { OccursCheck { unifier, binders: 0, var, universe_index } } - fn check_apply(&mut self, apply: &ApplicationTy) -> Result<ApplicationTy> { + fn check_parameter(&mut self, arg: &Parameter) -> Result<Parameter> { + let binders = self.binders; + match *arg { + ParameterKind::Ty(ref t) => + Ok(ParameterKind::Ty(self.fold_ty(t, binders)?)), + ParameterKind::Lifetime(ref lt) => + Ok(ParameterKind::Lifetime(self.fold_lifetime(lt, binders)?)), + } + } + + fn check_ty_apply(&mut self, apply: &ApplicationTy) -> Result<Ty> { let ApplicationTy { name, ref parameters } = *apply; self.universe_check(name.universe_index())?; let parameters = parameters.iter() .map(|p| self.check_parameter(p)) .collect::<Result<Vec<_>>>()?; - Ok(ApplicationTy { name, parameters }) + let at = ApplicationTy { name, parameters }; + Ok(Ty::Apply(at)) } - fn check_quantified(&mut self, quantified_ty: &QuantifiedTy) -> Result<QuantifiedTy> { + fn check_ty_forall(&mut self, quantified_ty: &QuantifiedTy) -> Result<Ty> { let QuantifiedTy { num_binders, ref ty } = *quantified_ty; self.binders += num_binders; - let ty = self.check_ty(ty)?; + let ty = self.fold_ty(ty, 0)?; self.binders -= num_binders; - Ok(QuantifiedTy { num_binders, ty }) + Ok(Ty::ForAll(Box::new(QuantifiedTy { num_binders, ty }))) } - fn check_parameter(&mut self, arg: &Parameter) -> Result<Parameter> { - match *arg { - ParameterKind::Ty(ref t) => Ok(ParameterKind::Ty(self.check_ty(t)?)), - ParameterKind::Lifetime(ref lt) => Ok(ParameterKind::Lifetime(self.check_lifetime(lt)?)), + fn universe_check(&mut self, + application_universe_index: UniverseIndex) + -> Result<()> { + debug!("universe_check({:?}, {:?})", + self.universe_index, + application_universe_index); + if self.universe_index < application_universe_index { + bail!("incompatible universes(universe_index={:?}, application_universe_index={:?})", + self.universe_index, + application_universe_index) + } else { + Ok(()) } } - fn check_lifetime(&mut self, lifetime: &Lifetime) -> Result<Lifetime> { - match *lifetime { - Lifetime::Var(depth) => { - if depth >= self.binders { - // a free existentially bound region; find the - // inference variable it corresponds to - let v = LifetimeInferenceVariable::from_depth(depth - self.binders); - match self.unifier.table.lifetime_unify.probe_value(v) { - InferenceValue::Unbound(ui) => { - if self.universe_index < ui { - // Scenario is like: - // - // exists<T> forall<'b> exists<'a> ?T = Foo<'a> - // - // where ?A is in universe 0 and `'b` is in universe 1. - // This is OK, if `'b` is promoted to universe 0. - self.unifier - .table - .lifetime_unify - .unify_var_value(v, InferenceValue::Unbound(self.universe_index)) - .unwrap(); - } - Ok(Lifetime::Var(depth)) - } - - InferenceValue::Bound(l) => { - Ok(l.up_shift(self.binders)) - } - } - } else { - // a bound region like `'a` in `for<'a> fn(&'a i32)` - Ok(Lifetime::Var(depth)) - } - } - Lifetime::ForAll(ui) => { - if self.universe_index < ui { - // Scenario is like: - // - // exists<T> forall<'b> ?T = Foo<'b> - // - // unlike with a type variable, this **might** be - // ok. Ultimately it depends on whether the - // `forall` also introduced relations to lifetimes - // nameable in T. To handle that, we introduce a - // fresh region variable `'x` in same universe as `T` - // and add a side-constraint that `'x = 'b`: - // - // exists<'x> forall<'b> ?T = Foo<'x>, where 'x = 'b - - let tick_x = self.unifier.table.new_lifetime_variable(self.universe_index); - self.unifier.push_lifetime_eq_constraint(tick_x.to_lifetime(), *lifetime); - Ok(tick_x.to_lifetime()) - } else { - // If the `ui` is higher than `self.universe_index`, then we can name - // this lifetime, no problem. - Ok(Lifetime::ForAll(ui)) - } - } - } - } + fn check_ty_var(&mut self, var: usize, binders: usize) -> Result<Ty> { + let v = TyInferenceVariable::from_depth(var - binders); + let ui = self.unifier.table.ty_unify.probe_value(v).unbound().unwrap(); - fn check_ty(&mut self, parameter: &Ty) -> Result<Ty> { - if let Some(n_parameter) = self.unifier.table.normalize_shallow(parameter) { - return self.check_ty(&n_parameter); + if self.unifier.table.ty_unify.unioned(v, self.var) { + bail!("cycle during unification"); } - match *parameter { - Ty::Apply(ref parameter_apply) => { - Ok(Ty::Apply(self.check_apply(parameter_apply)?)) - } + if self.universe_index < ui { + // Scenario is like: + // + // ?A = foo(?B) + // + // where ?A is in universe 0 and ?B is in universe 1. + // This is OK, if ?B is promoted to universe 0. + self.unifier + .table + .ty_unify + .unify_var_value(v, InferenceValue::Unbound(self.universe_index)) + .unwrap(); + } - Ty::ForAll(ref quantified_ty) => { - Ok(Ty::ForAll(Box::new(self.check_quantified(quantified_ty)?))) - } + Ok(Ty::Var(var)) + } - Ty::Var(depth) => { - let v = TyInferenceVariable::from_depth(depth - self.binders); - let ui = self.unifier.table.ty_unify.probe_value(v).unbound().unwrap(); + fn check_ty_projection(&mut self, proj: &ProjectionTy) -> Result<Ty> { + let ProjectionTy { associated_ty_id, ref parameters } = *proj; + + // FIXME(#6) -- this rejects constraints like + // `exists(A -> A = Item0<<A as Item1>::foo>)`, which + // is probably too conservative. + let parameters = + parameters.iter() + .map(|p| self.check_parameter(p)) + .collect::<Result<Vec<_>>>()?; + Ok(Ty::Projection(ProjectionTy { associated_ty_id, parameters })) + } - if self.unifier.table.ty_unify.unioned(v, self.var) { - bail!("cycle during unification"); + fn check_lt_var(&mut self, depth: usize, binders: usize) -> Result<Lifetime> { + if depth >= binders { + // a free existentially bound region; find the + // inference variable it corresponds to + let v = LifetimeInferenceVariable::from_depth(depth - binders); + match self.unifier.table.lifetime_unify.probe_value(v) { + InferenceValue::Unbound(ui) => { + if self.universe_index < ui { + // Scenario is like: + // + // exists<T> forall<'b> exists<'a> ?T = Foo<'a> + // + // where ?A is in universe 0 and `'b` is in universe 1. + // This is OK, if `'b` is promoted to universe 0. + self.unifier + .table + .lifetime_unify + .unify_var_value(v, InferenceValue::Unbound(self.universe_index)) + .unwrap(); + } + Ok(Lifetime::Var(depth)) } - if self.universe_index < ui { - // Scenario is like: - // - // ?A = foo(?B) - // - // where ?A is in universe 0 and ?B is in universe 1. - // This is OK, if ?B is promoted to universe 0. - self.unifier - .table - .ty_unify - .unify_var_value(v, InferenceValue::Unbound(self.universe_index)) - .unwrap(); + InferenceValue::Bound(l) => { + Ok(l.up_shift(binders)) } - - Ok(Ty::Var(depth)) - } - - Ty::Projection(ProjectionTy { associated_ty_id, ref parameters }) => { - // FIXME(#6) -- this rejects constraints like - // `exists(A -> A = Item0<<A as Item1>::foo>)`, which - // is probably too conservative. - let parameters = - parameters.iter() - .map(|p| self.check_parameter(p)) - .collect::<Result<Vec<_>>>()?; - Ok(Ty::Projection(ProjectionTy { associated_ty_id, parameters })) } + } else { + // a bound region like `'a` in `for<'a> fn(&'a i32)` + Ok(Lifetime::Var(depth)) } } - fn universe_check(&mut self, - application_universe_index: UniverseIndex) - -> Result<()> { - debug!("universe_check({:?}, {:?})", - self.universe_index, - application_universe_index); - if self.universe_index < application_universe_index { - bail!("incompatible universes(universe_index={:?}, application_universe_index={:?})", - self.universe_index, - application_universe_index) + fn check_lt_forall(&mut self, ui: UniverseIndex, lifetime: &Lifetime) -> Result<Lifetime> { + if self.universe_index < ui { + // Scenario is like: + // + // exists<T> forall<'b> ?T = Foo<'b> + // + // unlike with a type variable, this **might** be + // ok. Ultimately it depends on whether the + // `forall` also introduced relations to lifetimes + // nameable in T. To handle that, we introduce a + // fresh region variable `'x` in same universe as `T` + // and add a side-constraint that `'x = 'b`: + // + // exists<'x> forall<'b> ?T = Foo<'x>, where 'x = 'b + + let tick_x = self.unifier.table.new_lifetime_variable(self.universe_index); + self.unifier.push_lifetime_eq_constraint(tick_x.to_lifetime(), *lifetime); + Ok(tick_x.to_lifetime()) } else { - Ok(()) + // If the `ui` is higher than `self.universe_index`, then we can name + // this lifetime, no problem. + Ok(Lifetime::ForAll(ui)) + } + } +} + +impl<'u, 't> Folder for OccursCheck<'u, 't> { + fn fold_ty(&mut self, ty: &Ty, binders: usize) -> Result<Ty> { + if let Some(n_parameter) = self.unifier.table.normalize_shallow(ty) { + return self.fold_ty(&n_parameter, binders); + } + + match *ty { + Ty::Apply(ref parameter_apply) => self.check_ty_apply(parameter_apply), + Ty::ForAll(ref quantified_ty) => self.check_ty_forall(quantified_ty), + Ty::Projection(ref proj) => self.check_ty_projection(proj), + Ty::Var(depth) => self.check_ty_var(depth, binders), + } + } + + fn fold_lifetime(&mut self, lifetime: &Lifetime, binders: usize) -> Result<Lifetime> { + match *lifetime { + Lifetime::ForAll(ui) => self.check_lt_forall(ui, lifetime), + Lifetime::Var(depth) => self.check_lt_var(depth, binders), } } }
diff --git a/src/solve/infer/test.rs b/src/solve/infer/test.rs --- a/src/solve/infer/test.rs +++ b/src/solve/infer/test.rs @@ -65,7 +65,7 @@ struct Normalizer<'a> { table: &'a mut InferenceTable, } -impl<'q> Folder for Normalizer<'q> { +impl<'q> FolderVar for Normalizer<'q> { fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty> { assert_eq!(binders, 0); let var = TyInferenceVariable::from_depth(depth);
refactor occurs check into a folder The occurs check code in `src/solve/infer/unify.rs` (specifically, the methods defined on `OccursCheck`) follows a very folder-like pattern. Unfortunately, it can't quite use the `Folder` trait (as defined in `fold.rs`) because that trait only contains "callback methods" for processing free lifetime/type/krate variables. The occurs check needs to be able intercept all types, at least, as well as names that live in a universe and a few other things. We could add callback methods for those things to `Folder`. I imagine the resulting trait would look like: ```rust pub trait Folder { // Methods today: fn fold_free_var(&mut self, depth: usize, binders: usize) -> Result<Ty>; fn fold_free_lifetime_var(&mut self, depth: usize, binders: usize) -> Result<Lifetime>; fn fold_free_krate_var(&mut self, depth: usize, binders: usize) -> Result<Krate>; // Methods we need: fn fold_ty(&mut self, ty: &Ty, binders: usize) -> Result<Ty>; fn fold_lifetime(&mut self, lifetime: &Lifetime, binders: usize) -> Result<Lifetime>; } ``` One thing that I'm not crazy about is that `fold_ty` invokes `fold_free_var` etc, at least in its default incarnation, so putting them into the same trait might mean that if you override `fold_ty` you would not need the other methods. So it might be better to have `Folder` just include the higher-level methods (e.g., `fold_ty`) and then have a new trait `VarFolder` where we define a bridge impl like `impl<T: VarFolder> Folder for T`. Or something like that.
Working on it. @fabric-and-ink cool, feel free to come to gitter channel with questions, if any arise Slow but steady progress... :) I followed your suggestion to implement a bridge trait. Now I am stuck at connecting both kinds of folders at this point: ```rust fn fold_lifetime(&mut self, lifetime: &Lifetime, binders: usize) -> Result<Lifetime> { match *lifetime { Lifetime::Var(ref var) => self.fold_free_lifetime_var(*var, binders), Lifetime::ForAll(universe_index) => { unimplemented!(); }, } } ``` I don't know what a *universe* is in this context (see #51) and therefore don't now how to proceed. Any hints? :) @fabric-and-ink sorry, missed these comments! Maybe post your branch somewhere I can see it?
2017-08-05T18:28:06Z
0.1
2017-10-10T11:21:48Z
154020e4884e7b9fe41a93a6970cfff78783cdcc
[ "solve::infer::test::cycle_error", "solve::infer::test::cycle_indirect", "solve::infer::test::universe_promote_bad", "lower::test::type_parameter_bound", "solve::infer::test::universe_error_indirect_2", "lower::test::invalid_name", "solve::infer::test::universe_promote", "solve::infer::test::infer", "lower::test::type_parameter", "lower::test::two_blanket_impls", "solve::infer::test::universe_error_indirect_1", "lower::test::concrete_impl_and_blanket_impl", "lower::test::two_blanket_impls_open_ended", "lower::test::multiple_nonoverlapping_impls", "lower::test::nonoverlapping_assoc_types", "lower::test::two_impls_for_same_type", "lower::test::goal_quantifiers", "solve::infer::test::universe_error", "lower::test::overlapping_negative_impls", "lower::test::overlapping_negative_positive_impls", "lower::test::atc_accounting", "solve::infer::test::projection_eq", "lower::test::lower_success", "lower::test::negative_impl", "lower::test::not_trait", "lower::test::multiple_parameters", "solve::test::auto_trait_without_impls", "solve::infer::test::quantify_bound", "solve::infer::test::quantify_simple", "lower::test::overlapping_assoc_types", "lower::test::check_parameter_kinds", "solve::test::struct_wf", "lower::test::auto_trait", "lower::test::local_negative_reasoning_in_coherence", "lower::test::generic_vec_and_specific_vec", "solve::test::mixed_indices_normalize_application", "solve::test::mixed_indices_unify", "solve::test::overflow", "solve::test::unify_quantified_lifetimes", "solve::test::where_clause_trumps", "solve::test::deep_negation", "solve::test::cycle_no_solution", "solve::test::suggested_subst", "solve::test::normalize_under_binder", "lower::test::assoc_tys", "solve::test::deep_success", "solve::test::higher_ranked", "solve::test::elaborate_eq", "solve::test::cycle_unique_solution", "solve::test::negation_free_vars", "solve::test::inapplicable_assumption_does_not_shadow", "solve::test::normalize_rev_infer", "solve::test::region_equality", "solve::test::cycle_many_solutions", "solve::test::definite_guidance", "solve::test::deep_failure", "solve::test::ordering", "solve::test::mixed_indices_match_program", "solve::test::equality_binder", "solve::test::multiple_ambiguous_cycles", "solve::test::generic_trait", "solve::test::forall_equality", "solve::test::auto_trait_with_impls", "solve::test::elaborate_transitive", "solve::test::atc1", "solve::test::mixed_semantics", "solve::test::prove_infer", "solve::test::negation_quantifiers", "solve::test::prove_clone", "solve::test::simple_negation", "solve::test::normalize_basic", "solve::test::prove_forall", "solve::test::coinductive_semantics", "solve::test::elaborate_normalize", "solve::test::trait_wf" ]
[]
[]
[]
auto_2025-06-13
rust-lang/chalk
282
rust-lang__chalk-282
[ "275" ]
f9658ca506598fd711e89972b88721ce3afa5382
diff --git a/chalk-solve/src/infer/instantiate.rs b/chalk-solve/src/infer/instantiate.rs --- a/chalk-solve/src/infer/instantiate.rs +++ b/chalk-solve/src/infer/instantiate.rs @@ -58,35 +58,33 @@ impl InferenceTable { } /// Variant on `instantiate_in` that takes a `Binders<T>`. - #[allow(non_camel_case_types)] pub(crate) fn instantiate_binders_existentially<T>( &mut self, - arg: &impl BindersAndValue<Output = T>, + arg: impl IntoBindersAndValue<Value = T>, ) -> T::Result where T: Fold<ChalkIr>, { - let (binders, value) = arg.split(); + let (binders, value) = arg.into_binders_and_value(); let max_universe = self.max_universe; - self.instantiate_in(max_universe, binders.iter().cloned(), value) + self.instantiate_in(max_universe, binders, &value) } - #[allow(non_camel_case_types)] pub(crate) fn instantiate_binders_universally<T>( &mut self, - arg: &impl BindersAndValue<Output = T>, + arg: impl IntoBindersAndValue<Value = T>, ) -> T::Result where T: Fold<ChalkIr>, { - let (binders, value) = arg.split(); + let (binders, value) = arg.into_binders_and_value(); let ui = self.new_universe(); let parameters: Vec<_> = binders - .iter() + .into_iter() .enumerate() .map(|(idx, pk)| { let placeholder_idx = PlaceholderIndex { ui, idx }; - match *pk { + match pk { ParameterKind::Lifetime(()) => { let lt = placeholder_idx.to_lifetime::<ChalkIr>(); lt.cast() diff --git a/chalk-solve/src/infer/instantiate.rs b/chalk-solve/src/infer/instantiate.rs --- a/chalk-solve/src/infer/instantiate.rs +++ b/chalk-solve/src/infer/instantiate.rs @@ -95,28 +93,45 @@ impl InferenceTable { } }) .collect(); - Subst::apply(&parameters, value) + Subst::apply(&parameters, &value) } } -pub(crate) trait BindersAndValue { - type Output; +pub(crate) trait IntoBindersAndValue { + type Binders: IntoIterator<Item = ParameterKind<()>>; + type Value; - fn split(&self) -> (&[ParameterKind<()>], &Self::Output); + fn into_binders_and_value(self) -> (Self::Binders, Self::Value); } -impl<T> BindersAndValue for Binders<T> { - type Output = T; +impl<'a, T> IntoBindersAndValue for &'a Binders<T> { + type Binders = std::iter::Cloned<std::slice::Iter<'a, ParameterKind<()>>>; + type Value = &'a T; + + fn into_binders_and_value(self) -> (Self::Binders, Self::Value) { + (self.binders.iter().cloned(), &self.value) + } +} + +impl<'a> IntoBindersAndValue for &'a QuantifiedTy<ChalkIr> { + type Binders = std::iter::Map<std::ops::Range<usize>, fn(usize) -> chalk_ir::ParameterKind<()>>; + type Value = &'a Ty<ChalkIr>; + + fn into_binders_and_value(self) -> (Self::Binders, Self::Value) { + fn make_lifetime(_: usize) -> ParameterKind<()> { + ParameterKind::Lifetime(()) + } - fn split(&self) -> (&[ParameterKind<()>], &Self::Output) { - (&self.binders, &self.value) + let p: fn(usize) -> ParameterKind<()> = make_lifetime; + ((0..self.num_binders).map(p), &self.ty) } } -impl<'a, T> BindersAndValue for (&'a Vec<ParameterKind<()>>, &'a T) { - type Output = T; +impl<'a, T> IntoBindersAndValue for (&'a Vec<ParameterKind<()>>, &'a T) { + type Binders = std::iter::Cloned<std::slice::Iter<'a, ParameterKind<()>>>; + type Value = &'a T; - fn split(&self) -> (&[ParameterKind<()>], &Self::Output) { - (&self.0, &self.1) + fn into_binders_and_value(self) -> (Self::Binders, Self::Value) { + (self.0.iter().cloned(), &self.1) } } diff --git a/chalk-solve/src/infer/unify.rs b/chalk-solve/src/infer/unify.rs --- a/chalk-solve/src/infer/unify.rs +++ b/chalk-solve/src/infer/unify.rs @@ -1,3 +1,6 @@ +use super::var::*; +use super::*; +use crate::infer::instantiate::IntoBindersAndValue; use chalk_engine::fallible::*; use chalk_ir::cast::Cast; use chalk_ir::family::ChalkIr; diff --git a/chalk-solve/src/infer/unify.rs b/chalk-solve/src/infer/unify.rs --- a/chalk-solve/src/infer/unify.rs +++ b/chalk-solve/src/infer/unify.rs @@ -5,9 +8,7 @@ use chalk_ir::fold::{ DefaultFreeVarFolder, DefaultTypeFolder, Fold, InferenceFolder, PlaceholderFolder, }; use chalk_ir::zip::{Zip, Zipper}; - -use super::var::*; -use super::*; +use std::fmt::Debug; impl InferenceTable { pub(crate) fn unify<T>( diff --git a/chalk-solve/src/infer/unify.rs b/chalk-solve/src/infer/unify.rs --- a/chalk-solve/src/infer/unify.rs +++ b/chalk-solve/src/infer/unify.rs @@ -131,7 +132,7 @@ impl<'t> Unifier<'t> { // Unifying `forall<X> { T }` with some other forall type `forall<X> { U }` (&TyData::ForAll(ref quantified_ty1), &TyData::ForAll(ref quantified_ty2)) => { - self.unify_forall_tys(quantified_ty1, quantified_ty2) + self.unify_binders(&**quantified_ty1, &**quantified_ty2) } // Unifying `forall<X> { T }` with some other type `U` diff --git a/chalk-solve/src/infer/unify.rs b/chalk-solve/src/infer/unify.rs --- a/chalk-solve/src/infer/unify.rs +++ b/chalk-solve/src/infer/unify.rs @@ -200,43 +201,35 @@ impl<'t> Unifier<'t> { } } - fn unify_forall_tys( + fn unify_binders<T, R>( &mut self, - ty1: &QuantifiedTy<ChalkIr>, - ty2: &QuantifiedTy<ChalkIr>, - ) -> Fallible<()> { + a: impl IntoBindersAndValue<Value = T> + Copy + Debug, + b: impl IntoBindersAndValue<Value = T> + Copy + Debug, + ) -> Fallible<()> + where + T: Fold<ChalkIr, Result = R>, + R: Zip<ChalkIr> + Fold<ChalkIr, Result = R>, + { // for<'a...> T == for<'b...> U // // if: // // for<'a...> exists<'b...> T == U && // for<'b...> exists<'a...> T == U - // - // Here we only check for<'a...> exists<'b...> T == U, - // can someone smart comment why this is sufficient? - debug!("unify_forall_tys({:?}, {:?})", ty1, ty2); + debug!("unify_binders({:?}, {:?})", a, b); - let ui = self.table.new_universe(); - let lifetimes1: Vec<_> = (0..ty1.num_binders) - .map(|idx| { - LifetimeData::Placeholder(PlaceholderIndex { ui, idx }) - .intern() - .cast() - }) - .collect(); - - let max_universe = self.table.max_universe; - let lifetimes2: Vec<_> = (0..ty2.num_binders) - .map(|_| self.table.new_variable(max_universe).to_lifetime().cast()) - .collect(); - - let ty1 = ty1.substitute(&lifetimes1); - let ty2 = ty2.substitute(&lifetimes2); - debug!("unify_forall_tys: ty1 = {:?}", ty1); - debug!("unify_forall_tys: ty2 = {:?}", ty2); + { + let a_universal = self.table.instantiate_binders_universally(a); + let b_existential = self.table.instantiate_binders_existentially(b); + Zip::zip_with(self, &a_universal, &b_existential)?; + } - self.sub_unify(ty1, ty2) + { + let b_universal = self.table.instantiate_binders_universally(b); + let a_existential = self.table.instantiate_binders_existentially(a); + Zip::zip_with(self, &a_existential, &b_universal) + } } /// Unify an associated type projection `proj` like `<T as Trait>::Item` with some other diff --git a/chalk-solve/src/infer/unify.rs b/chalk-solve/src/infer/unify.rs --- a/chalk-solve/src/infer/unify.rs +++ b/chalk-solve/src/infer/unify.rs @@ -396,11 +389,22 @@ impl<'t> Zipper<ChalkIr> for Unifier<'t> { self.unify_lifetime_lifetime(a, b) } - fn zip_binders<T>(&mut self, _: &Binders<T>, _: &Binders<T>) -> Fallible<()> + fn zip_binders<T>(&mut self, a: &Binders<T>, b: &Binders<T>) -> Fallible<()> where T: Zip<ChalkIr> + Fold<ChalkIr, Result = T>, { - panic!("cannot unify things with binders (other than types)") + // The binders that appear in types (apart from quantified types, which are + // handled in `unify_ty`) appear as part of `dyn Trait` and `impl Trait` types. + // + // They come in two varieties: + // + // * The existential binder from `dyn Trait` / `impl Trait` + // (representing the hidden "self" type) + // * The `for<..>` binders from higher-ranked traits. + // + // In both cases we can use the same `unify_binders` routine. + + self.unify_binders(a, b) } }
diff --git /dev/null b/tests/test/existential_types.rs new file mode 100644 --- /dev/null +++ b/tests/test/existential_types.rs @@ -0,0 +1,198 @@ +//! Tests related to the implied bounds rules. + +use super::*; + +#[test] +fn dyn_Clone_is_Clone() { + test! { + program { + trait Clone { } + } + + goal { + dyn Clone: Clone + } yields { + "Unique; substitution []" + } + + goal { + impl Clone: Clone + } yields { + "Unique; substitution []" + } + } +} + +#[test] +fn dyn_Clone_is_not_Send() { + test! { + program { + trait Clone { } + #[auto] trait Send { } + } + + goal { + dyn Clone: Send + } yields { + "No possible solution" + } + } +} + +#[test] +fn dyn_Clone_Send_is_Send() { + test! { + program { + trait Clone { } + #[auto] trait Send { } + } + + goal { + (dyn Clone + Send): Send + } yields { + "Unique; substitution []" + } + } +} + +#[test] +fn dyn_Foo_Bar() { + test! { + program { + trait Foo<T> { } + + struct Bar { } + struct Baz { } + } + + goal { + dyn Foo<Bar>: Foo<Baz> + } yields { + "No possible solution" + } + + goal { + exists<T> { + dyn Foo<T>: Foo<Bar> + } + } yields { + "Unique; substitution [?0 := Bar], lifetime constraints []" + } + } +} + +#[test] +fn dyn_higher_ranked_type_arguments() { + test! { + program { + trait Foo<T> { } + trait Bar { } + + struct Ref<'a> { } + } + + goal { + forall<'static> { + dyn forall<'a> Foo<Ref<'a>>: Foo<Ref<'static>> + } + } yields { + "Unique; substitution [], lifetime constraints []" + } + + goal { + forall<'static> { + impl forall<'a> Foo<Ref<'a>>: Foo<Ref<'static>> + } + } yields { + "Unique; substitution [], lifetime constraints []" + } + + goal { + forall<'static> { + dyn forall<'a> Foo<Ref<'a>> + Bar: Foo<Ref<'static>> + } + } yields { + "Unique; substitution [], lifetime constraints []" + } + + goal { + forall<'static> { + impl forall<'a> Foo<Ref<'a>> + Bar: Foo<Ref<'static>> + } + } yields { + "Unique; substitution [], lifetime constraints []" + } + + goal { + dyn forall<'a> Foo<Ref<'a>> + Bar: Bar + } yields { + "Unique; substitution [], lifetime constraints []" + } + + goal { + forall<'static> { + forall<'a> { + dyn Foo<Ref<'static>>: Foo<Ref<'a>> + } + } + } yields { + // Note that this requires 'a == 'static, so it would be resolveable later on. + "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!2_0 == '!1_0 }]" + } + + goal { + forall<'static> { + forall<'a> { + impl Foo<Ref<'static>>: Foo<Ref<'a>> + } + } + } yields { + // Note that this requires 'a == 'static, so it would be resolveable later on. + "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!2_0 == '!1_0 }]" + } + } +} + +#[test] +fn dyn_binders_reverse() { + test! { + program { + trait Fn<T> { } + + trait Eq<A> { } + + struct Refs<'a, 'b> { } + + impl<A> Eq<A> for A { } + } + + // Note: these constraints are ultimately unresolveable (we + // have to show that 'a == 'b, basically) + goal { + dyn forall<'a, 'b> Fn<Refs<'a, 'b>>: Eq< + dyn forall<'c> Fn<Refs<'c, 'c>> + > + } yields { + "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!3_0 == '!3_1 }, InEnvironment { environment: Env([]), goal: '!6_0 == '!6_1 }]" + } + + // Note: these constraints are ultimately unresolveable (we + // have to show that 'a == 'b, basically) + goal { + dyn forall<'c> Fn<Refs<'c, 'c>>: Eq< + dyn forall<'a, 'b> Fn<Refs<'a, 'b>> + > + } yields { + "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!2_1 == '!2_0 }, InEnvironment { environment: Env([]), goal: '!5_1 == '!5_0 }]" + } + + // Note: ordering of parameters is reversed here, but that's no problem + goal { + dyn forall<'c, 'd> Fn<Refs<'d, 'c>>: Eq< + dyn forall<'a, 'b> Fn<Refs<'a, 'b>> + > + } yields { + "Unique; substitution [], lifetime constraints []" + } + } +} diff --git a/tests/test/mod.rs b/tests/test/mod.rs --- a/tests/test/mod.rs +++ b/tests/test/mod.rs @@ -1,3 +1,5 @@ +#![allow(non_snake_case)] + use chalk_integration::db::ChalkDatabase; use chalk_integration::query::LoweringDatabase; use chalk_ir; diff --git a/tests/test/mod.rs b/tests/test/mod.rs --- a/tests/test/mod.rs +++ b/tests/test/mod.rs @@ -200,6 +202,7 @@ mod auto_traits; mod coherence_goals; mod coinduction; mod cycle; +mod existential_types; mod implied_bounds; mod impls; mod negation; diff --git a/tests/test/unify.rs b/tests/test/unify.rs --- a/tests/test/unify.rs +++ b/tests/test/unify.rs @@ -71,9 +71,7 @@ fn forall_equality() { for<'a, 'b> Ref<'a, Ref<'b, Ref<'a, Unit>>>: Eq< for<'c, 'd> Ref<'c, Ref<'d, Ref<'d, Unit>>>> } yields { - "Unique; substitution [], lifetime constraints [ - InEnvironment { environment: Env([]), goal: '!1_1 == '!1_0 } - ]" + "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!1_1 == '!1_0 }, InEnvironment { environment: Env([]), goal: '!2_1 == '!2_0 }]" } } } diff --git a/tests/test/unify.rs b/tests/test/unify.rs --- a/tests/test/unify.rs +++ b/tests/test/unify.rs @@ -144,6 +142,27 @@ fn equality_binder() { } } +#[test] +fn equality_binder2() { + test! { + program { + struct Ref<'a, 'b> { } + } + + goal { + for<'b, 'c> Ref<'b, 'c> = for<'a> Ref<'a, 'a> + } yields { + "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!1_1 == '!1_0 }]" + } + + goal { + for<'a> Ref<'a, 'a> = for<'b, 'c> Ref<'b, 'c> + } yields { + "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!2_0 == '!2_1 }]" + } + } +} + #[test] fn mixed_indices_unify() { test! {
unification under binders is broken The current logic for unifying under binders as broken in two ways. First off, it's specific (rather unnecessarily) to `for<'a>` types, when it should be applicable to any zippable things. Secondly, it only tests one half of the necessary conditions! In fact, we've got a comment to this effect, somehow: https://github.com/rust-lang/chalk/blob/3ea7a60b73e202f2799efa8d711b633ed55b276a/chalk-solve/src/infer/unify.rs#L201-L209 What I think we should do is two things. First, we need to instantiate in *both* directions, as the comment suggests. We should be able to add a "sibling test" to this existing test https://github.com/rust-lang/chalk/blob/3ea7a60b73e202f2799efa8d711b633ed55b276a/src/test/unify.rs#L122-L123 that looks like this one: ```rust #[test] fn equality_binder2() { test! { program { struct Ref<'a, 'b> { } } goal { for<'b, 'c> Ref<'b, 'c> = for<'a> Ref<'a, 'a> } yields { "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!1_1 == '!1_0 }]" } goal { for<'a> Ref<'a, 'a> = for<'b, 'c> Ref<'b, 'c> } yields { "Unique; substitution [], lifetime constraints [InEnvironment { environment: Env([]), goal: '!1_1 == '!1_0 }]" } } } ``` Right now, the second test fails for me -- I get `lifetime constraints []`, which is clearly wrong. We want to be generating constraints like the ones above, which are in fact not reconcilable. (Those constraints say "this is equal if `'b == 'c`", which cannot be proven.) Second, move this logic to `zip_binders` and remove [`unify_forall_tys`](https://github.com/rust-lang/chalk/blob/3ea7a60b73e202f2799efa8d711b633ed55b276a/chalk-solve/src/infer/unify.rs#L196-L200) (or make it just invoke `zip` on its arguments).: https://github.com/rust-lang/chalk/blob/3ea7a60b73e202f2799efa8d711b633ed55b276a/chalk-solve/src/infer/unify.rs#L384-L389 This should then allow us to support zipping the binders and things inside `dyn` and `impl` types using the same routines. Finally, third, if we like, we could optimize the case where you are zipping two `forall` with a **single** argument -- in that case, we could just instantiate with a placeholder on both sides and skip the existentials, I believe. But that's just an optimization.
2019-11-11T22:36:17Z
0.1
2019-11-14T10:30:40Z
154020e4884e7b9fe41a93a6970cfff78783cdcc
[ "test::existential_types::dyn_Clone_Send_is_Send", "test::existential_types::dyn_Foo_Bar", "test::existential_types::dyn_Clone_is_Clone", "test::existential_types::dyn_binders_reverse", "test::unify::equality_binder2", "test::unify::forall_equality", "test::existential_types::dyn_higher_ranked_type_arguments" ]
[ "lowering::fundamental_multiple_type_parameters", "lowering::invalid_name", "lowering::gat_higher_ranked_bound", "lowering::type_parameter", "lowering::lower_success", "lowering::type_parameter_bound", "test::coherence::multiple_nonoverlapping_impls", "lowering::upstream_items", "test::coherence::generic_vec_and_specific_vec", "test::coherence::concrete_impl_and_blanket_impl", "lowering::not_trait", "test::coherence::two_impls_for_same_type", "test::coherence::overlapping_negative_positive_impls", "test::coherence::multiple_parameters", "test::coherence::downstream_impl_of_fundamental_43355", "test::coherence::two_blanket_impls", "test::coherence::overlapping_negative_impls", "test::coherence::two_blanket_impls_open_ended", "test::coherence::local_negative_reasoning_in_coherence", "test::coherence::overlapping_assoc_types_error", "lowering::assoc_tys", "test::coherence::overlapping_assoc_types", "test::coherence::nonoverlapping_assoc_types", "lowering::goal_quantifiers", "lowering::atc_accounting", "lowering::gat_parse", "test::existential_types::dyn_Clone_is_not_Send", "test::coherence::fundamental_traits", "test::cycle::cycle_many_solutions", "lowering::negative_impl", "test::cycle::overflow_universe", "test::cycle::cycle_no_solution", "test::impls::inapplicable_assumption_does_not_shadow", "test::impls::deep_success", "test::cycle::cycle_unique_solution", "test::impls::definite_guidance", "test::implied_bounds::implied_bounds", "test::negation::negation_free_vars", "test::impls::normalize_rev_infer", "test::cycle::multiple_ambiguous_cycles", "test::impls::ordering", "test::impls::where_clause_trumps", "test::impls::normalize_rev_infer_gat", "test::impls::higher_ranked", "test::projection::forall_projection", "test::cycle::inner_cycle", "test::coinduction::mixed_semantics", "test::projection::normalize_gat1", "test::projection::normalize_gat_with_higher_ranked_trait_bound", "test::cycle::overflow", "lowering::auto_trait", "test::impls::deep_failure", "test::slg::example_2_2_EWFS", "lowering::duplicate_parameters", "test::auto_traits::auto_trait_without_impls", "test::implied_bounds::implied_from_env", "test::negation::deep_negation", "test::implied_bounds::higher_ranked_implied_bounds", "test::slg::auto_traits_flounder", "test::slg::cached_answers_1", "test::slg::example_2_3_EWFS", "test::slg::example_3_3_EWFS", "test::projection::projection_from_env_slow", "test::projection::normalize_gat_with_where_clause", "test::slg::cached_answers_2", "test::slg::cached_answers_3", "test::slg::basic_region_constraint_from_positive_impl", "test::projection::gat_unify_with_implied_wc", "test::slg::basic", "test::slg::example_2_1_EWFS", "test::impls::generic_trait", "test::slg::negative_loop", "test::slg::contradiction", "test::projection::projection_from_env_a", "test::unify::equality_binder", "test::slg::coinductive_unsound2", "test::impls::partial_overlap_3", "test::negation::negation_quantifiers", "test::unify::mixed_indices_unify", "test::slg::breadth_first", "test::impls::prove_infer", "test::unify::mixed_indices_match_program", "test::slg::flounder", "test::slg::coinductive_unsound1", "test::slg::non_enumerable_traits_indirect", "test::projection::projection_equality", "test::projection::normalize_gat2", "test::auto_traits::auto_trait_with_impls", "test::unify::mixed_indices_normalize_application", "test::coinduction::coinductive_semantics", "test::slg::subgoal_cycle_inhabited", "test::wf_lowering::ill_formed_trait_decl", "test::slg::only_draw_so_many", "test::wf_lowering::cyclic_wf_requirements", "test::wf_lowering::ill_formed_assoc_ty", "test::slg::negative_answer_ambiguous", "test::impls::partial_overlap_2", "test::impls::prove_clone", "test::wf_lowering::ill_formed_ty_decl", "test::slg::only_draw_so_many_blow_up", "test::wf_lowering::higher_ranked_trait_bound_on_gat", "test::slg::negative_reorder", "test::wf_lowering::implied_bounds_on_ty_decl", "test::projection::normalize_under_binder_multi", "lowering::check_parameter_kinds", "test::wf_lowering::well_formed_trait_decl", "test::impls::clauses_in_if_goals", "test::unify::mixed_indices_normalize_gat_application", "test::slg::non_enumerable_traits_reorder", "test::slg::non_enumerable_traits_double", "test::wf_lowering::implied_bounds", "test::projection::normalize_into_iterator", "test::projection::forall_projection_gat", "test::projection::normalize_gat_with_where_clause2", "test::wf_lowering::assoc_type_recursive_bound", "test::unify::unify_quantified_lifetimes", "test::wf_goals::recursive_where_clause_on_type", "test::unify::region_equality", "test::wf_lowering::higher_ranked_trait_bounds", "test::wf_lowering::bound_in_header_from_env", "test::slg::infinite_recursion", "test::slg::non_enumerable_traits_direct", "test::implied_bounds::gat_implied_bounds", "test::unify::quantified_types", "test::wf_lowering::higher_ranked_inline_bound_on_gat", "test::wf_lowering::mixed_indices_check_projection_bounds", "test::wf_lowering::wf_requiremements_for_projection", "test::wf_lowering::generic_projection_where_clause", "test::wf_lowering::ill_formed_type_in_header", "test::wf_lowering::generic_projection_bound", "test::negation::simple_negation", "test::projection::normalize_under_binder", "test::wf_lowering::mixed_indices_check_generic_projection_bounds", "test::wf_lowering::cyclic_traits", "test::wf_goals::struct_wf", "test::coherence_goals::local_and_upstream_types", "test::projection::normalize_basic", "test::slg::subgoal_cycle_uninhabited", "test::impls::prove_forall", "test::wf_lowering::higher_ranked_cyclic_requirements", "test::impls::suggested_subst", "test::coherence::orphan_check", "test::coherence_goals::is_fully_visible", "test::slg::subgoal_abstraction", "test::coherence_goals::local_impl_allowed_for_traits", "test::coherence_goals::fundamental_types" ]
[]
[]
auto_2025-06-13
rust-lang/chalk
237
rust-lang__chalk-237
[ "235", "235" ]
c9314e425e49969c33cabcb8fac7da6eac3c5073
diff --git a/chalk-solve/src/clauses/program_clauses.rs b/chalk-solve/src/clauses/program_clauses.rs --- a/chalk-solve/src/clauses/program_clauses.rs +++ b/chalk-solve/src/clauses/program_clauses.rs @@ -52,7 +52,7 @@ impl ToProgramClauses for AssociatedTyValue { /// /// Then for the following impl: /// ```notrust - /// impl<T> Iterable for Vec<T> { + /// impl<T> Iterable for Vec<T> where T: Clone { /// type IntoIter<'a> = Iter<'a, T>; /// } /// ``` diff --git a/chalk-solve/src/clauses/program_clauses.rs b/chalk-solve/src/clauses/program_clauses.rs --- a/chalk-solve/src/clauses/program_clauses.rs +++ b/chalk-solve/src/clauses/program_clauses.rs @@ -63,7 +63,7 @@ impl ToProgramClauses for AssociatedTyValue { /// -- Rule Normalize-From-Impl /// forall<'a, T> { /// Normalize(<Vec<T> as Iterable>::IntoIter<'a> -> Iter<'a, T>>) :- - /// Implemented(Vec<T>: Iterable), // (1) + /// Implemented(T: Clone), // (1) /// Implemented(Iter<'a, T>: 'a). // (2) /// } /// ``` diff --git a/chalk-solve/src/clauses/program_clauses.rs b/chalk-solve/src/clauses/program_clauses.rs --- a/chalk-solve/src/clauses/program_clauses.rs +++ b/chalk-solve/src/clauses/program_clauses.rs @@ -109,18 +109,24 @@ impl ToProgramClauses for AssociatedTyValue { // Assemble the full list of conditions for projection to be valid. // This comes in two parts, marked as (1) and (2) in doc above: // - // 1. require that the trait is implemented + // 1. require that the where clauses from the impl apply // 2. any where-clauses from the `type` declaration in the trait: the // parameters must be substituted with those of the impl - let where_clauses = associated_ty + let assoc_ty_where_clauses = associated_ty .where_clauses .iter() .map(|wc| Subst::apply(&all_parameters, wc)) .casted(); - let conditions: Vec<Goal> = where_clauses - .chain(Some(impl_trait_ref.clone().cast())) - .collect(); + let impl_where_clauses = impl_datum + .binders + .value + .where_clauses + .iter() + .map(|wc| wc.shifted_in(self.value.len())) + .casted(); + + let conditions: Vec<Goal> = assoc_ty_where_clauses.chain(impl_where_clauses).collect(); // Bound parameters + `Self` type of the trait-ref let parameters: Vec<_> = {
diff --git a/src/test.rs b/src/test.rs --- a/src/test.rs +++ b/src/test.rs @@ -549,6 +549,62 @@ fn normalize_basic() { } } +#[test] +fn normalize_into_iterator() { + test! { + program { + trait IntoIterator { type Item; } + trait Iterator { type Item; } + struct Vec<T> { } + struct u32 { } + impl<T> IntoIterator for Vec<T> { + type Item = T; + } + impl<T> IntoIterator for T where T: Iterator { + type Item = <T as Iterator>::Item; + } + } + + goal { + forall<T> { + exists<U> { + Normalize(<Vec<T> as IntoIterator>::Item -> U) + } + } + } yields { + "Unique" + } + } +} + +#[ignore] // currently failing +#[test] +fn projection_equality() { + test! { + program { + trait Trait1 { + type Type; + } + trait Trait2<T> { } + impl<T, U> Trait2<T> for U where U: Trait1<Type = T> {} + + struct u32 {} + struct S {} + impl Trait1 for S { + type Type = u32; + } + } + + goal { + exists<U> { + S: Trait2<U> + } + } yields { + "Unique" + } + } +} + #[test] fn normalize_gat1() { test! {
Normalization doesn't take into account which impl actually applied Split off from #234: ```rust #[test] fn normalize_into_iterator() { test! { program { trait IntoIterator { type Item; } trait Iterator { type Item; } struct Vec<T> { } struct u32 { } impl<T> IntoIterator for Vec<T> { type Item = T; } impl<T> IntoIterator for T where T: Iterator { type Item = <T as Iterator>::Item; } } goal { forall<T> { exists<U> { Normalize(<Vec<T> as IntoIterator>::Item -> U) } } } yields { "Unique" } } } ``` I'd expect this test to pass because the second IntoIterator impl should not have any effect at all here, but the result is instead ambiguous, because apparently the Normalize rule from the second impl applies too, because it just checks that the type implements IntoIterator, and not that it does so with that impl. That seems really wrong. Niko: > We wind up with these two program clauses: ``` for<type> Normalize(<Vec<^0> as IntoIterator>::Item -> ^0) :- Implemented(Vec<^0>: IntoIterator) for<type> Normalize(<^0 as IntoIterator>::Item -> <^0 as Iterator>::Item) :- Implemented(^0: IntoIterator) ``` > I think what I'd expect is something like ``` for<type> Normalize(<Vec<^0> as IntoIterator>::Item -> ^0) for<type> Normalize(<^0 as IntoIterator>::Item -> <^0 as Iterator>::Item) :- Implemented(^0: Iterator) ``` > In particular, inlining the where-clauses and conditions of the impl into the rule. @scalexm -- do you recall why we set things up the way we did? scalexm: > I don’t think there’s any good reason why the where clauses are not inlined. > I probably thought it was equivalent because there would be a « perfect match » with the impl, but of course two impls can have a non-empty intersection with respect to their receiver type. Normalization doesn't take into account which impl actually applied Split off from #234: ```rust #[test] fn normalize_into_iterator() { test! { program { trait IntoIterator { type Item; } trait Iterator { type Item; } struct Vec<T> { } struct u32 { } impl<T> IntoIterator for Vec<T> { type Item = T; } impl<T> IntoIterator for T where T: Iterator { type Item = <T as Iterator>::Item; } } goal { forall<T> { exists<U> { Normalize(<Vec<T> as IntoIterator>::Item -> U) } } } yields { "Unique" } } } ``` I'd expect this test to pass because the second IntoIterator impl should not have any effect at all here, but the result is instead ambiguous, because apparently the Normalize rule from the second impl applies too, because it just checks that the type implements IntoIterator, and not that it does so with that impl. That seems really wrong. Niko: > We wind up with these two program clauses: ``` for<type> Normalize(<Vec<^0> as IntoIterator>::Item -> ^0) :- Implemented(Vec<^0>: IntoIterator) for<type> Normalize(<^0 as IntoIterator>::Item -> <^0 as Iterator>::Item) :- Implemented(^0: IntoIterator) ``` > I think what I'd expect is something like ``` for<type> Normalize(<Vec<^0> as IntoIterator>::Item -> ^0) for<type> Normalize(<^0 as IntoIterator>::Item -> <^0 as Iterator>::Item) :- Implemented(^0: Iterator) ``` > In particular, inlining the where-clauses and conditions of the impl into the rule. @scalexm -- do you recall why we set things up the way we did? scalexm: > I don’t think there’s any good reason why the where clauses are not inlined. > I probably thought it was equivalent because there would be a « perfect match » with the impl, but of course two impls can have a non-empty intersection with respect to their receiver type.
2019-09-03T11:54:34Z
0.1
2019-09-03T22:39:44Z
154020e4884e7b9fe41a93a6970cfff78783cdcc
[ "test::normalize_into_iterator" ]
[ "lowering::test::invalid_name", "lowering::test::lower_success", "test::coherence::concrete_impl_and_blanket_impl", "lowering::test::fundamental_multiple_type_parameters", "lowering::test::upstream_items", "lowering::test::not_trait", "lowering::test::gat_higher_ranked_bound", "lowering::test::type_parameter_bound", "lowering::test::type_parameter", "test::coherence::two_impls_for_same_type", "lowering::test::assoc_tys", "test::coherence::multiple_parameters", "test::coherence::multiple_nonoverlapping_impls", "test::coherence::two_blanket_impls", "test::coherence::local_negative_reasoning_in_coherence", "lowering::test::goal_quantifiers", "test::coherence::overlapping_assoc_types_error", "test::coherence::generic_vec_and_specific_vec", "test::coherence::two_blanket_impls_open_ended", "test::coherence::overlapping_negative_positive_impls", "lowering::test::gat_parse", "lowering::test::atc_accounting", "test::coherence::overlapping_negative_impls", "test::coherence::nonoverlapping_assoc_types", "test::coherence::fundamental_traits", "lowering::test::auto_trait", "test::definite_guidance", "test::cycle_no_solution", "test::cycle_many_solutions", "test::coherence::downstream_impl_of_fundamental_43355", "test::coherence::overlapping_assoc_types", "test::overflow", "test::cycle_unique_solution", "lowering::test::negative_impl", "test::overflow_universe", "test::deep_failure", "lowering::test::duplicate_parameters", "test::partial_overlap_3", "test::forall_equality", "test::projection_from_env_a", "test::auto_trait_without_impls", "test::negation_free_vars", "test::equality_binder", "test::higher_ranked", "test::inapplicable_assumption_does_not_shadow", "test::implied_bounds", "test::deep_negation", "test::recursive_where_clause_on_type", "test::forall_projection", "test::deep_success", "test::slg::basic", "test::slg::cached_answers_3", "test::projection_from_env_slow", "test::inner_cycle", "test::mixed_indices_match_program", "test::slg::negative_answer_delayed_literal", "test::slg::contradiction", "test::auto_trait_with_impls", "test::slg::flounder", "test::mixed_indices_normalize_gat_application", "test::generic_trait", "test::slg::only_draw_so_many_blow_up", "test::normalize_rev_infer", "lowering::test::check_parameter_kinds", "test::slg::infinite_recursion", "test::partial_overlap_2", "test::clauses_in_if_goals", "test::higher_ranked_implied_bounds", "test::ordering", "test::wf::bound_in_header_from_env", "test::mixed_indices_unify", "test::inscope", "test::multiple_ambiguous_cycles", "test::wf::higher_ranked_trait_bound_on_gat", "test::normalize_gat1", "test::gat_unify_with_implied_wc", "test::mixed_indices_normalize_application", "test::wf::ill_formed_trait_decl", "test::mixed_semantics", "test::implied_from_env", "test::slg::negative_reorder", "test::prove_clone", "test::normalize_gat_with_where_clause", "test::coinductive_semantics", "test::wf::cyclic_wf_requirements", "test::negation_quantifiers", "test::slg::non_enumerable_traits_indirect", "test::wf::implied_bounds_on_ty_decl", "test::slg::subgoal_cycle_inhabited", "test::slg::only_draw_so_many", "test::wf::ill_formed_assoc_ty", "test::wf::ill_formed_ty_decl", "test::normalize_gat_with_where_clause2", "test::unify_quantified_lifetimes", "test::slg::cached_answers_2", "test::wf::implied_bounds", "test::wf::well_formed_trait_decl", "test::gat_implied_bounds", "test::unselected_projection_a", "test::normalize_rev_infer_gat", "test::forall_projection_gat", "test::wf::assoc_type_recursive_bound", "test::normalize_gat2", "test::slg::auto_traits_flounder", "test::normalize_gat_with_higher_ranked_trait_bound", "test::slg::basic_region_constraint_from_positive_impl", "test::unselected_projection_with_parametric_trait", "test::slg::cached_answers_1", "test::slg::negative_loop", "test::slg::breadth_first", "test::wf::higher_ranked_inline_bound_on_gat", "test::slg::example_2_2_EWFS", "test::slg::example_2_3_EWFS", "test::where_clause_trumps", "test::slg::example_2_1_EWFS", "test::wf::generic_projection_bound", "test::unselected_projection_with_gat", "test::slg::example_3_3_EWFS", "test::wf::generic_projection_where_clause", "test::struct_wf", "test::wf::wf_requiremements_for_projection", "test::slg::non_enumerable_traits_double", "test::wf::ill_formed_type_in_header", "test::wf::mixed_indices_check_generic_projection_bounds", "test::wf::higher_ranked_trait_bounds", "test::wf::cyclic_traits", "test::wf::mixed_indices_check_projection_bounds", "test::prove_infer", "test::quantified_types", "test::region_equality", "test::slg::non_enumerable_traits_reorder", "test::wf::higher_ranked_cyclic_requirements", "test::slg::non_enumerable_traits_direct", "test::simple_negation", "test::slg::subgoal_cycle_uninhabited", "test::normalize_basic", "test::normalize_under_binder", "test::local_and_upstream_types", "test::prove_forall", "test::suggested_subst", "test::coherence::orphan_check", "test::slg::subgoal_abstraction", "test::is_fully_visible", "test::fundamental_types", "test::local_impl_allowed_for_traits" ]
[]
[]
auto_2025-06-13
rust-lang/chalk
780
rust-lang__chalk-780
[ "777" ]
a0e4882f93436fe38a4940ea92c4745121878488
diff --git a/chalk-solve/src/clauses.rs b/chalk-solve/src/clauses.rs --- a/chalk-solve/src/clauses.rs +++ b/chalk-solve/src/clauses.rs @@ -624,7 +624,10 @@ pub fn program_clauses_that_could_match<I: Interner>( if let Some(well_known) = trait_datum.well_known { builtin_traits::add_builtin_assoc_program_clauses( - db, builder, well_known, self_ty, + db, + builder, + well_known, + self_ty.clone(), )?; } diff --git a/chalk-solve/src/clauses.rs b/chalk-solve/src/clauses.rs --- a/chalk-solve/src/clauses.rs +++ b/chalk-solve/src/clauses.rs @@ -645,6 +648,18 @@ pub fn program_clauses_that_could_match<I: Interner>( proj.associated_ty_id, ); } + + // When `self_ty` is dyn type or opaque type, there may be associated type bounds + // for which we generate `Normalize` clauses. + match self_ty.kind(interner) { + // FIXME: see the fixme for the analogous code for Implemented goals. + TyKind::Dyn(_) => dyn_ty::build_dyn_self_ty_clauses(db, builder, self_ty), + TyKind::OpaqueType(id, _) => { + db.opaque_ty_data(*id) + .to_program_clauses(builder, environment); + } + _ => {} + } } AliasTy::Opaque(_) => (), }, diff --git a/chalk-solve/src/clauses/super_traits.rs b/chalk-solve/src/clauses/super_traits.rs --- a/chalk-solve/src/clauses/super_traits.rs +++ b/chalk-solve/src/clauses/super_traits.rs @@ -1,34 +1,43 @@ +use itertools::{Either, Itertools}; use rustc_hash::FxHashSet; use super::builder::ClauseBuilder; -use crate::RustIrDatabase; +use crate::{split::Split, RustIrDatabase}; use chalk_ir::{ - fold::shift::Shift, interner::Interner, Binders, BoundVar, DebruijnIndex, TraitId, TraitRef, - WhereClause, + fold::shift::Shift, interner::Interner, AliasEq, AliasTy, Binders, BoundVar, DebruijnIndex, + Normalize, ProjectionTy, TraitId, TraitRef, Ty, WhereClause, }; -/// Generate `Implemented` clauses for `dyn Trait` and opaque types. We need to generate -/// `Implemented` clauses for all super traits, and for each trait we require -/// its where clauses. (See #203.) +/// Generate `Implemented` and `Normalize` clauses for `dyn Trait` and opaque types. +/// We need to generate those clauses for all super traits, and for each trait we +/// require its where clauses. (See #203) pub(super) fn push_trait_super_clauses<I: Interner>( db: &dyn RustIrDatabase<I>, builder: &mut ClauseBuilder<'_, I>, trait_ref: TraitRef<I>, ) { let interner = db.interner(); - // Given`trait SuperTrait: WC`, which is a super trait + // Given `trait SuperTrait: WC`, which is a super trait // of `Trait` (including actually just being the same trait); // then we want to push // - for `dyn Trait`: // `Implemented(dyn Trait: SuperTrait) :- WC`. // - for placeholder `!T` of `opaque type T: Trait = HiddenTy`: // `Implemented(!T: SuperTrait) :- WC` - - let super_trait_refs = + // + // When `SuperTrait` has `AliasEq` bounds like `trait SuperTrait: AnotherTrait<Assoc = Ty>`, + // we also push + // - for `dyn Trait`: + // `Normalize(<dyn Trait as AnotherTrait>::Assoc -> Ty) :- AssocWC, WC` + // - for placeholder `!T` of `opaque type T: Trait = HiddenTy`: + // `Normalize(<!T as AnotherTrait>::Assoc -> Ty) :- AssocWC, WC` + // where `WC` and `AssocWC` are the where clauses for `AnotherTrait` and `AnotherTrait::Assoc` + // respectively. + let (super_trait_refs, super_trait_proj) = super_traits(db, trait_ref.trait_id).substitute(interner, &trait_ref.substitution); for q_super_trait_ref in super_trait_refs { - builder.push_binders(q_super_trait_ref.clone(), |builder, super_trait_ref| { + builder.push_binders(q_super_trait_ref, |builder, super_trait_ref| { let trait_datum = db.trait_datum(super_trait_ref.trait_id); let wc = trait_datum .where_clauses() diff --git a/chalk-solve/src/clauses/super_traits.rs b/chalk-solve/src/clauses/super_traits.rs --- a/chalk-solve/src/clauses/super_traits.rs +++ b/chalk-solve/src/clauses/super_traits.rs @@ -37,12 +46,40 @@ pub(super) fn push_trait_super_clauses<I: Interner>( builder.push_clause(super_trait_ref, wc); }); } + + for q_super_trait_proj in super_trait_proj { + builder.push_binders(q_super_trait_proj, |builder, (proj, ty)| { + let assoc_ty_datum = db.associated_ty_data(proj.associated_ty_id); + let trait_datum = db.trait_datum(assoc_ty_datum.trait_id); + let assoc_wc = assoc_ty_datum + .binders + .map_ref(|b| &b.where_clauses) + .into_iter() + .map(|wc| wc.cloned().substitute(interner, &proj.substitution)); + + let impl_params = db.trait_parameters_from_projection(&proj); + let impl_wc = trait_datum + .where_clauses() + .into_iter() + .map(|wc| wc.cloned().substitute(interner, impl_params)); + builder.push_clause( + Normalize { + alias: AliasTy::Projection(proj.clone()), + ty, + }, + impl_wc.chain(assoc_wc), + ); + }); + } } -pub fn super_traits<I: Interner>( +fn super_traits<I: Interner>( db: &dyn RustIrDatabase<I>, trait_id: TraitId<I>, -) -> Binders<Vec<Binders<TraitRef<I>>>> { +) -> Binders<( + Vec<Binders<TraitRef<I>>>, + Vec<Binders<(ProjectionTy<I>, Ty<I>)>>, +)> { let interner = db.interner(); let mut seen_traits = FxHashSet::default(); let trait_datum = db.trait_datum(trait_id); diff --git a/chalk-solve/src/clauses/super_traits.rs b/chalk-solve/src/clauses/super_traits.rs --- a/chalk-solve/src/clauses/super_traits.rs +++ b/chalk-solve/src/clauses/super_traits.rs @@ -57,13 +94,21 @@ pub fn super_traits<I: Interner>( }, ); let mut trait_refs = Vec::new(); - go(db, trait_ref, &mut seen_traits, &mut trait_refs); + let mut aliases = Vec::new(); + go( + db, + trait_ref, + &mut seen_traits, + &mut trait_refs, + &mut aliases, + ); fn go<I: Interner>( db: &dyn RustIrDatabase<I>, trait_ref: Binders<TraitRef<I>>, seen_traits: &mut FxHashSet<TraitId<I>>, trait_refs: &mut Vec<Binders<TraitRef<I>>>, + aliases: &mut Vec<Binders<(ProjectionTy<I>, Ty<I>)>>, ) { let interner = db.interner(); let trait_id = trait_ref.skip_binders().trait_id; diff --git a/chalk-solve/src/clauses/super_traits.rs b/chalk-solve/src/clauses/super_traits.rs --- a/chalk-solve/src/clauses/super_traits.rs +++ b/chalk-solve/src/clauses/super_traits.rs @@ -73,32 +118,39 @@ pub fn super_traits<I: Interner>( } trait_refs.push(trait_ref.clone()); let trait_datum = db.trait_datum(trait_id); - let super_trait_refs = trait_datum + let (super_trait_refs, super_trait_projs): (Vec<_>, Vec<_>) = trait_datum .binders .map_ref(|td| { td.where_clauses .iter() - .filter_map(|qwc| { - qwc.as_ref().filter_map(|wc| match wc { - WhereClause::Implemented(tr) => { - let self_ty = tr.self_type_parameter(db.interner()); + .filter(|qwc| { + let trait_ref = match qwc.skip_binders() { + WhereClause::Implemented(tr) => tr.clone(), + WhereClause::AliasEq(AliasEq { + alias: AliasTy::Projection(p), + .. + }) => db.trait_ref_from_projection(p), + _ => return false, + }; + // We're looking for where clauses of the form + // `Self: Trait` or `<Self as Trait>::Assoc`. `Self` is + // ^1.0 because we're one binder in. + trait_ref.self_type_parameter(interner).bound_var(interner) + == Some(BoundVar::new(DebruijnIndex::ONE, 0)) + }) + .cloned() + .partition_map(|qwc| { + let (value, binders) = qwc.into_value_and_skipped_binders(); - // We're looking for where clauses - // of the form `Self: Trait`. That's - // ^1.0 because we're one binder in. - if self_ty.bound_var(db.interner()) - != Some(BoundVar::new(DebruijnIndex::ONE, 0)) - { - return None; - } - Some(tr.clone()) - } - WhereClause::AliasEq(_) => None, - WhereClause::LifetimeOutlives(..) => None, - WhereClause::TypeOutlives(..) => None, - }) + match value { + WhereClause::Implemented(tr) => Either::Left(Binders::new(binders, tr)), + WhereClause::AliasEq(AliasEq { + alias: AliasTy::Projection(p), + ty, + }) => Either::Right(Binders::new(binders, (p, ty))), + _ => unreachable!(), + } }) - .collect::<Vec<_>>() }) // we skip binders on the trait_ref here and add them to the binders // on the trait ref in the loop below. We could probably avoid this if diff --git a/chalk-solve/src/clauses/super_traits.rs b/chalk-solve/src/clauses/super_traits.rs --- a/chalk-solve/src/clauses/super_traits.rs +++ b/chalk-solve/src/clauses/super_traits.rs @@ -109,10 +161,15 @@ pub fn super_traits<I: Interner>( // binders of super_trait_ref. let actual_binders = Binders::new(trait_ref.binders.clone(), q_super_trait_ref); let q_super_trait_ref = actual_binders.fuse_binders(interner); - go(db, q_super_trait_ref, seen_traits, trait_refs); + go(db, q_super_trait_ref, seen_traits, trait_refs, aliases); + } + for q_super_trait_proj in super_trait_projs { + let actual_binders = Binders::new(trait_ref.binders.clone(), q_super_trait_proj); + let q_super_trait_proj = actual_binders.fuse_binders(interner); + aliases.push(q_super_trait_proj); } seen_traits.remove(&trait_id); } - Binders::new(trait_datum.binders.binders.clone(), trait_refs) + Binders::new(trait_datum.binders.binders.clone(), (trait_refs, aliases)) }
diff --git a/tests/test/existential_types.rs b/tests/test/existential_types.rs --- a/tests/test/existential_types.rs +++ b/tests/test/existential_types.rs @@ -406,6 +406,31 @@ fn dyn_associated_type_binding() { } } +#[test] +fn dyn_assoc_in_super_trait_bounds() { + test! { + program { + trait Base { type Output; } + trait Trait where Self: Base<Output = usize> {} + } + + goal { + forall<'s> { + dyn Trait + 's: Trait + } + } yields { + expect![[r#"Unique"#]] + } + + goal { + forall<'s> { + dyn Trait + 's: Base + } + } yields { + expect![[r#"Unique"#]] + } + } +} #[test] fn dyn_well_formed() { test! { diff --git a/tests/test/opaque_types.rs b/tests/test/opaque_types.rs --- a/tests/test/opaque_types.rs +++ b/tests/test/opaque_types.rs @@ -283,3 +283,33 @@ fn opaque_super_trait() { } } } + +#[test] +fn opaque_assoc_in_super_trait_bounds() { + test! { + program { + trait Foo { + type A; + } + trait EmptyFoo where Self: Foo<A = ()> { } + impl Foo for i32 { + type A = (); + } + impl<T> EmptyFoo for T where T: Foo<A = ()> { } + + opaque type T: EmptyFoo = i32; + } + + goal { + T: EmptyFoo + } yields { + expect![[r#"Unique"#]] + } + + goal { + T: Foo + } yields { + expect![[r#"Unique"#]] + } + } +} diff --git a/tests/test/projection.rs b/tests/test/projection.rs --- a/tests/test/projection.rs +++ b/tests/test/projection.rs @@ -1134,3 +1134,34 @@ fn projection_to_opaque() { } } } + +#[test] +fn projection_from_super_trait_bounds() { + test! { + program { + trait Foo { + type A; + } + trait Bar where Self: Foo<A = ()> {} + impl Foo for i32 { + type A = (); + } + impl Bar for i32 {} + opaque type Opaque: Bar = i32; + } + + goal { + forall<'a> { + <dyn Bar + 'a as Foo>::A = () + } + } yields { + expect![[r#"Unique"#]] + } + + goal { + <Opaque as Foo>::A = () + } yields { + expect![[r#"Unique"#]] + } + } +}
Unable to deduce projection types of dyn types from supertrait bounds Context: https://github.com/rust-lang/rust-analyzer/issues/13169 It seems chalk is unable to deduce projection type of trait object types when it's not specified in `dyn` notation but the trait has supertrait with its projection type specified. I expect the following tests to succeed but all three fail. This is because according to the rules described in #203, chalk yields `AliasEq(<dyn Trait as Base>::Output = usize)` as a subgoal but there's no "fact" clause for that to prove it. Shouldn't the `AliasEq` clause be also produced as a fact under these circumstances, or should we explicitly pass the `AliasEq` clause? ```rust test! { program { trait Base { type Output; } trait Trait where Self: Base<Output = usize> {} } goal { forall<'s> { dyn Trait + 's: Trait } } yields[SolverChoice::recursive_default()] { expect![[r#"Unique"#]] // fails: "No possible solution" } goal { forall<'s> { dyn Trait + 's: Base<Output = usize> } } yields[SolverChoice::recursive_default()] { expect![[r#"Unique"#]] // fails: "No possible solution" } goal { forall<'s> { exists<T> { dyn Trait + 's: Base<Output = T> } } } yields[SolverChoice::recursive_default()] { // fails: "Unique; substitution [?0 := (Base::Output)<dyn for<type> [for<> Implemented(^1.0: Trait)] + '!1_0>]" expect![[r#"Unique; substitution [?0 := Uint(Usize)]"#]] } } ```
2022-10-21T08:27:01Z
7.1
2023-06-13T17:06:29Z
a0e4882f93436fe38a4940ea92c4745121878488
[ "test::existential_types::dyn_assoc_in_super_trait_bounds", "test::opaque_types::opaque_assoc_in_super_trait_bounds", "test::projection::projection_from_super_trait_bounds" ]
[ "display::built_ins::test_empty_tuple", "display::assoc_ty::test_impl_assoc_ty", "display::assoc_ty::test_assoc_type_bounds", "display::built_ins::test_array_types", "display::assoc_ty::test_simple_assoc_type", "display::assoc_ty::test_assoc_type_in_generic_trait", "display::assoc_ty::test_assoc_type_where_clause_referencing_trait_generics", "display::assoc_ty::test_simple_generic_assoc_type_with_bounds", "display::assoc_ty::test_assoc_type_in_trait_with_multiple_generics", "display::assoc_ty::test_simple_generic_assoc_type", "display::assoc_ty::test_impl_assoc_ty_in_generic_block", "display::assoc_ty::test_assoc_type_and_trait_generics_coexist", "display::assoc_ty::test_impl_assoc_type_with_generics_using_impl_generics", "display::assoc_ty::test_alias_ty_bound_in_struct_where_clauses", "display::assoc_ty::test_impl_assoc_type_with_generics_using_gat_generics", "display::assoc_ty::test_impl_assoc_ty_value_referencing_block_generic", "display::assoc_ty::test_alias_ty_bound_in_assoc_ty_where_clauses", "display::assoc_ty::test_impl_generics_and_assoc_ty_generics_coexist", "display::assoc_ty::test_alias_ty_bound_in_impl_where_clauses", "display::assoc_ty::test_trait_impl_assoc_type", "display::assoc_ty::test_simple_generic_assoc_type_with_where_clause", "display::built_ins::test_impl_on_tuples_with_generics", "display::assoc_ty::test_trait_with_multiple_assoc_types", "display::enum_::test_enum_generics", "display::built_ins::test_const_ptr", "display::assoc_ty::test_impl_assoc_type_with_generics_multiple_gat_generics_dont_conflict", "display::assoc_ty::test_impl_assoc_ty_value_referencing_block_generic_nested", "display::assoc_ty::test_impl_assoc_type_with_generics_using_gat_generics_and_impl_block", "display::assoc_ty::test_impl_assoc_ty_alias", "display::built_ins::test_generic_function_pointer_type", "display::dyn_::test_dyn_forall_in_impl", "display::dyn_::test_simple_dyn_referencing_outer_generic_parameters", "display::built_ins::test_function_pointer_type", "display::dyn_::test_multiple_forall_one_dyn", "display::const_::test_const_generics", "display::built_ins::test_mutable_references", "display::dyn_::test_dyn_forall_multiple_parameters", "display::enum_::test_enum_bounds", "display::built_ins::test_mut_ptr", "display::dyn_::test_dyn_forall_in_struct", "display::built_ins::test_str_types", "display::enum_::test_enum_fields", "display::enum_::test_enum_repr_and_keywords_ordered_correctly", "display::dyn_::test_simple_dyn", "display::built_ins::test_one_and_many_tuples", "display::built_ins::test_immutable_references", "display::enum_::test_simple_enum", "integration::panic::custom_clauses_panics", "integration::panic::program_clauses_for_env", "integration::panic::interner", "integration::panic::impl_datum_panics", "integration::panic::impls_for_trait", "display::enum_::test_enum_repr", "display::const_::test_basic_const_values_in_opaque_ty_values", "integration::panic::trait_datum_panics", "display::const_::test_basic_const_values_in_assoc_ty_values", "display::fn_::test_opaque_ty_with_fn_def", "display::formatting::test_name_disambiguation", "display::impl_::test_negative_auto_trait_impl", "display::fn_::test_generic_fn_def", "display::built_ins::test_tuples_using_generic_args", "display::built_ins::test_slice_types", "display::enum_::test_enum_keywords", "display::const_::test_basic_const_values_in_impls", "display::formatting::test_assoc_type_formatting", "display::dyn_::test_dyn_forall_with_trait_referencing_outer_lifetime", "display::fn_::test_const_generic_fn_def", "display::formatting::test_fn_where_clause", "display::impl_::test_generic_impl", "display::fn_::test_basic_fn_def", "display::formatting::test_assoc_ty_where_clause", "display::opaque_ty::opaque_ty_no_bounds", "display::formatting::test_struct_field_formatting", "display::formatting::test_where_clause_formatting", "display::lifetimes::test_lifetimes_in_structs", "display::impl_::test_upstream_impl_keyword", "display::opaque_ty::test_opaque_type_as_type_value", "display::opaque_ty::multiple_bounds", "display::opaque_ty::test_generic_opaque_type_as_value", "display::opaque_ty::test_generic_opaque_types", "display::opaque_ty::opaque_types", "display::impl_::test_impl_for_generic_adt", "display::lifetimes::test_lifetime_outlives", "display::opaque_ty::test_generic_opaque_type_in_fn_ptr", "display::self_::test_self_in_forall", "display::opaque_ty::test_opaque_type_in_fn_ptr", "display::trait_::test_generic_trait", "lowering::assoc_tys", "lowering::invalid_name", "display::self_::test_self_in_dyn", "display::trait_::test_trait_where_clauses", "display::unique_names::lots_of_traits", "display::struct_::test_struct_repr", "display::lifetimes::test_various_forall", "lowering::phantom_data", "display::struct_::test_struct_keywords", "display::trait_::test_simple_trait", "display::struct_::test_struct_generic_fields", "lowering::not_trait", "display::unique_names::traits_and_structs", "lowering::extern_functions", "lowering::type_parameter", "lowering::closures", "display::where_clauses::test_struct_where_clauses", "lowering::negative_impl", "display::struct_::test_simple_struct", "lowering::lifetime_outlives", "lowering::gat_parse", "lowering::upstream_items", "display::unique_names::lots_of_structs", "lowering::atc_accounting", "display::self_::test_self_in_generic_associated_type_declarations", "display::trait_::test_lang_with_flag", "lowering::tuples", "display::self_::test_self_in_dyn_with_generics", "display::struct_::test_struct_fields", "lowering::lower_success", "display::self_::test_self_in_trait_bounds", "display::unique_names::assoc_types", "display::trait_::test_basic_trait_impl", "lowering::slices", "display::struct_::test_struct_where_clauses", "lowering::struct_repr", "display::struct_::test_struct_repr_with_flags", "lowering::algebraic_data_types", "lowering::type_parameter_bound", "display::struct_::test_generic_struct", "lowering::refs", "display::where_clauses::test_trait_projection_with_dyn_arg", "display::where_clauses::test_complicated_bounds", "lowering::gat_higher_ranked_bound", "lowering::type_outlives", "lowering::arrays", "lowering::auto_trait", "lowering::fn_defs", "display::self_::test_self_in_assoc_type_declarations", "lowering::goal_quantifiers", "test::auto_traits::auto_traits_flounder", "display::where_clauses::test_dyn_on_left", "display::where_clauses::test_impl_where_clauses", "test::coherence::downstream_impl_of_fundamental_43355", "display::where_clauses::test_trait_projection", "lowering::raw_pointers", "lowering::duplicate_parameters", "display::where_clauses::test_alias_eq", "test::coherence::overlapping_negative_positive_impls", "lowering::scalars", "lowering::unsafe_variadic_functions", "test::coherence::overlapping_assoc_types_error_generics", "test::arrays::arrays_are_not_clone_if_element_not_clone", "test::coherence::multiple_nonoverlapping_impls", "test::ambiguity_issue_727::issue_727_3", "logging_db::does_not_need_necessary_separate_impl", "test::coherence::two_blanket_impls", "test::coherence::two_blanket_impls_open_ended", "test::coherence::overlapping_assoc_types_error_simple", "test::arrays::arrays_are_not_copy_if_element_not_copy", "logging_db::stubs_types_from_assoc_type_bounds", "logging_db::records_opaque_type", "test::arrays::arrays_are_copy_if_element_copy", "logging_db::stubs_types_from_opaque_ty_bounds", "test::closures::closure_is_sized", "test::coherence::concrete_impl_and_blanket_impl", "test::arrays::arrays_are_clone_if_element_clone", "test::arrays::arrays_are_sized", "logging_db::records_struct_trait_and_impl", "logging_db::can_stub_types_referenced_in_alias_ty_generics", "test::coherence::generic_vec_and_specific_vec", "test::coherence::overlapping_negative_impls", "test::coherence::multiple_parameters", "logging_db::opaque_ty_in_opaque_ty", "logging_db::records_fn_def", "logging_db::stubs_types_from_assoc_type_values_not_mentioned", "display::self_::test_against_accidental_self", "logging_db::records_associated_type_bounds", "test::coherence::fundamental_traits", "test::auto_traits::phantom_auto_trait", "logging_db::stubs_types_in_dyn_ty", "test::coherence::local_negative_reasoning_in_coherence", "logging_db::records_parents_parent", "logging_db::can_stub_types_referenced_in_alias_ty_bounds", "logging_db::opaque_ty_in_projection", "test::coherence::nonoverlapping_assoc_types", "test::coherence::overlapping_assoc_types", "test::discriminant_kind::no_discriminant_kind_impls", "test::coinduction::coinductive_multicycle1", "test::coinduction::coinductive_trivial_variant1", "test::coinduction::coinductive_trivial_variant3", "test::coinduction::coinductive_nontrivial", "test::coinduction::coinductive_trivial_variant2", "test::coinduction::coinductive_multicycle3", "test::coherence::overlapping_assoc_types_error", "test::coinduction::coinductive_unsound2", "test::coinduction::coinductive_unification_forall", "test::coinduction::coinductive_unification_exists", "test::coherence::two_impls_for_same_type", "test::coinduction::coinductive_unsound_nested", "test::cycle::infinite_recursion", "test::coinduction::coinductive_multicycle2", "test::coinduction::coinductive_unsound1", "test::coherence::fundamental_type_multiple_parameters", "logging_db::records_generics", "test::ambiguity_issue_727::issue_727_2", "test::cycle::overflow_universe", "test::cycle::cycle_many_solutions", "test::cycle::cycle_unique_solution", "test::closures::closure_is_well_formed", "test::cycle::inner_cycle", "test::coinduction::coinductive_unsound_inter_cycle_dependency", "test::closures::closures_propagate_auto_traits", "test::cycle::cycle_no_solution", "test::coinduction::coinductive_unsound_nested2", "test::arrays::arrays_are_well_formed_if_elem_sized", "test::cycle::multiple_ambiguous_cycles", "test::cycle::cycle_with_ambiguity", "test::coinduction::coinductive_multicycle4", "test::existential_types::dyn_associated_type_binding", "test::existential_types::dyn_Clone_is_Clone", "test::constants::multi_impl", "test::existential_types::dyn_Clone_is_not_Send", "test::fn_def::fn_def_is_sized", "test::existential_types::dyn_lifetime_bound", "test::fn_def::fn_def_is_copy", "test::coinduction::mixed_semantics", "test::fn_def::fn_def_is_well_formed", "test::foreign_types::foreign_ty_lowering", "test::fn_def::fn_def_is_clone", "test::auto_traits::auto_trait_without_impls", "test::constants::generic_impl", "test::existential_types::dyn_Clone_Send_is_Send", "display::where_clauses::test_generic_vars_inside_assoc_bounds", "test::existential_types::dyn_well_formed", "test::foreign_types::foreign_ty_is_not_sized", "logging_db::can_stub_traits_with_unreferenced_assoc_ty", "test::foreign_types::foreign_ty_is_not_copy", "test::foreign_types::foreign_ty_is_not_clone", "logging_db::records_generic_impls", "test::foreign_types::foreign_ty_trait_impl", "test::existential_types::dyn_super_trait_cycle", "test::foreign_types::foreign_ty_is_well_formed", "test::closures::closure_is_clone", "test::auto_traits::auto_semantics", "lowering::check_variable_kinds", "test::lifetimes::static_lowering", "test::impls::normalize_rev_infer", "test::implied_bounds::implied_bounds", "test::fn_def::fn_def_implied_bounds_from_env", "test::existential_types::dyn_Foo_Bar", "display::where_clauses::test_forall_in_where", "test::auto_traits::adt_auto_trait", "test::auto_traits::enum_auto_trait", "test::impls::higher_ranked", "logging_db::can_stub_traits_with_referenced_assoc_ty", "test::impls::where_clause_trumps", "test::misc::basic_region_constraint_from_positive_impl", "test::impls::deep_success", "test::impls::definite_guidance", "test::impls::normalize_rev_infer_gat", "test::impls::unify_types_in_ambiguous_impl", "test::misc::cached_answers_2", "test::functions::functions_are_sized", "test::constants::placeholders_eq", "test::impls::inapplicable_assumption_does_not_shadow", "test::misc::basic", "test::impls::ordering", "test::ambiguity_issue_727::issue_727_1", "test::lifetimes::empty_lowering", "test::functions::functions_are_copy", "test::impls::unify_types_in_impl", "test::lifetimes::erased_impls", "test::impls::deep_failure", "test::existential_types::dyn_super_trait_non_super_trait_clause", "test::misc::cached_answers_3", "test::auto_traits::auto_trait_with_impls", "test::lifetimes::empty_impls", "test::existential_types::dyn_binders_reverse", "test::misc::example_2_1_EWFS", "test::lifetimes::erased_lowering", "test::misc::ambiguous_unification_in_fn", "test::impls::partial_overlap_3", "test::implied_bounds::higher_ranked_implied_bounds", "test::lifetimes::erased_outlives", "test::misc::cached_answers_1", "test::constants::single_impl", "test::misc::non_enumerable_traits_double", "test::misc::empty_definite_guidance", "test::fn_def::fn_defs", "test::misc::canonicalization_regression", "test::existential_types::dyn_super_trait_higher_ranked", "test::misc::non_enumerable_traits_indirect", "test::existential_types::dyn_higher_ranked_type_arguments", "test::negation::negative_loop - should panic", "test::negation::example_2_2_EWFS", "test::lifetimes::static_outlives", "test::negation::contradiction - should panic", "test::negation::example_2_3_EWFS - should panic", "test::existential_types::dyn_super_trait_not_a_cycle", "test::misc::subgoal_cycle_inhabited", "test::negation::negative_answer_ambiguous - should panic", "test::misc::endless_loop", "test::lifetimes::empty_outlives", "test::coherence::orphan_check", "test::discriminant_kind::discriminant_kind_impl", "test::misc::only_draw_so_many_blow_up", "test::misc::flounder_ambiguous", "test::negation::negation_free_vars", "test::existential_types::dyn_super_trait_simple", "test::misc::normalize_ambiguous", "test::implied_bounds::implied_from_env", "test::fn_def::generic_fn_implements_fn_traits", "test::misc::non_enumerable_traits_reorder", "test::cycle::overflow", "test::never::never_is_well_formed", "test::misc::recursive_hang", "test::impls::generic_trait", "test::numerics::integer_ambiguity", "test::impls::prove_infer", "test::never::never_is_sized", "test::lifetimes::static_impls", "test::misc::lifetime_outlives_constraints", "test::misc::only_draw_so_many", "test::closures::closure_is_copy", "test::misc::flounder", "test::numerics::float_ambiguity", "test::misc::builtin_impl_enumeration", "test::negation::negative_reorder", "test::numerics::integers_are_not_floats", "test::negation::example_3_3_EWFS - should panic", "test::numerics::integers_are_sized", "test::misc::not_really_ambig", "test::numerics::float_kind_trait", "test::numerics::integers_are_copy", "test::misc::type_outlives_constraints", "test::numerics::shl_ice", "test::numerics::integer_index", "test::misc::env_bound_vars", "test::impls::partial_overlap_2", "test::misc::non_enumerable_traits_direct", "test::opaque_types::opaque_bounds", "test::negation::deep_negation", "test::misc::futures_ambiguity", "test::impls::clauses_in_if_goals", "test::opaque_types::opaque_super_trait", "display::trait_::test_wellknown_traits", "test::implied_bounds::gat_implied_bounds", "test::opaque_types::opaque_trait_generic", "test::numerics::integer_kind_trait", "test::opaque_types::opaque_generics_simple", "test::numerics::integer_and_float_are_specialized_ty_kinds", "test::numerics::unify_general_then_specific_ty", "test::impls::prove_clone", "test::misc::subgoal_cycle_uninhabited", "test::projection::projection_equality_from_env", "test::coherence_goals::local_and_upstream_types", "test::projection::projection_equality_priority1", "test::negation::negation_quantifiers", "test::fn_def::fn_def_implements_fn_traits", "test::object_safe::object_safe_flag", "test::projection::rust_analyzer_regression", "test::projection::issue_144_regression", "test::projection::guidance_for_projection_on_flounder", "test::numerics::ambiguous_add", "test::projection::normalize_gat_with_higher_ranked_trait_bound", "test::opaque_types::opaque_reveal", "test::projection::projection_equality_nested", "test::projection::projection_from_env_a", "test::projection::projection_to_dyn", "test::refs::immut_refs_are_sized", "test::projection::forall_projection", "test::opaque_types::opaque_auto_traits_indirect", "test::projection::gat_in_non_enumerable_trait", "test::projection::normalize_gat1", "test::refs::mut_refs_are_sized", "test::slices::slices_are_not_sized", "test::type_flags::dyn_ty_flags_correct", "test::type_flags::flagless_ty_has_no_flags", "test::refs::mut_refs_are_well_formed", "test::type_flags::opaque_ty_flags_correct", "test::type_flags::placeholder_ty_flags_correct", "test::type_flags::static_and_bound_lifetimes", "test::projection::normalize_gat_with_where_clause", "test::projection::normalize_under_binder_multi", "test::projection::normalize_into_iterator", "test::opaque_types::opaque_auto_traits", "test::string::str_is_not_clone", "test::numerics::general_ty_kind_becomes_specific", "test::projection::projection_from_env_slow", "test::slices::slices_are_not_copy", "test::string::str_is_not_sized", "display::trait_::test_trait_flags", "test::refs::immut_refs_are_well_formed", "test::subtype::variance_lowering", "test::string::str_trait_impl", "test::projection::projection_equality", "test::subtype::fn_lifetime_variance_args", "test::subtype::generalize_contravariant_struct", "test::projection::normalize_gat_with_where_clause2", "test::string::str_is_well_formed", "test::misc::subgoal_abstraction", "test::subtype::multi_lifetime", "test::subtype::generalize", "test::subtype::ref_lifetime_variance", "test::string::str_is_not_copy", "test::subtype::multi_lifetime_inverted", "test::subtype::subtype_simple", "test::projection::projection_to_opaque", "test::unpin::unpin_lowering", "test::slices::slices_are_well_formed_if_elem_sized", "test::unify::equality_binder", "test::discriminant_kind::discriminant_kind_assoc", "test::subtype::generalize_slice", "test::subtype::generalize_array", "test::subtype::generalize_covariant_struct", "test::projection::gat_unify_with_implied_wc", "test::slices::slices_are_not_clone", "test::impls::prove_forall", "test::unify::mixed_indices_normalize_gat_application", "test::opaque_types::opaque_generics", "test::unpin::unpin_inherit_negative", "test::subtype::generalize_2tuple", "test::projection::normalize_gat_const", "test::subtype::generalize_tuple", "test::subtype::generalize_invariant_struct", "test::unpin::unpin_auto_trait", "test::unify::mixed_indices_match_program", "test::subtype::multi_lifetime_array", "test::subtype::struct_lifetime_variance", "test::unify::forall_equality_unsolveable_simple", "test::unify::forall_equality_solveable_simple", "test::unify::mixed_indices_normalize_application", "test::subtype::multi_lifetime_covariant_struct", "test::unpin::unpin_overwrite", "test::unpin::unpin_negative", "test::wf_lowering::cyclic_wf_requirements", "test::wf_lowering::higher_ranked_trait_bound_on_gat", "test::wf_lowering::ill_formed_assoc_ty", "test::projection::forall_projection_gat", "test::wf_lowering::implied_bounds_on_ty_decl", "test::wf_lowering::ill_formed_ty_decl", "test::wf_lowering::no_unsize_impls", "test::opaque_types::opaque_where_clause", "test::wf_goals::placeholder_wf", "test::subtype::fn_lifetime_variance_with_return_type", "test::wf_goals::drop_compatible", "test::unify::equality_binder2", "test::subtype::multi_lifetime_invariant_struct", "test::projection::normalize_gat2", "test::wf_lowering::ill_formed_trait_decl", "test::wf_lowering::well_formed_trait_decl", "test::unify::unify_quantified_lifetimes", "test::subtype::multi_lifetime_contravariant_struct", "test::unify::mixed_indices_unify", "test::wf_lowering::higher_ranked_trait_bounds", "test::wf_lowering::implied_bounds", "test::wf_lowering::bound_in_header_from_env", "test::unsize::array_unsizing", "test::wf_lowering::ill_formed_opaque_ty", "test::wf_lowering::generic_projection_where_clause", "test::wf_lowering::assoc_type_recursive_bound", "test::wf_lowering::higher_ranked_inline_bound_on_gat", "test::unify::region_equality", "test::projection::projection_equality_priority2", "test::wf_lowering::ill_formed_type_in_header", "test::wf_goals::recursive_where_clause_on_type", "test::impls::suggested_subst", "test::subtype::multi_lifetime_slice", "test::wf_lowering::generic_projection_bound", "test::wf_lowering::mixed_indices_check_projection_bounds", "test::wf_lowering::enum_sized_constraints", "test::wf_lowering::mixed_indices_check_generic_projection_bounds", "test::wf_lowering::wf_requiremements_for_projection", "test::projection::normalize_under_binder", "test::wf_lowering::cyclic_traits", "test::subtype::multi_lifetime_tuple", "test::scalars::scalar_in_tuple_trait_impl", "test::tuples::tuple_trait_impl", "test::unpin::generator_unpin", "test::unify::quantified_types", "test::wf_lowering::drop_constraints", "test::negation::simple_negation", "test::wf_lowering::higher_ranked_cyclic_requirements", "test::wf_goals::enum_wf", "test::wf_lowering::struct_sized_constraints", "test::wf_goals::struct_wf", "test::generators::generator_test", "test::projection::normalize_basic", "test::auto_traits::builtin_auto_trait", "test::closures::closure_implements_fn_traits", "test::wf_lowering::coerce_unsized_struct", "test::wf_lowering::coerce_unsized_pointer", "test::tuples::tuples_are_wf", "test::tuples::tuples_are_clone", "test::unify::forall_equality", "test::unsize::tuple_unsizing", "test::tuples::tuples_are_copy", "display::built_ins::test_scalar_types", "test::coherence_goals::is_fully_visible", "test::tuples::tuples_are_sized", "test::wf_lowering::copy_constraints", "test::functions::function_implement_fn_traits", "test::unsize::struct_unsizing", "test::scalars::scalars_are_sized", "test::scalars::scalars_are_well_formed", "test::unsize::dyn_to_dyn_unsizing", "test::unsize::ty_to_dyn_unsizing", "test::projection::iterator_flatten", "test::coherence_goals::fundamental_types", "test::coherence_goals::local_impl_allowed_for_traits", "test::scalars::scalar_trait_impl" ]
[]
[]
auto_2025-06-13
rust-lang/chalk
755
rust-lang__chalk-755
[ "734" ]
f470f2f493203f58d493c7221863bca2ce1a6dad
diff --git a/chalk-solve/src/clauses.rs b/chalk-solve/src/clauses.rs --- a/chalk-solve/src/clauses.rs +++ b/chalk-solve/src/clauses.rs @@ -161,14 +161,16 @@ pub fn push_auto_trait_impls<I: Interner>( TyKind::Foreign(_) => Ok(()), // closures require binders, while the other types do not - TyKind::Closure(closure_id, _) => { - let binders = builder - .db - .closure_upvars(*closure_id, &Substitution::empty(interner)); - builder.push_binders(binders, |builder, upvar_ty| { - let conditions = iter::once(mk_ref(upvar_ty)); - builder.push_clause(consequence, conditions); - }); + TyKind::Closure(closure_id, substs) => { + let closure_fn_substitution = builder.db.closure_fn_substitution(*closure_id, substs); + let binders = builder.db.closure_upvars(*closure_id, substs); + let upvars = binders.substitute(builder.db.interner(), &closure_fn_substitution); + + // in a same behavior as for non-auto traits (reuse the code) we can require that + // every bound type must implement this auto-trait + use crate::clauses::builtin_traits::needs_impl_for_tys; + needs_impl_for_tys(builder.db, builder, consequence, Some(upvars).into_iter()); + Ok(()) } TyKind::Generator(generator_id, _) => {
diff --git a/tests/test/closures.rs b/tests/test/closures.rs --- a/tests/test/closures.rs +++ b/tests/test/closures.rs @@ -280,3 +280,35 @@ fn closure_implements_fn_traits() { } } } + +#[test] +fn closures_propagate_auto_traits() { + test! { + program { + #[auto] + trait Send { } + + closure foo(self,) {} + + closure with_ty<T>(self,) { T } + } + + goal { + foo: Send + } yields { + expect![["Unique"]] + } + + goal { + forall<T> { with_ty<T>: Send } + } yields { + expect![["No possible solution"]] + } + + goal { + forall<T> { if (T: Send) { with_ty<T>: Send } } + } yields { + expect![["Unique"]] + } + } +}
Auto traits are not handled for generic closures The following test fails with both solvers (returning ambiguous). ```rust program { #[auto] trait Send { } closure with_ty<T>(self,) { T } } goal { forall<T> { if (T: Send) { with_ty<T>: Send } } } yields { "Unique" } ``` The empty substs here seem suspicious. https://github.com/rust-lang/chalk/blob/e0c94db8a497eee4ed1f49534fb0714801cb90e8/chalk-solve/src/clauses.rs#L167 <!-- TRIAGEBOT_START --> <!-- TRIAGEBOT_ASSIGN_START --> <!-- TRIAGEBOT_ASSIGN_DATA_START$${"user":"shamatar"}$$TRIAGEBOT_ASSIGN_DATA_END --> <!-- TRIAGEBOT_ASSIGN_END --> <!-- TRIAGEBOT_END -->
I'm interested in learning more about chalk, so I'll @rustbot claim.
2022-03-12T14:17:16Z
7.1
2022-07-28T21:05:13Z
a0e4882f93436fe38a4940ea92c4745121878488
[ "test::closures::closures_propagate_auto_traits" ]
[ "display::assoc_ty::test_simple_assoc_type", "display::assoc_ty::test_assoc_type_and_trait_generics_coexist", "display::assoc_ty::test_simple_generic_assoc_type_with_where_clause", "display::built_ins::test_empty_tuple", "display::assoc_ty::test_assoc_type_bounds", "display::assoc_ty::test_simple_generic_assoc_type_with_bounds", "display::assoc_ty::test_trait_impl_assoc_type", "display::assoc_ty::test_assoc_type_in_generic_trait", "display::assoc_ty::test_impl_assoc_ty", "display::assoc_ty::test_assoc_type_in_trait_with_multiple_generics", "display::enum_::test_enum_bounds", "display::assoc_ty::test_impl_assoc_ty_value_referencing_block_generic", "display::built_ins::test_impl_on_tuples_with_generics", "display::assoc_ty::test_impl_assoc_type_with_generics_using_gat_generics", "display::assoc_ty::test_alias_ty_bound_in_assoc_ty_where_clauses", "display::assoc_ty::test_impl_assoc_ty_value_referencing_block_generic_nested", "display::built_ins::test_function_pointer_type", "display::built_ins::test_array_types", "display::const_::test_basic_const_values_in_opaque_ty_values", "display::assoc_ty::test_impl_generics_and_assoc_ty_generics_coexist", "display::assoc_ty::test_trait_with_multiple_assoc_types", "display::assoc_ty::test_impl_assoc_type_with_generics_using_gat_generics_and_impl_block", "display::assoc_ty::test_impl_assoc_type_with_generics_using_impl_generics", "display::built_ins::test_one_and_many_tuples", "display::assoc_ty::test_alias_ty_bound_in_impl_where_clauses", "display::dyn_::test_simple_dyn", "display::assoc_ty::test_simple_generic_assoc_type", "display::assoc_ty::test_impl_assoc_ty_in_generic_block", "display::assoc_ty::test_alias_ty_bound_in_struct_where_clauses", "display::const_::test_basic_const_values_in_impls", "display::assoc_ty::test_impl_assoc_type_with_generics_multiple_gat_generics_dont_conflict", "display::assoc_ty::test_assoc_type_where_clause_referencing_trait_generics", "display::built_ins::test_mut_ptr", "display::enum_::test_enum_generics", "display::assoc_ty::test_impl_assoc_ty_alias", "display::built_ins::test_const_ptr", "display::enum_::test_simple_enum", "display::dyn_::test_dyn_forall_in_impl", "display::dyn_::test_simple_dyn_referencing_outer_generic_parameters", "display::enum_::test_enum_repr_and_keywords_ordered_correctly", "display::dyn_::test_dyn_forall_in_struct", "display::built_ins::test_str_types", "display::opaque_ty::opaque_ty_no_bounds", "display::built_ins::test_mutable_references", "display::enum_::test_enum_keywords", "display::impl_::test_generic_impl", "integration::panic::custom_clauses_panics", "display::fn_::test_opaque_ty_with_fn_def", "integration::panic::impls_for_trait", "display::dyn_::test_multiple_forall_one_dyn", "display::fn_::test_const_generic_fn_def", "integration::panic::impl_datum_panics", "integration::panic::program_clauses_for_env", "integration::panic::interner", "display::formatting::test_assoc_ty_where_clause", "integration::panic::trait_datum_panics", "display::dyn_::test_dyn_forall_with_trait_referencing_outer_lifetime", "display::built_ins::test_generic_function_pointer_type", "display::built_ins::test_immutable_references", "display::impl_::test_impl_for_generic_adt", "display::enum_::test_enum_repr", "display::dyn_::test_dyn_forall_multiple_parameters", "display::built_ins::test_tuples_using_generic_args", "display::fn_::test_generic_fn_def", "display::const_::test_basic_const_values_in_assoc_ty_values", "display::enum_::test_enum_fields", "display::opaque_ty::multiple_bounds", "display::formatting::test_name_disambiguation", "display::built_ins::test_slice_types", "display::lifetimes::test_lifetimes_in_structs", "display::fn_::test_basic_fn_def", "display::formatting::test_assoc_type_formatting", "display::lifetimes::test_lifetime_outlives", "display::formatting::test_struct_field_formatting", "display::const_::test_const_generics", "display::formatting::test_where_clause_formatting", "display::formatting::test_fn_where_clause", "display::opaque_ty::opaque_types", "display::opaque_ty::test_opaque_type_as_type_value", "display::opaque_ty::test_generic_opaque_type_as_value", "display::impl_::test_upstream_impl_keyword", "display::opaque_ty::test_generic_opaque_type_in_fn_ptr", "display::impl_::test_negative_auto_trait_impl", "display::opaque_ty::test_generic_opaque_types", "display::lifetimes::test_various_forall", "lowering::invalid_name", "lowering::lifetime_outlives", "lowering::closures", "lowering::not_trait", "lowering::phantom_data", "lowering::gat_higher_ranked_bound", "lowering::lower_success", "lowering::assoc_tys", "display::unique_names::lots_of_structs", "display::unique_names::lots_of_traits", "display::unique_names::assoc_types", "display::unique_names::traits_and_structs", "lowering::extern_functions", "lowering::struct_repr", "lowering::goal_quantifiers", "lowering::fn_defs", "lowering::atc_accounting", "lowering::gat_parse", "lowering::type_parameter", "display::struct_::test_struct_fields", "display::self_::test_self_in_forall", "lowering::upstream_items", "lowering::negative_impl", "display::trait_::test_generic_trait", "display::struct_::test_struct_where_clauses", "display::struct_::test_simple_struct", "display::struct_::test_struct_keywords", "display::trait_::test_trait_where_clauses", "display::struct_::test_generic_struct", "lowering::type_parameter_bound", "display::opaque_ty::test_opaque_type_in_fn_ptr", "lowering::type_outlives", "display::trait_::test_simple_trait", "display::struct_::test_struct_repr_with_flags", "display::self_::test_self_in_generic_associated_type_declarations", "display::self_::test_self_in_dyn", "display::trait_::test_lang_with_flag", "display::where_clauses::test_trait_projection", "display::where_clauses::test_dyn_on_left", "lowering::tuples", "display::trait_::test_basic_trait_impl", "lowering::refs", "display::where_clauses::test_trait_projection_with_dyn_arg", "display::self_::test_self_in_trait_bounds", "display::where_clauses::test_complicated_bounds", "display::where_clauses::test_impl_where_clauses", "display::self_::test_self_in_dyn_with_generics", "display::struct_::test_struct_generic_fields", "display::self_::test_self_in_assoc_type_declarations", "display::where_clauses::test_struct_where_clauses", "display::struct_::test_struct_repr", "lowering::slices", "lowering::unsafe_variadic_functions", "lowering::algebraic_data_types", "test::coherence::multiple_parameters", "lowering::raw_pointers", "lowering::duplicate_parameters", "test::coherence::generic_vec_and_specific_vec", "test::coherence::overlapping_negative_positive_impls", "test::coherence::local_negative_reasoning_in_coherence", "test::coherence::downstream_impl_of_fundamental_43355", "test::coherence::multiple_nonoverlapping_impls", "test::auto_traits::auto_traits_flounder", "test::coherence::overlapping_negative_impls", "lowering::auto_trait", "test::coherence::overlapping_assoc_types_error_simple", "test::coherence::two_blanket_impls", "test::coherence::two_blanket_impls_open_ended", "test::arrays::arrays_are_not_clone_if_element_not_clone", "lowering::arrays", "test::coherence::overlapping_assoc_types_error_generics", "test::coherence::overlapping_assoc_types", "test::coherence::overlapping_assoc_types_error", "test::arrays::arrays_are_copy_if_element_copy", "test::arrays::arrays_are_sized", "test::coherence::concrete_impl_and_blanket_impl", "test::arrays::arrays_are_not_copy_if_element_not_copy", "test::coherence::nonoverlapping_assoc_types", "test::coherence::fundamental_traits", "test::coherence::two_impls_for_same_type", "test::arrays::arrays_are_clone_if_element_clone", "test::closures::closure_is_sized", "lowering::scalars", "test::auto_traits::phantom_auto_trait", "logging_db::records_parents_parent", "logging_db::can_stub_types_referenced_in_alias_ty_bounds", "logging_db::does_not_need_necessary_separate_impl", "logging_db::records_struct_trait_and_impl", "logging_db::records_fn_def", "logging_db::opaque_ty_in_opaque_ty", "logging_db::can_stub_types_referenced_in_alias_ty_generics", "logging_db::stubs_types_in_dyn_ty", "logging_db::stubs_types_from_assoc_type_bounds", "logging_db::stubs_types_from_assoc_type_values_not_mentioned", "logging_db::records_associated_type_bounds", "display::where_clauses::test_alias_eq", "logging_db::stubs_types_from_opaque_ty_bounds", "logging_db::records_opaque_type", "test::coinduction::coinductive_multicycle1", "test::discriminant_kind::no_discriminant_kind_impls", "logging_db::opaque_ty_in_projection", "test::coinduction::coinductive_multicycle3", "test::coinduction::coinductive_nontrivial", "test::coinduction::coinductive_multicycle4", "test::coinduction::coinductive_unification_exists", "test::coinduction::coinductive_trivial_variant1", "test::coinduction::coinductive_unification_forall", "test::coherence::fundamental_type_multiple_parameters", "test::coinduction::coinductive_multicycle2", "test::coinduction::coinductive_trivial_variant2", "test::coinduction::coinductive_unsound1", "test::coinduction::coinductive_trivial_variant3", "test::coinduction::coinductive_unsound2", "test::coinduction::coinductive_unsound_nested", "test::coinduction::coinductive_unsound_nested2", "test::coinduction::coinductive_unsound_inter_cycle_dependency", "test::cycle::infinite_recursion", "test::cycle::cycle_many_solutions", "test::cycle::cycle_no_solution", "test::foreign_types::foreign_ty_lowering", "test::cycle::overflow_universe", "test::cycle::cycle_unique_solution", "test::existential_types::dyn_Clone_Send_is_Send", "test::existential_types::dyn_Clone_is_Clone", "display::self_::test_against_accidental_self", "test::cycle::cycle_with_ambiguity", "test::existential_types::dyn_Clone_is_not_Send", "test::existential_types::dyn_associated_type_binding", "test::cycle::multiple_ambiguous_cycles", "test::cycle::inner_cycle", "test::closures::closure_is_clone", "test::existential_types::dyn_lifetime_bound", "test::arrays::arrays_are_well_formed_if_elem_sized", "test::closures::closure_is_well_formed", "test::existential_types::dyn_super_trait_cycle", "test::fn_def::fn_def_is_well_formed", "test::fn_def::fn_def_is_clone", "test::fn_def::fn_def_is_copy", "test::auto_traits::auto_trait_without_impls", "test::constants::generic_impl", "test::fn_def::fn_def_is_sized", "test::coinduction::mixed_semantics", "test::existential_types::dyn_well_formed", "test::constants::multi_impl", "test::fn_def::fn_def_implied_bounds_from_env", "lowering::check_variable_kinds", "test::auto_traits::enum_auto_trait", "test::foreign_types::foreign_ty_is_not_sized", "test::foreign_types::foreign_ty_is_not_copy", "logging_db::records_generics", "test::foreign_types::foreign_ty_trait_impl", "test::foreign_types::foreign_ty_is_well_formed", "test::foreign_types::foreign_ty_is_not_clone", "test::lifetimes::empty_lowering", "test::lifetimes::static_lowering", "test::lifetimes::erased_lowering", "test::implied_bounds::implied_bounds", "test::existential_types::dyn_Foo_Bar", "logging_db::can_stub_traits_with_unreferenced_assoc_ty", "display::where_clauses::test_forall_in_where", "test::cycle::overflow", "test::impls::deep_success", "test::impls::definite_guidance", "test::impls::higher_ranked", "test::existential_types::dyn_super_trait_non_super_trait_clause", "test::impls::ordering", "test::impls::inapplicable_assumption_does_not_shadow", "test::impls::normalize_rev_infer", "logging_db::can_stub_traits_with_referenced_assoc_ty", "test::impls::normalize_rev_infer_gat", "test::misc::cached_answers_1", "display::where_clauses::test_generic_vars_inside_assoc_bounds", "test::auto_traits::auto_semantics", "logging_db::records_generic_impls", "test::functions::functions_are_copy", "test::misc::basic", "test::misc::basic_region_constraint_from_positive_impl", "test::functions::functions_are_sized", "test::misc::cached_answers_3", "test::lifetimes::empty_impls", "test::impls::where_clause_trumps", "test::auto_traits::adt_auto_trait", "test::lifetimes::erased_impls", "test::impls::unify_types_in_impl", "test::misc::cached_answers_2", "test::impls::unify_types_in_ambiguous_impl", "test::auto_traits::auto_trait_with_impls", "test::existential_types::dyn_super_trait_higher_ranked", "test::constants::single_impl", "test::impls::deep_failure", "test::misc::canonicalization_regression", "test::existential_types::dyn_binders_reverse", "test::implied_bounds::implied_from_env", "test::constants::placeholders_eq", "test::misc::example_2_1_EWFS", "test::misc::ambiguous_unification_in_fn", "test::existential_types::dyn_super_trait_not_a_cycle", "test::fn_def::fn_defs", "test::misc::flounder", "test::misc::non_enumerable_traits_indirect", "test::implied_bounds::higher_ranked_implied_bounds", "test::misc::empty_definite_guidance", "test::negation::contradiction - should panic", "test::misc::endless_loop", "test::discriminant_kind::discriminant_kind_impl", "test::negation::negative_answer_ambiguous - should panic", "test::impls::partial_overlap_3", "test::misc::subgoal_cycle_inhabited", "test::negation::example_2_3_EWFS - should panic", "test::negation::example_3_3_EWFS - should panic", "test::misc::non_enumerable_traits_double", "test::lifetimes::empty_outlives", "test::lifetimes::erased_outlives", "test::negation::negative_loop - should panic", "test::negation::example_2_2_EWFS", "test::misc::flounder_ambiguous", "test::misc::recursive_hang", "test::lifetimes::static_outlives", "test::existential_types::dyn_higher_ranked_type_arguments", "test::impls::generic_trait", "test::negation::negation_free_vars", "test::misc::non_enumerable_traits_reorder", "test::misc::non_enumerable_traits_direct", "test::misc::only_draw_so_many_blow_up", "test::misc::env_bound_vars", "test::existential_types::dyn_super_trait_simple", "test::misc::not_really_ambig", "test::misc::normalize_ambiguous", "test::impls::prove_infer", "test::negation::negative_reorder", "test::never::never_is_sized", "test::numerics::integer_ambiguity", "test::lifetimes::static_impls", "test::numerics::float_kind_trait", "test::numerics::float_ambiguity", "test::coherence::orphan_check", "test::fn_def::generic_fn_implements_fn_traits", "test::misc::lifetime_outlives_constraints", "test::misc::only_draw_so_many", "test::never::never_is_well_formed", "test::numerics::integer_kind_trait", "test::numerics::integers_are_sized", "test::impls::partial_overlap_2", "test::numerics::integer_index", "test::numerics::integers_are_not_floats", "test::numerics::ambiguous_add", "test::projection::guidance_for_projection_on_flounder", "test::numerics::shl_ice", "test::numerics::integers_are_copy", "test::impls::clauses_in_if_goals", "test::misc::builtin_impl_enumeration", "test::numerics::unify_general_then_specific_ty", "test::negation::deep_negation", "test::opaque_types::opaque_generics_simple", "test::misc::type_outlives_constraints", "test::opaque_types::opaque_trait_generic", "test::numerics::integer_and_float_are_specialized_ty_kinds", "test::opaque_types::opaque_bounds", "test::opaque_types::opaque_super_trait", "test::projection::forall_projection", "test::numerics::general_ty_kind_becomes_specific", "test::projection::normalize_gat1", "test::closures::closure_is_copy", "test::object_safe::object_safe_flag", "test::implied_bounds::gat_implied_bounds", "test::impls::prove_clone", "test::projection::issue_144_regression", "test::projection::rust_analyzer_regression", "test::projection::normalize_gat_with_higher_ranked_trait_bound", "test::opaque_types::opaque_auto_traits", "test::projection::normalize_into_iterator", "test::projection::projection_equality_priority1", "test::opaque_types::opaque_reveal", "test::misc::futures_ambiguity", "test::projection::projection_equality_from_env", "test::misc::subgoal_cycle_uninhabited", "test::negation::negation_quantifiers", "test::refs::immut_refs_are_sized", "test::projection::projection_to_dyn", "test::type_flags::dyn_ty_flags_correct", "test::type_flags::flagless_ty_has_no_flags", "test::type_flags::opaque_ty_flags_correct", "test::type_flags::placeholder_ty_flags_correct", "test::opaque_types::opaque_auto_traits_indirect", "test::projection::projection_equality_nested", "test::type_flags::static_and_bound_lifetimes", "test::slices::slices_are_not_clone", "test::string::str_is_not_copy", "test::string::str_is_well_formed", "test::projection::normalize_under_binder_multi", "test::fn_def::fn_def_implements_fn_traits", "test::slices::slices_are_not_copy", "test::refs::mut_refs_are_well_formed", "test::slices::slices_are_not_sized", "test::refs::mut_refs_are_sized", "test::coherence_goals::local_and_upstream_types", "test::projection::normalize_gat_with_where_clause", "test::string::str_trait_impl", "test::subtype::variance_lowering", "test::subtype::fn_lifetime_variance_args", "test::projection::projection_from_env_a", "test::misc::subgoal_abstraction", "test::subtype::generalize_covariant_struct", "test::string::str_is_not_clone", "test::subtype::generalize_contravariant_struct", "test::projection::normalize_gat_with_where_clause2", "test::refs::immut_refs_are_well_formed", "test::projection::projection_from_env_slow", "test::string::str_is_not_sized", "test::subtype::generalize_invariant_struct", "test::subtype::generalize", "test::subtype::multi_lifetime", "test::projection::projection_to_opaque", "test::subtype::multi_lifetime_inverted", "test::unpin::unpin_lowering", "test::opaque_types::opaque_generics", "test::subtype::subtype_simple", "test::projection::projection_equality", "test::projection::gat_unify_with_implied_wc", "test::subtype::ref_lifetime_variance", "test::subtype::struct_lifetime_variance", "test::projection::normalize_gat2", "test::subtype::generalize_2tuple", "test::unify::forall_equality_solveable_simple", "test::unify::equality_binder", "test::subtype::fn_lifetime_variance_with_return_type", "test::slices::slices_are_well_formed_if_elem_sized", "test::subtype::generalize_array", "test::projection::normalize_gat_const", "test::subtype::generalize_tuple", "test::wf_lowering::cyclic_wf_requirements", "display::trait_::test_wellknown_traits", "test::unify::mixed_indices_unify", "test::unify::mixed_indices_normalize_application", "test::discriminant_kind::discriminant_kind_assoc", "test::unify::forall_equality_unsolveable_simple", "display::trait_::test_trait_flags", "test::unpin::unpin_inherit_negative", "test::unify::mixed_indices_normalize_gat_application", "test::unify::mixed_indices_match_program", "test::unpin::unpin_auto_trait", "test::unpin::unpin_negative", "test::subtype::generalize_slice", "test::subtype::multi_lifetime_slice", "test::subtype::multi_lifetime_invariant_struct", "test::unpin::unpin_overwrite", "test::subtype::multi_lifetime_array", "test::impls::prove_forall", "test::subtype::multi_lifetime_contravariant_struct", "test::subtype::multi_lifetime_covariant_struct", "test::subtype::multi_lifetime_tuple", "test::wf_lowering::bound_in_header_from_env", "test::wf_goals::drop_compatible", "test::wf_lowering::higher_ranked_trait_bound_on_gat", "test::wf_lowering::ill_formed_ty_decl", "test::wf_lowering::implied_bounds_on_ty_decl", "test::wf_lowering::ill_formed_assoc_ty", "test::wf_lowering::well_formed_trait_decl", "test::opaque_types::opaque_where_clause", "test::wf_lowering::ill_formed_trait_decl", "test::unify::equality_binder2", "test::wf_goals::placeholder_wf", "test::wf_lowering::no_unsize_impls", "test::wf_lowering::implied_bounds", "test::projection::forall_projection_gat", "test::wf_goals::recursive_where_clause_on_type", "test::wf_lowering::assoc_type_recursive_bound", "test::wf_lowering::ill_formed_opaque_ty", "test::wf_lowering::higher_ranked_trait_bounds", "test::unify::region_equality", "test::unify::unify_quantified_lifetimes", "test::wf_lowering::mixed_indices_check_projection_bounds", "test::wf_lowering::generic_projection_where_clause", "test::wf_lowering::higher_ranked_inline_bound_on_gat", "test::unsize::array_unsizing", "test::wf_lowering::mixed_indices_check_generic_projection_bounds", "test::wf_lowering::enum_sized_constraints", "test::unpin::generator_unpin", "test::wf_lowering::wf_requiremements_for_projection", "test::negation::simple_negation", "test::wf_lowering::cyclic_traits", "test::unify::quantified_types", "test::wf_lowering::generic_projection_bound", "test::wf_lowering::drop_constraints", "test::wf_lowering::higher_ranked_cyclic_requirements", "test::wf_lowering::ill_formed_type_in_header", "test::projection::projection_equality_priority2", "test::wf_goals::enum_wf", "test::tuples::tuple_trait_impl", "test::scalars::scalar_in_tuple_trait_impl", "test::projection::normalize_under_binder", "test::wf_lowering::struct_sized_constraints", "test::impls::suggested_subst", "test::projection::normalize_basic", "test::wf_goals::struct_wf", "test::generators::generator_test", "test::wf_lowering::coerce_unsized_pointer", "test::wf_lowering::coerce_unsized_struct", "test::unify::forall_equality", "test::closures::closure_implements_fn_traits", "test::tuples::tuples_are_wf", "test::auto_traits::builtin_auto_trait", "test::tuples::tuples_are_clone", "test::tuples::tuples_are_copy", "test::unsize::tuple_unsizing", "test::tuples::tuples_are_sized", "test::coherence_goals::is_fully_visible", "test::wf_lowering::copy_constraints", "display::built_ins::test_scalar_types", "test::functions::function_implement_fn_traits", "test::unsize::dyn_to_dyn_unsizing", "test::unsize::struct_unsizing", "test::scalars::scalars_are_well_formed", "test::unsize::ty_to_dyn_unsizing", "test::scalars::scalars_are_sized", "test::projection::iterator_flatten", "test::coherence_goals::fundamental_types", "test::coherence_goals::local_impl_allowed_for_traits", "test::scalars::scalar_trait_impl" ]
[]
[]
auto_2025-06-13
rust-lang/chalk
392
rust-lang__chalk-392
[ "306" ]
154020e4884e7b9fe41a93a6970cfff78783cdcc
diff --git a/chalk-solve/src/solve/slg.rs b/chalk-solve/src/solve/slg.rs --- a/chalk-solve/src/solve/slg.rs +++ b/chalk-solve/src/solve/slg.rs @@ -348,9 +348,7 @@ impl<I: Interner> TruncatingInferenceTable<I> { impl<I: Interner> context::TruncateOps<SlgContext<I>> for TruncatingInferenceTable<I> { fn goal_needs_truncation(&mut self, interner: &I, subgoal: &InEnvironment<Goal<I>>) -> bool { - // We only want to check the goal itself. We keep the environment intact. - // See rust-lang/chalk#280 - truncate::needs_truncation(interner, &mut self.infer, self.max_size, &subgoal.goal) + truncate::needs_truncation(interner, &mut self.infer, self.max_size, &subgoal) } fn answer_needs_truncation(&mut self, interner: &I, subst: &Substitution<I>) -> bool {
diff --git a/tests/test/projection.rs b/tests/test/projection.rs --- a/tests/test/projection.rs +++ b/tests/test/projection.rs @@ -712,8 +712,8 @@ fn rust_analyzer_regression() { PI: ParallelIterator } } - } yields_all[SolverChoice::slg(4, None)] { - "substitution [], lifetime constraints []" + } yields_first[SolverChoice::slg(4, None)] { + "Floundered" } } }
deferred: can we / should we truncate the environment, and how to avoid loops? In https://github.com/rust-lang/chalk/pull/294, we opted to stop truncating the environment. The problem was due to an infinite loop that arose in some rust-analyzer cases. The scenario [was described on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/144729-wg-traits/topic/design.20meeting.202019.2E12.2E09/near/182989871) recently but is also covered in #280 and #289. In short, we would truncate a projection `Foo::Bar` from the environment and replace it with an inference variable `?X`. When we get back an answer, we would unify `Foo::Bar` with the value inferred for `?X` -- which would up being a fresh inference variable. This would create a projection goal, but that projection goal includes the same environment that we started with, and hence that same environment would get truncated again. This would result in the cycle beginning anew. For now, we opted to just stop truncating the environment, because it isn't really needed at the moment -- Rust doesn't generate queries that grow the environment in indefinite ways. But we may want to revisit this with another fix, or -- depending on how we resolve normalization -- this may become a non-issue in the future. <!-- TRIAGEBOT_START --> <!-- TRIAGEBOT_ASSIGN_START --> This issue has been assigned to @zaharidichev via [this comment](https://github.com/rust-lang/chalk/issues/306#issuecomment-612038103). <!-- TRIAGEBOT_ASSIGN_DATA_START$${"user":"zaharidichev"}$$TRIAGEBOT_ASSIGN_DATA_END --> <!-- TRIAGEBOT_ASSIGN_END --> <!-- TRIAGEBOT_END -->
Thinking more about this, now that truncation in general just leads to `Floundering`, we should also just check if the `Environment` is too large. I think this question is still *valid* if we ever add truncation back in, but I'm not sure it should be an open issue, rather than just a note when `Environment` truncation is checked. This should be pretty easy to fix, so I'll mark it as a `good first issue`. @rustbot claim
2020-04-13T14:38:34Z
0.1
2020-04-14T19:19:57Z
154020e4884e7b9fe41a93a6970cfff78783cdcc
[ "test::projection::rust_analyzer_regression" ]
[ "lowering::invalid_name", "lowering::not_trait", "lowering::gat_higher_ranked_bound", "lowering::lower_success", "test::coherence::overlapping_negative_positive_impls", "test::coherence::two_impls_for_same_type", "lowering::upstream_items", "lowering::fundamental_multiple_type_parameters", "lowering::type_parameter", "lowering::type_parameter_bound", "test::coherence::concrete_impl_and_blanket_impl", "test::coherence::multiple_parameters", "test::coherence::generic_vec_and_specific_vec", "test::coherence::multiple_nonoverlapping_impls", "test::coherence::two_blanket_impls_open_ended", "test::coherence::downstream_impl_of_fundamental_43355", "test::coherence::two_blanket_impls", "test::coherence::local_negative_reasoning_in_coherence", "test::coherence::overlapping_negative_impls", "lowering::assoc_tys", "test::coherence::overlapping_assoc_types_error", "test::auto_traits::auto_traits_flounder", "test::coherence::overlapping_assoc_types", "lowering::atc_accounting", "lowering::gat_parse", "lowering::negative_impl", "lowering::goal_quantifiers", "test::coinduction::coinductive_multicycle1", "test::coinduction::coinductive_trivial_variant3", "test::coherence::nonoverlapping_assoc_types", "test::coinduction::coinductive_multicycle2", "test::existential_types::dyn_Clone_is_Clone", "test::coinduction::coinductive_trivial_variant1", "test::cycle::overflow_universe", "test::coinduction::coinductive_multicycle4", "test::coinduction::coinductive_multicycle3", "test::existential_types::dyn_Clone_is_not_Send", "test::existential_types::dyn_Clone_Send_is_Send", "test::coinduction::coinductive_unsound1", "test::coinduction::coinductive_unsound2", "test::cycle::cycle_no_solution", "test::coinduction::coinductive_nontrivial", "test::coherence::fundamental_traits", "test::coinduction::coinductive_trivial_variant2", "test::implied_bounds::implied_bounds", "test::impls::ordering", "test::impls::higher_ranked", "test::impls::deep_success", "test::cycle::cycle_many_solutions", "test::impls::normalize_rev_infer", "test::cycle::cycle_unique_solution", "test::impls::normalize_rev_infer_gat", "test::impls::definite_guidance", "test::impls::inapplicable_assumption_does_not_shadow", "test::impls::where_clause_trumps", "test::cycle::inner_cycle", "test::misc::basic", "test::misc::cached_answers_1", "test::existential_types::dyn_Foo_Bar", "test::misc::cached_answers_2", "test::misc::basic_region_constraint_from_positive_impl", "test::coinduction::mixed_semantics", "test::misc::flounder", "lowering::duplicate_parameters", "lowering::auto_trait", "test::cycle::infinite_recursion", "test::negation::contradiction", "test::implied_bounds::implied_from_env", "test::auto_traits::auto_trait_without_impls", "test::cycle::multiple_ambiguous_cycles", "test::impls::deep_failure", "test::misc::cached_answers_3", "test::misc::non_enumerable_traits_indirect", "test::misc::example_2_1_EWFS", "test::negation::example_3_3_EWFS", "test::negation::example_2_3_EWFS", "test::negation::example_2_2_EWFS", "test::coinduction::coinductive_unification", "test::projection::forall_projection", "test::existential_types::dyn_binders_reverse", "test::negation::negative_answer_ambiguous", "test::negation::negation_free_vars", "test::impls::generic_trait", "test::projection::issue_144_regression", "test::misc::subgoal_cycle_inhabited", "test::projection::normalize_gat1", "test::negation::negative_loop", "test::implied_bounds::higher_ranked_implied_bounds", "test::misc::non_enumerable_traits_double", "test::wf_lowering::cyclic_wf_requirements", "test::unify::equality_binder", "test::misc::only_draw_so_many_blow_up", "test::impls::partial_overlap_3", "test::projection::normalize_gat_with_higher_ranked_trait_bound", "test::unify::mixed_indices_unify", "test::unify::mixed_indices_match_program", "test::impls::prove_infer", "test::wf_lowering::higher_ranked_trait_bound_on_gat", "test::wf_lowering::ill_formed_ty_decl", "test::unify::mixed_indices_normalize_application", "test::wf_lowering::ill_formed_trait_decl", "test::existential_types::dyn_higher_ranked_type_arguments", "test::projection::normalize_into_iterator", "test::unify::mixed_indices_normalize_gat_application", "test::wf_lowering::ill_formed_assoc_ty", "test::negation::deep_negation", "test::negation::negation_quantifiers", "test::auto_traits::auto_semantics", "test::projection::projection_from_env_a", "test::negation::negative_reorder", "test::wf_lowering::well_formed_trait_decl", "test::impls::clauses_in_if_goals", "lowering::check_parameter_kinds", "test::misc::non_enumerable_traits_direct", "test::auto_traits::auto_trait_with_impls", "test::misc::only_draw_so_many", "test::unify::equality_binder2", "test::wf_lowering::implied_bounds_on_ty_decl", "test::projection::normalize_gat_with_where_clause", "test::impls::partial_overlap_2", "test::projection::normalize_gat_with_where_clause2", "test::misc::futures_ambiguity", "test::wf_lowering::bound_in_header_from_env", "test::impls::prove_clone", "test::projection::normalize_under_binder_multi", "test::wf_lowering::implied_bounds", "test::misc::non_enumerable_traits_reorder", "test::wf_lowering::higher_ranked_inline_bound_on_gat", "test::wf_goals::recursive_where_clause_on_type", "test::projection::projection_equality", "test::unify::forall_equality", "test::projection::projection_from_env_slow", "test::unify::unify_quantified_lifetimes", "test::unify::region_equality", "test::wf_lowering::higher_ranked_trait_bounds", "test::projection::gat_unify_with_implied_wc", "test::wf_lowering::mixed_indices_check_projection_bounds", "test::implied_bounds::gat_implied_bounds", "test::wf_lowering::generic_projection_where_clause", "test::projection::normalize_gat2", "test::wf_lowering::assoc_type_recursive_bound", "test::wf_lowering::wf_requiremements_for_projection", "test::cycle::overflow", "test::unify::quantified_types", "test::wf_lowering::ill_formed_type_in_header", "test::projection::forall_projection_gat", "test::wf_lowering::cyclic_traits", "test::wf_lowering::generic_projection_bound", "test::wf_goals::struct_wf", "test::impls::prove_forall", "test::projection::normalize_under_binder", "test::wf_lowering::mixed_indices_check_generic_projection_bounds", "test::negation::simple_negation", "test::coherence_goals::local_and_upstream_types", "test::misc::subgoal_cycle_uninhabited", "test::wf_lowering::struct_sized_constraints", "test::projection::normalize_basic", "test::wf_lowering::higher_ranked_cyclic_requirements", "test::impls::suggested_subst", "test::coherence::orphan_check", "test::coherence_goals::is_fully_visible", "test::coherence_goals::fundamental_types", "test::coherence_goals::local_impl_allowed_for_traits", "test::misc::subgoal_abstraction" ]
[]
[]
auto_2025-06-13
atuinsh/atuin
747
atuinsh__atuin-747
[ "745" ]
d46e3ad47d03e53232269973806fb9da2248ba19
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs --- a/atuin-client/src/import/bash.rs +++ b/atuin-client/src/import/bash.rs @@ -1,8 +1,10 @@ -use std::{fs::File, io::Read, path::PathBuf}; +use std::{fs::File, io::Read, path::PathBuf, str}; use async_trait::async_trait; +use chrono::{DateTime, Duration, NaiveDateTime, Utc}; use directories::UserDirs; use eyre::{eyre, Result}; +use itertools::Itertools; use super::{get_histpath, unix_byte_lines, Importer, Loader}; use crate::history::History; diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs --- a/atuin-client/src/import/bash.rs +++ b/atuin-client/src/import/bash.rs @@ -32,37 +34,54 @@ impl Importer for Bash { } async fn entries(&mut self) -> Result<usize> { - Ok(super::count_lines(&self.bytes)) + let count = unix_byte_lines(&self.bytes) + .map(LineType::from) + .filter(|line| matches!(line, LineType::Command(_))) + .count(); + Ok(count) } async fn load(self, h: &mut impl Loader) -> Result<()> { - let now = chrono::Utc::now(); - let mut line = String::new(); - - for (i, b) in unix_byte_lines(&self.bytes).enumerate() { - let s = match std::str::from_utf8(b) { - Ok(s) => s, - Err(_) => continue, // we can skip past things like invalid utf8 - }; - - if let Some(s) = s.strip_suffix('\\') { - line.push_str(s); - line.push_str("\\\n"); - } else { - line.push_str(s); - let command = std::mem::take(&mut line); - - let offset = chrono::Duration::seconds(i as i64); - h.push(History::new( - now - offset, // preserve ordering - command, - String::from("unknown"), - -1, - -1, - None, - None, - )) - .await?; + let lines = unix_byte_lines(&self.bytes) + .map(LineType::from) + .filter(|line| !matches!(line, LineType::NotUtf8)) // invalid utf8 are ignored + .collect_vec(); + + let (commands_before_first_timestamp, first_timestamp) = lines + .iter() + .enumerate() + .find_map(|(i, line)| match line { + LineType::Timestamp(t) => Some((i, *t)), + _ => None, + }) + // if no known timestamps, use now as base + .unwrap_or((lines.len(), Utc::now())); + + // if no timestamp is recorded, then use this increment to set an arbitrary timestamp + // to preserve ordering + let timestamp_increment = Duration::seconds(1); + // make sure there is a minimum amount of time before the first known timestamp + // to fit all commands, given the default increment + let mut next_timestamp = + first_timestamp - timestamp_increment * commands_before_first_timestamp as i32; + + for line in lines.into_iter() { + match line { + LineType::NotUtf8 => unreachable!(), // already filtered + LineType::Timestamp(t) => next_timestamp = t, + LineType::Command(c) => { + let entry = History::new( + next_timestamp, + c.into(), + "unknown".into(), + -1, + -1, + None, + None, + ); + h.push(entry).await?; + next_timestamp += timestamp_increment; + } } } diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs --- a/atuin-client/src/import/bash.rs +++ b/atuin-client/src/import/bash.rs @@ -89,7 +137,7 @@ cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷ .to_owned(); let mut bash = Bash { bytes }; - assert_eq!(bash.entries().await.unwrap(), 4); + assert_eq!(bash.entries().await.unwrap(), 3); let mut loader = TestLoader::default(); bash.load(&mut loader).await.unwrap();
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs --- a/atuin-client/src/import/bash.rs +++ b/atuin-client/src/import/bash.rs @@ -70,18 +89,47 @@ impl Importer for Bash { } } +#[derive(Debug, Clone)] +enum LineType<'a> { + NotUtf8, + /// A timestamp line start with a '#', followed immediately by an integer + /// that represents seconds since UNIX epoch. + Timestamp(DateTime<Utc>), + /// Anything that doesn't look like a timestamp. + Command(&'a str), +} +impl<'a> From<&'a [u8]> for LineType<'a> { + fn from(bytes: &'a [u8]) -> Self { + let Ok(line) = str::from_utf8(bytes) else { + return LineType::NotUtf8; + }; + let parsed = match try_parse_line_as_timestamp(line) { + Some(time) => LineType::Timestamp(time), + None => LineType::Command(line), + }; + parsed + } +} + +fn try_parse_line_as_timestamp(line: &str) -> Option<DateTime<Utc>> { + let seconds = line.strip_prefix('#')?.parse().ok()?; + let time = NaiveDateTime::from_timestamp(seconds, 0); + Some(DateTime::from_utc(time, Utc)) +} + #[cfg(test)] -mod tests { - use itertools::assert_equal; +mod test { + use std::cmp::Ordering; + + use itertools::{assert_equal, Itertools}; use crate::import::{tests::TestLoader, Importer}; use super::Bash; #[tokio::test] - async fn test_parse_file() { + async fn parse_no_timestamps() { let bytes = r"cargo install atuin -cargo install atuin; \ cargo update cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷ " diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs --- a/atuin-client/src/import/bash.rs +++ b/atuin-client/src/import/bash.rs @@ -98,9 +146,72 @@ cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷ loader.buf.iter().map(|h| h.command.as_str()), [ "cargo install atuin", - "cargo install atuin; \\\ncargo update", + "cargo update", "cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷", ], ); + assert!(is_strictly_sorted( + loader.buf.iter().map(|h| h.timestamp.timestamp()) + )) + } + + #[tokio::test] + async fn parse_with_timestamps() { + let bytes = b"#1672918999 +git reset +#1672919006 +git clean -dxf +#1672919020 +cd ../ +" + .to_vec(); + + let mut bash = Bash { bytes }; + assert_eq!(bash.entries().await.unwrap(), 3); + + let mut loader = TestLoader::default(); + bash.load(&mut loader).await.unwrap(); + + assert_equal( + loader.buf.iter().map(|h| h.command.as_str()), + ["git reset", "git clean -dxf", "cd ../"], + ); + assert_equal( + loader.buf.iter().map(|h| h.timestamp.timestamp()), + [1672918999, 1672919006, 1672919020], + ) + } + + #[tokio::test] + async fn parse_with_partial_timestamps() { + let bytes = b"git reset +#1672919006 +git clean -dxf +cd ../ +" + .to_vec(); + + let mut bash = Bash { bytes }; + assert_eq!(bash.entries().await.unwrap(), 3); + + let mut loader = TestLoader::default(); + bash.load(&mut loader).await.unwrap(); + + assert_equal( + loader.buf.iter().map(|h| h.command.as_str()), + ["git reset", "git clean -dxf", "cd ../"], + ); + assert!(is_strictly_sorted( + loader.buf.iter().map(|h| h.timestamp.timestamp()) + )) + } + + fn is_strictly_sorted<T>(iter: impl IntoIterator<Item = T>) -> bool + where + T: Clone + PartialOrd, + { + iter.into_iter() + .tuple_windows() + .all(|(a, b)| matches!(a.partial_cmp(&b), Some(Ordering::Less))) } }
Bash history import issues I spotted two issues while trying to import my Bash history: 1. Import ordering is incorrectly reversed. 2. `.bash_history` can be configured to store timestamps, a case not handled. --- ## Ordering In the following snippet, lines from the top of the file will receive the newest timestamp: https://github.com/cyqsimon/atuin/blob/d46e3ad47d03e53232269973806fb9da2248ba19/atuin-client/src/import/bash.rs#L42-L67 This is incorrect for `.bash_history` - new items are appended to the end of the file, not the start. So the first lines are in fact the oldest commands. ## Stored timestamps The current import code for Bash assumes that each line is a command. However if `HISTTIMEFORMAT` is set, then a timestamp is recorded for each command (see `man bash`). So `.bash_history` would look something like this: ``` #1672918999 git reset #1672919006 git clean -dxf #1672919020 cd ../ ``` This case is currently not handled, so the timestamp lines are getting falsely-imported as commands. --- I am working on a patch that will fix both these issues, so give me a little while and I'll submit a PR. The reason I'm posing this issue mostly concerns the extent of the ordering problem. Did it happen because - the original author used a different shell that does store the newest commands at the start of its history file, and wrongly assumed the same for Bash? - or the original author made a simple arithmetic mistake, and this is an issue for the import code of all shells? In other words, I'm not that familiar with other shells, so does the import code for them need fixing as well?
2023-03-01T16:30:56Z
13.0
2023-04-05T15:22:17Z
edcd477153d00944c5dae16ec3ba69e339e1450c
[ "encryption::test::test_encrypt_decrypt", "import::zsh::test::test_parse_extended_simple", "import::zsh::test::test_parse_file", "import::fish::test::parse_complex", "import::zsh_histdb::test::test_env_vars", "import::zsh_histdb::test::test_import", "database::test::test_search_prefix", "database::test::test_search_reordered_fuzzy", "database::test::test_search_fulltext", "database::test::test_search_fuzzy", "database::test::test_search_bench_dupes" ]
[]
[]
[]
auto_2025-06-06
atuinsh/atuin
1,238
atuinsh__atuin-1238
[ "691" ]
15abf429842969e56598b1922a21693a7253f117
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs --- a/atuin-client/src/api_client.rs +++ b/atuin-client/src/api_client.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; use std::env; +use std::time::Duration; use eyre::{bail, Result}; use reqwest::{ diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs --- a/atuin-client/src/api_client.rs +++ b/atuin-client/src/api_client.rs @@ -115,6 +121,8 @@ impl<'a> Client<'a> { client: reqwest::Client::builder() .user_agent(APP_USER_AGENT) .default_headers(headers) + .connect_timeout(Duration::new(connect_timeout, 0)) + .timeout(Duration::new(timeout, 0)) .build()?, }) } diff --git a/atuin-client/src/record/sync.rs b/atuin-client/src/record/sync.rs --- a/atuin-client/src/record/sync.rs +++ b/atuin-client/src/record/sync.rs @@ -22,7 +22,12 @@ pub enum Operation { } pub async fn diff(settings: &Settings, store: &mut impl Store) -> Result<(Vec<Diff>, RecordIndex)> { - let client = Client::new(&settings.sync_address, &settings.session_token)?; + let client = Client::new( + &settings.sync_address, + &settings.session_token, + settings.network_connect_timeout, + settings.network_timeout, + )?; let local_index = store.tail_records().await?; let remote_index = client.record_index().await?; diff --git a/atuin-client/src/record/sync.rs b/atuin-client/src/record/sync.rs --- a/atuin-client/src/record/sync.rs +++ b/atuin-client/src/record/sync.rs @@ -218,7 +223,12 @@ pub async fn sync_remote( local_store: &mut impl Store, settings: &Settings, ) -> Result<(i64, i64)> { - let client = Client::new(&settings.sync_address, &settings.session_token)?; + let client = Client::new( + &settings.sync_address, + &settings.session_token, + settings.network_connect_timeout, + settings.network_timeout, + )?; let mut uploaded = 0; let mut downloaded = 0; diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs --- a/atuin-client/src/settings.rs +++ b/atuin-client/src/settings.rs @@ -175,6 +175,9 @@ pub struct Settings { pub workspaces: bool, pub ctrl_n_shortcuts: bool, + pub network_connect_timeout: u64, + pub network_timeout: u64, + // This is automatically loaded when settings is created. Do not set in // config! Keep secrets and settings apart. pub session_token: String, diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs --- a/atuin-client/src/settings.rs +++ b/atuin-client/src/settings.rs @@ -371,6 +374,8 @@ impl Settings { .set_default("workspaces", false)? .set_default("ctrl_n_shortcuts", false)? .set_default("secrets_filter", true)? + .set_default("network_connect_timeout", 5)? + .set_default("network_timeout", 30)? .add_source( Environment::with_prefix("atuin") .prefix_separator("_") diff --git a/atuin-client/src/sync.rs b/atuin-client/src/sync.rs --- a/atuin-client/src/sync.rs +++ b/atuin-client/src/sync.rs @@ -189,7 +189,12 @@ async fn sync_upload( } pub async fn sync(settings: &Settings, force: bool, db: &mut (impl Database + Send)) -> Result<()> { - let client = api_client::Client::new(&settings.sync_address, &settings.session_token)?; + let client = api_client::Client::new( + &settings.sync_address, + &settings.session_token, + settings.network_connect_timeout, + settings.network_timeout, + )?; let key = load_key(settings)?; // encryption key diff --git a/atuin/src/command/client/account/delete.rs b/atuin/src/command/client/account/delete.rs --- a/atuin/src/command/client/account/delete.rs +++ b/atuin/src/command/client/account/delete.rs @@ -9,7 +9,12 @@ pub async fn run(settings: &Settings) -> Result<()> { bail!("You are not logged in"); } - let client = api_client::Client::new(&settings.sync_address, &settings.session_token)?; + let client = api_client::Client::new( + &settings.sync_address, + &settings.session_token, + settings.network_connect_timeout, + settings.network_timeout, + )?; client.delete().await?; diff --git a/atuin/src/command/client/sync/status.rs b/atuin/src/command/client/sync/status.rs --- a/atuin/src/command/client/sync/status.rs +++ b/atuin/src/command/client/sync/status.rs @@ -4,7 +4,12 @@ use colored::Colorize; use eyre::Result; pub async fn run(settings: &Settings, db: &impl Database) -> Result<()> { - let client = api_client::Client::new(&settings.sync_address, &settings.session_token)?; + let client = api_client::Client::new( + &settings.sync_address, + &settings.session_token, + settings.network_connect_timeout, + settings.network_timeout, + )?; let status = client.status().await?; let last_sync = Settings::last_sync()?; diff --git a/docs/docs/config/config.md b/docs/docs/config/config.md --- a/docs/docs/config/config.md +++ b/docs/docs/config/config.md @@ -280,3 +280,16 @@ macOS does not have an <kbd>Alt</kbd> key, although terminal emulators can often # Use Ctrl-0 .. Ctrl-9 instead of Alt-0 .. Alt-9 UI shortcuts ctrl_n_shortcuts = true ``` + +## network_timeout +Default: 30 + +The max amount of time (in seconds) to wait for a network request. If any +operations with a sync server take longer than this, the code will fail - +rather than wait indefinitely. + +## network_connect_timeout +Default: 5 + +The max time (in seconds) we wait for a connection to become established with a +remote sync server. Any longer than this and the request will fail.
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs --- a/atuin-client/src/api_client.rs +++ b/atuin-client/src/api_client.rs @@ -106,7 +107,12 @@ pub async fn latest_version() -> Result<Version> { } impl<'a> Client<'a> { - pub fn new(sync_addr: &'a str, session_token: &'a str) -> Result<Self> { + pub fn new( + sync_addr: &'a str, + session_token: &'a str, + connect_timeout: u64, + timeout: u64, + ) -> Result<Self> { let mut headers = HeaderMap::new(); headers.insert(AUTHORIZATION, format!("Token {session_token}").parse()?); diff --git a/atuin/tests/sync.rs b/atuin/tests/sync.rs --- a/atuin/tests/sync.rs +++ b/atuin/tests/sync.rs @@ -77,7 +77,7 @@ async fn registration() { .await .unwrap(); - let client = api_client::Client::new(&address, &registration_response.session).unwrap(); + let client = api_client::Client::new(&address, &registration_response.session, 5, 30).unwrap(); // the session token works let status = client.status().await.unwrap();
atuin hangs at first start in bad network environments This issue can be reproduced with the following preconditions: - a really (as in awfully) bad network environment with a rather large-ish (>=98%) packet loss rate - using atuin to browse the history the first time after boot Atuin hangs for an indefinite amount of time while trying to make a request to atuin.sh: ``` connect(13, {sa_family=AF_INET, sin_port=htons(443), sin_addr=inet_addr("104.21.80.213")}, 16) = -1 EINPROGRESS (Operation now in progress) epoll_ctl(5, EPOLL_CTL_ADD, 13, {events=EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLET, data={u32=1, u64=1}}) = 0 write(4, "\1\0\0\0\0\0\0\0", 8) = 8 epoll_wait(3, [{events=EPOLLIN, data={u32=2147483648, u64=2147483648}}], 1024, 249) = 1 epoll_wait(3, [], 1024, 249) = 0 epoll_wait(3, [], 1024, 51) = 0 write(4, "\1\0\0\0\0\0\0\0", 8) = 8 socket(AF_INET6, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_TCP) = 14 fcntl(14, F_GETFL) = 0x2 (flags O_RDWR) fcntl(14, F_SETFL, O_RDWR|O_NONBLOCK) = 0 connect(14, {sa_family=AF_INET6, sin6_port=htons(443), sin6_flowinfo=htonl(0), inet_pton(AF_INET6, "2606:4700:3037::6815:50d5", &sin6_addr), sin6_scope_id=0}, 28) = -1 ENETUNREACH (Network is unreachable) close(14) = 0 socket(AF_INET6, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_TCP) = 14 fcntl(14, F_GETFL) = 0x2 (flags O_RDWR) fcntl(14, F_SETFL, O_RDWR|O_NONBLOCK) = 0 connect(14, {sa_family=AF_INET6, sin6_port=htons(443), sin6_flowinfo=htonl(0), inet_pton(AF_INET6, "2606:4700:3030::ac43:9a5a", &sin6_addr), sin6_scope_id=0}, 28) = -1 ENETUNREACH (Network is unreachable) close(14) = 0 epoll_wait(3, [{events=EPOLLIN, data={u32=2147483648, u64=2147483648}}], 1024, 523979) = 1 epoll_wait(3, 0x564d2b85abe0, 1024, 523979) = -1 EINTR (Interrupted system call) ``` I have configured atuin for offline usage (e.g. am not using the sync server at atuin.sh) so I suspect this happens while querying what the latest version is, calling `latest_version()` as defined in `api_client.rs`. I haven't spend too much time debugging this yet, but suspect that letting the requests timeout after a few seconds should mitigate this issue.
Thanks for the report. I reckon I can rewrite this part to get the version lazily https://user-images.githubusercontent.com/6625462/216926816-fd536a1c-8f35-4a89-b097-8224638960bd.mov There we go :) This issue is sort of fixed but there's a related problem. There were 2 issues here: 1. Atuin _was_ blocking on that network request (fixed by @conradludgate ) 2. The Atuin client doesn't appear to use a timeout for any requests to the server, so may end up hanging forever in some cases. I think the fix for the second issue is to add a timeout to all the reqwest clients created in https://github.com/atuinsh/atuin/blob/main/atuin-client/src/api_client.rs
2023-09-17T17:26:20Z
16.0
2023-09-18T07:39:20Z
1735be05d71ec21ffb8648866fca83e210cfe31a
[ "encryption::test::test_decode_old", "encryption::test::test_decode", "encryption::test::key_encodings", "encryption::test::test_decode_deleted", "encryption::test::test_encrypt_decrypt", "kv::tests::encode_decode", "import::zsh::test::test_parse_extended_simple", "import::bash::test::parse_with_partial_timestamps", "import::bash::test::parse_no_timestamps", "import::bash::test::parse_with_timestamps", "import::fish::test::parse_complex", "import::zsh::test::test_parse_file", "record::encryption::tests::cannot_decrypt_different_key", "record::encryption::tests::full_record_round_trip", "record::encryption::tests::cannot_decrypt_different_id", "record::encryption::tests::round_trip", "record::encryption::tests::same_entry_different_output", "record::encryption::tests::full_record_round_trip_fail", "record::encryption::tests::re_encrypt_round_trip", "secrets::tests::test_secrets", "import::zsh_histdb::test::test_env_vars", "history::tests::disable_secrets", "record::sqlite_store::tests::create_db", "record::sqlite_store::tests::get_record", "record::sqlite_store::tests::len", "record::sqlite_store::tests::len_different_tags", "record::sqlite_store::tests::push_record", "kv::tests::build_kv", "import::zsh_histdb::test::test_import", "record::sync::tests::test_basic_diff", "record::sync::tests::build_two_way_diff", "database::test::test_search_prefix", "record::sync::tests::build_complex_diff", "database::test::test_search_reordered_fuzzy", "database::test::test_search_fulltext", "database::test::test_search_fuzzy", "record::sqlite_store::tests::append_a_bunch", "history::tests::privacy_test", "record::sqlite_store::tests::test_chain", "database::test::test_search_bench_dupes", "record::sqlite_store::tests::append_a_big_bunch", "atuin-client/src/history.rs - history::History::capture (line 149) - compile fail", "atuin-client/src/history.rs - history::History::import (line 116) - compile fail", "atuin-client/src/history.rs - history::History::from_db (line 167) - compile fail", "atuin-client/src/history.rs - history::History::import (line 89)", "atuin-client/src/history.rs - history::History::capture (line 136)", "atuin-client/src/history.rs - history::History::import (line 100)" ]
[]
[]
[]
auto_2025-06-06
atuinsh/atuin
2,058
atuinsh__atuin-2058
[ "1882" ]
4d74e38a515bc14381e1342afdf5ee2ec345f589
diff --git a/crates/atuin-history/src/stats.rs b/crates/atuin-history/src/stats.rs --- a/crates/atuin-history/src/stats.rs +++ b/crates/atuin-history/src/stats.rs @@ -92,7 +92,7 @@ fn split_at_pipe(command: &str) -> Vec<&str> { "\\" => if graphemes.next().is_some() {}, "|" => { if !quoted { - if command[start..].starts_with('|') { + if current > start && command[start..].starts_with('|') { start += 1; } result.push(&command[start..current]);
diff --git a/crates/atuin-history/src/stats.rs b/crates/atuin-history/src/stats.rs --- a/crates/atuin-history/src/stats.rs +++ b/crates/atuin-history/src/stats.rs @@ -396,4 +396,20 @@ mod tests { ["git commit -m \"🚀\""] ); } + + #[test] + fn starts_with_pipe() { + assert_eq!( + split_at_pipe("| sed 's/[0-9a-f]//g'"), + ["", " sed 's/[0-9a-f]//g'"] + ); + } + + #[test] + fn starts_with_spaces_and_pipe() { + assert_eq!( + split_at_pipe(" | sed 's/[0-9a-f]//g'"), + [" ", " sed 's/[0-9a-f]//g'"] + ); + } }
[Bug]: atuin stats panics when faced with unusual string in history ### What did you expect to happen? No panic! ;] ### What happened? When running `atuin stats` it panics with: ``` ❯ RUST_BACKTRACE=1 atuin stats thread 'main' panicked at atuin/src/command/client/stats.rs:56:41: begin <= end (1 <= 0) when slicing `| awk '{print $1}' | R --no-echo -e 'x <- scan(file="stdin", quiet=TRUE); summary(x)'` stack backtrace: 0: _rust_begin_unwind 1: core::panicking::panic_fmt 2: core::str::slice_error_fail_rt 3: core::str::slice_error_fail 4: atuin::command::client::stats::compute_stats 5: atuin::command::client::Cmd::run_inner::{{closure}} 6: tokio::runtime::scheduler::current_thread::Context::enter 7: tokio::runtime::context::set_scheduler 8: tokio::runtime::scheduler::current_thread::CoreGuard::block_on 9: tokio::runtime::context::runtime::enter_runtime 10: tokio::runtime::runtime::Runtime::block_on 11: atuin::main note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. ``` Now that string `| awk '{print $1}' | R --no-echo -e 'x <- scan(file="stdin", quiet=TRUE); summary(x)'` is actually in my history like that (it's the "entire" command), so obviously some copy-pasta failure on my part, but I don't think it should make `atuin` panic (maybe due to starting with a `|`?). ### Atuin doctor output ```yaml Atuin Doctor Checking for diagnostics Please include the output below with any bug reports or issues atuin: version: 18.1.0 sync: cloud: false records: true auto_sync: true last_sync: 2024-03-14 18:05:58.081633 +00:00:00 shell: name: zsh plugins: - atuin system: os: Darwin arch: x86_64 version: 14.3.1 disks: - name: Macintosh HD filesystem: apfs - name: Macintosh HD filesystem: apfs ``` ### Code of Conduct - [X] I agree to follow this project's Code of Conduct
seconding this- here's another fun string this happens with. ```console $ RUST_BACKTRACE=1 atuin stats thread 'main' panicked at atuin/src/command/client/stats.rs:56:41: begin <= end (1 <= 0) when slicing `|_| |____||___||_| |_| |___||_|_` stack backtrace: 0: 0x1054a29d0 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h61949099c17bb561 1: 0x1054ca8e0 - core::fmt::write::he0c0819610fe7c82 2: 0x105487c8c - std::io::Write::write_fmt::h14dadda6958822c3 3: 0x1054a2824 - std::sys_common::backtrace::print::h10166cbeffac9d38 4: 0x1054a3360 - std::panicking::default_hook::{{closure}}::hfec7fca779e11f3b 5: 0x1054a30e0 - std::panicking::default_hook::h26402d2c6670ffd0 6: 0x1054a39d4 - std::panicking::rust_panic_with_hook::hb00dd38969b5a277 7: 0x1054a378c - std::panicking::begin_panic_handler::{{closure}}::hc86edf66ba485638 8: 0x1054a2c04 - std::sys_common::backtrace::__rust_end_short_backtrace::h24f57ebe971b5eac 9: 0x1054a3514 - _rust_begin_unwind 10: 0x1055123e8 - core::panicking::panic_fmt::h21b3a72f47844886 11: 0x1054c6c10 - core::str::slice_error_fail_rt::h0bcfaeca513f69c4 12: 0x105512790 - core::str::slice_error_fail::h2e034b398f7b75a7 13: 0x104c3f69c - atuin::command::client::stats::compute_stats::h309a358b9b61ecd5 14: 0x104a24714 - atuin::command::client::Cmd::run_inner::{{closure}}::h4a9567b4490695de 15: 0x104b13448 - tokio::runtime::scheduler::current_thread::CoreGuard::block_on::h351c1c892460edf6 16: 0x104c38318 - tokio::runtime::context::runtime::enter_runtime::hef50c501bad43a82 17: 0x104b6e14c - tokio::runtime::runtime::Runtime::block_on::h7d3459fe69753074 18: 0x104bd38a4 - atuin::command::client::Cmd::run::h588a5ab129b29fa6 19: 0x104c400a4 - atuin::command::AtuinCmd::run::hf663edac3a0da924 20: 0x104bd3d70 - atuin::main::h61cb3fcec8322f37 21: 0x104b96218 - std::sys_common::backtrace::__rust_begin_short_backtrace::he76aba5053fdcc16 22: 0x104c242b8 - std::rt::lang_start::{{closure}}::h024e6bed810fd961 23: 0x1054a3400 - std::panicking::try::ha883230fd73a158c 24: 0x105485fc0 - std::rt::lang_start_internal::ha86617696da0c619 25: 0x104bd8c0c - _main ``` installed via nixpkgs/nix-darwin. atuin doctor output: ```yaml atuin: version: 18.1.0 sync: cloud: false records: false auto_sync: true last_sync: 2024-03-24 19:14:04.454307 +00:00:00 shell: name: zsh plugins: - atuin system: os: Darwin arch: arm64 version: '14.4' disks: - name: Macintosh HD filesystem: apfs - name: Macintosh HD filesystem: apfs ``` this helped me track down and a similar panic, with `| landscape` as a history entry. I deleted the entry in atuin to fix my stats output. Got something very similar: ``` atuin stats thread 'main' panicked at atuin/src/command/client/stats.rs:56:41: begin <= end (1 <= 0) when slicing `| wc -l` note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` It would be helpful if it printed the entire command that caused the problem, so I could delete it. something similar ![image](https://github.com/atuinsh/atuin/assets/1120692/7ca9cd61-c402-4507-845a-41158e0d9fef) ` RUST_BACKTRACE=full atuin stats thread 'main' panicked at atuin/src/command/client/stats.rs:56:41: begin <= end (1 <= 0) when slicing `| HTTPCode=%{http_code}\n\n"` stack backtrace: 0: 0x562b9d838c96 - <unknown> 1: 0x562b9d868f20 - <unknown> 2: 0x562b9d834f6f - <unknown>` Appears to happen for all commands starting with a pipe/| character for me (I used prune with a history_filter on the offending string in my config.toml to work around the issue). Here's my backtrace output: ``` ❯ atuin stats thread 'main' panicked at atuin/src/command/client/stats.rs:56:41: begin <= end (1 <= 0) when slicing `| grep -v CHOST` stack backtrace: 0: 0x105397884 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::hfb3c5255bdb4eac9 1: 0x1053cc6a4 - core::fmt::write::h4f9b26a431923163 2: 0x10539d8a8 - std::io::Write::write_fmt::h65a3848fda965d9a 3: 0x1053976b4 - std::sys_common::backtrace::print::hfb8e68d5340a5773 4: 0x1053adb90 - std::panicking::default_hook::{{closure}}::h3c1629cb3dea24df 5: 0x1053ad918 - std::panicking::default_hook::h5b4a788645c74387 6: 0x1053adf9c - std::panicking::rust_panic_with_hook::h2f1b18b39b6242c7 7: 0x105397d74 - std::panicking::begin_panic_handler::{{closure}}::hd6c9d27d8f83f59d 8: 0x105397ab8 - std::sys_common::backtrace::__rust_end_short_backtrace::hb3b76dda55c5a574 9: 0x1053add24 - _rust_begin_unwind 10: 0x10541fd60 - core::panicking::panic_fmt::h737710d5a381d17b 11: 0x1053cf9a0 - core::str::slice_error_fail_rt::h4b74b83a2a7f6848 12: 0x1054200b4 - core::str::slice_error_fail::h63b632dfbbc1ab21 13: 0x104b2a234 - atuin::command::client::stats::compute_stats::hda9c3aa01b72b14e 14: 0x10495420c - atuin::command::client::Cmd::run_inner::{{closure}}::ha0d80b7b53df7bfe 15: 0x1049e9670 - tokio::runtime::scheduler::current_thread::Context::enter::he4718aa49284b4be 16: 0x104abeb60 - tokio::runtime::context::scoped::Scoped<T>::set::h3ad6c66c16925748 17: 0x1049e984c - tokio::runtime::scheduler::current_thread::CoreGuard::block_on::ha97983b83be644af 18: 0x104ac06e0 - tokio::runtime::context::runtime::enter_runtime::h891287b6d7d34412 19: 0x104a38ac4 - atuin::command::client::Cmd::run::h1c7da15a92888fd9 20: 0x104b2b3cc - atuin::main::h45ddc4795688d199 21: 0x104a58bb0 - std::sys_common::backtrace::__rust_begin_short_backtrace::haad479e4b60591cd 22: 0x104a01e3c - std::rt::lang_start::{{closure}}::h862dbd93209a848c 23: 0x1053adc1c - std::panicking::try::he7b2dbdb2ebe3a2a 24: 0x105399730 - std::rt::lang_start_internal::h3cdb23022df8f974 25: 0x104b453a8 - _main ```
2024-05-30T14:26:22Z
18.2
2024-05-30T14:58:06Z
4d74e38a515bc14381e1342afdf5ee2ec345f589
[ "stats::tests::starts_with_pipe" ]
[ "stats::tests::escaped_pipes", "stats::tests::interesting_commands_spaces", "stats::tests::split_multi_quoted", "stats::tests::starts_with_spaces_and_pipe", "stats::tests::interesting_commands", "stats::tests::split_simple_quoted", "stats::tests::split_multi", "stats::tests::split_simple", "stats::tests::interesting_commands_spaces_both", "stats::tests::emoji", "stats::tests::ignored_commands", "stats::tests::interesting_commands_spaces_subcommand" ]
[]
[]
auto_2025-06-06
atuinsh/atuin
1,739
atuinsh__atuin-1739
[ "1054" ]
2a65f89cd54b8b8187240a1fdc288867b35f6b01
diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -217,6 +217,7 @@ dependencies = [ "tracing", "tracing-subscriber", "tracing-tree", + "unicode-segmentation", "unicode-width", "uuid", "whoami", diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -3937,9 +3938,9 @@ dependencies = [ [[package]] name = "unicode-segmentation" -version = "1.10.1" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" +checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" [[package]] name = "unicode-width" diff --git a/atuin/Cargo.toml b/atuin/Cargo.toml --- a/atuin/Cargo.toml +++ b/atuin/Cargo.toml @@ -78,6 +78,7 @@ ratatui = "0.25" tracing = "0.1" cli-clipboard = { version = "0.4.0", optional = true } uuid = { workspace = true } +unicode-segmentation = "1.11.0" [dependencies.tracing-subscriber] diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -1,6 +1,5 @@ use std::collections::{HashMap, HashSet}; -use atuin_common::utils::Escapable as _; use clap::Parser; use crossterm::style::{Color, ResetColor, SetAttribute, SetForegroundColor}; use eyre::Result; diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -12,6 +11,7 @@ use atuin_client::{ settings::Settings, }; use time::{Duration, OffsetDateTime, Time}; +use unicode_segmentation::UnicodeSegmentation; #[derive(Parser, Debug)] #[command(infer_subcommands = true)] diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -22,12 +22,60 @@ pub struct Cmd { /// How many top commands to list #[arg(long, short, default_value = "10")] count: usize, + + /// The number of consecutive commands to consider + #[arg(long, short, default_value = "1")] + ngram_size: usize, } -fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usize, usize) { +fn split_at_pipe(command: &str) -> Vec<&str> { + let mut result = vec![]; + let mut quoted = false; + let mut start = 0; + let mut graphemes = UnicodeSegmentation::grapheme_indices(command, true); + + while let Some((i, c)) = graphemes.next() { + let current = i; + match c { + "\"" => { + if command[start..current] != *"\"" { + quoted = !quoted; + } + } + "'" => { + if command[start..current] != *"'" { + quoted = !quoted; + } + } + "\\" => if graphemes.next().is_some() {}, + "|" => { + if !quoted { + if command[start..].starts_with('|') { + start += 1; + } + result.push(&command[start..current]); + start = current; + } + } + _ => {} + } + } + if command[start..].starts_with('|') { + start += 1; + } + result.push(&command[start..]); + result +} + +fn compute_stats( + settings: &Settings, + history: &[History], + count: usize, + ngram_size: usize, +) -> (usize, usize) { let mut commands = HashSet::<&str>::with_capacity(history.len()); - let mut prefixes = HashMap::<&str, usize>::with_capacity(history.len()); let mut total_unignored = 0; + let mut prefixes = HashMap::<Vec<&str>, usize>::with_capacity(history.len()); for i in history { // just in case it somehow has a leading tab or space or something (legacy atuin didn't ignore space prefixes) let command = i.command.trim(); diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -39,7 +87,21 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usi total_unignored += 1; commands.insert(command); - *prefixes.entry(prefix).or_default() += 1; + + split_at_pipe(i.command.trim()) + .iter() + .map(|l| { + let command = l.trim(); + commands.insert(command); + command + }) + .collect::<Vec<_>>() + .windows(ngram_size) + .for_each(|w| { + *prefixes + .entry(w.iter().map(|c| interesting_command(settings, c)).collect()) + .or_default() += 1; + }); } let unique = commands.len(); diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -54,6 +116,17 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usi let max = top.iter().map(|x| x.1).max().unwrap(); let num_pad = max.ilog10() as usize + 1; + // Find the length of the longest command name for each column + let column_widths = top + .iter() + .map(|(commands, _)| commands.iter().map(|c| c.len()).collect::<Vec<usize>>()) + .fold(vec![0; ngram_size], |acc, item| { + acc.iter() + .zip(item.iter()) + .map(|(a, i)| *std::cmp::max(a, i)) + .collect() + }); + for (command, count) in top { let gray = SetForegroundColor(Color::Grey); let bold = SetAttribute(crossterm::style::Attribute::Bold); diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -74,10 +147,14 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usi print!(" "); } - println!( - "{ResetColor}] {gray}{count:num_pad$}{ResetColor} {bold}{}{ResetColor}", - command.escape_control() - ); + let formatted_command = command + .iter() + .zip(column_widths.iter()) + .map(|(cmd, width)| format!("{cmd:width$}")) + .collect::<Vec<_>>() + .join(" | "); + + println!("{ResetColor}] {gray}{count:num_pad$}{ResetColor} {bold}{formatted_command}{ResetColor}"); } println!("Total commands: {total_unignored}"); println!("Unique commands: {unique}"); diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -120,7 +197,7 @@ impl Cmd { let end = start + Duration::days(1); db.range(start, end).await? }; - compute_stats(settings, &history, self.count); + compute_stats(settings, &history, self.count, self.ngram_size); Ok(()) } }
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -189,7 +266,7 @@ mod tests { use time::OffsetDateTime; use super::compute_stats; - use super::interesting_command; + use super::{interesting_command, split_at_pipe}; #[test] fn ignored_commands() { diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -209,7 +286,7 @@ mod tests { .into(), ]; - let (total, unique) = compute_stats(&settings, &history, 10); + let (total, unique) = compute_stats(&settings, &history, 10, 1); assert_eq!(total, 1); assert_eq!(unique, 1); } diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -312,4 +389,49 @@ mod tests { "cargo build foo" ); } + + #[test] + fn split_simple() { + assert_eq!(split_at_pipe("fd | rg"), ["fd ", " rg"]); + } + + #[test] + fn split_multi() { + assert_eq!( + split_at_pipe("kubectl | jq | rg"), + ["kubectl ", " jq ", " rg"] + ); + } + + #[test] + fn split_simple_quoted() { + assert_eq!( + split_at_pipe("foo | bar 'baz {} | quux' | xyzzy"), + ["foo ", " bar 'baz {} | quux' ", " xyzzy"] + ); + } + + #[test] + fn split_multi_quoted() { + assert_eq!( + split_at_pipe("foo | bar 'baz \"{}\" | quux' | xyzzy"), + ["foo ", " bar 'baz \"{}\" | quux' ", " xyzzy"] + ); + } + + #[test] + fn escaped_pipes() { + assert_eq!( + split_at_pipe("foo | bar baz \\| quux"), + ["foo ", " bar baz \\| quux"] + ); + } + + #[test] + fn emoji() { + assert_eq!( + split_at_pipe("git commit -m \"🚀\""), + ["git commit -m \"🚀\""] + ); + } }
Enable multiple command stats to be shown These changes extend the `stats` subcommand with an `--ngram-size` argument, which supports providing statistics for combinations of commands. I have found this useful for identifying the most common combinations of commands as candidates for further automation.
2024-02-20T05:51:10Z
18.0
2024-02-27T19:41:41Z
2a65f89cd54b8b8187240a1fdc288867b35f6b01
[ "command::client::search::cursor::cursor_tests::back", "command::client::search::cursor::cursor_tests::left", "command::client::search::cursor::cursor_tests::pop", "command::client::stats::tests::interesting_commands", "command::client::search::cursor::cursor_tests::test_emacs_get_prev_word_pos", "command::client::search::cursor::cursor_tests::insert", "command::client::search::cursor::cursor_tests::test_subl_get_next_word_pos", "command::client::stats::tests::interesting_commands_spaces", "command::client::search::cursor::cursor_tests::right", "command::client::search::cursor::cursor_tests::test_emacs_get_next_word_pos", "command::client::stats::tests::interesting_commands_spaces_both", "command::client::account::login::tests::mnemonic_round_trip", "command::client::search::cursor::cursor_tests::test_subl_get_prev_word_pos", "command::client::stats::tests::interesting_commands_spaces_subcommand", "command::client::stats::tests::ignored_commands" ]
[]
[]
[]
auto_2025-06-06
atuinsh/atuin
1,722
atuinsh__atuin-1722
[ "1714" ]
063d9054d74c0c44781507eed27378415ab9fef5
diff --git a/atuin-client/config.toml b/atuin-client/config.toml --- a/atuin-client/config.toml +++ b/atuin-client/config.toml @@ -171,3 +171,6 @@ enter_accept = true ## Set commands that should be totally stripped and ignored from stats #common_prefix = ["sudo"] + +## Set commands that will be completely ignored from stats +#ignored_commands = ["cd", "ls", "vi"] diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs --- a/atuin-client/src/settings.rs +++ b/atuin-client/src/settings.rs @@ -270,6 +270,8 @@ pub struct Stats { pub common_prefix: Vec<String>, // sudo, etc. commands we want to strip off #[serde(default = "Stats::common_subcommands_default")] pub common_subcommands: Vec<String>, // kubectl, commands we should consider subcommands for + #[serde(default = "Stats::ignored_commands_default")] + pub ignored_commands: Vec<String>, // cd, ls, etc. commands we want to completely hide from stats } impl Stats { diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs --- a/atuin-client/src/settings.rs +++ b/atuin-client/src/settings.rs @@ -283,6 +285,10 @@ impl Stats { .map(String::from) .collect() } + + fn ignored_commands_default() -> Vec<String> { + vec![] + } } impl Default for Stats { diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs --- a/atuin-client/src/settings.rs +++ b/atuin-client/src/settings.rs @@ -290,6 +296,7 @@ impl Default for Stats { Self { common_prefix: Self::common_prefix_default(), common_subcommands: Self::common_subcommands_default(), + ignored_commands: Self::ignored_commands_default(), } } } diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -24,16 +24,22 @@ pub struct Cmd { count: usize, } -fn compute_stats(settings: &Settings, history: &[History], count: usize) { +fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usize, usize) { let mut commands = HashSet::<&str>::with_capacity(history.len()); let mut prefixes = HashMap::<&str, usize>::with_capacity(history.len()); + let mut total_unignored = 0; for i in history { // just in case it somehow has a leading tab or space or something (legacy atuin didn't ignore space prefixes) let command = i.command.trim(); + let prefix = interesting_command(settings, command); + + if settings.stats.ignored_commands.iter().any(|c| c == prefix) { + continue; + } + + total_unignored += 1; commands.insert(command); - *prefixes - .entry(interesting_command(settings, command)) - .or_default() += 1; + *prefixes.entry(prefix).or_default() += 1; } let unique = commands.len(); diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -42,7 +48,7 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) { top.truncate(count); if top.is_empty() { println!("No commands found"); - return; + return (0, 0); } let max = top.iter().map(|x| x.1).max().unwrap(); diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -73,8 +79,10 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) { command.escape_control() ); } - println!("Total commands: {}", history.len()); + println!("Total commands: {total_unignored}"); println!("Unique commands: {unique}"); + + (total_unignored, unique) } impl Cmd {
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs --- a/atuin/src/command/client/stats.rs +++ b/atuin/src/command/client/stats.rs @@ -176,10 +184,36 @@ fn interesting_command<'a>(settings: &Settings, mut command: &'a str) -> &'a str #[cfg(test)] mod tests { + use atuin_client::history::History; use atuin_client::settings::Settings; + use time::OffsetDateTime; + use super::compute_stats; use super::interesting_command; + #[test] + fn ignored_commands() { + let mut settings = Settings::utc(); + settings.stats.ignored_commands.push("cd".to_string()); + + let history = [ + History::import() + .timestamp(OffsetDateTime::now_utc()) + .command("cd foo") + .build() + .into(), + History::import() + .timestamp(OffsetDateTime::now_utc()) + .command("cargo build stuff") + .build() + .into(), + ]; + + let (total, unique) = compute_stats(&settings, &history, 10); + assert_eq!(total, 1); + assert_eq!(unique, 1); + } + #[test] fn interesting_commands() { let settings = Settings::utc();
`ignore_commands` option for stats Would you be open to having an `ignore_commands` option for `atuin stats`? `cd`, `ls`, and `vi` are my three top commands by nearly an order of and I don't find this particularly informative; I'd be interested in filtering these out entirely from my stats. If you're interested in this, I'd be willing to take a stab at a PR for it.
I'd be interested! Otherwise, you can see more commands with the -c arg, if you find them a waste of space eg `atuin stats -c 100` will show the top 100, rather than top 10 OK I will see how hard this is and take a stab at a PR. The issue is not so much a waste of space, but that it makes the histogram kindof useless: ``` > atuin stats [▮▮▮▮▮▮▮▮▮▮] 890 cd [▮▮▮▮▮▮▮▮▮ ] 868 vi [▮▮▮▮▮▮ ] 608 ls [▮▮ ] 199 kcgp [▮ ] 165 git stat [▮ ] 159 kcl [▮ ] 141 kcapp [▮ ] 131 kcrm [▮ ] 130 git co [▮ ] 119 kcg ``` When all the other commands only have one bar because the top three are so large, it's hard to actually tell "at a glance" the magnitude difference between them all.
2024-02-14T17:42:21Z
18.0
2024-02-15T18:52:19Z
2a65f89cd54b8b8187240a1fdc288867b35f6b01
[ "command::client::search::cursor::cursor_tests::test_emacs_get_next_word_pos", "command::client::search::cursor::cursor_tests::test_subl_get_prev_word_pos", "command::client::search::cursor::cursor_tests::right", "command::client::search::cursor::cursor_tests::pop", "command::client::search::cursor::cursor_tests::left", "command::client::search::cursor::cursor_tests::back", "command::client::account::login::tests::mnemonic_round_trip", "command::client::search::cursor::cursor_tests::test_emacs_get_prev_word_pos", "command::client::stats::tests::interesting_commands", "command::client::search::cursor::cursor_tests::test_subl_get_next_word_pos", "command::client::stats::tests::interesting_commands_spaces_subcommand", "command::client::search::cursor::cursor_tests::insert", "command::client::stats::tests::interesting_commands_spaces_both", "command::client::stats::tests::interesting_commands_spaces" ]
[]
[]
[]
auto_2025-06-06