repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/parameter/range_step.rs
src/parameter/range_step.rs
use std::convert::TryInto; use std::ops::{Add, AddAssign, Div, Sub}; use crate::error::ParameterScanError; use crate::util::number::Number; pub trait Numeric: Add<Output = Self> + Sub<Output = Self> + Div<Output = Self> + AddAssign + PartialOrd + Copy + Clone + From<i32> + Into<Number> { } impl< T: Add<Output = Self> + Sub<Output = Self> + Div<Output = Self> + AddAssign + PartialOrd + Copy + Clone + From<i32> + Into<Number>, > Numeric for T { } #[derive(Debug)] pub struct RangeStep<T> { state: T, end: T, step: T, } impl<T: Numeric> RangeStep<T> { pub fn new(start: T, end: T, step: T) -> Result<Self, ParameterScanError> { if end < start { return Err(ParameterScanError::EmptyRange); } if step == T::from(0) { return Err(ParameterScanError::ZeroStep); } const MAX_PARAMETERS: usize = 100_000; match range_step_size_hint(start, end, step) { (_, Some(size)) if size <= MAX_PARAMETERS => Ok(Self { state: start, end, step, }), _ => Err(ParameterScanError::TooLarge), } } } impl<T: Numeric> Iterator for RangeStep<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { if self.state > self.end { return None; } let return_val = self.state; self.state += self.step; Some(return_val) } fn size_hint(&self) -> (usize, Option<usize>) { range_step_size_hint(self.state, self.end, self.step) } } fn range_step_size_hint<T: Numeric>(start: T, end: T, step: T) -> (usize, Option<usize>) { if step == T::from(0) { return (usize::MAX, None); } let steps = (end - start + T::from(1)) / step; steps .into() .try_into() .map_or((usize::MAX, None), |u| (u, Some(u))) } #[cfg(test)] mod tests { use super::*; use rust_decimal::Decimal; use std::str::FromStr; #[test] fn test_integer_range() { let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect(); assert_eq!(param_range.len(), 4); assert_eq!(param_range[0], 0); assert_eq!(param_range[3], 9); } #[test] fn test_decimal_range() { let param_min = Decimal::from(0); let param_max = Decimal::from(1); let step = Decimal::from_str("0.1").unwrap(); let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step) .unwrap() .collect(); assert_eq!(param_range.len(), 11); assert_eq!(param_range[0], Decimal::from(0)); assert_eq!(param_range[10], Decimal::from(1)); } #[test] fn test_range_step_validate() { let result = RangeStep::new(0, 10, 3); assert!(result.is_ok()); let result = RangeStep::new( Decimal::from(0), Decimal::from(1), Decimal::from_str("0.1").unwrap(), ); assert!(result.is_ok()); let result = RangeStep::new(11, 10, 1); assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range"); let result = RangeStep::new(0, 10, 0); assert_eq!( format!("{}", result.unwrap_err()), "Zero is not a valid parameter step" ); let result = RangeStep::new(0, 100_001, 1); assert_eq!( format!("{}", result.unwrap_err()), "Parameter range is too large" ); } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/parameter/mod.rs
src/parameter/mod.rs
use crate::util::number::Number; use std::fmt::Display; pub mod range_step; pub mod tokenize; #[derive(Debug, Clone, PartialEq, Eq)] pub enum ParameterValue { Text(String), Numeric(Number), } impl Display for ParameterValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { ParameterValue::Text(ref value) => value.clone(), ParameterValue::Numeric(value) => value.to_string(), }; write!(f, "{str}") } } pub type ParameterNameAndValue<'a> = (&'a str, ParameterValue);
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/parameter/tokenize.rs
src/parameter/tokenize.rs
pub fn tokenize(values: &str) -> Vec<String> { let mut tokens = vec![]; let mut buf = String::new(); let mut iter = values.chars(); while let Some(c) = iter.next() { match c { '\\' => match iter.next() { Some(c2 @ ',') | Some(c2 @ '\\') => { buf.push(c2); } Some(c2) => { buf.push('\\'); buf.push(c2); } None => buf.push('\\'), }, ',' => { tokens.push(buf); buf = String::new(); } _ => { buf.push(c); } }; } tokens.push(buf); tokens } #[test] fn test_tokenize_single_value() { assert_eq!(tokenize(r""), vec![""]); assert_eq!(tokenize(r"foo"), vec!["foo"]); assert_eq!(tokenize(r" "), vec![" "]); assert_eq!(tokenize(r"hello\, world!"), vec!["hello, world!"]); assert_eq!(tokenize(r"\,"), vec![","]); assert_eq!(tokenize(r"\,\,\,"), vec![",,,"]); assert_eq!(tokenize(r"\n"), vec![r"\n"]); assert_eq!(tokenize(r"\\"), vec![r"\"]); assert_eq!(tokenize(r"\\\,"), vec![r"\,"]); } #[test] fn test_tokenize_multiple_values() { assert_eq!(tokenize(r"foo,bar,baz"), vec!["foo", "bar", "baz"]); assert_eq!(tokenize(r"hello world,foo"), vec!["hello world", "foo"]); assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]); } #[test] fn test_tokenize_empty_values() { assert_eq!(tokenize(r"foo,,bar"), vec!["foo", "", "bar"]); assert_eq!(tokenize(r",bar"), vec!["", "bar"]); assert_eq!(tokenize(r"bar,"), vec!["bar", ""]); assert_eq!(tokenize(r",,"), vec!["", "", ""]); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/timer/windows_timer.rs
src/timer/windows_timer.rs
#![cfg(windows)] #![warn(unsafe_op_in_unsafe_fn)] use std::{mem, os::windows::io::AsRawHandle, process, ptr}; use windows_sys::Win32::{ Foundation::{CloseHandle, HANDLE}, System::JobObjects::{ AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicAccountingInformation, QueryInformationJobObject, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, }, }; #[cfg(feature = "windows_process_extensions_main_thread_handle")] use std::os::windows::process::ChildExt; #[cfg(feature = "windows_process_extensions_main_thread_handle")] use windows_sys::Win32::System::Threading::ResumeThread; #[cfg(not(feature = "windows_process_extensions_main_thread_handle"))] use once_cell::sync::Lazy; #[cfg(not(feature = "windows_process_extensions_main_thread_handle"))] use windows_sys::{ s, w, Win32::{ Foundation::{NTSTATUS, STATUS_SUCCESS}, System::LibraryLoader::{GetModuleHandleW, GetProcAddress}, }, }; use crate::util::units::Second; const HUNDRED_NS_PER_MS: i64 = 10; #[cfg(not(feature = "windows_process_extensions_main_thread_handle"))] #[allow(non_upper_case_globals)] static NtResumeProcess: Lazy<unsafe extern "system" fn(ProcessHandle: HANDLE) -> NTSTATUS> = Lazy::new(|| { // SAFETY: Getting the module handle for ntdll.dll is safe let ntdll = unsafe { GetModuleHandleW(w!("ntdll.dll")) }; assert!(ntdll != std::ptr::null_mut(), "GetModuleHandleW failed"); // SAFETY: The ntdll handle is valid let nt_resume_process = unsafe { GetProcAddress(ntdll, s!("NtResumeProcess")) }; // SAFETY: We transmute to the correct function signature unsafe { mem::transmute(nt_resume_process.unwrap()) } }); pub struct CPUTimer { job_object: HANDLE, } impl CPUTimer { pub unsafe fn start_suspended_process(child: &process::Child) -> Self { let child_handle = child.as_raw_handle() as HANDLE; // SAFETY: Creating a new job object is safe let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) }; assert!( job_object != std::ptr::null_mut(), "CreateJobObjectW failed" ); // SAFETY: The job object handle is valid let ret = unsafe { AssignProcessToJobObject(job_object, child_handle) }; assert!(ret != 0, "AssignProcessToJobObject failed"); #[cfg(feature = "windows_process_extensions_main_thread_handle")] { // SAFETY: The main thread handle is valid let ret = unsafe { ResumeThread(child.main_thread_handle().as_raw_handle() as HANDLE) }; assert!(ret != u32::MAX, "ResumeThread failed"); } #[cfg(not(feature = "windows_process_extensions_main_thread_handle"))] { // Since we can't get the main thread handle on stable rust, we use // the undocumented but widely known `NtResumeProcess` function to // resume a process by it's handle. // SAFETY: The process handle is valid let ret = unsafe { NtResumeProcess(child_handle) }; assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed"); } Self { job_object } } pub fn stop(&self) -> (Second, Second, u64) { let mut job_object_info = mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit(); // SAFETY: A valid job object got created in `start_suspended_process` let res = unsafe { QueryInformationJobObject( self.job_object, JobObjectBasicAccountingInformation, job_object_info.as_mut_ptr().cast(), mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32, ptr::null_mut(), ) }; if res != 0 { // SAFETY: The job object info got correctly initialized let job_object_info = unsafe { job_object_info.assume_init() }; // The `TotalUserTime` is "The total amount of user-mode execution time for // all active processes associated with the job, as well as all terminated processes no // longer associated with the job, in 100-nanosecond ticks." let user: i64 = job_object_info.TotalUserTime / HUNDRED_NS_PER_MS; // The `TotalKernelTime` is "The total amount of kernel-mode execution time // for all active processes associated with the job, as well as all terminated // processes no longer associated with the job, in 100-nanosecond ticks." let kernel: i64 = job_object_info.TotalKernelTime / HUNDRED_NS_PER_MS; (user as f64 * 1e-6, kernel as f64 * 1e-6, 0) } else { (0.0, 0.0, 0) } } } impl Drop for CPUTimer { fn drop(&mut self) { // SAFETY: A valid job object got created in `start_suspended_process` unsafe { CloseHandle(self.job_object) }; } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/timer/mod.rs
src/timer/mod.rs
mod wall_clock_timer; #[cfg(windows)] mod windows_timer; #[cfg(not(windows))] mod unix_timer; #[cfg(target_os = "linux")] use nix::fcntl::{splice, SpliceFFlags}; #[cfg(target_os = "linux")] use std::fs::File; #[cfg(target_os = "linux")] use std::os::fd::AsFd; #[cfg(target_os = "windows")] use windows_sys::Win32::System::Threading::CREATE_SUSPENDED; use crate::util::units::Second; use wall_clock_timer::WallClockTimer; use std::io::Read; use std::process::{ChildStdout, Command, ExitStatus}; use anyhow::Result; #[cfg(not(windows))] #[derive(Debug, Copy, Clone)] struct CPUTimes { /// Total amount of time spent executing in user mode pub user_usec: i64, /// Total amount of time spent executing in kernel mode pub system_usec: i64, /// Maximum amount of memory used by the process, in bytes pub memory_usage_byte: u64, } /// Used to indicate the result of running a command #[derive(Debug, Copy, Clone)] pub struct TimerResult { pub time_real: Second, pub time_user: Second, pub time_system: Second, pub memory_usage_byte: u64, /// The exit status of the process pub status: ExitStatus, } /// Discard the output of a child process. fn discard(output: ChildStdout) { const CHUNK_SIZE: usize = 64 << 10; #[cfg(target_os = "linux")] { if let Ok(file) = File::create("/dev/null") { while let Ok(bytes) = splice( output.as_fd(), None, file.as_fd(), None, CHUNK_SIZE, SpliceFFlags::empty(), ) { if bytes == 0 { break; } } } } let mut output = output; let mut buf = [0; CHUNK_SIZE]; while let Ok(bytes) = output.read(&mut buf) { if bytes == 0 { break; } } } /// Execute the given command and return a timing summary pub fn execute_and_measure(mut command: Command) -> Result<TimerResult> { #[cfg(not(windows))] let cpu_timer = self::unix_timer::CPUTimer::start(); #[cfg(windows)] { use std::os::windows::process::CommandExt; // Create the process in a suspended state so that we don't miss any cpu time between process creation and `CPUTimer` start. command.creation_flags(CREATE_SUSPENDED); } let wallclock_timer = WallClockTimer::start(); let mut child = command.spawn()?; #[cfg(windows)] let cpu_timer = { // SAFETY: We created a suspended process unsafe { self::windows_timer::CPUTimer::start_suspended_process(&child) } }; if let Some(output) = child.stdout.take() { // Handle CommandOutputPolicy::Pipe discard(output); } let status = child.wait()?; let time_real = wallclock_timer.stop(); let (time_user, time_system, memory_usage_byte) = cpu_timer.stop(); Ok(TimerResult { time_real, time_user, time_system, memory_usage_byte, status, }) }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/timer/wall_clock_timer.rs
src/timer/wall_clock_timer.rs
use std::time::Instant; use crate::util::units::Second; pub struct WallClockTimer { start: Instant, } impl WallClockTimer { pub fn start() -> WallClockTimer { WallClockTimer { start: Instant::now(), } } pub fn stop(&self) -> Second { let duration = self.start.elapsed(); duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) * 1e-9 } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/timer/unix_timer.rs
src/timer/unix_timer.rs
#![cfg(not(windows))] use std::convert::TryFrom; use std::mem; use crate::timer::CPUTimes; use crate::util::units::Second; #[derive(Debug, Copy, Clone)] pub struct CPUInterval { /// Total amount of time spent executing in user mode pub user: Second, /// Total amount of time spent executing in kernel mode pub system: Second, } pub struct CPUTimer { start_cpu: CPUTimes, } impl CPUTimer { pub fn start() -> Self { CPUTimer { start_cpu: get_cpu_times(), } } pub fn stop(&self) -> (Second, Second, u64) { let end_cpu = get_cpu_times(); let cpu_interval = cpu_time_interval(&self.start_cpu, &end_cpu); ( cpu_interval.user, cpu_interval.system, end_cpu.memory_usage_byte, ) } } /// Read CPU execution times ('user' and 'system') fn get_cpu_times() -> CPUTimes { use libc::{getrusage, rusage, RUSAGE_CHILDREN}; let result: rusage = unsafe { let mut buf = mem::zeroed(); let success = getrusage(RUSAGE_CHILDREN, &mut buf); assert_eq!(0, success); buf }; const MICROSEC_PER_SEC: i64 = 1000 * 1000; // Linux and *BSD return the value in KibiBytes, Darwin flavors in bytes let max_rss_byte = if cfg!(target_os = "macos") || cfg!(target_os = "ios") { result.ru_maxrss } else { result.ru_maxrss * 1024 }; #[allow(clippy::useless_conversion)] CPUTimes { user_usec: i64::from(result.ru_utime.tv_sec) * MICROSEC_PER_SEC + i64::from(result.ru_utime.tv_usec), system_usec: i64::from(result.ru_stime.tv_sec) * MICROSEC_PER_SEC + i64::from(result.ru_stime.tv_usec), memory_usage_byte: u64::try_from(max_rss_byte).unwrap_or(0), } } /// Compute the time intervals in between two `CPUTimes` snapshots fn cpu_time_interval(start: &CPUTimes, end: &CPUTimes) -> CPUInterval { CPUInterval { user: ((end.user_usec - start.user_usec) as f64) * 1e-6, system: ((end.system_usec - start.system_usec) as f64) * 1e-6, } } #[cfg(test)] use approx::assert_relative_eq; #[test] fn test_cpu_time_interval() { let t_a = CPUTimes { user_usec: 12345, system_usec: 54321, memory_usage_byte: 0, }; let t_b = CPUTimes { user_usec: 20000, system_usec: 70000, memory_usage_byte: 0, }; let t_zero = cpu_time_interval(&t_a, &t_a); assert!(t_zero.user.abs() < f64::EPSILON); assert!(t_zero.system.abs() < f64::EPSILON); let t_ab = cpu_time_interval(&t_a, &t_b); assert_relative_eq!(0.007655, t_ab.user); assert_relative_eq!(0.015679, t_ab.system); let t_ba = cpu_time_interval(&t_b, &t_a); assert_relative_eq!(-0.007655, t_ba.user); assert_relative_eq!(-0.015679, t_ba.system); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/markup.rs
src/export/markup.rs
use crate::benchmark::relative_speed::BenchmarkResultWithRelativeSpeed; use crate::benchmark::{benchmark_result::BenchmarkResult, relative_speed}; use crate::options::SortOrder; use crate::output::format::format_duration_value; use crate::util::units::Unit; use super::Exporter; use anyhow::Result; pub enum Alignment { Left, Right, } pub trait MarkupExporter { fn table_results(&self, entries: &[BenchmarkResultWithRelativeSpeed], unit: Unit) -> String { // prepare table header strings let notation = format!("[{}]", unit.short_name()); // prepare table cells alignment let cells_alignment = [ Alignment::Left, Alignment::Right, Alignment::Right, Alignment::Right, Alignment::Right, ]; // emit table header format let mut table = self.table_header(&cells_alignment); // emit table header data table.push_str(&self.table_row(&[ "Command", &format!("Mean {notation}"), &format!("Min {notation}"), &format!("Max {notation}"), "Relative", ])); // emit horizontal line table.push_str(&self.table_divider(&cells_alignment)); for entry in entries { let measurement = &entry.result; // prepare data row strings let cmd_str = measurement .command_with_unused_parameters .replace('|', "\\|"); let mean_str = format_duration_value(measurement.mean, Some(unit)).0; let stddev_str = if let Some(stddev) = measurement.stddev { format!(" ± {}", format_duration_value(stddev, Some(unit)).0) } else { "".into() }; let min_str = format_duration_value(measurement.min, Some(unit)).0; let max_str = format_duration_value(measurement.max, Some(unit)).0; let rel_str = format!("{:.2}", entry.relative_speed); let rel_stddev_str = if entry.is_reference { "".into() } else if let Some(stddev) = entry.relative_speed_stddev { format!(" ± {stddev:.2}") } else { "".into() }; // prepare table row entries table.push_str(&self.table_row(&[ &self.command(&cmd_str), &format!("{mean_str}{stddev_str}"), &min_str, &max_str, &format!("{rel_str}{rel_stddev_str}"), ])) } // emit table footer format table.push_str(&self.table_footer(&cells_alignment)); table } fn table_row(&self, cells: &[&str]) -> String; fn table_divider(&self, cell_aligmnents: &[Alignment]) -> String; fn table_header(&self, _cell_aligmnents: &[Alignment]) -> String { "".to_string() } fn table_footer(&self, _cell_aligmnents: &[Alignment]) -> String { "".to_string() } fn command(&self, size: &str) -> String; } fn determine_unit_from_results(results: &[BenchmarkResult]) -> Unit { if let Some(first_result) = results.first() { // Use the first BenchmarkResult entry to determine the unit for all entries. format_duration_value(first_result.mean, None).1 } else { // Default to `Second`. Unit::Second } } impl<T: MarkupExporter> Exporter for T { fn serialize( &self, results: &[BenchmarkResult], unit: Option<Unit>, sort_order: SortOrder, ) -> Result<Vec<u8>> { let unit = unit.unwrap_or_else(|| determine_unit_from_results(results)); let entries = relative_speed::compute(results, sort_order); let table = self.table_results(&entries, unit); Ok(table.as_bytes().to_vec()) } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/orgmode.rs
src/export/orgmode.rs
use super::markup::Alignment; use crate::export::markup::MarkupExporter; #[derive(Default)] pub struct OrgmodeExporter {} impl MarkupExporter for OrgmodeExporter { fn table_row(&self, cells: &[&str]) -> String { format!( "| {} | {} |\n", cells.first().unwrap(), &cells[1..].join(" | ") ) } fn table_divider(&self, cell_aligmnents: &[Alignment]) -> String { format!("|{}--|\n", "--+".repeat(cell_aligmnents.len() - 1)) } fn command(&self, cmd: &str) -> String { format!("={cmd}=") } } /// Check Emacs org-mode data row formatting #[test] fn test_orgmode_formatter_table_data() { let exporter = OrgmodeExporter::default(); let actual = exporter.table_row(&["a", "b", "c"]); let expect = "| a | b | c |\n"; assert_eq!(expect, actual); } /// Check Emacs org-mode horizontal line formatting #[test] fn test_orgmode_formatter_table_line() { let exporter = OrgmodeExporter::default(); let actual = exporter.table_divider(&[ Alignment::Left, Alignment::Left, Alignment::Left, Alignment::Left, Alignment::Left, ]); let expect = "|--+--+--+--+--|\n"; assert_eq!(expect, actual); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/tests.rs
src/export/tests.rs
use super::Exporter; use crate::benchmark::benchmark_result::BenchmarkResult; use crate::export::asciidoc::AsciidocExporter; use crate::export::orgmode::OrgmodeExporter; use crate::util::units::Unit; use crate::{export::markdown::MarkdownExporter, options::SortOrder}; use std::collections::BTreeMap; fn get_output<E: Exporter + Default>( results: &[BenchmarkResult], unit: Option<Unit>, sort_order: SortOrder, ) -> String { let exporter = E::default(); String::from_utf8(exporter.serialize(results, unit, sort_order).unwrap()).unwrap() } /// Ensure the makrup output includes the table header and the multiple /// benchmark results as a table. The list of actual times is not included /// in the output. /// /// This also demonstrates that the first entry's units (ms) are used to set /// the units for all entries when the time unit is not specified. #[test] fn test_markup_export_auto_ms() { let results = [ BenchmarkResult { command: String::from("sleep 0.1"), command_with_unused_parameters: String::from("sleep 0.1"), mean: 0.1057, stddev: Some(0.0016), median: 0.1057, user: 0.0009, system: 0.0011, min: 0.1023, max: 0.1080, times: Some(vec![0.1, 0.1, 0.1]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, BenchmarkResult { command: String::from("sleep 2"), command_with_unused_parameters: String::from("sleep 2"), mean: 2.0050, stddev: Some(0.0020), median: 2.0050, user: 0.0009, system: 0.0012, min: 2.0020, max: 2.0080, times: Some(vec![2.0, 2.0, 2.0]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, ]; insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, None, SortOrder::Command), @r#" | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |:---|---:|---:|---:|---:| | `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 | | `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 | "#); insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, None, SortOrder::Command), @r#" [cols="<,>,>,>,>"] |=== | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 | `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |=== "#); insta::assert_snapshot!(get_output::<OrgmodeExporter>(&results, None, SortOrder::Command), @r#" | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |--+--+--+--+--| | =sleep 0.1= | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 | | =sleep 2= | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 | "#); } /// This (again) demonstrates that the first entry's units (s) are used to set /// the units for all entries when the time unit is not given. #[test] fn test_markup_export_auto_s() { let results = [ BenchmarkResult { command: String::from("sleep 2"), command_with_unused_parameters: String::from("sleep 2"), mean: 2.0050, stddev: Some(0.0020), median: 2.0050, user: 0.0009, system: 0.0012, min: 2.0020, max: 2.0080, times: Some(vec![2.0, 2.0, 2.0]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, BenchmarkResult { command: String::from("sleep 0.1"), command_with_unused_parameters: String::from("sleep 0.1"), mean: 0.1057, stddev: Some(0.0016), median: 0.1057, user: 0.0009, system: 0.0011, min: 0.1023, max: 0.1080, times: Some(vec![0.1, 0.1, 0.1]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, ]; insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, None, SortOrder::Command), @r#" | Command | Mean [s] | Min [s] | Max [s] | Relative | |:---|---:|---:|---:|---:| | `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 | | `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 | "#); insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, None, SortOrder::Command), @r#" [cols="<,>,>,>,>"] |=== | Command | Mean [s] | Min [s] | Max [s] | Relative | `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 | `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |=== "#); insta::assert_snapshot!(get_output::<OrgmodeExporter>(&results, None, SortOrder::Command), @r#" | Command | Mean [s] | Min [s] | Max [s] | Relative | |--+--+--+--+--| | =sleep 2= | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 | | =sleep 0.1= | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 | "#); } /// This (again) demonstrates that the given time unit (ms) is used to set /// the units for all entries. #[test] fn test_markup_export_manual_ms() { let timing_results = [ BenchmarkResult { command: String::from("sleep 2"), command_with_unused_parameters: String::from("sleep 2"), mean: 2.0050, stddev: Some(0.0020), median: 2.0050, user: 0.0009, system: 0.0012, min: 2.0020, max: 2.0080, times: Some(vec![2.0, 2.0, 2.0]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, BenchmarkResult { command: String::from("sleep 0.1"), command_with_unused_parameters: String::from("sleep 0.1"), mean: 0.1057, stddev: Some(0.0016), median: 0.1057, user: 0.0009, system: 0.0011, min: 0.1023, max: 0.1080, times: Some(vec![0.1, 0.1, 0.1]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, ]; insta::assert_snapshot!(get_output::<MarkdownExporter>(&timing_results, Some(Unit::MilliSecond), SortOrder::Command), @r#" | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |:---|---:|---:|---:|---:| | `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 | | `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 | "#); insta::assert_snapshot!(get_output::<AsciidocExporter>(&timing_results, Some(Unit::MilliSecond), SortOrder::Command), @r#" [cols="<,>,>,>,>"] |=== | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 | `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |=== "#); insta::assert_snapshot!(get_output::<OrgmodeExporter>(&timing_results, Some(Unit::MilliSecond), SortOrder::Command), @r#" | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |--+--+--+--+--| | =sleep 2= | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 | | =sleep 0.1= | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 | "#); } /// The given time unit (s) is used to set the units for all entries. #[test] fn test_markup_export_manual_s() { let results = [ BenchmarkResult { command: String::from("sleep 2"), command_with_unused_parameters: String::from("sleep 2"), mean: 2.0050, stddev: Some(0.0020), median: 2.0050, user: 0.0009, system: 0.0012, min: 2.0020, max: 2.0080, times: Some(vec![2.0, 2.0, 2.0]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, BenchmarkResult { command: String::from("sleep 0.1"), command_with_unused_parameters: String::from("sleep 0.1"), mean: 0.1057, stddev: Some(0.0016), median: 0.1057, user: 0.0009, system: 0.0011, min: 0.1023, max: 0.1080, times: Some(vec![0.1, 0.1, 0.1]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: BTreeMap::new(), }, ]; insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, Some(Unit::Second), SortOrder::Command), @r#" | Command | Mean [s] | Min [s] | Max [s] | Relative | |:---|---:|---:|---:|---:| | `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 | | `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 | "#); insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, Some(Unit::Second), SortOrder::MeanTime), @r#" | Command | Mean [s] | Min [s] | Max [s] | Relative | |:---|---:|---:|---:|---:| | `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 | | `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 | "#); insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, Some(Unit::Second), SortOrder::Command), @r#" [cols="<,>,>,>,>"] |=== | Command | Mean [s] | Min [s] | Max [s] | Relative | `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 | `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |=== "#); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/asciidoc.rs
src/export/asciidoc.rs
use super::markup::Alignment; use crate::export::markup::MarkupExporter; #[derive(Default)] pub struct AsciidocExporter {} impl MarkupExporter for AsciidocExporter { fn table_header(&self, cell_aligmnents: &[Alignment]) -> String { format!( "[cols=\"{}\"]\n|===", cell_aligmnents .iter() .map(|a| match a { Alignment::Left => "<", Alignment::Right => ">", }) .collect::<Vec<&str>>() .join(",") ) } fn table_footer(&self, _cell_aligmnents: &[Alignment]) -> String { "|===\n".to_string() } fn table_row(&self, cells: &[&str]) -> String { format!("\n| {} \n", cells.join(" \n| ")) } fn table_divider(&self, _cell_aligmnents: &[Alignment]) -> String { "".to_string() } fn command(&self, cmd: &str) -> String { format!("`{cmd}`") } } /// Check Asciidoc-based data row formatting #[test] fn test_asciidoc_exporter_table_data() { let exporter = AsciidocExporter::default(); let data = vec!["a", "b", "c"]; let actual = exporter.table_row(&data); let expect = "\n| a \n| b \n| c \n"; assert_eq!(expect, actual); } /// Check Asciidoc-based table header formatting #[test] fn test_asciidoc_exporter_table_header() { let exporter = AsciidocExporter::default(); let cells_alignment = [ Alignment::Left, Alignment::Right, Alignment::Right, Alignment::Right, Alignment::Right, ]; let actual = exporter.table_header(&cells_alignment); let expect = "[cols=\"<,>,>,>,>\"]\n|==="; assert_eq!(expect, actual); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/json.rs
src/export/json.rs
use serde::*; use serde_json::to_vec_pretty; use super::Exporter; use crate::benchmark::benchmark_result::BenchmarkResult; use crate::options::SortOrder; use crate::util::units::Unit; use anyhow::Result; #[derive(Serialize, Debug)] struct HyperfineSummary<'a> { results: &'a [BenchmarkResult], } #[derive(Default)] pub struct JsonExporter {} impl Exporter for JsonExporter { fn serialize( &self, results: &[BenchmarkResult], _unit: Option<Unit>, _sort_order: SortOrder, ) -> Result<Vec<u8>> { let mut output = to_vec_pretty(&HyperfineSummary { results }); if let Ok(ref mut content) = output { content.push(b'\n'); } Ok(output?) } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/markdown.rs
src/export/markdown.rs
use crate::export::markup::MarkupExporter; use super::markup::Alignment; #[derive(Default)] pub struct MarkdownExporter {} impl MarkupExporter for MarkdownExporter { fn table_row(&self, cells: &[&str]) -> String { format!("| {} |\n", cells.join(" | ")) } fn table_divider(&self, cell_aligmnents: &[Alignment]) -> String { format!( "|{}\n", cell_aligmnents .iter() .map(|a| match a { Alignment::Left => ":---|", Alignment::Right => "---:|", }) .collect::<String>() ) } fn command(&self, cmd: &str) -> String { format!("`{cmd}`") } } /// Check Markdown-based data row formatting #[test] fn test_markdown_formatter_table_data() { let formatter = MarkdownExporter::default(); assert_eq!(formatter.table_row(&["a", "b", "c"]), "| a | b | c |\n"); } /// Check Markdown-based horizontal line formatting #[test] fn test_markdown_formatter_table_divider() { let formatter = MarkdownExporter::default(); let divider = formatter.table_divider(&[Alignment::Left, Alignment::Right, Alignment::Left]); assert_eq!(divider, "|:---|---:|:---|\n"); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/mod.rs
src/export/mod.rs
use std::fs::{File, OpenOptions}; use std::io::Write; mod asciidoc; mod csv; mod json; mod markdown; mod markup; mod orgmode; #[cfg(test)] mod tests; use self::asciidoc::AsciidocExporter; use self::csv::CsvExporter; use self::json::JsonExporter; use self::markdown::MarkdownExporter; use self::orgmode::OrgmodeExporter; use crate::benchmark::benchmark_result::BenchmarkResult; use crate::options::SortOrder; use crate::util::units::Unit; use anyhow::{Context, Result}; use clap::ArgMatches; /// The desired form of exporter to use for a given file. #[derive(Clone)] pub enum ExportType { /// Asciidoc Table Asciidoc, /// CSV (comma separated values) format Csv, /// JSON format Json, /// Markdown table Markdown, /// Emacs org-mode tables Orgmode, } /// Interface for different exporters. trait Exporter { /// Export the given entries in the serialized form. fn serialize( &self, results: &[BenchmarkResult], unit: Option<Unit>, sort_order: SortOrder, ) -> Result<Vec<u8>>; } pub enum ExportTarget { File(String), Stdout, } struct ExporterWithTarget { exporter: Box<dyn Exporter>, target: ExportTarget, } /// Handles the management of multiple file exporters. pub struct ExportManager { exporters: Vec<ExporterWithTarget>, time_unit: Option<Unit>, sort_order: SortOrder, } impl ExportManager { /// Build the ExportManager that will export the results specified /// in the given ArgMatches pub fn from_cli_arguments( matches: &ArgMatches, time_unit: Option<Unit>, sort_order: SortOrder, ) -> Result<Self> { let mut export_manager = Self { exporters: vec![], time_unit, sort_order, }; { let mut add_exporter = |flag, exporttype| -> Result<()> { if let Some(filename) = matches.get_one::<String>(flag) { export_manager.add_exporter(exporttype, filename)?; } Ok(()) }; add_exporter("export-asciidoc", ExportType::Asciidoc)?; add_exporter("export-json", ExportType::Json)?; add_exporter("export-csv", ExportType::Csv)?; add_exporter("export-markdown", ExportType::Markdown)?; add_exporter("export-orgmode", ExportType::Orgmode)?; } Ok(export_manager) } /// Add an additional exporter to the ExportManager pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> { let exporter: Box<dyn Exporter> = match export_type { ExportType::Asciidoc => Box::<AsciidocExporter>::default(), ExportType::Csv => Box::<CsvExporter>::default(), ExportType::Json => Box::<JsonExporter>::default(), ExportType::Markdown => Box::<MarkdownExporter>::default(), ExportType::Orgmode => Box::<OrgmodeExporter>::default(), }; self.exporters.push(ExporterWithTarget { exporter, target: if filename == "-" { ExportTarget::Stdout } else { let _ = File::create(filename) .with_context(|| format!("Could not create export file '{filename}'"))?; ExportTarget::File(filename.to_string()) }, }); Ok(()) } /// Write the given results to all Exporters. The 'intermediate' flag specifies /// whether this is being called while still performing benchmarks, or if this /// is the final call after all benchmarks have been finished. In the former case, /// results are written to all file targets (to always have them up to date, even /// if a benchmark fails). In the latter case, we only print to stdout targets (in /// order not to clutter the output of hyperfine with intermediate results). pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> { for e in &self.exporters { let content = || { e.exporter .serialize(results, self.time_unit, self.sort_order) }; match e.target { ExportTarget::File(ref filename) => { if intermediate { write_to_file(filename, &content()?)? } } ExportTarget::Stdout => { if !intermediate { println!(); println!("{}", String::from_utf8(content()?).unwrap()); } } } } Ok(()) } } /// Write the given content to a file with the specified name fn write_to_file(filename: &str, content: &[u8]) -> Result<()> { let mut file = OpenOptions::new().write(true).open(filename)?; file.write_all(content) .with_context(|| format!("Failed to export results to '{filename}'")) }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/export/csv.rs
src/export/csv.rs
use std::borrow::Cow; use csv::WriterBuilder; use super::Exporter; use crate::benchmark::benchmark_result::BenchmarkResult; use crate::options::SortOrder; use crate::util::units::Unit; use anyhow::Result; #[derive(Default)] pub struct CsvExporter {} impl Exporter for CsvExporter { fn serialize( &self, results: &[BenchmarkResult], _unit: Option<Unit>, _sort_order: SortOrder, ) -> Result<Vec<u8>> { let mut writer = WriterBuilder::new().from_writer(vec![]); { let mut headers: Vec<Cow<[u8]>> = [ // The list of times and exit codes cannot be exported to the CSV file - omit them. "command", "mean", "stddev", "median", "user", "system", "min", "max", ] .iter() .map(|x| Cow::Borrowed(x.as_bytes())) .collect(); if let Some(res) = results.first() { for param_name in res.parameters.keys() { headers.push(Cow::Owned(format!("parameter_{param_name}").into_bytes())); } } writer.write_record(headers)?; } for res in results { let mut fields = vec![Cow::Borrowed(res.command.as_bytes())]; for f in &[ res.mean, res.stddev.unwrap_or(0.0), res.median, res.user, res.system, res.min, res.max, ] { fields.push(Cow::Owned(f.to_string().into_bytes())) } for v in res.parameters.values() { fields.push(Cow::Borrowed(v.as_bytes())) } writer.write_record(fields)?; } Ok(writer.into_inner()?) } } #[test] fn test_csv() { use std::collections::BTreeMap; let exporter = CsvExporter::default(); let results = vec![ BenchmarkResult { command: String::from("command_a"), command_with_unused_parameters: String::from("command_a"), mean: 1.0, stddev: Some(2.0), median: 1.0, user: 3.0, system: 4.0, min: 5.0, max: 6.0, times: Some(vec![7.0, 8.0, 9.0]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: { let mut params = BTreeMap::new(); params.insert("foo".into(), "one".into()); params.insert("bar".into(), "two".into()); params }, }, BenchmarkResult { command: String::from("command_b"), command_with_unused_parameters: String::from("command_b"), mean: 11.0, stddev: Some(12.0), median: 11.0, user: 13.0, system: 14.0, min: 15.0, max: 16.5, times: Some(vec![17.0, 18.0, 19.0]), memory_usage_byte: None, exit_codes: vec![Some(0), Some(0), Some(0)], parameters: { let mut params = BTreeMap::new(); params.insert("foo".into(), "one".into()); params.insert("bar".into(), "seven".into()); params }, }, ]; let actual = String::from_utf8( exporter .serialize(&results, Some(Unit::Second), SortOrder::Command) .unwrap(), ) .unwrap(); insta::assert_snapshot!(actual, @r#" command,mean,stddev,median,user,system,min,max,parameter_bar,parameter_foo command_a,1,2,1,3,4,5,6,two,one command_b,11,12,11,13,14,15,16.5,seven,one "#); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/output/progress_bar.rs
src/output/progress_bar.rs
use indicatif::{ProgressBar, ProgressStyle}; use std::time::Duration; use crate::options::OutputStyleOption; #[cfg(not(windows))] const TICK_SETTINGS: (&str, u64) = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ", 80); #[cfg(windows)] const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200); /// Return a pre-configured progress bar pub fn get_progress_bar(length: u64, msg: &str, option: OutputStyleOption) -> ProgressBar { let progressbar_style = match option { OutputStyleOption::Basic | OutputStyleOption::Color => ProgressStyle::default_bar(), _ => ProgressStyle::default_spinner() .tick_chars(TICK_SETTINGS.0) .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise} ") .expect("no template error"), }; let progress_bar = match option { OutputStyleOption::Basic | OutputStyleOption::Color => ProgressBar::hidden(), _ => ProgressBar::new(length), }; progress_bar.set_style(progressbar_style); progress_bar.enable_steady_tick(Duration::from_millis(TICK_SETTINGS.1)); progress_bar.set_message(msg.to_owned()); progress_bar }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/output/mod.rs
src/output/mod.rs
pub mod format; pub mod progress_bar; pub mod warnings;
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/output/format.rs
src/output/format.rs
use crate::util::units::{Second, Unit}; /// Format the given duration as a string. The output-unit can be enforced by setting `unit` to /// `Some(target_unit)`. If `unit` is `None`, it will be determined automatically. pub fn format_duration(duration: Second, unit: Option<Unit>) -> String { let (duration_fmt, _) = format_duration_unit(duration, unit); duration_fmt } /// Like `format_duration`, but returns the target unit as well. pub fn format_duration_unit(duration: Second, unit: Option<Unit>) -> (String, Unit) { let (out_str, out_unit) = format_duration_value(duration, unit); (format!("{} {}", out_str, out_unit.short_name()), out_unit) } /// Like `format_duration`, but returns the target unit as well. pub fn format_duration_value(duration: Second, unit: Option<Unit>) -> (String, Unit) { if (duration < 0.001 && unit.is_none()) || unit == Some(Unit::MicroSecond) { (Unit::MicroSecond.format(duration), Unit::MicroSecond) } else if (duration < 1.0 && unit.is_none()) || unit == Some(Unit::MilliSecond) { (Unit::MilliSecond.format(duration), Unit::MilliSecond) } else { (Unit::Second.format(duration), Unit::Second) } } #[test] fn test_format_duration_unit_basic() { let (out_str, out_unit) = format_duration_unit(1.3, None); assert_eq!("1.300 s", out_str); assert_eq!(Unit::Second, out_unit); let (out_str, out_unit) = format_duration_unit(1.0, None); assert_eq!("1.000 s", out_str); assert_eq!(Unit::Second, out_unit); let (out_str, out_unit) = format_duration_unit(0.999, None); assert_eq!("999.0 ms", out_str); assert_eq!(Unit::MilliSecond, out_unit); let (out_str, out_unit) = format_duration_unit(0.0005, None); assert_eq!("500.0 µs", out_str); assert_eq!(Unit::MicroSecond, out_unit); let (out_str, out_unit) = format_duration_unit(0.0, None); assert_eq!("0.0 µs", out_str); assert_eq!(Unit::MicroSecond, out_unit); let (out_str, out_unit) = format_duration_unit(1000.0, None); assert_eq!("1000.000 s", out_str); assert_eq!(Unit::Second, out_unit); } #[test] fn test_format_duration_unit_with_unit() { let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::Second)); assert_eq!("1.300 s", out_str); assert_eq!(Unit::Second, out_unit); let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::MilliSecond)); assert_eq!("1300.0 ms", out_str); assert_eq!(Unit::MilliSecond, out_unit); let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::MicroSecond)); assert_eq!("1300000.0 µs", out_str); assert_eq!(Unit::MicroSecond, out_unit); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/output/warnings.rs
src/output/warnings.rs
use std::fmt; use crate::benchmark::MIN_EXECUTION_TIME; use crate::output::format::format_duration; use crate::util::units::Second; pub struct OutlierWarningOptions { pub warmup_in_use: bool, pub prepare_in_use: bool, } /// A list of all possible warnings pub enum Warnings { FastExecutionTime, NonZeroExitCode, SlowInitialRun(Second, OutlierWarningOptions), OutliersDetected(OutlierWarningOptions), } impl fmt::Display for Warnings { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Warnings::FastExecutionTime => write!( f, "Command took less than {:.0} ms to complete. Note that the results might be \ inaccurate because hyperfine can not calibrate the shell startup time much \ more precise than this limit. You can try to use the `-N`/`--shell=none` \ option to disable the shell completely.", MIN_EXECUTION_TIME * 1e3 ), Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."), Warnings::SlowInitialRun(time_first_run, ref options) => write!( f, "The first benchmarking run for this command was significantly slower than the \ rest ({time}). This could be caused by (filesystem) caches that were not filled until \ after the first run. {hints}", time=format_duration(time_first_run, None), hints=match (options.warmup_in_use, options.prepare_in_use) { (true, true) => "You are already using both the '--warmup' option as well \ as the '--prepare' option. Consider re-running the benchmark on a quiet system. \ Maybe it was a random outlier. Alternatively, consider increasing the warmup \ count.", (true, false) => "You are already using the '--warmup' option which helps \ to fill these caches before the actual benchmark. You can either try to \ increase the warmup count further or re-run this benchmark on a quiet system \ in case it was a random outlier. Alternatively, consider using the '--prepare' \ option to clear the caches before each timing run.", (false, true) => "You are already using the '--prepare' option which can \ be used to clear caches. If you did not use a cache-clearing command with \ '--prepare', you can either try that or consider using the '--warmup' option \ to fill those caches before the actual benchmark.", (false, false) => "You should consider using the '--warmup' option to fill \ those caches before the actual benchmark. Alternatively, use the '--prepare' \ option to clear the caches before each timing run." } ), Warnings::OutliersDetected(ref options) => write!( f, "Statistical outliers were detected. Consider re-running this benchmark on a quiet \ system without any interferences from other programs.{hint}", hint=if options.warmup_in_use && options.prepare_in_use { "" } else { " It might help to use the '--warmup' or '--prepare' options." } ), } } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/tests/execution_order_tests.rs
tests/execution_order_tests.rs
use std::{fs::File, io::Read, path::PathBuf}; use tempfile::{tempdir, TempDir}; mod common; use common::hyperfine; struct ExecutionOrderTest { cmd: assert_cmd::Command, expected_content: String, logfile_path: PathBuf, #[allow(dead_code)] tempdir: TempDir, } impl ExecutionOrderTest { fn new() -> Self { let tempdir = tempdir().unwrap(); let logfile_path = tempdir.path().join("output.log"); ExecutionOrderTest { cmd: hyperfine(), expected_content: String::new(), logfile_path, tempdir, } } fn arg<S: AsRef<str>>(&mut self, arg: S) -> &mut Self { self.cmd.arg(arg.as_ref()); self } fn get_command(&self, output: &str) -> String { format!( "echo {output} >> {path}", output = output, path = self.logfile_path.to_string_lossy() ) } fn command(&mut self, output: &str) -> &mut Self { self.arg(self.get_command(output)); self } fn setup(&mut self, output: &str) -> &mut Self { self.arg("--setup"); self.command(output) } fn prepare(&mut self, output: &str) -> &mut Self { self.arg("--prepare"); self.command(output) } fn reference(&mut self, output: &str) -> &mut Self { self.arg("--reference"); self.command(output) } fn conclude(&mut self, output: &str) -> &mut Self { self.arg("--conclude"); self.command(output) } fn cleanup(&mut self, output: &str) -> &mut Self { self.arg("--cleanup"); self.command(output) } fn expect_output(&mut self, output: &str) -> &mut Self { self.expected_content.push_str(output); #[cfg(windows)] { self.expected_content.push_str(" \r"); } self.expected_content.push('\n'); self } fn run(&mut self) { self.cmd.assert().success(); let mut f = File::open(&self.logfile_path).unwrap(); let mut content = String::new(); f.read_to_string(&mut content).unwrap(); assert_eq!(content, self.expected_content); } } impl Default for ExecutionOrderTest { fn default() -> Self { Self::new() } } #[test] fn benchmarks_are_executed_sequentially_one() { ExecutionOrderTest::new() .arg("--runs=1") .command("command 1") .command("command 2") .expect_output("command 1") .expect_output("command 2") .run(); } #[test] fn benchmarks_are_executed_sequentially() { ExecutionOrderTest::new() .arg("--runs=2") .command("command 1") .command("command 2") .expect_output("command 1") .expect_output("command 1") .expect_output("command 2") .expect_output("command 2") .run(); } #[test] fn warmup_runs_are_executed_before_benchmarking_runs() { ExecutionOrderTest::new() .arg("--runs=2") .arg("--warmup=3") .command("command 1") .expect_output("command 1") .expect_output("command 1") .expect_output("command 1") .expect_output("command 1") .expect_output("command 1") .run(); } #[test] fn setup_commands_are_executed_before_each_series_of_timing_runs() { ExecutionOrderTest::new() .arg("--runs=2") .setup("setup") .command("command 1") .command("command 2") .expect_output("setup") .expect_output("command 1") .expect_output("command 1") .expect_output("setup") .expect_output("command 2") .expect_output("command 2") .run(); } #[test] fn prepare_commands_are_executed_before_each_timing_run() { ExecutionOrderTest::new() .arg("--runs=2") .prepare("prepare") .command("command 1") .command("command 2") .expect_output("prepare") .expect_output("command 1") .expect_output("prepare") .expect_output("command 1") .expect_output("prepare") .expect_output("command 2") .expect_output("prepare") .expect_output("command 2") .run(); } #[test] fn conclude_commands_are_executed_after_each_timing_run() { ExecutionOrderTest::new() .arg("--runs=2") .conclude("conclude") .command("command 1") .command("command 2") .expect_output("command 1") .expect_output("conclude") .expect_output("command 1") .expect_output("conclude") .expect_output("command 2") .expect_output("conclude") .expect_output("command 2") .expect_output("conclude") .run(); } #[test] fn prepare_commands_are_executed_before_each_warmup() { ExecutionOrderTest::new() .arg("--warmup=2") .arg("--runs=1") .prepare("prepare") .command("command 1") .command("command 2") // warmup 1 .expect_output("prepare") .expect_output("command 1") .expect_output("prepare") .expect_output("command 1") // benchmark 1 .expect_output("prepare") .expect_output("command 1") // warmup 2 .expect_output("prepare") .expect_output("command 2") .expect_output("prepare") .expect_output("command 2") // benchmark 2 .expect_output("prepare") .expect_output("command 2") .run(); } #[test] fn conclude_commands_are_executed_after_each_warmup() { ExecutionOrderTest::new() .arg("--warmup=2") .arg("--runs=1") .conclude("conclude") .command("command 1") .command("command 2") // warmup 1 .expect_output("command 1") .expect_output("conclude") .expect_output("command 1") .expect_output("conclude") // benchmark 1 .expect_output("command 1") .expect_output("conclude") // warmup 2 .expect_output("command 2") .expect_output("conclude") .expect_output("command 2") .expect_output("conclude") // benchmark 2 .expect_output("command 2") .expect_output("conclude") .run(); } #[test] fn cleanup_commands_are_executed_once_after_each_benchmark() { ExecutionOrderTest::new() .arg("--runs=2") .cleanup("cleanup") .command("command 1") .command("command 2") .expect_output("command 1") .expect_output("command 1") .expect_output("cleanup") .expect_output("command 2") .expect_output("command 2") .expect_output("cleanup") .run(); } #[test] fn setup_prepare_cleanup_combined() { ExecutionOrderTest::new() .arg("--warmup=1") .arg("--runs=2") .setup("setup") .prepare("prepare") .command("command1") .command("command2") .cleanup("cleanup") // 1 .expect_output("setup") .expect_output("prepare") .expect_output("command1") .expect_output("prepare") .expect_output("command1") .expect_output("prepare") .expect_output("command1") .expect_output("cleanup") // 2 .expect_output("setup") .expect_output("prepare") .expect_output("command2") .expect_output("prepare") .expect_output("command2") .expect_output("prepare") .expect_output("command2") .expect_output("cleanup") .run(); } #[test] fn setup_prepare_conclude_cleanup_combined() { ExecutionOrderTest::new() .arg("--warmup=1") .arg("--runs=2") .setup("setup") .prepare("prepare") .command("command1") .command("command2") .conclude("conclude") .cleanup("cleanup") // 1 .expect_output("setup") .expect_output("prepare") .expect_output("command1") .expect_output("conclude") .expect_output("prepare") .expect_output("command1") .expect_output("conclude") .expect_output("prepare") .expect_output("command1") .expect_output("conclude") .expect_output("cleanup") // 2 .expect_output("setup") .expect_output("prepare") .expect_output("command2") .expect_output("conclude") .expect_output("prepare") .expect_output("command2") .expect_output("conclude") .expect_output("prepare") .expect_output("command2") .expect_output("conclude") .expect_output("cleanup") .run(); } #[test] fn single_parameter_value() { ExecutionOrderTest::new() .arg("--runs=2") .arg("--parameter-list") .arg("number") .arg("1,2,3") .command("command {number}") .expect_output("command 1") .expect_output("command 1") .expect_output("command 2") .expect_output("command 2") .expect_output("command 3") .expect_output("command 3") .run(); } #[test] fn multiple_parameter_values() { ExecutionOrderTest::new() .arg("--runs=2") .arg("--parameter-list") .arg("number") .arg("1,2,3") .arg("--parameter-list") .arg("letter") .arg("a,b") .command("command {number} {letter}") .expect_output("command 1 a") .expect_output("command 1 a") .expect_output("command 2 a") .expect_output("command 2 a") .expect_output("command 3 a") .expect_output("command 3 a") .expect_output("command 1 b") .expect_output("command 1 b") .expect_output("command 2 b") .expect_output("command 2 b") .expect_output("command 3 b") .expect_output("command 3 b") .run(); } #[test] fn reference_is_executed_first() { ExecutionOrderTest::new() .arg("--runs=1") .reference("reference") .command("command 1") .command("command 2") .expect_output("reference") .expect_output("command 1") .expect_output("command 2") .run(); } #[test] fn reference_is_executed_first_parameter_value() { ExecutionOrderTest::new() .arg("--runs=2") .reference("reference") .arg("--parameter-list") .arg("number") .arg("1,2,3") .command("command {number}") .expect_output("reference") .expect_output("reference") .expect_output("command 1") .expect_output("command 1") .expect_output("command 2") .expect_output("command 2") .expect_output("command 3") .expect_output("command 3") .run(); } #[test] fn reference_is_executed_separately_from_commands() { ExecutionOrderTest::new() .arg("--runs=1") .reference("command 1") .command("command 1") .command("command 2") .expect_output("command 1") .expect_output("command 1") .expect_output("command 2") .run(); } #[test] fn setup_prepare_reference_conclude_cleanup_combined() { ExecutionOrderTest::new() .arg("--warmup=1") .arg("--runs=2") .setup("setup") .prepare("prepare") .reference("reference") .command("command1") .command("command2") .conclude("conclude") .cleanup("cleanup") // reference .expect_output("setup") .expect_output("prepare") .expect_output("reference") .expect_output("conclude") .expect_output("prepare") .expect_output("reference") .expect_output("conclude") .expect_output("prepare") .expect_output("reference") .expect_output("conclude") .expect_output("cleanup") // 1 .expect_output("setup") .expect_output("prepare") .expect_output("command1") .expect_output("conclude") .expect_output("prepare") .expect_output("command1") .expect_output("conclude") .expect_output("prepare") .expect_output("command1") .expect_output("conclude") .expect_output("cleanup") // 2 .expect_output("setup") .expect_output("prepare") .expect_output("command2") .expect_output("conclude") .expect_output("prepare") .expect_output("command2") .expect_output("conclude") .expect_output("prepare") .expect_output("command2") .expect_output("conclude") .expect_output("cleanup") .run(); } #[test] fn setup_separate_prepare_separate_conclude_cleanup_combined() { ExecutionOrderTest::new() .arg("--warmup=1") .arg("--runs=2") .setup("setup") .cleanup("cleanup") .prepare("prepare1") .command("command1") .conclude("conclude1") .prepare("prepare2") .command("command2") .conclude("conclude2") // 1 .expect_output("setup") .expect_output("prepare1") .expect_output("command1") .expect_output("conclude1") .expect_output("prepare1") .expect_output("command1") .expect_output("conclude1") .expect_output("prepare1") .expect_output("command1") .expect_output("conclude1") .expect_output("cleanup") // 2 .expect_output("setup") .expect_output("prepare2") .expect_output("command2") .expect_output("conclude2") .expect_output("prepare2") .expect_output("command2") .expect_output("conclude2") .expect_output("prepare2") .expect_output("command2") .expect_output("conclude2") .expect_output("cleanup") .run(); } #[test] fn setup_separate_prepare_reference_separate_conclude_cleanup_combined() { ExecutionOrderTest::new() .arg("--warmup=1") .arg("--runs=2") .setup("setup") .cleanup("cleanup") .prepare("prepareref") .reference("reference") .conclude("concluderef") .prepare("prepare1") .command("command1") .conclude("conclude1") .prepare("prepare2") .command("command2") .conclude("conclude2") // reference .expect_output("setup") .expect_output("prepareref") .expect_output("reference") .expect_output("concluderef") .expect_output("prepareref") .expect_output("reference") .expect_output("concluderef") .expect_output("prepareref") .expect_output("reference") .expect_output("concluderef") .expect_output("cleanup") // 1 .expect_output("setup") .expect_output("prepare1") .expect_output("command1") .expect_output("conclude1") .expect_output("prepare1") .expect_output("command1") .expect_output("conclude1") .expect_output("prepare1") .expect_output("command1") .expect_output("conclude1") .expect_output("cleanup") // 2 .expect_output("setup") .expect_output("prepare2") .expect_output("command2") .expect_output("conclude2") .expect_output("prepare2") .expect_output("command2") .expect_output("conclude2") .expect_output("prepare2") .expect_output("command2") .expect_output("conclude2") .expect_output("cleanup") .run(); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/tests/integration_tests.rs
tests/integration_tests.rs
mod common; use common::hyperfine; use predicates::prelude::*; /// Platform-specific I/O utility. /// - On Unix-like systems, defaults to `cat`. /// - On Windows, uses `findstr` as an alternative. /// See: <https://superuser.com/questions/853580/real-windows-equivalent-to-cat-stdin> const STDIN_READ_COMMAND: &str = if cfg!(windows) { "findstr x*" } else { "cat" }; pub fn hyperfine_debug() -> assert_cmd::Command { let mut cmd = hyperfine(); cmd.arg("--debug-mode"); cmd } #[test] fn runs_successfully() { hyperfine() .arg("--runs=2") .arg("echo dummy benchmark") .assert() .success(); } #[test] fn one_run_is_supported() { hyperfine() .arg("--runs=1") .arg("echo dummy benchmark") .assert() .success(); } #[test] fn can_run_commands_without_a_shell() { hyperfine() .arg("--runs=1") .arg("--show-output") .arg("--shell=none") .arg("echo 'hello world' argument2") .assert() .success() .stdout(predicate::str::contains("hello world argument2")); } #[test] fn fails_with_wrong_number_of_command_name_arguments() { hyperfine() .arg("--command-name=a") .arg("--command-name=b") .arg("echo a") .assert() .failure() .stderr(predicate::str::contains("Too many --command-name options")); } #[test] fn fails_with_wrong_number_of_prepare_options() { hyperfine() .arg("--runs=1") .arg("--prepare=echo a") .arg("--prepare=echo b") .arg("echo a") .arg("echo b") .assert() .success(); hyperfine() .arg("--runs=1") .arg("--prepare=echo ref") .arg("--prepare=echo a") .arg("--prepare=echo b") .arg("--reference=echo ref") .arg("echo a") .arg("echo b") .assert() .success(); hyperfine() .arg("--runs=1") .arg("--prepare=echo a") .arg("--prepare=echo b") .arg("echo a") .arg("echo b") .arg("echo c") .assert() .failure() .stderr(predicate::str::contains( "The '--prepare' option has to be provided", )); hyperfine() .arg("--runs=1") .arg("--prepare=echo a") .arg("--prepare=echo b") .arg("--reference=echo ref") .arg("echo a") .arg("echo b") .assert() .failure() .stderr(predicate::str::contains( "The '--prepare' option has to be provided", )); } #[test] fn fails_with_wrong_number_of_conclude_options() { hyperfine() .arg("--runs=1") .arg("--conclude=echo a") .arg("--conclude=echo b") .arg("echo a") .arg("echo b") .assert() .success(); hyperfine() .arg("--runs=1") .arg("--conclude=echo ref") .arg("--conclude=echo a") .arg("--conclude=echo b") .arg("--reference=echo ref") .arg("echo a") .arg("echo b") .assert() .success(); hyperfine() .arg("--runs=1") .arg("--conclude=echo a") .arg("--conclude=echo b") .arg("echo a") .arg("echo b") .arg("echo c") .assert() .failure() .stderr(predicate::str::contains( "The '--conclude' option has to be provided", )); hyperfine() .arg("--runs=1") .arg("--conclude=echo a") .arg("--conclude=echo b") .arg("--reference=echo ref") .arg("echo a") .arg("echo b") .assert() .failure() .stderr(predicate::str::contains( "The '--conclude' option has to be provided", )); } #[test] fn fails_with_duplicate_parameter_names() { hyperfine() .arg("--parameter-list") .arg("x") .arg("1,2,3") .arg("--parameter-list") .arg("x") .arg("a,b,c") .arg("echo test") .assert() .failure() .stderr(predicate::str::contains("Duplicate parameter names: x")); } #[test] fn fails_for_unknown_command() { hyperfine() .arg("--runs=1") .arg("some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577") .assert() .failure() .stderr(predicate::str::contains( "Command terminated with non-zero exit code", )); } #[test] fn fails_for_unknown_command_without_shell() { hyperfine() .arg("--shell=none") .arg("--runs=1") .arg("some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577") .assert() .failure() .stderr(predicate::str::contains( "Failed to run command 'some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577'", )); } #[cfg(unix)] #[test] fn fails_for_failing_command_without_shell() { hyperfine() .arg("--shell=none") .arg("--runs=1") .arg("false") .assert() .failure() .stderr(predicate::str::contains( "Command terminated with non-zero exit code", )); } #[test] fn fails_for_unknown_setup_command() { hyperfine() .arg("--runs=1") .arg("--setup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577") .arg("echo test") .assert() .failure() .stderr(predicate::str::contains( "The setup command terminated with a non-zero exit code.", )); } #[test] fn fails_for_unknown_cleanup_command() { hyperfine() .arg("--runs=1") .arg("--cleanup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577") .arg("echo test") .assert() .failure() .stderr(predicate::str::contains( "The cleanup command terminated with a non-zero exit code.", )); } #[test] fn fails_for_unknown_prepare_command() { hyperfine() .arg("--prepare=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577") .arg("echo test") .assert() .failure() .stderr(predicate::str::contains( "The preparation command terminated with a non-zero exit code.", )); } #[test] fn fails_for_unknown_conclude_command() { hyperfine() .arg("--conclude=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577") .arg("echo test") .assert() .failure() .stderr(predicate::str::contains( "The conclusion command terminated with a non-zero exit code.", )); } #[cfg(unix)] #[test] fn can_run_failing_commands_with_ignore_failure_option() { hyperfine() .arg("false") .assert() .failure() .stderr(predicate::str::contains( "Command terminated with non-zero exit code", )); hyperfine() .arg("--runs=1") .arg("--ignore-failure") .arg("false") .assert() .success(); } #[cfg(unix)] #[test] fn can_ignore_specific_exit_codes() { // Test that specifying exit code 1 ignores it hyperfine() .arg("--runs=1") .arg("--ignore-failure=1") .arg("exit 1") .assert() .success(); // Test that other exit codes still fail hyperfine() .arg("--runs=1") .arg("--ignore-failure=1") .arg("exit 2") .assert() .failure() .stderr(predicate::str::contains( "Command terminated with non-zero exit code 2", )); } #[cfg(unix)] #[test] fn can_ignore_multiple_exit_codes() { // Test that all specified exit codes are ignored hyperfine() .arg("--runs=1") .arg("--ignore-failure=1,2,3") .arg("exit 1") .assert() .success(); hyperfine() .arg("--runs=1") .arg("--ignore-failure=1,2,3") .arg("exit 2") .assert() .success(); hyperfine() .arg("--runs=1") .arg("--ignore-failure=1,2,3") .arg("exit 3") .assert() .success(); // Test that other exit codes still fail hyperfine() .arg("--runs=1") .arg("--ignore-failure=1,2,3") .arg("exit 4") .assert() .failure() .stderr(predicate::str::contains( "Command terminated with non-zero exit code 4", )); } #[cfg(unix)] #[test] fn ignore_failure_with_all_non_zero() { // Test explicit "all-non-zero" mode hyperfine() .arg("--runs=1") .arg("--ignore-failure=all-non-zero") .arg("exit 5") .assert() .success(); } #[test] fn shows_output_of_benchmarked_command() { hyperfine() .arg("--runs=2") .arg("--command-name=dummy") .arg("--show-output") .arg("echo 4fd47015") .assert() .success() .stdout(predicate::str::contains("4fd47015").count(2)); } #[test] fn runs_commands_using_user_defined_shell() { hyperfine() .arg("--runs=1") .arg("--show-output") .arg("--shell") .arg("echo 'custom_shell' '--shell-arg'") .arg("echo benchmark") .assert() .success() .stdout( predicate::str::contains("custom_shell --shell-arg -c echo benchmark").or( predicate::str::contains("custom_shell --shell-arg /C echo benchmark"), ), ); } #[test] fn can_pass_input_to_command_from_a_file() { hyperfine() .arg("--runs=1") .arg("--input=example_input_file.txt") .arg("--show-output") .arg(STDIN_READ_COMMAND) .assert() .success() .stdout(predicate::str::contains("This text is part of a file")); } #[test] fn fails_if_invalid_stdin_data_file_provided() { hyperfine() .arg("--runs=1") .arg("--input=example_non_existent_file.txt") .arg("--show-output") .arg(STDIN_READ_COMMAND) .assert() .failure() .stderr(predicate::str::contains( "The file 'example_non_existent_file.txt' specified as '--input' does not exist", )); } #[test] fn returns_mean_time_in_correct_unit() { hyperfine_debug() .arg("sleep 1.234") .assert() .success() .stdout(predicate::str::contains("Time (mean ± σ): 1.234 s ±")); hyperfine_debug() .arg("sleep 0.123") .assert() .success() .stdout(predicate::str::contains("Time (mean ± σ): 123.0 ms ±")); hyperfine_debug() .arg("--time-unit=millisecond") .arg("sleep 1.234") .assert() .success() .stdout(predicate::str::contains("Time (mean ± σ): 1234.0 ms ±")); hyperfine_debug() .arg("--time-unit=microsecond") .arg("sleep 1.234") .assert() .success() .stdout(predicate::str::contains( "Time (mean ± σ): 1234000.0 µs ±", )); } #[test] fn performs_ten_runs_for_slow_commands() { hyperfine_debug() .arg("sleep 0.5") .assert() .success() .stdout(predicate::str::contains("10 runs")); } #[test] fn performs_three_seconds_of_benchmarking_for_fast_commands() { hyperfine_debug() .arg("sleep 0.01") .assert() .success() .stdout(predicate::str::contains("300 runs")); } #[test] fn takes_shell_spawning_time_into_account_for_computing_number_of_runs() { hyperfine_debug() .arg("--shell=sleep 0.02") .arg("sleep 0.01") .assert() .success() .stdout(predicate::str::contains("100 runs")); } #[test] fn takes_preparation_command_into_account_for_computing_number_of_runs() { hyperfine_debug() .arg("--prepare=sleep 0.02") .arg("sleep 0.01") .assert() .success() .stdout(predicate::str::contains("100 runs")); // Shell overhead needs to be added to both the prepare command and the actual command, // leading to a total benchmark time of (prepare + shell + cmd + shell = 0.1 s) hyperfine_debug() .arg("--shell=sleep 0.01") .arg("--prepare=sleep 0.03") .arg("sleep 0.05") .assert() .success() .stdout(predicate::str::contains("30 runs")); } #[test] fn takes_conclusion_command_into_account_for_computing_number_of_runs() { hyperfine_debug() .arg("--conclude=sleep 0.02") .arg("sleep 0.01") .assert() .success() .stdout(predicate::str::contains("100 runs")); // Shell overhead needs to be added to both the conclude command and the actual command, // leading to a total benchmark time of (cmd + shell + conclude + shell = 0.1 s) hyperfine_debug() .arg("--shell=sleep 0.01") .arg("--conclude=sleep 0.03") .arg("sleep 0.05") .assert() .success() .stdout(predicate::str::contains("30 runs")); } #[test] fn takes_both_preparation_and_conclusion_command_into_account_for_computing_number_of_runs() { hyperfine_debug() .arg("--prepare=sleep 0.01") .arg("--conclude=sleep 0.01") .arg("sleep 0.01") .assert() .success() .stdout(predicate::str::contains("100 runs")); // Shell overhead needs to be added to both the prepare, conclude and the actual command, // leading to a total benchmark time of (prepare + shell + cmd + shell + conclude + shell = 0.1 s) hyperfine_debug() .arg("--shell=sleep 0.01") .arg("--prepare=sleep 0.01") .arg("--conclude=sleep 0.01") .arg("sleep 0.05") .assert() .success() .stdout(predicate::str::contains("30 runs")); } #[test] fn shows_benchmark_comparison_with_relative_times() { hyperfine_debug() .arg("sleep 1.0") .arg("sleep 2.0") .arg("sleep 3.0") .assert() .success() .stdout( predicate::str::contains("2.00 ± 0.00 times faster") .and(predicate::str::contains("3.00 ± 0.00 times faster")), ); } #[test] fn shows_benchmark_comparison_with_same_time() { hyperfine_debug() .arg("--command-name=A") .arg("--command-name=B") .arg("sleep 1.0") .arg("sleep 1.0") .arg("sleep 2.0") .arg("sleep 1000.0") .assert() .success() .stdout( predicate::str::contains("As fast (1.00 ± 0.00) as") .and(predicate::str::contains("2.00 ± 0.00 times faster")) .and(predicate::str::contains("1000.00 ± 0.00 times faster")), ); } #[test] fn shows_benchmark_comparison_relative_to_reference() { hyperfine_debug() .arg("--reference=sleep 2.0") .arg("sleep 1.0") .arg("sleep 3.0") .assert() .success() .stdout( predicate::str::contains("2.00 ± 0.00 times slower") .and(predicate::str::contains("1.50 ± 0.00 times faster")), ); } #[test] fn shows_reference_name() { hyperfine_debug() .arg("--reference=sleep 2.0") .arg("--reference-name=refabc123") .arg("sleep 1.0") .arg("sleep 3.0") .assert() .success() .stdout(predicate::str::contains("Benchmark 1: refabc123")); } #[test] fn performs_all_benchmarks_in_parameter_scan() { hyperfine_debug() .arg("--parameter-scan") .arg("time") .arg("30") .arg("45") .arg("--parameter-step-size") .arg("5") .arg("sleep {time}") .assert() .success() .stdout( predicate::str::contains("Benchmark 1: sleep 30") .and(predicate::str::contains("Benchmark 2: sleep 35")) .and(predicate::str::contains("Benchmark 3: sleep 40")) .and(predicate::str::contains("Benchmark 4: sleep 45")) .and(predicate::str::contains("Benchmark 5: sleep 50").not()), ); } #[test] fn performs_reference_and_all_benchmarks_in_parameter_scan() { hyperfine_debug() .arg("--reference=sleep 25") .arg("--parameter-scan") .arg("time") .arg("30") .arg("45") .arg("--parameter-step-size") .arg("5") .arg("sleep {time}") .assert() .success() .stdout( predicate::str::contains("Benchmark 1: sleep 25") .and(predicate::str::contains("Benchmark 2: sleep 30")) .and(predicate::str::contains("Benchmark 3: sleep 35")) .and(predicate::str::contains("Benchmark 4: sleep 40")) .and(predicate::str::contains("Benchmark 5: sleep 45")) .and(predicate::str::contains("Benchmark 6: sleep 50").not()), ); } #[test] fn intermediate_results_are_not_exported_to_stdout() { hyperfine_debug() .arg("--style=none") // To only see the Markdown export on stdout .arg("--export-markdown") .arg("-") .arg("sleep 1") .arg("sleep 2") .assert() .success() .stdout( (predicate::str::contains("sleep 1").count(1)) .and(predicate::str::contains("sleep 2").count(1)), ); } #[test] #[cfg(unix)] fn exports_intermediate_results_to_file() { use tempfile::tempdir; let tempdir = tempdir().unwrap(); let export_path = tempdir.path().join("results.md"); hyperfine() .arg("--runs=1") .arg("--export-markdown") .arg(&export_path) .arg("true") .arg("false") .assert() .failure(); let contents = std::fs::read_to_string(export_path).unwrap(); assert!(contents.contains("true")); } #[test] fn unused_parameters_are_shown_in_benchmark_name() { hyperfine() .arg("--runs=2") .arg("--parameter-list") .arg("branch") .arg("master,feature") .arg("echo test") .assert() .success() .stdout( predicate::str::contains("echo test (branch = master)") .and(predicate::str::contains("echo test (branch = feature)")), ); } #[test] fn speed_comparison_sort_order() { for sort_order in ["auto", "mean-time"] { hyperfine_debug() .arg("sleep 2") .arg("sleep 1") .arg(format!("--sort={sort_order}")) .assert() .success() .stdout(predicate::str::contains( "sleep 1 ran\n 2.00 ± 0.00 times faster than sleep 2", )); } hyperfine_debug() .arg("sleep 2") .arg("sleep 1") .arg("--sort=command") .assert() .success() .stdout(predicate::str::contains( "2.00 ± 0.00 sleep 2\n 1.00 sleep 1", )); } #[cfg(windows)] #[test] fn windows_quote_args() { hyperfine() .arg("more \"example_input_file.txt\"") .assert() .success(); } #[cfg(windows)] #[test] fn windows_quote_before_quote_args() { hyperfine() .arg("dir \"..\\src\\\" \"..\\tests\\\"") .assert() .success(); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/tests/common.rs
tests/common.rs
use std::process::Command; use assert_cmd::cargo::CommandCargoExt; pub fn hyperfine_raw_command() -> Command { let mut cmd = Command::cargo_bin("hyperfine").unwrap(); cmd.current_dir("tests/"); cmd } pub fn hyperfine() -> assert_cmd::Command { assert_cmd::Command::from_std(hyperfine_raw_command()) }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/.github/workflows/scripts/check-dep-versions/src/main.rs
.github/workflows/scripts/check-dep-versions/src/main.rs
use regex::Regex; use std::collections::HashSet; // Import HashSet use std::fs; use std::process::exit; use toml::Value; // Dependency name required to use x.y.z format const REQUIRED_XYZ_DEP: &str = "fuel-core-client"; // Dependency names allowed (but not required) to use x.y.z format // Add names of common dev-dependencies here if you want to allow x.y.z for them const ALLOWED_XYZ_DEPS: &[&str] = &["etk-asm", "etk-ops", "dap", "fuel-abi-types"]; // Regex to strictly match semantic version x.y.z (no prefixes like ^, ~) const XYZ_REGEX_STR: &str = r"^\d+\.\d+\.\d+([\w.-]*)$"; // Allow suffixes like -alpha, .1 // Regex to strictly match semantic version x.y (no prefixes) const STRICT_XYZ_REQ_REGEX_STR: &str = r"^=\s*\d+\.\d+\.\d+([\w.-]*)$"; fn main() { let args: Vec<String> = std::env::args().collect(); let cargo_toml_path = args.get(1).unwrap_or_else(|| { eprintln!("Usage: check-dep-versions <path/to/root/Cargo.toml>"); exit(1); }); println!("Checking dependency versions in: {}", cargo_toml_path); let content = fs::read_to_string(cargo_toml_path).expect("Failed to read root Cargo.toml"); let doc: Value = content .parse::<Value>() .expect("Failed to parse root Cargo.toml"); let xyz_regex = Regex::new(XYZ_REGEX_STR).unwrap(); let strict_xyz_req_regex = Regex::new(STRICT_XYZ_REQ_REGEX_STR).unwrap(); // Convert the allowlist slice to a HashSet for efficient lookups let allowed_xyz_set: HashSet<String> = ALLOWED_XYZ_DEPS.iter().map(|s| s.to_string()).collect(); let mut errors_found = false; if let Some(workspace) = doc.get("workspace") { if let Some(dependencies) = workspace.get("dependencies") { if let Some(deps_table) = dependencies.as_table() { for (name, value) in deps_table { if let Some(table) = value.as_table() { if table.contains_key("path") { continue; } } let version_str = match value { Value::String(s) => Some(s.as_str()), Value::Table(t) => t.get("version").and_then(|v| v.as_str()), _ => None, }; if let Some(version) = version_str { let version_trimmed = version.trim(); // Trim whitespace // Check if the version string matches x.y.z patterns let is_specific_xyz = xyz_regex.is_match(version_trimmed) || strict_xyz_req_regex.is_match(version_trimmed); // Check required dependency if name == REQUIRED_XYZ_DEP { if !is_specific_xyz { eprintln!( "Error: Dependency '{}' MUST use specific 'x.y.z' format (e.g., \"0.41.9\" or \"= 0.41.9\"), but found '{}'", name, version ); errors_found = true; } } else if allowed_xyz_set.contains(name) { // It's on the allowlist, so x.y.z OR x.y is fine. No check needed here for format. continue; } else { // Check all other dependencies (not required and not allowed x.y.z explicitly) if is_specific_xyz { eprintln!( "Error: Dependency '{}' uses specific 'x.y.z' format ('{}'). Use 'x.y' format (e.g., \"0.59\") or add to allowlist if it's a dev-dependency.", name, version ); errors_found = true; } } } } } else { eprintln!("Warning: [workspace.dependencies] is not a table."); } } else { println!("No [workspace.dependencies] section found."); } } else { eprintln!("Warning: No [workspace] section found in Cargo.toml."); } if errors_found { eprintln!("\nDependency version format check failed."); exit(1); } else { println!("\nDependency version format check passed."); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/.github/workflows/scripts/check-forc-manifest-version/src/main.rs
.github/workflows/scripts/check-forc-manifest-version/src/main.rs
use std::fs; use std::process; use toml::Value; fn main() { println!("Checking that sway-lib-std version matches Cargo.toml"); let workspace_root = std::env::current_dir().expect("Failed to get current directory"); let cargo_content = fs::read_to_string(workspace_root.join("Cargo.toml")) .expect("Failed to read Cargo.toml"); let forc_content = fs::read_to_string(workspace_root.join("sway-lib-std/Forc.toml")) .expect("Failed to read sway-lib-std/Forc.toml"); let cargo_toml: Value = cargo_content.parse() .expect("Failed to parse Cargo.toml"); let forc_toml: Value = forc_content.parse() .expect("Failed to parse Forc.toml"); let cargo_version = cargo_toml["workspace"]["package"]["version"] .as_str() .expect("Could not find version in Cargo.toml"); let forc_version = forc_toml["project"]["version"] .as_str() .expect("Could not find version in sway-lib-std/Forc.toml"); if cargo_version != forc_version { eprintln!("Version mismatch!"); eprintln!("Cargo.toml: {}", cargo_version); eprintln!("sway-lib-std/Forc.toml: {}", forc_version); process::exit(1); } println!("Versions match: {}", cargo_version); process::exit(0); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/scripts/mdbook-forc-documenter/src/lib.rs
scripts/mdbook-forc-documenter/src/lib.rs
use crate::formatter::format_index_entry; use anyhow::{anyhow, bail}; use commands::{ get_contents_from_commands, get_forc_command_from_file_name, possible_forc_commands, }; use mdbook::book::{Book, BookItem, Chapter}; use mdbook::errors::{Error, Result}; use mdbook::preprocess::{Preprocessor, PreprocessorContext}; use plugins::forc_plugins_from_path; use std::collections::HashMap; use std::fs; use std::path::PathBuf; mod commands; mod formatter; mod plugins; #[derive(Default)] pub struct ForcDocumenter; impl ForcDocumenter { pub fn new() -> ForcDocumenter { ForcDocumenter } } impl Preprocessor for ForcDocumenter { fn name(&self) -> &str { "forc-documenter" } fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book, Error> { let strict = ctx .config .get_preprocessor(self.name()) .and_then(|t| t.get("strict")) .and_then(|val| val.as_bool()) .unwrap_or(false); let possible_commands: Vec<String> = possible_forc_commands(); let examples: HashMap<String, String> = load_examples()?; let plugin_commands = forc_plugins_from_path()?; let mut command_contents: HashMap<String, String> = get_contents_from_commands(&possible_commands); let mut plugin_contents: HashMap<String, String> = get_contents_from_commands(&plugin_commands); let mut removed_commands = Vec::new(); book.for_each_mut(|item| { if let BookItem::Chapter(ref mut chapter) = item { if chapter.name == "Plugins" { for sub_item in &mut chapter.sub_items { if let BookItem::Chapter(ref mut plugin_chapter) = sub_item { if let Some(content) = plugin_contents.remove(&plugin_chapter.name) { inject_content(plugin_chapter, &content, &examples); } else { // When sub_items exist, it means that a plugin installs a group of // commands, and the name of the plugin will not match this group. // Note that this is determined by SUMMARY.md by placing // sub-chapters under a chapter. if plugin_chapter.sub_items.is_empty() { removed_commands.push(plugin_chapter.name.clone()); } }; for sub_sub_item in &mut plugin_chapter.sub_items { if let BookItem::Chapter(ref mut plugin_sub_chapter) = sub_sub_item { // Skip validation for nested documentation entries // These are documentation-only entries that don't correspond to actual commands if let Some(content) = plugin_contents.remove(&plugin_sub_chapter.name) { inject_content(plugin_sub_chapter, &content, &examples); } // Don't mark nested entries as removed - they're documentation sections } } } } } if chapter.name == "Commands" { let mut command_index_content = String::new(); for sub_item in &mut chapter.sub_items { if let BookItem::Chapter(ref mut command_chapter) = sub_item { if let Some(content) = command_contents.remove(&command_chapter.name) { command_index_content .push_str(&format_index_entry(&command_chapter.name)); inject_content(command_chapter, &content, &examples); } else { removed_commands.push(command_chapter.name.clone()); }; } } chapter.content.push_str(&command_index_content); } } }); let mut error_message = String::new(); if !command_contents.is_empty() || !plugin_contents.is_empty() { let mut missing: Vec<String> = command_contents.keys().cloned().collect(); missing.append(&mut plugin_contents.keys().cloned().collect()); error_message.push_str(&missing_entries_msg(&missing)); }; if !removed_commands.is_empty() { error_message.push_str(&dangling_chapters_msg(&removed_commands)); }; if strict && !error_message.is_empty() { Err(Error::msg(error_message)) } else { if !error_message.is_empty() { eprintln!("Warning:"); eprintln!("{error_message}"); eprintln!("The book built successfully - if the changes above were intended or if you are editing pages unrelated to Forc, you may ignore this message."); } Ok(book) } } fn supports_renderer(&self, renderer: &str) -> bool { renderer == "html" } } fn inject_content(chapter: &mut Chapter, content: &str, examples: &HashMap<String, String>) { chapter.content = content.to_string(); if let Some(example_content) = examples.get(&chapter.name) { chapter.content += example_content; } } fn missing_entries_msg(missing: &[String]) -> String { let missing_commands = missing .iter() .map(|s| s.to_owned() + "\n") .collect::<String>(); let missing_entries: String = missing.iter().map(|c| format_index_entry(c)).collect(); format!("\nSome entries were missing from SUMMARY.md:\n\n{missing_commands}\n\nTo fix this, add the above entries under the Commands or Plugins chapter in SUMMARY.md, like so:\n\n{missing_entries}\n") } fn dangling_chapters_msg(commands: &[String]) -> String { format!("\nSome commands/plugins were removed from the Forc toolchain, but still exist in SUMMARY.md:\n\n{}\n\nTo fix this, remove the corresponding entries from SUMMARY.md.\n", commands .iter() .map(|s| s.to_owned() + "\n") .collect::<String>()) } fn find_sway_repo_root() -> anyhow::Result<PathBuf> { let mut curr_path = std::env::current_dir().unwrap(); loop { if curr_path.is_dir() { // Some heuristics that should pass if we've found the sway repo. if curr_path.join("Cargo.toml").exists() && curr_path.join("forc-plugins").exists() && curr_path .join("scripts") .join("mdbook-forc-documenter") .exists() { return Ok(curr_path); } } curr_path = curr_path .parent() .ok_or_else(|| anyhow!("Could not find Sway repo root directory"))? .to_path_buf(); } } fn find_forc_cmd_examples_dir() -> anyhow::Result<PathBuf> { let sway_dir = find_sway_repo_root()?; let examples_dir = sway_dir .join("scripts") .join("mdbook-forc-documenter") .join("examples"); if !examples_dir.exists() || !examples_dir.is_dir() { bail!( "Failed to find examples directory at {}", examples_dir.display() ); } Ok(examples_dir) } fn load_examples() -> Result<HashMap<String, String>> { let examples_dir = find_forc_cmd_examples_dir().unwrap(); let mut command_examples: HashMap<String, String> = HashMap::new(); for entry in examples_dir .read_dir() .expect("read dir examples failed") .flatten() { let command_name = get_forc_command_from_file_name(entry.file_name()); let example_content = fs::read_to_string(entry.path())?; command_examples.insert(command_name, example_content); } Ok(command_examples) } #[cfg(test)] mod tests { use super::*; #[test] fn test_missing_entries_msg() { let missing = vec!["forc addr2line".to_string(), "forc build".to_string()]; let expected_msg = r#" Some entries were missing from SUMMARY.md: forc addr2line forc build To fix this, add the above entries under the Commands or Plugins chapter in SUMMARY.md, like so: - [forc addr2line](./forc_addr2line.md) - [forc build](./forc_build.md) "#; assert_eq!(expected_msg, missing_entries_msg(&missing)); } #[test] fn test_dangling_chapters_msg() { let commands = vec!["forc addr2line".to_string(), "forc build".to_string()]; let expected_msg = r#" Some commands/plugins were removed from the Forc toolchain, but still exist in SUMMARY.md: forc addr2line forc build To fix this, remove the corresponding entries from SUMMARY.md. "#; assert_eq!(expected_msg, dangling_chapters_msg(&commands)); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/scripts/mdbook-forc-documenter/src/commands.rs
scripts/mdbook-forc-documenter/src/commands.rs
use crate::formatter::{format_header_line, format_line}; use anyhow::{anyhow, Result}; use std::{collections::HashMap, ffi::OsString, process}; pub fn possible_forc_commands() -> Vec<String> { let output = process::Command::new("forc") .arg("--help") .output() .expect("Failed running forc --help"); let output_str = String::from_utf8_lossy(&output.stdout); let lines = output_str.lines(); let mut possible_commands = Vec::new(); let mut in_commands_section = false; for line in lines { if line.trim() == "Commands:" { // Start of commands section in_commands_section = true; continue; } if in_commands_section { if line.trim().is_empty() || line.trim().starts_with("Options:") { // End of commands section break; } // Extract command name (first word of the line) if let Some(command) = line.split_whitespace().next() { possible_commands.push(command.to_string()); } } } possible_commands } pub fn get_contents_from_commands(commands: &[String]) -> HashMap<String, String> { let mut contents: HashMap<String, String> = HashMap::new(); for command in commands { let Ok(result) = generate_documentation(command) else { continue; }; contents.insert("forc ".to_owned() + command, result); } contents } fn generate_documentation(subcommand: &str) -> Result<String> { let mut result = String::new(); let mut has_parsed_subcommand_header = false; let output = process::Command::new("forc") .args([subcommand, "--help"]) .output() .expect("Failed running forc --help"); if !output.status.success() { return Err(anyhow!("Failed to run forc {} --help", subcommand)); } let s = String::from_utf8_lossy(&output.stdout) + String::from_utf8_lossy(&output.stderr); for (index, line) in s.lines().enumerate() { let mut formatted_line = String::new(); let line = line.trim(); if line == "SUBCOMMANDS:" { has_parsed_subcommand_header = true; } if index == 0 { formatted_line.push_str(&format_header_line(line)); } else if index == 1 { formatted_line.push_str(line); } else { formatted_line.push_str(&format_line(line, has_parsed_subcommand_header)); } result.push_str(&formatted_line); if !formatted_line.ends_with('\n') { result.push('\n'); } } result = result.trim().to_string(); Ok(result) } pub fn get_forc_command_from_file_name(file_name: OsString) -> String { file_name .into_string() .unwrap() .split('.') .next() .unwrap() .to_string() .replace('_', " ") } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_forc_command_from_file_name() { assert_eq!( "forc fmt", get_forc_command_from_file_name(OsString::from("forc_fmt.md")), ); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/scripts/mdbook-forc-documenter/src/plugins.rs
scripts/mdbook-forc-documenter/src/plugins.rs
use anyhow::{anyhow, Result}; use std::{collections::HashSet, process}; /// Detects plugins available via `PATH`. /// /// Note that plugin discovery works reliably within the Sway CI since the installed plugins are in /// a controlled environment. Building the book locally on your own machine may create a different /// book depending on what plugins are available on your PATH. pub(crate) fn forc_plugins_from_path() -> Result<Vec<String>> { let output = process::Command::new("forc") .arg("plugins") .output() .expect("Failed running forc plugins"); if !output.status.success() { return Err(anyhow!("Failed to run forc plugins")); } let mut plugins = HashSet::new(); let s = String::from_utf8_lossy(&output.stdout) + String::from_utf8_lossy(&output.stderr); for plugin in s.lines() { if let Some(("", command)) = plugin.split_once("forc-") { plugins.insert(command.to_string()); } } Ok(Vec::from_iter(plugins)) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/scripts/mdbook-forc-documenter/src/formatter.rs
scripts/mdbook-forc-documenter/src/formatter.rs
#[derive(PartialEq, Eq)] pub enum LineKind { SubHeader, Arg, Option, Subcommand, Text, } fn get_line_kind(line: &str, has_parsed_subcommand_header: bool) -> LineKind { if SUBHEADERS.contains(&line) { LineKind::SubHeader } else if is_args_line(line) { LineKind::Arg } else if is_options_line(line) { LineKind::Option } else if has_parsed_subcommand_header { LineKind::Subcommand } else { LineKind::Text } } pub const SUBHEADERS: &[&str] = &["USAGE:", "ARGS:", "OPTIONS:", "SUBCOMMANDS:"]; pub fn is_args_line(line: &str) -> bool { line.trim().starts_with('<') } pub fn is_options_line(line: &str) -> bool { line.trim().starts_with('-') && line.trim().chars().nth(1).unwrap() != ' ' } pub fn is_option(token: &str) -> bool { token.starts_with('-') } pub fn is_arg(token: &str) -> bool { token.starts_with('<') } pub fn format_header_line(header_line: &str) -> String { "\n# ".to_owned() + header_line.split_whitespace().next().unwrap() + "\n" } pub fn format_line(line: &str, has_parsed_subcommand_header: bool) -> String { match get_line_kind(line, has_parsed_subcommand_header) { LineKind::SubHeader => format_subheader_line(line), LineKind::Option => format_option_line(line), LineKind::Arg => format_arg_line(line), LineKind::Subcommand => format_subcommand_line(line), LineKind::Text => line.to_string(), } } fn format_subheader_line(subheader_line: &str) -> String { "\n## ".to_owned() + subheader_line + "\n" } fn format_subcommand_line(line: &str) -> String { let mut line_iter = line.trim().splitn(2, ' '); let name = "`".to_owned() + line_iter.next().unwrap() + "`\n\n"; let text = line_iter.collect::<String>().trim_start().to_owned() + "\n\n"; name + &text } fn format_arg_line(arg_line: &str) -> String { let mut formatted_arg_line = String::new(); for c in arg_line.chars() { if c == '>' { formatted_arg_line.push('_'); formatted_arg_line.push(c); } else if c == '<' { formatted_arg_line.push(c); formatted_arg_line.push('_'); } else { formatted_arg_line.push(c); } } if !formatted_arg_line.trim().ends_with('>') { let last_closing_bracket_idx = formatted_arg_line.rfind('>').unwrap(); formatted_arg_line.replace_range( last_closing_bracket_idx + 1..last_closing_bracket_idx + 2, "\n\n", ); } "\n".to_owned() + &formatted_arg_line } fn format_option_line(option_line: &str) -> String { let mut tokens_iter = option_line.trim().split(' '); let mut result = String::new(); let mut rest_of_line = String::new(); while let Some(token) = tokens_iter.next() { if is_option(token) { result.push_str(&format_option(token)); } else if is_arg(token) { result.push_str(&format_arg(token)); } else { rest_of_line.push_str(token); rest_of_line.push(' '); rest_of_line = tokens_iter .fold(rest_of_line, |mut a, b| { a.reserve(b.len() + 1); a.push_str(b); a.push(' '); a }) .trim() .to_string(); break; } } result.push_str("\n\n"); result.push_str(&rest_of_line); result.push('\n'); "\n".to_owned() + &result } fn format_arg(arg: &str) -> String { let mut result = String::new(); let mut inner = arg.to_string(); inner.pop(); inner.remove(0); result.push('<'); result.push('_'); result.push_str(&inner); result.push('_'); result.push('>'); result } fn format_option(option: &str) -> String { if option.ends_with(',') { let mut s = option.to_string(); s.pop(); "`".to_owned() + &s + "`, " } else { "`".to_owned() + option + "` " } } /// Index entries should be in the form of: /// - [forc addr2line](./forc_addr2line.md)\n pub fn format_index_entry(forc_command_str: &str) -> String { let command_name = forc_command_str; let command_link = forc_command_str.replace(' ', "_"); format!("- [{command_name}](./{command_link}.md)\n") } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_options_line() { let example_option_line_1= " -s, --silent Silent mode. Don't output any warnings or errors to the command line"; let example_option_line_2 = " -o <JSON_OUTFILE> If set, outputs a json file representing the output json abi"; let example_option_line_3 = " - counter"; assert!(is_options_line(example_option_line_1)); assert!(is_options_line(example_option_line_2)); assert!(!is_options_line(example_option_line_3)); } #[test] fn test_format_index_entry() { let forc_command = "forc build"; assert_eq!( format_index_entry(forc_command), "- [forc build](./forc_build.md)\n" ); } #[test] fn test_format_header_line() { let example_header = "forc-fmt"; let expected_header = "\n# forc-fmt\n"; assert_eq!(expected_header, format_header_line(example_header)); } #[test] fn test_format_subheader_line() { let example_subheader = "USAGE:"; let expected_subheader = "\n## USAGE:\n"; assert_eq!(expected_subheader, format_subheader_line(example_subheader)); } #[test] fn test_format_arg_line() { let example_arg_line_1 = "<PROJECT_NAME> Some description"; let example_arg_line_2 = "<arg1> <arg2> Some description"; let expected_arg_line_1 = "\n<_PROJECT_NAME_>\n\nSome description"; let expected_arg_line_2 = "\n<_arg1_> <_arg2_>\n\nSome description"; assert_eq!(expected_arg_line_1, format_arg_line(example_arg_line_1)); assert_eq!(expected_arg_line_2, format_arg_line(example_arg_line_2)); } #[test] fn test_format_option_line() { let example_option_line_1 = "-c, --check Run in 'check' mode. Exits with 0 if input is formatted correctly. Exits with 1 and prints a diff if formatting is required"; let example_option_line_2 = "-o <JSON_OUTFILE> If set, outputs a json file representing the output json abi"; let expected_option_line_1= "\n`-c`, `--check` \n\nRun in 'check' mode. Exits with 0 if input is formatted correctly. Exits with 1 and prints a diff if formatting is required\n"; let expected_option_line_2 = "\n`-o` <_JSON_OUTFILE_>\n\nIf set, outputs a json file representing the output json abi\n"; assert_eq!( expected_option_line_1, format_option_line(example_option_line_1) ); assert_eq!( expected_option_line_2, format_option_line(example_option_line_2) ); } #[test] fn test_format_subcommand_line() { let example_subcommand = " clean Cleans up any existing state associated with the fuel block explorer"; let expected_subcommand = "`clean`\n\nCleans up any existing state associated with the fuel block explorer\n\n"; assert_eq!( expected_subcommand, format_subcommand_line(example_subcommand) ); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/scripts/mdbook-forc-documenter/src/bin/mdbook-forc-documenter.rs
scripts/mdbook-forc-documenter/src/bin/mdbook-forc-documenter.rs
use clap::{Arg, ArgMatches, Command}; use mdbook::errors::Error; use mdbook::preprocess::{CmdPreprocessor, Preprocessor}; use mdbook_forc_documenter::ForcDocumenter; use semver::{Version, VersionReq}; use std::io; use std::process; pub fn make_app() -> Command { Command::new("forc-documenter") .about("A mdbook preprocessor which documents Forc commands") .subcommand( Command::new("supports") .arg( Arg::new("renderer") .required(true) .value_parser(clap::value_parser!(String)), ) .about("Check whether a renderer is supported by this preprocessor"), ) } fn main() { let matches = make_app().get_matches(); let preprocessor = ForcDocumenter::new(); if let Some(sub_args) = matches.subcommand_matches("supports") { handle_supports(&preprocessor, sub_args); } else if let Err(e) = handle_preprocessing(&preprocessor) { eprintln!("{e}"); process::exit(1); } } fn handle_preprocessing(pre: &dyn Preprocessor) -> Result<(), Error> { let (ctx, book) = CmdPreprocessor::parse_input(io::stdin())?; let book_version = Version::parse(&ctx.mdbook_version)?; let version_req = VersionReq::parse(mdbook::MDBOOK_VERSION)?; if !version_req.matches(&book_version) { eprintln!( "Warning: The {} plugin was built against version {} of mdbook, \ but we're being called from version {}", pre.name(), mdbook::MDBOOK_VERSION, ctx.mdbook_version ); } let processed_book = pre.run(&ctx, book)?; serde_json::to_writer(io::stdout(), &processed_book)?; Ok(()) } fn handle_supports(pre: &dyn Preprocessor, sub_args: &ArgMatches) -> ! { let renderer = sub_args.get_one::<String>("renderer").map(String::as_str); let supported = renderer.map(|r| pre.supports_renderer(r)).unwrap_or(false); // Signal whether the renderer is supported by exiting with 1 or 0. if supported { process::exit(0); } else { process::exit(1); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/source_map.rs
sway-core/src/source_map.rs
use dirs::home_dir; use std::{ collections::BTreeMap, path::{Path, PathBuf}, }; use sway_types::{LineCol, SourceEngine}; use serde::{Deserialize, Serialize}; use sway_types::span::Span; /// Index of an interned path string #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct PathIndex(pub usize); #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SourceMap { /// Paths of dependencies in the `~/.forc` directory, with the prefix stripped. /// This makes inverse source mapping work on any machine with deps downloaded. pub dependency_paths: Vec<PathBuf>, /// Paths to source code files, defined separately to avoid repetition. pub paths: Vec<PathBuf>, /// Mapping from opcode index to source location // count of instructions, multiply the opcode by 4 to get the byte offset pub map: BTreeMap<usize, SourceMapSpan>, } impl SourceMap { pub fn new() -> Self { Self::default() } /// Inserts dependency path. Unsupported locations are ignored for now. pub fn insert_dependency<P: AsRef<Path>>(&mut self, path: P) { if let Some(home) = home_dir() { let forc = home.join(".forc/"); if let Ok(unprefixed) = path.as_ref().strip_prefix(forc) { self.dependency_paths.push(unprefixed.to_owned()); } } // TODO: Only dependencies in ~/.forc are supported for now } pub fn insert(&mut self, source_engine: &SourceEngine, pc: usize, span: &Span) { if let Some(source_id) = span.source_id() { let path = source_engine.get_path(source_id); let path_index = self .paths .iter() .position(|p| *p == *path) .unwrap_or_else(|| { self.paths.push((*path).to_owned()); self.paths.len() - 1 }); self.map.insert( pc, SourceMapSpan { path: PathIndex(path_index), range: LocationRange { start: span.start_line_col_one_index(), end: span.end_line_col_one_index(), }, }, ); } } /// Inverse source mapping pub fn addr_to_span(&self, pc: usize) -> Option<(PathBuf, LocationRange)> { self.map .get(&pc) .map(|sms| sms.to_span(&self.paths, &self.dependency_paths)) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SourceMapSpan { pub path: PathIndex, pub range: LocationRange, } impl SourceMapSpan { pub fn to_span( &self, paths: &[PathBuf], dependency_paths: &[PathBuf], ) -> (PathBuf, LocationRange) { let p = &paths[self.path.0]; for dep in dependency_paths { if p.starts_with(dep.file_name().unwrap()) { let mut path = home_dir().expect("Could not get homedir").join(".forc"); if let Some(dp) = dep.parent() { path = path.join(dp); } return (path.join(p), self.range); } } (p.to_owned(), self.range) } } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct LocationRange { pub start: LineCol, pub end: LineCol, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/lib.rs
sway-core/src/lib.rs
#![recursion_limit = "256"] #[macro_use] pub mod error; #[macro_use] pub mod engine_threading; pub mod abi_generation; pub mod asm_generation; mod asm_lang; mod build_config; pub mod compiler_generated; mod concurrent_slab; mod control_flow_analysis; mod debug_generation; pub mod decl_engine; pub mod ir_generation; pub mod language; pub mod marker_traits; mod metadata; pub mod obs_engine; pub mod query_engine; pub mod semantic_analysis; pub mod source_map; pub mod transform; pub mod type_system; use crate::ir_generation::check_function_purity; use crate::language::{CallPath, CallPathType}; use crate::query_engine::ModuleCacheEntry; use crate::semantic_analysis::namespace::ResolvedDeclaration; use crate::semantic_analysis::type_resolve::{resolve_call_path, VisibilityCheck}; use crate::source_map::SourceMap; pub use asm_generation::from_ir::compile_ir_context_to_finalized_asm; use asm_generation::FinalizedAsm; pub use asm_generation::{CompiledBytecode, FinalizedEntry}; pub use build_config::DbgGeneration; pub use build_config::{Backtrace, BuildConfig, BuildTarget, IrCli, LspConfig, OptLevel, PrintAsm}; use control_flow_analysis::ControlFlowGraph; pub use debug_generation::write_dwarf; use itertools::Itertools; use metadata::MetadataManager; use query_engine::{ModuleCacheKey, ModuleCommonInfo, ParsedModuleInfo, ProgramsCacheEntry}; use semantic_analysis::program::TypeCheckFailed; use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use sway_ast::AttributeDecl; use sway_error::convert_parse_tree_error::ConvertParseTreeError; use sway_error::handler::{ErrorEmitted, Handler}; use sway_error::warning::{CollectedTraitImpl, CompileInfo, CompileWarning, Info, Warning}; use sway_features::ExperimentalFeatures; use sway_ir::{ create_o1_pass_group, register_known_passes, Context, Kind, Module, PassGroup, PassManager, PrintPassesOpts, VerifyPassesOpts, ARG_DEMOTION_NAME, ARG_POINTEE_MUTABILITY_TAGGER_NAME, CONST_DEMOTION_NAME, DCE_NAME, FN_DEDUP_DEBUG_PROFILE_NAME, FN_INLINE_NAME, GLOBALS_DCE_NAME, MEM2REG_NAME, MEMCPYOPT_NAME, MEMCPYPROP_REVERSE_NAME, MISC_DEMOTION_NAME, RET_DEMOTION_NAME, SIMPLIFY_CFG_NAME, SROA_NAME, }; use sway_types::span::Source; use sway_types::{SourceEngine, SourceLocation, Span}; use sway_utils::{time_expr, PerformanceData, PerformanceMetric}; use transform::{ArgsExpectValues, Attribute, AttributeKind, Attributes, ExpectedArgs}; use types::{CollectTypesMetadata, CollectTypesMetadataContext, LogId, TypeMetadata}; pub use semantic_analysis::namespace::{self, Namespace}; pub mod types; use sway_error::error::CompileError; use sway_types::{ident::Ident, span, Spanned}; pub use type_system::*; pub use language::Programs; use language::{lexed, parsed, ty, Visibility}; use transform::to_parsed_lang::{self, convert_module_kind}; pub mod fuel_prelude { pub use fuel_vm::{self, fuel_asm, fuel_crypto, fuel_tx, fuel_types}; } pub use engine_threading::Engines; pub use obs_engine::{ObservabilityEngine, Observer}; /// Given an input `Arc<str>` and an optional [BuildConfig], parse the input into a [lexed::LexedProgram] and [parsed::ParseProgram]. /// /// # Example /// ```ignore /// # use sway_core::parse; /// # fn main() { /// let input = "script; fn main() -> bool { true }"; /// let result = parse(input.into(), <_>::default(), None); /// # } /// ``` /// /// # Panics /// Panics if the parser panics. pub fn parse( src: Source, handler: &Handler, engines: &Engines, config: Option<&BuildConfig>, experimental: ExperimentalFeatures, package_name: &str, ) -> Result<(lexed::LexedProgram, parsed::ParseProgram), ErrorEmitted> { match config { None => parse_in_memory( handler, engines, src, experimental, DbgGeneration::None, package_name, ), // When a `BuildConfig` is given, // the module source may declare `mod`s that must be parsed from other files. Some(config) => parse_module_tree( handler, engines, src, config.canonical_root_module(), None, config.build_target, config.dbg_generation, config.include_tests, experimental, config.lsp_mode.as_ref(), package_name, ) .map( |ParsedModuleTree { tree_type: kind, lexed_module, parse_module, }| { let lexed = lexed::LexedProgram { kind, root: lexed_module, }; let parsed = parsed::ParseProgram { kind, root: parse_module, }; (lexed, parsed) }, ), } } /// Parses the tree kind in the input provided. /// /// This will lex the entire input, but parses only the module kind. pub fn parse_tree_type(handler: &Handler, src: Source) -> Result<parsed::TreeType, ErrorEmitted> { // Parsing only the module kind does not depend on any // experimental feature. So, we can just pass the default // experimental features here. let experimental = ExperimentalFeatures::default(); sway_parse::parse_module_kind(handler, src, None, experimental) .map(|kind| convert_module_kind(&kind)) } /// Converts `attribute_decls` to [Attributes]. /// /// This function always returns [Attributes], even if the attributes are erroneous. /// Errors and warnings are returned via [Handler]. The callers should ignore eventual errors /// in attributes and proceed with the compilation. [Attributes] are tolerant to erroneous /// attributes and follows the last-wins principle, which allows annotated elements to /// proceed with compilation. After their successful compilation, callers need to inspect /// the [Handler] and still emit errors if there were any. pub(crate) fn attr_decls_to_attributes( attribute_decls: &[AttributeDecl], can_annotate: impl Fn(&Attribute) -> bool, target_friendly_name: &'static str, ) -> (Handler, Attributes) { let handler = Handler::default(); // Check if attribute is an unsupported inner attribute (`#!`). // Note that we are doing that before creating the flattened `attributes`, // because we want the error to point at the `#!` token. // Note also that we will still include those attributes into // the `attributes`. There are cases, like e.g., LSP, where // having complete list of attributes is needed. // In the below analysis, though, we will be ignoring inner attributes, // means not checking their content. for attr_decl in attribute_decls .iter() .filter(|attr| !attr.is_doc_comment() && attr.is_inner()) { handler.emit_err(CompileError::Unimplemented { span: attr_decl.hash_kind.span(), feature: "Using inner attributes (`#!`)".to_string(), help: vec![], }); } let attributes = Attributes::new(attribute_decls); // Check for unknown attributes. for attribute in attributes.unknown().filter(|attr| attr.is_outer()) { handler.emit_warn(CompileWarning { span: attribute.name.span(), warning_content: Warning::UnknownAttribute { attribute: (&attribute.name).into(), known_attributes: attributes.known_attribute_names(), }, }); } // Check for attributes annotating invalid targets. for ((attribute_kind, _attribute_direction), mut attributes) in &attributes .all() .filter(|attr| attr.is_doc_comment() || attr.is_outer()) .chunk_by(|attr| (attr.kind, attr.direction)) { // For doc comments, we want to show the error on a complete doc comment, // and not on every documentation line. if attribute_kind == AttributeKind::DocComment { let first_doc_line = attributes .next() .expect("`chunk_by` guarantees existence of at least one element in the chunk"); if !can_annotate(first_doc_line) { let last_doc_line = match attributes.last() { Some(last_attr) => last_attr, // There is only one doc line in the complete doc comment. None => first_doc_line, }; handler.emit_err( ConvertParseTreeError::InvalidAttributeTarget { span: Span::join( first_doc_line.span.clone(), &last_doc_line.span.start_span(), ), attribute: first_doc_line.name.clone(), target_friendly_name, can_only_annotate_help: first_doc_line .can_only_annotate_help(target_friendly_name), } .into(), ); } } else { // For other attributes, the error is shown for every individual attribute. for attribute in attributes { if !can_annotate(attribute) { handler.emit_err( ConvertParseTreeError::InvalidAttributeTarget { span: attribute.name.span(), attribute: attribute.name.clone(), target_friendly_name, can_only_annotate_help: attribute .can_only_annotate_help(target_friendly_name), } .into(), ); } } } } // In all the subsequent test we are checking only non-doc-comment attributes // and only those that didn't produce invalid target or unsupported inner attributes errors. let should_be_checked = |attr: &&Attribute| !attr.is_doc_comment() && attr.is_outer() && can_annotate(attr); // Check for attributes multiplicity. for (_attribute_kind, attributes_of_kind) in attributes.all_by_kind(|attr| should_be_checked(attr) && !attr.kind.allows_multiple()) { if attributes_of_kind.len() > 1 { let (last_attribute, previous_attributes) = attributes_of_kind .split_last() .expect("`attributes_of_kind` has more than one element"); handler.emit_err( ConvertParseTreeError::InvalidAttributeMultiplicity { last_occurrence: (&last_attribute.name).into(), previous_occurrences: previous_attributes .iter() .map(|attr| (&attr.name).into()) .collect(), } .into(), ); } } // Check for arguments multiplicity. // For attributes that can be applied only once but are applied several times // we will still check arguments in every attribute occurrence. for attribute in attributes.all().filter(should_be_checked) { let _ = attribute.check_args_multiplicity(&handler); } // Check for expected arguments. // For attributes that can be applied only once but are applied more times // we will check arguments of every attribute occurrence. // If an attribute does not expect any arguments, we will not check them, // but emit only the above error about invalid number of arguments. for attribute in attributes .all() .filter(|attr| should_be_checked(attr) && attr.can_have_arguments()) { match attribute.expected_args() { ExpectedArgs::None => unreachable!("`attribute` can have arguments"), ExpectedArgs::Any => {} ExpectedArgs::MustBeIn(expected_args) => { for arg in attribute.args.iter() { if !expected_args.contains(&arg.name.as_str()) { handler.emit_err( ConvertParseTreeError::InvalidAttributeArg { attribute: attribute.name.clone(), arg: (&arg.name).into(), expected_args: expected_args.clone(), } .into(), ); } } } ExpectedArgs::ShouldBeIn(expected_args) => { for arg in attribute.args.iter() { if !expected_args.contains(&arg.name.as_str()) { handler.emit_warn(CompileWarning { span: arg.name.span(), warning_content: Warning::UnknownAttributeArg { attribute: attribute.name.clone(), arg: (&arg.name).into(), expected_args: expected_args.clone(), }, }); } } } } } // Check for expected argument values. // We use here the same logic for what to check, as in the above check // for expected arguments. for attribute in attributes .all() .filter(|attr| should_be_checked(attr) && attr.can_have_arguments()) { // In addition, if an argument **must** be in expected args but is not, // we will not be checking it, but only emit the error above. // But if it **should** be in expected args and is not, // we still impose on it the expectation coming from its attribute. fn check_value_expected(handler: &Handler, attribute: &Attribute, is_value_expected: bool) { for arg in attribute.args.iter() { if let ExpectedArgs::MustBeIn(expected_args) = attribute.expected_args() { if !expected_args.contains(&arg.name.as_str()) { continue; } } if (is_value_expected && arg.value.is_none()) || (!is_value_expected && arg.value.is_some()) { handler.emit_err( ConvertParseTreeError::InvalidAttributeArgExpectsValue { attribute: attribute.name.clone(), arg: (&arg.name).into(), value_span: arg.value.as_ref().map(|literal| literal.span()), } .into(), ); } } } match attribute.args_expect_values() { ArgsExpectValues::Yes => check_value_expected(&handler, attribute, true), ArgsExpectValues::No => check_value_expected(&handler, attribute, false), ArgsExpectValues::Maybe => {} } } (handler, attributes) } /// When no `BuildConfig` is given, we're assumed to be parsing in-memory with no submodules. fn parse_in_memory( handler: &Handler, engines: &Engines, src: Source, experimental: ExperimentalFeatures, dbg_generation: DbgGeneration, package_name: &str, ) -> Result<(lexed::LexedProgram, parsed::ParseProgram), ErrorEmitted> { let mut hasher = DefaultHasher::new(); src.text.hash(&mut hasher); let hash = hasher.finish(); let module = sway_parse::parse_file(handler, src, None, experimental)?; let (attributes_handler, attributes) = attr_decls_to_attributes( &module.attributes, |attr| attr.can_annotate_module_kind(), module.value.kind.friendly_name(), ); let attributes_error_emitted = handler.append(attributes_handler); let (kind, tree) = to_parsed_lang::convert_parse_tree( &mut to_parsed_lang::Context::new( BuildTarget::EVM, dbg_generation, experimental, package_name, ), handler, engines, module.value.clone(), )?; match attributes_error_emitted { Some(err) => Err(err), None => { let root = parsed::ParseModule { span: span::Span::dummy(), module_kind_span: module.value.kind.span(), module_eval_order: vec![], tree, submodules: vec![], attributes, hash, }; let lexed_program = lexed::LexedProgram::new( kind, lexed::LexedModule { tree: module, submodules: vec![], }, ); Ok((lexed_program, parsed::ParseProgram { kind, root })) } } } pub struct Submodule { name: Ident, path: Arc<PathBuf>, lexed: lexed::LexedSubmodule, parsed: parsed::ParseSubmodule, } /// Contains the lexed and parsed submodules 'deps' of a module. pub type Submodules = Vec<Submodule>; /// Parse all dependencies `deps` as submodules. #[allow(clippy::too_many_arguments)] fn parse_submodules( handler: &Handler, engines: &Engines, module_name: Option<&str>, module: &sway_ast::Module, module_dir: &Path, build_target: BuildTarget, dbg_generation: DbgGeneration, include_tests: bool, experimental: ExperimentalFeatures, lsp_mode: Option<&LspConfig>, package_name: &str, ) -> Submodules { // Assume the happy path, so there'll be as many submodules as dependencies, but no more. let mut submods = Vec::with_capacity(module.submodules().count()); module.submodules().for_each(|submod| { // Read the source code from the dependency. // If we cannot, record as an error, but continue with other files. let submod_path = Arc::new(module_path(module_dir, module_name, submod)); let submod_src: Source = match std::fs::read_to_string(&*submod_path) { Ok(s) => s.as_str().into(), Err(e) => { handler.emit_err(CompileError::FileCouldNotBeRead { span: submod.name.span(), file_path: submod_path.to_string_lossy().to_string(), stringified_error: e.to_string(), }); return; } }; if let Ok(ParsedModuleTree { tree_type: kind, lexed_module, parse_module, }) = parse_module_tree( handler, engines, submod_src.clone(), submod_path.clone(), Some(submod.name.as_str()), build_target, dbg_generation, include_tests, experimental, lsp_mode, package_name, ) { if !matches!(kind, parsed::TreeType::Library) { let source_id = engines.se().get_source_id(submod_path.as_ref()); let span = span::Span::new(submod_src, 0, 0, Some(source_id)).unwrap(); handler.emit_err(CompileError::ImportMustBeLibrary { span }); return; } let parse_submodule = parsed::ParseSubmodule { module: parse_module, visibility: match submod.visibility { Some(..) => Visibility::Public, None => Visibility::Private, }, mod_name_span: submod.name.span(), }; let lexed_submodule = lexed::LexedSubmodule { module: lexed_module, }; let submodule = Submodule { name: submod.name.clone(), path: submod_path, lexed: lexed_submodule, parsed: parse_submodule, }; submods.push(submodule); } }); submods } pub type SourceHash = u64; #[derive(Clone, Debug)] pub struct ParsedModuleTree { pub tree_type: parsed::TreeType, pub lexed_module: lexed::LexedModule, pub parse_module: parsed::ParseModule, } /// Given the source of the module along with its path, /// parse this module including all of its submodules. #[allow(clippy::too_many_arguments)] fn parse_module_tree( handler: &Handler, engines: &Engines, src: Source, path: Arc<PathBuf>, module_name: Option<&str>, build_target: BuildTarget, dbg_generation: DbgGeneration, include_tests: bool, experimental: ExperimentalFeatures, lsp_mode: Option<&LspConfig>, package_name: &str, ) -> Result<ParsedModuleTree, ErrorEmitted> { let query_engine = engines.qe(); // Parse this module first. let module_dir = path.parent().expect("module file has no parent directory"); let source_id = engines.se().get_source_id(&path.clone()); // don't use reloaded file if we already have it in memory, that way new spans will still point to the same string let src = engines.se().get_or_create_source_buffer(&source_id, src); let module = sway_parse::parse_file(handler, src.clone(), Some(source_id), experimental)?; // Parse all submodules before converting to the `ParseTree`. // This always recovers on parse errors for the file itself by skipping that file. let submodules = parse_submodules( handler, engines, module_name, &module.value, module_dir, build_target, dbg_generation, include_tests, experimental, lsp_mode, package_name, ); let (attributes_handler, attributes) = attr_decls_to_attributes( &module.attributes, |attr| attr.can_annotate_module_kind(), module.value.kind.friendly_name(), ); let attributes_error_emitted = handler.append(attributes_handler); // Convert from the raw parsed module to the `ParseTree` ready for type-check. let (kind, tree) = to_parsed_lang::convert_parse_tree( &mut to_parsed_lang::Context::new(build_target, dbg_generation, experimental, package_name), handler, engines, module.value.clone(), )?; if let Some(err) = attributes_error_emitted { return Err(err); } let module_kind_span = module.value.kind.span(); let lexed_submodules = submodules .iter() .map(|s| (s.name.clone(), s.lexed.clone())) .collect::<Vec<_>>(); let lexed = lexed::LexedModule { tree: module, submodules: lexed_submodules, }; let mut hasher = DefaultHasher::new(); src.text.hash(&mut hasher); let hash = hasher.finish(); let parsed_submodules = submodules .iter() .map(|s| (s.name.clone(), s.parsed.clone())) .collect::<Vec<_>>(); let parsed = parsed::ParseModule { span: span::Span::new(src, 0, 0, Some(source_id)).unwrap(), module_kind_span, module_eval_order: vec![], tree, submodules: parsed_submodules, attributes, hash, }; // Let's prime the cache with the module dependency and hash data. let modified_time = std::fs::metadata(path.as_path()) .ok() .and_then(|m| m.modified().ok()); let dependencies = submodules.into_iter().map(|s| s.path).collect::<Vec<_>>(); let version = lsp_mode .and_then(|lsp| lsp.file_versions.get(path.as_ref()).copied()) .unwrap_or(None); let common_info = ModuleCommonInfo { path: path.clone(), include_tests, dependencies, hash, }; let parsed_info = ParsedModuleInfo { modified_time, version, }; let cache_entry = ModuleCacheEntry::new(common_info, parsed_info); query_engine.update_or_insert_parsed_module_cache_entry(cache_entry); Ok(ParsedModuleTree { tree_type: kind, lexed_module: lexed, parse_module: parsed, }) } /// Checks if the typed module cache for a given path is up to date. /// /// This function determines whether the cached typed representation of a module /// is still valid based on file versions and dependencies. /// /// Note: This functionality is currently only supported when the compiler is /// initiated from the language server. pub(crate) fn is_ty_module_cache_up_to_date( engines: &Engines, path: &Arc<PathBuf>, include_tests: bool, build_config: Option<&BuildConfig>, ) -> bool { let cache = engines.qe().module_cache.read(); let key = ModuleCacheKey::new(path.clone(), include_tests); cache.get(&key).is_some_and(|entry| { entry.typed.as_ref().is_some_and(|typed| { // Check if the cache is up to date based on file versions let cache_up_to_date = build_config .and_then(|x| x.lsp_mode.as_ref()) .and_then(|lsp| lsp.file_versions.get(path.as_ref())) .is_none_or(|version| { version.is_none_or(|v| typed.version.is_some_and(|tv| v <= tv)) }); // If the cache is up to date, recursively check all dependencies cache_up_to_date && entry.common.dependencies.iter().all(|dep_path| { is_ty_module_cache_up_to_date(engines, dep_path, include_tests, build_config) }) }) }) } /// Checks if the parsed module cache for a given path is up to date. /// /// This function determines whether the cached parsed representation of a module /// is still valid based on file versions, modification times, or content hashes. pub(crate) fn is_parse_module_cache_up_to_date( engines: &Engines, path: &Arc<PathBuf>, include_tests: bool, build_config: Option<&BuildConfig>, ) -> bool { let cache = engines.qe().module_cache.read(); let key = ModuleCacheKey::new(path.clone(), include_tests); cache.get(&key).is_some_and(|entry| { // Determine if the cached dependency information is still valid let cache_up_to_date = build_config .and_then(|x| x.lsp_mode.as_ref()) .and_then(|lsp| lsp.file_versions.get(path.as_ref())) .map_or_else( || { // If LSP mode is not active or file version is unavailable, fall back to filesystem checks. let modified_time = std::fs::metadata(path.as_path()) .ok() .and_then(|m| m.modified().ok()); // Check if modification time matches, or if not, compare file content hash entry.parsed.modified_time == modified_time || { let src = std::fs::read_to_string(path.as_path()).unwrap(); let mut hasher = DefaultHasher::new(); src.hash(&mut hasher); hasher.finish() == entry.common.hash } }, |version| { // Determine if the parse cache is up-to-date in LSP mode: // - If there's no LSP file version (version is None), consider the cache up-to-date. // - If there is an LSP file version: // - If there's no cached version (entry.parsed.version is None), the cache is outdated. // - If there's a cached version, compare them: cache is up-to-date if the LSP file version // is not greater than the cached version. version.is_none_or(|v| entry.parsed.version.is_some_and(|ev| v <= ev)) }, ); // Checks if the typed module cache for a given path is up to date// If the cache is up to date, recursively check all dependencies to make sure they have not been // modified either. cache_up_to_date && entry.common.dependencies.iter().all(|dep_path| { is_parse_module_cache_up_to_date(engines, dep_path, include_tests, build_config) }) }) } fn module_path( parent_module_dir: &Path, parent_module_name: Option<&str>, submod: &sway_ast::Submodule, ) -> PathBuf { if let Some(parent_name) = parent_module_name { parent_module_dir .join(parent_name) .join(submod.name.to_string()) .with_extension(sway_types::constants::DEFAULT_FILE_EXTENSION) } else { // top level module parent_module_dir .join(submod.name.to_string()) .with_extension(sway_types::constants::DEFAULT_FILE_EXTENSION) } } pub fn build_module_dep_graph( handler: &Handler, parse_module: &mut parsed::ParseModule, ) -> Result<(), ErrorEmitted> { let module_dep_graph = ty::TyModule::build_dep_graph(handler, parse_module)?; parse_module.module_eval_order = module_dep_graph.compute_order(handler)?; for (_, submodule) in &mut parse_module.submodules { build_module_dep_graph(handler, &mut submodule.module)?; } Ok(()) } /// A possible occurrence of a `panic` expression that is located in code at [PanicOccurrence::loc]. /// /// Note that a single `panic` expression can have multiple [PanicOccurrence]s related to it. /// /// For example: /// - `panic "Some message.";` will have just a single occurrence, with `msg` containing the message. /// - `panic some_value_of_a_concrete_type;` will have just a single occurrence, with `log_id` containing the [LogId] of the concrete type. /// - `panic some_value_of_a_generic_type;` will have multiple occurrences, one with `log_id` for every monomorphized type. /// /// **Every [PanicOccurrence] has exactly one revert code assigned to it.** #[derive(Default, Debug, Clone, PartialEq, Eq, Hash)] pub struct PanicOccurrence { pub function: String, pub loc: SourceLocation, pub log_id: Option<LogId>, pub msg: Option<String>, } /// Represents a function call that could panic during execution. /// E.g., for the following code: /// /// ```ignore /// fn some_function() { /// let _ = this_function_might_panic(42); ///} /// ``` /// /// the `function` field will contain the name of the function that might panic: /// `function: "some_other_package::module::this_function_might_panic"` /// /// and the `loc` and `caller_function` fields will contain the source location of the call to the `function` /// that might panic: /// /// ```ignore /// caller_function: "some_package::some_module::some_function", /// pkg: "some_package@0.1.0", /// file: "src/some_module.sw", /// ... /// ``` /// /// Note that, in case of panicking function or caller function being /// generic functions, a single panicking call can have multiple /// [PanickingCallOccurrence]s related to it. /// /// For example: /// - `this_function_might_panic(42);` will have a single occurrence, /// with `function` containing the full name of the function that might panic. /// - `this_generic_function_might_panic::<u64>(42);` will have a single occurrence, /// with `function` containing the full name of the function that might panic, /// but with the generic type parameter `u64` included in the name. /// - `this_generic_function_might_panic::<T>(42);` will have multiple occurrences, /// one for every monomorphized type. /// /// Similar is for a generic caller function. /// /// **Every [PanickingCallOccurrence] has exactly one panicking call code assigned to it.** #[derive(Default, Debug, Clone, PartialEq, Eq, Hash)] pub struct PanickingCallOccurrence { pub function: String, pub caller_function: String, pub loc: SourceLocation, } /// [PanicOccurrence]s mapped to their corresponding panic error codes. pub type PanicOccurrences = HashMap<PanicOccurrence, u64>; /// [PanickingCallOccurrence]s mapped to their corresponding panicking call codes. pub type PanickingCallOccurrences = HashMap<PanickingCallOccurrence, u64>; pub struct CompiledAsm { pub finalized_asm: FinalizedAsm, pub panic_occurrences: PanicOccurrences, pub panicking_call_occurrences: PanickingCallOccurrences, } #[allow(clippy::result_large_err)] #[allow(clippy::too_many_arguments)] pub fn parsed_to_ast( handler: &Handler, engines: &Engines, parse_program: &mut parsed::ParseProgram, initial_namespace: namespace::Package, build_config: Option<&BuildConfig>, package_name: &str, retrigger_compilation: Option<Arc<AtomicBool>>, experimental: ExperimentalFeatures, backtrace: Backtrace, ) -> Result<ty::TyProgram, TypeCheckFailed> {
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/concurrent_slab.rs
sway-core/src/concurrent_slab.rs
use parking_lot::RwLock; use std::{fmt, sync::Arc}; #[derive(Debug, Clone)] pub struct Inner<T> { pub items: Vec<Option<Arc<T>>>, pub free_list: Vec<usize>, } impl<T> Default for Inner<T> { fn default() -> Self { Self { items: Default::default(), free_list: Default::default(), } } } #[derive(Debug)] pub(crate) struct ConcurrentSlab<T> { pub inner: RwLock<Inner<T>>, } impl<T> Clone for ConcurrentSlab<T> where T: Clone, { fn clone(&self) -> Self { let inner = self.inner.read(); Self { inner: RwLock::new(inner.clone()), } } } impl<T> Default for ConcurrentSlab<T> { fn default() -> Self { Self { inner: Default::default(), } } } pub struct ListDisplay<I> { pub list: I, } impl<I: IntoIterator + Clone> fmt::Display for ListDisplay<I> where I::Item: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let fmt_elems = self .list .clone() .into_iter() .enumerate() .map(|(i, value)| format!("{i:<10}\t->\t{value}")) .collect::<Vec<_>>(); write!(f, "{}", fmt_elems.join("\n")) } } impl<T> ConcurrentSlab<T> where T: Clone, { #[allow(dead_code)] pub fn len(&self) -> usize { let inner = self.inner.read(); inner.items.len() } pub fn values(&self) -> Vec<Arc<T>> { let inner = self.inner.read(); inner.items.iter().filter_map(|x| x.clone()).collect() } pub fn insert(&self, value: T) -> usize { self.insert_arc(Arc::new(value)) } pub fn insert_arc(&self, value: Arc<T>) -> usize { let mut inner = self.inner.write(); if let Some(free) = inner.free_list.pop() { assert!(inner.items[free].is_none()); inner.items[free] = Some(value); free } else { inner.items.push(Some(value)); inner.items.len() - 1 } } pub fn replace(&self, index: usize, new_value: T) -> Option<T> { let mut inner = self.inner.write(); let item = inner.items.get_mut(index)?; let old = item.replace(Arc::new(new_value))?; Arc::into_inner(old) } pub fn replace_arc(&self, index: usize, new_value: Arc<T>) -> Option<T> { let mut inner = self.inner.write(); let item = inner.items.get_mut(index)?; let old = item.replace(new_value)?; Arc::into_inner(old) } pub fn get(&self, index: usize) -> Arc<T> { let inner = self.inner.read(); inner.items[index] .as_ref() .expect("invalid slab index for ConcurrentSlab::get") .clone() } /// Improve performance by avoiding `Arc::clone`. /// The slab is kept locked while running `f`. pub fn map<R>(&self, index: usize, f: impl FnOnce(&T) -> R) -> R { let inner = self.inner.read(); f(inner.items[index] .as_ref() .expect("invalid slab index for ConcurrentSlab::get")) } pub fn retain(&self, predicate: impl Fn(&usize, &mut Arc<T>) -> bool) { let mut inner = self.inner.write(); let Inner { items, free_list } = &mut *inner; for (idx, item) in items.iter_mut().enumerate() { if let Some(arc) = item { if !predicate(&idx, arc) { free_list.push(idx); item.take(); } } } } pub fn clear(&self) { let mut inner = self.inner.write(); inner.items.clear(); inner.items.shrink_to(0); inner.free_list.clear(); inner.free_list.shrink_to(0); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis.rs
sway-core/src/semantic_analysis.rs
//! Type checking for Sway. pub mod ast_node; pub(crate) mod cei_pattern_analysis; pub(crate) mod coins_analysis; mod method_lookup; mod module; pub mod namespace; mod node_dependencies; pub mod program; pub mod symbol_collection_context; pub mod symbol_resolve; pub mod symbol_resolve_context; mod type_check_analysis; pub(crate) mod type_check_context; mod type_check_finalization; pub(crate) mod type_resolve; pub use ast_node::*; pub use namespace::Namespace; pub(crate) use type_check_analysis::*; pub use type_check_context::TypeCheckContext; pub(crate) use type_check_finalization::*;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/build_config.rs
sway-core/src/build_config.rs
use itertools::Itertools; use serde::{Deserialize, Deserializer, Serialize}; use std::{ collections::{BTreeMap, HashSet}, path::PathBuf, sync::Arc, }; use strum::{Display, EnumString}; use sway_ir::{PassManager, PrintPassesOpts, VerifyPassesOpts}; #[derive( Clone, Copy, Debug, Display, Default, Eq, PartialEq, Hash, Serialize, Deserialize, clap::ValueEnum, EnumString, )] pub enum BuildTarget { #[default] #[serde(rename = "fuel")] #[clap(name = "fuel")] #[strum(serialize = "fuel")] Fuel, #[serde(rename = "evm")] #[clap(name = "evm")] #[strum(serialize = "evm")] EVM, } impl BuildTarget { pub const CFG: &'static [&'static str] = &["evm", "fuel"]; } #[derive(Default, Clone, Copy)] pub enum DbgGeneration { Full, #[default] None, } #[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)] pub enum OptLevel { #[default] Opt0 = 0, Opt1 = 1, } impl<'de> serde::Deserialize<'de> for OptLevel { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let num = u8::deserialize(d)?; match num { 0 => Ok(OptLevel::Opt0), 1 => Ok(OptLevel::Opt1), _ => Err(serde::de::Error::custom(format!("invalid opt level {num}"))), } } } /// Which ASM to print. #[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct PrintAsm { #[serde(rename = "virtual")] pub virtual_abstract: bool, #[serde(rename = "allocated")] pub allocated_abstract: bool, pub r#final: bool, } impl PrintAsm { pub fn all() -> Self { Self { virtual_abstract: true, allocated_abstract: true, r#final: true, } } pub fn none() -> Self { Self::default() } pub fn abstract_virtual() -> Self { Self { virtual_abstract: true, ..Self::default() } } pub fn abstract_allocated() -> Self { Self { allocated_abstract: true, ..Self::default() } } pub fn r#final() -> Self { Self { r#final: true, ..Self::default() } } } impl std::ops::BitOrAssign for PrintAsm { fn bitor_assign(&mut self, rhs: Self) { self.virtual_abstract |= rhs.virtual_abstract; self.allocated_abstract |= rhs.allocated_abstract; self.r#final |= rhs.r#final; } } /// Which IR states to print. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct IrCli { pub initial: bool, pub r#final: bool, #[serde(rename = "modified")] pub modified_only: bool, pub passes: Vec<String>, } impl Default for IrCli { fn default() -> Self { Self { initial: false, r#final: false, modified_only: true, // Default option is more restrictive. passes: vec![], } } } impl IrCli { pub fn all(modified_only: bool) -> Self { Self { initial: true, r#final: true, modified_only, passes: PassManager::OPTIMIZATION_PASSES .iter() .map(|pass| pass.to_string()) .collect_vec(), } } pub fn none() -> Self { Self::default() } pub fn r#final() -> Self { Self { r#final: true, ..Self::default() } } } impl std::ops::BitOrAssign for IrCli { fn bitor_assign(&mut self, rhs: Self) { self.initial |= rhs.initial; self.r#final |= rhs.r#final; // Both sides must request only passes that modify IR // in order for `modified_only` to be true. // Otherwise, displaying passes regardless if they // are modified or not wins. self.modified_only &= rhs.modified_only; for pass in rhs.passes { if !self.passes.contains(&pass) { self.passes.push(pass); } } } } impl From<&IrCli> for PrintPassesOpts { fn from(value: &IrCli) -> Self { Self { initial: value.initial, r#final: value.r#final, modified_only: value.modified_only, passes: HashSet::from_iter(value.passes.iter().cloned()), } } } impl From<&IrCli> for VerifyPassesOpts { fn from(value: &IrCli) -> Self { Self { initial: value.initial, r#final: value.r#final, modified_only: value.modified_only, passes: HashSet::from_iter(value.passes.iter().cloned()), } } } #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)] #[serde(rename_all = "snake_case")] pub enum Backtrace { All, #[default] AllExceptNever, OnlyAlways, None, } impl From<Backtrace> for sway_ir::Backtrace { fn from(value: Backtrace) -> Self { match value { Backtrace::All => sway_ir::Backtrace::All, Backtrace::AllExceptNever => sway_ir::Backtrace::AllExceptNever, Backtrace::OnlyAlways => sway_ir::Backtrace::OnlyAlways, Backtrace::None => sway_ir::Backtrace::None, } } } /// Configuration for the overall build and compilation process. #[derive(Clone)] pub struct BuildConfig { // Build target for code generation. pub(crate) build_target: BuildTarget, pub(crate) dbg_generation: DbgGeneration, // The canonical file path to the root module. // E.g. `/home/user/project/src/main.sw`. pub(crate) canonical_root_module: Arc<PathBuf>, pub(crate) print_dca_graph: Option<String>, pub(crate) print_dca_graph_url_format: Option<String>, pub(crate) print_asm: PrintAsm, pub(crate) print_bytecode: bool, pub(crate) print_bytecode_spans: bool, pub(crate) print_ir: IrCli, pub(crate) verify_ir: IrCli, pub(crate) include_tests: bool, pub(crate) optimization_level: OptLevel, pub(crate) backtrace: Backtrace, pub time_phases: bool, pub profile: bool, pub metrics_outfile: Option<String>, pub lsp_mode: Option<LspConfig>, } impl BuildConfig { /// Construct a `BuildConfig` from a relative path to the root module and the canonical path to /// the manifest directory. /// /// The `root_module` path must be either canonical, or relative to the directory containing /// the manifest. E.g. `project/src/main.sw` or `project/src/lib.sw`. /// /// The `canonical_manifest_dir` must be the canonical (aka absolute) path to the directory /// containing the `Forc.toml` file for the project. E.g. `/home/user/project`. pub fn root_from_file_name_and_manifest_path( root_module: PathBuf, canonical_manifest_dir: PathBuf, build_target: BuildTarget, dbg_generation: DbgGeneration, ) -> Self { assert!( canonical_manifest_dir.has_root(), "manifest dir must be a canonical path", ); let canonical_root_module = match root_module.has_root() { true => root_module, false => { assert!( root_module.starts_with(canonical_manifest_dir.file_name().unwrap()), "file_name must be either absolute or relative to manifest directory", ); canonical_manifest_dir .parent() .expect("unable to retrieve manifest directory parent") .join(&root_module) } }; Self { build_target, dbg_generation, canonical_root_module: Arc::new(canonical_root_module), print_dca_graph: None, print_dca_graph_url_format: None, print_asm: PrintAsm::default(), print_bytecode: false, print_bytecode_spans: false, print_ir: IrCli::default(), verify_ir: IrCli::default(), include_tests: false, time_phases: false, profile: false, metrics_outfile: None, optimization_level: OptLevel::default(), backtrace: Backtrace::default(), lsp_mode: None, } } /// Dummy build config that can be used for testing. /// This is not valid generally, but asm generation will accept it. pub fn dummy_for_asm_generation() -> Self { Self::root_from_file_name_and_manifest_path( PathBuf::from("/"), PathBuf::from("/"), BuildTarget::default(), DbgGeneration::None, ) } pub fn with_print_dca_graph(self, a: Option<String>) -> Self { Self { print_dca_graph: a, ..self } } pub fn with_print_dca_graph_url_format(self, a: Option<String>) -> Self { Self { print_dca_graph_url_format: a, ..self } } pub fn with_print_asm(self, print_asm: PrintAsm) -> Self { Self { print_asm, ..self } } pub fn with_print_bytecode(self, bytecode: bool, bytecode_spans: bool) -> Self { Self { print_bytecode: bytecode, print_bytecode_spans: bytecode_spans, ..self } } pub fn with_print_ir(self, a: IrCli) -> Self { Self { print_ir: a, ..self } } pub fn with_verify_ir(self, a: IrCli) -> Self { Self { verify_ir: a, ..self } } pub fn with_time_phases(self, a: bool) -> Self { Self { time_phases: a, ..self } } pub fn with_profile(self, a: bool) -> Self { Self { profile: a, ..self } } pub fn with_metrics(self, a: Option<String>) -> Self { Self { metrics_outfile: a, ..self } } pub fn with_optimization_level(self, optimization_level: OptLevel) -> Self { Self { optimization_level, ..self } } pub fn with_backtrace(self, backtrace: Backtrace) -> Self { Self { backtrace, ..self } } /// Whether or not to include test functions in parsing, type-checking and codegen. /// /// This should be set to `true` by invocations like `forc test` or `forc check --tests`. /// /// Default: `false` pub fn with_include_tests(self, include_tests: bool) -> Self { Self { include_tests, ..self } } pub fn with_lsp_mode(self, lsp_mode: Option<LspConfig>) -> Self { Self { lsp_mode, ..self } } pub fn canonical_root_module(&self) -> Arc<PathBuf> { self.canonical_root_module.clone() } } #[derive(Clone, Debug, Default)] pub struct LspConfig { // This is set to true if compilation was triggered by a didChange LSP event. In this case, we // bypass collecting type metadata and skip DCA. // // This is set to false if compilation was triggered by a didSave or didOpen LSP event. pub optimized_build: bool, // The value of the `version` field in the `DidChangeTextDocumentParams` struct. // This is used to determine if the file has been modified since the last compilation. pub file_versions: BTreeMap<PathBuf, Option<u64>>, } #[cfg(test)] mod test { use super::*; #[test] fn test_root_from_file_name_and_manifest_path() { let root_module = PathBuf::from("mock_path/src/main.sw"); let canonical_manifest_dir = PathBuf::from("/tmp/sway_project/mock_path"); BuildConfig::root_from_file_name_and_manifest_path( root_module, canonical_manifest_dir, BuildTarget::default(), DbgGeneration::Full, ); } #[test] fn test_root_from_file_name_and_manifest_path_contains_dot() { let root_module = PathBuf::from("mock_path_contains_._dot/src/main.sw"); let canonical_manifest_dir = PathBuf::from("/tmp/sway_project/mock_path_contains_._dot"); BuildConfig::root_from_file_name_and_manifest_path( root_module, canonical_manifest_dir, BuildTarget::default(), DbgGeneration::Full, ); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/engine_threading.rs
sway-core/src/engine_threading.rs
use crate::{ decl_engine::{parsed_engine::ParsedDeclEngine, DeclEngine}, language::CallPath, query_engine::QueryEngine, type_system::TypeEngine, ObservabilityEngine, }; use std::{ cmp::Ordering, fmt, hash::{BuildHasher, Hash, Hasher}, sync::Arc, }; use sway_types::{SourceEngine, Span}; #[derive(Clone, Debug, Default)] pub struct Engines { type_engine: TypeEngine, decl_engine: DeclEngine, parsed_decl_engine: ParsedDeclEngine, query_engine: QueryEngine, source_engine: SourceEngine, obs_engine: Arc<ObservabilityEngine>, } impl Engines { pub fn te(&self) -> &TypeEngine { &self.type_engine } pub fn de(&self) -> &DeclEngine { &self.decl_engine } pub fn pe(&self) -> &ParsedDeclEngine { &self.parsed_decl_engine } pub fn qe(&self) -> &QueryEngine { &self.query_engine } pub fn se(&self) -> &SourceEngine { &self.source_engine } pub fn obs(&self) -> &ObservabilityEngine { &self.obs_engine } /// Removes all data associated with `program_id` from the engines. /// It is intended to be used during garbage collection to remove any data that is no longer needed. pub fn clear_program(&mut self, program_id: &sway_types::ProgramId) { self.type_engine.clear_program(program_id); self.decl_engine.clear_program(program_id); self.parsed_decl_engine.clear_program(program_id); self.query_engine.clear_program(program_id); } /// Removes all data associated with `source_id` from the engines. /// It is intended to be used during garbage collection to remove any data that is no longer needed. /// /// It will also clear the associated autogenerated file for the `source_id` parameter. pub fn clear_module(&mut self, source_id: &sway_types::SourceId) { self.type_engine.clear_module(source_id); self.decl_engine.clear_module(source_id); self.parsed_decl_engine.clear_module(source_id); self.query_engine.clear_module(source_id); // Check if `source_id` has an associated autogenerated file // and clear it if let Some(autogenerated_source_id) = self.se().get_associated_autogenerated_source_id(source_id) { if autogenerated_source_id == *source_id { return; } self.type_engine.clear_module(&autogenerated_source_id); self.decl_engine.clear_module(&autogenerated_source_id); self.parsed_decl_engine .clear_module(&autogenerated_source_id); self.query_engine.clear_module(&autogenerated_source_id); } } /// Helps out some `thing: T` by adding `self` as context. pub fn help_out<T>(&self, thing: T) -> WithEngines<'_, T> { WithEngines { thing, engines: self, } } } #[derive(Clone, Copy)] pub struct WithEngines<'a, T> { pub thing: T, pub engines: &'a Engines, } impl<'a, T> WithEngines<'a, T> { pub fn new(thing: T, engines: &'a Engines) -> Self { WithEngines { thing, engines } } } /// Displays the user-friendly formatted view of `thing` using `engines` as context. impl<T: DisplayWithEngines> fmt::Display for WithEngines<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.thing.fmt(f, self.engines) } } /// Displays the internals of `thing` using `engines` as context. Useful for debugging. impl<T: DebugWithEngines> fmt::Debug for WithEngines<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.thing.fmt(f, self.engines) } } impl<T: HashWithEngines> Hash for WithEngines<'_, T> { fn hash<H: Hasher>(&self, state: &mut H) { self.thing.hash(state, self.engines) } } impl<T: PartialEqWithEngines> PartialEq for WithEngines<'_, T> { fn eq(&self, rhs: &Self) -> bool { self.thing .eq(&rhs.thing, &PartialEqWithEnginesContext::new(self.engines)) } } impl<T: EqWithEngines> Eq for WithEngines<'_, T> {} impl<T: OrdWithEngines> PartialOrd for WithEngines<'_, T> where T: PartialEqWithEngines, { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some( self.thing .cmp(&other.thing, &OrdWithEnginesContext::new(self.engines)), ) } } impl<T: OrdWithEngines> Ord for WithEngines<'_, T> where T: EqWithEngines, { fn cmp(&self, other: &Self) -> Ordering { self.thing .cmp(&other.thing, &OrdWithEnginesContext::new(self.engines)) } } pub(crate) trait DisplayWithEngines { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result; } impl<T: DisplayWithEngines> DisplayWithEngines for &T { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { (*self).fmt(f, engines) } } impl<T: DisplayWithEngines> DisplayWithEngines for Option<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { match self { None => Ok(()), Some(x) => x.fmt(f, engines), } } } impl<T: DisplayWithEngines> DisplayWithEngines for Box<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { (**self).fmt(f, engines) } } impl<T: DisplayWithEngines> DisplayWithEngines for Vec<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { let text = self .iter() .map(|e| format!("{}", engines.help_out(e))) .collect::<Vec<_>>() .join(", ") .to_string(); f.write_str(&text) } } impl DisplayWithEngines for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { let file = self .source_id() .and_then(|id| engines.source_engine.get_file_name(id)); f.write_fmt(format_args!( "Span {{ {:?}, {} }}", file, self.line_col_one_index() )) } } pub(crate) trait DebugWithEngines { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result; } impl<T: DebugWithEngines> DebugWithEngines for &T { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { (*self).fmt(f, engines) } } impl<T: DebugWithEngines> DebugWithEngines for std::sync::Arc<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { (**self).fmt(f, engines) } } impl<T: DebugWithEngines> DebugWithEngines for Option<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { match self { None => Ok(()), Some(x) => x.fmt(f, engines), } } } impl<T: DebugWithEngines> DebugWithEngines for Box<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { (**self).fmt(f, engines) } } impl<T: DebugWithEngines> DebugWithEngines for Vec<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { let text = self .iter() .map(|e| format!("{:?}", engines.help_out(e))) .collect::<Vec<_>>() .join(", ") .to_string(); f.write_str(&text) } } impl DebugWithEngines for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { DisplayWithEngines::fmt(self, f, engines) } } pub trait HashWithEngines { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines); } impl<T: HashWithEngines + ?Sized> HashWithEngines for &T { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { (*self).hash(state, engines) } } impl<T: HashWithEngines> HashWithEngines for Option<T> { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { match self { None => state.write_u8(0), Some(x) => x.hash(state, engines), } } } impl<T: HashWithEngines> HashWithEngines for [T] { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { for x in self { x.hash(state, engines) } } } impl<T: HashWithEngines> HashWithEngines for Box<T> { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { (**self).hash(state, engines) } } impl<T: HashWithEngines> HashWithEngines for Arc<T> { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { (**self).hash(state, engines) } } pub trait EqWithEngines: PartialEqWithEngines {} pub struct PartialEqWithEnginesContext<'a> { engines: &'a Engines, is_inside_trait_constraint: bool, } impl<'a> PartialEqWithEnginesContext<'a> { pub(crate) fn new(engines: &'a Engines) -> Self { Self { engines, is_inside_trait_constraint: false, } } pub(crate) fn with_is_inside_trait_constraint(&self) -> Self { Self { is_inside_trait_constraint: true, ..*self } } pub(crate) fn engines(&self) -> &Engines { self.engines } pub(crate) fn is_inside_trait_constraint(&self) -> bool { self.is_inside_trait_constraint } } pub trait PartialEqWithEngines { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool; } pub struct OrdWithEnginesContext<'a> { engines: &'a Engines, is_inside_trait_constraint: bool, } impl<'a> OrdWithEnginesContext<'a> { pub(crate) fn new(engines: &'a Engines) -> Self { Self { engines, is_inside_trait_constraint: false, } } pub(crate) fn with_is_inside_trait_constraint(&self) -> Self { Self { is_inside_trait_constraint: true, ..*self } } pub(crate) fn engines(&self) -> &Engines { self.engines } pub(crate) fn is_inside_trait_constraint(&self) -> bool { self.is_inside_trait_constraint } } pub trait OrdWithEngines { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering; } impl<T: EqWithEngines + ?Sized> EqWithEngines for &T {} impl<T: PartialEqWithEngines + ?Sized> PartialEqWithEngines for &T { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { (*self).eq(*other, ctx) } } impl<T: OrdWithEngines + ?Sized> OrdWithEngines for &T { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { (*self).cmp(*other, ctx) } } impl<T: OrdWithEngines> OrdWithEngines for Option<T> { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { match (self, other) { (Some(x), Some(y)) => x.cmp(y, ctx), (Some(_), None) => Ordering::Less, (None, Some(_)) => Ordering::Greater, (None, None) => Ordering::Equal, } } } impl<T: OrdWithEngines> OrdWithEngines for Box<T> { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { (**self).cmp(&(**other), ctx) } } impl<T: EqWithEngines> EqWithEngines for Option<T> {} impl<T: PartialEqWithEngines> PartialEqWithEngines for Option<T> { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { match (self, other) { (None, None) => true, (Some(x), Some(y)) => x.eq(y, ctx), _ => false, } } } impl<T: EqWithEngines> EqWithEngines for Box<T> {} impl<T: PartialEqWithEngines> PartialEqWithEngines for Box<T> { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { (**self).eq(&(**other), ctx) } } impl<T: EqWithEngines> EqWithEngines for [T] {} impl<T: PartialEqWithEngines> PartialEqWithEngines for [T] { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.len() == other.len() && self.iter().zip(other.iter()).all(|(x, y)| x.eq(y, ctx)) } } impl<T: OrdWithEngines> OrdWithEngines for [T] { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { let len_cmp = self.len().cmp(&other.len()); if len_cmp != Ordering::Equal { return len_cmp; } for (a, b) in self.iter().zip(other.iter()) { let cmp = a.cmp(b, ctx); if cmp != Ordering::Equal { return cmp; } } Ordering::Equal } } pub(crate) fn make_hasher<'a: 'b, 'b, K>( hash_builder: &'a impl BuildHasher, engines: &'b Engines, ) -> impl Fn(&K) -> u64 + 'b where K: HashWithEngines + ?Sized, { move |key: &K| { let mut state = hash_builder.build_hasher(); key.hash(&mut state, engines); state.finish() } } pub trait SpannedWithEngines { fn span(&self, engines: &Engines) -> Span; } pub trait GetCallPathWithEngines { fn call_path(&self, engines: &Engines) -> Option<CallPath>; }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/compiler_generated.rs
sway-core/src/compiler_generated.rs
//! This module encapsulates generation of various elements generated internally by the compiler, //! e.g., unique names of variables in desugared code and similar. //! It also provides functions for inspecting such generated elements. /// The prefix for the compiler generated names of tuples. const TUPLE_VAR_NAME_PREFIX: &str = "__tuple_"; pub(crate) fn generate_tuple_var_name(suffix: usize) -> String { format!("{TUPLE_VAR_NAME_PREFIX}{suffix}") } pub fn is_generated_tuple_var_name(name: &str) -> bool { name.starts_with(TUPLE_VAR_NAME_PREFIX) } /// The prefix for the compiler generated names of structs used in destructuring /// structs in `let` statements. const DESTRUCTURED_STRUCT_VAR_NAME_PREFIX: &str = "__destructured_struct_"; pub(crate) fn generate_destructured_struct_var_name(suffix: usize) -> String { format!("{DESTRUCTURED_STRUCT_VAR_NAME_PREFIX}{suffix}") } pub fn is_generated_destructured_struct_var_name(name: &str) -> bool { name.starts_with(DESTRUCTURED_STRUCT_VAR_NAME_PREFIX) } /// The prefix for the compiler generated names of /// variables that store values matched in match expressions. const MATCHED_VALUE_VAR_NAME_PREFIX: &str = "__matched_value_"; pub(crate) fn generate_matched_value_var_name(suffix: usize) -> String { format!("{MATCHED_VALUE_VAR_NAME_PREFIX}{suffix}") } /// The prefix for the compiler generated names of /// variables that store 1-based index of the OR match /// alternative that gets matched, or zero if non of the /// OR alternatives get matched. const MATCHED_OR_VARIANT_INDEX_VAR_NAME_PREFIX: &str = "__matched_or_variant_index_"; pub(crate) fn generate_matched_or_variant_index_var_name(suffix: usize) -> String { format!("{MATCHED_OR_VARIANT_INDEX_VAR_NAME_PREFIX}{suffix}") } /// The prefix for the compiler generated names of /// tuple variables that store values of the variables declared /// in OR match alternatives. const MATCHED_OR_VARIANT_VARIABLES_VAR_NAME_PREFIX: &str = "__matched_or_variant_variables_"; pub(crate) fn generate_matched_or_variant_variables_var_name(suffix: usize) -> String { format!("{MATCHED_OR_VARIANT_VARIABLES_VAR_NAME_PREFIX}{suffix}") } pub fn is_generated_any_match_expression_var_name(name: &str) -> bool { name.starts_with(MATCHED_VALUE_VAR_NAME_PREFIX) || name.starts_with(MATCHED_OR_VARIANT_INDEX_VAR_NAME_PREFIX) || name.starts_with(MATCHED_OR_VARIANT_VARIABLES_VAR_NAME_PREFIX) } /// A revert with this value signals that it was caused by an internal compiler error that /// occurred during the flattening of match arms that contain variables in OR match patterns. /// /// The value is: 14757395258967588865 pub(crate) const INVALID_MATCHED_OR_VARIABLE_INDEX_SIGNAL: u64 = 0xcccc_cccc_cccc_0001; /// A revert with this value signals that it was caused by an internal compiler error that /// occurred during the flattening of match arms that contain variables in OR match patterns. /// /// The value is: 14757395258967588866 pub(crate) const INVALID_DESUGARED_MATCHED_EXPRESSION_SIGNAL: u64 = 0xcccc_cccc_cccc_0002;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/error.rs
sway-core/src/error.rs
//! Tools related to handling/recovering from Sway compile errors and reporting them to the user. use crate::{language::parsed::VariableDeclaration, namespace::ModulePath, Engines, Namespace}; /// Acts as the result of parsing `Declaration`s, `Expression`s, etc. /// Some `Expression`s need to be able to create `VariableDeclaration`s, /// so this struct is used to "bubble up" those declarations to a viable /// place in the AST. #[derive(Debug, Clone)] pub struct ParserLifter<T> { pub var_decls: Vec<VariableDeclaration>, pub value: T, } impl<T> ParserLifter<T> { #[allow(dead_code)] pub(crate) fn empty(value: T) -> Self { ParserLifter { var_decls: vec![], value, } } } /// When providing suggestions for errors and warnings, a solution for an issue can sometimes /// be changing the code in some other module. We want to provide such suggestions only if /// the programmer can actually change the code in that module. /// /// Assuming that the issue occurs in the `issue_namespace` to which the programmer has access, /// and that fixing it means changing the code in the module given by the `absolute_module_path` /// this function returns true if the programmer can change that module. pub(crate) fn module_can_be_changed( _engines: &Engines, issue_namespace: &Namespace, absolute_module_path: &ModulePath, ) -> bool { // For now, we assume that the programmers can change the module // if the module is in the same package where the issue is. // A bit too restrictive, considering the same workspace might be more appropriate, // but it's a good start. !issue_namespace.module_is_external(absolute_module_path) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/marker_traits.rs
sway-core/src/marker_traits.rs
use sway_types::{Ident, SourceEngine}; use crate::{ language::{parsed::ImplSelfOrTrait, ty::TyTraitDecl, CallPathType}, namespace::{Module, TraitEntry}, }; impl TyTraitDecl { pub(crate) fn is_marker_trait(&self) -> bool { assert!( matches!(self.call_path.callpath_type, CallPathType::Full), "call paths of trait declarations must always be full paths" ); is_std_marker_module_path(&self.call_path.prefixes) } } impl Module { pub(crate) fn is_std_marker_module(&self) -> bool { is_std_marker_module_path(self.mod_path()) } } impl ImplSelfOrTrait { pub(crate) fn is_autogenerated(&self, source_engine: &SourceEngine) -> bool { source_engine .is_span_in_autogenerated(&self.block_span) .unwrap_or(false) } } impl TraitEntry { pub(crate) fn is_std_marker_error_trait(&self) -> bool { let trait_call_path = &*self.key.name; trait_call_path.callpath_type == CallPathType::Full && trait_call_path.prefixes.len() == 2 && trait_call_path.prefixes[0].as_str() == "std" && trait_call_path.prefixes[1].as_str() == "marker" && trait_call_path.suffix.name.as_str() == "Error" } } fn is_std_marker_module_path(path: &[Ident]) -> bool { path.len() == 2 && path[0].as_str() == "std" && path[1].as_str() == "marker" }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/metadata.rs
sway-core/src/metadata.rs
use crate::{ decl_engine::DeclId, language::{ty::TyFunctionDecl, CallPath, Inline, Purity, Trace}, }; use sway_ir::{Context, MetadataIndex, Metadatum, Value}; use sway_types::{span::Source, Ident, SourceId, Span, Spanned}; use std::{collections::HashMap, path::PathBuf, sync::Arc}; /// IR metadata needs to be consistent between IR generation (converting [Span]s, etc. to metadata) /// and ASM generation (converting the metadata back again). Here we consolidate all of /// `sway-core`s metadata needs into a single place to enable that consistency. /// /// The [MetadataManager] also does its best to reduce redundancy by caching certain common /// elements, such as source paths and storage attributes, and to avoid recreating the same /// indices repeatedly. #[derive(Default)] pub(crate) struct MetadataManager { // We want to be able to store more than one `Span` per `MetadataIndex`. // E.g., storing the span of the function name, and the whole function declaration. // The spans differ then by the tag property of their `Metadatum::Struct`. // We could cache all such spans in a single `HashMap` where the key would be `(Span, tag)`. // But since the vast majority of stored spans will be tagged with the generic "span" tag, // and only a few elements will have additional spans in their `MetadataIndex`, it is // more efficient to provide two separate caches, one for the spans tagged with "span", // and one for all other spans, tagged with arbitrary tags. /// Holds [Span]s tagged with "span". md_span_cache: HashMap<MetadataIndex, Span>, /// Holds [Span]s tagged with an arbitrary tag. md_tagged_span_cache: HashMap<MetadataIndex, (Span, &'static str)>, md_file_loc_cache: HashMap<MetadataIndex, (Arc<PathBuf>, Source)>, md_purity_cache: HashMap<MetadataIndex, Purity>, md_inline_cache: HashMap<MetadataIndex, Inline>, md_trace_cache: HashMap<MetadataIndex, Trace>, md_test_decl_index_cache: HashMap<MetadataIndex, DeclId<TyFunctionDecl>>, span_md_cache: HashMap<Span, MetadataIndex>, tagged_span_md_cache: HashMap<(Span, &'static str), MetadataIndex>, file_loc_md_cache: HashMap<SourceId, MetadataIndex>, purity_md_cache: HashMap<Purity, MetadataIndex>, inline_md_cache: HashMap<Inline, MetadataIndex>, trace_md_cache: HashMap<Trace, MetadataIndex>, test_decl_index_md_cache: HashMap<DeclId<TyFunctionDecl>, MetadataIndex>, } impl MetadataManager { pub(crate) fn md_to_span( &mut self, context: &Context, md_idx: Option<MetadataIndex>, ) -> Option<Span> { Self::for_each_md_idx(context, md_idx, |md_idx| { self.md_span_cache.get(&md_idx).cloned().or_else(|| { md_idx .get_content(context) .unwrap_struct("span", 3) .and_then(|fields| { // Create a new span and save it in the cache. let span = self.create_span_from_metadatum_fields(context, fields)?; self.md_span_cache.insert(md_idx, span.clone()); Some(span) }) }) }) } /// Returns the [Span] tagged with `tag` from the `md_idx`, /// or `None` if such span does not exist. /// If there are more spans tagged with `tag` inside of the /// `md_idx`, the first one will be returned. pub(crate) fn md_to_tagged_span( &mut self, context: &Context, md_idx: Option<MetadataIndex>, tag: &'static str, ) -> Option<Span> { Self::for_each_md_idx(context, md_idx, |md_idx| { let fields = md_idx.get_content(context).unwrap_struct(tag, 3); match fields { Some(fields) => self .md_tagged_span_cache .get(&md_idx) .map(|span_and_tag| span_and_tag.0.clone()) .or_else(|| { // Create a new span and save it in the cache. let span = self.create_span_from_metadatum_fields(context, fields)?; self.md_tagged_span_cache .insert(md_idx, (span.clone(), tag)); Some(span) }), None => None, } }) } /// Returns the [Span] pointing to the function name in the function declaration from the `md_idx`, /// or `None` if such span does not exist. pub(crate) fn md_to_fn_name_span( &mut self, context: &Context, md_idx: Option<MetadataIndex>, ) -> Option<Span> { self.md_to_tagged_span(context, md_idx, "fn_name_span") } /// Returns the [Span] pointing to the call path in the function call from the `md_idx`, /// or `None` if such span does not exist. pub(crate) fn md_to_fn_call_path_span( &mut self, context: &Context, md_idx: Option<MetadataIndex>, ) -> Option<Span> { self.md_to_tagged_span(context, md_idx, "fn_call_path_span") } pub(crate) fn md_to_test_decl_index( &mut self, context: &Context, md_idx: Option<MetadataIndex>, ) -> Option<DeclId<TyFunctionDecl>> { Self::for_each_md_idx(context, md_idx, |md_idx| { self.md_test_decl_index_cache .get(&md_idx) .cloned() .or_else(|| { // Create a new decl index and save it in the cache md_idx .get_content(context) .unwrap_struct("decl_index", 1) .and_then(|fields| { let index = fields[0] .unwrap_integer() .map(|index| DeclId::new(index as usize))?; self.md_test_decl_index_cache.insert(md_idx, index); Some(index) }) }) }) } pub(crate) fn md_to_purity( &mut self, context: &Context, md_idx: Option<MetadataIndex>, ) -> Purity { // If the purity metadata is not available, we assume the function to // be pure, because in the case of a pure function, we do not store // its purity attribute, to avoid bloating the metadata. Self::for_each_md_idx(context, md_idx, |md_idx| { self.md_purity_cache.get(&md_idx).copied().or_else(|| { // Create a new purity and save it in the cache. md_idx .get_content(context) .unwrap_struct("purity", 1) .and_then(|fields| { fields[0].unwrap_string().and_then(|purity_str| { let purity = match purity_str { "reads" => Some(Purity::Reads), "writes" => Some(Purity::Writes), "readswrites" => Some(Purity::ReadsWrites), _otherwise => panic!("Invalid purity metadata: {purity_str}."), }?; self.md_purity_cache.insert(md_idx, purity); Some(purity) }) }) }) }) .unwrap_or(Purity::Pure) } /// Gets Inline information from metadata index. /// TODO: We temporarily allow this because we need this /// in the sway-ir inliner, but cannot access it. So the code /// itself has been (modified and) copied there. When we decide /// on the right place for Metadata to be /// (and how it can be accessed form sway-ir), this will be fixed. #[allow(dead_code)] pub(crate) fn md_to_inline( &mut self, context: &Context, md_idx: Option<MetadataIndex>, ) -> Option<Inline> { Self::for_each_md_idx(context, md_idx, |md_idx| { self.md_inline_cache.get(&md_idx).copied().or_else(|| { // Create a new inline and save it in the cache. md_idx .get_content(context) .unwrap_struct("inline", 1) .and_then(|fields| fields[0].unwrap_string()) .and_then(|inline_str| { let inline = match inline_str { "always" => Some(Inline::Always), "never" => Some(Inline::Never), _otherwise => None, }?; self.md_inline_cache.insert(md_idx, inline); Some(inline) }) }) }) } #[allow(dead_code)] pub(crate) fn md_to_trace( &mut self, context: &Context, md_idx: Option<MetadataIndex>, ) -> Option<Trace> { Self::for_each_md_idx(context, md_idx, |md_idx| { self.md_trace_cache.get(&md_idx).copied().or_else(|| { // Create a new trace and save it in the cache. md_idx .get_content(context) .unwrap_struct("trace", 1) .and_then(|fields| fields[0].unwrap_string()) .and_then(|trace_str| { let trace = match trace_str { "always" => Some(Trace::Always), "never" => Some(Trace::Never), _otherwise => None, }?; self.md_trace_cache.insert(md_idx, trace); Some(trace) }) }) }) } fn md_to_file_location( &mut self, context: &Context, md: &Metadatum, ) -> Option<(Arc<PathBuf>, Source)> { md.unwrap_index().and_then(|md_idx| { self.md_file_loc_cache.get(&md_idx).cloned().or_else(|| { // Create a new file location (path and src) and save it in the cache. md_idx .get_content(context) .unwrap_source_id() .and_then(|source_id| { let path_buf = context.source_engine.get_path(source_id); let src = std::fs::read_to_string(&path_buf).ok()?; let path_and_src = (Arc::new(path_buf), src.as_str().into()); self.md_file_loc_cache.insert(md_idx, path_and_src.clone()); Some(path_and_src) }) }) }) } pub(crate) fn val_to_span(&mut self, context: &Context, value: Value) -> Option<Span> { self.md_to_span(context, value.get_metadata(context)) } pub(crate) fn span_to_md( &mut self, context: &mut Context, span: &Span, ) -> Option<MetadataIndex> { self.span_md_cache.get(span).copied().or_else(|| { span.source_id().and_then(|source_id| { let md_idx = self.create_metadata_from_span(context, source_id, span, "span")?; self.span_md_cache.insert(span.clone(), md_idx); Some(md_idx) }) }) } /// Returns [MetadataIndex] with [Metadatum::Struct] tagged with `tag` /// whose content will be the provided `span`. /// /// If the `span` does not have [Span::source_id], `None` is returned. /// /// This [Span] can later be retrieved from the [MetadataIndex] by calling /// [Self::md_to_tagged_span]. pub(crate) fn tagged_span_to_md( &mut self, context: &mut Context, span: &Span, tag: &'static str, ) -> Option<MetadataIndex> { let span_and_tag = (span.clone(), tag); self.tagged_span_md_cache .get(&span_and_tag) .copied() .or_else(|| { span.source_id().and_then(|source_id| { let md_idx = self.create_metadata_from_span(context, source_id, span, tag)?; self.tagged_span_md_cache.insert(span_and_tag, md_idx); Some(md_idx) }) }) } /// Returns [MetadataIndex] with [Metadatum::Struct] /// whose content will be the [Span] of the `fn_name` [Ident]. /// /// If that span does not have [Span::source_id], `None` is returned. /// /// This [Span] can later be retrieved from the [MetadataIndex] by calling /// [Self::md_to_fn_name_span]. pub(crate) fn fn_name_span_to_md( &mut self, context: &mut Context, fn_name: &Ident, ) -> Option<MetadataIndex> { self.tagged_span_to_md(context, &fn_name.span(), "fn_name_span") } /// Returns [MetadataIndex] with [Metadatum::Struct] /// whose content will be the [Span] of the `call_path`. /// /// If that span does not have [Span::source_id], `None` is returned. /// /// This [Span] can later be retrieved from the [MetadataIndex] by calling /// [Self::md_to_fn_call_path_span]. pub(crate) fn fn_call_path_span_to_md( &mut self, context: &mut Context, call_path: &CallPath, ) -> Option<MetadataIndex> { self.tagged_span_to_md(context, &call_path.span(), "fn_call_path_span") } pub(crate) fn test_decl_index_to_md( &mut self, context: &mut Context, decl_index: DeclId<TyFunctionDecl>, ) -> Option<MetadataIndex> { self.test_decl_index_md_cache .get(&decl_index) .copied() .or_else(|| { let md_idx = MetadataIndex::new_struct( context, "decl_index", vec![Metadatum::Integer(decl_index.inner() as u64)], ); self.test_decl_index_md_cache.insert(decl_index, md_idx); Some(md_idx) }) } pub(crate) fn purity_to_md( &mut self, context: &mut Context, purity: Purity, ) -> Option<MetadataIndex> { // If the function is pure, we do not store the purity attribute, // to avoid bloating the metadata. (purity != Purity::Pure).then(|| { self.purity_md_cache .get(&purity) .copied() .unwrap_or_else(|| { // Create new metadatum. let field = match purity { Purity::Pure => unreachable!("Already checked for Pure above."), Purity::Reads => "reads", Purity::Writes => "writes", Purity::ReadsWrites => "readswrites", }; let md_idx = MetadataIndex::new_struct( context, "purity", vec![Metadatum::String(field.to_owned())], ); self.purity_md_cache.insert(purity, md_idx); md_idx }) }) } pub(crate) fn inline_to_md( &mut self, context: &mut Context, inline: Inline, ) -> Option<MetadataIndex> { Some( self.inline_md_cache .get(&inline) .copied() .unwrap_or_else(|| { // Create new metadatum. let field = match inline { Inline::Always => "always", Inline::Never => "never", }; let md_idx = MetadataIndex::new_struct( context, "inline", vec![Metadatum::String(field.to_owned())], ); self.inline_md_cache.insert(inline, md_idx); md_idx }), ) } pub(crate) fn trace_to_md( &mut self, context: &mut Context, trace: Trace, ) -> Option<MetadataIndex> { Some(self.trace_md_cache.get(&trace).copied().unwrap_or_else(|| { // Create new metadatum. let field = match trace { Trace::Always => "always", Trace::Never => "never", }; let md_idx = MetadataIndex::new_struct( context, "trace", vec![Metadatum::String(field.to_owned())], ); self.trace_md_cache.insert(trace, md_idx); md_idx })) } fn file_location_to_md( &mut self, context: &mut Context, source_id: SourceId, ) -> Option<MetadataIndex> { self.file_loc_md_cache.get(&source_id).copied().or_else(|| { let md_idx = MetadataIndex::new_source_id(context, source_id); self.file_loc_md_cache.insert(source_id, md_idx); Some(md_idx) }) } fn for_each_md_idx<T, F: FnMut(MetadataIndex) -> Option<T>>( context: &Context, md_idx: Option<MetadataIndex>, mut f: F, ) -> Option<T> { // If md_idx is not None and is a list then try them all. md_idx.and_then(|md_idx| { if let Some(md_idcs) = md_idx.get_content(context).unwrap_list() { md_idcs.iter().find_map(|md_idx| f(*md_idx)) } else { f(md_idx) } }) } fn create_span_from_metadatum_fields( &mut self, context: &Context, fields: &[Metadatum], ) -> Option<Span> { let (path, src) = self.md_to_file_location(context, &fields[0])?; let start = fields[1].unwrap_integer()?; let end = fields[2].unwrap_integer()?; let source_engine = context.source_engine(); let source_id = source_engine.get_source_id(&path); let span = Span::new(src, start as usize, end as usize, Some(source_id))?; Some(span) } fn create_metadata_from_span( &mut self, context: &mut Context, source_id: &SourceId, span: &Span, tag: &'static str, ) -> Option<MetadataIndex> { let file_location_md_idx = self.file_location_to_md(context, *source_id)?; let md_idx = MetadataIndex::new_struct( context, tag, vec![ Metadatum::Index(file_location_md_idx), Metadatum::Integer(span.start() as u64), Metadatum::Integer(span.end() as u64), ], ); Some(md_idx) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/obs_engine.rs
sway-core/src/obs_engine.rs
use std::fmt::{Debug, Formatter, Result}; use std::sync::Mutex; use sway_ir::Type; use crate::decl_engine::DeclRefFunction; use crate::language::parsed::MethodName; use crate::semantic_analysis::TypeCheckContext; use crate::{Engines, TypeBinding, TypeId, TypeInfo}; pub trait Observer { fn on_trace(&self, _msg: &str) {} fn on_before_method_resolution( &self, _ctx: &TypeCheckContext<'_>, _method_name: &TypeBinding<MethodName>, _args_types: &[TypeId], ) { } fn on_after_method_resolution( &self, _ctx: &TypeCheckContext<'_>, _method_name: &TypeBinding<MethodName>, _args_types: &[TypeId], _new_ref: DeclRefFunction, _new_type_id: TypeId, ) { } fn on_after_ir_type_resolution( &self, _engines: &Engines, _ctx: &sway_ir::Context, _type_info: &TypeInfo, _ir_type: &Type, ) { } } #[derive(Default)] pub struct ObservabilityEngine { observer: Mutex<Option<Box<dyn Observer>>>, trace: Mutex<bool>, } unsafe impl Send for ObservabilityEngine {} unsafe impl Sync for ObservabilityEngine {} impl Debug for ObservabilityEngine { fn fmt(&self, f: &mut Formatter<'_>) -> Result { f.debug_struct("ObservabilityEngine") .field("trace", &self.trace) .finish() } } impl ObservabilityEngine { pub fn set_observer(&self, observer: Box<dyn Observer>) { let mut obs = self.observer.lock().unwrap(); *obs = Some(observer); } pub fn raise_on_before_method_resolution( &self, ctx: &TypeCheckContext, method_name: &TypeBinding<MethodName>, arguments_types: &[TypeId], ) { if let Some(obs) = self.observer.lock().unwrap().as_mut() { obs.on_before_method_resolution(ctx, method_name, arguments_types); } } pub fn raise_on_after_method_resolution( &self, ctx: &TypeCheckContext, method_name: &TypeBinding<MethodName>, arguments_types: &[TypeId], ref_function: DeclRefFunction, tid: TypeId, ) { if let Some(obs) = self.observer.lock().unwrap().as_mut() { obs.on_after_method_resolution(ctx, method_name, arguments_types, ref_function, tid); } } pub fn raise_on_after_ir_type_resolution( &self, engines: &Engines, ctx: &sway_ir::Context, type_info: &TypeInfo, ir_type: &Type, ) { if let Some(obs) = self.observer.lock().unwrap().as_mut() { obs.on_after_ir_type_resolution(engines, ctx, type_info, ir_type); } } pub(crate) fn trace(&self, get_txt: impl FnOnce() -> String) { let trace = self.trace.lock().unwrap(); if *trace { if let Some(obs) = self.observer.lock().unwrap().as_mut() { obs.on_trace(&get_txt()); } } } pub fn enable_trace(&self, enable: bool) { let mut trace = self.trace.lock().unwrap(); *trace = enable } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation.rs
sway-core/src/ir_generation.rs
pub(crate) mod compile; pub mod const_eval; mod convert; mod function; mod lexical_map; mod purity; pub mod storage; mod types; use std::{ collections::HashMap, hash::{DefaultHasher, Hasher}, }; use sway_error::error::CompileError; use sway_features::ExperimentalFeatures; use sway_ir::{ Backtrace, Context, Function, InstOp, InstructionInserter, IrError, Kind, Module, Type, Value, }; use sway_types::{span::Span, Ident}; pub use function::{get_encoding_representation, get_runtime_representation, MemoryRepresentation}; pub(crate) use purity::{check_function_purity, PurityEnv}; use crate::{ engine_threading::HashWithEngines, ir_generation::function::FnCompiler, language::ty::{self, TyCodeBlock, TyExpression, TyFunctionDecl, TyReassignmentTarget}, metadata::MetadataManager, types::{LogId, MessageId}, Engines, PanicOccurrences, PanickingCallOccurrences, TypeId, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct FnKey(u64); impl FnKey { fn new(decl: &TyFunctionDecl, engines: &Engines) -> Self { let mut hasher = DefaultHasher::default(); decl.hash(&mut hasher, engines); let key = hasher.finish(); Self(key) } } /// Groups a [TyFunctionDecl] with its [FnKey]. pub(crate) struct KeyedTyFunctionDecl<'a> { key: FnKey, decl: &'a TyFunctionDecl, } impl<'a> KeyedTyFunctionDecl<'a> { fn new(decl: &'a TyFunctionDecl, engines: &'a Engines) -> Self { Self { key: FnKey::new(decl, engines), decl, } } } /// Every compiled function needs to go through this cache for two reasons: /// 1. to have its IR name unique; /// 2. to avoid being compiled twice. #[derive(Default)] pub(crate) struct CompiledFunctionCache { cache: HashMap<FnKey, Function>, } impl CompiledFunctionCache { #[allow(clippy::too_many_arguments)] fn get_compiled_function( &mut self, engines: &Engines, context: &mut Context, module: Module, md_mgr: &mut MetadataManager, keyed_decl: &KeyedTyFunctionDecl, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, ) -> Result<Function, CompileError> { let fn_key = keyed_decl.key; let decl = keyed_decl.decl; let new_callee = match self.cache.get(&fn_key) { Some(func) => *func, None => { let name = Ident::new(Span::from_string(format!( "{}_{}", decl.name, context.get_unique_symbol_id() ))); let callee_fn_decl = ty::TyFunctionDecl { type_parameters: Vec::new(), name, parameters: decl.parameters.clone(), ..decl.clone() }; // Entry functions are already compiled at the top level // when compiling scripts, predicates, contracts, and libraries. let is_entry = false; let is_original_entry = callee_fn_decl.is_main() || callee_fn_decl.is_test(); let new_func = compile::compile_function( engines, context, md_mgr, module, &callee_fn_decl, &decl.name, FnCompiler::fn_abi_errors_display(decl, engines), logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, is_entry, is_original_entry, None, self, ) .map_err(|mut x| x.pop().unwrap())? .unwrap(); self.cache.insert(fn_key, new_func); new_func } }; Ok(new_callee) } } #[derive(Default)] pub(crate) struct PanickingFunctionCache { cache: HashMap<FnKey, bool>, } impl PanickingFunctionCache { /// Returns `true` if the function represented by `keyed_decl` can panic. /// /// By definition, a function can panic, and have the `__backtrace` argument /// added, *if it is not an entry or original entry* and if it contains a /// `panic` expression, or calls functions that contain `panic` expressions, /// recursively. /// /// Note that "can panic" is purely an IR concept that does not exist in the AST. /// The reason is, because we don't have a language, frontend, concept of "can panic", /// that we can check during the type checking phase. This would require an attribute /// or a similar mechanism to mark functions as "can panic", which we do not want to /// have. /// /// Because of this, we can cannot check during the type checking phase if a /// generic function can panic. E.g., in the below example, `foo` needs to be /// monomorphized to check if it can panic, and "can panic" can be different /// for different monomorphized versions of the function: /// /// ```sway /// fn foo<T>() where T: DoSomething { /// T::do_something(); /// } /// ``` pub(crate) fn can_panic( &mut self, keyed_decl: &KeyedTyFunctionDecl, engines: &Engines, ) -> bool { let fn_key = keyed_decl.key; let decl = keyed_decl.decl; // Function must not be an entry or original entry (test or main). if !decl.is_default() { return false; } match self.cache.get(&fn_key) { Some(can_panic) => *can_panic, None => { let can_panic = self.can_code_block_panic(&decl.body, engines); self.cache.insert(fn_key, can_panic); can_panic } } } fn can_code_block_panic(&mut self, body: &TyCodeBlock, engines: &Engines) -> bool { for node in body.contents.iter() { use ty::TyAstNodeContent::*; match &node.content { Declaration(ty_decl) => { if let ty::TyDecl::VariableDecl(var_decl) = ty_decl { if self.can_expression_panic(&var_decl.body, engines) { return true; } } } Expression(expr) => { if self.can_expression_panic(expr, engines) { return true; } } SideEffect(_) | Error(_, _) => {} } } false } fn can_expression_panic(&mut self, expr: &TyExpression, engines: &Engines) -> bool { use ty::TyExpressionVariant::*; match &expr.expression { // `Panic` panics by definition. Panic(_) => true, // `FunctionApplication` can panic if the callee can panic. FunctionApplication { fn_ref, .. } => { let decl = engines.de().get_function(fn_ref.id()); let keyed_decl = KeyedTyFunctionDecl::new(&decl, engines); // TODO: Add support for recursive functions once https://github.com/FuelLabs/sway/issues/3018 gets developed. self.can_panic(&keyed_decl, engines) } // Expressions with a single expression that could panic. MatchExp { desugared: expr, .. } | StructFieldAccess { prefix: expr, .. } | TupleElemAccess { prefix: expr, .. } | AbiCast { address: expr, .. } | EnumTag { exp: expr } | UnsafeDowncast { exp: expr, .. } | ForLoop { desugared: expr } | ImplicitReturn(expr) | Return(expr) | Ref(expr) | Deref(expr) => self.can_expression_panic(expr, engines), // Expressions with multiple sub-expressions that could panic. LazyOperator { lhs, rhs, .. } => { self.can_expression_panic(lhs, engines) || self.can_expression_panic(rhs, engines) } Tuple { fields } => fields .iter() .any(|field| self.can_expression_panic(field, engines)), ArrayExplicit { contents, .. } => contents .iter() .any(|elem| self.can_expression_panic(elem, engines)), ArrayRepeat { value, length, .. } => { self.can_expression_panic(value, engines) || self.can_expression_panic(length, engines) } ArrayIndex { prefix, index } => { self.can_expression_panic(prefix, engines) || self.can_expression_panic(index, engines) } StructExpression { fields, .. } => fields .iter() .any(|field| self.can_expression_panic(&field.value, engines)), IfExp { condition, then, r#else, } => { self.can_expression_panic(condition, engines) || self.can_expression_panic(then, engines) || r#else .as_ref() .map_or(false, |r#else| self.can_expression_panic(r#else, engines)) } AsmExpression { registers, .. } => registers.iter().any(|reg| { reg.initializer .as_ref() .is_some_and(|init| self.can_expression_panic(init, engines)) }), EnumInstantiation { contents, .. } => contents .as_ref() .is_some_and(|contents| self.can_expression_panic(contents, engines)), WhileLoop { condition, body } => { self.can_expression_panic(condition, engines) || self.can_code_block_panic(body, engines) } Reassignment(reassignment) => match &reassignment.lhs { TyReassignmentTarget::ElementAccess { indices, .. } => { indices.iter().any(|index| match index { ty::ProjectionKind::StructField { .. } | ty::ProjectionKind::TupleField { .. } => false, ty::ProjectionKind::ArrayIndex { index, .. } => { self.can_expression_panic(index, engines) } }) } TyReassignmentTarget::DerefAccess { exp, indices } => { self.can_expression_panic(exp, engines) || indices.iter().any(|index| match index { ty::ProjectionKind::StructField { .. } | ty::ProjectionKind::TupleField { .. } => false, ty::ProjectionKind::ArrayIndex { index, .. } => { self.can_expression_panic(index, engines) } }) } }, CodeBlock(block) => self.can_code_block_panic(block, engines), // Expressions that cannot panic. Literal(_) | ConstantExpression { .. } | ConfigurableExpression { .. } | ConstGenericExpression { .. } | VariableExpression { .. } | FunctionParameter | StorageAccess(_) | IntrinsicFunction(_) | AbiName(_) | Break | Continue => false, } } } pub fn compile_program<'a>( program: &ty::TyProgram, panic_occurrences: &'a mut PanicOccurrences, panicking_call_occurrences: &'a mut PanickingCallOccurrences, include_tests: bool, engines: &'a Engines, experimental: ExperimentalFeatures, backtrace: Backtrace, ) -> Result<Context<'a>, Vec<CompileError>> { let declaration_engine = engines.de(); let test_fns = match include_tests { true => program.test_fns(declaration_engine).collect(), false => vec![], }; let ty::TyProgram { kind, namespace, logged_types, messages_types, declarations, .. } = program; let logged_types = logged_types .iter() .map(|(log_id, type_id)| (*type_id, *log_id)) .collect(); let messages_types = messages_types .iter() .map(|(message_id, type_id)| (*type_id, *message_id)) .collect(); let mut ctx = Context::new(engines.se(), experimental, backtrace); ctx.program_kind = match kind { ty::TyProgramKind::Script { .. } => Kind::Script, ty::TyProgramKind::Predicate { .. } => Kind::Predicate, ty::TyProgramKind::Contract { .. } => Kind::Contract, ty::TyProgramKind::Library { .. } => Kind::Library, }; let mut compiled_fn_cache = CompiledFunctionCache::default(); let mut panicking_fn_cache = PanickingFunctionCache::default(); match kind { // Predicates and scripts have the same codegen, their only difference is static // type-check time checks. ty::TyProgramKind::Script { entry_function, .. } => compile::compile_script( engines, &mut ctx, entry_function, namespace, &logged_types, &messages_types, panic_occurrences, panicking_call_occurrences, &mut panicking_fn_cache, &test_fns, &mut compiled_fn_cache, ), ty::TyProgramKind::Predicate { entry_function, .. } => compile::compile_predicate( engines, &mut ctx, entry_function, namespace, &logged_types, &messages_types, panic_occurrences, panicking_call_occurrences, &mut panicking_fn_cache, &test_fns, &mut compiled_fn_cache, ), ty::TyProgramKind::Contract { entry_function, abi_entries, } => compile::compile_contract( &mut ctx, entry_function.as_ref(), abi_entries, namespace, declarations, &logged_types, &messages_types, panic_occurrences, panicking_call_occurrences, &mut panicking_fn_cache, &test_fns, engines, &mut compiled_fn_cache, ), ty::TyProgramKind::Library { .. } => compile::compile_library( engines, &mut ctx, namespace, &logged_types, &messages_types, panic_occurrences, panicking_call_occurrences, &mut panicking_fn_cache, &test_fns, &mut compiled_fn_cache, ), }?; type_correction(&mut ctx).map_err(|ir_error: sway_ir::IrError| { vec![CompileError::InternalOwned( ir_error.to_string(), Span::dummy(), )] })?; ctx.verify().map_err(|ir_error: sway_ir::IrError| { vec![CompileError::InternalOwned( ir_error.to_string(), Span::dummy(), )] })?; Ok(ctx) } fn type_correction(ctx: &mut Context) -> Result<(), IrError> { struct TypeCorrection { actual_ty: sway_ir::Type, expected_ty: sway_ir::Type, use_instr: sway_ir::Value, use_idx: usize, } // This is a copy of sway_core::asm_generation::fuel::fuel_asm_builder::FuelAsmBuilder::is_copy_type. fn is_copy_type(ty: &Type, context: &Context) -> bool { ty.is_unit(context) || ty.is_never(context) || ty.is_bool(context) || ty.is_ptr(context) || ty.get_uint_width(context).map(|x| x < 256).unwrap_or(false) } let mut instrs_to_fix = Vec::new(); for module in ctx.module_iter() { for function in module.function_iter(ctx) { for (_block, instr) in function.instruction_iter(ctx).collect::<Vec<_>>() { match &instr.get_instruction(ctx).unwrap().op { InstOp::Call(callee, actual_params) => { let formal_params: Vec<_> = callee.args_iter(ctx).collect(); for (param_idx, (actual_param, (_, formal_param))) in actual_params.iter().zip(formal_params.iter()).enumerate() { let actual_ty = actual_param.get_type(ctx).unwrap(); let formal_ty = formal_param.get_type(ctx).unwrap(); if actual_ty != formal_ty { instrs_to_fix.push(TypeCorrection { actual_ty, expected_ty: formal_ty, use_instr: instr, use_idx: param_idx, }); } } } InstOp::AsmBlock(_block, _args) => { // Non copy type args to asm blocks are passed by reference. let op = &instr.get_instruction(ctx).unwrap().op; let args = op .get_operands() .iter() .enumerate() .map(|(idx, init)| (idx, init.get_type(ctx).unwrap())) .collect::<Vec<_>>(); for (arg_idx, arg_ty) in args { if !is_copy_type(&arg_ty, ctx) { instrs_to_fix.push(TypeCorrection { actual_ty: arg_ty, expected_ty: Type::new_typed_pointer(ctx, arg_ty), use_instr: instr, use_idx: arg_idx, }); } } } InstOp::GetElemPtr { base, elem_ptr_ty, indices, } => { let base_ty = base.get_type(ctx).unwrap(); if let (Some(base_pointee_ty), Some(elem_inner_ty)) = ( base_ty.get_pointee_type(ctx), elem_ptr_ty.get_pointee_type(ctx), ) { // The base is a pointer type. We need to see if it's a double pointer. if let Some(base_pointee_pointee_ty) = base_pointee_ty.get_pointee_type(ctx) { // We have a double pointer. If just loading once solves our problem, we do that. let indexed_ty = base_pointee_pointee_ty.get_value_indexed_type(ctx, indices); if indexed_ty.is_some_and(|ty| ty == elem_inner_ty) { instrs_to_fix.push(TypeCorrection { actual_ty: base_ty, expected_ty: base_pointee_ty, use_instr: instr, use_idx: indices.len(), }); } } } else { // The base is not a pointer type. If a pointer to base_ty works for us, do that. let elem_ptr_ty = *elem_ptr_ty; let indices = indices.clone(); // Cloning needed because of mutable and immutable borrow of `ctx`. let pointer_to_base = Type::new_typed_pointer(ctx, base_ty); if pointer_to_base.get_value_indexed_type(ctx, &indices) == Some(elem_ptr_ty) { instrs_to_fix.push(TypeCorrection { actual_ty: base_ty, expected_ty: pointer_to_base, use_instr: instr, use_idx: indices.len(), }); } } } InstOp::Store { dst_val_ptr, stored_val, } => { let dst_ty = dst_val_ptr.get_type(ctx).unwrap(); let stored_ty = stored_val.get_type(ctx).unwrap(); if let Some(dst_pointee_ty) = dst_ty.get_pointee_type(ctx) { // The destination is a pointer type. We need to see if it's a double pointer. if let Some(dst_pointee_pointee_ty) = dst_pointee_ty.get_pointee_type(ctx) { // We have a double pointer. If just loading once solves our problem, we do that. if dst_pointee_pointee_ty == stored_ty { instrs_to_fix.push(TypeCorrection { actual_ty: dst_ty, expected_ty: dst_pointee_ty, use_instr: instr, use_idx: 0, }); } } else if let Some(stored_pointee_ty) = stored_ty.get_pointee_type(ctx) { // The value being stored is a pointer to what should've been stored. // So we just load the value and store it. if dst_pointee_ty == stored_pointee_ty { instrs_to_fix.push(TypeCorrection { actual_ty: stored_ty, expected_ty: stored_pointee_ty, use_instr: instr, use_idx: 1, }); } } } else { // The destination is not a pointer type, but should've been. let pointer_to_dst = Type::new_typed_pointer(ctx, dst_ty); if pointer_to_dst == stored_ty { instrs_to_fix.push(TypeCorrection { actual_ty: dst_ty, expected_ty: pointer_to_dst, use_instr: instr, use_idx: 0, }); } } } InstOp::Ret(ret_val, ret_ty) => { if let Some(ret_val_pointee_ty) = ret_val .get_type(ctx) .and_then(|ret_val_ty| ret_val_ty.get_pointee_type(ctx)) { if ret_val_pointee_ty == *ret_ty { instrs_to_fix.push(TypeCorrection { actual_ty: ret_val.get_type(ctx).unwrap(), expected_ty: *ret_ty, use_instr: instr, use_idx: 0, }); } } } _ => (), } } } } for TypeCorrection { actual_ty, expected_ty, use_instr, use_idx, } in instrs_to_fix { let function = use_instr.get_instruction(ctx).unwrap().get_function(ctx); if expected_ty .get_pointee_type(ctx) .is_some_and(|pointee| pointee == actual_ty) { // The expected type is a pointer to the actual type. // If the actual value was just loaded, then we go to the source of the load, // otherwise, we store it to a new local and pass the address of that local. let actual_use = use_instr.get_instruction(ctx).unwrap().op.get_operands()[use_idx]; if let Some(InstOp::Load(src_ptr)) = actual_use.get_instruction(ctx).map(|i| &i.op) { let src_ptr = *src_ptr; use_instr .get_instruction_mut(ctx) .unwrap() .op .set_operand(src_ptr, use_idx); } else { let parent_block = use_instr.get_instruction(ctx).unwrap().parent; let new_local = function.new_unique_local_var( ctx, "type_fix".to_string(), actual_ty, None, true, ); let new_local = Value::new_instruction(ctx, parent_block, InstOp::GetLocal(new_local)); let store = Value::new_instruction( ctx, parent_block, InstOp::Store { dst_val_ptr: new_local, stored_val: actual_use, }, ); let mut inserter = InstructionInserter::new( ctx, parent_block, sway_ir::InsertionPosition::Before(use_instr), ); inserter.insert_slice(&[new_local, store]); // Update the use instruction to use the new local use_instr .get_instruction_mut(ctx) .unwrap() .op .set_operand(new_local, use_idx); } } else if actual_ty .get_pointee_type(ctx) .is_some_and(|pointee| pointee == expected_ty) { // Just load the actual value. let load = Value::new_instruction( ctx, use_instr.get_instruction(ctx).unwrap().parent, InstOp::Load(use_instr.get_instruction(ctx).unwrap().op.get_operands()[use_idx]), ); let mut inserter = InstructionInserter::new( ctx, use_instr.get_instruction(ctx).unwrap().parent, sway_ir::InsertionPosition::Before(use_instr), ); inserter.insert_slice(&[load]); // Update the use instruction to use the new load use_instr .get_instruction_mut(ctx) .unwrap() .op .set_operand(load, use_idx); } } Ok(()) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/engine.rs
sway-core/src/type_system/engine.rs
use crate::{ ast_elements::type_argument::GenericTypeArgument, concurrent_slab::{ConcurrentSlab, ListDisplay}, decl_engine::*, engine_threading::*, language::{ parsed::{EnumDeclaration, StructDeclaration}, ty::{TyEnumDecl, TyExpression, TyStructDecl}, QualifiedCallPath, }, type_system::priv_prelude::*, }; use core::fmt::Write; use hashbrown::{hash_map::RawEntryMut, HashMap}; use parking_lot::RwLock; use std::{ hash::{BuildHasher, Hash, Hasher}, sync::Arc, time::Instant, }; use sway_error::{ error::CompileError, handler::{ErrorEmitted, Handler}, type_error::TypeError, }; use sway_types::{ integer_bits::IntegerBits, span::Span, Ident, Named, ProgramId, SourceId, Spanned, }; use super::{ast_elements::type_parameter::ConstGenericExpr, unify::unifier::UnifyKind}; /// To be able to garbage-collect [TypeInfo]s from the [TypeEngine] /// we need to track which types need to be GCed when a particular /// module, represented by its source id, is GCed. [TypeSourceInfo] /// encapsulates this information. /// /// For types that should never be GCed the `source_id` must be `None`. /// /// The concrete logic of assigning `source_id`s to `type_info`s is /// given in the [TypeEngine::get_type_fallback_source_id]. // TODO: This logic will be further improved when https://github.com/FuelLabs/sway/issues/6603 // is implemented (Optimize `TypeEngine` for garbage collection). #[derive(Debug, Default, Clone)] struct TypeSourceInfo { type_info: Arc<TypeInfo>, source_id: Option<SourceId>, } impl TypeSourceInfo { /// Returns true if the `self` would be equal to another [TypeSourceInfo] /// created from `type_info` and `source_id`. /// /// This method allows us to test equality "upfront", without the need to /// create a new [TypeSourceInfo] which would require a heap allocation /// of a new [TypeInfo]. pub(crate) fn equals( &self, type_info: &TypeInfo, source_id: &Option<SourceId>, ctx: &PartialEqWithEnginesContext, ) -> bool { &self.source_id == source_id && self.type_info.eq(type_info, ctx) } } impl HashWithEngines for TypeSourceInfo { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { self.type_info.hash(state, engines); self.source_id.hash(state); } } impl EqWithEngines for TypeSourceInfo {} impl PartialEqWithEngines for TypeSourceInfo { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.equals(&other.type_info, &other.source_id, ctx) } } /// Holds the singleton instances of [TypeSourceInfo]s of *replaceable types* that, /// although being inserted anew into the [TypeEngine], all share the single definition. /// This means that, e.g., all the different [TypeEngine::slab] entries representing /// the, e.g., [TypeInfo::Unknown] will point to the same singleton instance /// of the corresponding [TypeSourceInfo]. #[derive(Debug, Clone)] struct SingletonTypeSourceInfos { /// The single instance of the [TypeSourceInfo] /// representing the [TypeInfo::Unknown] replaceable type. unknown: Arc<TypeSourceInfo>, /// The single instance of the [TypeSourceInfo] /// representing the [TypeInfo::Numeric] replaceable type. numeric: Arc<TypeSourceInfo>, } /// Holds the instances of [TypeInfo]s and allows exchanging them for [TypeId]s. /// Supports LSP garbage collection of unused [TypeInfo]s assigned to a particular [SourceId]. /// /// ## Intended Usage /// Inserting [TypeInfo]s into the type engine returns a [TypeId] that can later be used /// to get the same [TypeInfo] by using the [TypeEngine::get] method. /// /// Properly using the various inserting methods is crucial for the optimal work of the type engine. /// /// These methods are grouped by the following convention and are intended to be used in the /// order of precedence given below: /// - `id_of_<type>`: methods that always return the same [TypeId] for a type. /// These methods, when inlined, compile to constant [TypeId]s. /// - `new_<type>`: methods that always return a new [TypeId] for a type. /// - `insert_<type>[_<additional options>]`: methods that might insert a new type into the engine, /// and return a new [TypeId], but also reuse an existing [TypeInfo] and return an existing [TypeId]. /// - `insert`: the fallback method that should be used only in cases when the type is not known /// at the call site. /// /// ## Internal Implementation /// [TypeInfo]s are stored in a private [TypeSourceInfo] structure that binds them with a [SourceId] /// of the module in which they are used. Those [TypeSourceInfo]s are referenced from the `slab`. /// The actual [TypeId] of a [TypeInfo] is just an index in the `slab`. /// /// The engine attempts to maximize the reuse of [TypeSourceInfo]s by holding _shareable types_ /// (see: [Self::is_type_shareable]) in the `shareable_types` hash map. /// /// TODO: Note that the reuse currently happens on the level of [TypeSourceInfo]s, and not [TypeInfo]s. /// This is not optimal and will be improved in https://github.com/FuelLabs/sway/issues/6603. /// Also note that because of that, having [TypeInfo] stored in `Arc` within the [TypeSourceInfo] /// does not bring any real benefits. /// /// The implementation of the type engine is primarily directed with the goal of maximizing the /// reuse of the [TypeSourceInfo]s while at the same time having the [TypeInfo]s bound to [SourceId]s /// of their use site, so that they can be garbage collected. /// /// TODO: Note that the assignment of [SourceId]s to [TypeInfo]s is currently not as optimal as it /// can be. This will be improved in https://github.com/FuelLabs/sway/issues/6603. #[derive(Debug)] pub struct TypeEngine { slab: ConcurrentSlab<TypeSourceInfo>, /// Holds [TypeId]s of [TypeSourceInfo]s of shareable types (see: [Self::is_type_shareable]). /// [TypeSourceInfo]s of shareable types can be reused if the type is used more /// then once. In that case, for every usage, instead of inserting a new [TypeSourceInfo] instance /// into the [Self::slab], the [TypeId] of an existing instance is returned. shareable_types: RwLock<HashMap<Arc<TypeSourceInfo>, TypeId>>, singleton_types: RwLock<SingletonTypeSourceInfos>, unifications: ConcurrentSlab<Unification>, last_replace: RwLock<Instant>, } pub trait IsConcrete { fn is_concrete(&self, handler: &Handler, engines: &Engines) -> bool; } #[derive(Debug, Clone)] pub(crate) struct Unification { pub received: TypeId, pub expected: TypeId, pub span: Span, pub help_text: String, pub unify_kind: UnifyKind, } impl Default for TypeEngine { fn default() -> Self { let singleton_types = SingletonTypeSourceInfos { unknown: TypeSourceInfo { type_info: TypeInfo::Unknown.into(), source_id: None, } .into(), numeric: TypeSourceInfo { type_info: TypeInfo::Numeric.into(), source_id: None, } .into(), }; let mut te = TypeEngine { slab: Default::default(), shareable_types: Default::default(), singleton_types: RwLock::new(singleton_types), unifications: Default::default(), last_replace: RwLock::new(Instant::now()), }; te.insert_shareable_built_in_types(); te } } impl Clone for TypeEngine { fn clone(&self) -> Self { TypeEngine { slab: self.slab.clone(), shareable_types: RwLock::new(self.shareable_types.read().clone()), singleton_types: RwLock::new(self.singleton_types.read().clone()), unifications: self.unifications.clone(), last_replace: RwLock::new(*self.last_replace.read()), } } } /// Generates: /// - `id_of_<type>` methods for every provided shareable built-in type. /// - `insert_shareable_built_in_types` method for initial creation of built-in types within the [TypeEngine]. /// - `get_shareable_built_in_type_id` method for potential retrieval of built-in types in the [TypeEngine::insert] method. /// /// Note that, when invoking the macro, the `unit` and the [TypeInfo::ErrorRecovery] types *must not be provided in the list*. /// The shareable `unit` type requires a special treatment within the macro, because it is modeled /// as [TypeInfo::Tuple] with zero elements and not as a separate [TypeInfo] variant. /// The [TypeInfo::ErrorRecovery], although being an enum variant with the parameter (the [ErrorEmitted] proof), is /// actually a single type because all the [ErrorEmitted] proofs are the same. /// This special case is also handled within the macro. /// /// Unfortunately, due to limitations of Rust's macro-by-example, the [TypeInfo] must be /// provided twice during the macro invocation, once as an expression `expr` and once as a pattern `pat`. /// /// The macro recursively creates the `id_of_<type>` methods in order to get the proper `usize` value /// generated, which corresponds to the index of those types within the slab. macro_rules! type_engine_shareable_built_in_types { // The base recursive case. (@step $_idx:expr,) => {}; // The actual recursion step that generates the `id_of_<type>` functions. (@step $idx:expr, ($ty_name:ident, $ti:expr, $ti_pat:pat), $(($tail_ty_name:ident, $tail_ti:expr, $tail_ti_pat:pat),)*) => { paste::paste! { pub const fn [<id_of_ $ty_name>](&self) -> TypeId { TypeId::new($idx) } } type_engine_shareable_built_in_types!(@step $idx + 1, $(($tail_ty_name, $tail_ti, $tail_ti_pat),)*); }; // The entry point. Invoking the macro matches this arm. ($(($ty_name:ident, $ti:expr, $ti_pat:pat),)*) => { // The `unit` type is a special case. It will be inserted in the slab as the first type. pub(crate) const fn id_of_unit(&self) -> TypeId { TypeId::new(0) } // The error recovery type is a special case. It will be inserted in the slab as the second type. // To preserve the semantics of the `TypeInfo::ErrorRecovery(ErrorEmitted)`, we still insist on // providing the proof of the error being emitted, although that proof is actually // not needed to obtain the type id, nor is used within this method at all. #[allow(unused_variables)] pub(crate) const fn id_of_error_recovery(&self, error_emitted: ErrorEmitted) -> TypeId { TypeId::new(1) } // Generate the remaining `id_of_<type>` methods. We start counting the indices from 2. type_engine_shareable_built_in_types!(@step 2, $(($ty_name, $ti, $ti_pat),)*); // Generate the method that initially inserts the built-in shareable types into the `slab` in the right order. // // Note that we are inserting the types **only into the `slab`, but not into the `shareable_types`**, // although they should, by definition, be in the `shareable_types` as well. // // What is the reason for not inserting them into the `shareable_types`? // // To insert them into the `shareable_types` we need `Engines` to be able to calculate // the hash and equality with engines, and method is supposed be called internally during the creation // of the `TypeEngine`. At that moment, we are creating a single, isolated engine, and do not // have all the engines available. The only way to have it called with all the engines, is // to do it when `Engines` are created. But this would mean that we cannot have a semantically // valid `TypeEngine` created in isolation, without the `Engines`, which would be a problematic // design that breaks cohesion and creates unexpected dependency. // // Note that having the built-in shareable types initially inserted only in the `slab` does // not cause any issues with type insertion and retrieval. The `id_of_<type>` methods return // indices that are compile-time constants and there is no need for `shareable_types` access. // Also, calling `insert` with built-in shareable types has an optimized path which will redirect // to `id_of_<type>` methods, again bypassing the `shareable_types`. // // The only negligible small "penalty" comes during replacements of replaceable types, // where a potential replacement with a built-in shareable type will create a separate instance // of that built-in type and add it to `shareable_types`. fn insert_shareable_built_in_types(&mut self) { use TypeInfo::*; let tsi = TypeSourceInfo { type_info: Tuple(vec![]).into(), source_id: None, }; self.slab.insert(tsi); // For the `ErrorRecovery`, we need an `ErrorEmitted` instance. // All of its instances are the same, so we will use, or perhaps misuse, // the `Handler::cancel` method here to obtain an instance. let tsi = TypeSourceInfo { type_info: ErrorRecovery(crate::Handler::default().cancel()).into(), source_id: None, }; self.slab.insert(tsi); $( let tsi = TypeSourceInfo { type_info: $ti.into(), source_id: None, }; self.slab.insert(tsi); )* } /// Returns the [TypeId] of the `type_info` only if the type info is /// a shareable built-in type, otherwise `None`. /// /// For a particular shareable built-in type, the method guarantees to always /// return the same, existing [TypeId]. fn get_shareable_built_in_type_id(&self, type_info: &TypeInfo) -> Option<TypeId> { paste::paste! { use TypeInfo::*; match type_info { Tuple(v) if v.is_empty() => Some(self.id_of_unit()), // Here we also "pass" the dummy value obtained from `Handler::cancel` which will be // optimized away. ErrorRecovery(_) => Some(self.id_of_error_recovery(crate::Handler::default().cancel())), $( $ti_pat => Some(self.[<id_of_ $ty_name>]()), )* _ => None } } } /// Returns true if the type represented by the `type_info` /// is a shareable built-in type. fn is_shareable_built_in_type(&self, type_info: &TypeInfo) -> bool { use TypeInfo::*; match type_info { Tuple(v) if v.is_empty() => true, // Here we also "pass" the dummy value obtained from `Handler::cancel` which will be // optimized away. ErrorRecovery(_) => true, $( $ti_pat => true, )* _ => false } } } } impl TypeEngine { type_engine_shareable_built_in_types!( (never, Never, Never), (string_slice, StringSlice, StringSlice), ( u8, UnsignedInteger(IntegerBits::Eight), UnsignedInteger(IntegerBits::Eight) ), ( u16, UnsignedInteger(IntegerBits::Sixteen), UnsignedInteger(IntegerBits::Sixteen) ), ( u32, UnsignedInteger(IntegerBits::ThirtyTwo), UnsignedInteger(IntegerBits::ThirtyTwo) ), ( u64, UnsignedInteger(IntegerBits::SixtyFour), UnsignedInteger(IntegerBits::SixtyFour) ), ( u256, UnsignedInteger(IntegerBits::V256), UnsignedInteger(IntegerBits::V256) ), (bool, Boolean, Boolean), (b256, B256, B256), (contract, Contract, Contract), (raw_ptr, RawUntypedPtr, RawUntypedPtr), (raw_slice, RawUntypedSlice, RawUntypedSlice), ); /// Inserts a new [TypeInfo::Unknown] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::Unknown] is an always replaceable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_unknown(&self) -> TypeId { TypeId::new( self.slab .insert_arc(self.singleton_types.read().unknown.clone()), ) } /// Inserts a new [TypeInfo::Numeric] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::Numeric] is an always replaceable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_numeric(&self) -> TypeId { TypeId::new( self.slab .insert_arc(self.singleton_types.read().numeric.clone()), ) } /// Inserts a new [TypeInfo::TypeParam] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::TypeParam] is an always replaceable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_type_param(&self, type_parameter: TypeParameter) -> TypeId { self.new_type_param_impl(TypeInfo::TypeParam(type_parameter)) } fn new_type_param_impl(&self, type_param: TypeInfo) -> TypeId { let source_id = self.get_type_parameter_fallback_source_id(&type_param); let tsi = TypeSourceInfo { type_info: type_param.into(), source_id, }; TypeId::new(self.slab.insert(tsi)) } /// Inserts a new [TypeInfo::Placeholder] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::Placeholder] is an always replaceable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_placeholder(&self, type_parameter: TypeParameter) -> TypeId { self.new_placeholder_impl(TypeInfo::Placeholder(type_parameter)) } fn new_placeholder_impl(&self, placeholder: TypeInfo) -> TypeId { let source_id = self.get_placeholder_fallback_source_id(&placeholder); let tsi = TypeSourceInfo { type_info: placeholder.into(), source_id, }; TypeId::new(self.slab.insert(tsi)) } /// Inserts a new [TypeInfo::UnknownGeneric] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::UnknownGeneric] is an always replaceable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_unknown_generic( &self, name: Ident, trait_constraints: VecSet<TraitConstraint>, parent: Option<TypeId>, is_from_type_parameter: bool, ) -> TypeId { self.new_unknown_generic_impl(TypeInfo::UnknownGeneric { name, trait_constraints, parent, is_from_type_parameter, }) } fn new_unknown_generic_impl(&self, unknown_generic: TypeInfo) -> TypeId { let source_id = Self::get_unknown_generic_fallback_source_id(&unknown_generic); let tsi = TypeSourceInfo { type_info: unknown_generic.into(), source_id, }; TypeId::new(self.slab.insert(tsi)) } /// Inserts a new [TypeInfo::UnknownGeneric] into the [TypeEngine] /// that represents a `Self` type and returns its [TypeId]. /// The unknown generic `name` [Ident] will be set to "Self" with the provided `use_site_span`. /// /// Note that the span in general does not point to a reserved word "Self" in /// the source code, nor is related to it. The `Self` type represents the type /// in `impl`s and does not necessarily relate to the "Self" keyword in code. /// /// Therefore, *the span must always point to a location in the source file in which /// the particular `Self` type is, e.g., being declared or implemented*. /// /// Returns the [TypeId] and the [Ident] set to "Self" and the provided `use_site_span`. pub(crate) fn new_unknown_generic_self( &self, use_site_span: Span, is_from_type_parameter: bool, ) -> (TypeId, Ident) { let name = Ident::new_with_override("Self".into(), use_site_span); let type_id = self.new_unknown_generic(name.clone(), VecSet(vec![]), None, is_from_type_parameter); (type_id, name) } /// Inserts a new [TypeInfo::Enum] into the [TypeEngine] and returns /// its [TypeId], or returns a [TypeId] of an existing shareable enum type /// that corresponds to the enum given by the `decl_id`. pub(crate) fn insert_enum(&self, engines: &Engines, decl_id: DeclId<TyEnumDecl>) -> TypeId { let decl = engines.de().get_enum(&decl_id); let source_id = Self::get_enum_fallback_source_id(&decl); let is_shareable_type = self.is_shareable_enum(engines, &decl); let type_info = TypeInfo::Enum(decl_id); self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Inserts a new [TypeInfo::Struct] into the [TypeEngine] and returns /// its [TypeId], or returns a [TypeId] of an existing shareable struct type /// that corresponds to the struct given by the `decl_id`. pub(crate) fn insert_struct(&self, engines: &Engines, decl_id: DeclId<TyStructDecl>) -> TypeId { let decl = engines.de().get_struct(&decl_id); let source_id = Self::get_struct_fallback_source_id(&decl); let is_shareable_type = self.is_shareable_struct(engines, &decl); let type_info = TypeInfo::Struct(decl_id); self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Inserts a new [TypeInfo::Tuple] into the [TypeEngine] and returns /// its [TypeId], or returns a [TypeId] of an existing shareable tuple type /// that corresponds to the tuple given by the `elements`. pub(crate) fn insert_tuple( &self, engines: &Engines, elements: Vec<GenericTypeArgument>, ) -> TypeId { let source_id = self.get_tuple_fallback_source_id(&elements); let is_shareable_type = self.is_shareable_tuple(engines, &elements); let type_info = TypeInfo::Tuple(elements); self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Same as [Self::insert_tuple], but intended to be used mostly in the code generation, /// where the tuple elements are non-annotated [TypeArgument]s that contain /// only the [TypeId]s provided in the `elements`. pub(crate) fn insert_tuple_without_annotations( &self, engines: &Engines, elements: Vec<TypeId>, ) -> TypeId { self.insert_tuple( engines, elements.into_iter().map(|type_id| type_id.into()).collect(), ) } /// Inserts a new [TypeInfo::Array] into the [TypeEngine] and returns /// its [TypeId], or returns a [TypeId] of an existing shareable array type /// that corresponds to the array given by the `elem_type` and the `length`. pub(crate) fn insert_array( &self, engines: &Engines, elem_type: GenericTypeArgument, length: Length, ) -> TypeId { let source_id = self.get_array_fallback_source_id(&elem_type, &length); let is_shareable_type = self.is_shareable_array(engines, &elem_type, &length); let type_info = TypeInfo::Array(elem_type, length); self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Same as [Self::insert_array], but intended to insert arrays without annotations. // TODO: Unlike `insert_array`, once the https://github.com/FuelLabs/sway/issues/6603 gets implemented, // this method will get the additional `use_site_source_id` parameter. pub(crate) fn insert_array_without_annotations( &self, engines: &Engines, elem_type: TypeId, length: usize, ) -> TypeId { self.insert_array( engines, elem_type.into(), Length(ConstGenericExpr::literal(length, None)), ) } /// Inserts a new [TypeInfo::StringArray] into the [TypeEngine] and returns /// its [TypeId], or returns a [TypeId] of an existing shareable string array type /// that corresponds to the string array given by the `length`. pub(crate) fn insert_string_array(&self, engines: &Engines, length: Length) -> TypeId { let source_id = Self::get_string_array_fallback_source_id(&length); let is_shareable_type = self.is_shareable_string_array(&length); let type_info = TypeInfo::StringArray(length); self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Same as [Self::insert_string_array], but intended to insert string arrays without annotations. // TODO: Unlike `insert_string_array`, once the https://github.com/FuelLabs/sway/issues/6603 gets implemented, // this method will get the additional `use_site_source_id` parameter. pub(crate) fn insert_string_array_without_annotations( &self, engines: &Engines, length: usize, ) -> TypeId { self.insert_string_array(engines, Length(ConstGenericExpr::literal(length, None))) } /// Inserts a new [TypeInfo::ContractCaller] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::ContractCaller] is not a shareable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_contract_caller( &self, engines: &Engines, abi_name: AbiName, address: Option<Box<TyExpression>>, ) -> TypeId { // The contract caller type shareability would be calculated as: // // !(Self::is_replaceable_contract_caller(abi_name, address) // || // Self::is_contract_caller_distinguishable_by_annotations(abi_name, address)) // // If the contract caller is replaceable, either the `abi_name` id `Deferred` or the `address` is `None`. // On the other hand, if the `abi_name` is `Known` or the `address` is `Some`, it will be distinguishable by annotations. // Which means, it will be either replaceable or distinguishable by annotations, which makes the condition always // evaluating to false. // // The fact that we cannot share `ContractCaller`s is not an issue. In any real-life project, the number of contract callers // will be negligible, order of magnitude of ~10. let source_id = Self::get_contract_caller_fallback_source_id(&abi_name, &address); let type_info = TypeInfo::ContractCaller { abi_name, address }; self.insert_or_replace_type_source_info(engines, type_info, source_id, false, None) } /// Inserts a new [TypeInfo::Alias] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::Alias] is not a shareable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_alias( &self, engines: &Engines, name: Ident, ty: GenericTypeArgument, ) -> TypeId { // The alias type shareability would be calculated as `!(false || true) ==>> false`. let source_id = self.get_alias_fallback_source_id(&name, &ty); let type_info = TypeInfo::Alias { name, ty }; self.insert_or_replace_type_source_info(engines, type_info, source_id, false, None) } /// Inserts a new [TypeInfo::Custom] into the [TypeEngine] and returns its [TypeId]. /// /// [TypeInfo::Custom] is not a shareable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_custom( &self, engines: &Engines, qualified_call_path: QualifiedCallPath, type_arguments: Option<Vec<GenericArgument>>, ) -> TypeId { let source_id = self.get_custom_fallback_source_id(&qualified_call_path, &type_arguments); // The custom type shareability would be calculated as `!(true || true) ==>> false`. // TODO: Improve handling of `TypeInfo::Custom` and `TypeInfo::TraitType`` within the `TypeEngine`: // https://github.com/FuelLabs/sway/issues/6601 let is_shareable_type = false; let type_info = TypeInfo::Custom { qualified_call_path, type_arguments, }; self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Inserts a new [TypeInfo::Custom] into the [TypeEngine] and returns its [TypeId]. /// The custom type is defined only by its `name`. In other words, it does not have /// the qualified call path or type arguments. This is a very common situation in /// the code that just uses the type name, like, e.g., when instantiating structs: /// /// ```ignore /// let _ = Struct { }; /// ``` /// /// [TypeInfo::Custom] is not a shareable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_custom_from_name(&self, engines: &Engines, name: Ident) -> TypeId { self.new_custom(engines, name.into(), None) } /// Creates a new [TypeInfo::Custom] that represents a Self type. /// /// The `span` must either be a [Span::dummy] or a span pointing /// to text "Self" or "self", otherwise the method panics. /// /// [TypeInfo::Custom] is not a shareable type and the method /// guarantees that a new (or unused) [TypeId] will be returned on every /// call. pub(crate) fn new_self_type(&self, engines: &Engines, span: Span) -> TypeId { let source_id = span.source_id().copied(); // The custom type shareability would be calculated as `!(true || true) ==>> false`. // TODO: Improve handling of `TypeInfo::Custom` and `TypeInfo::TraitType`` within the `TypeEngine`: // https://github.com/FuelLabs/sway/issues/6601 let is_shareable_type = false; let type_info = TypeInfo::new_self_type(span); self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Inserts a new [TypeInfo::Slice] into the [TypeEngine] and returns /// its [TypeId], or returns a [TypeId] of an existing shareable slice type /// that corresponds to the slice given by the `elem_type`. pub(crate) fn insert_slice(&self, engines: &Engines, elem_type: GenericTypeArgument) -> TypeId { let source_id = self.get_slice_fallback_source_id(&elem_type); let is_shareable_type = self.is_shareable_slice(engines, &elem_type); let type_info = TypeInfo::Slice(elem_type); self.insert_or_replace_type_source_info( engines, type_info, source_id, is_shareable_type, None, ) } /// Inserts a new [TypeInfo::Ptr] into the [TypeEngine] and returns /// its [TypeId], or returns a [TypeId] of an existing shareable pointer type /// that corresponds to the pointer given by the `pointee_type`. pub(crate) fn insert_ptr( &self, engines: &Engines, pointee_type: GenericTypeArgument, ) -> TypeId { let source_id = self.get_ptr_fallback_source_id(&pointee_type); let is_shareable_type = self.is_shareable_ptr(engines, &pointee_type); let type_info = TypeInfo::Ptr(pointee_type); self.insert_or_replace_type_source_info( engines, type_info,
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/id.rs
sway-core/src/type_system/id.rs
#![allow(clippy::mutable_key_type)] use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use sway_error::{ error::CompileError, handler::{ErrorEmitted, Handler}, }; use sway_types::{BaseIdent, Named, Span, Spanned}; use crate::{ decl_engine::{ DeclEngineGet, DeclEngineGetParsedDecl, DeclEngineInsert, MaterializeConstGenerics, }, engine_threading::{DebugWithEngines, DisplayWithEngines, Engines, WithEngines}, language::{ty::TyStructDecl, CallPath}, namespace::TraitMap, semantic_analysis::TypeCheckContext, type_system::priv_prelude::*, types::{CollectTypesMetadata, CollectTypesMetadataContext, TypeMetadata}, EnforceTypeArguments, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, fmt, }; use super::ast_elements::type_parameter::ConstGenericExpr; const EXTRACT_ANY_MAX_DEPTH: usize = 128; pub enum IncludeSelf { Yes, No, } pub enum TreatNumericAs { Abstract, Concrete, } /// A identifier to uniquely refer to our type terms #[derive(PartialEq, Eq, Hash, Clone, Copy, Ord, PartialOrd, Debug, Deserialize, Serialize)] pub struct TypeId(usize); impl DisplayWithEngines for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { write!(f, "{}", engines.help_out(&*engines.te().get(*self))) } } impl DebugWithEngines for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { write!(f, "{:?}", engines.help_out(&*engines.te().get(*self))) } } impl From<usize> for TypeId { fn from(o: usize) -> Self { TypeId(o) } } impl CollectTypesMetadata for TypeId { fn collect_types_metadata( &self, _handler: &Handler, ctx: &mut CollectTypesMetadataContext, ) -> Result<Vec<TypeMetadata>, ErrorEmitted> { fn filter_fn(type_info: &TypeInfo) -> bool { matches!( type_info, TypeInfo::UnknownGeneric { .. } | TypeInfo::Placeholder(_) ) } let engines = ctx.engines; let possible = self.extract_any_including_self(engines, &filter_fn, vec![], 0); let mut res = vec![]; for (type_id, _) in possible { match &*ctx.engines.te().get(type_id) { TypeInfo::UnknownGeneric { name, .. } => { res.push(TypeMetadata::UnresolvedType( name.clone(), ctx.call_site_get(&type_id), )); } TypeInfo::Placeholder(type_param) => { res.push(TypeMetadata::UnresolvedType( type_param.name().clone(), ctx.call_site_get(self), )); } _ => {} } } Ok(res) } } impl SubstTypes for TypeId { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let type_engine = ctx.engines.te(); if let Some(matching_id) = ctx .type_subst_map .and_then(|tsm| tsm.find_match(*self, ctx.handler, ctx.engines)) { if !matches!(&*type_engine.get(matching_id), TypeInfo::ErrorRecovery(_)) { *self = matching_id; HasChanges::Yes } else { HasChanges::No } } else { HasChanges::No } } } impl MaterializeConstGenerics for TypeId { fn materialize_const_generics( &mut self, engines: &Engines, handler: &Handler, name: &str, value: &crate::language::ty::TyExpression, ) -> Result<(), ErrorEmitted> { match &*engines.te().get(*self) { TypeInfo::Array( element_type, Length(ConstGenericExpr::AmbiguousVariableExpression { ident, decl }), ) => { let mut elem_type = element_type.clone(); elem_type.materialize_const_generics(engines, handler, name, value)?; if ident.as_str() == name { let val = match &value.expression { crate::language::ty::TyExpressionVariant::Literal(literal) => { literal.cast_value_to_u64().unwrap() } _ => { return Err(handler.emit_err(CompileError::Internal( "Unexpected error on const generics", value.span.clone(), ))); } }; *self = engines.te().insert_array( engines, elem_type, Length(ConstGenericExpr::Literal { val: val as usize, span: value.span.clone(), }), ); } else { let mut decl = decl.clone(); if let Some(decl) = decl.as_mut() { decl.materialize_const_generics(engines, handler, name, value)?; } *self = engines.te().insert_array( engines, elem_type, Length(ConstGenericExpr::AmbiguousVariableExpression { ident: ident.clone(), decl, }), ); } } TypeInfo::Enum(id) => { let decl = engines.de().get(id); let mut decl = (*decl).clone(); decl.materialize_const_generics(engines, handler, name, value)?; let parsed_decl = engines .de() .get_parsed_decl(id) .unwrap() .to_enum_decl(handler, engines) .ok(); let decl_ref = engines.de().insert(decl, parsed_decl.as_ref()); *self = engines.te().insert_enum(engines, *decl_ref.id()); } TypeInfo::Struct(id) => { let mut decl = TyStructDecl::clone(&engines.de().get(id)); decl.materialize_const_generics(engines, handler, name, value)?; let parsed_decl = engines .de() .get_parsed_decl(id) .unwrap() .to_struct_decl(handler, engines) .ok(); let decl_ref = engines.de().insert(decl, parsed_decl.as_ref()); *self = engines.te().insert_struct(engines, *decl_ref.id()); } TypeInfo::StringArray(Length(ConstGenericExpr::AmbiguousVariableExpression { ident, .. })) if ident.as_str() == name => { let val = match &value.expression { crate::language::ty::TyExpressionVariant::Literal(literal) => { literal.cast_value_to_u64().unwrap() } _ => { return Err(handler.emit_err(CompileError::Internal( "Unexpected error on const generics", value.span.clone(), ))); } }; *self = engines.te().insert_string_array( engines, Length(ConstGenericExpr::Literal { val: val as usize, span: value.span.clone(), }), ); } TypeInfo::Ref { to_mutable_value, referenced_type, .. } => { let mut referenced_type = referenced_type.clone(); referenced_type .type_id .materialize_const_generics(engines, handler, name, value)?; *self = engines .te() .insert_ref(engines, *to_mutable_value, referenced_type); } _ => {} } Ok(()) } } impl TypeId { pub(super) const fn new(index: usize) -> TypeId { TypeId(index) } /// Returns the index that identifies the type. pub fn index(&self) -> usize { self.0 } pub(crate) fn get_type_parameters(self, engines: &Engines) -> Option<Vec<TypeParameter>> { let type_engine = engines.te(); let decl_engine = engines.de(); match &*type_engine.get(self) { TypeInfo::Enum(decl_id) => { let decl = decl_engine.get(decl_id); (!decl.generic_parameters.is_empty()).then_some(decl.generic_parameters.clone()) } TypeInfo::Struct(decl_ref) => { let decl = decl_engine.get_struct(decl_ref); (!decl.generic_parameters.is_empty()).then_some(decl.generic_parameters.clone()) } _ => None, } } /// Indicates of a given type is generic or not. Rely on whether the type is `Custom` and /// consider the special case where the resolved type is a struct or enum with a name that /// matches the name of the `Custom`. pub(crate) fn is_generic_parameter(self, engines: &Engines, resolved_type_id: TypeId) -> bool { let type_engine = engines.te(); let decl_engine = engines.de(); match (&*type_engine.get(self), &*type_engine.get(resolved_type_id)) { ( TypeInfo::Custom { qualified_call_path: call_path, .. }, TypeInfo::Enum(decl_ref), ) => call_path.call_path.suffix != decl_engine.get_enum(decl_ref).call_path.suffix, ( TypeInfo::Custom { qualified_call_path: call_path, .. }, TypeInfo::Struct(decl_ref), ) => call_path.call_path.suffix != decl_engine.get_struct(decl_ref).call_path.suffix, ( TypeInfo::Custom { qualified_call_path: call_path, .. }, TypeInfo::Alias { name, .. }, ) => call_path.call_path.suffix != name.clone(), (TypeInfo::Custom { .. }, _) => true, _ => false, } } pub(crate) fn extract_any_including_self<F>( self, engines: &Engines, filter_fn: &F, trait_constraints: Vec<TraitConstraint>, depth: usize, ) -> IndexMap<TypeId, Vec<TraitConstraint>> where F: Fn(&TypeInfo) -> bool, { let type_engine = engines.te(); let type_info = type_engine.get(self); let mut found = self.extract_any(engines, filter_fn, depth + 1); if filter_fn(&type_info) { found.insert(self, trait_constraints); } found } pub(crate) fn walk_any_including_self<F, WT, WTC>( self, engines: &Engines, filter_fn: &F, trait_constraints: Vec<TraitConstraint>, depth: usize, walk_type: &WT, walk_tc: &WTC, ) where F: Fn(&TypeInfo) -> bool, WT: Fn(&TypeId), WTC: Fn(&TraitConstraint), { let type_engine = engines.te(); self.walk_any(engines, filter_fn, depth + 1, walk_type, walk_tc); let type_info = type_engine.get(self); if filter_fn(&type_info) { walk_type(&self); trait_constraints.iter().for_each(walk_tc); } } /// Returns all pairs of type parameters and its /// concrete types. /// This includes primitive types that have "implicit" /// type parameters such as tuples, arrays and others... pub(crate) fn extract_type_parameters( self, handler: &Handler, engines: &Engines, depth: usize, type_parameters: &mut Vec<(TypeId, TypeId)>, const_generic_parameters: &mut BTreeMap<String, crate::language::ty::TyExpression>, orig_type_id: TypeId, ) { if depth >= EXTRACT_ANY_MAX_DEPTH { panic!("Possible infinite recursion at extract_type_parameters"); } let decl_engine = engines.de(); match (&*engines.te().get(self), &*engines.te().get(orig_type_id)) { (TypeInfo::Unknown, TypeInfo::Unknown) | (TypeInfo::Never, TypeInfo::Never) | (TypeInfo::Placeholder(_), TypeInfo::Placeholder(_)) | (TypeInfo::TypeParam(_), TypeInfo::TypeParam(_)) | (TypeInfo::StringArray(_), TypeInfo::StringArray(_)) | (TypeInfo::StringSlice, TypeInfo::StringSlice) | (TypeInfo::UnsignedInteger(_), TypeInfo::UnsignedInteger(_)) | (TypeInfo::RawUntypedPtr, TypeInfo::RawUntypedPtr) | (TypeInfo::RawUntypedSlice, TypeInfo::RawUntypedSlice) | (TypeInfo::Boolean, TypeInfo::Boolean) | (TypeInfo::B256, TypeInfo::B256) | (TypeInfo::Numeric, TypeInfo::Numeric) | (TypeInfo::Contract, TypeInfo::Contract) | (TypeInfo::ErrorRecovery(_), TypeInfo::ErrorRecovery(_)) | (TypeInfo::TraitType { .. }, TypeInfo::TraitType { .. }) => {} (TypeInfo::UntypedEnum(decl_id), TypeInfo::UntypedEnum(orig_decl_id)) => { let enum_decl = engines.pe().get_enum(decl_id); let orig_enum_decl = engines.pe().get_enum(orig_decl_id); assert_eq!( enum_decl.type_parameters.len(), orig_enum_decl.type_parameters.len() ); for (type_param, orig_type_param) in enum_decl .type_parameters .iter() .zip(orig_enum_decl.type_parameters.iter()) { let orig_type_param = orig_type_param .as_type_parameter() .expect("only works with type parameters"); let type_param = type_param .as_type_parameter() .expect("only works with type parameters"); type_parameters.push((type_param.type_id, orig_type_param.type_id)); type_param.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_type_param.type_id, ); } } (TypeInfo::UntypedStruct(decl_id), TypeInfo::UntypedStruct(orig_decl_id)) => { let struct_decl = engines.pe().get_struct(decl_id); let orig_struct_decl = engines.pe().get_struct(orig_decl_id); assert_eq!( struct_decl.type_parameters.len(), orig_struct_decl.type_parameters.len() ); for (type_param, orig_type_param) in struct_decl .type_parameters .iter() .zip(orig_struct_decl.type_parameters.iter()) { let orig_type_param = orig_type_param .as_type_parameter() .expect("only works with type parameters"); let type_param = type_param .as_type_parameter() .expect("only works with type parameters"); type_parameters.push((type_param.type_id, orig_type_param.type_id)); type_param.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_type_param.type_id, ); } } (TypeInfo::Enum(enum_ref), TypeInfo::Enum(orig_enum_ref)) => { let enum_decl = decl_engine.get_enum(enum_ref); let orig_enum_decl = decl_engine.get_enum(orig_enum_ref); assert_eq!( enum_decl.generic_parameters.len(), orig_enum_decl.generic_parameters.len() ); for (type_param, orig_type_param) in enum_decl .generic_parameters .iter() .zip(orig_enum_decl.generic_parameters.iter()) { match (orig_type_param, type_param) { (TypeParameter::Type(orig_type_param), TypeParameter::Type(type_param)) => { type_parameters.push((type_param.type_id, orig_type_param.type_id)); type_param.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_type_param.type_id, ); } ( TypeParameter::Const(orig_type_param), TypeParameter::Const(type_param), ) => match (orig_type_param.expr.as_ref(), type_param.expr.as_ref()) { (None, Some(expr)) => { const_generic_parameters.insert( orig_type_param.name.as_str().to_string(), expr.to_ty_expression(engines), ); } _ => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", orig_type_param.span.clone(), )); } }, _ => {} } } } (TypeInfo::Struct(struct_id), TypeInfo::Struct(orig_struct_id)) => { let struct_decl = decl_engine.get_struct(struct_id); let orig_struct_decl = decl_engine.get_struct(orig_struct_id); assert_eq!( struct_decl.generic_parameters.len(), orig_struct_decl.generic_parameters.len() ); for (type_param, orig_type_param) in struct_decl .generic_parameters .iter() .zip(orig_struct_decl.generic_parameters.iter()) { match (orig_type_param, type_param) { (TypeParameter::Type(orig_type_param), TypeParameter::Type(type_param)) => { type_parameters.push((type_param.type_id, orig_type_param.type_id)); type_param.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_type_param.type_id, ); } ( TypeParameter::Const(orig_type_param), TypeParameter::Const(type_param), ) => match (orig_type_param.expr.as_ref(), type_param.expr.as_ref()) { (None, Some(expr)) => { const_generic_parameters.insert( orig_type_param.name.as_str().to_string(), expr.to_ty_expression(engines), ); } _ => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", orig_type_param.span.clone(), )); } }, _ => {} } } } // Primitive types have "implicit" type parameters (TypeInfo::Tuple(elems), TypeInfo::Tuple(orig_elems)) => { assert_eq!(elems.len(), orig_elems.len()); for (elem, orig_elem) in elems.iter().zip(orig_elems.iter()) { type_parameters.push((elem.type_id, orig_elem.type_id)); elem.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_elem.type_id, ); } } ( TypeInfo::ContractCaller { abi_name: _, address, }, TypeInfo::ContractCaller { abi_name: _, address: orig_address, }, ) => { if let Some(address) = address { address.return_type.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_address.clone().unwrap().return_type, ); } } ( TypeInfo::Custom { qualified_call_path: _, type_arguments, }, TypeInfo::Custom { qualified_call_path: _, type_arguments: orig_type_arguments, }, ) => { if let Some(type_arguments) = type_arguments { for (type_arg, orig_type_arg) in type_arguments .iter() .zip(orig_type_arguments.clone().unwrap().iter()) { type_arg.type_id().extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_type_arg.type_id(), ); } } } // Primitive types have "implicit" type parameters (TypeInfo::Array(ty, _), TypeInfo::Array(orig_ty, _)) => { type_parameters.push((ty.type_id, orig_ty.type_id)); ty.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_ty.type_id, ); } (TypeInfo::Alias { name: _, ty }, _) => { ty.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_type_id, ); } (_, TypeInfo::Alias { name: _, ty }) => { self.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, ty.type_id, ); } (TypeInfo::UnknownGeneric { .. }, TypeInfo::UnknownGeneric { .. }) => {} // Primitive types have "implicit" type parameters (TypeInfo::Ptr(ty), TypeInfo::Ptr(orig_ty)) => { type_parameters.push((ty.type_id, orig_ty.type_id)); ty.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_ty.type_id, ); } // Primitive types have "implicit" type parameters (TypeInfo::Slice(ty), TypeInfo::Slice(orig_ty)) => { type_parameters.push((ty.type_id, orig_ty.type_id)); ty.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_ty.type_id, ); } // Primitive types have "implicit" type parameters ( TypeInfo::Ref { referenced_type, .. }, TypeInfo::Ref { referenced_type: orig_referenced_type, .. }, ) => { type_parameters.push((referenced_type.type_id, orig_referenced_type.type_id)); referenced_type.type_id.extract_type_parameters( handler, engines, depth + 1, type_parameters, const_generic_parameters, orig_referenced_type.type_id, ); } (_, TypeInfo::UnknownGeneric { .. }) => {} (_, _) => {} } } pub(crate) fn walk_any<F, WT, WTC>( self, engines: &Engines, filter_fn: &F, depth: usize, walk_type: &WT, walk_tc: &WTC, ) where F: Fn(&TypeInfo) -> bool, WT: Fn(&TypeId), WTC: Fn(&TraitConstraint), { if depth >= EXTRACT_ANY_MAX_DEPTH { panic!("Possible infinite recursion at walk_any"); } let decl_engine = engines.de(); match &*engines.te().get(self) { TypeInfo::Unknown | TypeInfo::Never | TypeInfo::Placeholder(_) | TypeInfo::TypeParam(_) | TypeInfo::StringArray(_) | TypeInfo::StringSlice | TypeInfo::UnsignedInteger(_) | TypeInfo::RawUntypedPtr | TypeInfo::RawUntypedSlice | TypeInfo::Boolean | TypeInfo::B256 | TypeInfo::Numeric | TypeInfo::Contract | TypeInfo::ErrorRecovery(_) | TypeInfo::TraitType { .. } => {} TypeInfo::UntypedEnum(decl_id) => { let enum_decl = engines.pe().get_enum(decl_id); for type_param in &enum_decl.type_parameters { match type_param { TypeParameter::Type(type_param) => { type_param.type_id.walk_any_including_self( engines, filter_fn, type_param.trait_constraints.clone(), depth + 1, walk_type, walk_tc, ) } TypeParameter::Const(type_param) => type_param.ty.walk_any_including_self( engines, filter_fn, vec![], depth + 1, walk_type, walk_tc, ), } } for variant in &enum_decl.variants { variant.type_argument.type_id.walk_any_including_self( engines, filter_fn, vec![], depth + 1, walk_type, walk_tc, ); } } TypeInfo::UntypedStruct(decl_id) => { let struct_decl = engines.pe().get_struct(decl_id); for type_param in &struct_decl.type_parameters { match type_param { TypeParameter::Type(type_param) => { type_param.type_id.walk_any_including_self( engines, filter_fn, type_param.trait_constraints.clone(), depth + 1, walk_type, walk_tc, ) } TypeParameter::Const(type_param) => type_param.ty.walk_any_including_self( engines, filter_fn, vec![], depth + 1, walk_type, walk_tc, ), } } for field in &struct_decl.fields { field.type_argument.type_id.walk_any_including_self( engines, filter_fn, vec![], depth + 1, walk_type, walk_tc, ); } } TypeInfo::Enum(enum_ref) => { let enum_decl = decl_engine.get_enum(enum_ref); for type_param in &enum_decl.generic_parameters { match type_param { TypeParameter::Type(type_param) => { type_param.type_id.walk_any_including_self( engines, filter_fn, type_param.trait_constraints.clone(), depth + 1, walk_type, walk_tc, ) } TypeParameter::Const(type_param) => type_param.ty.walk_any_including_self( engines, filter_fn, vec![], depth + 1, walk_type, walk_tc, ), } } for variant in &enum_decl.variants { variant.type_argument.type_id.walk_any_including_self( engines, filter_fn, vec![], depth + 1, walk_type, walk_tc, ); } } TypeInfo::Struct(struct_id) => { let struct_decl = decl_engine.get_struct(struct_id); for type_param in &struct_decl.generic_parameters { match type_param { TypeParameter::Type(type_param) => { type_param.type_id.walk_any_including_self( engines, filter_fn, type_param.trait_constraints.clone(), depth + 1, walk_type, walk_tc, ) } TypeParameter::Const(type_param) => type_param.ty.walk_any_including_self( engines, filter_fn, vec![], depth + 1, walk_type, walk_tc,
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/priv_prelude.rs
sway-core/src/type_system/priv_prelude.rs
pub(super) use super::unify::unifier::Unifier; pub(crate) use super::{ ast_elements::{ binding::{TypeArgs, TypeBinding, TypeCheckTypeBinding}, create_type_id::CreateTypeId, }, info::VecSet, substitute::{ subst_map::TypeSubstMap, subst_types::HasChanges, subst_types::{SubstTypes, SubstTypesContext}, }, unify::unify_check::UnifyCheck, }; pub use super::{ ast_elements::{ length::Length, trait_constraint::TraitConstraint, type_argument::{GenericArgument, GenericTypeArgument}, type_parameter::TypeParameter, }, engine::IsConcrete, engine::TypeEngine, id::{IncludeSelf, TreatNumericAs, TypeId}, info::{AbiEncodeSizeHint, AbiName, TypeInfo, TypeInfoDisplay}, };
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/monomorphization.rs
sway-core/src/type_system/monomorphization.rs
use crate::{ decl_engine::{engine::DeclEngineGetParsedDeclId, DeclEngineInsert, MaterializeConstGenerics}, language::{ ty::{self, TyExpression}, CallPath, }, namespace::{ModulePath, ResolvedDeclaration}, semantic_analysis::type_resolve::{resolve_type, VisibilityCheck}, type_system::ast_elements::create_type_id::CreateTypeId, EnforceTypeArguments, Engines, GenericArgument, Namespace, SubstTypes, SubstTypesContext, TypeId, TypeParameter, TypeSubstMap, }; use std::collections::BTreeMap; use sway_error::{ error::CompileError, handler::{ErrorEmitted, Handler}, }; use sway_types::{Ident, Span, Spanned}; pub(crate) trait MonomorphizeHelper { fn name(&self) -> &Ident; fn type_parameters(&self) -> &[TypeParameter]; fn has_self_type_param(&self) -> bool; } /// Given a `value` of type `T` that is able to be monomorphized and a set /// of `type_arguments`, prepare a `TypeSubstMap` that can be used as an /// input for monomorphization. #[allow(clippy::too_many_arguments)] pub(crate) fn prepare_type_subst_map_for_monomorphize<T>( handler: &Handler, engines: &Engines, namespace: &Namespace, value: &T, type_arguments: &mut [GenericArgument], enforce_type_arguments: EnforceTypeArguments, call_site_span: &Span, mod_path: &ModulePath, self_type: Option<TypeId>, subst_ctx: &SubstTypesContext, ) -> Result<TypeSubstMap, ErrorEmitted> where T: MonomorphizeHelper + SubstTypes, { fn make_type_arity_mismatch_error( name: Ident, span: Span, given: usize, expected: usize, ) -> CompileError { match (expected, given) { (0, 0) => unreachable!(), (_, 0) => CompileError::NeedsTypeArguments { name, span }, (0, _) => CompileError::DoesNotTakeTypeArguments { name, span }, (_, _) => CompileError::IncorrectNumberOfTypeArguments { name, given, expected, span, }, } } match (value.type_parameters().len(), type_arguments.len()) { (0, 0) => Ok(TypeSubstMap::default()), (num_type_params, 0) => { if let EnforceTypeArguments::Yes = enforce_type_arguments { return Err(handler.emit_err(make_type_arity_mismatch_error( value.name().clone(), call_site_span.clone(), 0, num_type_params, ))); } let type_mapping = TypeSubstMap::from_type_parameters(engines, value.type_parameters()); Ok(type_mapping) } (0, num_type_args) => { let type_arguments_span = type_arguments .iter() .map(|x| x.span().clone()) .reduce(|s1: Span, s2: Span| Span::join(s1, &s2)) .unwrap_or_else(|| value.name().span()); Err(handler.emit_err(make_type_arity_mismatch_error( value.name().clone(), type_arguments_span.clone(), num_type_args, 0, ))) } (_, num_type_args) => { // a trait decl is passed the self type parameter and the corresponding argument // but it would be confusing for the user if the error reporting mechanism // reported the number of arguments including the implicit self, hence // we adjust it below let adjust_for_trait_decl = value.has_self_type_param() as usize; let non_parent_type_params = value .type_parameters() .iter() .filter(|x| !x.is_from_parent()) .count() - adjust_for_trait_decl; let num_type_args = num_type_args - adjust_for_trait_decl; if non_parent_type_params != num_type_args { let type_arguments_span = type_arguments .iter() .map(|x| x.span()) .reduce(|s1: Span, s2: Span| Span::join(s1, &s2)) .unwrap_or_else(|| value.name().span()); return Err(handler.emit_err(make_type_arity_mismatch_error( value.name().clone(), type_arguments_span, num_type_args, non_parent_type_params, ))); } let params = value.type_parameters(); let args = type_arguments.iter_mut(); for (param, arg) in params.iter().zip(args) { match (param, arg) { (TypeParameter::Type(_), GenericArgument::Type(arg)) => { arg.type_id = resolve_type( handler, engines, namespace, mod_path, arg.type_id, &arg.span, enforce_type_arguments, None, self_type, subst_ctx, VisibilityCheck::Yes, ) .unwrap_or_else(|err| engines.te().id_of_error_recovery(err)); } (TypeParameter::Const(_), GenericArgument::Type(arg)) => { let suffix = arg .call_path_tree .as_ref() .unwrap() .qualified_call_path .call_path .suffix .clone(); let _ = crate::semantic_analysis::type_resolve::resolve_call_path( handler, engines, namespace, mod_path, &CallPath { prefixes: vec![], suffix, callpath_type: crate::language::CallPathType::Ambiguous, }, self_type, VisibilityCheck::No, ) .map(|d| d.expect_typed())?; } (_, GenericArgument::Const(arg)) => { match &arg.expr { crate::ast_elements::type_parameter::ConstGenericExpr::Literal { ..} => {}, crate::ast_elements::type_parameter::ConstGenericExpr::AmbiguousVariableExpression { ident, .. } => { let _ = crate::semantic_analysis::type_resolve::resolve_call_path( handler, engines, namespace, mod_path, &CallPath { prefixes: vec![], suffix: ident.clone(), callpath_type: crate::language::CallPathType::Ambiguous, }, self_type, VisibilityCheck::No, ) .map(|d| d.expect_typed())?; }, } } } } let mut params = vec![]; let mut args = vec![]; let mut consts = BTreeMap::new(); for (p, a) in value.type_parameters().iter().zip(type_arguments.iter()) { match (p, a) { (TypeParameter::Type(p), GenericArgument::Type(a)) => { params.push(p.type_id); args.push(a.type_id); } (TypeParameter::Const(p), GenericArgument::Const(a)) => { consts.insert( p.name.as_str().to_string(), a.expr.to_ty_expression(engines), ); } // TODO const generic was not materialized yet (TypeParameter::Const(_), GenericArgument::Type(_)) => {} x => todo!("{x:?}"), } } Ok( TypeSubstMap::from_type_parameters_and_type_arguments_and_const_generics( params, args, consts, ), ) } } } /// Given a `value` of type `T` that is able to be monomorphized and a set /// of `type_arguments`, monomorphize `value` with the `type_arguments`. /// /// When this function is called, it is passed a `T` that is a copy of some /// original declaration for `T` (let's denote the original with `[T]`). /// Because monomorphization happens at application time (e.g. function /// application), we want to be able to modify `value` such that type /// checking the application of `value` affects only `T` and not `[T]`. /// /// So, at a high level, this function does two things. It 1) performs the /// necessary work to refresh the relevant generic types in `T` so that they /// are distinct from the generics of the same name in `[T]`. And it 2) /// applies `type_arguments` (if any are provided) to the type parameters /// of `value`, unifying the types. /// /// There are 4 cases that are handled in this function: /// /// 1. `value` does not have type parameters + `type_arguments` is empty: /// 1a. return ok /// 2. `value` has type parameters + `type_arguments` is empty: /// 2a. if the [EnforceTypeArguments::Yes] variant is provided, then /// error /// 2b. refresh the generic types with a [TypeSubstMapping] /// 3. `value` does have type parameters + `type_arguments` is nonempty: /// 3a. error /// 4. `value` has type parameters + `type_arguments` is nonempty: /// 4a. check to see that the type parameters and `type_arguments` have /// the same length /// 4b. for each type argument in `type_arguments`, resolve the type /// 4c. refresh the generic types with a [TypeSubstMapping] #[allow(clippy::too_many_arguments)] pub(crate) fn monomorphize_with_modpath<T>( handler: &Handler, engines: &Engines, namespace: &Namespace, value: &mut T, type_arguments: &mut [GenericArgument], const_generics: BTreeMap<String, TyExpression>, enforce_type_arguments: EnforceTypeArguments, call_site_span: &Span, mod_path: &ModulePath, self_type: Option<TypeId>, subst_ctx: &SubstTypesContext, ) -> Result<(), ErrorEmitted> where T: MonomorphizeHelper + SubstTypes + MaterializeConstGenerics, { let type_mapping = prepare_type_subst_map_for_monomorphize( handler, engines, namespace, value, type_arguments, enforce_type_arguments, call_site_span, mod_path, self_type, subst_ctx, )?; value.subst(&SubstTypesContext::new( handler, engines, &type_mapping, true, )); for (name, expr) in const_generics.iter() { let _ = value.materialize_const_generics(engines, handler, name, expr); } for (name, expr) in type_mapping.const_generics_materialization.iter() { let _ = value.materialize_const_generics(engines, handler, name, expr); } Ok(()) } #[allow(clippy::too_many_arguments)] pub(crate) fn type_decl_opt_to_type_id( handler: &Handler, engines: &Engines, namespace: &Namespace, type_decl_opt: Option<ResolvedDeclaration>, call_path: &CallPath, span: &Span, enforce_type_arguments: EnforceTypeArguments, mod_path: &ModulePath, type_arguments: Option<Vec<GenericArgument>>, self_type: Option<TypeId>, subst_ctx: &SubstTypesContext, ) -> Result<TypeId, ErrorEmitted> { let decl_engine = engines.de(); let type_engine = engines.te(); Ok(match type_decl_opt { Some(ResolvedDeclaration::Typed(ty::TyDecl::StructDecl(ty::StructDecl { decl_id: original_id, .. }))) => { // get the copy from the declaration engine let mut new_copy = (*decl_engine.get_struct(&original_id)).clone(); // monomorphize the copy, in place monomorphize_with_modpath( handler, engines, namespace, &mut new_copy, &mut type_arguments.unwrap_or_default(), BTreeMap::new(), enforce_type_arguments, span, mod_path, self_type, subst_ctx, )?; // insert the new copy in the decl engine let new_decl_ref = decl_engine.insert( new_copy, decl_engine.get_parsed_decl_id(&original_id).as_ref(), ); // create the type id from the copy type_engine.insert_struct(engines, *new_decl_ref.id()) } Some(ResolvedDeclaration::Typed(ty::TyDecl::EnumDecl(ty::EnumDecl { decl_id: original_id, .. }))) => { // get the copy from the declaration engine let mut new_copy = (*decl_engine.get_enum(&original_id)).clone(); // monomorphize the copy, in place monomorphize_with_modpath( handler, engines, namespace, &mut new_copy, &mut type_arguments.unwrap_or_default(), BTreeMap::new(), enforce_type_arguments, span, mod_path, self_type, subst_ctx, )?; // insert the new copy in the decl engine let new_decl_ref = decl_engine.insert( new_copy, decl_engine.get_parsed_decl_id(&original_id).as_ref(), ); // create the type id from the copy type_engine.insert_enum(engines, *new_decl_ref.id()) } Some(ResolvedDeclaration::Typed(ty::TyDecl::TypeAliasDecl(ty::TypeAliasDecl { decl_id: original_id, .. }))) => { let new_copy = decl_engine.get_type_alias(&original_id); // TODO: (GENERIC-TYPE-ALIASES) Monomorphize the copy, in place, once generic type aliases are // supported. new_copy.create_type_id(engines) } Some(ResolvedDeclaration::Typed(ty::TyDecl::GenericTypeForFunctionScope( ty::GenericTypeForFunctionScope { type_id, .. }, ))) => type_id, Some(ResolvedDeclaration::Typed(ty::TyDecl::TraitTypeDecl(ty::TraitTypeDecl { decl_id, }))) => { let decl_type = decl_engine.get_type(&decl_id); if let Some(ty) = &decl_type.ty { ty.type_id() } else if let Some(implementing_type) = self_type { type_engine.insert_trait_type(engines, decl_type.name.clone(), implementing_type) } else { return Err(handler.emit_err(CompileError::Internal( "Self type not provided.", span.clone(), ))); } } Some(ResolvedDeclaration::Typed(ty::TyDecl::ConstGenericDecl(_))) => { return Ok(engines.te().id_of_u64()) } _ => { let err = handler.emit_err(CompileError::UnknownTypeName { name: call_path.to_string(), span: call_path.span(), }); type_engine.id_of_error_recovery(err) } }) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/info.rs
sway-core/src/type_system/info.rs
use crate::{ decl_engine::{parsed_id::ParsedDeclId, DeclEngine, DeclEngineGet, DeclId}, engine_threading::{ DebugWithEngines, DisplayWithEngines, Engines, EqWithEngines, GetCallPathWithEngines, HashWithEngines, OrdWithEngines, OrdWithEnginesContext, PartialEqWithEngines, PartialEqWithEnginesContext, }, language::{ parsed::{EnumDeclaration, StructDeclaration}, ty::{self, TyEnumDecl, TyStructDecl}, CallPath, CallPathType, QualifiedCallPath, }, type_system::priv_prelude::*, Ident, }; use serde::{Deserialize, Serialize}; use std::{ borrow::Cow, cmp::Ordering, fmt, hash::{Hash, Hasher}, }; use sway_ast::ImplItemParent; use sway_error::{ error::{CompileError, InvalidImplementingForType}, handler::{ErrorEmitted, Handler}, }; use sway_types::{integer_bits::IntegerBits, span::Span, Named}; use super::ast_elements::{type_argument::GenericTypeArgument, type_parameter::ConstGenericExpr}; #[derive(Debug, Clone, Hash, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub enum AbiName { Deferred, Known(CallPath), } impl fmt::Display for AbiName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str( &(match self { AbiName::Deferred => "for unspecified ABI".to_string(), AbiName::Known(cp) => cp.to_string(), }), ) } } /// A slow set primitive using `==` to check for containment. #[derive(Clone)] pub struct VecSet<T>(pub Vec<T>); impl<T: fmt::Debug> fmt::Debug for VecSet<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl<T> core::ops::Deref for VecSet<T> { type Target = [T]; fn deref(&self) -> &Self::Target { &self.0 } } impl<T: PartialEqWithEngines> VecSet<T> { pub fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.0.len() <= other.0.len() && self.0.iter().all(|x| other.0.iter().any(|y| x.eq(y, ctx))) } } impl<T: PartialEqWithEngines> PartialEqWithEngines for VecSet<T> { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.eq(other, ctx) && other.eq(self, ctx) } } /// Type information without an associated value, used for type inferencing and definition. #[derive(Debug, Clone, Default)] pub enum TypeInfo { #[default] Unknown, Never, /// Represents a type parameter. /// /// The equivalent type in the Rust compiler is: /// https://doc.rust-lang.org/nightly/nightly-rustc/src/rustc_type_ir/sty.rs.html#190 UnknownGeneric { name: Ident, // NOTE(Centril): Used to be BTreeSet; need to revert back later. Must be sorted! trait_constraints: VecSet<TraitConstraint>, // Methods can have type parameters with unknown generic that extend the trait constraints of a parent unknown generic. parent: Option<TypeId>, // This is true when the UnknownGeneric is used in a type parameter. is_from_type_parameter: bool, }, /// Represents a type that will be inferred by the Sway compiler. This type /// is created when the user writes code that creates a new ADT that has /// type parameters in it's definition, before type inference can determine /// what the type of those type parameters are. /// /// This type would also be created in a case where the user wrote a type /// annotation with a wildcard type, like: /// `let v: Vec<_> = iter.collect();`. /// /// The equivalent type in the Rust compiler is: /// https://doc.rust-lang.org/nightly/nightly-rustc/src/rustc_type_ir/sty.rs.html#208 Placeholder(TypeParameter), /// Represents a type created from a type parameter. /// /// NOTE: This type is *not used yet*. // https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/enum.TyKind.html#variant.Param TypeParam(TypeParameter), StringSlice, StringArray(Length), UnsignedInteger(IntegerBits), UntypedEnum(ParsedDeclId<EnumDeclaration>), UntypedStruct(ParsedDeclId<StructDeclaration>), Enum(DeclId<TyEnumDecl>), Struct(DeclId<TyStructDecl>), Boolean, Tuple(Vec<GenericTypeArgument>), /// Represents a type which contains methods to issue a contract call. /// The specific contract is identified via the `Ident` within. ContractCaller { abi_name: AbiName, // boxed for size address: Option<Box<ty::TyExpression>>, }, /// A custom type could be a struct or similar if the name is in scope, /// or just a generic parameter if it is not. /// At parse time, there is no sense of scope, so this determination is not made /// until the semantic analysis stage. Custom { qualified_call_path: QualifiedCallPath, type_arguments: Option<Vec<GenericArgument>>, }, B256, /// This means that specific type of a number is not yet known. It will be /// determined via inference at a later time. Numeric, Contract, // used for recovering from errors in the ast ErrorRecovery(ErrorEmitted), // Static, constant size arrays. Array(GenericTypeArgument, Length), /// Pointers. /// These are represented in memory as u64 but are a different type since pointers only make /// sense in the context they were created in. Users can obtain pointers via standard library /// functions such `alloc` or `stack_ptr`. These functions are implemented using asm blocks /// which can create pointers by (eg.) reading logically-pointer-valued registers, using the /// gtf instruction, or manipulating u64s. RawUntypedPtr, RawUntypedSlice, Ptr(GenericTypeArgument), Slice(GenericTypeArgument), /// Type aliases. /// This type and the type `ty` it encapsulates always coerce. They are effectively /// interchangeable. /// Currently, we support only non-generic type aliases. // TODO: (GENERIC-TYPE-ALIASES) If we ever introduce generic type aliases, update the logic // in the `TypeEngine` accordingly, e.g., the `is_type_changeable`. Alias { name: Ident, ty: GenericTypeArgument, }, TraitType { name: Ident, /// [TypeId] of the type in which this associated type is implemented. /// E.g., for `type AssociatedType = u8;` implemented in `struct Struct` /// this will be the [TypeId] of `Struct`. implemented_in: TypeId, }, Ref { to_mutable_value: bool, referenced_type: GenericTypeArgument, }, } impl HashWithEngines for TypeInfo { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { self.discriminant_value().hash(state); match self { TypeInfo::StringArray(len) => { len.expr().hash(state); } TypeInfo::UnsignedInteger(bits) => { bits.hash(state); } TypeInfo::Tuple(fields) => { fields.hash(state, engines); } TypeInfo::Enum(decl_id) => { HashWithEngines::hash(&decl_id, state, engines); } TypeInfo::Struct(decl_id) => { HashWithEngines::hash(&decl_id, state, engines); } TypeInfo::UntypedEnum(decl_id) => decl_id.unique_id().hash(state), TypeInfo::UntypedStruct(decl_id) => decl_id.unique_id().hash(state), TypeInfo::ContractCaller { abi_name, address } => { abi_name.hash(state); let address = address .as_ref() .map(|x| x.span.as_str().to_string()) .unwrap_or_default(); address.hash(state); } TypeInfo::UnknownGeneric { name, trait_constraints: _, parent: _, is_from_type_parameter: _, } => { name.hash(state); // Do not hash trait_constraints as those can point back to this type_info // This avoids infinite hash loop. More collisions should occur but // Eq implementations can disambiguate. //trait_constraints.hash(state, engines); } TypeInfo::Custom { qualified_call_path: call_path, type_arguments, } => { call_path.hash(state, engines); type_arguments.as_deref().hash(state, engines); } TypeInfo::Array(elem_ty, len) => { elem_ty.hash(state, engines); len.expr().hash(state); } TypeInfo::Placeholder(ty) => { ty.hash(state, engines); } TypeInfo::TypeParam(param) => { param.hash(state, engines); } TypeInfo::Alias { name, ty } => { name.hash(state); ty.hash(state, engines); } TypeInfo::Ptr(ty) => { ty.hash(state, engines); } TypeInfo::Slice(ty) => { ty.hash(state, engines); } TypeInfo::TraitType { name, implemented_in, } => { name.hash(state); implemented_in.hash(state); } TypeInfo::Ref { to_mutable_value, referenced_type: ty, } => { to_mutable_value.hash(state); ty.hash(state, engines); } TypeInfo::StringSlice | TypeInfo::Numeric | TypeInfo::Boolean | TypeInfo::B256 | TypeInfo::Contract | TypeInfo::ErrorRecovery(_) | TypeInfo::Unknown | TypeInfo::Never | TypeInfo::RawUntypedPtr | TypeInfo::RawUntypedSlice => {} } } } impl EqWithEngines for TypeInfo {} impl PartialEqWithEngines for TypeInfo { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { let type_engine = ctx.engines().te(); match (self, other) { ( Self::UnknownGeneric { name: l, trait_constraints: ltc, parent: _, is_from_type_parameter: _, }, Self::UnknownGeneric { name: r, trait_constraints: rtc, parent: _, is_from_type_parameter: _, }, ) => l == r && ltc.eq(rtc, ctx), (Self::Placeholder(l), Self::Placeholder(r)) => l.eq(r, ctx), (Self::TypeParam(l), Self::TypeParam(r)) => l.eq(r, ctx), ( Self::Custom { qualified_call_path: l_name, type_arguments: l_type_args, }, Self::Custom { qualified_call_path: r_name, type_arguments: r_type_args, }, ) => { l_name.call_path.suffix == r_name.call_path.suffix && l_name .qualified_path_root .eq(&r_name.qualified_path_root, ctx) && l_type_args.as_deref().eq(&r_type_args.as_deref(), ctx) } (Self::StringSlice, Self::StringSlice) => true, (Self::StringArray(l), Self::StringArray(r)) => l.expr() == r.expr(), (Self::UnsignedInteger(l), Self::UnsignedInteger(r)) => l == r, (Self::Enum(l_decl_ref), Self::Enum(r_decl_ref)) => { let l_decl = ctx.engines().de().get_enum(l_decl_ref); let r_decl = ctx.engines().de().get_enum(r_decl_ref); assert!( matches!(l_decl.call_path.callpath_type, CallPathType::Full) && matches!(r_decl.call_path.callpath_type, CallPathType::Full), "The call paths of the enum declarations must always be resolved." ); l_decl.call_path == r_decl.call_path && l_decl.variants.eq(&r_decl.variants, ctx) && l_decl .generic_parameters .eq(&r_decl.generic_parameters, ctx) } (Self::Struct(l_decl_ref), Self::Struct(r_decl_ref)) => { let l_decl = ctx.engines().de().get_struct(l_decl_ref); let r_decl = ctx.engines().de().get_struct(r_decl_ref); assert!( matches!(l_decl.call_path.callpath_type, CallPathType::Full) && matches!(r_decl.call_path.callpath_type, CallPathType::Full), "The call paths of the struct declarations must always be resolved." ); l_decl.call_path == r_decl.call_path && l_decl.fields.eq(&r_decl.fields, ctx) && l_decl .generic_parameters .eq(&r_decl.generic_parameters, ctx) } (Self::Tuple(l), Self::Tuple(r)) => l.eq(r, ctx), ( Self::ContractCaller { abi_name: l_abi_name, address: l_address, }, Self::ContractCaller { abi_name: r_abi_name, address: r_address, }, ) => { let l_address_span = l_address.as_ref().map(|x| x.span.clone()); let r_address_span = r_address.as_ref().map(|x| x.span.clone()); l_abi_name == r_abi_name && l_address_span == r_address_span } (Self::Array(l0, l1), Self::Array(r0, r1)) => { ((l0.type_id == r0.type_id) || type_engine .get(l0.type_id) .eq(&type_engine.get(r0.type_id), ctx)) && l1.expr() == r1.expr() } ( Self::Alias { name: l_name, ty: l_ty, }, Self::Alias { name: r_name, ty: r_ty, }, ) => { l_name == r_name && ((l_ty.type_id == r_ty.type_id) || type_engine .get(l_ty.type_id) .eq(&type_engine.get(r_ty.type_id), ctx)) } ( Self::TraitType { name: l_name, implemented_in: l_implemented_in, }, Self::TraitType { name: r_name, implemented_in: r_implemented_in, }, ) => { l_name == r_name && ((*l_implemented_in == *r_implemented_in) || type_engine .get(*l_implemented_in) .eq(&type_engine.get(*r_implemented_in), ctx)) } ( Self::Ref { to_mutable_value: l_to_mut, referenced_type: l_ty, }, Self::Ref { to_mutable_value: r_to_mut, referenced_type: r_ty, }, ) => { (l_to_mut == r_to_mut) && ((l_ty.type_id == r_ty.type_id) || type_engine .get(l_ty.type_id) .eq(&type_engine.get(r_ty.type_id), ctx)) } (l, r) => l.discriminant_value() == r.discriminant_value(), } } } impl OrdWithEngines for TypeInfo { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { let type_engine = ctx.engines().te(); let decl_engine = ctx.engines().de(); match (self, other) { ( Self::UnknownGeneric { name: l, trait_constraints: ltc, parent: _, is_from_type_parameter: _, }, Self::UnknownGeneric { name: r, trait_constraints: rtc, parent: _, is_from_type_parameter: _, }, ) => l.cmp(r).then_with(|| ltc.cmp(rtc, ctx)), (Self::Placeholder(l), Self::Placeholder(r)) => l.cmp(r, ctx), ( Self::Custom { qualified_call_path: l_call_path, type_arguments: l_type_args, }, Self::Custom { qualified_call_path: r_call_path, type_arguments: r_type_args, }, ) => l_call_path .call_path .suffix .cmp(&r_call_path.call_path.suffix) .then_with(|| { l_call_path .qualified_path_root .cmp(&r_call_path.qualified_path_root, ctx) }) .then_with(|| l_type_args.as_deref().cmp(&r_type_args.as_deref(), ctx)), (Self::StringArray(l), Self::StringArray(r)) => { if let Some(ord) = l.expr().partial_cmp(r.expr()) { ord } else { l.expr() .discriminant_value() .cmp(&r.expr().discriminant_value()) } } (Self::UnsignedInteger(l), Self::UnsignedInteger(r)) => l.cmp(r), (Self::Enum(l_decl_id), Self::Enum(r_decl_id)) => { let l_decl = decl_engine.get_enum(l_decl_id); let r_decl = decl_engine.get_enum(r_decl_id); l_decl .call_path .suffix .cmp(&r_decl.call_path.suffix) .then_with(|| { l_decl .generic_parameters .cmp(&r_decl.generic_parameters, ctx) }) .then_with(|| l_decl.variants.cmp(&r_decl.variants, ctx)) } (Self::Struct(l_decl_ref), Self::Struct(r_decl_ref)) => { let l_decl = decl_engine.get_struct(l_decl_ref); let r_decl = decl_engine.get_struct(r_decl_ref); l_decl .call_path .suffix .cmp(&r_decl.call_path.suffix) .then_with(|| { l_decl .generic_parameters .cmp(&r_decl.generic_parameters, ctx) }) .then_with(|| l_decl.fields.cmp(&r_decl.fields, ctx)) } (Self::Tuple(l), Self::Tuple(r)) => l.cmp(r, ctx), ( Self::ContractCaller { abi_name: l_abi_name, address: _, }, Self::ContractCaller { abi_name: r_abi_name, address: _, }, ) => { // NOTE: we assume all contract callers are unique l_abi_name.cmp(r_abi_name) } (Self::Array(l0, l1), Self::Array(r0, r1)) => type_engine .get(l0.type_id) .cmp(&type_engine.get(r0.type_id), ctx) .then_with(|| { if let Some(ord) = l1.expr().partial_cmp(r1.expr()) { ord } else { l1.expr() .discriminant_value() .cmp(&r1.expr().discriminant_value()) } }), ( Self::Alias { name: l_name, ty: l_ty, }, Self::Alias { name: r_name, ty: r_ty, }, ) => type_engine .get(l_ty.type_id) .cmp(&type_engine.get(r_ty.type_id), ctx) .then_with(|| l_name.cmp(r_name)), ( Self::TraitType { name: l_name, implemented_in: l_implemented_in, }, Self::TraitType { name: r_name, implemented_in: r_implemented_in, }, ) => l_implemented_in .cmp(r_implemented_in) .then_with(|| l_name.cmp(r_name)), ( Self::Ref { to_mutable_value: l_to_mut, referenced_type: l_ty, }, Self::Ref { to_mutable_value: r_to_mut, referenced_type: r_ty, }, ) => l_to_mut.cmp(r_to_mut).then_with(|| { type_engine .get(l_ty.type_id) .cmp(&type_engine.get(r_ty.type_id), ctx) }), (l, r) => l.discriminant_value().cmp(&r.discriminant_value()), } } } impl DisplayWithEngines for TypeInfo { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { const DISPLAY: TypeInfoDisplay = TypeInfoDisplay::full().with_alias_name(); f.write_str(&DISPLAY.display(self, engines)) } } impl DebugWithEngines for TypeInfo { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { use TypeInfo::*; let s: &str = match self { Unknown => "unknown", Never => "!", UnknownGeneric { name, trait_constraints, .. } => { let tc_str = trait_constraints .iter() .map(|tc| engines.help_out(tc).to_string()) .collect::<Vec<_>>() .join("+"); if tc_str.is_empty() { name.as_str() } else { &format!("{name}:{tc_str}") } } Placeholder(t) => &format!("placeholder({:?})", engines.help_out(t)), TypeParam(param) => &format!("typeparam({})", param.name()), StringSlice => "str", StringArray(length) => &format!("str[{:?}]", engines.help_out(length.expr()),), UnsignedInteger(x) => match x { IntegerBits::Eight => "u8", IntegerBits::Sixteen => "u16", IntegerBits::ThirtyTwo => "u32", IntegerBits::SixtyFour => "u64", IntegerBits::V256 => "u256", }, Boolean => "bool", Custom { qualified_call_path: call_path, type_arguments, .. } => { let mut s = String::new(); if let Some(type_arguments) = type_arguments { if !type_arguments.is_empty() { s = format!( "<{}>", type_arguments .iter() .map(|a| format!("{:?}", engines.help_out(a))) .collect::<Vec<_>>() .join(", ") ); } } &format!("unresolved {}{}", call_path.call_path, s) } Tuple(fields) => { let field_strs = fields .iter() .map(|field| format!("{:?}", engines.help_out(field))) .collect::<Vec<String>>(); &format!("({})", field_strs.join(", ")) } B256 => "b256", Numeric => "numeric", Contract => "contract", ErrorRecovery(_) => "unknown due to error", UntypedEnum(decl_id) => { let decl = engines.pe().get_enum(decl_id); &print_inner_types_debug( engines, decl.name.as_str(), decl.type_parameters .iter() .map(|arg| format!("{:?}", engines.help_out(arg))), ) } UntypedStruct(decl_id) => { let decl = engines.pe().get_struct(decl_id); &print_inner_types_debug( engines, decl.name.as_str(), decl.type_parameters .iter() .map(|arg| format!("{:?}", engines.help_out(arg))), ) } Enum(decl_ref) => { let decl = engines.de().get_enum(decl_ref); &print_inner_types_debug( engines, decl.call_path.suffix.as_str(), decl.generic_parameters .iter() .map(|arg| format!("{:?}", engines.help_out(arg))), ) } Struct(decl_ref) => { let decl = engines.de().get_struct(decl_ref); &print_inner_types_debug( engines, decl.call_path.suffix.as_str(), decl.generic_parameters .iter() .map(|arg| format!("{:?}", engines.help_out(arg))), ) } ContractCaller { abi_name, address } => &format!( "contract caller {} ( {} )", abi_name, address.as_ref().map_or_else( || "None".into(), |address| address.span.as_str().to_string() ) ), Array(elem_ty, length) => &format!( "[{:?}; {:?}]", engines.help_out(elem_ty), engines.help_out(length.expr()), ), RawUntypedPtr => "raw untyped ptr", RawUntypedSlice => "raw untyped slice", Ptr(ty) => &format!("__ptr[{:?}]", engines.help_out(ty)), Slice(ty) => &format!("__slice[{:?}]", engines.help_out(ty)), Alias { name, ty } => &format!("type {} = {:?}", name, engines.help_out(ty)), TraitType { name, implemented_in, } => &format!("trait type {}::{}", engines.help_out(implemented_in), name), Ref { to_mutable_value, referenced_type: ty, } => &format!( "&{}{:?}", if *to_mutable_value { "mut " } else { "" }, engines.help_out(ty) ), }; write!(f, "{s}") } } impl GetCallPathWithEngines for TypeInfo { fn call_path(&self, engines: &Engines) -> Option<CallPath> { match self { TypeInfo::Unknown => None, TypeInfo::Never => None, TypeInfo::UnknownGeneric { .. } => None, TypeInfo::Placeholder(_type_parameter) => None, TypeInfo::TypeParam(_type_parameter) => None, TypeInfo::StringSlice => None, TypeInfo::StringArray(_numeric_length) => None, TypeInfo::UnsignedInteger(_integer_bits) => None, TypeInfo::UntypedEnum(_parsed_decl_id) => todo!(), TypeInfo::UntypedStruct(_parsed_decl_id) => todo!(), TypeInfo::Enum(decl_id) => Some(engines.de().get_enum(decl_id).call_path.clone()), TypeInfo::Struct(decl_id) => Some(engines.de().get_struct(decl_id).call_path.clone()), TypeInfo::Boolean => None, TypeInfo::Tuple(_generic_arguments) => None, TypeInfo::ContractCaller { .. } => None, TypeInfo::Custom { qualified_call_path, .. } => Some(qualified_call_path.call_path.clone()), TypeInfo::B256 => None, TypeInfo::Numeric => None, TypeInfo::Contract => None, TypeInfo::ErrorRecovery(_error_emitted) => None, TypeInfo::Array(_generic_argument, _length) => None, TypeInfo::RawUntypedPtr => None, TypeInfo::RawUntypedSlice => None, TypeInfo::Ptr(ty) => ty .call_path_tree .as_ref() .map(|v| v.qualified_call_path.call_path.clone()), TypeInfo::Slice(ty) => ty .call_path_tree .as_ref() .map(|v| v.qualified_call_path.call_path.clone()), TypeInfo::Alias { name: _, ty } => ty .call_path_tree .as_ref() .map(|v| v.qualified_call_path.call_path.clone()), TypeInfo::TraitType { name: _, implemented_in, } => engines.te().get(*implemented_in).call_path(engines), TypeInfo::Ref { to_mutable_value: _, referenced_type, } => referenced_type .call_path_tree .as_ref() .map(|v| v.qualified_call_path.call_path.clone()), } } } impl TypeInfo { /// Returns a discriminant for the variant. // NOTE: This is approach is not the most straightforward, but is needed // because of this missing feature on Rust's `Discriminant` type: // https://github.com/rust-lang/rust/pull/106418 fn discriminant_value(&self) -> u8 { match self { TypeInfo::Unknown => 0, TypeInfo::UnknownGeneric { .. } => 1, TypeInfo::Placeholder(_) => 2, TypeInfo::StringArray(_) => 3, TypeInfo::UnsignedInteger(_) => 4, TypeInfo::Enum { .. } => 5, TypeInfo::Struct { .. } => 6, TypeInfo::Boolean => 7, TypeInfo::Tuple(_) => 8, TypeInfo::ContractCaller { .. } => 9, TypeInfo::Custom { .. } => 10, TypeInfo::B256 => 11, TypeInfo::Numeric => 12, TypeInfo::Contract => 13, TypeInfo::ErrorRecovery(_) => 14, TypeInfo::Array(_, _) => 15, TypeInfo::RawUntypedPtr => 16, TypeInfo::RawUntypedSlice => 17, TypeInfo::TypeParam(_) => 18, TypeInfo::Alias { .. } => 19, TypeInfo::Ptr(..) => 20, TypeInfo::Slice(..) => 21, TypeInfo::StringSlice => 22, TypeInfo::TraitType { .. } => 23, TypeInfo::Ref { .. } => 24, TypeInfo::Never => 25, TypeInfo::UntypedEnum(_) => 26, TypeInfo::UntypedStruct(_) => 27, } } /// Creates a new [TypeInfo::Custom] that represents a Self type. /// /// The `span` must either be a [Span::dummy] or a span pointing /// to text "Self" or "self", otherwise the method panics. pub(crate) fn new_self_type(span: Span) -> TypeInfo { assert!( span.is_dummy() || span.as_str() == "Self" || span.as_str() == "self", "The Self type span must either be a dummy span, or a span pointing to text \"Self\" or \"self\". The span was pointing to text: \"{}\".", span.as_str() ); TypeInfo::Custom { qualified_call_path: QualifiedCallPath { call_path: CallPath { prefixes: vec![], suffix: Ident::new_with_override("Self".into(), span), callpath_type: CallPathType::Ambiguous, }, qualified_path_root: None, }, type_arguments: None, } } pub(crate) fn is_self_type(&self) -> bool { match self { TypeInfo::UnknownGeneric { name, .. } => { name.as_str() == "Self" || name.as_str() == "self" } TypeInfo::Custom { qualified_call_path, .. } => { qualified_call_path.call_path.suffix.as_str() == "Self" || qualified_call_path.call_path.suffix.as_str() == "self" }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/mod.rs
sway-core/src/type_system/mod.rs
pub mod ast_elements; mod engine; mod id; mod info; pub(crate) mod monomorphization; mod priv_prelude; mod substitute; pub(crate) mod unify; #[allow(unused)] use std::ops::Deref; pub use substitute::subst_types::SubstTypesContext; #[cfg(test)] use crate::language::{CallPath, CallPathType}; #[cfg(test)] use crate::{language::ty::TyEnumDecl, transform::Attributes}; pub use priv_prelude::*; #[cfg(test)] use sway_error::handler::Handler; #[cfg(test)] use sway_types::BaseIdent; #[cfg(test)] use sway_types::{integer_bits::IntegerBits, Span}; /// This type is used to denote if, during monomorphization, the compiler /// should enforce that type arguments be provided. An example of that /// might be this: /// /// ```ignore /// struct Point<T> { /// x: u64, /// y: u64 /// } /// /// fn add<T>(p1: Point<T>, p2: Point<T>) -> Point<T> { /// Point { /// x: p1.x + p2.x, /// y: p1.y + p2.y /// } /// } /// ``` /// /// `EnforceTypeArguments` would require that the type annotations /// for `p1` and `p2` contain `<...>`. This is to avoid ambiguous definitions: /// /// ```ignore /// fn add(p1: Point, p2: Point) -> Point { /// Point { /// x: p1.x + p2.x, /// y: p1.y + p2.y /// } /// } /// ``` #[derive(Clone, Copy)] pub(crate) enum EnforceTypeArguments { Yes, No, } #[test] fn generic_enum_resolution() { use crate::{ decl_engine::DeclEngineInsert, language::ty, span::Span, transform, Engines, Ident, }; use ast_elements::type_argument::GenericTypeArgument; use ast_elements::type_parameter::GenericTypeParameter; let engines = Engines::default(); let sp = Span::dummy(); let generic_name = Ident::new_with_override("T".into(), sp.clone()); let a_name = Ident::new_with_override("a".into(), sp.clone()); let result_name = Ident::new_with_override("Result".into(), sp.clone()); /* Result<_> { a: _ } */ let generic_type = engines .te() .new_unknown_generic(generic_name.clone(), VecSet(vec![]), None, false); let placeholder_type = engines .te() .new_placeholder(TypeParameter::Type(GenericTypeParameter { type_id: generic_type, initial_type_id: generic_type, name: generic_name.clone(), trait_constraints: vec![], trait_constraints_span: sp.clone(), is_from_parent: false, })); let placeholder_type_param = TypeParameter::Type(GenericTypeParameter { type_id: placeholder_type, initial_type_id: placeholder_type, name: generic_name.clone(), trait_constraints: vec![], trait_constraints_span: sp.clone(), is_from_parent: false, }); let variant_types = vec![ty::TyEnumVariant { name: a_name.clone(), tag: 0, type_argument: GenericTypeArgument { type_id: placeholder_type, initial_type_id: placeholder_type, span: sp.clone(), call_path_tree: None, }, span: sp.clone(), attributes: transform::Attributes::default(), }]; let mut call_path: CallPath<BaseIdent> = result_name.clone().into(); call_path.callpath_type = CallPathType::Full; let decl_ref_1 = engines.de().insert( TyEnumDecl { call_path, generic_parameters: vec![placeholder_type_param], variants: variant_types, span: sp.clone(), visibility: crate::language::Visibility::Public, attributes: Attributes::default(), }, None, ); let ty_1 = engines.te().insert_enum(&engines, *decl_ref_1.id()); /* Result<bool> { a: bool } */ let boolean_type = engines.te().id_of_bool(); let variant_types = vec![ty::TyEnumVariant { name: a_name, tag: 0, type_argument: GenericTypeArgument { type_id: boolean_type, initial_type_id: boolean_type, span: sp.clone(), call_path_tree: None, }, span: sp.clone(), attributes: transform::Attributes::default(), }]; let type_param = TypeParameter::Type(GenericTypeParameter { type_id: boolean_type, initial_type_id: boolean_type, name: generic_name, trait_constraints: vec![], trait_constraints_span: sp.clone(), is_from_parent: false, }); let mut call_path: CallPath<BaseIdent> = result_name.into(); call_path.callpath_type = CallPathType::Full; let decl_ref_2 = engines.de().insert( TyEnumDecl { call_path, generic_parameters: vec![type_param], variants: variant_types.clone(), span: sp.clone(), visibility: crate::language::Visibility::Public, attributes: Attributes::default(), }, None, ); let ty_2 = engines.te().insert_enum(&engines, *decl_ref_2.id()); // Unify them together... let h = Handler::default(); engines .te() .unify(&h, &engines, ty_1, ty_2, &sp, "", || None); let (errors, _warnings, _infos) = h.consume(); assert!(errors.is_empty()); if let TypeInfo::Enum(decl_ref_1) = &*engines.te().get(ty_1) { let decl = engines.de().get_enum(decl_ref_1); assert_eq!(decl.call_path.suffix.as_str(), "Result"); assert!(matches!( &*engines.te().get(variant_types[0].type_argument.type_id), TypeInfo::Boolean )); } else { panic!() } } #[test] fn basic_numeric_unknown() { use crate::Engines; let engines = Engines::default(); let sp = Span::dummy(); // numerics let id = engines.te().new_numeric(); let id2 = engines.te().id_of_u8(); // Unify them together... let h = Handler::default(); engines.te().unify(&h, &engines, id, id2, &sp, "", || None); let (errors, _warnings, _infos) = h.consume(); assert!(errors.is_empty()); assert!(matches!( engines.te().to_typeinfo(id, &Span::dummy()).unwrap(), TypeInfo::UnsignedInteger(IntegerBits::Eight) )); } #[test] fn unify_numerics() { use crate::Engines; let engines = Engines::default(); let sp = Span::dummy(); // numerics let id = engines.te().new_numeric(); let id2 = engines.te().id_of_u8(); // Unify them together... let h = Handler::default(); engines.te().unify(&h, &engines, id2, id, &sp, "", || None); let (errors, _warnings, _infos) = h.consume(); assert!(errors.is_empty()); assert!(matches!( engines.te().to_typeinfo(id, &Span::dummy()).unwrap(), TypeInfo::UnsignedInteger(IntegerBits::Eight) )); } #[test] fn unify_numerics_2() { use crate::Engines; let engines = Engines::default(); let type_engine = engines.te(); let sp = Span::dummy(); // numerics let id = engines.te().new_numeric(); let id2 = engines.te().id_of_u8(); // Unify them together... let h = Handler::default(); type_engine.unify(&h, &engines, id, id2, &sp, "", || None); let (errors, _warnings, _infos) = h.consume(); assert!(errors.is_empty()); assert!(matches!( type_engine.to_typeinfo(id, &Span::dummy()).unwrap(), TypeInfo::UnsignedInteger(IntegerBits::Eight) )); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/ast_elements/type_parameter.rs
sway-core/src/type_system/ast_elements/type_parameter.rs
use crate::{ abi_generation::abi_str::AbiStrContext, decl_engine::{ parsed_id::ParsedDeclId, DeclEngineGet, DeclEngineInsert as _, DeclMapping, InterfaceItemMap, ItemMap, MaterializeConstGenerics, ParsedDeclEngineGet as _, }, engine_threading::*, has_changes, language::{ parsed::ConstGenericDeclaration, ty::{ self, ConstGenericDecl, ConstantDecl, TyConstGenericDecl, TyConstantDecl, TyExpression, TyExpressionVariant, }, CallPath, CallPathType, }, namespace::TraitMap, semantic_analysis::{GenericShadowingMode, TypeCheckContext}, type_system::priv_prelude::*, }; use serde::{Deserialize, Serialize}; use std::{ borrow::Cow, cmp::Ordering, collections::{BTreeMap, HashMap}, fmt, hash::{Hash, Hasher}, }; use sway_error::{ error::CompileError, handler::{ErrorEmitted, Handler}, }; use sway_types::{ident::Ident, span::Span, BaseIdent, Named, Spanned}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum TypeParameter { Type(GenericTypeParameter), Const(ConstGenericParameter), } impl TypeParameter { pub(crate) fn insert_into_namespace_constraints( &self, handler: &Handler, mut ctx: TypeCheckContext, ) -> Result<(), ErrorEmitted> { // Insert the trait constraints into the namespace. match self { TypeParameter::Type(p) => { for trait_constraint in &p.trait_constraints { TraitConstraint::insert_into_namespace( handler, ctx.by_ref(), p.type_id, trait_constraint, )?; } } TypeParameter::Const(_) => {} } Ok(()) } pub(crate) fn insert_into_namespace_self( &self, handler: &Handler, mut ctx: TypeCheckContext, ) -> Result<(), ErrorEmitted> { let (is_from_parent, name, type_id, ty_decl) = match self { TypeParameter::Type(GenericTypeParameter { is_from_parent, name, type_id, .. }) => ( is_from_parent, name, *type_id, ty::TyDecl::GenericTypeForFunctionScope(ty::GenericTypeForFunctionScope { name: name.clone(), type_id: *type_id, }), ), TypeParameter::Const(ConstGenericParameter { is_from_parent, name, id, span, ty, .. }) => { let decl_ref = ctx.engines.de().insert( TyConstGenericDecl { call_path: CallPath { prefixes: vec![], suffix: name.clone(), callpath_type: CallPathType::Ambiguous, }, span: span.clone(), return_type: *ty, value: None, }, id.as_ref(), ); ( is_from_parent, name, ctx.engines.te().id_of_u64(), ty::TyDecl::ConstGenericDecl(ConstGenericDecl { decl_id: *decl_ref.id(), }), ) } }; if *is_from_parent { ctx = ctx.with_generic_shadowing_mode(GenericShadowingMode::Allow); let (resolve_declaration, _) = ctx.namespace() .current_module() .resolve_symbol(handler, ctx.engines(), name)?; match resolve_declaration.expect_typed_ref() { ty::TyDecl::GenericTypeForFunctionScope(ty::GenericTypeForFunctionScope { type_id: parent_type_id, .. }) => { if let TypeInfo::UnknownGeneric { name, trait_constraints, parent, is_from_type_parameter, } = &*ctx.engines().te().get(type_id) { if parent.is_some() { return Ok(()); } ctx.engines.te().replace( ctx.engines(), type_id, TypeInfo::UnknownGeneric { name: name.clone(), trait_constraints: trait_constraints.clone(), parent: Some(*parent_type_id), is_from_type_parameter: *is_from_type_parameter, }, ); } } ty::TyDecl::ConstGenericDecl(_) => {} _ => { handler.emit_err(CompileError::Internal( "Unexpected TyDeclaration for TypeParameter.", name.span(), )); } } } // Insert the type parameter into the namespace as a dummy type // declaration. ctx.insert_symbol(handler, name.clone(), ty_decl).ok(); Ok(()) } pub(crate) fn unifies( &self, type_id: TypeId, decider: impl Fn(TypeId, TypeId) -> bool, ) -> bool { match self { TypeParameter::Type(generic_type_parameter) => { decider(type_id, generic_type_parameter.type_id) } TypeParameter::Const(const_generic_parameter) => { decider(type_id, const_generic_parameter.ty) } } } } impl Named for TypeParameter { fn name(&self) -> &BaseIdent { match self { TypeParameter::Type(p) => &p.name, TypeParameter::Const(p) => &p.name, } } } impl EqWithEngines for TypeParameter {} impl PartialEqWithEngines for TypeParameter { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { match (self, other) { (TypeParameter::Type(l), TypeParameter::Type(r)) => l.eq(r, ctx), (TypeParameter::Const(l), TypeParameter::Const(r)) => { <ConstGenericParameter as PartialEqWithEngines>::eq(l, r, ctx) } _ => false, } } } impl HashWithEngines for TypeParameter { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { std::mem::discriminant(self).hash(state); match self { TypeParameter::Type(p) => p.hash(state, engines), TypeParameter::Const(p) => p.hash(state, engines), } } } impl SubstTypes for TypeParameter { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { match self { TypeParameter::Type(p) => p.subst_inner(ctx), TypeParameter::Const(p) => p.subst_inner(ctx), } } } impl IsConcrete for TypeParameter { fn is_concrete(&self, handler: &Handler, engines: &Engines) -> bool { match self { TypeParameter::Type(p) => p.is_concrete(handler, engines), TypeParameter::Const(p) => p.is_concrete(handler, engines), } } } impl OrdWithEngines for TypeParameter { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { match (self, other) { (TypeParameter::Type(l), TypeParameter::Type(r)) => l.cmp(r, ctx), (TypeParameter::Const(l), TypeParameter::Const(r)) => l.cmp(r), _ => todo!(), } } } impl DebugWithEngines for TypeParameter { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { let s = match self { TypeParameter::Type(p) => { format!( "{:?} -> {:?}", engines.help_out(p.initial_type_id), engines.help_out(p.type_id) ) } TypeParameter::Const(p) => match p.expr.as_ref() { Some(ConstGenericExpr::Literal { val, .. }) => format!("{} -> {}", p.name, val), Some(ConstGenericExpr::AmbiguousVariableExpression { ident, .. }) => { format!("{ident}") } None => format!("{} -> None", p.name), }, }; write!(f, "{s}") } } impl TypeParameter { pub fn as_type_parameter(&self) -> Option<&GenericTypeParameter> { match self { TypeParameter::Type(p) => Some(p), TypeParameter::Const(_) => None, } } pub fn as_type_parameter_mut(&mut self) -> Option<&mut GenericTypeParameter> { match self { TypeParameter::Type(p) => Some(p), TypeParameter::Const(_) => None, } } pub fn abi_str( &self, handler: &Handler, engines: &Engines, ctx: &AbiStrContext, is_root: bool, ) -> Result<String, ErrorEmitted> { match self { TypeParameter::Type(p) => engines .te() .get(p.type_id) .abi_str(handler, ctx, engines, is_root), TypeParameter::Const(_) => Err(handler.emit_err(CompileError::Internal( "Unexpected error on const generics", match self { TypeParameter::Type(p) => p.name.span(), TypeParameter::Const(p) => p.span.clone(), }, ))), } } pub fn as_const_parameter(&self) -> Option<&ConstGenericParameter> { match self { TypeParameter::Type(_) => None, TypeParameter::Const(p) => Some(p), } } pub fn as_const_parameter_mut(&mut self) -> Option<&mut ConstGenericParameter> { match self { TypeParameter::Type(_) => None, TypeParameter::Const(p) => Some(p), } } pub fn is_from_parent(&self) -> bool { match self { TypeParameter::Type(p) => p.is_from_parent, TypeParameter::Const(p) => p.is_from_parent, } } pub fn with_is_from_parent(self, is_from_parent: bool) -> Self { match self { TypeParameter::Type(mut p) => { p.is_from_parent = is_from_parent; TypeParameter::Type(p) } TypeParameter::Const(mut p) => { p.is_from_parent = is_from_parent; TypeParameter::Const(p) } } } } /// [GenericTypeParameter] describes a generic type parameter, including its /// monomorphized version. It holds the `name` of the parameter, its /// `type_id`, and the `initial_type_id`, as well as an additional /// information about that type parameter, called the annotation. /// /// If a [GenericTypeParameter] is considered as not being annotated, /// its `initial_type_id` must be same as `type_id`, its /// `trait_constraints_span` must be [Span::dummy] /// and its `is_from_parent` must be false. /// /// The annotations are ignored when calculating the [GenericTypeParameter]'s hash /// (with engines) and equality (with engines). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GenericTypeParameter { pub type_id: TypeId, /// Denotes the initial type represented by the [GenericTypeParameter], before /// unification, monomorphization, or replacement of [TypeInfo::Custom]s. pub(crate) initial_type_id: TypeId, pub name: Ident, pub(crate) trait_constraints: Vec<TraitConstraint>, pub(crate) trait_constraints_span: Span, pub(crate) is_from_parent: bool, } impl GenericTypeParameter { /// Returns true if `self` is annotated by heaving either /// its [Self::initial_type_id] different from [Self::type_id], /// or [Self::trait_constraints_span] different from [Span::dummy] /// or [Self::is_from_parent] different from false. pub fn is_annotated(&self) -> bool { self.type_id != self.initial_type_id || self.is_from_parent || !self.trait_constraints_span.is_dummy() } } impl HashWithEngines for GenericTypeParameter { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { let GenericTypeParameter { type_id, name, trait_constraints, // these fields are not hashed because they aren't relevant/a // reliable source of obj v. obj distinction trait_constraints_span: _, initial_type_id: _, is_from_parent: _, } = self; let type_engine = engines.te(); type_engine.get(*type_id).hash(state, engines); name.hash(state); trait_constraints.hash(state, engines); } } impl EqWithEngines for GenericTypeParameter {} impl PartialEqWithEngines for GenericTypeParameter { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { let type_engine = ctx.engines().te(); type_engine .get(self.type_id) .eq(&type_engine.get(other.type_id), ctx) && self.name == other.name && self.trait_constraints.eq(&other.trait_constraints, ctx) } } impl OrdWithEngines for GenericTypeParameter { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { let GenericTypeParameter { type_id: lti, name: lname, trait_constraints: ltc, // these fields are not compared because they aren't relevant/a // reliable source of obj v. obj distinction trait_constraints_span: _, initial_type_id: _, is_from_parent: _, } = &self; let GenericTypeParameter { type_id: rti, name: rn, trait_constraints: rtc, // these fields are not compared because they aren't relevant/a // reliable source of obj v. obj distinction trait_constraints_span: _, initial_type_id: _, is_from_parent: _, } = &other; let type_engine = ctx.engines().te(); let ltype = type_engine.get(*lti); let rtype = type_engine.get(*rti); ltype .cmp(&rtype, ctx) .then_with(|| lname.cmp(rn).then_with(|| ltc.cmp(rtc, ctx))) } } impl SubstTypes for GenericTypeParameter { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { has_changes! { self.type_id.subst(ctx); self.trait_constraints.subst(ctx); } } } impl Spanned for GenericTypeParameter { fn span(&self) -> Span { self.name.span() } } impl IsConcrete for GenericTypeParameter { fn is_concrete(&self, _: &Handler, engines: &Engines) -> bool { self.type_id.is_concrete(engines, TreatNumericAs::Concrete) } } impl DebugWithEngines for GenericTypeParameter { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { write!(f, "{}", self.name)?; if !self.trait_constraints.is_empty() { write!( f, ":{}", self.trait_constraints .iter() .map(|c| format!("{:?}", engines.help_out(c))) .collect::<Vec<_>>() .join("+") )?; } Ok(()) } } impl GenericTypeParameter { /// Creates a new [GenericTypeParameter] that represents a `Self` type. /// The returned type parameter will have its [GenericTypeParameter::name] /// set to "Self" with the provided `use_site_span`. /// /// `Self` type is a [TypeInfo::UnknownGeneric] and therefore [GenericTypeParameter::type_id]s /// will be set to newly created unknown generic type. /// /// Note that the span in general does not point to a reserved word "Self" in /// the source code, nor is related to it. The `Self` type represents the type /// in `impl`s and does not necessarily relate to the "Self" keyword in code. /// /// Therefore, *the span must always point to a location in the source file in which /// the particular `Self` type is, e.g., being declared or implemented*. pub(crate) fn new_self_type(engines: &Engines, use_site_span: Span) -> GenericTypeParameter { let type_engine = engines.te(); let (type_id, name) = type_engine.new_unknown_generic_self(use_site_span, true); GenericTypeParameter { type_id, initial_type_id: type_id, name, trait_constraints: vec![], trait_constraints_span: Span::dummy(), is_from_parent: false, } } /// Creates a new [TypeParameter] specifically to be used as the type parameter /// for a [TypeInfo::Placeholder]. The returned type parameter will have its /// [TypeParameter::name] set to "_" with the provided `placeholder_or_use_site_span` /// and its [TypeParameter::type_id]s set to the `type_id`. /// /// Note that in the user written code, the span will always point to the place in /// the source code where "_" is located. In the compiler generated code that is not always the case /// be the case. For cases when the span does not point to "_" see the comments /// in the usages of this method. /// /// However, *the span must always point to a location in the source file in which /// the particular placeholder is considered to be used*. pub(crate) fn new_placeholder( type_id: TypeId, placeholder_or_use_site_span: Span, ) -> GenericTypeParameter { GenericTypeParameter { type_id, initial_type_id: type_id, name: BaseIdent::new_with_override("_".into(), placeholder_or_use_site_span), trait_constraints: vec![], trait_constraints_span: Span::dummy(), is_from_parent: false, } } pub(crate) fn insert_self_type_into_namespace( &self, handler: &Handler, mut ctx: TypeCheckContext, ) { let type_parameter_decl = ty::TyDecl::GenericTypeForFunctionScope(ty::GenericTypeForFunctionScope { name: self.name.clone(), type_id: self.type_id, }); let name_a = Ident::new_with_override("self".into(), self.name.span()); let name_b = Ident::new_with_override("Self".into(), self.name.span()); let _ = ctx.insert_symbol(handler, name_a, type_parameter_decl.clone()); let _ = ctx.insert_symbol(handler, name_b, type_parameter_decl); } /// Type check a list of [TypeParameter] and return a new list of /// [TypeParameter]. This will also insert this new list into the current /// namespace. pub(crate) fn type_check_type_params( handler: &Handler, mut ctx: TypeCheckContext, generic_params: Vec<TypeParameter>, self_type_param: Option<GenericTypeParameter>, ) -> Result<Vec<TypeParameter>, ErrorEmitted> { let mut new_generic_params: Vec<TypeParameter> = vec![]; if let Some(self_type_param) = self_type_param.clone() { self_type_param.insert_self_type_into_namespace(handler, ctx.by_ref()); } handler.scope(|handler| { let mut already_declared = HashMap::new(); for p in generic_params { let p = match p { TypeParameter::Type(p) => { match GenericTypeParameter::type_check(handler, ctx.by_ref(), p) { Ok(res) => res, Err(_) => continue, } } TypeParameter::Const(p) => { if let Some(old) = already_declared.insert(p.name.clone(), p.span.clone()) { let (old, new) = if old < p.span { (old, p.span.clone()) } else { (p.span.clone(), old) }; handler.emit_err(CompileError::MultipleDefinitionsOfConstant { name: p.name.clone(), new, old, }); } TypeParameter::Const(p.clone()) } }; p.insert_into_namespace_self(handler, ctx.by_ref())?; new_generic_params.push(p) } // Type check trait constraints only after type checking all type parameters. // This is required because a trait constraint may use other type parameters. // Ex: `struct Struct2<A, B> where A : MyAdd<B>` for type_parameter in new_generic_params.iter_mut() { match type_parameter { TypeParameter::Type(type_parameter) => { GenericTypeParameter::type_check_trait_constraints( handler, ctx.by_ref(), type_parameter, )?; } TypeParameter::Const(_) => {} } type_parameter.insert_into_namespace_constraints(handler, ctx.by_ref())?; } Ok(new_generic_params) }) } // Expands a trait constraint to include all its supertraits. // Another way to incorporate this info would be at the level of unification, // we would check that two generic type parameters should unify when // the left one is a supertrait of the right one (at least in the NonDynamicEquality mode) fn expand_trait_constraints( handler: &Handler, ctx: &TypeCheckContext, tc: &TraitConstraint, ) -> Vec<TraitConstraint> { match ctx.resolve_call_path(handler, &tc.trait_name).ok() { Some(ty::TyDecl::TraitDecl(ty::TraitDecl { decl_id, .. })) => { let trait_decl = ctx.engines.de().get_trait(&decl_id); let mut result = vec![tc.clone()]; result.extend( trait_decl .supertraits .iter() .flat_map(|supertrait| { GenericTypeParameter::expand_trait_constraints( handler, ctx, &TraitConstraint { trait_name: supertrait.name.clone(), type_arguments: tc.type_arguments.clone(), }, ) }) .collect::<Vec<TraitConstraint>>(), ); result } _ => vec![tc.clone()], } } /// Type checks a [TypeParameter] (excluding its [TraitConstraint]s) and /// inserts into into the current namespace. fn type_check( handler: &Handler, ctx: TypeCheckContext, type_parameter: GenericTypeParameter, ) -> Result<TypeParameter, ErrorEmitted> { let type_engine = ctx.engines.te(); let GenericTypeParameter { initial_type_id, name, trait_constraints, trait_constraints_span, is_from_parent, type_id, } = type_parameter; let trait_constraints_with_supertraits: Vec<TraitConstraint> = trait_constraints .iter() .flat_map(|tc| GenericTypeParameter::expand_trait_constraints(handler, &ctx, tc)) .collect(); let parent = if let TypeInfo::UnknownGeneric { name: _, trait_constraints: _, parent, is_from_type_parameter: _, } = &*type_engine.get(type_id) { *parent } else { None }; // Create type id and type parameter before type checking trait constraints. // This order is required because a trait constraint may depend on its own type parameter. let type_id = type_engine.new_unknown_generic( name.clone(), VecSet(trait_constraints_with_supertraits.clone()), parent, true, ); let type_parameter = GenericTypeParameter { name, type_id, initial_type_id, trait_constraints, trait_constraints_span: trait_constraints_span.clone(), is_from_parent, }; // Insert the type parameter into the namespace Ok(TypeParameter::Type(type_parameter)) } /// Type checks a [TypeParameter] [TraitConstraint]s and /// inserts them into into the current namespace. fn type_check_trait_constraints( handler: &Handler, mut ctx: TypeCheckContext, type_parameter: &mut GenericTypeParameter, ) -> Result<(), ErrorEmitted> { let type_engine = ctx.engines.te(); let mut trait_constraints_with_supertraits: Vec<TraitConstraint> = type_parameter .trait_constraints .iter() .flat_map(|tc| GenericTypeParameter::expand_trait_constraints(handler, &ctx, tc)) .collect(); // Type check the trait constraints. for trait_constraint in &mut trait_constraints_with_supertraits { trait_constraint.type_check(handler, ctx.by_ref())?; } // TODO: add check here to see if the type parameter has a valid name and does not have type parameters let parent = if let TypeInfo::UnknownGeneric { name: _, trait_constraints: _, parent, is_from_type_parameter: _, } = &*type_engine.get(type_parameter.type_id) { *parent } else { None }; // Trait constraints mutate so we replace the previous type id associated TypeInfo. type_engine.replace( ctx.engines(), type_parameter.type_id, TypeInfo::UnknownGeneric { name: type_parameter.name.clone(), trait_constraints: VecSet(trait_constraints_with_supertraits.clone()), parent, is_from_type_parameter: true, }, ); type_parameter.trait_constraints = trait_constraints_with_supertraits; Ok(()) } /// Creates a [DeclMapping] from a list of [TypeParameter]s. /// `function_name` and `access_span` are used only for error reporting. pub(crate) fn gather_decl_mapping_from_trait_constraints( handler: &Handler, mut ctx: TypeCheckContext, type_parameters: &[TypeParameter], function_name: &str, access_span: &Span, ) -> Result<DeclMapping, ErrorEmitted> { let mut interface_item_refs: InterfaceItemMap = BTreeMap::new(); let mut item_refs: ItemMap = BTreeMap::new(); let mut impld_item_refs: ItemMap = BTreeMap::new(); let engines = ctx.engines(); handler.scope(|handler| { for type_param in type_parameters.iter().filter_map(|x| x.as_type_parameter()) { let GenericTypeParameter { type_id, trait_constraints, .. } = type_param; let code_block_first_pass = ctx.code_block_first_pass(); if !code_block_first_pass { // Tries to unify type id with a single existing trait implementation. // If more than one implementation exists we throw an error. // We only try to do the type inference from trait with a single trait constraint. if !type_id.is_concrete(engines, TreatNumericAs::Concrete) && trait_constraints.len() == 1 { let concrete_trait_type_ids : Vec<(TypeId, String)>= TraitMap::get_trait_constraints_are_satisfied_for_types( ctx .namespace() .current_module(), handler, *type_id, trait_constraints, engines, )? .into_iter() .filter_map(|t| { if t.0.is_concrete(engines, TreatNumericAs::Concrete) { Some(t) } else { None } }).collect(); match concrete_trait_type_ids.len().cmp(&1) { Ordering::Equal => { ctx.engines.te().unify_with_generic( handler, engines, *type_id, concrete_trait_type_ids.first().unwrap().0, access_span, "Type parameter type does not match up with matched trait implementing type.", || None, ); } Ordering::Greater => { return Err(handler.emit_err(CompileError::MultipleImplsSatisfyingTraitForType{ span:access_span.clone(), type_annotation: engines.help_out(type_id).to_string(), trait_names: trait_constraints.iter().map(|t| t.to_display_name(engines, ctx.namespace())).collect(), trait_types_and_names: concrete_trait_type_ids.iter().map(|t| (engines.help_out(t.0).to_string(), t.1.clone())).collect::<Vec<_>>() })); } Ordering::Less => { } } } // Check to see if the trait constraints are satisfied. match TraitMap::check_if_trait_constraints_are_satisfied_for_type( handler, ctx.namespace_mut().current_module_mut(), *type_id, trait_constraints, access_span, engines, ) { Ok(res) => { res }, Err(_) => { continue }, } } for trait_constraint in trait_constraints { let TraitConstraint { trait_name, type_arguments: trait_type_arguments, } = trait_constraint; let Ok((mut trait_interface_item_refs, mut trait_item_refs, mut trait_impld_item_refs)) = handle_trait( handler, &ctx, *type_id, trait_name, trait_type_arguments, function_name, access_span.clone(), ) else { continue; }; interface_item_refs.append(&mut trait_interface_item_refs); item_refs.append(&mut trait_item_refs); impld_item_refs.append(&mut trait_impld_item_refs); } } let decl_mapping = DeclMapping::from_interface_and_item_and_impld_decl_refs( interface_item_refs, item_refs, impld_item_refs, ); Ok(decl_mapping) }) } } fn handle_trait( handler: &Handler, ctx: &TypeCheckContext, type_id: TypeId, trait_name: &CallPath, type_arguments: &[GenericArgument], function_name: &str,
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/ast_elements/mod.rs
sway-core/src/type_system/ast_elements/mod.rs
pub mod binding; pub(crate) mod create_type_id; pub(crate) mod length; pub(crate) mod trait_constraint; pub(crate) mod type_argument; pub(crate) mod type_parameter;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/ast_elements/binding.rs
sway-core/src/type_system/ast_elements/binding.rs
use std::collections::BTreeMap; use crate::{ decl_engine::{ parsed_id::ParsedDeclId, DeclEngineGetParsedDeclId, DeclEngineInsert, DeclId, DeclRef, }, engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext}, language::{ parsed::{FunctionDeclaration, StructDeclaration}, ty, CallPath, QualifiedCallPath, }, semantic_analysis::{ symbol_resolve::ResolveSymbols, symbol_resolve_context::SymbolResolveContext, TypeCheckContext, }, type_system::priv_prelude::*, EnforceTypeArguments, Ident, }; use serde::{Deserialize, Serialize}; use sway_ast::Intrinsic; use sway_error::handler::{ErrorEmitted, Handler}; use sway_types::{Span, Spanned}; /// A `TypeBinding` is the result of using turbofish to bind types to /// generic parameters. /// /// For example: /// /// ```ignore /// let data = Data::<bool> { /// value: true /// }; /// ``` /// /// Would produce the type binding (in pseudocode): /// /// ```ignore /// TypeBinding { /// inner: CallPath(["Data"]), /// type_arguments: [bool] /// } /// ``` /// /// --- /// /// Further: /// /// ```ignore /// struct Data<T> { /// value: T /// } /// /// let data1 = Data { /// value: true /// }; /// /// let data2 = Data::<bool> { /// value: true /// }; /// /// let data3: Data<bool> = Data { /// value: true /// }; /// /// let data4: Data<bool> = Data::<bool> { /// value: true /// }; /// ``` /// /// Each of these 4 examples generates a valid struct expression for `Data` /// and passes type checking. But each does so in a unique way: /// - `data1` has no type ascription and no type arguments in the `TypeBinding`, /// so both are inferred from the value passed to `value` /// - `data2` has no type ascription but does have type arguments in the /// `TypeBinding`, so the type ascription and type of the value passed to /// `value` are both unified to the `TypeBinding` /// - `data3` has a type ascription but no type arguments in the `TypeBinding`, /// so the type arguments in the `TypeBinding` and the type of the value /// passed to `value` are both unified to the type ascription /// - `data4` has a type ascription and has type arguments in the `TypeBinding`, /// so, with the type from the value passed to `value`, all three are unified /// together #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TypeBinding<T> { pub inner: T, pub type_arguments: TypeArgs, pub span: Span, } /// A [TypeArgs] contains a `Vec<TypeArgument>` either in the variant `Regular` /// or in the variant `Prefix`. /// /// `Regular` variant indicates the type arguments are located after the suffix. /// `Prefix` variant indicates the type arguments are located between the last /// prefix and the suffix. /// /// In the case of an enum we can have either the type parameters in the `Regular` /// variant, case of: /// ```ignore /// let z = Option::Some::<u32>(10); /// ``` /// Or the enum can have the type parameters in the `Prefix` variant, case of: /// ```ignore /// let z = Option::<u32>::Some(10); /// ``` /// So we can have type parameters in the `Prefix` or `Regular` variant but not /// in both. #[derive(Debug, Clone, Serialize, Deserialize)] pub enum TypeArgs { /// `Regular` variant indicates the type arguments are located after the suffix. Regular(Vec<GenericArgument>), /// `Prefix` variant indicates the type arguments are located between the last /// prefix and the suffix. Prefix(Vec<GenericArgument>), } impl TypeArgs { pub fn to_vec(&self) -> Vec<GenericArgument> { match self { TypeArgs::Regular(vec) => vec.to_vec(), TypeArgs::Prefix(vec) => vec.to_vec(), } } pub fn as_slice(&self) -> &[GenericArgument] { match self { TypeArgs::Regular(vec) | TypeArgs::Prefix(vec) => vec, } } pub(crate) fn to_vec_mut(&mut self) -> &mut Vec<GenericArgument> { match self { TypeArgs::Regular(vec) => vec, TypeArgs::Prefix(vec) => vec, } } } impl Spanned for TypeArgs { fn span(&self) -> Span { Span::join_all(self.to_vec().iter().map(sway_types::Spanned::span)) } } impl PartialEqWithEngines for TypeArgs { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { match (self, other) { (TypeArgs::Regular(vec1), TypeArgs::Regular(vec2)) => vec1.eq(vec2, ctx), (TypeArgs::Prefix(vec1), TypeArgs::Prefix(vec2)) => vec1.eq(vec2, ctx), _ => false, } } } impl<T> Spanned for TypeBinding<T> { fn span(&self) -> Span { self.span.clone() } } impl PartialEqWithEngines for TypeBinding<Ident> { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.inner == other.inner && self.span == other.span && self.type_arguments.eq(&other.type_arguments, ctx) } } impl PartialEqWithEngines for TypeBinding<Intrinsic> { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.inner == other.inner && self.span == other.span && self.type_arguments.eq(&other.type_arguments, ctx) } } impl<T> EqWithEngines for TypeBinding<T> where T: EqWithEngines {} impl<T> PartialEqWithEngines for TypeBinding<T> where T: PartialEqWithEngines, { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.inner.eq(&other.inner, ctx) && self.span == other.span && self.type_arguments.eq(&other.type_arguments, ctx) } } impl<T> TypeBinding<T> { pub fn strip_inner(self) -> TypeBinding<()> { TypeBinding { inner: (), type_arguments: self.type_arguments, span: self.span, } } pub(crate) fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext<'_>) { match self.type_arguments { TypeArgs::Regular(ref mut args) => args .iter_mut() .for_each(|arg| arg.resolve_symbols(handler, ctx.by_ref())), TypeArgs::Prefix(ref mut args) => args .iter_mut() .for_each(|arg| arg.resolve_symbols(handler, ctx.by_ref())), } } } impl TypeBinding<CallPath<(TypeInfo, Ident)>> { pub(crate) fn type_check_with_type_info( &self, handler: &Handler, ctx: &mut TypeCheckContext, ) -> Result<TypeId, ErrorEmitted> { let type_engine = ctx.engines.te(); let engines = ctx.engines(); let (type_info, type_ident) = self.inner.suffix.clone(); let type_info_span = type_ident.span(); // find the module that the symbol is in let full_path = self.inner.to_fullpath(engines, ctx.namespace()); ctx.namespace() .require_module_from_absolute_path(handler, &full_path.prefixes)?; // create the type info object let type_info = type_info.apply_type_arguments( handler, self.type_arguments.to_vec(), &type_info_span, )?; // resolve the type of the type info object let type_id = ctx .resolve_type( handler, type_engine.insert(engines, type_info, type_info_span.source_id()), &type_info_span, EnforceTypeArguments::No, Some(&full_path.prefixes), ) .unwrap_or_else(|err| type_engine.id_of_error_recovery(err)); Ok(type_id) } } impl EqWithEngines for (TypeInfo, Ident) {} impl PartialEqWithEngines for (TypeInfo, Ident) { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.0.eq(&other.0, ctx) && self.1 == other.1 } } impl TypeBinding<CallPath> { pub(crate) fn strip_prefixes(&mut self) { self.inner.prefixes = vec![]; } } /// Trait that adds a workaround for easy generic returns in Rust: /// https://blog.jcoglan.com/2019/04/22/generic-returns-in-rust/ #[allow(clippy::type_complexity)] pub(crate) trait TypeCheckTypeBinding<T> { fn type_check( &mut self, handler: &Handler, ctx: TypeCheckContext, ) -> Result<(DeclRef<DeclId<T>>, Option<TypeId>, Option<ty::TyDecl>), ErrorEmitted>; } #[allow(clippy::type_complexity)] pub trait SymbolResolveTypeBinding<T> { fn resolve_symbol( &mut self, handler: &Handler, ctx: SymbolResolveContext, ) -> Result<ParsedDeclId<T>, ErrorEmitted>; } impl SymbolResolveTypeBinding<FunctionDeclaration> for TypeBinding<CallPath> { fn resolve_symbol( &mut self, handler: &Handler, ctx: SymbolResolveContext, ) -> Result<ParsedDeclId<FunctionDeclaration>, ErrorEmitted> { let engines = ctx.engines(); // Grab the declaration. let unknown_decl = ctx.resolve_call_path_with_visibility_check(handler, &self.inner)?; // Check to see if this is a function declaration. let fn_decl = unknown_decl .resolve_parsed(engines.de()) .to_fn_ref(handler, engines)?; Ok(fn_decl) } } impl TypeCheckTypeBinding<ty::TyFunctionDecl> for TypeBinding<CallPath> { fn type_check( &mut self, handler: &Handler, mut ctx: TypeCheckContext, ) -> Result< ( DeclRef<DeclId<ty::TyFunctionDecl>>, Option<TypeId>, Option<ty::TyDecl>, ), ErrorEmitted, > { let type_engine = ctx.engines.te(); let decl_engine = ctx.engines.de(); // Grab the declaration. let unknown_decl = ctx.resolve_call_path_with_visibility_check(handler, &self.inner)?; // Check to see if this is a fn declaration. let fn_ref = unknown_decl.to_fn_ref(handler, ctx.engines())?; // Get a new copy from the declaration engine. let mut new_copy = (*decl_engine.get_function(fn_ref.id())).clone(); match self.type_arguments { // Monomorphize the copy, in place. TypeArgs::Regular(_) => { ctx.monomorphize( handler, &mut new_copy, self.type_arguments.to_vec_mut(), BTreeMap::new(), EnforceTypeArguments::No, &self.span, )?; } TypeArgs::Prefix(_) => { // Resolve the type arguments without monomorphizing. for type_argument in self.type_arguments.to_vec_mut().iter_mut() { ctx.resolve_type( handler, type_argument.type_id(), &type_argument.span(), EnforceTypeArguments::Yes, None, ) .unwrap_or_else(|err| type_engine.id_of_error_recovery(err)); } } } // Insert the new copy into the declaration engine. let new_fn_ref = decl_engine .insert( new_copy, decl_engine.get_parsed_decl_id(fn_ref.id()).as_ref(), ) .with_parent(ctx.engines.de(), fn_ref.id().into()); Ok((new_fn_ref, None, None)) } } impl SymbolResolveTypeBinding<StructDeclaration> for TypeBinding<CallPath> { fn resolve_symbol( &mut self, handler: &Handler, ctx: SymbolResolveContext, ) -> Result<ParsedDeclId<StructDeclaration>, ErrorEmitted> { let engines = ctx.engines(); // Grab the declaration. let unknown_decl = ctx.resolve_call_path_with_visibility_check(handler, &self.inner)?; // Check to see if this is a struct declaration. let struct_decl = unknown_decl.to_struct_decl(handler, engines)?; struct_decl .resolve_parsed(engines.de()) .to_struct_decl(handler, engines) } } impl TypeCheckTypeBinding<ty::TyStructDecl> for TypeBinding<CallPath> { fn type_check( &mut self, handler: &Handler, mut ctx: TypeCheckContext, ) -> Result< ( DeclRef<DeclId<ty::TyStructDecl>>, Option<TypeId>, Option<ty::TyDecl>, ), ErrorEmitted, > { let type_engine = ctx.engines.te(); let decl_engine = ctx.engines.de(); let engines = ctx.engines(); // Grab the declaration. let unknown_decl = ctx.resolve_call_path_with_visibility_check(handler, &self.inner)?; // Check to see if this is a struct declaration. let struct_id = unknown_decl.to_struct_decl(handler, engines)?; // Get a new copy from the declaration engine. let mut new_copy = (*decl_engine.get_struct(&struct_id)).clone(); // Monomorphize the copy, in place. ctx.monomorphize( handler, &mut new_copy, self.type_arguments.to_vec_mut(), BTreeMap::new(), EnforceTypeArguments::No, &self.span, )?; // Insert the new copy into the declaration engine. let new_struct_ref = decl_engine.insert( new_copy, decl_engine.get_parsed_decl_id(&struct_id).as_ref(), ); let type_id = type_engine.insert_struct(engines, *new_struct_ref.id()); Ok((new_struct_ref, Some(type_id), None)) } } impl TypeCheckTypeBinding<ty::TyEnumDecl> for TypeBinding<CallPath> { fn type_check( &mut self, handler: &Handler, mut ctx: TypeCheckContext, ) -> Result< ( DeclRef<DeclId<ty::TyEnumDecl>>, Option<TypeId>, Option<ty::TyDecl>, ), ErrorEmitted, > { let type_engine = ctx.engines.te(); let decl_engine = ctx.engines.de(); let engines = ctx.engines(); // Grab the declaration. let unknown_decl = ctx.resolve_call_path_with_visibility_check(handler, &self.inner)?; // Get a new copy from the declaration engine. let enum_id = if let ty::TyDecl::EnumVariantDecl(ty::EnumVariantDecl { enum_ref, .. }) = &unknown_decl { *enum_ref.id() } else { // Check to see if this is a enum declaration. unknown_decl.to_enum_id(handler, engines)? }; let mut new_copy = (*decl_engine.get_enum(&enum_id)).clone(); // Monomorphize the copy, in place. ctx.monomorphize( handler, &mut new_copy, self.type_arguments.to_vec_mut(), BTreeMap::new(), EnforceTypeArguments::No, &self.span, )?; // Insert the new copy into the declaration engine. let new_enum_ref = decl_engine.insert(new_copy, decl_engine.get_parsed_decl_id(&enum_id).as_ref()); let type_id = type_engine.insert_enum(engines, *new_enum_ref.id()); Ok((new_enum_ref, Some(type_id), Some(unknown_decl))) } } impl TypeBinding<QualifiedCallPath> { pub(crate) fn type_check_qualified( &mut self, handler: &Handler, ctx: &mut TypeCheckContext, ) -> Result<DeclRef<DeclId<ty::TyConstantDecl>>, ErrorEmitted> { // Grab the declaration. let unknown_decl = ctx.resolve_qualified_call_path(handler, &self.inner)?; // Check to see if this is a const declaration. let const_ref = unknown_decl.to_const_ref(handler, ctx.engines())?; Ok(const_ref) } } impl TypeCheckTypeBinding<ty::TyConstantDecl> for TypeBinding<CallPath> { fn type_check( &mut self, handler: &Handler, ctx: TypeCheckContext, ) -> Result< ( DeclRef<DeclId<ty::TyConstantDecl>>, Option<TypeId>, Option<ty::TyDecl>, ), ErrorEmitted, > { // Grab the declaration. let unknown_decl = ctx.resolve_call_path_with_visibility_check(handler, &self.inner)?; // Check to see if this is a const declaration. let const_ref = unknown_decl.to_const_ref(handler, ctx.engines())?; Ok((const_ref, None, None)) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/ast_elements/create_type_id.rs
sway-core/src/type_system/ast_elements/create_type_id.rs
use crate::{type_system::priv_prelude::*, Engines}; pub(crate) trait CreateTypeId { fn create_type_id(&self, engines: &Engines) -> TypeId; }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/ast_elements/length.rs
sway-core/src/type_system/ast_elements/length.rs
use crate::{ ast_elements::type_parameter::ConstGenericExprTyDecl, decl_engine::DeclEngineGet as _, Engines, }; use super::type_parameter::ConstGenericExpr; /// Describes a fixed length for types that need it, e.g., [crate::TypeInfo::Array]. /// /// Optionally, if the length is coming from a literal in code, the [Length] /// also keeps the [Span] of that literal. In that case, we say that the length /// is annotated. /// /// E.g., in this example, the two lengths coming from the literal `3` will /// have two different spans pointing to the two different strings "3": /// /// ```ignore /// fn copy(a: [u64;3], b: [u64;3]) /// ``` #[derive(Debug, Clone)] pub struct Length(pub ConstGenericExpr); impl Length { pub fn expr(&self) -> &ConstGenericExpr { &self.0 } pub fn extract_literal(&self, engines: &Engines) -> Option<u64> { match &self.0 { ConstGenericExpr::Literal { val, .. } => Some(*val as u64), ConstGenericExpr::AmbiguousVariableExpression { decl, .. } => match decl.as_ref()? { ConstGenericExprTyDecl::ConstGenericDecl(decl) => { let decl = engines.de().get(&decl.decl_id); let expr = decl.value.as_ref()?; let expr = expr.expression.as_literal()?; expr.cast_value_to_u64() } ConstGenericExprTyDecl::ConstantDecl(_) => None, }, } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/ast_elements/type_argument.rs
sway-core/src/type_system/ast_elements/type_argument.rs
use super::type_parameter::ConstGenericExpr; use crate::{ decl_engine::MaterializeConstGenerics, engine_threading::*, language::CallPathTree, type_system::priv_prelude::*, }; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, fmt, hash::{Hash as _, Hasher}, }; use sway_types::{Span, Spanned}; /// [GenericTypeArgument] can be seen as an "annotated reference" to a [TypeInfo]. /// It holds the [GenericTypeArgument::type_id] which is the actual "reference" /// to the type, as well as an additional information about that type, /// called the annotation. /// /// If a [GenericTypeArgument] only references a [TypeInfo] and is considered as /// not being annotated, its `initial_type_id` must be the same as `type_id`, /// its `span` must be [Span::dummy] and its `call_path_tree` must be `None`. /// /// The annotations are ignored when calculating the [GenericTypeArgument]'s hash /// (with engines) and equality (with engines). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GenericTypeArgument { /// The [TypeId] of the "referenced" [TypeInfo]. pub type_id: TypeId, /// Denotes the initial type that was referenced before the type /// unification, monomorphization, or replacement of [TypeInfo::Custom]s. pub initial_type_id: TypeId, /// The [Span] related in code to the [TypeInfo] represented by this /// [TypeArgument]. This information is mostly used by the LSP and it /// differs from use case to use case. /// /// E.g., in the following example: /// /// ```ignore /// let a: [u64;2] = [0, 0]; /// let b: [u64;2] = [1, 1]; /// ``` /// /// the type arguments of the [TypeInfo::Array]s of `a` and `b` will /// have two different spans pointing to two different strings "u64". /// On the other hand, the two [TypeInfo::Array]s describing the /// two instances `[0, 0]`, and `[1, 1]` will have neither the array /// type span set, nor the length span, which means they will not be /// annotated. pub span: Span, pub call_path_tree: Option<CallPathTree>, } impl From<TypeId> for GenericTypeArgument { /// Creates *a non-annotated* [GenericArgument::Type] that points /// to the [TypeInfo] represented by the `type_id`. fn from(type_id: TypeId) -> Self { GenericTypeArgument { type_id, initial_type_id: type_id, span: Span::dummy(), call_path_tree: None, } } } impl HashWithEngines for GenericTypeArgument { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { let GenericTypeArgument { type_id, // these fields are not hashed because they aren't relevant/a // reliable source of obj v. obj distinction initial_type_id: _, span: _, call_path_tree: _, } = self; let type_engine = engines.te(); type_engine.get(*type_id).hash(state, engines); } } impl DisplayWithEngines for GenericTypeArgument { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { write!(f, "{}", engines.help_out(self.type_id)) } } impl DebugWithEngines for GenericTypeArgument { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { write!( f, "{:?} -> {:?}", engines.help_out(self.initial_type_id), engines.help_out(self.type_id) ) } } impl MaterializeConstGenerics for GenericTypeArgument { fn materialize_const_generics( &mut self, engines: &Engines, handler: &sway_error::handler::Handler, name: &str, value: &crate::language::ty::TyExpression, ) -> Result<(), sway_error::handler::ErrorEmitted> { self.type_id .materialize_const_generics(engines, handler, name, value) } } impl GenericTypeArgument { pub fn is_annotated(&self) -> bool { self.type_id != self.initial_type_id || self.call_path_tree.is_some() || !self.span.is_dummy() } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GenericConstArgument { pub expr: ConstGenericExpr, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum GenericArgument { Type(GenericTypeArgument), Const(GenericConstArgument), } impl GenericArgument { pub fn as_type_argument(&self) -> Option<&GenericTypeArgument> { match self { GenericArgument::Type(a) => Some(a), _ => None, } } pub fn as_type_argument_mut(&mut self) -> Option<&mut GenericTypeArgument> { match self { GenericArgument::Type(a) => Some(a), _ => None, } } pub fn type_id(&self) -> TypeId { self.as_type_argument() .expect("only works with type arguments") .type_id } pub fn type_id_mut(&mut self) -> &mut TypeId { &mut self .as_type_argument_mut() .expect("only works with type arguments") .type_id } pub fn initial_type_id(&self) -> TypeId { self.as_type_argument() .expect("only works with type arguments") .initial_type_id } /// Returns true if `self` is annotated by having either /// its [Self::initial_type_id] different from [Self::type_id], /// or [Self::span] different from [Span::dummy] /// or [Self::call_path_tree] different from `None`. pub fn is_annotated(&self) -> bool { match self { GenericArgument::Type(a) => { a.type_id != a.initial_type_id || a.call_path_tree.is_some() || !a.span.is_dummy() } GenericArgument::Const(_) => false, } } } impl Spanned for GenericArgument { fn span(&self) -> Span { match self { GenericArgument::Type(a) => a.span(), GenericArgument::Const(a) => a.expr.span(), } } } impl From<TypeId> for GenericArgument { /// Creates *a non-annotated* [TypeArgument] that points /// to the [TypeInfo] represented by the `type_id`. fn from(type_id: TypeId) -> Self { GenericArgument::Type(GenericTypeArgument { type_id, initial_type_id: type_id, span: Span::dummy(), call_path_tree: None, }) } } impl HashWithEngines for GenericArgument { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { match self { GenericArgument::Type(a) => { HashWithEngines::hash(&a, state, engines); } GenericArgument::Const(GenericConstArgument { expr }) => expr.hash(state), } } } impl EqWithEngines for GenericArgument {} impl PartialEqWithEngines for GenericArgument { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { match (self, other) { (GenericArgument::Type(l), GenericArgument::Type(r)) => l.eq(r, ctx), (GenericArgument::Const(l), GenericArgument::Const(r)) => l.expr.eq(&r.expr), _ => false, } } } impl OrdWithEngines for GenericArgument { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { match (self, other) { (GenericArgument::Type(l), GenericArgument::Type(r)) => l.cmp(r, ctx), (GenericArgument::Const(l), GenericArgument::Const(r)) => l.expr.cmp(&r.expr), (GenericArgument::Type(_), _) => Ordering::Less, (GenericArgument::Const(_), _) => Ordering::Greater, } } } impl DisplayWithEngines for GenericArgument { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { match self { GenericArgument::Type(a) => { write!(f, "{}", engines.help_out(&*engines.te().get(a.type_id))) } GenericArgument::Const(a) => match &a.expr { ConstGenericExpr::Literal { val, .. } => { write!(f, "{val}") } ConstGenericExpr::AmbiguousVariableExpression { ident, .. } => { write!(f, "{}", ident.as_str()) } }, } } } impl DebugWithEngines for GenericArgument { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { match self { GenericArgument::Type(a) => DebugWithEngines::fmt(&a, f, engines), GenericArgument::Const(a) => match &a.expr { ConstGenericExpr::Literal { val, .. } => { write!(f, "{val}") } ConstGenericExpr::AmbiguousVariableExpression { ident, .. } => { write!(f, "{}", ident.as_str()) } }, } } } impl From<&TypeParameter> for GenericArgument { fn from(p: &TypeParameter) -> Self { match p { TypeParameter::Type(p) => GenericArgument::Type(GenericTypeArgument { type_id: p.type_id, initial_type_id: p.initial_type_id, span: p.name.span(), call_path_tree: None, }), TypeParameter::Const(p) => GenericArgument::Const(GenericConstArgument { expr: match p.expr.as_ref() { Some(expr) => expr.clone(), None => ConstGenericExpr::AmbiguousVariableExpression { ident: p.name.clone(), decl: None, }, }, }), } } } impl SubstTypes for GenericArgument { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { match self { GenericArgument::Type(a) => a.subst(ctx), GenericArgument::Const(_) => HasChanges::No, } } } impl MaterializeConstGenerics for GenericArgument { fn materialize_const_generics( &mut self, engines: &Engines, handler: &sway_error::handler::Handler, name: &str, value: &crate::language::ty::TyExpression, ) -> Result<(), sway_error::handler::ErrorEmitted> { match self { GenericArgument::Type(arg) => { arg.materialize_const_generics(engines, handler, name, value)?; } GenericArgument::Const(arg) => { arg.expr = match arg.expr.clone() { ConstGenericExpr::AmbiguousVariableExpression { ident, mut decl } => { if let Some(decl) = decl.as_mut() { decl.materialize_const_generics(engines, handler, name, value)?; } if ident.as_str() == name { ConstGenericExpr::Literal { val: value .extract_literal_value() .unwrap() .cast_value_to_u64() .unwrap() as usize, span: value.span.clone(), } } else { ConstGenericExpr::AmbiguousVariableExpression { ident, decl } } } expr => expr, }; } } Ok(()) } } impl Spanned for GenericTypeArgument { fn span(&self) -> Span { self.span.clone() } } impl SubstTypes for GenericTypeArgument { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { self.type_id.subst(ctx) } } impl PartialEqWithEngines for GenericTypeArgument { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { let type_engine = ctx.engines().te(); self.type_id == other.type_id || type_engine .get(self.type_id) .eq(&type_engine.get(other.type_id), ctx) } } impl OrdWithEngines for GenericTypeArgument { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { let GenericTypeArgument { type_id: lti, // these fields are not compared because they aren't relevant/a // reliable source of obj v. obj distinction initial_type_id: _, span: _, call_path_tree: _, } = self; let GenericTypeArgument { type_id: rti, // these fields are not compared because they aren't relevant/a // reliable source of obj v. obj distinction initial_type_id: _, span: _, call_path_tree: _, } = other; if lti == rti { return Ordering::Equal; } ctx.engines() .te() .get(*lti) .cmp(&ctx.engines().te().get(*rti), ctx) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/ast_elements/trait_constraint.rs
sway-core/src/type_system/ast_elements/trait_constraint.rs
use crate::{ engine_threading::*, language::{parsed::Supertrait, ty, CallPath, CallPathDisplayType}, semantic_analysis::{ declaration::{insert_supertraits_into_namespace, SupertraitOf}, TypeCheckContext, }, type_system::priv_prelude::*, types::{CollectTypesMetadata, CollectTypesMetadataContext, TypeMetadata}, EnforceTypeArguments, Namespace, }; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, collections::BTreeMap, fmt, hash::{Hash, Hasher}, }; use sway_error::{ error::CompileError, handler::{ErrorEmitted, Handler}, }; use sway_types::Spanned; use super::type_argument::GenericTypeArgument; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TraitConstraint { pub trait_name: CallPath, pub type_arguments: Vec<GenericArgument>, } impl HashWithEngines for TraitConstraint { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { self.trait_name.hash(state); self.type_arguments.hash(state, engines); } } impl EqWithEngines for TraitConstraint {} impl PartialEqWithEngines for TraitConstraint { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { self.trait_name == other.trait_name // Check if eq is already inside of a trait constraint, if it is we don't compare type arguments. // This breaks the recursion when we use a where clause such as `T:MyTrait<T>`. && (ctx.is_inside_trait_constraint() || self.type_arguments.eq( &other.type_arguments, &(ctx.with_is_inside_trait_constraint()), )) } } impl OrdWithEngines for TraitConstraint { fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering { let TraitConstraint { trait_name: ltn, type_arguments: lta, } = self; let TraitConstraint { trait_name: rtn, type_arguments: rta, } = other; let mut res = ltn.cmp(rtn); // Check if cmp is already inside of a trait constraint, if it is we don't compare type arguments. // This breaks the recursion when we use a where clause such as `T:MyTrait<T>`. if !ctx.is_inside_trait_constraint() { res = res.then_with(|| lta.cmp(rta, &ctx.with_is_inside_trait_constraint())); } res } } impl DisplayWithEngines for TraitConstraint { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { write!(f, "{:?}", engines.help_out(self)) } } impl DebugWithEngines for TraitConstraint { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { let mut res = write!(f, "{}", self.trait_name); if !self.type_arguments.is_empty() { write!(f, "<")?; for ty_arg in self.type_arguments.clone() { write!(f, "{:?}", engines.help_out(ty_arg))?; } res = write!(f, ">"); } res } } impl Spanned for TraitConstraint { fn span(&self) -> sway_types::Span { self.trait_name.span() } } impl SubstTypes for TraitConstraint { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { self.type_arguments.subst(ctx) } } impl From<&Supertrait> for TraitConstraint { fn from(supertrait: &Supertrait) -> Self { TraitConstraint { trait_name: supertrait.name.clone(), type_arguments: vec![], } } } impl CollectTypesMetadata for TraitConstraint { fn collect_types_metadata( &self, handler: &Handler, ctx: &mut CollectTypesMetadataContext, ) -> Result<Vec<TypeMetadata>, ErrorEmitted> { let mut res = vec![]; handler.scope(|handler| { for type_arg in &self.type_arguments { res.extend( match type_arg.type_id().collect_types_metadata(handler, ctx) { Ok(res) => res, Err(_) => continue, }, ); } Ok(res) }) } } impl TraitConstraint { pub(crate) fn type_check( &mut self, handler: &Handler, ctx: TypeCheckContext, ) -> Result<(), ErrorEmitted> { // Right now we don't have the ability to support defining a type for a // trait constraint using a callpath directly, so we check to see if the // user has done this and we disallow it. if !self.trait_name.prefixes.is_empty() { return Err(handler.emit_err(CompileError::Unimplemented { feature: "Using module paths to define trait constraints".to_string(), help: vec![ // Note that eventual leading `::` will not be shown. It'a fine for now, we anyhow want to implement using module paths. format!( "Import the supertrait by using: `use {};`.", self.trait_name ), format!( "Then, in the trait constraints, just use the trait name \"{}\".", self.trait_name.suffix ), ], span: self.trait_name.span(), })); } self.trait_name = self .trait_name .to_canonical_path(ctx.engines(), ctx.namespace()); // Type check the type arguments. for type_argument in &mut self.type_arguments { *type_argument.type_id_mut() = ctx .resolve_type( handler, type_argument.type_id(), &type_argument.span(), EnforceTypeArguments::Yes, None, ) .unwrap_or_else(|err| ctx.engines.te().id_of_error_recovery(err)); } Ok(()) } pub(crate) fn insert_into_namespace( handler: &Handler, mut ctx: TypeCheckContext, type_id: TypeId, trait_constraint: &TraitConstraint, ) -> Result<(), ErrorEmitted> { let engines = ctx.engines; let decl_engine = engines.de(); let TraitConstraint { trait_name, type_arguments, } = trait_constraint; let mut type_arguments = type_arguments.clone(); match ctx // Use the default Handler to avoid emitting the redundant SymbolNotFound error. .resolve_call_path(&Handler::default(), trait_name) .ok() { Some(ty::TyDecl::TraitDecl(ty::TraitDecl { decl_id, .. })) => { let mut trait_decl = (*decl_engine.get_trait(&decl_id)).clone(); // the following essentially is needed to map `Self` to the right type // during trait decl monomorphization trait_decl .type_parameters .push(trait_decl.self_type.clone()); type_arguments.push(GenericArgument::Type(GenericTypeArgument { type_id, initial_type_id: type_id, span: trait_name.span(), call_path_tree: None, })); // Monomorphize the trait declaration. ctx.monomorphize( handler, &mut trait_decl, &mut type_arguments, BTreeMap::new(), EnforceTypeArguments::Yes, &trait_name.span(), )?; // restore type parameters and type arguments trait_decl.type_parameters.pop(); type_arguments.pop(); // Insert the interface surface and methods from this trait into // the namespace. trait_decl.insert_interface_surface_and_items_into_namespace( handler, ctx.by_ref(), trait_name, &type_arguments, type_id, ); // Recursively make the interface surfaces and methods of the // supertraits available to this trait. insert_supertraits_into_namespace( handler, ctx.by_ref(), type_id, &trait_decl.supertraits, &SupertraitOf::Trait, )?; } Some(ty::TyDecl::AbiDecl { .. }) => { handler.emit_err(CompileError::AbiAsSupertrait { span: trait_name.span(), }); } _ => { handler.emit_err(CompileError::TraitNotFound { name: trait_name.to_string(), span: trait_name.span(), }); } } Ok(()) } pub fn to_display_name(&self, engines: &Engines, namespace: &Namespace) -> String { let display_path = self .trait_name .to_display_path(CallPathDisplayType::StripPackagePrefix, namespace); display_path.to_string_with_args(engines, &self.type_arguments) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/substitute/subst_map.rs
sway-core/src/type_system/substitute/subst_map.rs
use crate::{ ast_elements::type_parameter::ConstGenericExpr, decl_engine::{DeclEngineGetParsedDeclId, DeclEngineInsert, ParsedDeclEngineInsert}, engine_threading::{ DebugWithEngines, Engines, PartialEqWithEngines, PartialEqWithEnginesContext, }, type_system::priv_prelude::*, }; use std::{collections::BTreeMap, fmt}; use sway_error::handler::Handler; use sway_types::Ident; type SourceType = TypeId; type DestinationType = TypeId; /// The [TypeSubstMap] is used to create a mapping between a [SourceType] (LHS) /// and a [DestinationType] (RHS). #[derive(Clone, Default)] pub struct TypeSubstMap { mapping: BTreeMap<SourceType, DestinationType>, pub const_generics_materialization: BTreeMap<String, crate::language::ty::TyExpression>, pub const_generics_renaming: BTreeMap<Ident, Ident>, } impl DebugWithEngines for TypeSubstMap { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { write!( f, "TypeSubstMap {{ {}; {}; {} }}", self.mapping .iter() .map(|(source_type, dest_type)| { format!( "{:?} -> {:?}", engines.help_out(source_type), engines.help_out(dest_type) ) }) .collect::<Vec<_>>() .join(", "), self.const_generics_materialization .iter() .map(|(a, b)| format!("{:?} -> {:?}", a, engines.help_out(b))) .collect::<Vec<_>>() .join(", "), self.const_generics_renaming .iter() .map(|(a, b)| format!("{a:?} -> {b:?}")) .collect::<Vec<_>>() .join(", ") ) } } impl fmt::Debug for TypeSubstMap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "TypeSubstMap {{ {} }}", self.mapping .iter() .map(|(source_type, dest_type)| { format!("{source_type:?} -> {dest_type:?}") }) .collect::<Vec<_>>() .join(", ") ) } } impl TypeSubstMap { /// Returns `true` if the [TypeSubstMap] is empty. pub(crate) fn is_empty(&self) -> bool { self.mapping.is_empty() && self.const_generics_renaming.is_empty() } /// Constructs a new empty [TypeSubstMap]. pub(crate) fn new() -> TypeSubstMap { TypeSubstMap { mapping: BTreeMap::<SourceType, DestinationType>::new(), const_generics_materialization: BTreeMap::new(), const_generics_renaming: BTreeMap::default(), } } pub(crate) fn source_ids_contains_concrete_type(&self, engines: &Engines) -> bool { for source_id in self.mapping.keys() { if source_id.is_concrete(engines, TreatNumericAs::Concrete) { return true; } } false } /// Constructs a new [TypeSubstMap] from a list of [TypeParameter]s /// `type_parameters`. The [SourceType]s of the resulting [TypeSubstMap] are /// the [TypeId]s from `type_parameters` and the [DestinationType]s are the /// new [TypeId]s created from a transformation upon `type_parameters`. pub(crate) fn from_type_parameters( engines: &Engines, type_parameters: &[TypeParameter], ) -> TypeSubstMap { let type_engine = engines.te(); let mapping = type_parameters .iter() .filter_map(|p| p.as_type_parameter()) .filter(|p| { let type_info = type_engine.get(p.type_id); !matches!(*type_info, TypeInfo::Placeholder(_)) }) .map(|p| { ( p.type_id, type_engine.new_placeholder(TypeParameter::Type(p.clone())), ) }) .collect(); TypeSubstMap { mapping, const_generics_materialization: BTreeMap::new(), const_generics_renaming: BTreeMap::default(), } } /// Constructs a new [TypeSubstMap] from a superset [TypeId] and a subset /// [TypeId]. The [SourceType]s of the resulting [TypeSubstMap] are the /// [TypeId]s from `superset` and the [DestinationType]s are the [TypeId]s /// from `subset`. Thus, the resulting [TypeSubstMap] maps the type /// parameters of the superset [TypeId] to the type parameters of the subset /// [TypeId], and is used in monomorphization. /// /// *Importantly, this function does not check to see if the two types /// given are indeed a superset and subset of one another, but instead that /// is an assumption.* /// /// Here is an example, given these input types (in pseudo-code): /// /// ```ignore /// superset: /// /// TypeInfo::Struct { /// name: "Either", /// type_parameters: [L, R], /// fields: .. /// } /// /// subset: /// /// TypeInfo::Struct { /// name: "Either" /// type_parameters: [u64, bool], /// fields: .. /// } /// ``` /// /// So then the resulting [TypeSubstMap] would look like: /// /// ```ignore /// TypeSubstMap { /// mapping: [ /// (L, u64), /// (R, bool) /// ] /// } /// ```` /// /// So, as we can see, the resulting [TypeSubstMap] is a mapping from the /// type parameters of the `superset` to the type parameters of the /// `subset`. This [TypeSubstMap] can be used to complete monomorphization on /// methods, etc, that are implemented for the type of `superset` so that /// they can be used for `subset`. pub(crate) fn from_superset_and_subset( engines: &Engines, superset: TypeId, subset: TypeId, ) -> TypeSubstMap { let type_engine = engines.te(); let decl_engine = engines.de(); match (&*type_engine.get(superset), &*type_engine.get(subset)) { (TypeInfo::UnknownGeneric { .. }, _) => TypeSubstMap { mapping: BTreeMap::from([(superset, subset)]), const_generics_materialization: BTreeMap::new(), const_generics_renaming: BTreeMap::new(), }, ( TypeInfo::Custom { type_arguments: type_parameters, .. }, TypeInfo::Custom { type_arguments, .. }, ) => { let type_parameters = type_parameters.iter().flatten().map(|x| x.type_id()); let type_arguments = type_arguments.iter().flatten().map(|x| x.type_id()); TypeSubstMap::from_superset_and_subset_helper( engines, type_parameters, type_arguments, ) } (TypeInfo::Enum(decl_ref_params), TypeInfo::Enum(decl_ref_args)) => { let decl_params = decl_engine.get_enum(decl_ref_params); let decl_args = decl_engine.get_enum(decl_ref_args); let type_parameters = decl_params .generic_parameters .iter() .filter_map(|x| x.as_type_parameter()) .map(|x| x.type_id); let type_arguments = decl_args .generic_parameters .iter() .filter_map(|x| x.as_type_parameter()) .map(|x| x.type_id); TypeSubstMap::from_superset_and_subset_helper( engines, type_parameters, type_arguments, ) } (TypeInfo::Struct(decl_ref_params), TypeInfo::Struct(decl_ref_args)) => { let decl_params = decl_engine.get_struct(decl_ref_params); let decl_args = decl_engine.get_struct(decl_ref_args); let type_parameters = decl_params .generic_parameters .iter() .filter_map(|x| x.as_type_parameter()) .map(|x| x.type_id); let type_arguments = decl_args .generic_parameters .iter() .filter_map(|x| x.as_type_parameter()) .map(|x| x.type_id); TypeSubstMap::from_superset_and_subset_helper( engines, type_parameters, type_arguments, ) } (TypeInfo::Tuple(type_parameters), TypeInfo::Tuple(type_arguments)) => { TypeSubstMap::from_superset_and_subset_helper( engines, type_parameters.iter().map(|x| x.type_id), type_arguments.iter().map(|x| x.type_id), ) } (TypeInfo::StringArray(l), TypeInfo::StringArray(r)) => { let map = TypeSubstMap::new(); map_from_length(type_engine, l, r, map) } (TypeInfo::Array(type_parameter, l), TypeInfo::Array(type_argument, r)) => { let map = TypeSubstMap::from_superset_and_subset_helper( engines, [type_parameter.type_id].into_iter(), [type_argument.type_id].into_iter(), ); map_from_length(type_engine, l, r, map) } (TypeInfo::Slice(type_parameter), TypeInfo::Slice(type_argument)) => { TypeSubstMap::from_superset_and_subset_helper( engines, [type_parameter.type_id].into_iter(), [type_argument.type_id].into_iter(), ) } (TypeInfo::Unknown, TypeInfo::Unknown) | (TypeInfo::Boolean, TypeInfo::Boolean) | (TypeInfo::B256, TypeInfo::B256) | (TypeInfo::Numeric, TypeInfo::Numeric) | (TypeInfo::Contract, TypeInfo::Contract) | (TypeInfo::ErrorRecovery(_), TypeInfo::ErrorRecovery(_)) | (TypeInfo::StringSlice, TypeInfo::StringSlice) | (TypeInfo::UnsignedInteger(_), TypeInfo::UnsignedInteger(_)) | (TypeInfo::ContractCaller { .. }, TypeInfo::ContractCaller { .. }) => TypeSubstMap { mapping: BTreeMap::new(), const_generics_materialization: BTreeMap::new(), const_generics_renaming: BTreeMap::new(), }, _ => TypeSubstMap { mapping: BTreeMap::new(), const_generics_materialization: BTreeMap::new(), const_generics_renaming: BTreeMap::new(), }, } } /// Constructs a [TypeSubstMap] from a list of [TypeId]s `type_parameters` /// and a list of [TypeId]s `type_arguments`, the generated [TypeSubstMap] /// is extended with the result from calling `from_superset_and_subset` /// with each [SourceType]s and [DestinationType]s in the original [TypeSubstMap]. fn from_superset_and_subset_helper( engines: &Engines, type_parameters: impl Iterator<Item = SourceType>, type_arguments: impl Iterator<Item = DestinationType>, ) -> TypeSubstMap { let mut type_mapping = TypeSubstMap::from_type_parameters_and_type_arguments(type_parameters, type_arguments); for (s, d) in type_mapping.mapping.clone().iter() { type_mapping.mapping.extend( TypeSubstMap::from_superset_and_subset(engines, *s, *d) .mapping .iter(), ); } type_mapping } /// Constructs a [TypeSubstMap] from a list of [TypeId]s `type_parameters` /// and a list of [TypeId]s `type_arguments`. The [SourceType]s of the /// resulting [TypeSubstMap] are the [TypeId]s from `type_parameters` and the /// [DestinationType]s are the [TypeId]s from `type_arguments`. pub(crate) fn from_type_parameters_and_type_arguments( type_parameters: impl Iterator<Item = SourceType>, type_arguments: impl Iterator<Item = DestinationType>, ) -> TypeSubstMap { let mapping = type_parameters.into_iter().zip(type_arguments).collect(); TypeSubstMap { mapping, const_generics_materialization: BTreeMap::new(), const_generics_renaming: BTreeMap::default(), } } pub(crate) fn from_type_parameters_and_type_arguments_and_const_generics( type_parameters: Vec<SourceType>, type_arguments: Vec<DestinationType>, const_generics_materialization: BTreeMap<String, crate::language::ty::TyExpression>, ) -> TypeSubstMap { let mapping = type_parameters.into_iter().zip(type_arguments).collect(); TypeSubstMap { mapping, const_generics_materialization, const_generics_renaming: BTreeMap::default(), } } pub(crate) fn extend(&mut self, other: &TypeSubstMap) { self.mapping.extend(other.mapping.iter()); self.const_generics_materialization.extend( other .const_generics_materialization .iter() .map(|x| (x.0.clone(), x.1.clone())), ); } pub(crate) fn insert(&mut self, source: SourceType, destination: DestinationType) { self.mapping.insert(source, destination); } /// Given a [TypeId] `type_id`, find (or create) a match for `type_id` in /// this [TypeSubstMap] and return it, if there is a match. Importantly, this /// function is recursive, so any `type_id` it's given will undergo /// recursive calls of this function. For instance, in the case of /// [TypeInfo::Struct], both `fields` and `type_parameters` will recursively /// call `find_match` (via calling [SubstTypes]). /// /// A match can be found in these circumstances: /// - `type_id` is one of the following: [TypeInfo::Custom], /// [TypeInfo::UnknownGeneric], [TypeInfo::Placeholder], or [TypeInfo::TraitType]. /// /// A match is potentially created (i.e. a new [TypeId] is created) in these /// circumstances: /// - `type_id` is one of the following: [TypeInfo::Struct], [TypeInfo::Enum], /// [TypeInfo::Array], [TypeInfo::Tuple], [TypeInfo::Alias], [TypeInfo::Ptr], /// [TypeInfo::Slice], or [TypeInfo::Ref], /// - and one of the contained types (e.g. a struct field, or a referenced type) /// finds a match in a recursive call to `find_match`. /// /// A match cannot be found in any other circumstance. pub(crate) fn find_match( &self, type_id: TypeId, handler: &Handler, engines: &Engines, ) -> Option<TypeId> { let type_engine = engines.te(); let decl_engine = engines.de(); let parsed_decl_engine = engines.pe(); let type_info = type_engine.get(type_id); match (*type_info).clone() { TypeInfo::Custom { .. } => iter_for_match(engines, self, &type_info), TypeInfo::UnknownGeneric { .. } => iter_for_match(engines, self, &type_info), TypeInfo::Placeholder(_) => iter_for_match(engines, self, &type_info), TypeInfo::TypeParam(_) => None, TypeInfo::UntypedEnum(decl_id) => { let mut decl = (*parsed_decl_engine.get_enum(&decl_id)).clone(); let mut need_to_create_new = false; for variant in &mut decl.variants { if let Some(type_id) = self.find_match(variant.type_argument.type_id, handler, engines) { need_to_create_new = true; variant.type_argument.type_id = type_id; } } for type_param in &mut decl.type_parameters { let type_param = type_param .as_type_parameter_mut() .expect("only works with type parameters"); if let Some(type_id) = self.find_match(type_param.type_id, handler, engines) { need_to_create_new = true; type_param.type_id = type_id; } } if need_to_create_new { let source_id = decl.span.source_id().copied(); let new_decl_id = engines.pe().insert(decl); Some(type_engine.insert( engines, TypeInfo::UntypedEnum(new_decl_id), source_id.as_ref(), )) } else { None } } TypeInfo::UntypedStruct(decl_id) => { let mut decl = (*parsed_decl_engine.get_struct(&decl_id)).clone(); let mut need_to_create_new = false; for field in &mut decl.fields { if let Some(type_id) = self.find_match(field.type_argument.type_id, handler, engines) { need_to_create_new = true; field.type_argument.type_id = type_id; } } for type_param in &mut decl.type_parameters { let type_param = type_param .as_type_parameter_mut() .expect("only works with type parameters"); if let Some(type_id) = self.find_match(type_param.type_id, handler, engines) { need_to_create_new = true; type_param.type_id = type_id; } } if need_to_create_new { let source_id = decl.span.source_id().copied(); let new_decl_id = parsed_decl_engine.insert(decl); Some(type_engine.insert( engines, TypeInfo::UntypedStruct(new_decl_id), source_id.as_ref(), )) } else { None } } TypeInfo::Struct(decl_id) => { let mut decl = (*decl_engine.get_struct(&decl_id)).clone(); let mut need_to_create_new = false; for field in &mut decl.fields { if let Some(type_id) = self.find_match(field.type_argument.type_id, handler, engines) { need_to_create_new = true; field.type_argument.type_id = type_id; } } for p in &mut decl.generic_parameters.iter_mut() { match p { TypeParameter::Type(p) => { if let Some(type_id) = self.find_match(p.type_id, handler, engines) { need_to_create_new = true; p.type_id = type_id; } } TypeParameter::Const(p) => { let ctx = &SubstTypesContext { handler, engines, type_subst_map: Some(self), subst_function_body: false, }; if matches!(p.subst_inner(ctx), HasChanges::Yes) { need_to_create_new = true } } } } if need_to_create_new { let new_decl_ref = decl_engine.insert(decl, decl_engine.get_parsed_decl_id(&decl_id).as_ref()); Some(type_engine.insert_struct(engines, *new_decl_ref.id())) } else { None } } TypeInfo::Enum(decl_id) => { let mut decl = (*decl_engine.get_enum(&decl_id)).clone(); let mut need_to_create_new = false; for variant in &mut decl.variants { if let Some(type_id) = self.find_match(variant.type_argument.type_id, handler, engines) { need_to_create_new = true; variant.type_argument.type_id = type_id; } } for type_param in &mut decl.generic_parameters { let Some(type_param) = type_param.as_type_parameter_mut() else { continue; }; if let Some(type_id) = self.find_match(type_param.type_id, handler, engines) { need_to_create_new = true; type_param.type_id = type_id; } } if need_to_create_new { let new_decl_ref = decl_engine.insert(decl, decl_engine.get_parsed_decl_id(&decl_id).as_ref()); Some(type_engine.insert_enum(engines, *new_decl_ref.id())) } else { None } } TypeInfo::Array(mut elem_type, length) => self .find_match(elem_type.type_id, handler, engines) .map(|type_id| { elem_type.type_id = type_id; type_engine.insert_array(engines, elem_type, length) }), TypeInfo::Slice(mut elem_type) => self .find_match(elem_type.type_id, handler, engines) .map(|type_id| { elem_type.type_id = type_id; type_engine.insert_slice(engines, elem_type) }), TypeInfo::Tuple(fields) => { let mut need_to_create_new = false; let fields = fields .into_iter() .map(|mut field| { if let Some(type_id) = self.find_match(field.type_id, handler, engines) { need_to_create_new = true; field.type_id = type_id; } field.clone() }) .collect::<Vec<_>>(); if need_to_create_new { Some(type_engine.insert_tuple(engines, fields)) } else { None } } TypeInfo::Alias { name, mut ty } => { self.find_match(ty.type_id, handler, engines) .map(|type_id| { ty.type_id = type_id; type_engine.new_alias(engines, name, ty) }) } TypeInfo::Ptr(mut ty) => self .find_match(ty.type_id, handler, engines) .map(|type_id| { ty.type_id = type_id; type_engine.insert_ptr(engines, ty) }), TypeInfo::TraitType { .. } => iter_for_match(engines, self, &type_info), TypeInfo::Ref { to_mutable_value, referenced_type: mut ty, } => self .find_match(ty.type_id, handler, engines) .map(|type_id| { ty.type_id = type_id; type_engine.insert_ref(engines, to_mutable_value, ty) }), TypeInfo::Unknown | TypeInfo::Never | TypeInfo::StringArray(..) | TypeInfo::StringSlice | TypeInfo::UnsignedInteger(..) | TypeInfo::Boolean | TypeInfo::ContractCaller { .. } | TypeInfo::B256 | TypeInfo::Numeric | TypeInfo::RawUntypedPtr | TypeInfo::RawUntypedSlice | TypeInfo::Contract | TypeInfo::ErrorRecovery(..) => None, } } } fn map_from_length( type_engine: &TypeEngine, l: &Length, r: &Length, mut map: TypeSubstMap, ) -> TypeSubstMap { match (&l.expr(), &r.expr()) { ( ConstGenericExpr::AmbiguousVariableExpression { ident, .. }, ConstGenericExpr::Literal { val, .. }, ) => { map.const_generics_materialization.insert( ident.as_str().into(), crate::language::ty::TyExpression { expression: crate::language::ty::TyExpressionVariant::Literal( crate::language::Literal::U64(*val as u64), ), return_type: type_engine.id_of_u64(), span: sway_types::Span::dummy(), }, ); map } _ => map, } } fn iter_for_match( engines: &Engines, type_mapping: &TypeSubstMap, type_info: &TypeInfo, ) -> Option<TypeId> { let type_engine = engines.te(); for (source_type, dest_type) in &type_mapping.mapping { let source_type_info = type_engine.get(*source_type); // Allows current placeholder(T:T1+T2) to match source placeholder(T:T1) if let ( TypeInfo::Placeholder(source_type_param), TypeInfo::Placeholder(current_type_param), ) = ((*source_type_info).clone(), type_info) { let source_type_param = source_type_param .as_type_parameter() .expect("only works with type parameters"); let current_type_param = current_type_param .as_type_parameter() .expect("only works with type parameters"); if source_type_param.name.as_str() == current_type_param.name.as_str() && current_type_param .trait_constraints .iter() .all(|current_tc| { source_type_param.trait_constraints.iter().any(|source_tc| { source_tc.eq(current_tc, &PartialEqWithEnginesContext::new(engines)) }) }) { return Some(*dest_type); } } if source_type_info.eq(type_info, &PartialEqWithEnginesContext::new(engines)) { return Some(*dest_type); } } None }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/substitute/subst_types.rs
sway-core/src/type_system/substitute/subst_types.rs
use crate::{engine_threading::Engines, type_system::priv_prelude::*}; use sway_error::handler::Handler; use sway_types::Ident; #[derive(Default)] pub enum HasChanges { Yes, #[default] No, } impl HasChanges { pub fn has_changes(&self) -> bool { matches!(self, HasChanges::Yes) } } impl std::ops::BitOr for HasChanges { type Output = HasChanges; fn bitor(self, rhs: Self) -> Self::Output { match (self, rhs) { (HasChanges::No, HasChanges::No) => HasChanges::No, _ => HasChanges::Yes, } } } pub struct SubstTypesContext<'a> { pub handler: &'a Handler, pub engines: &'a Engines, pub type_subst_map: Option<&'a TypeSubstMap>, pub subst_function_body: bool, } impl<'a> SubstTypesContext<'a> { pub fn new( handler: &'a Handler, engines: &'a Engines, type_subst_map: &'a TypeSubstMap, subst_function_body: bool, ) -> SubstTypesContext<'a> { SubstTypesContext { handler, engines, type_subst_map: Some(type_subst_map), subst_function_body, } } pub fn dummy(handler: &'a Handler, engines: &'a Engines) -> SubstTypesContext<'a> { SubstTypesContext { handler, engines, type_subst_map: None, subst_function_body: false, } } pub fn get_renamed_const_generic(&self, name: &Ident) -> Option<&sway_types::BaseIdent> { self.type_subst_map .as_ref() .and_then(|map| map.const_generics_renaming.get(name)) } } pub trait SubstTypes { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges; fn subst(&mut self, ctx: &SubstTypesContext) -> HasChanges { if ctx.type_subst_map.is_some_and(|tsm| tsm.is_empty()) { HasChanges::No } else { self.subst_inner(ctx) } } } impl<T: SubstTypes + Clone> SubstTypes for std::sync::Arc<T> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { if let Some(item) = std::sync::Arc::get_mut(self) { item.subst_inner(ctx) } else { let mut item = self.as_ref().clone(); let r = item.subst_inner(ctx); *self = std::sync::Arc::new(item); r } } } impl<A, B: SubstTypes> SubstTypes for (A, B) { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { self.1.subst(ctx) } } impl<T: SubstTypes> SubstTypes for Box<T> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { self.as_mut().subst(ctx) } } impl<T: SubstTypes> SubstTypes for Option<T> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { self.as_mut().map(|x| x.subst(ctx)).unwrap_or_default() } } impl<T: SubstTypes> SubstTypes for Vec<T> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { self.iter_mut() .fold(HasChanges::No, |has_change, x| x.subst(ctx) | has_change) } } #[macro_export] macro_rules! has_changes { ($($stmt:expr);* ;) => {{ let mut has_changes = $crate::type_system::HasChanges::No; $( has_changes = $stmt | has_changes; )* has_changes }}; }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/substitute/mod.rs
sway-core/src/type_system/substitute/mod.rs
pub(crate) mod subst_map; pub(crate) mod subst_types;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/unify/unifier.rs
sway-core/src/type_system/unify/unifier.rs
use std::fmt; use crate::{ ast_elements::{type_argument::GenericTypeArgument, type_parameter::ConstGenericExpr}, decl_engine::{DeclEngineGet, DeclId}, engine_threading::{Engines, PartialEqWithEngines, PartialEqWithEnginesContext, WithEngines}, language::ty::{TyEnumDecl, TyStructDecl}, type_system::{engine::Unification, priv_prelude::*}, }; use sway_error::{ error::CompileError, handler::{ErrorEmitted, Handler}, type_error::TypeError, }; use sway_types::{Span, Spanned}; use super::occurs_check::OccursCheck; #[derive(Debug, Clone)] pub(crate) enum UnifyKind { /// Make the types of `received` and `expected` equivalent (or produce an /// error if there is a conflict between them). /// /// More specifically, this function tries to make `received` equivalent to /// `expected`. Default, /// Make the types of `received` and `expected` equivalent (or produce an /// error if there is a conflict between them). /// /// More specifically, this function tries to make `received` equivalent to /// `expected`, except in cases where `received` has more type information /// than `expected` (e.g. when `expected` is a self type and `received` /// is not). WithSelf, /// Make the types of `received` and `expected` equivalent (or produce an /// error if there is a conflict between them). /// /// More specifically, this function tries to make `received` equivalent to /// `expected`, except in cases where `received` has more type information /// than `expected` (e.g. when `expected` is a generic type and `received` /// is not). WithGeneric, } /// Helper struct to aid in type unification. pub(crate) struct Unifier<'a> { engines: &'a Engines, help_text: String, unify_kind: UnifyKind, } impl<'a> Unifier<'a> { /// Creates a new [Unifier]. pub(crate) fn new(engines: &'a Engines, help_text: &str, unify_kind: UnifyKind) -> Unifier<'a> { Unifier { engines, help_text: help_text.to_string(), unify_kind, } } /// Helper method for replacing the values in the [TypeEngine]. fn replace_received_with_expected( &self, received: TypeId, expected_type_info: &TypeInfo, span: &Span, ) { self.engines.te().replace_with_new_source_id( self.engines, received, expected_type_info.clone(), span.source_id().copied(), ); } /// Helper method for replacing the values in the [TypeEngine]. fn replace_expected_with_received( &self, expected: TypeId, received_type_info: &TypeInfo, span: &Span, ) { self.engines.te().replace_with_new_source_id( self.engines, expected, received_type_info.clone(), span.source_id().copied(), ); } /// Performs type unification with `received` and `expected`. pub(crate) fn unify( &self, handler: &Handler, received: TypeId, expected: TypeId, span: &Span, push_unification: bool, ) { if push_unification { let unification = Unification { received, expected, span: span.clone(), help_text: self.help_text.clone(), unify_kind: self.unify_kind.clone(), }; self.engines.te().push_unification(unification); } use TypeInfo::{ Alias, Array, Boolean, Contract, Enum, Never, Numeric, Placeholder, RawUntypedPtr, RawUntypedSlice, Ref, Slice, StringArray, StringSlice, Struct, Tuple, Unknown, UnknownGeneric, UnsignedInteger, B256, }; if received == expected { return; } let r_type_source_info = self.engines.te().get(received); let e_type_source_info = self.engines.te().get(expected); match (&*r_type_source_info, &*e_type_source_info) { // If they have the same `TypeInfo`, then we either compare them for // correctness or perform further unification. (Boolean, Boolean) => (), (B256, B256) => (), (Numeric, Numeric) => (), (Contract, Contract) => (), (RawUntypedPtr, RawUntypedPtr) => (), (RawUntypedSlice, RawUntypedSlice) => (), (StringSlice, StringSlice) => (), (StringArray(r), StringArray(e)) => { self.unify_strs( handler, received, &r_type_source_info, expected, &e_type_source_info, span, r, e, ); } (Tuple(rfs), Tuple(efs)) if rfs.len() == efs.len() => { self.unify_tuples(handler, rfs, efs); } (Array(re, rc), Array(ee, ec)) => { if self .unify_type_arguments_in_parents(handler, received, expected, span, re, ee) .is_err() { return; } match (rc.expr(), ec.expr()) { ( ConstGenericExpr::Literal { val: r_eval, .. }, ConstGenericExpr::Literal { val: e_eval, .. }, ) => { assert!(r_eval == e_eval); } ( ConstGenericExpr::Literal { .. }, ConstGenericExpr::AmbiguousVariableExpression { .. }, ) => { self.replace_expected_with_received(expected, &r_type_source_info, span); } ( ConstGenericExpr::AmbiguousVariableExpression { .. }, ConstGenericExpr::Literal { .. }, ) => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", rc.expr().span(), )); } ( ConstGenericExpr::AmbiguousVariableExpression { ident: r_ident, .. }, ConstGenericExpr::AmbiguousVariableExpression { ident: e_ident, .. }, ) => { assert!(r_ident.as_str() == e_ident.as_str()); } } } (Slice(re), Slice(ee)) => { let _ = self.unify_type_arguments_in_parents(handler, received, expected, span, re, ee); } (Struct(received_decl_id), Struct(expected_decl_id)) => { self.unify_structs( handler, received, expected, span, received_decl_id, expected_decl_id, ); } // When we don't know anything about either term, assume that // they match and make the one we know nothing about reference the // one we may know something about. (Unknown, Unknown) => (), (Unknown, e) => self.replace_received_with_expected(received, e, span), (r, Unknown) => self.replace_expected_with_received(expected, r, span), (r @ Placeholder(_), _e @ Placeholder(_)) => { self.replace_expected_with_received(expected, r, span); } (_r @ Placeholder(_), e) => self.replace_received_with_expected(received, e, span), (r, _e @ Placeholder(_)) => self.replace_expected_with_received(expected, r, span), // Generics are handled similarly to the case for unknowns, except // we take more careful consideration for the type/purpose for the // unification that we are performing. (UnknownGeneric { parent: rp, .. }, e) if rp.is_some() && self .engines .te() .get(rp.unwrap()) .eq(e, &PartialEqWithEnginesContext::new(self.engines)) => {} (r, UnknownGeneric { parent: ep, .. }) if ep.is_some() && self .engines .te() .get(ep.unwrap()) .eq(r, &PartialEqWithEnginesContext::new(self.engines)) => {} (UnknownGeneric { parent: rp, .. }, UnknownGeneric { parent: ep, .. }) if rp.is_some() && ep.is_some() && self.engines.te().get(ep.unwrap()).eq( &*self.engines.te().get(rp.unwrap()), &PartialEqWithEnginesContext::new(self.engines), ) => {} ( UnknownGeneric { name: rn, trait_constraints: rtc, parent: _, is_from_type_parameter: _, }, UnknownGeneric { name: en, trait_constraints: etc, parent: _, is_from_type_parameter: _, }, ) if rn.as_str() == en.as_str() && rtc.eq(etc, &PartialEqWithEnginesContext::new(self.engines)) => {} (_r @ UnknownGeneric { .. }, e) if !self.occurs_check(received, expected) && (matches!(self.unify_kind, UnifyKind::WithGeneric) || !matches!( &*self.engines.te().get(expected), TypeInfo::UnknownGeneric { .. } )) => { self.replace_received_with_expected(received, e, span) } (r, e @ UnknownGeneric { .. }) if !self.occurs_check(expected, received) && e.is_self_type() && matches!(self.unify_kind, UnifyKind::WithSelf) => { self.replace_expected_with_received(expected, r, span); } // Never type coerces to any other type. // This should be after the unification of self types. (Never, _) => {} // Type aliases and the types they encapsulate coerce to each other. (Alias { ty, .. }, _) => self.unify(handler, ty.type_id, expected, span, false), (_, Alias { ty, .. }) => self.unify(handler, received, ty.type_id, span, false), (Enum(r_decl_ref), Enum(e_decl_ref)) => { self.unify_enums(handler, received, expected, span, r_decl_ref, e_decl_ref); } // For integers and numerics, we (potentially) unify the numeric // with the integer. (UnsignedInteger(r), UnsignedInteger(e)) if r == e => (), (Numeric, e @ UnsignedInteger(_)) => { self.replace_received_with_expected(received, e, span); } (r @ UnsignedInteger(_), Numeric) => { self.replace_expected_with_received(expected, r, span); } // For contract callers, we (potentially) unify them if they have // the same name and their address is `None` ( _r @ TypeInfo::ContractCaller { abi_name: ref ran, address: ref rra, }, TypeInfo::ContractCaller { abi_name: ref ean, .. }, ) if (ran == ean && rra.is_none()) || matches!(ran, AbiName::Deferred) => { // if one address is empty, coerce to the other one self.replace_received_with_expected( received, &self.engines.te().get(expected), span, ); } ( TypeInfo::ContractCaller { abi_name: ref ran, .. }, _e @ TypeInfo::ContractCaller { abi_name: ref ean, address: ref ea, }, ) if (ran == ean && ea.is_none()) || matches!(ean, AbiName::Deferred) => { // if one address is empty, coerce to the other one self.replace_expected_with_received( expected, &self.engines.te().get(received), span, ); } (ref r @ TypeInfo::ContractCaller { .. }, ref e @ TypeInfo::ContractCaller { .. }) if r.eq(e, &PartialEqWithEnginesContext::new(self.engines)) => { // if they are the same, then it's ok } // Unification is possible in these situations, assuming that the referenced types // can unify: // - `&` -> `&` // - `&mut` -> `&` // - `&mut` -> `&mut` ( Ref { to_mutable_value: r_to_mut, referenced_type: r_ty, }, Ref { to_mutable_value: e_to_mut, referenced_type: e_ty, }, ) if *r_to_mut || !*e_to_mut => { let _ = self .unify_type_arguments_in_parents(handler, received, expected, span, r_ty, e_ty); } // If no previous attempts to unify were successful, raise an error. (TypeInfo::ErrorRecovery(_), _) => (), (_, TypeInfo::ErrorRecovery(_)) => (), (r, e) => { let (received, expected) = self.assign_args(r, e); handler.emit_err( TypeError::MismatchedType { expected, received, help_text: self.help_text.clone(), span: span.clone(), } .into(), ); } } } fn occurs_check(&self, generic: TypeId, other: TypeId) -> bool { OccursCheck::new(self.engines).check(generic, other) } #[allow(clippy::too_many_arguments)] fn unify_strs( &self, handler: &Handler, received: TypeId, received_type_info: &TypeInfo, expected: TypeId, _expected_type_info: &TypeInfo, span: &Span, r: &Length, e: &Length, ) { match (r.expr(), e.expr()) { ( ConstGenericExpr::Literal { val: r_val, .. }, ConstGenericExpr::Literal { val: e_val, .. }, ) if r_val == e_val => {} ( ConstGenericExpr::Literal { .. }, ConstGenericExpr::AmbiguousVariableExpression { .. }, ) => { self.replace_expected_with_received(expected, received_type_info, span); } ( ConstGenericExpr::AmbiguousVariableExpression { .. }, ConstGenericExpr::Literal { .. }, ) => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", r.expr().span(), )); } ( ConstGenericExpr::AmbiguousVariableExpression { ident: r_ident, .. }, ConstGenericExpr::AmbiguousVariableExpression { ident: e_ident, .. }, ) if r_ident == e_ident => {} _ => { let (received, expected) = self.assign_args(received, expected); handler.emit_err( TypeError::MismatchedType { expected, received, help_text: self.help_text.clone(), span: span.clone(), } .into(), ); } } } fn unify_tuples( &self, handler: &Handler, rfs: &[GenericTypeArgument], efs: &[GenericTypeArgument], ) { for (rf, ef) in rfs.iter().zip(efs.iter()) { self.unify(handler, rf.type_id, ef.type_id, &rf.span, false); } } fn unify_structs( &self, handler: &Handler, received_type_id: TypeId, expected_type_id: TypeId, span: &Span, received_decl_id: &DeclId<TyStructDecl>, expected_decl_id: &DeclId<TyStructDecl>, ) { let TyStructDecl { call_path: received_call_path, generic_parameters: received_parameters, .. } = &*self.engines.de().get(received_decl_id); let TyStructDecl { call_path: expected_call_path, generic_parameters: expected_parameters, .. } = &*self.engines.de().get(expected_decl_id); if received_parameters.len() == expected_parameters.len() && received_call_path == expected_call_path { for (received_parameter, expected_parameter) in received_parameters.iter().zip(expected_parameters.iter()) { match (received_parameter, expected_parameter) { ( TypeParameter::Type(received_parameter), TypeParameter::Type(expected_parameter), ) => self.unify( handler, received_parameter.type_id, expected_parameter.type_id, span, false, ), ( TypeParameter::Const(received_parameter), TypeParameter::Const(expected_parameter), ) => { match ( received_parameter.expr.as_ref(), expected_parameter.expr.as_ref(), ) { (Some(r), Some(e)) => match (r.as_literal_val(), e.as_literal_val()) { (Some(r), Some(e)) if r == e => {} _ => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", r.span(), )); } }, (Some(_), None) => { self.replace_expected_with_received( expected_type_id, &TypeInfo::Struct(*received_decl_id), span, ); } (None, Some(_)) => { self.replace_received_with_expected( received_type_id, &TypeInfo::Struct(*expected_decl_id), span, ); } (None, None) => {} } } _ => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", match received_parameter { TypeParameter::Type(p) => p.name.span(), TypeParameter::Const(p) => p.span.clone(), }, )); } } } } else { let (received, expected) = self.assign_args(received_type_id, expected_type_id); handler.emit_err( TypeError::MismatchedType { expected, received, help_text: self.help_text.clone(), span: span.clone(), } .into(), ); } } fn unify_enums( &self, handler: &Handler, received_type_id: TypeId, expected_type_id: TypeId, span: &Span, received_decl_id: &DeclId<TyEnumDecl>, expected_decl_id: &DeclId<TyEnumDecl>, ) { let TyEnumDecl { call_path: received_call_path, generic_parameters: received_parameters, .. } = &*self.engines.de().get(received_decl_id); let TyEnumDecl { call_path: expected_call_path, generic_parameters: expected_parameters, .. } = &*self.engines.de().get(expected_decl_id); if received_parameters.len() == expected_parameters.len() && received_call_path == expected_call_path { for (received_parameter, expected_parameter) in received_parameters.iter().zip(expected_parameters.iter()) { match (received_parameter, expected_parameter) { ( TypeParameter::Type(received_parameter), TypeParameter::Type(expected_parameter), ) => self.unify( handler, received_parameter.type_id, expected_parameter.type_id, span, false, ), ( TypeParameter::Const(received_parameter), TypeParameter::Const(expected_parameter), ) => { match ( received_parameter.expr.as_ref(), expected_parameter.expr.as_ref(), ) { (Some(r), Some(e)) => match (r.as_literal_val(), e.as_literal_val()) { (Some(r), Some(e)) if r == e => {} _ => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", r.span(), )); } }, (Some(_), None) => { self.replace_expected_with_received( expected_type_id, &TypeInfo::Enum(*received_decl_id), span, ); } (None, Some(_)) => { self.replace_received_with_expected( received_type_id, &TypeInfo::Enum(*expected_decl_id), span, ); } (None, None) => { if received_parameter.name == expected_parameter.name { } else { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", received_parameter.name.span(), )); } } } } _ => { handler.emit_err(CompileError::Internal( "Unexpected error on const generics", match received_parameter { TypeParameter::Type(p) => p.name.span(), TypeParameter::Const(p) => p.span.clone(), }, )); } } } } else { let (received, expected) = self.assign_args(received_type_id, expected_type_id); handler.emit_err( TypeError::MismatchedType { expected, received, help_text: self.help_text.clone(), span: span.clone(), } .into(), ); } } /// Unifies `received_type_argument` and `expected_type_argument`, and in case of a /// mismatch, reports the `received_parent` and `expected_parent` as mismatching. /// Useful for unifying types like arrays and references where issues in unification /// of their [TypeArgument]s directly corresponds to the unification of enclosed types themselves. fn unify_type_arguments_in_parents( &self, handler: &Handler, received_parent: TypeId, expected_parent: TypeId, span: &Span, received_type_argument: &GenericTypeArgument, expected_type_argument: &GenericTypeArgument, ) -> Result<(), ErrorEmitted> { let h = Handler::default(); self.unify( &h, received_type_argument.type_id, expected_type_argument.type_id, span, false, ); let (new_errors, warnings, infos) = h.consume(); for info in infos { handler.emit_info(info); } for warn in warnings { handler.emit_warn(warn); } // If there was an error then we want to report the parent types as mismatching, not // the argument types. if !new_errors.is_empty() { let (received, expected) = self.assign_args(received_parent, expected_parent); Err(handler.emit_err( TypeError::MismatchedType { expected, received, help_text: self.help_text.clone(), span: span.clone(), } .into(), )) } else { Ok(()) } } fn assign_args<T>(&self, r: T, e: T) -> (String, String) where WithEngines<'a, T>: fmt::Display, { let r = format!("{}", self.engines.help_out(r)); let e = format!("{}", self.engines.help_out(e)); (r, e) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/unify/mod.rs
sway-core/src/type_system/unify/mod.rs
pub(crate) mod occurs_check; pub(crate) mod unifier; pub(super) mod unify_check;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/unify/occurs_check.rs
sway-core/src/type_system/unify/occurs_check.rs
#![allow(clippy::mutable_key_type)] use crate::{engine_threading::Engines, type_system::priv_prelude::*}; /// Helper struct to perform the occurs check. /// /// --- /// /// "causes unification of a variable V and a structure S to fail if S /// contains V" /// https://en.wikipedia.org/wiki/Occurs_check /// /// "occurs check: a check for whether the same variable occurs on both /// sides and, if it does, decline to unify" /// https://papl.cs.brown.edu/2016/Type_Inference.html pub(super) struct OccursCheck<'a> { engines: &'a Engines, } impl<'a> OccursCheck<'a> { /// Creates a new [OccursCheck]. pub(super) fn new(engines: &'a Engines) -> OccursCheck<'a> { OccursCheck { engines } } /// Checks whether `generic` occurs in `other` and returns true if so. /// /// NOTE: This first-cut implementation takes the most simple approach--- /// does `other` contain `generic`? If so, return true. /// TODO: In the future, we may need to expand this definition. /// /// NOTE: This implementation assumes that `other` =/ `generic`, in which /// case the occurs check would return `false`, as this is a valid /// unification. pub(super) fn check(&self, generic: TypeId, other: TypeId) -> bool { let other_generics = other.extract_nested_generics(self.engines); other_generics.contains( &self .engines .help_out((*self.engines.te().get(generic)).clone()), ) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/type_system/unify/unify_check.rs
sway-core/src/type_system/unify/unify_check.rs
use crate::{ ast_elements::type_parameter::ConstGenericExpr, engine_threading::{Engines, PartialEqWithEngines, PartialEqWithEnginesContext}, language::{ ty::{TyEnumDecl, TyStructDecl}, CallPathType, }, type_system::priv_prelude::*, }; #[derive(Debug, Clone)] enum UnifyCheckMode { /// Given two [TypeId]'s `left` and `right`, check to see if `left` can be /// coerced into `right`. /// /// `left` can be coerced into `right` if it can be generalized over /// `right`. For example, the generic `T` can be coerced into the /// placeholder type `_` or another generic with the same name and with /// certain compatible trait constraints. The type `u8` can also be coerced /// into the placeholder type `_` or a generic type. The placeholder type /// can be coerced into any type. /// /// Given: /// /// ```ignore /// struct Data<T, F> { /// x: T, /// y: F, /// } /// ``` /// /// the type `Data<T, F>` can be coerced into the placeholder type `_` or a /// generic type. /// /// Given: /// /// ```ignore /// struct Data<T, F> { /// x: T, /// y: F, /// } /// /// impl<T> Data<T, T> { } /// ``` /// /// the type `Data<T, T>` can be coerced into `Data<T, F>`, but /// _`Data<T, F>` cannot be coerced into `Data<T, T>`_. /// /// Given: /// /// ```ignore /// struct Data<T, F> { /// x: T, /// y: F, /// } /// /// impl<T> Data<T, T> { } /// /// fn dummy() { /// // the type of foo is Data<bool, u64> /// let foo = Data { /// x: true, /// y: 1u64 /// }; /// // the type of bar is Data<u8, u8> /// let bar = Data { /// x: 0u8, /// y: 0u8 /// }; /// } /// ``` /// /// then: /// /// | type: | can be coerced into of: | can not be: | /// |-------------------|--------------------------------------------------------|---------------------| /// | `Data<T, T>` | `Data<T, F>`, any generic type, `_` type | | /// | `Data<T, F>` | any generic type, `_` type | `Data<T, T>` | /// | `Data<bool, u64>` | `Data<T, F>`, any generic type, `_` type | `Data<T, T>` | /// | `Data<u8, u8>` | `Data<T, T>`, `Data<T, F>`, any generic type, `_` type | | /// /// For generic types with trait constraints, the generic type `left` can be /// coerced into the generic type `right` when the trait constraints of /// `right` can be coerced into the trait constraints of `left`. This is a /// bit unintuitive, but you can think of it this way---a generic type /// `left` can be generalized over `right` when `right` has no methods /// that `left` doesn't have. These methods are coming from the trait /// constraints---if the trait constraints of `right` can be coerced into /// the trait constraints of `left`, then we know that `right` has unique /// methods. Coercion, /// Given two `TypeInfo`'s `self` and `other`, check to see if `self` is /// unidirectionally a subset of `other`. /// /// `self` is a subset of `other` if it can be generalized over `other`. /// For example, the generic `T` is a subset of the generic `F` because /// anything of the type `T` could also be of the type `F` (minus any /// external context that may make this statement untrue). /// /// Given: /// /// ```ignore /// struct Data<T, F> { /// x: T, /// y: F, /// } /// ``` /// /// the type `Data<T, F>` is a subset of any generic type. /// /// Given: /// /// ```ignore /// struct Data<T, F> { /// x: T, /// y: F, /// } /// /// impl<T> Data<T, T> { } /// ``` /// /// the type `Data<T, T>` is a subset of `Data<T, F>`, but _`Data<T, F>` is /// not a subset of `Data<T, T>`_. /// /// Given: /// /// ```ignore /// struct Data<T, F> { /// x: T, /// y: F, /// } /// /// impl<T> Data<T, T> { } /// /// fn dummy() { /// // the type of foo is Data<bool, u64> /// let foo = Data { /// x: true, /// y: 1u64 /// }; /// // the type of bar is Data<u8, u8> /// let bar = Data { /// x: 0u8, /// y: 0u8 /// }; /// } /// ``` /// /// then: /// /// | type: | is subset of: | is not a subset of: | /// |-------------------|----------------------------------------------|---------------------| /// | `Data<T, T>` | `Data<T, F>`, any generic type | | /// | `Data<T, F>` | any generic type | `Data<T, T>` | /// | `Data<bool, u64>` | `Data<T, F>`, any generic type | `Data<T, T>` | /// | `Data<u8, u8>` | `Data<T, T>`, `Data<T, F>`, any generic type | | /// /// For generic types with trait constraints, the generic type `self` is a /// subset of the generic type `other` when the trait constraints of /// `other` are a subset of the trait constraints of `self`. This is a bit /// unintuitive, but you can think of it this way---a generic type `self` /// can be generalized over `other` when `other` has no methods /// that `self` doesn't have. These methods are coming from the trait /// constraints---if the trait constraints of `other` are a subset of the /// trait constraints of `self`, then we know that `other` has unique /// methods. ConstraintSubset, /// Given two `TypeInfo`'s `self` and `other`, checks to see if `self` is /// unidirectionally a subset of `other`, excluding consideration of generic /// types. NonGenericConstraintSubset, NonDynamicEquality, } /// Helper struct to aid in type coercion. pub(crate) struct UnifyCheck<'a> { engines: &'a Engines, mode: UnifyCheckMode, unify_ref_mut: bool, ignore_generic_names: bool, } impl<'a> UnifyCheck<'a> { pub(crate) fn coercion(engines: &'a Engines) -> Self { Self { engines, mode: UnifyCheckMode::Coercion, unify_ref_mut: true, ignore_generic_names: false, } } pub(crate) fn constraint_subset(engines: &'a Engines) -> Self { Self { engines, mode: UnifyCheckMode::ConstraintSubset, unify_ref_mut: true, ignore_generic_names: false, } } pub(crate) fn non_generic_constraint_subset(engines: &'a Engines) -> Self { Self { engines, mode: UnifyCheckMode::NonGenericConstraintSubset, unify_ref_mut: true, ignore_generic_names: false, } } pub(crate) fn non_dynamic_equality(engines: &'a Engines) -> Self { Self { engines, mode: UnifyCheckMode::NonDynamicEquality, unify_ref_mut: true, ignore_generic_names: false, } } pub(crate) fn with_unify_ref_mut(&self, unify_ref_mut: bool) -> Self { Self { unify_ref_mut, ignore_generic_names: self.ignore_generic_names, engines: self.engines, mode: self.mode.clone(), } } pub(crate) fn with_ignore_generic_names(&self, ignore_generic_names: bool) -> Self { Self { unify_ref_mut: self.unify_ref_mut, ignore_generic_names, engines: self.engines, mode: self.mode.clone(), } } pub(crate) fn check(&self, left: TypeId, right: TypeId) -> bool { use TypeInfo::*; use UnifyCheckMode::NonGenericConstraintSubset; if left == right { return true; } let left_info = self.engines.te().get(left); let right_info = self.engines.te().get(right); // override top level generics with simple equality but only at top level if let NonGenericConstraintSubset = self.mode { if let UnknownGeneric { .. } = &*right_info { return left_info.eq(&right_info, &PartialEqWithEnginesContext::new(self.engines)); } } self.check_inner(left, right) } fn check_length(&self, l1: &Length, r1: &Length) -> bool { match (&l1.expr(), &r1.expr()) { ( ConstGenericExpr::Literal { val: l, .. }, ConstGenericExpr::Literal { val: r, .. }, ) => l == r, ( ConstGenericExpr::AmbiguousVariableExpression { ident: l, .. }, ConstGenericExpr::AmbiguousVariableExpression { ident: r, .. }, ) => l == r, ( ConstGenericExpr::Literal { .. }, ConstGenericExpr::AmbiguousVariableExpression { .. }, ) => true, _ => false, } } fn check_inner(&self, left: TypeId, right: TypeId) -> bool { use TypeInfo::{ Alias, Array, ContractCaller, Custom, Enum, ErrorRecovery, Never, Numeric, Placeholder, Ref, Slice, StringArray, StringSlice, Struct, Tuple, Unknown, UnknownGeneric, UnsignedInteger, }; use UnifyCheckMode::{ Coercion, ConstraintSubset, NonDynamicEquality, NonGenericConstraintSubset, }; if left == right { return true; } let left_info = self.engines.te().get(left); let right_info = self.engines.te().get(right); // common recursion patterns match (&*left_info, &*right_info) { // when a type alias is encountered, defer the decision to the type it contains (i.e. the // type it aliases with) (Alias { ty, .. }, _) => return self.check_inner(ty.type_id, right), (_, Alias { ty, .. }) => return self.check_inner(left, ty.type_id), (Never, Never) => { return true; } (Array(l0, l1), Array(r0, r1)) => { let elem_types_unify = self.check_inner(l0.type_id, r0.type_id); return if !elem_types_unify { false } else { self.check_length(l1, r1) }; } (Slice(l0), Slice(r0)) => { return self.check_inner(l0.type_id, r0.type_id); } (Tuple(l_types), Tuple(r_types)) => { let l_types = l_types.iter().map(|x| x.type_id).collect::<Vec<_>>(); let r_types = r_types.iter().map(|x| x.type_id).collect::<Vec<_>>(); return self.check_multiple(&l_types, &r_types); } (Struct(l_decl_ref), Struct(r_decl_ref)) => { let l_decl = self.engines.de().get_struct(l_decl_ref); let r_decl = self.engines.de().get_struct(r_decl_ref); return self.check_structs(&l_decl, &r_decl); } ( Custom { qualified_call_path: l_name, type_arguments: l_type_args, }, Custom { qualified_call_path: r_name, type_arguments: r_type_args, }, ) => { let l_types = l_type_args .as_ref() .unwrap_or(&vec![]) .iter() .map(|x| x.type_id()) .collect::<Vec<_>>(); let r_types = r_type_args .as_ref() .unwrap_or(&vec![]) .iter() .map(|x| x.type_id()) .collect::<Vec<_>>(); let same_qualified_path_root = match ( l_name.qualified_path_root.clone(), r_name.qualified_path_root.clone(), ) { (Some(l_qualified_path_root), Some(r_qualified_path_root)) => { self.check_inner( l_qualified_path_root.ty.type_id(), r_qualified_path_root.ty.type_id(), ) && self.check_inner( l_qualified_path_root.as_trait, r_qualified_path_root.as_trait, ) } (None, None) => true, _ => false, }; return l_name.call_path.suffix == r_name.call_path.suffix && same_qualified_path_root && self.check_multiple(&l_types, &r_types); } (Enum(l_decl_ref), Enum(r_decl_ref)) => { let l_decl = self.engines.de().get_enum(l_decl_ref); let r_decl = self.engines.de().get_enum(r_decl_ref); return self.check_enums(&l_decl, &r_decl); } ( Ref { to_mutable_value: l_to_mut, referenced_type: l_ty, }, Ref { to_mutable_value: r_to_mut, referenced_type: r_ty, }, ) if self.unify_ref_mut => { // Unification is possible in these situations, assuming that the referenced types // can unify: // l -> r // - `&` -> `&` // - `&mut` -> `&` // - `&mut` -> `&mut` return (*l_to_mut || !*r_to_mut) && self.check_inner(l_ty.type_id, r_ty.type_id); } ( Ref { to_mutable_value: l_to_mut, referenced_type: l_ty, }, Ref { to_mutable_value: r_to_mut, referenced_type: r_ty, }, ) => { return *l_to_mut == *r_to_mut && self.check_inner(l_ty.type_id, r_ty.type_id); } (UnknownGeneric { parent: lp, .. }, r) if lp.is_some() && self .engines .te() .get(lp.unwrap()) .eq(r, &PartialEqWithEnginesContext::new(self.engines)) => { return true; } (l, UnknownGeneric { parent: rp, .. }) if rp.is_some() && self .engines .te() .get(rp.unwrap()) .eq(l, &PartialEqWithEnginesContext::new(self.engines)) => { return true; } (UnknownGeneric { parent: lp, .. }, UnknownGeneric { parent: rp, .. }) if lp.is_some() && rp.is_some() && self.engines.te().get(lp.unwrap()).eq( &*self.engines.te().get(rp.unwrap()), &PartialEqWithEnginesContext::new(self.engines), ) => { return true; } _ => {} } match self.mode { Coercion => { match (&*left_info, &*right_info) { (r @ UnknownGeneric { .. }, e @ UnknownGeneric { .. }) if TypeInfo::is_self_type(r) || TypeInfo::is_self_type(e) => { true } ( UnknownGeneric { name: ln, trait_constraints: ltc, parent: _, is_from_type_parameter: _, }, UnknownGeneric { name: rn, trait_constraints: rtc, parent: _, is_from_type_parameter: _, }, ) => { (ln == rn || self.ignore_generic_names) && rtc.eq(ltc, &PartialEqWithEnginesContext::new(self.engines)) } // any type can be coerced into a generic, (_e, _g @ UnknownGeneric { .. }) => true, // Never coerces to any other type. (Never, _) => true, // the placeholder type can be coerced into any type (Placeholder(_), _) => true, // any type can be coerced into the placeholder type (_, Placeholder(_)) => true, (Unknown, _) => true, (_, Unknown) => true, (UnsignedInteger(lb), UnsignedInteger(rb)) => lb == rb, (Numeric, UnsignedInteger(_)) => true, (UnsignedInteger(_), Numeric) => true, (StringSlice, StringSlice) => true, (StringArray(l), StringArray(r)) => self.check_length(l, r), // For contract callers, they can be coerced if they have the same // name and at least one has an address of `None` ( ref r @ ContractCaller { abi_name: ref ran, address: ref ra, }, ref e @ ContractCaller { abi_name: ref ean, address: ref ea, }, ) => { r.eq(e, &PartialEqWithEnginesContext::new(self.engines)) || (ran == ean && ra.is_none()) || matches!(ran, AbiName::Deferred) || (ran == ean && ea.is_none()) || matches!(ean, AbiName::Deferred) } (ErrorRecovery(_), _) => true, (_, ErrorRecovery(_)) => true, (a, b) => a.eq(b, &PartialEqWithEnginesContext::new(self.engines)), } } ConstraintSubset | NonGenericConstraintSubset => { match (&*left_info, &*right_info) { (StringArray(l), StringArray(r)) => self.check_length(l, r), ( UnknownGeneric { name: _, trait_constraints: ltc, parent: _, is_from_type_parameter: _, }, UnknownGeneric { name: _, trait_constraints: rtc, parent: _, is_from_type_parameter: _, }, ) => { matches!(self.mode, NonGenericConstraintSubset) || rtc.eq(ltc, &PartialEqWithEnginesContext::new(self.engines)) } // any type can be coerced into a generic, (_e, _g @ UnknownGeneric { .. }) => { // Perform this check otherwise &T and T would return true !matches!(&*left_info, TypeInfo::Ref { .. }) } (Placeholder(..), _) => true, (a, b) => a.eq(b, &PartialEqWithEnginesContext::new(self.engines)), } } NonDynamicEquality => match (&*left_info, &*right_info) { // these cases are false because, unless left and right have the same // TypeId, they may later resolve to be different types in the type // engine (TypeInfo::Unknown, TypeInfo::Unknown) => false, (TypeInfo::Numeric, TypeInfo::Numeric) => false, // these cases are able to be directly compared (TypeInfo::Contract, TypeInfo::Contract) => true, (TypeInfo::Boolean, TypeInfo::Boolean) => true, (TypeInfo::B256, TypeInfo::B256) => true, (TypeInfo::ErrorRecovery(_), TypeInfo::ErrorRecovery(_)) => true, (TypeInfo::StringSlice, TypeInfo::StringSlice) => true, (TypeInfo::StringArray(l), TypeInfo::StringArray(r)) => self.check_length(l, r), (TypeInfo::UnsignedInteger(l), TypeInfo::UnsignedInteger(r)) => l == r, (TypeInfo::RawUntypedPtr, TypeInfo::RawUntypedPtr) => true, (TypeInfo::RawUntypedSlice, TypeInfo::RawUntypedSlice) => true, ( TypeInfo::UnknownGeneric { name: rn, trait_constraints: rtc, parent: _, is_from_type_parameter: _, }, TypeInfo::UnknownGeneric { name: en, trait_constraints: etc, parent: _, is_from_type_parameter: _, }, ) => { rn.as_str() == en.as_str() && rtc.eq(etc, &PartialEqWithEnginesContext::new(self.engines)) } (TypeInfo::Placeholder(_), TypeInfo::Placeholder(_)) => false, ( TypeInfo::ContractCaller { abi_name: l_abi_name, address: l_address, }, TypeInfo::ContractCaller { abi_name: r_abi_name, address: r_address, }, ) => { l_abi_name == r_abi_name && Option::zip(l_address.clone(), r_address.clone()) .map(|(l_address, r_address)| { self.check(l_address.return_type, r_address.return_type) }) .unwrap_or(true) } _ => false, }, } } /// Given two lists of [TypeId]'s `left` and `right`, check to see if /// `left` can be coerced into `right`. /// /// `left` can be coerced into `right` if the following invariants are true: /// 1. `left` and `right` are of the same length _n_ /// 2. For every _i_ in [0, n), `left`ᵢ can be coerced into `right`ᵢ /// 3. The elements of `left` satisfy the trait constraints of `right` /// /// A property that falls of out these constraints are that if `left` and /// `right` are empty, then `left` can be coerced into `right`. /// /// Given: /// /// ```ignore /// left: [T] /// right: [T, F] /// ``` /// /// `left` cannot be coerced into `right` because it violates invariant #1. /// /// Given: /// /// ```ignore /// left: [T, F] /// right: [bool, F] /// ``` /// /// `left` cannot be coerced into `right` because it violates invariant #2. /// /// Given: /// /// ```ignore /// left: [T, F] /// right: [T, T] /// ``` /// /// `left` cannot be coerced into `right` because it violates invariant #3. /// /// Given: /// /// ```ignore /// left: [T, T] /// right: [T, F] /// ``` /// /// `left` can be coerced into `right`. /// /// Given: /// /// ```ignore /// left: [bool, T] /// right: [T, F] /// ``` /// /// `left` can be coerced into `right`. /// /// Given: /// /// ```ignore /// left: [Data<T, T>, Data<T, F>] /// right: [Data<T, F>, Data<T, F>] /// ``` /// /// `left` can be coerced into `right`. /// fn check_multiple(&self, left: &[TypeId], right: &[TypeId]) -> bool { use TypeInfo::{Numeric, Placeholder, Unknown, UnsignedInteger}; use UnifyCheckMode::{ Coercion, ConstraintSubset, NonDynamicEquality, NonGenericConstraintSubset, }; // invariant 1. `left` and `right` are of the same length _n_ if left.len() != right.len() { return false; } // if `left` and `right` are empty, `left` can be coerced into `right` if left.is_empty() && right.is_empty() { return true; } // invariant 2. For every _i_ in [0, n), `left`ᵢ can be coerced into // `right`ᵢ for (l, r) in left.iter().zip(right.iter()) { if !self.check_inner(*l, *r) { return false; } } match self.mode { Coercion | ConstraintSubset | NonGenericConstraintSubset => { // invariant 3. The elements of `left` satisfy the constraints of `right` let left_types = left .iter() .map(|x| self.engines.te().get(*x)) .collect::<Vec<_>>(); let right_types = right .iter() .map(|x| self.engines.te().get(*x)) .collect::<Vec<_>>(); let mut constraints = vec![]; for i in 0..(right_types.len() - 1) { for j in (i + 1)..right_types.len() { let a = right_types.get(i).unwrap(); let b = right_types.get(j).unwrap(); if matches!(&self.mode, Coercion) && (matches!( (&**a, &**b), (_, Placeholder(_)) | (Placeholder(_), _) | (UnsignedInteger(_), Numeric) | (Numeric, UnsignedInteger(_)) | (_, Unknown) | (Unknown, _) )) { continue; } if a.eq(b, &PartialEqWithEnginesContext::new(self.engines)) { // if a and b are the same type constraints.push((i, j)); } } } for (i, j) in &constraints { let a = left_types.get(*i).unwrap(); let b = left_types.get(*j).unwrap(); if matches!(&self.mode, Coercion) && (matches!( (&**a, &**b), (_, Placeholder(_)) | (Placeholder(_), _) | (UnsignedInteger(_), Numeric) | (Numeric, UnsignedInteger(_)) | (_, Unknown) | (Unknown, _) )) { continue; } if !a.eq(b, &PartialEqWithEnginesContext::new(self.engines)) { return false; } } } // no constraint check, just propagate the check NonDynamicEquality => {} } // if all of the invariants are met, then `self` can be coerced into // `other`! true } pub(crate) fn check_enums(&self, left: &TyEnumDecl, right: &TyEnumDecl) -> bool { assert!( matches!(left.call_path.callpath_type, CallPathType::Full) && matches!(right.call_path.callpath_type, CallPathType::Full), "call paths of enum declarations must always be full paths" ); // Avoid unnecessary `collect::<Vec>>` of variant names // and enum type parameters by short-circuiting. if left.call_path != right.call_path { return false; } // TODO: Is checking of variants necessary? Can we have two enums with the same `call_path` // with different variants? // We can have multiple declarations in a file and "already exist" errors, but those // different declarations shouldn't reach the type checking phase. The last one // will always win. if left.variants.len() != right.variants.len() { return false; } // Cheap name check first. if left .variants .iter() .zip(right.variants.iter()) .any(|(l, r)| l.name != r.name) { return false; } if left .variants .iter() .zip(right.variants.iter()) .any(|(l, r)| !self.check_inner(l.type_argument.type_id, r.type_argument.type_id)) { return false; } if left.generic_parameters.len() != right.generic_parameters.len() { return false; } let mut l_types = vec![]; let mut r_types = vec![]; for (l, r) in left .generic_parameters .iter() .zip(right.generic_parameters.iter()) { match (l, r) { (TypeParameter::Type(l), TypeParameter::Type(r)) => { l_types.push(l.type_id); r_types.push(r.type_id); } (TypeParameter::Const(l), TypeParameter::Const(r)) => { match (l.expr.as_ref(), r.expr.as_ref()) { (None, None) => {} (None, Some(_)) => {} (Some(_), None) => {} ( Some(ConstGenericExpr::Literal { val: l_val, .. }), Some(ConstGenericExpr::Literal { val: r_val, .. }), ) => { assert!(l_val == r_val); } (Some(_), Some(_)) => todo!( "Will be implemented by https://github.com/FuelLabs/sway/issues/6860" ), } } _ => return false, } } self.check_multiple(&l_types, &r_types) } pub(crate) fn check_structs(&self, left: &TyStructDecl, right: &TyStructDecl) -> bool { assert!( matches!(left.call_path.callpath_type, CallPathType::Full) && matches!(right.call_path.callpath_type, CallPathType::Full), "call paths of struct declarations must always be full paths" ); // Avoid unnecessary `collect::<Vec>>` of variant names // and enum type parameters by short-circuiting. if left.call_path != right.call_path { return false; } // TODO: Is checking of fields necessary? Can we have two structs with the same `call_path` // with different fields? // We can have multiple declarations in a file and "already exist" errors, but those // different declarations shouldn't reach the type checking phase. The last one // will always win. if left.fields.len() != right.fields.len() { return false; } // Cheap name check first. if left .fields .iter() .zip(right.fields.iter()) .any(|(l, r)| l.name != r.name) { return false; } if left .fields .iter() .zip(right.fields.iter()) .any(|(l, r)| !self.check_inner(l.type_argument.type_id, r.type_argument.type_id)) { return false; } if left.generic_parameters.len() != right.generic_parameters.len() { return false; } let mut l_types = vec![]; let mut r_types = vec![]; for (l, r) in left .generic_parameters .iter() .zip(right.generic_parameters.iter()) { match (l, r) {
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/query_engine/mod.rs
sway-core/src/query_engine/mod.rs
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::{ collections::HashMap, ops::{Deref, DerefMut}, path::PathBuf, sync::Arc, time::SystemTime, }; use sway_error::{ error::CompileError, warning::{CompileInfo, CompileWarning}, }; use sway_types::{IdentUnique, ProgramId, SourceId, Spanned}; use crate::{ decl_engine::{DeclId, DeclRef}, language::ty::{TyFunctionDecl, TyFunctionSig, TyModule}, namespace, Engines, Programs, }; #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct ModuleCacheKey { pub path: Arc<PathBuf>, pub include_tests: bool, } impl ModuleCacheKey { pub fn new(path: Arc<PathBuf>, include_tests: bool) -> Self { Self { path, include_tests, } } } #[derive(Clone, Debug)] pub struct ModuleCommonInfo { pub path: Arc<PathBuf>, pub hash: u64, pub include_tests: bool, pub dependencies: Vec<Arc<PathBuf>>, } #[derive(Clone, Debug)] pub struct ParsedModuleInfo { pub modified_time: Option<SystemTime>, pub version: Option<u64>, } #[derive(Clone, Debug)] pub struct TypedModuleInfo { pub module: Arc<TyModule>, pub namespace_module: Arc<namespace::Module>, pub version: Option<u64>, } #[derive(Clone, Debug)] pub struct ModuleCacheEntry { pub common: ModuleCommonInfo, pub parsed: ParsedModuleInfo, pub typed: Option<TypedModuleInfo>, } impl ModuleCacheEntry { pub fn new(common: ModuleCommonInfo, parsed: ParsedModuleInfo) -> Self { Self { common, parsed, typed: None, } } pub fn is_typed(&self) -> bool { self.typed.is_some() } pub fn set_typed(&mut self, typed: TypedModuleInfo) { self.typed = Some(typed); } pub fn update_common(&mut self, new_common: ModuleCommonInfo) { self.common = new_common; } pub fn update_parsed(&mut self, new_parsed: ParsedModuleInfo) { self.parsed = new_parsed; } pub fn update_parsed_and_common( &mut self, new_common: ModuleCommonInfo, new_parsed: ParsedModuleInfo, ) { self.common = new_common; self.parsed = new_parsed; } } #[derive(Debug, Default, Clone)] pub struct ModuleCacheMap(HashMap<ModuleCacheKey, ModuleCacheEntry>); impl Deref for ModuleCacheMap { type Target = HashMap<ModuleCacheKey, ModuleCacheEntry>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ModuleCacheMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl ModuleCacheMap { pub fn update_entry( &mut self, key: &ModuleCacheKey, new_common: ModuleCommonInfo, new_parsed: ParsedModuleInfo, ) { if let Some(entry) = self.get_mut(key) { entry.update_parsed_and_common(new_common, new_parsed); } else { self.insert(key.clone(), ModuleCacheEntry::new(new_common, new_parsed)); } } } pub type ProgramsCacheMap = HashMap<Arc<PathBuf>, ProgramsCacheEntry>; pub type FunctionsCacheMap = HashMap<(IdentUnique, String), FunctionCacheEntry>; #[derive(Clone, Debug)] pub struct ProgramsCacheEntry { pub path: Arc<PathBuf>, pub programs: Programs, pub handler_data: (Vec<CompileError>, Vec<CompileWarning>, Vec<CompileInfo>), } #[derive(Clone, Debug)] pub struct FunctionCacheEntry { pub fn_decl: DeclRef<DeclId<TyFunctionDecl>>, } #[derive(Debug, Default)] pub struct QueryEngine { // We want the below types wrapped in Arcs to optimize cloning from LSP. programs_cache: CowCache<ProgramsCacheMap>, pub module_cache: CowCache<ModuleCacheMap>, // NOTE: Any further AstNodes that are cached need to have garbage collection applied, see clear_module() function_cache: CowCache<FunctionsCacheMap>, } impl Clone for QueryEngine { fn clone(&self) -> Self { Self { programs_cache: CowCache::new(self.programs_cache.read().clone()), module_cache: CowCache::new(self.module_cache.read().clone()), function_cache: CowCache::new(self.function_cache.read().clone()), } } } impl QueryEngine { pub fn update_or_insert_parsed_module_cache_entry(&self, entry: ModuleCacheEntry) { let path = entry.common.path.clone(); let include_tests = entry.common.include_tests; let key = ModuleCacheKey::new(path, include_tests); let mut cache = self.module_cache.write(); cache.update_entry(&key, entry.common, entry.parsed); } pub fn update_typed_module_cache_entry(&self, key: &ModuleCacheKey, entry: TypedModuleInfo) { let mut cache = self.module_cache.write(); cache.get_mut(key).unwrap().set_typed(entry); } pub fn get_programs_cache_entry(&self, path: &Arc<PathBuf>) -> Option<ProgramsCacheEntry> { let cache = self.programs_cache.read(); cache.get(path).cloned() } pub fn insert_programs_cache_entry(&self, entry: ProgramsCacheEntry) { let mut cache = self.programs_cache.write(); cache.insert(entry.path.clone(), entry); } pub fn get_function( &self, engines: &Engines, ident: &IdentUnique, sig: TyFunctionSig, ) -> Option<DeclRef<DeclId<TyFunctionDecl>>> { let cache = self.function_cache.read(); cache .get(&(ident.clone(), sig.get_type_str(engines))) .map(|s| s.fn_decl.clone()) } pub fn insert_function( &self, engines: &Engines, ident: IdentUnique, sig: TyFunctionSig, fn_decl: DeclRef<DeclId<TyFunctionDecl>>, ) { let mut cache = self.function_cache.write(); cache.insert( (ident, sig.get_type_str(engines)), FunctionCacheEntry { fn_decl }, ); } /// Removes all data associated with the `source_id` from the function cache. pub fn clear_module(&mut self, source_id: &SourceId) { self.function_cache .write() .retain(|(ident, _), _| ident.span().source_id() != Some(source_id)); } /// Removes all data associated with the `program_id` from the function cache. pub fn clear_program(&mut self, program_id: &ProgramId) { self.function_cache.write().retain(|(ident, _), _| { ident .span() .source_id() .is_none_or(|id| id.program_id() != *program_id) }); } /// Commits all changes to their respective caches. pub fn commit(&self) { self.programs_cache.commit(); self.module_cache.commit(); self.function_cache.commit(); } } /// Thread-safe, copy-on-write cache optimized for LSP operations. /// /// Addresses key LSP challenges: /// 1. Concurrent read access to shared data /// 2. Local modifications for cancellable operations (e.g., compilation) /// 3. Prevents incomplete results from affecting shared state /// 4. Maintains consistency via explicit commit step /// /// Uses `Arc<RwLock<T>>` for shared state and `RwLock<Option<T>>` for local changes. /// Suitable for interactive sessions with frequent file changes. #[derive(Debug, Default)] pub struct CowCache<T: Clone> { inner: Arc<RwLock<T>>, local: RwLock<Option<T>>, } impl<T: Clone> CowCache<T> { /// Creates a new `CowCache` with the given initial value. /// /// The value is wrapped in an `Arc<RwLock<T>>` to allow shared access across threads. pub fn new(value: T) -> Self { Self { inner: Arc::new(RwLock::new(value)), local: RwLock::new(None), } } /// Provides read access to the cached value. /// /// If a local modification exists, it returns a reference to the local copy. /// Otherwise, it returns a reference to the shared state. /// /// This method is optimized for concurrent read access in LSP operations. pub fn read(&self) -> impl Deref<Target = T> + '_ { if self.local.read().is_some() { ReadGuard::Local(self.local.read()) } else { ReadGuard::Shared(self.inner.read()) } } /// Provides write access to a local copy of the cached value. /// /// In LSP, this is used for operations like compilation tasks that may be cancelled. /// It allows modifications without affecting the shared state until explicitly committed. pub fn write(&self) -> impl DerefMut<Target = T> + '_ { let mut local = self.local.write(); if local.is_none() { *local = Some(self.inner.read().clone()); } WriteGuard(local) } /// Commits local modifications to the shared state. /// /// Called after successful completion of a compilation task. /// If a task is cancelled, not calling this method effectively discards local changes. pub fn commit(&self) { if let Some(local) = self.local.write().take() { *self.inner.write() = local; } } } /// A guard type that provides read access to either the local or shared state. enum ReadGuard<'a, T: Clone> { Local(RwLockReadGuard<'a, Option<T>>), Shared(RwLockReadGuard<'a, T>), } impl<T: Clone> Deref for ReadGuard<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { match self { ReadGuard::Local(r) => r.as_ref().unwrap(), ReadGuard::Shared(guard) => guard.deref(), } } } /// A guard type that provides write access to the local state. struct WriteGuard<'a, T: Clone>(RwLockWriteGuard<'a, Option<T>>); impl<T: Clone> Deref for WriteGuard<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { self.0.as_ref().unwrap() } } impl<T: Clone> DerefMut for WriteGuard<'_, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.0.as_mut().unwrap() } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/control_flow_analysis/dead_code_analysis.rs
sway-core/src/control_flow_analysis/dead_code_analysis.rs
use super::*; use crate::{ decl_engine::*, language::{ parsed::TreeType, ty::{ self, ConfigurableDecl, ConstantDecl, FunctionDecl, ProjectionKind, StructDecl, TraitDecl, TyAstNode, TyAstNodeContent, TyDecl, TyImplItem, TypeAliasDecl, }, CallPath, CallPathType, Visibility, }, transform::Attributes, type_system::TypeInfo, Engines, GenericTypeArgument, TypeEngine, TypeId, }; use petgraph::{prelude::NodeIndex, visit::Dfs}; use std::collections::{BTreeSet, HashMap}; use sway_ast::Intrinsic; use sway_error::{error::CompileError, type_error::TypeError}; use sway_error::{ handler::Handler, warning::{CompileWarning, Warning}, }; use sway_types::{constants::STD, span::Span, Ident, Named, Spanned}; // Defines if this node is a root in the dca graph or not fn is_entry_point(node: &TyAstNode, decl_engine: &DeclEngine, tree_type: &TreeType) -> bool { match tree_type { TreeType::Predicate | TreeType::Script => { // Predicates and scripts have main and test functions as entry points. match node { TyAstNode { span: _, content: TyAstNodeContent::Declaration(TyDecl::FunctionDecl(FunctionDecl { decl_id, .. })), .. } => { let decl = decl_engine.get_function(decl_id); decl.is_entry() || decl.is_main() || decl.is_test() } _ => false, } } TreeType::Contract | TreeType::Library => match node { TyAstNode { content: TyAstNodeContent::Declaration(TyDecl::FunctionDecl(FunctionDecl { decl_id })), .. } => { let decl = decl_engine.get_function(decl_id); decl.visibility == Visibility::Public || decl.is_test() || decl.is_fallback() } TyAstNode { content: TyAstNodeContent::Declaration(TyDecl::TraitDecl(TraitDecl { decl_id })), .. } => decl_engine.get_trait(decl_id).visibility.is_public(), TyAstNode { content: TyAstNodeContent::Declaration(TyDecl::StructDecl(StructDecl { decl_id, .. })), .. } => { let struct_decl = decl_engine.get_struct(decl_id); struct_decl.visibility == Visibility::Public } TyAstNode { content: TyAstNodeContent::Declaration(TyDecl::ImplSelfOrTrait { .. }), .. } => true, TyAstNode { content: TyAstNodeContent::Declaration(TyDecl::ConstantDecl(ConstantDecl { decl_id })), .. } => { let decl = decl_engine.get_constant(decl_id); decl.visibility.is_public() } TyAstNode { content: TyAstNodeContent::Declaration(TyDecl::ConfigurableDecl(ConfigurableDecl { .. })), .. } => false, TyAstNode { content: TyAstNodeContent::Declaration(TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id, .. })), .. } => { let decl = decl_engine.get_type_alias(decl_id); decl.visibility.is_public() } _ => false, }, } } impl<'cfg> ControlFlowGraph<'cfg> { pub(crate) fn find_dead_code(&self, decl_engine: &DeclEngine) -> Vec<CompileWarning> { // Dead code is code that has no path from the entry point. // Collect all connected nodes by traversing from the entries. // The dead nodes are those we did not collect. let mut connected_from_entry = BTreeSet::new(); let mut dfs = Dfs::empty(&self.graph); for &entry in &self.entry_points { dfs.move_to(entry); while let Some(node) = dfs.next(&self.graph) { connected_from_entry.insert(node); } } // Collect all nodes that are connected from another node. let mut connections_count: HashMap<NodeIndex, u32> = HashMap::<NodeIndex, u32>::new(); for edge in self.graph.raw_edges() { if let Some(count) = connections_count.get(&edge.target()) { connections_count.insert(edge.target(), count + 1); } else { connections_count.insert(edge.target(), 1); } } let is_dead_check = |n: &NodeIndex| { match &self.graph[*n] { ControlFlowGraphNode::ProgramNode { node: ty::TyAstNode { content: ty::TyAstNodeContent::Declaration(ty::TyDecl::VariableDecl { .. }), .. }, .. } => { // Consider variables declarations dead when count is not greater than 1 connections_count .get(n) .cloned() .is_none_or(|count| count <= 1) } ControlFlowGraphNode::FunctionParameter { .. } => { // Consider variables declarations dead when count is not greater than 1 // Function param always has the function pointing to them connections_count .get(n) .cloned() .is_none_or(|count| count <= 1) } _ => false, } }; let is_alive_check = |n: &NodeIndex| { match &self.graph[*n] { ControlFlowGraphNode::ProgramNode { node: ty::TyAstNode { content: ty::TyAstNodeContent::Declaration(ty::TyDecl::VariableDecl(decl)), .. }, .. } => { if decl.name.as_str().starts_with('_') { true } else { // Consider variables declarations alive when count is greater than 1 // This is explicitly required because the variable may be considered dead // when it is not connected from an entry point, while it may still be used by other dead code. connections_count .get(n) .cloned() .is_some_and(|count| count > 1) } } ControlFlowGraphNode::FunctionParameter { param_name, is_self, .. } => { if *is_self || param_name.as_str().starts_with('_') { // self type parameter is always alive true } else { // Consider param alive when count is greater than 1 // This is explicitly required because the param may be considered dead // when it is not connected from an entry point, while it may still be used by other dead code. connections_count .get(n) .cloned() .is_none_or(|count| count > 1) } } ControlFlowGraphNode::ProgramNode { node: ty::TyAstNode { content: ty::TyAstNodeContent::Declaration(ty::TyDecl::ImplSelfOrTrait { .. }), .. }, .. } => { // Consider impls always alive. // Consider it alive when it does not have any methods. // Also consider it alive when it contains unused methods inside. true } ControlFlowGraphNode::StructField { .. } => { // Consider struct field alive when count is greater than 0 connections_count .get(n) .cloned() .is_some_and(|count| count > 0) } _ => false, } }; let dead_nodes: Vec<_> = self .graph .node_indices() .filter(|n| { (!connected_from_entry.contains(n) || is_dead_check(n)) && !is_alive_check(n) }) .collect(); let dead_function_contains_span = |span: &Span| -> bool { dead_nodes.iter().any(|x| { if let ControlFlowGraphNode::ProgramNode { node: ty::TyAstNode { span: function_span, content: ty::TyAstNodeContent::Declaration(ty::TyDecl::FunctionDecl { .. }), }, .. } = &self.graph[*x] { function_span.end() >= span.end() && function_span.start() <= span.start() } else { false } }) }; let priv_enum_var_warn = |name: &Ident| CompileWarning { span: name.span(), warning_content: Warning::DeadEnumVariant { variant_name: name.clone(), }, }; let dead_enum_variant_warnings = dead_nodes .iter() .filter_map(|x| { // If dead code is allowed return immediately no warning. if allow_dead_code_node(decl_engine, &self.graph, &self.graph[*x]) { None } else { match &self.graph[*x] { ControlFlowGraphNode::EnumVariant { variant_name, is_public, .. } if !is_public => Some(priv_enum_var_warn(variant_name)), _ => None, } } }) .collect::<Vec<_>>(); let dead_ast_node_warnings = dead_nodes .iter() .filter_map(|x| { // If dead code is allowed return immediately no warning. if allow_dead_code_node(decl_engine, &self.graph, &self.graph[*x]) { None } else { match &self.graph[*x] { ControlFlowGraphNode::ProgramNode { node, .. } => { construct_dead_code_warning_from_node(decl_engine, node) } ControlFlowGraphNode::EnumVariant { variant_name, is_public, .. } if !is_public => Some(priv_enum_var_warn(variant_name)), ControlFlowGraphNode::EnumVariant { .. } => None, ControlFlowGraphNode::MethodDeclaration { span, .. } => { Some(CompileWarning { span: span.clone(), warning_content: Warning::DeadMethod, }) } ControlFlowGraphNode::StructField { struct_field_name, .. } => Some(CompileWarning { span: struct_field_name.span(), warning_content: Warning::StructFieldNeverRead, }), ControlFlowGraphNode::StorageField { field_name, .. } => { Some(CompileWarning { span: field_name.span(), warning_content: Warning::DeadStorageDeclaration, }) } ControlFlowGraphNode::OrganizationalDominator(..) => None, ControlFlowGraphNode::FunctionParameter { param_name, .. } => { Some(CompileWarning { span: param_name.span(), warning_content: Warning::DeadDeclaration, }) } } } }) .collect::<Vec<_>>(); let all_warnings = [dead_enum_variant_warnings, dead_ast_node_warnings].concat(); // filter out any overlapping spans -- if a span is contained within another one, // remove it. all_warnings .clone() .into_iter() .filter( |CompileWarning { span, warning_content, }| { if let Warning::UnreachableCode = warning_content { // If the unreachable code is within an unused function, filter it out // since the dead function name is the only warning we want to show. if dead_function_contains_span(span) { return false; } } // if any other warnings contain a span which completely covers this one, filter // out this one. !all_warnings.iter().any( |CompileWarning { span: other_span, .. }| { other_span.end() > span.end() && other_span.start() < span.start() }, ) }, ) .collect() } pub(crate) fn append_module_to_dead_code_graph<'eng: 'cfg>( engines: &'eng Engines, module_nodes: &[ty::TyAstNode], tree_type: &TreeType, graph: &mut ControlFlowGraph<'cfg>, // the `Result` return is just to handle `Unimplemented` errors ) -> Result<(), CompileError> { // do a depth first traversal and cover individual inner ast nodes let decl_engine = engines.de(); let exit_node = Some(graph.add_node(("Program exit".to_string()).into())); let mut entry_points = vec![]; let mut non_entry_points = vec![]; for ast_node in module_nodes { if is_entry_point(ast_node, decl_engine, tree_type) { entry_points.push(ast_node); } else { non_entry_points.push(ast_node); } } for ast_entrypoint in non_entry_points.into_iter().chain(entry_points) { let (_l_leaves, _new_exit_node) = connect_node( engines, ast_entrypoint, graph, &[], exit_node, tree_type, NodeConnectionOptions::default(), )?; } graph.entry_points = collect_entry_points(decl_engine, tree_type, &graph.graph)?; Ok(()) } } /// Collect all entry points into the graph based on the tree type. fn collect_entry_points( decl_engine: &DeclEngine, tree_type: &TreeType, graph: &flow_graph::Graph, ) -> Result<Vec<flow_graph::EntryPoint>, CompileError> { let mut entry_points = vec![]; for i in graph.node_indices() { let is_entry = match &graph[i] { ControlFlowGraphNode::ProgramNode { node, .. } => { is_entry_point(node, decl_engine, tree_type) } _ => false, }; if is_entry { entry_points.push(i); } } Ok(entry_points) } /// This struct is used to pass node connection further down the tree as /// we are processing AST nodes. #[derive(Clone, Copy, Default)] struct NodeConnectionOptions { /// When this is enabled, connect struct fields to the struct itself, /// thus making all struct fields considered as being used in the graph. force_struct_fields_connection: bool, parent_node: Option<NodeIndex>, } fn connect_node<'eng: 'cfg, 'cfg>( engines: &'eng Engines, node: &ty::TyAstNode, graph: &mut ControlFlowGraph<'cfg>, leaves: &[NodeIndex], exit_node: Option<NodeIndex>, tree_type: &TreeType, options: NodeConnectionOptions, ) -> Result<(Vec<NodeIndex>, Option<NodeIndex>), CompileError> { // let mut graph = graph.clone(); let span = node.span.clone(); Ok(match &node.content { ty::TyAstNodeContent::Expression(ty::TyExpression { expression: expr_variant, span, .. }) => { let entry = graph.add_node(ControlFlowGraphNode::from_node_with_parent( node, options.parent_node, )); // insert organizational dominator node // connected to all current leaves for leaf in leaves { graph.add_edge(*leaf, entry, "".into()); } ( connect_expression( engines, expr_variant, graph, &[entry], exit_node, "", tree_type, span.clone(), options, )?, match expr_variant { ty::TyExpressionVariant::ImplicitReturn(_) => None, _ => exit_node, }, ) } ty::TyAstNodeContent::SideEffect(_) => (leaves.to_vec(), exit_node), ty::TyAstNodeContent::Declaration(decl) => { // all leaves connect to this node, then this node is the singular leaf let cfg_node: ControlFlowGraphNode = ControlFlowGraphNode::from_node_with_parent(node, options.parent_node); // check if node for this decl already exists let decl_node = match graph.get_node_from_decl(&cfg_node) { Some(node) => node, None => graph.add_node(cfg_node), }; for leaf in leaves { graph.add_edge(*leaf, decl_node, "".into()); } ( connect_declaration( engines, decl, graph, decl_node, span, exit_node, tree_type, leaves, options, )?, exit_node, ) } ty::TyAstNodeContent::Error(_, _) => (vec![], None), }) } #[allow(clippy::too_many_arguments)] fn connect_declaration<'eng: 'cfg, 'cfg>( engines: &'eng Engines, decl: &ty::TyDecl, graph: &mut ControlFlowGraph<'cfg>, entry_node: NodeIndex, span: Span, exit_node: Option<NodeIndex>, tree_type: &TreeType, leaves: &[NodeIndex], options: NodeConnectionOptions, ) -> Result<Vec<NodeIndex>, CompileError> { let decl_engine = engines.de(); match decl { ty::TyDecl::VariableDecl(var_decl) => { let ty::TyVariableDecl { body, name, type_ascription, .. } = &**var_decl; // Connect variable declaration node to body expression. let result = connect_expression( engines, &body.expression, graph, &[entry_node], exit_node, "variable instantiation", tree_type, body.clone().span, options, ); if let Ok(ref vec) = result { if !vec.is_empty() { // Connect variable declaration node to its type ascription. connect_type_id(engines, type_ascription.type_id, graph, entry_node)?; } } // Insert variable only after connecting body.expressions // This enables: // let ptr = alloc::<u64>(0); // let ptr = realloc::<u64>(ptr, 0, 2); // Where previous ptr is used before adding new ptr to variables. graph.namespace.insert_variable( name.clone(), VariableNamespaceEntry { variable_decl_ix: entry_node, }, ); result } ty::TyDecl::ConstantDecl(ty::ConstantDecl { decl_id, .. }) => { let const_decl = decl_engine.get_constant(decl_id); let ty::TyConstantDecl { call_path, value, .. } = &*const_decl; graph .namespace .insert_global_constant(call_path.suffix.clone(), entry_node); if let Some(value) = &value { connect_expression( engines, &value.expression, graph, &[entry_node], exit_node, "constant declaration expression", tree_type, value.span.clone(), options, ) } else { Ok(leaves.to_vec()) } } ty::TyDecl::ConfigurableDecl(ty::ConfigurableDecl { decl_id, .. }) => { let config_decl = decl_engine.get_configurable(decl_id); let ty::TyConfigurableDecl { call_path, value, type_ascription, .. } = &*config_decl; graph .namespace .insert_configurable(call_path.suffix.clone(), entry_node); connect_type_id(engines, type_ascription.type_id, graph, entry_node)?; if let Some(value) = &value { connect_expression( engines, &value.expression, graph, &[entry_node], exit_node, "configurable declaration expression", tree_type, value.span.clone(), options, ) } else { Ok(leaves.to_vec()) } } ty::TyDecl::ConstGenericDecl(_) => { unreachable!("ConstGenericDecl is not reachable from AstNode") } ty::TyDecl::FunctionDecl(ty::FunctionDecl { decl_id, .. }) => { let fn_decl = decl_engine.get_function(decl_id); connect_typed_fn_decl( engines, &fn_decl, graph, entry_node, span, exit_node, tree_type, options, )?; Ok(leaves.to_vec()) } ty::TyDecl::TraitDecl(ty::TraitDecl { decl_id, .. }) => { let trait_decl = decl_engine.get_trait(decl_id); connect_trait_declaration(&trait_decl, graph, entry_node, tree_type); Ok(leaves.to_vec()) } ty::TyDecl::AbiDecl(ty::AbiDecl { decl_id, .. }) => { let abi_decl = decl_engine.get_abi(decl_id); connect_abi_declaration(engines, &abi_decl, graph, entry_node, tree_type)?; Ok(leaves.to_vec()) } ty::TyDecl::StructDecl(ty::StructDecl { decl_id, .. }) => { let struct_decl = decl_engine.get_struct(decl_id); connect_struct_declaration(&struct_decl, *decl_id, graph, entry_node, tree_type); Ok(leaves.to_vec()) } ty::TyDecl::EnumDecl(ty::EnumDecl { decl_id, .. }) => { let enum_decl = decl_engine.get_enum(decl_id); connect_enum_declaration(&enum_decl, *decl_id, graph, entry_node); Ok(leaves.to_vec()) } ty::TyDecl::EnumVariantDecl(ty::EnumVariantDecl { enum_ref, .. }) => { let enum_decl = decl_engine.get_enum(enum_ref.id()); connect_enum_declaration(&enum_decl, *enum_ref.id(), graph, entry_node); Ok(leaves.to_vec()) } ty::TyDecl::ImplSelfOrTrait(ty::ImplSelfOrTrait { decl_id, .. }) => { let impl_trait_decl = decl_engine.get_impl_self_or_trait(decl_id); let ty::TyImplSelfOrTrait { trait_name, items, trait_decl_ref, implementing_for, .. } = &*impl_trait_decl; connect_impl_trait( engines, trait_name, graph, items, entry_node, tree_type, trait_decl_ref, implementing_for, options, )?; Ok(leaves.to_vec()) } ty::TyDecl::StorageDecl(ty::StorageDecl { decl_id, .. }) => { let storage = decl_engine.get_storage(decl_id); connect_storage_declaration(&storage, graph, entry_node, tree_type); Ok(leaves.to_vec()) } ty::TyDecl::TypeAliasDecl(ty::TypeAliasDecl { decl_id, .. }) => { let type_alias = decl_engine.get_type_alias(decl_id); connect_type_alias_declaration(engines, &type_alias, graph, entry_node)?; Ok(leaves.to_vec()) } ty::TyDecl::TraitTypeDecl(ty::TraitTypeDecl { .. }) => Ok(leaves.to_vec()), ty::TyDecl::ErrorRecovery(..) | ty::TyDecl::GenericTypeForFunctionScope(_) => { Ok(leaves.to_vec()) } } } /// Connect each individual struct field, and when that field is accessed in a subfield expression, /// connect that field. fn connect_struct_declaration<'eng: 'cfg, 'cfg>( struct_decl: &ty::TyStructDecl, struct_decl_id: DeclId<ty::TyStructDecl>, graph: &mut ControlFlowGraph<'cfg>, entry_node: NodeIndex, tree_type: &TreeType, ) { let ty::TyStructDecl { call_path, fields, visibility, .. } = struct_decl; let field_nodes = fields .iter() .map(|field| { ( field.name.clone(), graph.add_node(ControlFlowGraphNode::StructField { struct_decl_id, struct_field_name: field.name.clone(), attributes: field.attributes.clone(), }), ) }) .collect::<Vec<_>>(); // If this is a library or smart contract, and if this is public, then we want to connect the // declaration node itself to the individual fields. // // this is important because if the struct is public, you want to be able to signal that all // fields are accessible by just adding an edge to the struct declaration node if matches!(tree_type, TreeType::Contract | TreeType::Library) && *visibility == Visibility::Public { for (_name, node) in &field_nodes { graph.add_edge(entry_node, *node, "".into()); } } // Now, populate the struct namespace with the location of this struct as well as the indexes // of the field names graph.namespace.insert_struct( call_path.suffix.as_str().to_string(), entry_node, field_nodes, ); } /// Implementations of traits are top-level things that are not conditional, so /// we insert an edge from the function's starting point to the declaration to show /// that the declaration was indeed at some point implemented. /// Additionally, we insert the trait's methods into the method namespace in order to /// track which exact methods are dead code. #[allow(clippy::too_many_arguments)] fn connect_impl_trait<'eng: 'cfg, 'cfg>( engines: &'eng Engines, trait_name: &CallPath, graph: &mut ControlFlowGraph<'cfg>, items: &[TyImplItem], entry_node: NodeIndex, tree_type: &TreeType, trait_decl_ref: &Option<DeclRef<InterfaceDeclId>>, implementing_for: &GenericTypeArgument, options: NodeConnectionOptions, ) -> Result<(), CompileError> { let decl_engine = engines.de(); // If trait_decl_ref is None then the impl trait is an impl self. // Impl self does not have any trait to point to. if trait_decl_ref.is_some() { let trait_decl_node = graph.namespace.find_trait(trait_name).cloned(); match trait_decl_node { None => { let node_ix = graph.add_node("External trait".into()); graph.add_edge(entry_node, node_ix, "".into()); } Some(trait_decl_node) => { graph.add_edge_from_entry(entry_node, "".into()); graph.add_edge(entry_node, trait_decl_node.trait_idx, "".into()); } }; } connect_type_id(engines, implementing_for.type_id, graph, entry_node)?; let trait_entry = graph.namespace.find_trait(trait_name).cloned(); // Collect the methods that are directly implemented in the trait. let mut trait_items_method_names = Vec::new(); if let Some(trait_decl_ref) = trait_decl_ref { if let InterfaceDeclId::Trait(trait_decl_id) = &trait_decl_ref.id() { let trait_decl = decl_engine.get_trait(trait_decl_id); for trait_item in trait_decl.items.clone() { if let ty::TyTraitItem::Fn(func_decl_ref) = trait_item { let functional_decl_id = decl_engine.get_function(&func_decl_ref); trait_items_method_names.push(functional_decl_id.name.as_str().to_string()); } } } } let mut methods_and_indexes = vec![]; // insert method declarations into the graph for item in items { match item { TyImplItem::Fn(method_decl_ref) => { let fn_decl = decl_engine.get_function(method_decl_ref); let fn_decl_entry_node = graph.add_node(ControlFlowGraphNode::MethodDeclaration { span: fn_decl.span.clone(), method_name: fn_decl.name.clone(), method_decl_ref: method_decl_ref.clone(), engines, }); let add_edge_to_fn_decl = if trait_items_method_names.contains(&fn_decl.name.as_str().to_string()) { if let Some(trait_entry) = trait_entry.clone() { matches!( trait_entry.module_tree_type, TreeType::Library | TreeType::Contract ) } else { // trait_entry not found which means it is an external trait. // As the trait is external we assume it is within a library // thus we can return true directly. true } } else { matches!(tree_type, TreeType::Library | TreeType::Contract) }; if add_edge_to_fn_decl { graph.add_edge(entry_node, fn_decl_entry_node, "".into()); } // connect the impl declaration node to the functions themselves, as all trait functions are // public if the trait is in scope connect_typed_fn_decl( engines, &fn_decl, graph, fn_decl_entry_node, fn_decl.span.clone(), None, tree_type, options, )?; methods_and_indexes.push((fn_decl.name.clone(), fn_decl_entry_node)); } TyImplItem::Constant(_const_decl) => {} TyImplItem::Type(_type_decl) => {} } } // we also want to add an edge from the methods back to the trait, so if a method gets called, // the trait impl is considered used for (_, ix) in methods_and_indexes.iter() { graph.add_edge(*ix, entry_node, "".into()); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/control_flow_analysis/analyze_return_paths.rs
sway-core/src/control_flow_analysis/analyze_return_paths.rs
//! This is the flow graph, a graph which contains edges that represent possible steps of program //! execution. use crate::{ control_flow_analysis::*, language::{ ty::{self, TyImplItem}, CallPath, }, type_system::*, Engines, }; use petgraph::prelude::NodeIndex; use sway_error::error::CompileError; use sway_types::{ident::Ident, span::Span, IdentUnique}; impl<'cfg> ControlFlowGraph<'cfg> { pub(crate) fn construct_return_path_graph<'eng: 'cfg>( engines: &'eng Engines, module_nodes: &[ty::TyAstNode], ) -> Result<Self, Vec<CompileError>> { let mut errors = vec![]; let mut graph = ControlFlowGraph::new(engines); // do a depth first traversal and cover individual inner ast nodes let mut leaf_opt = None; for ast_entrypoint in module_nodes { match connect_node(engines, ast_entrypoint, &mut graph, leaf_opt) { Ok(NodeConnection::NextStep(node_opt)) => { leaf_opt = node_opt; } Ok(_) => {} Err(mut e) => { errors.append(&mut e); } } } if !errors.is_empty() { Err(errors) } else { Ok(graph) } } /// This function looks through the control flow graph and ensures that all paths that are /// required to return a value do, indeed, return a value of the correct type. /// It does this by checking every function declaration in both the methods namespace /// and the functions namespace and validating that all paths leading to the function exit node /// return the same type. Additionally, if a function has a return type, all paths must indeed /// lead to the function exit node. pub(crate) fn analyze_return_paths(&self, engines: &Engines) -> Vec<CompileError> { let mut errors = vec![]; for ( (name, _sig), FunctionNamespaceEntry { entry_point, exit_point, return_type, }, ) in &self.namespace.function_namespace { // For every node connected to the entry point errors.append(&mut self.ensure_all_paths_reach_exit( engines, *entry_point, *exit_point, name, return_type, )); } errors } /// Traverses the spine of a function to ensure that it does return if a return value is /// expected. The spine of the function does not include branches such as if-then-elses and /// loops. Those branches are ignored, and a branching expression is represented as a single /// node in the graph. The analysis continues once the branches join again. This means that the /// spine is linear, so every node has at most one outgoing edge. The graph is assumed to have /// been constructed this way. fn ensure_all_paths_reach_exit( &self, engines: &Engines, entry_point: EntryPoint, exit_point: ExitPoint, function_name: &IdentUnique, return_ty: &TypeInfo, ) -> Vec<CompileError> { let mut rover = entry_point; let mut errors = vec![]; while rover != exit_point { let neighbors = self .graph .neighbors_directed(rover, petgraph::Direction::Outgoing) .collect::<Vec<_>>(); // The graph is supposed to be a single path, so at most one outgoing neighbor is allowed. assert!(neighbors.len() <= 1); if neighbors.is_empty() { if !return_ty.is_unit() { // A return is expected, but none is found. Report an error. let span = match &self.graph[rover] { ControlFlowGraphNode::ProgramNode { node, .. } => node.span.clone(), ControlFlowGraphNode::MethodDeclaration { span, .. } => span.clone(), _ => { errors.push(CompileError::Internal( "Attempted to construct return path error \ but no source span was found.", Span::dummy(), )); return errors; } }; let function_name: Ident = function_name.into(); errors.push(CompileError::PathDoesNotReturn { span, function_name: function_name.clone(), ty: engines.help_out(return_ty).to_string(), }); } // No further neighbors, so we're done. break; } rover = neighbors[0]; } errors } } /// The resulting edges from connecting a node to the graph. enum NodeConnection { /// This represents a node that steps on to the next node. NextStep(Option<NodeIndex>), /// This represents a node which aborts the stepwise flow. /// Such nodes are: /// - return expressions, /// - implicit returns, /// - panic expressions. Return(NodeIndex), } fn connect_node<'eng: 'cfg, 'cfg>( engines: &'eng Engines, node: &ty::TyAstNode, graph: &mut ControlFlowGraph<'cfg>, leaf_opt: Option<NodeIndex>, ) -> Result<NodeConnection, Vec<CompileError>> { match &node.content { ty::TyAstNodeContent::Expression(ty::TyExpression { expression: ty::TyExpressionVariant::Return(..), .. }) | ty::TyAstNodeContent::Expression(ty::TyExpression { expression: ty::TyExpressionVariant::ImplicitReturn(..), .. }) | ty::TyAstNodeContent::Expression(ty::TyExpression { expression: ty::TyExpressionVariant::Panic(..), .. }) => { let this_index = graph.add_node(ControlFlowGraphNode::from_node(node)); if let Some(leaf_ix) = leaf_opt { graph.add_edge(leaf_ix, this_index, "".into()); } Ok(NodeConnection::Return(this_index)) } ty::TyAstNodeContent::Expression(ty::TyExpression { expression: ty::TyExpressionVariant::WhileLoop { .. }, .. }) => { // An abridged version of the dead code analysis for a while loop // since we don't really care about what the loop body contains when detecting // divergent paths let node = graph.add_node(ControlFlowGraphNode::from_node(node)); if let Some(leaf) = leaf_opt { graph.add_edge(leaf, node, "while loop entry".into()); } Ok(NodeConnection::NextStep(Some(node))) } ty::TyAstNodeContent::Expression(ty::TyExpression { .. }) => { let entry = graph.add_node(ControlFlowGraphNode::from_node(node)); // insert organizational dominator node // connected to all current leaves if let Some(leaf) = leaf_opt { graph.add_edge(leaf, entry, "".into()); } Ok(NodeConnection::NextStep(Some(entry))) } ty::TyAstNodeContent::SideEffect(_) => Ok(NodeConnection::NextStep(leaf_opt)), ty::TyAstNodeContent::Declaration(decl) => Ok(NodeConnection::NextStep( connect_declaration(engines, node, decl, graph, leaf_opt)?, )), ty::TyAstNodeContent::Error(_, _) => Ok(NodeConnection::NextStep(None)), } } fn connect_declaration<'eng: 'cfg, 'cfg>( engines: &'eng Engines, node: &ty::TyAstNode, decl: &ty::TyDecl, graph: &mut ControlFlowGraph<'cfg>, leaf_opt: Option<NodeIndex>, ) -> Result<Option<NodeIndex>, Vec<CompileError>> { let decl_engine = engines.de(); match decl { ty::TyDecl::TraitDecl(_) | ty::TyDecl::AbiDecl(_) | ty::TyDecl::StructDecl(_) | ty::TyDecl::EnumDecl(_) | ty::TyDecl::EnumVariantDecl(_) | ty::TyDecl::StorageDecl(_) | ty::TyDecl::TypeAliasDecl(_) | ty::TyDecl::TraitTypeDecl(_) | ty::TyDecl::GenericTypeForFunctionScope(_) => Ok(leaf_opt), ty::TyDecl::VariableDecl(_) | ty::TyDecl::ConstantDecl(_) | ty::TyDecl::ConfigurableDecl(_) => { let entry_node = graph.add_node(ControlFlowGraphNode::from_node(node)); if let Some(leaf) = leaf_opt { graph.add_edge(leaf, entry_node, "".into()); } Ok(Some(entry_node)) } ty::TyDecl::ConstGenericDecl(_) => { unreachable!("ConstGenericDecl is not reachable from AstNode") } ty::TyDecl::FunctionDecl(ty::FunctionDecl { decl_id, .. }) => { let fn_decl = decl_engine.get_function(decl_id); let entry_node = graph.add_node(ControlFlowGraphNode::from_node(node)); // Do not connect the leaves to the function entry point, since control cannot flow from them into the function. connect_typed_fn_decl(engines, &fn_decl, graph, entry_node)?; Ok(leaf_opt) } ty::TyDecl::ImplSelfOrTrait(ty::ImplSelfOrTrait { decl_id, .. }) => { let impl_trait = decl_engine.get_impl_self_or_trait(decl_id); let ty::TyImplSelfOrTrait { trait_name, items, .. } = &*impl_trait; // Do not connect the leaves to the impl entry point, since control cannot flow from them into the impl. connect_impl_trait(engines, trait_name, graph, items)?; Ok(leaf_opt) } ty::TyDecl::ErrorRecovery(..) => Ok(leaf_opt), } } /// Implementations of traits are top-level things that are not conditional, so /// we insert an edge from the function's starting point to the declaration to show /// that the declaration was indeed at some point implemented. /// Additionally, we insert the trait's methods into the method namespace in order to /// track which exact methods are dead code. fn connect_impl_trait<'eng: 'cfg, 'cfg>( engines: &'eng Engines, trait_name: &CallPath, graph: &mut ControlFlowGraph<'cfg>, items: &[TyImplItem], ) -> Result<(), Vec<CompileError>> { let decl_engine = engines.de(); let mut methods_and_indexes = vec![]; // insert method declarations into the graph for item in items { match item { TyImplItem::Fn(method_decl_ref) => { let fn_decl = decl_engine.get_function(method_decl_ref); let fn_decl_entry_node = graph.add_node(ControlFlowGraphNode::MethodDeclaration { span: fn_decl.span.clone(), method_name: fn_decl.name.clone(), method_decl_ref: method_decl_ref.clone(), engines, }); // connect the impl declaration node to the functions themselves, as all trait functions are // public if the trait is in scope connect_typed_fn_decl(engines, &fn_decl, graph, fn_decl_entry_node)?; methods_and_indexes.push((fn_decl.name.clone(), fn_decl_entry_node)); } TyImplItem::Constant(_const_decl) => {} TyImplItem::Type(_type_decl) => {} } } // Now, insert the methods into the trait method namespace. graph .namespace .insert_trait_methods(trait_name.clone(), methods_and_indexes); Ok(()) } /// The strategy here is to populate the trait namespace with just one singular trait /// and if it is ever implemented, by virtue of type checking, we know all interface points /// were met. /// Upon implementation, we can populate the methods namespace and track dead functions that way. /// TL;DR: At this point, we _only_ track the wholistic trait declaration and not the functions /// contained within. /// /// The trait node itself has already been added (as `entry_node`), so we just need to insert that /// node index into the namespace for the trait. /// /// When connecting a function declaration, we are inserting a new root node into the graph that /// has no entry points, since it is just a declaration. /// When something eventually calls it, it gets connected to the declaration. fn connect_typed_fn_decl<'eng: 'cfg, 'cfg>( engines: &'eng Engines, fn_decl: &ty::TyFunctionDecl, graph: &mut ControlFlowGraph<'cfg>, entry_node: NodeIndex, ) -> Result<(), Vec<CompileError>> { let type_engine = engines.te(); let fn_exit_node = graph.add_node(format!("\"{}\" fn exit", fn_decl.name.as_str()).into()); let return_nodes = depth_first_insertion_code_block(engines, &fn_decl.body, graph, Some(entry_node))?; for node in return_nodes { graph.add_edge(node, fn_exit_node, "return".into()); } let namespace_entry = FunctionNamespaceEntry { entry_point: entry_node, exit_point: fn_exit_node, return_type: type_engine .to_typeinfo(fn_decl.return_type.type_id, &fn_decl.return_type.span) .unwrap_or_else(|_| TypeInfo::Tuple(Vec::new())), }; graph.namespace.insert_function(fn_decl, namespace_entry); Ok(()) } type ReturnStatementNodes = Vec<NodeIndex>; fn depth_first_insertion_code_block<'eng: 'cfg, 'cfg>( engines: &'eng Engines, node_content: &ty::TyCodeBlock, graph: &mut ControlFlowGraph<'cfg>, init_leaf_opt: Option<NodeIndex>, ) -> Result<ReturnStatementNodes, Vec<CompileError>> { let mut errors = vec![]; let mut leaf_opt = init_leaf_opt; let mut return_nodes = vec![]; for node in node_content.contents.iter() { match connect_node(engines, node, graph, leaf_opt) { Ok(this_node) => match this_node { NodeConnection::NextStep(node_opt) => leaf_opt = node_opt, NodeConnection::Return(node) => { return_nodes.push(node); } }, Err(mut e) => errors.append(&mut e), } } if !errors.is_empty() { Err(errors) } else { Ok(return_nodes) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/control_flow_analysis/mod.rs
sway-core/src/control_flow_analysis/mod.rs
//! //! This module contains all of the logic related to control flow analysis. //! //! # Synopsis of Dead-Code Analysis Algorithm //! The dead code analysis algorithm constructs a node for every declaration, expression, and //! statement. Then, from the entry points of the AST, we begin drawing edges along the control //! flow path. If a declaration is instantiated, we draw an edge to it. If an expression or //! statement is executed, an edge is drawn to it. Finally, we trace the edges from the entry //! points of the AST. If there are no paths from any entry point to a node, then it is either a //! dead declaration or an unreachable expression or statement. //! //! See the Terms section for details on how entry points are determined. //! //! # Synopsis of Return-Path Analysis Algorithm //! The graph constructed for this algorithm does not go into the details of the contents of any //! declaration except for function declarations. Inside of every function, it traces the execution //! path along to ensure that all reachable paths do indeed return a value. We don't need to type //! check the value that is returned, since type checking of return statements happens in the type //! checking stage. Here, we know all present return statements have the right type, and we just //! need to verify that all paths do indeed contain a return statement. //! //! //! # # Terms //! # # # Node //! A node is any [crate::semantic_analysis::TyAstNode], with some //! [crate::semantic_analysis::TyAstNodeContent]. # # # Dominating nodes //! A dominating node is a node which all previous nodes pass through. These are what we are //! concerned about in control flow analysis. More formally, //! A node _M_ dominates a node _N_ if every path from the entry that reaches node _N_ has to pass //! through node _M_. //! //! # # # Reachability //! A node _N_ is reachable if there is a path to it from any one of the tree's entry points. //! //! # # # Entry Points //! The entry points to an AST depend on what type of AST it is. If it is a predicate or script, //! then the main function is the sole entry point. If it is a library or contract, then public //! functions or declarations are entry points. mod analyze_return_paths; mod dead_code_analysis; mod flow_graph; pub use flow_graph::*;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/control_flow_analysis/flow_graph/mod.rs
sway-core/src/control_flow_analysis/flow_graph/mod.rs
//! This is the flow graph, a graph which contains edges that represent possible steps of program //! execution. use std::{collections::HashMap, fs}; use crate::{ decl_engine::*, engine_threading::DebugWithEngines, language::ty::{self, GetDeclIdent}, transform, Engines, Ident, }; use sway_types::{span::Span, BaseIdent, IdentUnique, LineCol, Spanned}; use petgraph::{graph::EdgeIndex, prelude::NodeIndex}; mod namespace; use namespace::ControlFlowNamespace; pub(crate) use namespace::FunctionNamespaceEntry; pub(crate) use namespace::TraitNamespaceEntry; pub(crate) use namespace::VariableNamespaceEntry; pub type EntryPoint = NodeIndex; pub type ExitPoint = NodeIndex; #[derive(Clone)] /// A graph that can be used to model the control flow of a Sway program. /// This graph is used as the basis for all of the algorithms in the control flow analysis portion /// of the compiler. pub struct ControlFlowGraph<'cfg> { pub(crate) graph: Graph<'cfg>, pub(crate) entry_points: Vec<NodeIndex>, pub(crate) pending_entry_points_edges: Vec<(NodeIndex, ControlFlowGraphEdge)>, pub(crate) namespace: ControlFlowNamespace, pub(crate) decls: HashMap<IdentUnique, NodeIndex>, pub(crate) engines: &'cfg Engines, } pub type Graph<'cfg> = petgraph::Graph<ControlFlowGraphNode<'cfg>, ControlFlowGraphEdge>; impl<'cfg> ControlFlowGraph<'cfg> { pub fn new(engines: &'cfg Engines) -> Self { Self { graph: Default::default(), entry_points: Default::default(), pending_entry_points_edges: Default::default(), namespace: Default::default(), decls: Default::default(), engines, } } } #[derive(Clone)] pub struct ControlFlowGraphEdge(String); impl std::fmt::Debug for ControlFlowGraphEdge { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } } impl std::convert::From<&str> for ControlFlowGraphEdge { fn from(o: &str) -> Self { ControlFlowGraphEdge(o.to_string()) } } #[allow(clippy::large_enum_variant)] #[derive(Clone)] pub enum ControlFlowGraphNode<'cfg> { OrganizationalDominator(String), #[allow(clippy::large_enum_variant)] ProgramNode { node: ty::TyAstNode, parent_node: Option<NodeIndex>, }, EnumVariant { enum_decl_id: DeclId<ty::TyEnumDecl>, variant_name: Ident, is_public: bool, }, MethodDeclaration { span: Span, method_name: Ident, method_decl_ref: DeclRefFunction, engines: &'cfg Engines, }, StructField { struct_decl_id: DeclId<ty::TyStructDecl>, struct_field_name: Ident, attributes: transform::Attributes, }, StorageField { field_name: Ident, }, FunctionParameter { param_name: Ident, is_self: bool, }, } impl GetDeclIdent for ControlFlowGraphNode<'_> { fn get_decl_ident(&self, engines: &Engines) -> Option<Ident> { match self { ControlFlowGraphNode::OrganizationalDominator(_) => None, ControlFlowGraphNode::ProgramNode { node, .. } => node.get_decl_ident(engines), ControlFlowGraphNode::EnumVariant { variant_name, .. } => Some(variant_name.clone()), ControlFlowGraphNode::MethodDeclaration { method_name, .. } => { Some(method_name.clone()) } ControlFlowGraphNode::StructField { struct_field_name, .. } => Some(struct_field_name.clone()), ControlFlowGraphNode::StorageField { field_name, .. } => Some(field_name.clone()), ControlFlowGraphNode::FunctionParameter { param_name, .. } => Some(param_name.clone()), } } } impl std::convert::From<&ty::TyStorageField> for ControlFlowGraphNode<'_> { fn from(other: &ty::TyStorageField) -> Self { ControlFlowGraphNode::StorageField { field_name: other.name.clone(), } } } impl std::convert::From<String> for ControlFlowGraphNode<'_> { fn from(other: String) -> Self { ControlFlowGraphNode::OrganizationalDominator(other) } } impl std::convert::From<&str> for ControlFlowGraphNode<'_> { fn from(other: &str) -> Self { other.to_string().into() } } impl DebugWithEngines for ControlFlowGraphNode<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result { let text = match self { ControlFlowGraphNode::OrganizationalDominator(s) => s.to_string(), ControlFlowGraphNode::ProgramNode { node, .. } => { format!("{:?}", engines.help_out(node)) } ControlFlowGraphNode::EnumVariant { variant_name, .. } => { format!("Enum variant {variant_name}") } ControlFlowGraphNode::MethodDeclaration { method_name, method_decl_ref, engines, .. } => { let decl_engines = engines.de(); let method = decl_engines.get_function(method_decl_ref); if let Some(implementing_type) = &method.implementing_type { format!( "Method {}.{}", implementing_type.friendly_name(engines), method_name.as_str() ) } else { format!("Method {}", method_name.as_str()) } } ControlFlowGraphNode::StructField { struct_field_name, .. } => { format!("Struct field {}", struct_field_name.as_str()) } ControlFlowGraphNode::StorageField { field_name } => { format!("Storage field {}", field_name.as_str()) } ControlFlowGraphNode::FunctionParameter { param_name, .. } => { format!("Function param {}", param_name.as_str()) } }; f.write_str(&text) } } impl<'cfg> ControlFlowGraph<'cfg> { pub(crate) fn add_edge_from_entry(&mut self, to: NodeIndex, label: ControlFlowGraphEdge) { self.pending_entry_points_edges.push((to, label)); } pub(crate) fn add_node<'eng: 'cfg>(&mut self, node: ControlFlowGraphNode<'cfg>) -> NodeIndex { let ident_opt = node.get_decl_ident(self.engines); let node_index = self.graph.add_node(node); if let Some(ident) = ident_opt { self.decls.insert(ident.into(), node_index); } node_index } pub(crate) fn add_edge( &mut self, from: NodeIndex, to: NodeIndex, edge: ControlFlowGraphEdge, ) -> EdgeIndex { self.graph.add_edge(from, to, edge) } pub(crate) fn connect_pending_entry_edges(&mut self) { for entry in &self.entry_points { for (to, label) in &self.pending_entry_points_edges { self.graph.add_edge(*entry, *to, label.clone()); } } self.pending_entry_points_edges.clear(); } pub(crate) fn get_node_from_decl(&self, cfg_node: &ControlFlowGraphNode) -> Option<NodeIndex> { if let Some(ident) = cfg_node.get_decl_ident(self.engines) { if !ident.span().is_dummy() { self.decls.get(&ident.into()).cloned() } else { None } } else { None } } /// Prints out GraphViz DOT format for this graph. pub(crate) fn visualize( &self, engines: &Engines, print_graph: Option<String>, print_graph_url_format: Option<String>, ) { if let Some(graph_path) = print_graph { use petgraph::dot::{Config, Dot}; let string_graph = self.graph.filter_map( |_idx, node| Some(format!("{:?}", engines.help_out(node))), |_idx, edge| Some(edge.0.clone()), ); let output = format!( "{:?}", Dot::with_attr_getters( &string_graph, &[Config::NodeNoLabel, Config::EdgeNoLabel], &|_, er| format!("label = {:?}", er.weight()), &|_, nr| { let node = &self.graph[nr.0]; let mut shape = ""; if self.entry_points.contains(&nr.0) { shape = "shape=doubleoctagon"; } let mut url = "".to_string(); if let Some(url_format) = print_graph_url_format.clone() { if let Some(span) = node.span() { if let Some(source_id) = span.source_id() { let path = engines.se().get_path(source_id); let path = path.to_string_lossy(); let LineCol { line, col } = span.start_line_col_one_index(); let url_format = url_format .replace("{path}", path.to_string().as_str()) .replace("{line}", line.to_string().as_str()) .replace("{col}", col.to_string().as_str()); url = format!("URL = {url_format:?}"); } } } format!("{shape} label = {:?} {url}", nr.1) }, ) ); if graph_path.is_empty() { tracing::info!("{output}"); } else { let result = fs::write(graph_path.clone(), output); if let Some(error) = result.err() { tracing::error!( "There was an issue while outputting DCA graph to path {graph_path:?}\n{error}" ); } } } } } impl<'cfg> ControlFlowGraphNode<'cfg> { pub(crate) fn from_enum_variant( enum_decl_id: DeclId<ty::TyEnumDecl>, other_name: BaseIdent, is_public: bool, ) -> ControlFlowGraphNode<'cfg> { ControlFlowGraphNode::EnumVariant { enum_decl_id, variant_name: other_name, is_public, } } pub(crate) fn from_node_with_parent( node: &ty::TyAstNode, parent_node: Option<NodeIndex>, ) -> ControlFlowGraphNode<'cfg> { ControlFlowGraphNode::ProgramNode { node: node.clone(), parent_node, } } pub(crate) fn from_node(node: &ty::TyAstNode) -> ControlFlowGraphNode<'cfg> { ControlFlowGraphNode::ProgramNode { node: node.clone(), parent_node: None, } } fn span(&self) -> Option<Span> { match self { ControlFlowGraphNode::OrganizationalDominator(_) => None, ControlFlowGraphNode::ProgramNode { node, .. } => Some(node.span.clone()), ControlFlowGraphNode::EnumVariant { variant_name, .. } => Some(variant_name.span()), ControlFlowGraphNode::MethodDeclaration { span, .. } => Some(span.clone()), ControlFlowGraphNode::StructField { struct_field_name, .. } => Some(struct_field_name.span()), ControlFlowGraphNode::StorageField { field_name } => Some(field_name.span()), ControlFlowGraphNode::FunctionParameter { param_name, .. } => Some(param_name.span()), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/control_flow_analysis/flow_graph/namespace.rs
sway-core/src/control_flow_analysis/flow_graph/namespace.rs
use super::{EntryPoint, ExitPoint}; use crate::{ language::{ parsed::TreeType, ty::{ self, TyConfigurableDecl, TyConstGenericDecl, TyConstantDecl, TyFunctionDecl, TyFunctionSig, }, CallPath, }, type_system::TypeInfo, Ident, }; use indexmap::IndexMap; use petgraph::prelude::NodeIndex; use std::collections::HashMap; use sway_types::{IdentUnique, Named}; #[derive(Default, Clone)] /// Represents a single entry in the [ControlFlowNamespace]'s function namespace. Contains various /// metadata about a function including its node indexes in the graph, its return type, and more. /// Used to both perform control flow analysis on functions as well as produce good error messages. pub(crate) struct FunctionNamespaceEntry { pub(crate) entry_point: EntryPoint, pub(crate) exit_point: ExitPoint, pub(crate) return_type: TypeInfo, } #[derive(Default, Clone)] pub(crate) struct StructNamespaceEntry { pub(crate) struct_decl_ix: NodeIndex, pub(crate) fields: IndexMap<String, NodeIndex>, } #[derive(Clone, Debug)] pub(crate) struct TraitNamespaceEntry { pub(crate) trait_idx: NodeIndex, pub(crate) module_tree_type: TreeType, } #[derive(Default, Clone)] pub(crate) struct VariableNamespaceEntry { pub(crate) variable_decl_ix: NodeIndex, } #[derive(Default, Clone)] /// This namespace holds mappings from various declarations to their indexes in the graph. This is /// used for connecting those vertices when the declarations are instantiated. /// /// Since control flow happens after type checking, we are not concerned about things being out /// of scope at this point, as that would have been caught earlier and aborted the compilation /// process. pub struct ControlFlowNamespace { pub(crate) function_namespace: IndexMap<(IdentUnique, TyFunctionSig), FunctionNamespaceEntry>, pub(crate) enum_namespace: HashMap<IdentUnique, (NodeIndex, HashMap<Ident, NodeIndex>)>, pub(crate) trait_namespace: HashMap<CallPath, TraitNamespaceEntry>, /// This is a mapping from trait name to method names and their node indexes pub(crate) trait_method_namespace: HashMap<CallPath, HashMap<Ident, NodeIndex>>, /// This is a mapping from struct name to field names and their node indexes /// TODO this should be an Ident and not a String, switch when static spans are implemented pub(crate) struct_namespace: HashMap<String, StructNamespaceEntry>, pub(crate) const_namespace: HashMap<Ident, NodeIndex>, pub(crate) configurable_namespace: HashMap<Ident, NodeIndex>, pub(crate) const_generic_namespace: HashMap<Ident, NodeIndex>, pub(crate) storage: HashMap<Ident, NodeIndex>, pub(crate) code_blocks: Vec<ControlFlowCodeBlock>, pub(crate) alias: HashMap<IdentUnique, NodeIndex>, } #[derive(Default, Clone)] pub struct ControlFlowCodeBlock { pub(crate) variables: HashMap<Ident, VariableNamespaceEntry>, } impl ControlFlowNamespace { pub(crate) fn get_function(&self, fn_decl: &TyFunctionDecl) -> Option<&FunctionNamespaceEntry> { let ident: IdentUnique = fn_decl.name.clone().into(); self.function_namespace .get(&(ident, TyFunctionSig::from_fn_decl(fn_decl))) } pub(crate) fn insert_function( &mut self, fn_decl: &ty::TyFunctionDecl, entry: FunctionNamespaceEntry, ) { let ident = &fn_decl.name; let ident: IdentUnique = ident.into(); self.function_namespace .insert((ident, TyFunctionSig::from_fn_decl(fn_decl)), entry); } pub(crate) fn get_constant(&self, const_decl: &TyConstantDecl) -> Option<&NodeIndex> { self.const_namespace.get(&const_decl.name().clone()) } pub(crate) fn get_configurable(&self, decl: &TyConfigurableDecl) -> Option<&NodeIndex> { self.configurable_namespace.get(&decl.name().clone()) } pub(crate) fn get_const_generic(&self, decl: &TyConstGenericDecl) -> Option<&NodeIndex> { self.const_generic_namespace.get(&decl.name().clone()) } #[allow(dead_code)] pub(crate) fn insert_constant( &mut self, const_decl: TyConstantDecl, declaration_node: NodeIndex, ) { self.const_namespace .insert(const_decl.name().clone(), declaration_node); } pub(crate) fn get_global_constant(&self, ident: &Ident) -> Option<&NodeIndex> { self.const_namespace.get(ident) } pub(crate) fn insert_global_constant( &mut self, const_name: Ident, declaration_node: NodeIndex, ) { self.const_namespace.insert(const_name, declaration_node); } pub(crate) fn insert_configurable(&mut self, const_name: Ident, declaration_node: NodeIndex) { self.configurable_namespace .insert(const_name, declaration_node); } pub(crate) fn insert_enum(&mut self, enum_name: Ident, enum_decl_index: NodeIndex) { self.enum_namespace .insert(enum_name.into(), (enum_decl_index, HashMap::new())); } pub(crate) fn insert_enum_variant( &mut self, enum_name: Ident, enum_decl_index: NodeIndex, variant_name: Ident, variant_index: NodeIndex, ) { match self.enum_namespace.get_mut(&enum_name.clone().into()) { Some((_ix, variants)) => { variants.insert(variant_name, variant_index); } None => { let variant_space = { let mut map = HashMap::new(); map.insert(variant_name, variant_index); map }; self.enum_namespace .insert(enum_name.into(), (enum_decl_index, variant_space)); } } } pub(crate) fn find_enum(&self, enum_name: &Ident) -> Option<&NodeIndex> { self.enum_namespace.get(&enum_name.into()).map(|f| &f.0) } pub(crate) fn find_enum_variant_index( &self, enum_name: &Ident, variant_name: &Ident, ) -> Option<(NodeIndex, NodeIndex)> { let (enum_ix, enum_decl) = self.enum_namespace.get(&enum_name.into())?; Some((*enum_ix, *enum_decl.get(variant_name)?)) } pub(crate) fn add_trait(&mut self, trait_name: CallPath, trait_entry: TraitNamespaceEntry) { self.trait_namespace.insert(trait_name, trait_entry); } pub(crate) fn find_trait(&self, name: &CallPath) -> Option<&TraitNamespaceEntry> { self.trait_namespace.get(name) } pub(crate) fn find_trait_method( &self, trait_name: &CallPath, method_name: &Ident, ) -> Option<&NodeIndex> { self.trait_method_namespace .get(trait_name) .and_then(|methods| methods.get(method_name)) } pub(crate) fn insert_trait_methods( &mut self, trait_name: CallPath, methods: Vec<(Ident, NodeIndex)>, ) { match self.trait_method_namespace.get_mut(&trait_name) { Some(methods_ns) => { for (name, ix) in methods { methods_ns.insert(name, ix); } } None => { let mut ns = HashMap::default(); for (name, ix) in methods { ns.insert(name, ix); } self.trait_method_namespace.insert(trait_name, ns); } } } pub(crate) fn insert_storage(&mut self, field_nodes: Vec<(ty::TyStorageField, NodeIndex)>) { for (field, node) in field_nodes { self.storage.insert(field.name, node); } } pub(crate) fn get_struct(&self, ident: &Ident) -> Option<&StructNamespaceEntry> { self.struct_namespace.get(ident.as_str()) } pub(crate) fn insert_struct( &mut self, struct_name: String, declaration_node: NodeIndex, field_nodes: Vec<(Ident, NodeIndex)>, ) { let entry = StructNamespaceEntry { struct_decl_ix: declaration_node, fields: field_nodes .into_iter() .map(|(ident, ix)| (ident.as_str().to_string(), ix)) .collect(), }; self.struct_namespace.insert(struct_name, entry); } pub(crate) fn find_struct_decl(&self, struct_name: &str) -> Option<&NodeIndex> { self.struct_namespace .get(struct_name) .map(|StructNamespaceEntry { struct_decl_ix, .. }| struct_decl_ix) } pub(crate) fn find_struct_field_idx( &self, struct_name: &str, field_name: &str, ) -> Option<&NodeIndex> { self.struct_namespace .get(struct_name)? .fields .get(field_name) } pub(crate) fn push_code_block(&mut self) { self.code_blocks.push(ControlFlowCodeBlock { variables: HashMap::<Ident, VariableNamespaceEntry>::new(), }); } pub(crate) fn pop_code_block(&mut self) { self.code_blocks.pop(); } pub(crate) fn insert_variable(&mut self, name: Ident, entry: VariableNamespaceEntry) { if let Some(code_block) = self.code_blocks.last_mut() { code_block.variables.insert(name, entry); } } pub(crate) fn get_variable(&mut self, name: &Ident) -> Option<VariableNamespaceEntry> { for code_block in self.code_blocks.iter().rev() { if let Some(entry) = code_block.variables.get(name).cloned() { return Some(entry); } } None } pub(crate) fn insert_alias(&mut self, name: Ident, entry: NodeIndex) { self.alias.insert(name.into(), entry); } pub(crate) fn get_alias(&self, name: &Ident) -> Option<&NodeIndex> { self.alias.get(&name.into()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/lexical_map.rs
sway-core/src/ir_generation/lexical_map.rs
// Nested mappings between symbol strings. Allows shadowing and/or nested scopes for local // symbols. // // NOTE: ALL symbols should be represented in this data structure to be sure that we // don't accidentally ignore (i.e., neglect to shadow with) a new binding. // // A further complication is although we have enter_scope() and leave_scope() to potentially add // and remove shadowing symbols, the re-use of symbol names can't be allowed, so all names are // reserved even when they're not 'currently' valid. use std::collections::{HashMap, HashSet}; pub(super) struct LexicalMap { symbol_map: Vec<HashMap<String, String>>, reserved_symbols: HashSet<String>, } impl LexicalMap { pub(super) fn from_iter<I: IntoIterator<Item = String>>(names: I) -> Self { let (root_symbol_map, reserved_symbols): (HashMap<String, String>, HashSet<String>) = names .into_iter() .fold((HashMap::new(), HashSet::new()), |(mut m, mut r), name| { m.insert(name.clone(), name.clone()); r.insert(name); (m, r) }); LexicalMap { symbol_map: vec![root_symbol_map], reserved_symbols, } } pub(super) fn enter_scope(&mut self) -> &mut Self { self.symbol_map.push(HashMap::new()); self } pub(super) fn leave_scope(&mut self) -> &mut Self { assert!(self.symbol_map.len() > 1); self.symbol_map.pop(); self } pub(super) fn get(&self, symbol: &str) -> Option<&String> { // Only get 'valid' symbols which are currently in scope. self.symbol_map .iter() .rev() .find_map(|scope| scope.get(symbol)) } pub(super) fn insert(&mut self, new_symbol: String) -> String { // Insert this new symbol into this lexical scope. If it has ever existed then the // original will be shadowed and the shadower is returned. fn get_new_local_symbol(reserved: &HashSet<String>, candidate: String) -> String { if reserved.contains(&candidate) { // Try again with adjusted candidate. get_new_local_symbol(reserved, format!("{candidate}_")) } else { candidate } } let local_symbol = get_new_local_symbol(&self.reserved_symbols, new_symbol.clone()); self.symbol_map .last_mut() .expect("LexicalMap should always have at least the root scope.") .insert(new_symbol, local_symbol.clone()); self.reserved_symbols.insert(local_symbol.clone()); local_symbol } // Generate and reserve a unique 'anonymous' symbol. Is in the form `__anon_X` where `X` is a // unique number. pub(super) fn insert_anon(&mut self) -> String { let anon_symbol = (0..) .map(|n| format!("__anon_{n}")) .find(|candidate| !self.reserved_symbols.contains(candidate)) .unwrap(); self.symbol_map .last_mut() .expect("LexicalMap should always have at least the root scope.") .insert(anon_symbol.clone(), anon_symbol.clone()); self.reserved_symbols.insert(anon_symbol.clone()); anon_symbol } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/convert.rs
sway-core/src/ir_generation/convert.rs
use crate::{ ir_generation::function::FnCompiler, language::Literal, metadata::MetadataManager, type_system::{TypeId, TypeInfo}, Engines, }; use super::types::{create_tagged_union_type, create_tuple_aggregate}; use sway_error::error::CompileError; use sway_ir::{module::Module, Constant, ConstantContent, Context, Type, Value}; use sway_types::{integer_bits::IntegerBits, span::Span}; pub(super) fn convert_literal_to_value(context: &mut Context, ast_literal: &Literal) -> Value { match ast_literal { // In Sway for now we don't have `as` casting and for integers which may be implicitly cast // between widths we just emit a warning, and essentially ignore it. We also assume a // 'Numeric' integer of undetermined width is 'u64`. The IR would like to be type // consistent and doesn't tolerate missing integers of different width, so for now, until we // do introduce explicit `as` casting, all integers are `u64` as far as the IR is // concerned. // // XXX The above isn't true for other targets. We need to improved this. // FIXME Literal::U8(n) => ConstantContent::get_uint(context, 8, *n as u64), Literal::U16(n) => ConstantContent::get_uint(context, 64, *n as u64), Literal::U32(n) => ConstantContent::get_uint(context, 64, *n as u64), Literal::U64(n) => ConstantContent::get_uint(context, 64, *n), Literal::U256(n) => ConstantContent::get_uint256(context, n.clone()), Literal::Numeric(_) => unreachable!(), Literal::String(s) => ConstantContent::get_string(context, s.as_str().as_bytes().to_vec()), Literal::Boolean(b) => ConstantContent::get_bool(context, *b), Literal::B256(bs) => ConstantContent::get_b256(context, *bs), Literal::Binary(bytes) => ConstantContent::get_untyped_slice(context, bytes.clone()), } } pub(super) fn convert_literal_to_constant( context: &mut Context, ast_literal: &Literal, ) -> Constant { let c = match ast_literal { // All integers are `u64`. See comment above. Literal::U8(n) => ConstantContent::new_uint(context, 8, *n as u64), Literal::U16(n) => ConstantContent::new_uint(context, 64, *n as u64), Literal::U32(n) => ConstantContent::new_uint(context, 64, *n as u64), Literal::U64(n) => ConstantContent::new_uint(context, 64, *n), Literal::U256(n) => ConstantContent::new_uint256(context, n.clone()), Literal::Numeric(_) => unreachable!(), Literal::String(s) => ConstantContent::new_string(context, s.as_str().as_bytes().to_vec()), Literal::Boolean(b) => ConstantContent::new_bool(context, *b), Literal::B256(bs) => ConstantContent::new_b256(context, *bs), Literal::Binary(bytes) => ConstantContent::new_untyped_slice(context, bytes.clone()), }; Constant::unique(context, c) } pub(super) fn convert_resolved_type_id( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, function_compiler: Option<&FnCompiler>, ast_type: TypeId, span: &Span, ) -> Result<Type, CompileError> { let ast_type = engines.te().get(ast_type); convert_resolved_type_info( engines, context, md_mgr, module, function_compiler, &ast_type, span, ) } pub(super) fn convert_resolved_typeid_no_span( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, function_compiler: Option<&FnCompiler>, ast_type: TypeId, ) -> Result<Type, CompileError> { let msg = "unknown source location"; let span = crate::span::Span::from_string(msg.to_string()); convert_resolved_type_id( engines, context, md_mgr, module, function_compiler, ast_type, &span, ) } fn convert_resolved_type_info( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, function_compiler: Option<&FnCompiler>, ast_type: &TypeInfo, span: &Span, ) -> Result<Type, CompileError> { // A handy macro for rejecting unsupported types. macro_rules! reject_type { ($name_str:literal) => {{ return Err(CompileError::TypeMustBeKnownAtThisPoint { span: span.clone(), internal: $name_str.into(), }); }}; } let t = match ast_type { // See comment in convert_literal_to_value() above. TypeInfo::UnsignedInteger(IntegerBits::V256) => Type::get_uint256(context), TypeInfo::UnsignedInteger(IntegerBits::Eight) => Type::get_uint8(context), TypeInfo::UnsignedInteger(IntegerBits::Sixteen) | TypeInfo::UnsignedInteger(IntegerBits::ThirtyTwo) | TypeInfo::UnsignedInteger(IntegerBits::SixtyFour) | TypeInfo::Numeric => Type::get_uint64(context), TypeInfo::Boolean => Type::get_bool(context), TypeInfo::B256 => Type::get_b256(context), TypeInfo::StringSlice => Type::get_slice(context), TypeInfo::StringArray(length) if length.expr().as_literal_val().is_some() => { Type::new_string_array(context, length.expr().as_literal_val().unwrap() as u64) } TypeInfo::Struct(decl_ref) => super::types::get_struct_for_types( engines, context, md_mgr, module, engines .de() .get_struct(decl_ref) .fields .iter() .map(|field| field.type_argument.type_id) .collect::<Vec<_>>() .as_slice(), )?, TypeInfo::Enum(decl_ref) => create_tagged_union_type( engines, context, md_mgr, module, &engines.de().get_enum(decl_ref).variants, )?, TypeInfo::Array(elem_type, length) => { let const_expr = length.expr().to_ty_expression(engines); let constant_evaluated = crate::ir_generation::const_eval::compile_constant_expression_to_constant( engines, context, md_mgr, module, None, function_compiler, &const_expr, ) .unwrap(); let len = constant_evaluated.get_content(context).as_uint().unwrap(); let elem_type = convert_resolved_type_id( engines, context, md_mgr, module, function_compiler, elem_type.type_id, span, )?; Type::new_array(context, elem_type, len as u64) } TypeInfo::Tuple(fields) => { if fields.is_empty() { // XXX We've removed Unit from the core compiler, replaced with an empty Tuple. // Perhaps the same should be done for the IR, although it would use an empty // aggregate which might not make as much sense as a dedicated Unit type. Type::get_unit(context) } else { let new_fields: Vec<_> = fields.iter().map(|x| x.type_id).collect(); create_tuple_aggregate(engines, context, md_mgr, module, &new_fields)? } } TypeInfo::RawUntypedPtr => Type::get_ptr(context), TypeInfo::RawUntypedSlice => Type::get_slice(context), TypeInfo::Ptr(pointee_ty) => { let pointee_ty = convert_resolved_type_id( engines, context, md_mgr, module, function_compiler, pointee_ty.type_id, span, )?; Type::new_typed_pointer(context, pointee_ty) } TypeInfo::Alias { ty, .. } => convert_resolved_type_id( engines, context, md_mgr, module, function_compiler, ty.type_id, span, )?, // refs to slice are actually fat pointers, // all others refs are thin pointers. TypeInfo::Ref { referenced_type, .. } => { if let Some(slice_elem) = engines.te().get(referenced_type.type_id).as_slice() { let elem_ir_type = convert_resolved_type_id( engines, context, md_mgr, module, function_compiler, slice_elem.type_id, span, )?; Type::get_typed_slice(context, elem_ir_type) } else { let referenced_ir_type = convert_resolved_type_id( engines, context, md_mgr, module, function_compiler, referenced_type.type_id, span, )?; Type::new_typed_pointer(context, referenced_ir_type) } } TypeInfo::Never => Type::get_never(context), // Unsized types TypeInfo::Slice(_) => reject_type!("unsized"), // Unsupported types which shouldn't exist in the AST after type checking and // monomorphisation. TypeInfo::Custom { .. } => reject_type!("Custom"), TypeInfo::Contract => reject_type!("Contract"), TypeInfo::ContractCaller { .. } => reject_type!("ContractCaller"), TypeInfo::UntypedEnum(_) => reject_type!("UntypedEnum"), TypeInfo::UntypedStruct(_) => reject_type!("UntypedStruct"), TypeInfo::Unknown => reject_type!("Unknown"), TypeInfo::UnknownGeneric { .. } => reject_type!("Generic"), TypeInfo::Placeholder(_) => reject_type!("Placeholder"), TypeInfo::TypeParam(_) => reject_type!("TypeParam"), TypeInfo::ErrorRecovery(_) => reject_type!("Error recovery"), TypeInfo::TraitType { .. } => reject_type!("TraitType"), TypeInfo::StringArray(..) => reject_type!("String Array with non literal length"), }; engines .obs() .raise_on_after_ir_type_resolution(engines, context, ast_type, &t); Ok(t) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/compile.rs
sway-core/src/ir_generation/compile.rs
use crate::{ decl_engine::{DeclEngineGet, DeclId, DeclRefFunction}, ir_generation::{KeyedTyFunctionDecl, PanickingFunctionCache}, language::{ty, Visibility}, metadata::MetadataManager, namespace::ResolvedDeclaration, semantic_analysis::namespace, type_system::TypeId, types::{LogId, MessageId}, Engines, PanicOccurrences, PanickingCallOccurrences, }; use super::{ const_eval::{compile_const_decl, LookupEnv}, convert::convert_resolved_type_id, function::FnCompiler, CompiledFunctionCache, }; use sway_error::{error::CompileError, handler::Handler}; use sway_ir::{metadata::combine as md_combine, *}; use sway_types::{Ident, Span, Spanned}; use std::{cell::Cell, collections::HashMap, sync::Arc}; #[allow(clippy::too_many_arguments)] pub(super) fn compile_script( engines: &Engines, context: &mut Context, entry_function: &DeclId<ty::TyFunctionDecl>, namespace: &namespace::Namespace, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, test_fns: &[(Arc<ty::TyFunctionDecl>, DeclRefFunction)], compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Module, Vec<CompileError>> { let module = Module::new(context, Kind::Script); compile_constants_for_package(engines, context, module, namespace)?; let mut md_mgr = MetadataManager::default(); compile_configurables( engines, context, &mut md_mgr, module, namespace.current_package_root_module(), logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, compiled_fn_cache, ) .map_err(|err| vec![err])?; compile_entry_function( engines, context, &mut md_mgr, module, entry_function, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, None, compiled_fn_cache, )?; compile_tests( engines, context, &mut md_mgr, module, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, test_fns, compiled_fn_cache, )?; Ok(module) } #[allow(clippy::too_many_arguments)] pub(super) fn compile_predicate( engines: &Engines, context: &mut Context, entry_function: &DeclId<ty::TyFunctionDecl>, namespace: &namespace::Namespace, logged_types: &HashMap<TypeId, LogId>, messages_types: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, test_fns: &[(Arc<ty::TyFunctionDecl>, DeclRefFunction)], compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Module, Vec<CompileError>> { let module = Module::new(context, Kind::Predicate); compile_constants_for_package(engines, context, module, namespace)?; let mut md_mgr = MetadataManager::default(); compile_configurables( engines, context, &mut md_mgr, module, namespace.current_package_root_module(), logged_types, messages_types, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, compiled_fn_cache, ) .map_err(|err| vec![err])?; compile_entry_function( engines, context, &mut md_mgr, module, entry_function, &HashMap::new(), &HashMap::new(), panic_occurrences, panicking_call_occurrences, panicking_fn_cache, None, compiled_fn_cache, )?; compile_tests( engines, context, &mut md_mgr, module, logged_types, messages_types, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, test_fns, compiled_fn_cache, )?; Ok(module) } #[allow(clippy::too_many_arguments)] pub(super) fn compile_contract( context: &mut Context, entry_function: Option<&DeclId<ty::TyFunctionDecl>>, abi_entries: &[DeclId<ty::TyFunctionDecl>], namespace: &namespace::Namespace, declarations: &[ty::TyDecl], logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, test_fns: &[(Arc<ty::TyFunctionDecl>, DeclRefFunction)], engines: &Engines, compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Module, Vec<CompileError>> { let module = Module::new(context, Kind::Contract); compile_constants_for_package(engines, context, module, namespace)?; let mut md_mgr = MetadataManager::default(); compile_configurables( engines, context, &mut md_mgr, module, namespace.current_package_root_module(), logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, compiled_fn_cache, ) .map_err(|err| vec![err])?; // In the case of the new encoding, we need to compile only the entry function. // The compilation of the entry function will recursively compile all the // ABI methods and the fallback function, if specified. if context.experimental.new_encoding { let Some(entry_function) = entry_function else { return Err(vec![CompileError::Internal( "Entry function not specified when compiling contract with new encoding.", Span::dummy(), )]); }; compile_entry_function( engines, context, &mut md_mgr, module, entry_function, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, None, compiled_fn_cache, )?; } else { // In the case of the encoding v0, we need to compile individual ABI entries // and the fallback function. for decl in abi_entries { compile_encoding_v0_abi_method( context, &mut md_mgr, module, decl, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, engines, compiled_fn_cache, )?; } for decl in declarations { if let ty::TyDecl::FunctionDecl(decl) = decl { let decl_id = decl.decl_id; let decl = engines.de().get(&decl_id); if decl.is_fallback() { compile_encoding_v0_abi_method( context, &mut md_mgr, module, &decl_id, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, engines, compiled_fn_cache, )?; } } } } compile_tests( engines, context, &mut md_mgr, module, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, test_fns, compiled_fn_cache, )?; Ok(module) } #[allow(clippy::too_many_arguments)] pub(super) fn compile_library( engines: &Engines, context: &mut Context, namespace: &namespace::Namespace, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, test_fns: &[(Arc<ty::TyFunctionDecl>, DeclRefFunction)], compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Module, Vec<CompileError>> { let module = Module::new(context, Kind::Library); compile_constants_for_package(engines, context, module, namespace)?; let mut md_mgr = MetadataManager::default(); compile_tests( engines, context, &mut md_mgr, module, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, test_fns, compiled_fn_cache, )?; Ok(module) } #[allow(clippy::too_many_arguments)] pub(crate) fn compile_constants_for_package( engines: &Engines, context: &mut Context, module: Module, namespace: &namespace::Namespace, ) -> Result<Module, Vec<CompileError>> { // Traverses the tree of externals and collects all constants fn traverse( engines: &Engines, context: &mut Context, module: Module, current: &namespace::Package, ) -> Result<Module, Vec<CompileError>> { let mut md_mgr = MetadataManager::default(); // Collect constant for all dependencies for ext_package in current.external_packages.values() { traverse(engines, context, module, ext_package)?; } compile_constants(engines, context, &mut md_mgr, module, current.root_module()) .map_err(|err| vec![err])?; Ok(module) } traverse(engines, context, module, namespace.current_package_ref()) } fn compile_constants( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, module_ns: &namespace::Module, ) -> Result<(), CompileError> { for decl_name in module_ns.root_items().get_all_declared_symbols() { if let Some(resolved_decl) = module_ns.root_items().symbols.get(decl_name) { if let ty::TyDecl::ConstantDecl(ty::ConstantDecl { decl_id, .. }) = &resolved_decl.expect_typed_ref() { let const_decl = engines.de().get_constant(decl_id); let call_path = const_decl.call_path.clone(); compile_const_decl( &mut LookupEnv { engines, context, md_mgr, module, module_ns: Some(module_ns), function_compiler: None, lookup: compile_const_decl, }, &call_path, &Some((*const_decl).clone()), )?; } } } for submodule_ns in module_ns.submodules().values() { compile_constants(engines, context, md_mgr, module, submodule_ns)?; } Ok(()) } #[allow(clippy::too_many_arguments)] pub(crate) fn compile_configurables( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, module_ns: &namespace::Module, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<(), CompileError> { for decl_name in module_ns.root_items().get_all_declared_symbols() { if let Some(ResolvedDeclaration::Typed(ty::TyDecl::ConfigurableDecl( ty::ConfigurableDecl { decl_id, .. }, ))) = module_ns.root_items().symbols.get(decl_name) { let decl = engines.de().get(decl_id); let ty = convert_resolved_type_id( engines, context, md_mgr, module, None, decl.type_ascription.type_id, &decl.type_ascription.span(), ) .unwrap(); let ptr_ty = Type::new_typed_pointer(context, ty); let constant = super::const_eval::compile_constant_expression_to_constant( engines, context, md_mgr, module, Some(module_ns), None, decl.value.as_ref().unwrap(), )?; let opt_metadata = md_mgr.span_to_md(context, &decl.span); if context.experimental.new_encoding { let mut encoded_bytes = match constant.get_content(context).value.clone() { ConstantValue::RawUntypedSlice(bytes) => bytes, _ => unreachable!(), }; let config_type_info = engines.te().get(decl.type_ascription.type_id); let buffer_size = match config_type_info.abi_encode_size_hint(engines) { crate::AbiEncodeSizeHint::Exact(len) => len, crate::AbiEncodeSizeHint::Range(_, len) => len, _ => unreachable!("unexpected type accepted as configurable"), }; if buffer_size > encoded_bytes.len() { encoded_bytes.extend([0].repeat(buffer_size - encoded_bytes.len())); } assert!(encoded_bytes.len() == buffer_size); let decode_fn = engines.de().get(decl.decode_fn.as_ref().unwrap().id()); let keyed_decl = KeyedTyFunctionDecl::new(&decode_fn, engines); let decode_fn = compiled_fn_cache.get_compiled_function( engines, context, module, md_mgr, &keyed_decl, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, )?; let name = decl_name.as_str().to_string(); module.add_config( context, name.clone(), ConfigContent::V1 { name, ty, ptr_ty, encoded_bytes, decode_fn: Cell::new(decode_fn), opt_metadata, }, ); } else { let name = decl_name.as_str().to_string(); module.add_config( context, name.clone(), ConfigContent::V0 { name, ty, ptr_ty, constant, opt_metadata, }, ); } } } Ok(()) } #[allow(clippy::too_many_arguments)] pub(super) fn compile_function( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, ast_fn_decl: &ty::TyFunctionDecl, original_name: &Ident, abi_errors_display: String, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, is_entry: bool, is_original_entry: bool, test_decl_ref: Option<DeclRefFunction>, compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Option<Function>, Vec<CompileError>> { // Currently monomorphization of generics is inlined into main() and the functions with generic // args are still present in the AST declarations, but they can be ignored. if !ast_fn_decl.type_parameters.is_empty() { Ok(None) } else { compile_fn( engines, context, md_mgr, module, ast_fn_decl, original_name, abi_errors_display, is_entry, is_original_entry, None, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, test_decl_ref, compiled_fn_cache, ) .map(Some) } } #[allow(clippy::too_many_arguments)] pub(super) fn compile_entry_function( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, ast_fn_decl: &DeclId<ty::TyFunctionDecl>, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, test_decl_ref: Option<DeclRefFunction>, compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Function, Vec<CompileError>> { let is_entry = true; // In the new encoding, the only entry function is the `__entry`, // which is not an original entry. let is_original_entry = !context.experimental.new_encoding; let ast_fn_decl = engines.de().get_function(ast_fn_decl); compile_function( engines, context, md_mgr, module, &ast_fn_decl, &ast_fn_decl.name, FnCompiler::fn_abi_errors_display(&ast_fn_decl, engines), logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, is_entry, is_original_entry, test_decl_ref, compiled_fn_cache, ) .map(|f| f.expect("entry point should never contain generics")) } #[allow(clippy::too_many_arguments)] pub(super) fn compile_tests( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, test_fns: &[(Arc<ty::TyFunctionDecl>, DeclRefFunction)], compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Vec<Function>, Vec<CompileError>> { test_fns .iter() .map(|(_ast_fn_decl, decl_ref)| { compile_entry_function( engines, context, md_mgr, module, decl_ref.id(), logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, Some(decl_ref.clone()), compiled_fn_cache, ) }) .collect() } #[allow(clippy::too_many_arguments)] fn compile_fn( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, ast_fn_decl: &ty::TyFunctionDecl, // Original function name, before it is postfixed with // a number, to get a unique name. // The span in the name must point to the name in the // function declaration. original_name: &Ident, abi_errors_display: String, is_entry: bool, is_original_entry: bool, selector: Option<[u8; 4]>, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, test_decl_ref: Option<DeclRefFunction>, compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Function, Vec<CompileError>> { let inline = ast_fn_decl.inline(); let trace = ast_fn_decl.trace(); let ty::TyFunctionDecl { name, body, return_type, visibility, purity, span, is_trait_method_dummy, is_type_check_finalized, .. } = ast_fn_decl; if *is_trait_method_dummy { return Err(vec![CompileError::InternalOwned( format!("Method {name} is a trait method dummy and was not properly replaced."), span.clone(), )]); } if !*is_type_check_finalized { return Err(vec![CompileError::InternalOwned( format!("Method {name} did not finalize type checking phase."), span.clone(), )]); } let mut ref_mut_args = rustc_hash::FxHashSet::default(); let mut args = ast_fn_decl .parameters .iter() .map(|param| { // Convert to an IR type. convert_resolved_type_id( engines, context, md_mgr, module, None, param.type_argument.type_id, &param.type_argument.span, ) .map(|ty| { if param.is_reference && param.is_mutable { ref_mut_args.insert(param.name.as_str().to_owned()); } ( // Convert the name. param.name.as_str().into(), // Convert the type further to a pointer if it's a reference. if param.is_reference { Type::new_typed_pointer(context, ty) } else { ty }, // Convert the span to a metadata index. md_mgr.span_to_md(context, &param.name.span()), ) }) }) .collect::<Result<Vec<_>, CompileError>>() .map_err(|err| vec![err])?; let keyed_decl = KeyedTyFunctionDecl::new(ast_fn_decl, engines); if context.backtrace != Backtrace::None && panicking_fn_cache.can_panic(&keyed_decl, engines) { args.push(( FnCompiler::BACKTRACE_FN_ARG_NAME.to_string(), Type::new_uint(context, 64), None, )); } let args = args; // Remove mutability. let ret_type = convert_resolved_type_id( engines, context, md_mgr, module, None, return_type.type_id, &return_type.span, ) .map_err(|err| vec![err])?; let span_md_idx = md_mgr.span_to_md(context, span); let storage_md_idx = md_mgr.purity_to_md(context, *purity); let name_span_md_idx = md_mgr.fn_name_span_to_md(context, original_name); let mut metadata = md_combine(context, &span_md_idx, &storage_md_idx); metadata = md_combine(context, &metadata, &name_span_md_idx); let decl_index = test_decl_ref.map(|decl_ref| *decl_ref.id()); if let Some(decl_index) = decl_index { let test_decl_index_md_idx = md_mgr.test_decl_index_to_md(context, decl_index); metadata = md_combine(context, &metadata, &test_decl_index_md_idx); } if let Some(inline) = inline { let inline_md_idx = md_mgr.inline_to_md(context, inline); metadata = md_combine(context, &metadata, &inline_md_idx); } if let Some(trace) = trace { let trace_md_idx = md_mgr.trace_to_md(context, trace); metadata = md_combine(context, &metadata, &trace_md_idx); } let func = Function::new( context, module, name.as_str().to_owned(), abi_errors_display, args, ret_type, selector, *visibility == Visibility::Public, is_entry, is_original_entry, ast_fn_decl.is_fallback(), metadata, ); let mut compiler = FnCompiler::new( engines, context, module, func, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, compiled_fn_cache, ); compiler.ref_mut_args = ref_mut_args; let mut ret_val = compiler.compile_fn_to_value(context, md_mgr, body)?; // Special case: sometimes the returned value at the end of the function block is hacked // together and is invalid. This can happen with diverging control flow or with implicit // returns. We can double check here and make sure the return value type is correct. let undef = Constant::unique(context, ConstantContent::get_undef(ret_type)); ret_val = match ret_val.get_type(context) { Some(ret_val_type) if ret_type.eq(context, &ret_val_type) // TODO: This must be removed along with sway_core::ir_generation::type_correction. || ret_val_type .get_pointee_type(context) .is_some_and(|pointee_ty| pointee_ty.eq(context, &ret_type)) => { ret_val } // Mismatched or unavailable type. Set ret_val to a correctly typed Undef. _otherwise => Value::new_constant(context, undef), }; // Another special case: if the last expression in a function is a return then we don't want to // add another implicit return instruction here, as `ret_val` will be unit regardless of the // function return type actually is. This new RET will be going into an unreachable block // which is valid, but pointless and we should avoid it due to the aforementioned potential // type conflict. // // To tell if this is the case we can check that the current block is empty and has no // predecessors (and isn't the entry block which has none by definition), implying the most // recent instruction was a RET. let already_returns = compiler .current_block .is_terminated_by_return_or_revert(context); if !already_returns && (compiler.current_block.num_instructions(context) > 0 || compiler.current_block == compiler.function.get_entry_block(context) || compiler.current_block.num_predecessors(context) > 0) { if ret_type.is_unit(context) { ret_val = ConstantContent::get_unit(context); } compiler .current_block .append(context) .ret(ret_val, ret_type); } Ok(func) } #[allow(clippy::too_many_arguments)] fn compile_encoding_v0_abi_method( context: &mut Context, md_mgr: &mut MetadataManager, module: Module, ast_fn_decl: &DeclId<ty::TyFunctionDecl>, logged_types_map: &HashMap<TypeId, LogId>, messages_types_map: &HashMap<TypeId, MessageId>, panic_occurrences: &mut PanicOccurrences, panicking_call_occurrences: &mut PanickingCallOccurrences, panicking_fn_cache: &mut PanickingFunctionCache, engines: &Engines, compiled_fn_cache: &mut CompiledFunctionCache, ) -> Result<Function, Vec<CompileError>> { assert!( !context.experimental.new_encoding, "`new_encoding` was true while calling `compile_encoding_v0_abi_method`" ); // Use the error from .to_fn_selector_value() if possible, else make an CompileError::Internal. let handler = Handler::default(); let ast_fn_decl = engines.de().get_function(ast_fn_decl); let get_selector_result = ast_fn_decl.to_fn_selector_value(&handler, engines); let (errors, _warnings, _infos) = handler.consume(); let selector = match get_selector_result.ok() { Some(selector) => selector, None => { return if !errors.is_empty() { Err(vec![errors[0].clone()]) } else { Err(vec![CompileError::InternalOwned( format!( "Cannot generate selector for ABI method: {}", ast_fn_decl.name.as_str() ), ast_fn_decl.name.span(), )]) }; } }; compile_fn( engines, context, md_mgr, module, &ast_fn_decl, &ast_fn_decl.name, FnCompiler::fn_abi_errors_display(&ast_fn_decl, engines), // ABI methods are only entries when the "new encoding" is off !context.experimental.new_encoding, // ABI methods are always original entries true, Some(selector), logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, None, compiled_fn_cache, ) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/function.rs
sway-core/src/ir_generation/function.rs
//! Engine for compiling a function and all of the AST nodes within. //! //! This is mostly recursively compiling expressions, as Sway is fairly heavily expression based. use super::{ convert::*, lexical_map::LexicalMap, storage::{add_to_b256, get_storage_field_path_and_field_id, get_storage_key}, types::*, CompiledFunctionCache, }; use crate::{ decl_engine::DeclEngineGet as _, engine_threading::*, ir_generation::{ const_eval::{compile_constant_expression, compile_constant_expression_to_constant}, KeyedTyFunctionDecl, PanickingFunctionCache, }, language::{ ty::{ self, ProjectionKind, TyConfigurableDecl, TyConstantDecl, TyExpression, TyExpressionVariant, TyFunctionDisplay, TyStorageField, }, *, }, metadata::MetadataManager, type_system::*, types::*, PanicOccurrence, PanicOccurrences, PanickingCallOccurrence, PanickingCallOccurrences, }; use indexmap::IndexMap; use sway_ast::intrinsics::Intrinsic; use sway_error::error::CompileError; use sway_ir::{Context, *}; use sway_types::{ constants, ident::Ident, integer_bits::IntegerBits, span::{Span, Spanned}, u256::U256, Named, }; use std::convert::TryFrom; use std::{ collections::HashMap, hash::{DefaultHasher, Hash as _}, }; /// The result of compiling an expression can be in memory, or in an (SSA) register. #[derive(Debug, Clone, Copy)] enum CompiledValue { /// The value is in memory, and the pointer to it is returned. InMemory(Value), /// The value is in a register, and the value is returned. InRegister(Value), } impl CompiledValue { fn value(&self) -> Value { match self { CompiledValue::InMemory(value) | CompiledValue::InRegister(value) => *value, } } fn is_terminator(&self, context: &Context) -> bool { self.value().is_terminator(context) } fn get_type(&self, context: &Context) -> Option<Type> { self.value().get_type(context) } fn get_constant(&self, context: &Context) -> Option<Constant> { self.value().get_constant(context).cloned() } fn expect_memory(self) -> Value { match self { CompiledValue::InMemory(value) => value, CompiledValue::InRegister(_) => panic!("Expected InMemory, got InRegister"), } } fn expect_register(self) -> Value { match self { CompiledValue::InMemory(_) => panic!("Expected InRegister, got InMemory"), CompiledValue::InRegister(value) => value, } } } /// Wrapper around Value to enforce distinction between terminating and non-terminating values. struct TerminatorValue { value: CompiledValue, is_terminator: bool, } impl TerminatorValue { pub fn new(value: CompiledValue, context: &Context) -> Self { Self { value, is_terminator: value.is_terminator(context), } } } /// If the provided [TerminatorValue::is_terminator] is true, then return from the current function /// immediately. Otherwise extract the embedded [Value]. macro_rules! return_on_termination_or_extract { ($value:expr) => {{ let val = $value; if val.is_terminator { return Ok(val); }; val.value }}; } pub(crate) struct FnCompiler<'a> { engines: &'a Engines, module: Module, pub(super) function: Function, pub(super) current_block: Block, block_to_break_to: Option<Block>, block_to_continue_to: Option<Block>, current_fn_param: Option<ty::TyFunctionParameter>, lexical_map: LexicalMap, // TODO: (REFERENCES) This field and all its uses must go // once we have references properly implemented. pub ref_mut_args: rustc_hash::FxHashSet<String>, compiled_fn_cache: &'a mut CompiledFunctionCache, /// Maps a [TypeId] of a logged type to the [LogId] of its corresponding log. logged_types_map: &'a HashMap<TypeId, LogId>, /// Maps a [TypeId] of a message data type to the [MessageId] of its corresponding SMO. messages_types_map: &'a HashMap<TypeId, MessageId>, panic_occurrences: &'a mut PanicOccurrences, panicking_call_occurrences: &'a mut PanickingCallOccurrences, panicking_fn_cache: &'a mut PanickingFunctionCache, } /// Store the in-register `value` to a new local variable and return [CompiledValue::InMemory], or return the same `value` if it is already in memory. fn store_to_memory( s: &mut FnCompiler<'_>, context: &mut Context, value: CompiledValue, ) -> Result<CompiledValue, CompileError> { match value { CompiledValue::InMemory(_) => Ok(value), CompiledValue::InRegister(val) => { let temp_arg_name = s.lexical_map.insert_anon(); let value_type = val.get_type(context).unwrap(); let local_var = s .function .new_local_var(context, temp_arg_name, value_type, None, false) .map_err(|ir_error| { CompileError::InternalOwned(ir_error.to_string(), Span::dummy()) })?; let local_var_ptr = s.current_block.append(context).get_local(local_var); let _ = s.current_block.append(context).store(local_var_ptr, val); Ok(CompiledValue::InMemory(local_var_ptr)) } } } /// If a `value` is in memory, load it into a register and return the register value. /// If it is already in a register, return the same `value`. fn load_to_register( s: &mut FnCompiler<'_>, context: &mut Context, value: CompiledValue, ) -> CompiledValue { match value { CompiledValue::InMemory(ptr) => { let val = s.current_block.append(context).load(ptr); CompiledValue::InRegister(val) } CompiledValue::InRegister(_) => value, } } fn calc_addr_as_ptr( current_block: &mut Block, context: &mut Context, ptr: Value, len: Value, ptr_to: Type, ) -> Value { assert!(ptr.get_type(context).unwrap().is_ptr(context)); assert!(len.get_type(context).unwrap().is_uint64(context)); let addr = current_block .append(context) .binary_op(BinaryOpKind::Add, ptr, len); // cast the addr to ptr_to let ptr_to = Type::new_typed_pointer(context, ptr_to); current_block .append(context) .cast_ptr(addr, ptr_to) .add_metadatum(context, None) } impl<'a> FnCompiler<'a> { pub(super) const BACKTRACE_FN_ARG_NAME: &'static str = "__backtrace"; const MAX_PANIC_ERROR_CODE: u64 = 255; // 2^8 - 1. const MAX_PANICKING_CALL_ID: u64 = 2047; // 2^11 - 1. const FN_DISPLAY_FOR_ABI_ERRORS: TyFunctionDisplay = TyFunctionDisplay::full().without_signature(); #[allow(clippy::too_many_arguments)] pub(super) fn new( engines: &'a Engines, context: &mut Context, module: Module, function: Function, logged_types_map: &'a HashMap<TypeId, LogId>, messages_types_map: &'a HashMap<TypeId, MessageId>, panic_occurrences: &'a mut PanicOccurrences, panicking_call_occurrences: &'a mut PanickingCallOccurrences, panicking_fn_cache: &'a mut PanickingFunctionCache, compiled_fn_cache: &'a mut CompiledFunctionCache, ) -> Self { let lexical_map = LexicalMap::from_iter( function .args_iter(context) .map(|(name, _value)| name.clone()), ); FnCompiler { engines, module, function, current_block: function.get_entry_block(context), block_to_break_to: None, block_to_continue_to: None, lexical_map, ref_mut_args: rustc_hash::FxHashSet::default(), compiled_fn_cache, current_fn_param: None, logged_types_map, messages_types_map, panic_occurrences, panicking_call_occurrences, panicking_fn_cache, } } /// Returns the textual representation of the function represented /// by `fn_decl` in the ABI errors related context, in the "errorCodes" /// and "panickingCalls" sections. pub(super) fn fn_abi_errors_display(fn_decl: &ty::TyFunctionDecl, engines: &Engines) -> String { Self::FN_DISPLAY_FOR_ABI_ERRORS.display(fn_decl, engines) } fn compile_with_new_scope<F, T, R>(&mut self, inner: F) -> Result<T, R> where F: FnOnce(&mut FnCompiler) -> Result<T, R>, { self.lexical_map.enter_scope(); let result = inner(self); self.lexical_map.leave_scope(); result } pub(super) fn compile_fn_to_value( &mut self, context: &mut Context, md_mgr: &mut MetadataManager, ast_block: &ty::TyCodeBlock, ) -> Result<Value, Vec<CompileError>> { // Function arguments, like all locals need to be in memory, so that their addresses // can be taken. So we create locals for each argument and store the value there. let entry = self.function.get_entry_block(context); for (arg_name, arg_value) in self .function .args_iter(context) .cloned() .collect::<Vec<_>>() { let local_name = self.lexical_map.insert(arg_name.as_str().to_owned()); let local_var = self.function.new_unique_local_var( context, local_name.clone(), arg_value.get_type(context).unwrap(), None, false, ); if self.ref_mut_args.contains(&arg_name) { self.ref_mut_args.insert(local_name); } let local_val = entry.append(context).get_local(local_var); entry.append(context).store(local_val, arg_value); } match self.compile_code_block(context, md_mgr, ast_block)?.value { // Final value must always be in a register, not in memory. CompiledValue::InRegister(val) => Ok(val), CompiledValue::InMemory(_val) => { // Return an error indicating that the final value is in memory. Err(vec![CompileError::Internal( "Final value is in memory", ast_block.whole_block_span.clone(), )]) } } } fn compile_code_block( &mut self, context: &mut Context, md_mgr: &mut MetadataManager, ast_block: &ty::TyCodeBlock, ) -> Result<TerminatorValue, Vec<CompileError>> { self.compile_with_new_scope(|fn_compiler| { let mut errors = vec![]; let mut ast_nodes = ast_block.contents.iter(); let v = loop { let ast_node = match ast_nodes.next() { Some(ast_node) => ast_node, None => { break TerminatorValue::new( CompiledValue::InRegister(ConstantContent::get_unit(context)), context, ) } }; match fn_compiler.compile_ast_node(context, md_mgr, ast_node) { // 'Some' indicates an implicit return or a diverging expression, so break. Ok(Some(val)) => break val, Ok(None) => (), Err(e) => { errors.push(e); } } }; if !errors.is_empty() { Err(errors) } else { Ok(v) } }) } fn compile_ast_node( &mut self, context: &mut Context, md_mgr: &mut MetadataManager, ast_node: &ty::TyAstNode, ) -> Result<Option<TerminatorValue>, CompileError> { let unexpected_decl = |decl_type: &'static str| { Err(CompileError::UnexpectedDeclaration { decl_type, span: ast_node.span.clone(), }) }; let span_md_idx = md_mgr.span_to_md(context, &ast_node.span); match &ast_node.content { ty::TyAstNodeContent::Declaration(td) => match td { ty::TyDecl::VariableDecl(tvd) => { self.compile_var_decl(context, md_mgr, tvd, span_md_idx) } ty::TyDecl::ConstantDecl(ty::ConstantDecl { decl_id, .. }) => { let tcd = self.engines.de().get_constant(decl_id); self.compile_const_decl(context, md_mgr, &tcd, span_md_idx, false)?; Ok(None) } ty::TyDecl::ConfigurableDecl(ty::ConfigurableDecl { .. }) => { unreachable!() } ty::TyDecl::ConstGenericDecl(_) => { unreachable!("ConstGenericDecl is not reachable from AstNode") } ty::TyDecl::EnumDecl(ty::EnumDecl { decl_id, .. }) => { let ted = self.engines.de().get_enum(decl_id); create_tagged_union_type( self.engines, context, md_mgr, self.module, &ted.variants, ) .map(|_| ())?; Ok(None) } ty::TyDecl::TypeAliasDecl { .. } => unexpected_decl("type alias"), ty::TyDecl::ImplSelfOrTrait { .. } => { // XXX What if we ignore the trait implementation??? Potentially since // we currently inline everything and below we 'recreate' the functions // lazily as they are called, nothing needs to be done here. BUT! // This is obviously not really correct, and eventually we want to // compile and then call these properly. Ok(None) } ty::TyDecl::FunctionDecl { .. } => unexpected_decl("function"), ty::TyDecl::TraitDecl { .. } => unexpected_decl("trait"), ty::TyDecl::StructDecl { .. } => unexpected_decl("struct"), ty::TyDecl::AbiDecl { .. } => unexpected_decl("abi"), ty::TyDecl::GenericTypeForFunctionScope { .. } => unexpected_decl("generic type"), ty::TyDecl::ErrorRecovery { .. } => unexpected_decl("error recovery"), ty::TyDecl::StorageDecl { .. } => unexpected_decl("storage"), ty::TyDecl::EnumVariantDecl { .. } => unexpected_decl("enum variant"), ty::TyDecl::TraitTypeDecl { .. } => unexpected_decl("trait type"), }, ty::TyAstNodeContent::Expression(te) => { match &te.expression { TyExpressionVariant::ImplicitReturn(exp) => self .compile_expression_to_register(context, md_mgr, exp) .map(Some), _ => { // An expression with an ignored return value... I assume. let value = self.compile_expression_to_register(context, md_mgr, te)?; // Terminating values should end the compilation of the block if value.is_terminator { Ok(Some(value)) } else { Ok(None) } } } } // a side effect can be () because it just impacts the type system/namespacing. // There should be no new IR generated. ty::TyAstNodeContent::SideEffect(_) => Ok(None), ty::TyAstNodeContent::Error(_, _) => { unreachable!("error node found when generating IR"); } } } // Compile expression, and if the compiled result is in memory, load it to a register. fn compile_expression_to_register( &mut self, context: &mut Context, md_mgr: &mut MetadataManager, ast_expr: &ty::TyExpression, ) -> Result<TerminatorValue, CompileError> { let compiled = return_on_termination_or_extract!(self.compile_expression(context, md_mgr, ast_expr)?); Ok(TerminatorValue::new( load_to_register(self, context, compiled), context, )) } // Compile expression, and if the compiled result is in a register, store it to memory. fn compile_expression_to_memory( &mut self, context: &mut Context, md_mgr: &mut MetadataManager, ast_expr: &ty::TyExpression, ) -> Result<TerminatorValue, CompileError> { // Compile expression which *may* be a pointer. let val = return_on_termination_or_extract!(self.compile_expression(context, md_mgr, ast_expr)?); Ok(TerminatorValue::new( store_to_memory(self, context, val)?, context, )) } // Can be used for raw untyped slice and string slice fn compile_slice( &mut self, context: &mut Context, span_md_idx: Option<MetadataIndex>, slice_ptr: Value, slice_len: u64, ) -> Result<TerminatorValue, CompileError> { let int_ty = Type::get_uint64(context); let ptr_ty = Type::get_ptr(context); // build field values of the slice let ptr_val = self .current_block .append(context) .cast_ptr(slice_ptr, ptr_ty) .add_metadatum(context, span_md_idx); let len_val = ConstantContent::get_uint(context, 64, slice_len); // a slice is a pointer and a length let field_types = vec![ptr_ty, int_ty]; // build a struct variable to store the values let struct_type = Type::new_struct(context, field_types.clone()); let struct_var = self .function .new_local_var( context, self.lexical_map.insert_anon(), struct_type, None, false, ) .map_err(|ir_error| CompileError::InternalOwned(ir_error.to_string(), Span::dummy()))?; let struct_val = self .current_block .append(context) .get_local(struct_var) .add_metadatum(context, span_md_idx); // put field values inside the struct variable [ptr_val, len_val] .into_iter() .zip(field_types) .enumerate() .for_each(|(insert_idx, (insert_val, field_type))| { let gep_val = self.current_block.append(context).get_elem_ptr_with_idx( struct_val, field_type, insert_idx as u64, ); self.current_block .append(context) .store(gep_val, insert_val) .add_metadatum(context, span_md_idx); }); // build a slice variable to return let slice_type = Type::get_slice(context); let slice_var = self .function .new_local_var( context, self.lexical_map.insert_anon(), slice_type, None, false, ) .map_err(|ir_error| CompileError::InternalOwned(ir_error.to_string(), Span::dummy()))?; let slice_val = self .current_block .append(context) .get_local(slice_var) .add_metadatum(context, span_md_idx); // copy the value of the struct variable into the slice self.current_block .append(context) .mem_copy_bytes(slice_val, struct_val, 16); // return the slice Ok(TerminatorValue::new( CompiledValue::InMemory(slice_val), context, )) } fn compile_expression( &mut self, context: &mut Context, md_mgr: &mut MetadataManager, ast_expr: &ty::TyExpression, ) -> Result<TerminatorValue, CompileError> { let span_md_idx = md_mgr.span_to_md(context, &ast_expr.span); match &ast_expr.expression { ty::TyExpressionVariant::Literal(Literal::String(s)) => { let string_data = ConstantContent::get_string(context, s.as_str().as_bytes().to_vec()) .get_constant(context) .unwrap(); let string_data_ptr = self.module.new_unique_global_var( context, "__const_global".into(), string_data.get_content(context).ty, Some(*string_data), false, ); let string_ptr = self .current_block .append(context) .get_global(string_data_ptr); let string_len = s.as_str().len() as u64; self.compile_slice(context, span_md_idx, string_ptr, string_len) } ty::TyExpressionVariant::Literal(Literal::Binary(bytes)) => { let data = ConstantContent::get_untyped_slice(context, bytes.clone()) .get_constant(context) .unwrap(); let data_ptr = self.module.new_unique_global_var( context, "__const_global".into(), data.get_content(context).ty, Some(*data), false, ); let slice_ptr = self.current_block.append(context).get_global(data_ptr); let slice_len = bytes.len() as u64; self.compile_slice(context, span_md_idx, slice_ptr, slice_len) } ty::TyExpressionVariant::Literal(Literal::Numeric(n)) => { let implied_lit = match &*self.engines.te().get(ast_expr.return_type) { TypeInfo::UnsignedInteger(IntegerBits::Eight) => Literal::U8(*n as u8), TypeInfo::UnsignedInteger(IntegerBits::V256) => Literal::U256(U256::from(*n)), _ => // Anything more than a byte needs a u64 (except U256 of course). // (This is how convert_literal_to_value treats it too). { Literal::U64(*n) } }; let val = convert_literal_to_value(context, &implied_lit) .add_metadatum(context, span_md_idx); Ok(TerminatorValue::new( CompiledValue::InRegister(val), context, )) } ty::TyExpressionVariant::Literal(l) => { let val = convert_literal_to_value(context, l).add_metadatum(context, span_md_idx); Ok(TerminatorValue::new( CompiledValue::InRegister(val), context, )) } ty::TyExpressionVariant::FunctionApplication { call_path: name, contract_call_params, arguments, fn_ref, selector, .. } => { if let Some(metadata) = selector { self.compile_contract_call_encoding_v0( context, md_mgr, metadata, contract_call_params, name.suffix.as_str(), arguments, ast_expr.return_type, span_md_idx, ) } else { let function_decl = self.engines.de().get_function(fn_ref); self.compile_fn_call( context, md_mgr, arguments, &function_decl, span_md_idx, name, ) } } ty::TyExpressionVariant::LazyOperator { op, lhs, rhs } => { self.compile_lazy_op(context, md_mgr, op, lhs, rhs, span_md_idx) } ty::TyExpressionVariant::ConstantExpression { decl: const_decl, .. } => self.compile_const_expr(context, md_mgr, const_decl, span_md_idx), ty::TyExpressionVariant::ConfigurableExpression { decl: const_decl, .. } => self.compile_config_expr(context, const_decl, span_md_idx), ty::TyExpressionVariant::ConstGenericExpression { decl, span, .. } => { if let Some(value) = decl.value.as_ref() { self.compile_expression(context, md_mgr, value) } else { Err(CompileError::Internal( "Const generic not materialized", span.clone(), )) } } ty::TyExpressionVariant::VariableExpression { name, call_path, .. } => self.compile_var_expr(context, call_path, name, span_md_idx), ty::TyExpressionVariant::ArrayExplicit { elem_type, contents, } => { self.compile_array_explicit_expr(context, md_mgr, *elem_type, contents, span_md_idx) } ty::TyExpressionVariant::ArrayRepeat { elem_type, value, length, } => self.compile_array_repeat_expr( context, md_mgr, *elem_type, value, length, span_md_idx, ), ty::TyExpressionVariant::ArrayIndex { prefix, index } => { self.compile_array_index(context, md_mgr, prefix, index, span_md_idx) } ty::TyExpressionVariant::StructExpression { fields, .. } => { self.compile_struct_expr(context, md_mgr, fields, span_md_idx) } ty::TyExpressionVariant::CodeBlock(cb) => { //TODO return all errors self.compile_code_block(context, md_mgr, cb) .map_err(|mut x| x.pop().unwrap()) } ty::TyExpressionVariant::FunctionParameter => Err(CompileError::Internal( "Unexpected function parameter declaration.", ast_expr.span.clone(), )), ty::TyExpressionVariant::MatchExp { desugared, .. } => { self.compile_expression_to_register(context, md_mgr, desugared) } ty::TyExpressionVariant::IfExp { condition, then, r#else, } => self.compile_if( context, md_mgr, condition, then, r#else.as_deref(), ast_expr.return_type, ), ty::TyExpressionVariant::AsmExpression { registers, body, returns, whole_block_span, } => { let span_md_idx = md_mgr.span_to_md(context, whole_block_span); self.compile_asm_expr( context, md_mgr, registers, body, ast_expr.return_type, returns.as_ref(), span_md_idx, ) } ty::TyExpressionVariant::StructFieldAccess { prefix, field_to_access, resolved_type_of_parent, .. } => { let span_md_idx = md_mgr.span_to_md(context, &field_to_access.span); self.compile_struct_field_expr( context, md_mgr, prefix, *resolved_type_of_parent, field_to_access, span_md_idx, ) } ty::TyExpressionVariant::EnumInstantiation { enum_ref, tag, contents, .. } => { let enum_decl = self.engines.de().get_enum(enum_ref); self.compile_enum_expr(context, md_mgr, &enum_decl, *tag, contents.as_deref()) } ty::TyExpressionVariant::Tuple { fields } => { self.compile_tuple_expr(context, md_mgr, fields, span_md_idx) } ty::TyExpressionVariant::TupleElemAccess { prefix, elem_to_access_num: idx, elem_to_access_span: span, resolved_type_of_parent: tuple_type, } => self.compile_tuple_elem_expr( context, md_mgr, prefix, *tuple_type, *idx, span.clone(), ), ty::TyExpressionVariant::AbiCast { span, .. } => { let span_md_idx = md_mgr.span_to_md(context, span); let val = ConstantContent::get_unit(context).add_metadatum(context, span_md_idx); Ok(TerminatorValue::new( CompiledValue::InRegister(val), context, )) } ty::TyExpressionVariant::StorageAccess(access) => { let span_md_idx: Option<MetadataIndex> = md_mgr.span_to_md(context, &access.span()); let key = TyStorageField::get_key_expression_const( &access.key_expression.clone().map(|v| *v), self.engines, context, md_mgr, self.module, )?; self.compile_storage_access( context, md_mgr, access.storage_field_names.clone(), access.struct_field_names.clone(), key, &access.fields, span_md_idx, ) } ty::TyExpressionVariant::IntrinsicFunction(kind) => self.compile_intrinsic_function( context, md_mgr, kind, ast_expr.span.clone(), ast_expr.return_type, ), ty::TyExpressionVariant::AbiName(_) => { let val = ConstantContent::get_unit(context); Ok(TerminatorValue::new( CompiledValue::InRegister(val), context, )) } ty::TyExpressionVariant::UnsafeDowncast { exp, variant, call_path_decl: _, } => self.compile_unsafe_downcast(context, md_mgr, exp, variant), ty::TyExpressionVariant::EnumTag { exp } => { self.compile_enum_tag(context, md_mgr, exp.to_owned()) } ty::TyExpressionVariant::WhileLoop { body, condition } => { self.compile_while_loop(context, md_mgr, body, condition, span_md_idx) } ty::TyExpressionVariant::ForLoop { desugared } => { self.compile_expression(context, md_mgr, desugared) } ty::TyExpressionVariant::Break => { match self.block_to_break_to { // If `self.block_to_break_to` is not None, then it has been set inside // a loop and the use of `break` here is legal, so create a branch // instruction. Error out otherwise. Some(block_to_break_to) => { let val = self .current_block .append(context) .branch(block_to_break_to, vec![]); Ok(TerminatorValue::new( CompiledValue::InRegister(val), context, )) } None => Err(CompileError::BreakOutsideLoop { span: ast_expr.span.clone(), }), } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/storage.rs
sway-core/src/ir_generation/storage.rs
use crate::fuel_prelude::{ fuel_crypto::Hasher, fuel_tx::StorageSlot, fuel_types::{Bytes32, Bytes8}, }; use sway_ir::{ constant::{ConstantContent, ConstantValue}, context::Context, irtype::Type, Constant, }; use sway_types::u256::U256; /// Determines how values that are less then a word in length /// has to be padded to word boundary when in structs or enums. #[derive(Default)] enum InByte8Padding { #[default] Right, Left, } /// Hands out storage keys using storage field names or an existing key. /// Basically returns sha256((0u8, "storage::<storage_namespace_name1>::<storage_namespace_name2>.<storage_field_name>")) /// or key if defined. pub(super) fn get_storage_key(storage_field_names: Vec<String>, key: Option<U256>) -> Bytes32 { match key { Some(key) => key.to_be_bytes().into(), None => hash_storage_key_string(&get_storage_key_string(&storage_field_names)), } } pub fn get_storage_key_string(storage_field_names: &[String]) -> String { if storage_field_names.len() == 1 { format!( "{}{}{}", sway_utils::constants::STORAGE_TOP_LEVEL_NAMESPACE, sway_utils::constants::STORAGE_FIELD_SEPARATOR, storage_field_names.last().unwrap(), ) } else { format!( "{}{}{}{}{}", sway_utils::constants::STORAGE_TOP_LEVEL_NAMESPACE, sway_utils::constants::STORAGE_NAMESPACE_SEPARATOR, storage_field_names .iter() .take(storage_field_names.len() - 1) .cloned() .collect::<Vec<_>>() .join(sway_utils::constants::STORAGE_NAMESPACE_SEPARATOR), sway_utils::constants::STORAGE_FIELD_SEPARATOR, storage_field_names.last().unwrap(), ) } } /// Hands out unique storage field ids using storage field names and struct field names. /// Basically returns sha256((0u8, "storage::<storage_namespace_name1>::<storage_namespace_name2>.<storage_field_name>.<struct_field_name1>.<struct_field_name2>")). pub(super) fn get_storage_field_path_and_field_id( storage_field_names: &[String], struct_field_names: &[String], ) -> (String, Bytes32) { let path = format!( "{}{}", get_storage_key_string(storage_field_names), if struct_field_names.is_empty() { "".to_string() } else { format!( "{}{}", sway_utils::constants::STRUCT_FIELD_SEPARATOR, struct_field_names.join(sway_utils::constants::STRUCT_FIELD_SEPARATOR), ) } ); let id = hash_storage_key_string(&path); (path, id) } fn hash_storage_key_string(storage_key_string: &str) -> Bytes32 { let mut hasher = Hasher::default(); // Certain storage types, like, e.g., `StorageMap` allow // storage slots of their contained elements to be defined // based on developer's input. E.g., the `key` in a `StorageMap` // used to calculate the storage slot is a developer input. // // To ensure that pre-images of such storage slots can never // be the same as a pre-image of compiler generated key of storage // field, we prefix the pre-images with a single byte that denotes // the domain. Storage types like `StorageMap` must have a different // domain prefix than the `STORAGE_DOMAIN` which is 0u8. // // For detailed elaboration see: https://github.com/FuelLabs/sway/issues/6317 hasher.input(sway_utils::constants::STORAGE_DOMAIN); hasher.input(storage_key_string); hasher.finalize() } use uint::construct_uint; #[allow( // These warnings are generated by the `construct_uint!()` macro below. clippy::assign_op_pattern, clippy::ptr_offset_with_cast, clippy::manual_div_ceil )] pub(super) fn add_to_b256(x: Bytes32, y: u64) -> Bytes32 { construct_uint! { struct U256(4); } let x = U256::from(*x); let y = U256::from(y); let res: [u8; 32] = (x + y).into(); Bytes32::from(res) } /// Given a constant value `constant`, a type `ty`, a state index, and a vector of subfield /// indices, serialize the constant into a vector of storage slots. The keys (slots) are /// generated using the state index and the subfield indices which are recursively built. The /// values are generated such that each subfield gets its own storage slot except for enums and /// strings which are spread over successive storage slots (use `serialize_to_words` in this case). /// /// This behavior matches the behavior of how storage slots are assigned for storage reads and /// writes (i.e. how `state_read_*` and `state_write_*` instructions are generated). pub fn serialize_to_storage_slots( constant: &Constant, context: &Context, storage_field_names: Vec<String>, key: Option<U256>, ty: &Type, ) -> Vec<StorageSlot> { match &constant.get_content(context).value { ConstantValue::Undef => vec![], // If not being a part of an aggregate, single byte values like `bool`, `u8`, and unit // are stored as a byte at the beginning of the storage slot. ConstantValue::Unit if ty.is_unit(context) => vec![StorageSlot::new( get_storage_key(storage_field_names, key), Bytes32::new([0; 32]), )], ConstantValue::Bool(b) if ty.is_bool(context) => { vec![StorageSlot::new( get_storage_key(storage_field_names, key), Bytes32::new([ if *b { 1 } else { 0 }, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]), )] } ConstantValue::Uint(b) if ty.is_uint8(context) => { vec![StorageSlot::new( get_storage_key(storage_field_names, key), Bytes32::new([ *b as u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]), )] } // Similarly, other uint values are stored at the beginning of the storage slot. ConstantValue::Uint(n) if ty.is_uint(context) => { vec![StorageSlot::new( get_storage_key(storage_field_names, key), Bytes32::new( n.to_be_bytes() .iter() .cloned() .chain([0; 24].iter().cloned()) .collect::<Vec<u8>>() .try_into() .unwrap(), ), )] } ConstantValue::U256(b) if ty.is_uint_of(context, 256) => { vec![StorageSlot::new( get_storage_key(storage_field_names, key), Bytes32::new(b.to_be_bytes()), )] } ConstantValue::B256(b) if ty.is_b256(context) => { vec![StorageSlot::new( get_storage_key(storage_field_names, key), Bytes32::new(b.to_be_bytes()), )] } ConstantValue::Array(_a) if ty.is_array(context) => { unimplemented!("Arrays in storage have not been implemented yet.") } _ if ty.is_string_array(context) || ty.is_struct(context) || ty.is_union(context) => { // Serialize the constant data in words and add zero words until the number of words // is a multiple of 4. This is useful because each storage slot is 4 words. // Regarding padding, the top level type in the call is either a string array, struct, or // a union. They will properly set the initial padding for the further recursive calls. let mut packed = serialize_to_words( constant.get_content(context), context, ty, InByte8Padding::default(), ); packed.extend(vec![ Bytes8::new([0; 8]); packed.len().div_ceil(4) * 4 - packed.len() ]); assert!(packed.len().is_multiple_of(4)); // Return a list of `StorageSlot`s // First get the keys then get the values // TODO-MEMLAY: Warning! Here we make an assumption about the memory layout of // string arrays, structs, and enum. // The assumption is that they are rounded to word boundaries // which will very likely always be the case. // We will not refactor the Storage API at the moment to remove this // assumption. It is a questionable effort because we anyhow // want to improve and refactor Storage API in the future. let type_size_in_bytes = ty.size(context).in_bytes(); assert!( type_size_in_bytes.is_multiple_of(8), "Expected string arrays, structs, and enums to be aligned to word boundary. The type size in bytes was {} and the type was {}.", type_size_in_bytes, ty.as_string(context) ); let storage_key = get_storage_key(storage_field_names, key); (0..type_size_in_bytes.div_ceil(32)) .map(|i| add_to_b256(storage_key, i)) .zip((0..packed.len() / 4).map(|i| { Bytes32::new( Vec::from_iter((0..4).flat_map(|j| *packed[4 * i + j])) .try_into() .unwrap(), ) })) .map(|(k, r)| StorageSlot::new(k, r)) .collect() } _ => vec![], } } /// Given a constant value `constant` and a type `ty`, serialize the constant into a vector of /// words and apply the requested padding if needed. fn serialize_to_words( constant: &ConstantContent, context: &Context, ty: &Type, padding: InByte8Padding, ) -> Vec<Bytes8> { match &constant.value { ConstantValue::Undef => vec![], ConstantValue::Unit if ty.is_unit(context) => vec![Bytes8::new([0; 8])], ConstantValue::Bool(b) if ty.is_bool(context) => match padding { InByte8Padding::Right => { vec![Bytes8::new([if *b { 1 } else { 0 }, 0, 0, 0, 0, 0, 0, 0])] } InByte8Padding::Left => { vec![Bytes8::new([0, 0, 0, 0, 0, 0, 0, if *b { 1 } else { 0 }])] } }, ConstantValue::Uint(n) if ty.is_uint8(context) => match padding { InByte8Padding::Right => vec![Bytes8::new([*n as u8, 0, 0, 0, 0, 0, 0, 0])], InByte8Padding::Left => vec![Bytes8::new([0, 0, 0, 0, 0, 0, 0, *n as u8])], }, ConstantValue::Uint(n) if ty.is_uint(context) => { vec![Bytes8::new(n.to_be_bytes())] } ConstantValue::U256(b) if ty.is_uint_of(context, 256) => { let b = b.to_be_bytes(); Vec::from_iter((0..4).map(|i| Bytes8::new(b[8 * i..8 * i + 8].try_into().unwrap()))) } ConstantValue::B256(b) if ty.is_b256(context) => { let b = b.to_be_bytes(); Vec::from_iter((0..4).map(|i| Bytes8::new(b[8 * i..8 * i + 8].try_into().unwrap()))) } ConstantValue::String(s) if ty.is_string_array(context) => { // Turn the bytes into serialized words (Bytes8) and right pad it to the word boundary. let mut s = s.clone(); s.extend(vec![0; s.len().div_ceil(8) * 8 - s.len()]); assert!(s.len() % 8 == 0); // Group into words. Vec::from_iter((0..s.len() / 8).map(|i| { Bytes8::new( Vec::from_iter((0..8).map(|j| s[8 * i + j])) .try_into() .unwrap(), ) })) } ConstantValue::Array(_) if ty.is_array(context) => { unimplemented!("Arrays in storage have not been implemented yet.") } ConstantValue::Struct(vec) if ty.is_struct(context) => { let field_tys = ty.get_field_types(context); vec.iter() .zip(field_tys.iter()) // TODO-MEMLAY: Warning! Again, making an assumption about the memory layout // of struct fields. .flat_map(|(f, ty)| serialize_to_words(f, context, ty, InByte8Padding::Right)) .collect() } _ if ty.is_union(context) => { let value_size_in_words = ty.size(context).in_words(); let constant_size_in_words = constant.ty.size(context).in_words(); assert!(value_size_in_words >= constant_size_in_words); // Add enough left padding to satisfy the actual size of the union // TODO-MEMLAY: Warning! Here we make an assumption about the memory layout of enums, // that they are left padded. // The memory layout of enums can be changed in the future. // We will not refactor the Storage API at the moment to remove this // assumption. It is a questionable effort because we anyhow // want to improve and refactor Storage API in the future. let padding_size_in_words = value_size_in_words - constant_size_in_words; vec![Bytes8::new([0; 8]); padding_size_in_words as usize] .iter() .cloned() .chain( serialize_to_words(constant, context, &constant.ty, InByte8Padding::Left) .iter() .cloned(), ) .collect() } _ => vec![], } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/types.rs
sway-core/src/ir_generation/types.rs
use crate::{ ast_elements::type_argument::GenericTypeArgument, decl_engine::DeclEngine, language::ty, metadata::MetadataManager, type_system::{TypeId, TypeInfo}, Engines, TypeEngine, }; use super::convert::convert_resolved_typeid_no_span; use sway_error::error::CompileError; use sway_ir::{Context, Module, Type}; use sway_types::span::Spanned; pub(super) fn create_tagged_union_type( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, variants: &[ty::TyEnumVariant], ) -> Result<Type, CompileError> { // Create the enum aggregate first. NOTE: single variant enums don't need an aggregate but are // getting one here anyway. They don't need to be a tagged union either. let field_types: Vec<_> = variants .iter() .map(|variant| { convert_resolved_typeid_no_span( engines, context, md_mgr, module, None, variant.type_argument.type_id, ) }) .collect::<Result<Vec<_>, CompileError>>()?; // Enums where all the variants are unit types don't really need the union. Only a tag is // needed. For consistency, and to keep enums as reference types, we keep the tag in an // Aggregate. Ok(if field_types.iter().all(|f| f.is_unit(context)) { Type::new_struct(context, vec![Type::get_uint64(context)]) } else { let u64_ty = Type::get_uint64(context); let union_ty = Type::new_union(context, field_types); Type::new_struct(context, vec![u64_ty, union_ty]) }) } pub(super) fn create_tuple_aggregate( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, fields: &[TypeId], ) -> Result<Type, CompileError> { let field_types = fields .iter() .map(|ty_id| { convert_resolved_typeid_no_span(engines, context, md_mgr, module, None, *ty_id) }) .collect::<Result<Vec<_>, CompileError>>()?; Ok(Type::new_struct(context, field_types)) } pub(super) fn create_array_aggregate( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, element_type_id: TypeId, count: u64, ) -> Result<Type, CompileError> { let element_type = convert_resolved_typeid_no_span(engines, context, md_mgr, module, None, element_type_id)?; Ok(Type::new_array(context, element_type, count)) } pub(super) fn get_struct_for_types( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, type_ids: &[TypeId], ) -> Result<Type, CompileError> { let types = type_ids .iter() .map(|ty_id| { convert_resolved_typeid_no_span(engines, context, md_mgr, module, None, *ty_id) }) .collect::<Result<Vec<_>, CompileError>>()?; Ok(Type::new_struct(context, types)) } /// For the [TypeInfo::Struct] given by `struct_type_id` and the /// [ty::ProjectionKind::StructField] given by `field_kind` /// returns the name of the struct, and the field index within /// the struct together with the field [TypeId] if the field exists /// on the struct. /// /// Returns `None` if the `struct_type_id` is not a [TypeInfo::Struct] /// or an alias to a [TypeInfo::Struct] or if the `field_kind` /// is not a [ty::ProjectionKind::StructField]. pub(super) fn get_struct_name_field_index_and_type( type_engine: &TypeEngine, decl_engine: &DeclEngine, struct_type_id: TypeId, field_kind: ty::ProjectionKind, ) -> Option<(String, Option<(u64, TypeId)>)> { let struct_ty_info = type_engine .to_typeinfo(struct_type_id, &field_kind.span()) .ok()?; match (struct_ty_info, &field_kind) { ( TypeInfo::Struct(decl_ref), ty::ProjectionKind::StructField { name: field_name, field_to_access: _, }, ) => { let decl = decl_engine.get_struct(&decl_ref); Some(( decl.call_path.suffix.as_str().to_owned(), decl.fields .iter() .enumerate() .find(|(_, field)| field.name == *field_name) .map(|(idx, field)| (idx as u64, field.type_argument.type_id)), )) } ( TypeInfo::Alias { ty: GenericTypeArgument { type_id, .. }, .. }, _, ) => get_struct_name_field_index_and_type(type_engine, decl_engine, type_id, field_kind), _ => None, } } // To gather the indices into nested structs for the struct oriented IR instructions we need to // inspect the names and types of a vector of fields in a path. There are several different // representations of this in the AST but we can wrap fetching the struct type and field name in a // trait. And we can even wrap the implementation in a macro. pub(super) trait TypedNamedField { fn get_field_kind(&self) -> ty::ProjectionKind; } macro_rules! impl_typed_named_field_for { ($field_type_name: ident) => { impl TypedNamedField for $field_type_name { fn get_field_kind(&self) -> ty::ProjectionKind { ty::ProjectionKind::StructField { name: self.name.clone(), field_to_access: None, } } } }; } impl TypedNamedField for ty::ProjectionKind { fn get_field_kind(&self) -> ty::ProjectionKind { self.clone() } } use ty::TyStorageAccessDescriptor; impl_typed_named_field_for!(TyStorageAccessDescriptor); pub(super) fn get_indices_for_struct_access( type_engine: &TypeEngine, decl_engine: &DeclEngine, base_type: TypeId, fields: &[impl TypedNamedField], ) -> Result<Vec<u64>, CompileError> { fields .iter() .try_fold( (Vec::new(), base_type), |(mut fld_idcs, prev_type_id), field| { let field_kind = field.get_field_kind(); let ty_info = match type_engine.to_typeinfo(prev_type_id, &field_kind.span()) { Ok(ty_info) => ty_info, Err(error) => { return Err(CompileError::InternalOwned( format!("type error resolving type for reassignment: {error}"), field_kind.span(), )); } }; // Make sure we have an aggregate to index into. // Get the field index and also its type for the next iteration. match (ty_info, &field_kind) { ( TypeInfo::Struct(decl_ref), ty::ProjectionKind::StructField { name: field_name, field_to_access: _, }, ) => { let decl = decl_engine.get_struct(&decl_ref); let field_idx_and_type_opt = decl .fields .iter() .enumerate() .find(|(_, field)| field.name == *field_name); let (field_idx, field_type) = match field_idx_and_type_opt { Some((idx, field)) => (idx as u64, field.type_argument.type_id), None => { return Err(CompileError::InternalOwned( format!( "Unknown field '{}' for struct {} in reassignment.", field_kind.pretty_print(), decl.call_path, ), field_kind.span(), )); } }; // Save the field index. fld_idcs.push(field_idx); Ok((fld_idcs, field_type)) } (TypeInfo::Tuple(fields), ty::ProjectionKind::TupleField { index, .. }) => { let field_type = match fields.get(*index) { Some(field_type_argument) => field_type_argument.type_id, None => { return Err(CompileError::InternalOwned( format!( "index {} is out of bounds for tuple of length {}", index, fields.len(), ), field_kind.span(), )); } }; fld_idcs.push(*index as u64); Ok((fld_idcs, field_type)) } _ => Err(CompileError::Internal( "Unknown aggregate in reassignment.", field_kind.span(), )), } }, ) .map(|(fld_idcs, _)| fld_idcs) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/const_eval.rs
sway-core/src/ir_generation/const_eval.rs
use std::{ hash::{DefaultHasher, Hash}, io::Read, ops::{BitAnd, BitOr, BitXor, Not, Rem}, }; use crate::{ engine_threading::*, ir_generation::function::{get_encoding_representation_by_id, get_memory_id}, language::{ ty::{self, TyConstantDecl, TyIntrinsicFunctionKind}, CallPath, Literal, }, metadata::MetadataManager, semantic_analysis::*, TypeInfo, UnifyCheck, }; use super::{ convert::{convert_literal_to_constant, convert_resolved_type_id}, function::FnCompiler, types::*, }; use sway_ast::Intrinsic; use sway_error::error::CompileError; use sway_ir::{ constant::{ConstantContent, ConstantValue}, context::Context, module::Module, value::Value, Constant, GlobalVar, InstOp, Instruction, Type, TypeContent, }; use sway_types::{ident::Ident, integer_bits::IntegerBits, span::Spanned, Named, Span}; use sway_utils::mapped_stack::MappedStack; #[derive(Debug)] enum ConstEvalError { CompileError, CannotBeEvaluatedToConst { // This is not used at the moment because we do not give detailed description of why a // const eval failed. // Nonetheless, this is used in tests to help debug. #[allow(dead_code)] span: Span, }, } pub(crate) struct LookupEnv<'a, 'eng> { pub(crate) engines: &'a Engines, pub(crate) context: &'a mut Context<'eng>, pub(crate) md_mgr: &'a mut MetadataManager, pub(crate) module: Module, pub(crate) module_ns: Option<&'a namespace::Module>, pub(crate) function_compiler: Option<&'a FnCompiler<'a>>, #[allow(clippy::type_complexity)] pub(crate) lookup: fn( &mut LookupEnv, &CallPath, &Option<TyConstantDecl>, ) -> Result<Option<Value>, CompileError>, } pub(crate) fn compile_const_decl( env: &mut LookupEnv, call_path: &CallPath, const_decl: &Option<TyConstantDecl>, ) -> Result<Option<Value>, CompileError> { // Check if it's a processed local constant. if let Some(fn_compiler) = env.function_compiler { let mut found_local = false; if let Some(local_var) = fn_compiler.get_function_var(env.context, call_path.suffix.as_str()) { found_local = true; if let Some(constant) = local_var.get_initializer(env.context) { return Ok(Some(Value::new_constant(env.context, *constant))); } // Check if a constant was stored to a local variable in the current block. let mut stored_const_opt: Option<&Constant> = None; for ins in fn_compiler.current_block.instruction_iter(env.context) { if let Some(Instruction { op: InstOp::Store { dst_val_ptr: dst_val, stored_val, }, .. }) = ins.get_instruction(env.context) { if let Some(Instruction { op: InstOp::GetLocal(store_dst_var), .. }) = dst_val.get_instruction(env.context) { if &local_var == store_dst_var { stored_const_opt = stored_val.get_constant(env.context); } } } } if let Some(constant) = stored_const_opt { return Ok(Some(Value::new_constant(env.context, *constant))); } } if let Some(value) = fn_compiler.get_function_arg(env.context, call_path.suffix.as_str()) { found_local = true; if value.get_constant(env.context).is_some() { return Ok(Some(value)); } } if found_local { return Ok(None); } } // Check if it's a processed global constant. match ( env.module .get_global_variable(env.context, &call_path.as_vec_string()), env.module_ns, ) { (Some(global_var), _) => { let constant = global_var .get_initializer(env.context) .expect("const decl without initializer, should've been detected way early"); Ok(Some(Value::new_constant(env.context, *constant))) } (None, Some(module_ns)) => { // See if we it's a global const and whether we can compile it *now*. let decl = module_ns.root_items().check_symbol(&call_path.suffix); let const_decl = match const_decl { Some(decl) => Some(decl), None => None, }; let const_decl = match decl { Ok(decl) => match decl.expect_typed() { ty::TyDecl::ConstantDecl(ty::ConstantDecl { decl_id, .. }) => { Some((*env.engines.de().get_constant(&decl_id)).clone()) } _otherwise => const_decl.cloned(), }, Err(_) => const_decl.cloned(), }; match const_decl { Some(const_decl) => { let ty::TyConstantDecl { call_path, value, .. } = const_decl; let Some(value) = value else { return Ok(None); }; let const_val = compile_constant_expression( env.engines, env.context, env.md_mgr, env.module, env.module_ns, env.function_compiler, &call_path, &value, )?; let const_val_c = *const_val .get_constant(env.context) .expect("Must have been compiled to a constant"); let c_ty = const_val_c.get_content(env.context).ty; let const_global = GlobalVar::new(env.context, c_ty, Some(const_val_c), false); env.module.add_global_variable( env.context, call_path.as_vec_string().to_vec(), const_global, ); Ok(Some(const_val)) } None => Ok(None), } } _ => Ok(None), } } #[allow(clippy::too_many_arguments)] pub(super) fn compile_constant_expression( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, module_ns: Option<&namespace::Module>, function_compiler: Option<&FnCompiler>, _call_path: &CallPath, const_expr: &ty::TyExpression, ) -> Result<Value, CompileError> { let span_id_idx = md_mgr.span_to_md(context, &const_expr.span); let constant_evaluated = compile_constant_expression_to_constant( engines, context, md_mgr, module, module_ns, function_compiler, const_expr, )?; Ok(Value::new_constant(context, constant_evaluated).add_metadatum(context, span_id_idx)) } #[allow(clippy::too_many_arguments)] pub(crate) fn compile_constant_expression_to_constant( engines: &Engines, context: &mut Context, md_mgr: &mut MetadataManager, module: Module, module_ns: Option<&namespace::Module>, function_compiler: Option<&FnCompiler>, const_expr: &ty::TyExpression, ) -> Result<Constant, CompileError> { let lookup = &mut LookupEnv { engines, context, md_mgr, module, module_ns, function_compiler, lookup: compile_const_decl, }; let err = match &const_expr.expression { // Special case functions because the span in `const_expr` is to the inlined function // definition, rather than the actual call site. ty::TyExpressionVariant::FunctionApplication { call_path, .. } => { let span = call_path.span(); let span = if span.is_dummy() { const_expr.span.clone() } else { span }; Err(CompileError::NonConstantDeclValue { span }) } _otherwise => Err(CompileError::NonConstantDeclValue { span: const_expr.span.clone(), }), }; let mut known_consts = MappedStack::<Ident, Constant>::new(); match const_eval_typed_expr(lookup, &mut known_consts, const_expr) { Ok(Some(constant)) => Ok(constant), Ok(None) => err, Err(_) => err, } } fn create_array_from_vec( lookup: &mut LookupEnv, elem_type: crate::TypeId, element_types: Vec<crate::TypeId>, element_vals: Vec<Constant>, ) -> Option<Constant> { assert!({ let unify_check = UnifyCheck::coercion(lookup.engines); element_types .iter() .all(|tid| unify_check.check(*tid, elem_type)) }); let arr = create_array_aggregate( lookup.engines, lookup.context, lookup.md_mgr, lookup.module, elem_type, element_types.len().try_into().unwrap(), ) .map_or(None, |array_ty| { Some(ConstantContent::new_array( lookup.context, array_ty.get_array_elem_type(lookup.context).unwrap(), element_vals .iter() .map(|f| f.get_content(lookup.context).clone()) .collect(), )) }); arr.map(|c| Constant::unique(lookup.context, c)) } /// Given an environment mapping names to constants, /// attempt to evaluate a typed expression to a constant. fn const_eval_typed_expr( lookup: &mut LookupEnv, known_consts: &mut MappedStack<Ident, Constant>, expr: &ty::TyExpression, ) -> Result<Option<Constant>, ConstEvalError> { if let TypeInfo::ErrorRecovery(_) = &*lookup.engines.te().get(expr.return_type) { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } Ok(match &expr.expression { ty::TyExpressionVariant::ConstGenericExpression { decl, .. } => { assert!(decl.value.is_some()); const_eval_typed_expr(lookup, known_consts, decl.value.as_ref().unwrap())? } ty::TyExpressionVariant::Literal(Literal::Numeric(n)) => { let implied_lit = match &*lookup.engines.te().get(expr.return_type) { TypeInfo::UnsignedInteger(IntegerBits::Eight) => Literal::U8(*n as u8), _ => Literal::U64(*n), }; Some(convert_literal_to_constant(lookup.context, &implied_lit)) } ty::TyExpressionVariant::Literal(l) => Some(convert_literal_to_constant(lookup.context, l)), ty::TyExpressionVariant::FunctionApplication { arguments, fn_ref, call_path, .. } => { let mut actuals_const: Vec<_> = vec![]; for arg in arguments { let (name, sub_expr) = arg; let eval_expr_opt = const_eval_typed_expr(lookup, known_consts, sub_expr)?; if let Some(sub_const) = eval_expr_opt { actuals_const.push((name, sub_const)); } else { // If all actual arguments don't evaluate a constant, bail out. // TODO: Explore if we could continue here and if it'll be useful. return Err(ConstEvalError::CannotBeEvaluatedToConst { span: call_path.span(), }); } } assert!(actuals_const.len() == arguments.len()); for (name, cval) in actuals_const.into_iter() { known_consts.push(name.clone(), cval); } let function_decl = lookup.engines.de().get_function(fn_ref); let res = const_eval_codeblock(lookup, known_consts, &function_decl.body); for (name, _) in arguments { known_consts.pop(name); } res? } ty::TyExpressionVariant::ConstantExpression { decl, .. } => { let call_path = &decl.call_path; let name = &call_path.suffix; match known_consts.get(name) { Some(constant) => Some(*constant), None => (lookup.lookup)(lookup, call_path, &Some(*decl.clone())) .ok() .flatten() .and_then(|v| v.get_constant(lookup.context).cloned()), } } ty::TyExpressionVariant::ConfigurableExpression { span, .. } => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: span.clone() }); } ty::TyExpressionVariant::VariableExpression { name, call_path, .. } => match known_consts.get(name) { // 1. Check if name/call_path is in known_consts. Some(cvs) => Some(*cvs), None => { let call_path = match call_path { Some(call_path) => call_path.clone(), None => CallPath::from(name.clone()), }; // 2. Check if name is a global constant. (lookup.lookup)(lookup, &call_path, &None) .ok() .flatten() .and_then(|v| v.get_constant(lookup.context).cloned()) } }, ty::TyExpressionVariant::StructExpression { fields, instantiation_span, .. } => { let (mut field_types, mut field_vals): (Vec<_>, Vec<_>) = (vec![], vec![]); for field in fields { let ty::TyStructExpressionField { name: _, value, .. } = field; let eval_expr_opt = const_eval_typed_expr(lookup, known_consts, value)?; if let Some(cv) = eval_expr_opt { field_types.push(value.return_type); field_vals.push(cv); } else { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: instantiation_span.clone(), }); } } assert!(field_types.len() == fields.len()); assert!(field_vals.len() == fields.len()); get_struct_for_types( lookup.engines, lookup.context, lookup.md_mgr, lookup.module, &field_types, ) .map_or(None, |struct_ty| { let c = ConstantContent::new_struct( lookup.context, struct_ty.get_field_types(lookup.context), field_vals .iter() .map(|fv| fv.get_content(lookup.context).clone()) .collect(), ); let c = Constant::unique(lookup.context, c); Some(c) }) } ty::TyExpressionVariant::Tuple { fields } => { let (mut field_types, mut field_vals): (Vec<_>, Vec<_>) = (vec![], vec![]); for value in fields { let eval_expr_opt = const_eval_typed_expr(lookup, known_consts, value)?; if let Some(cv) = eval_expr_opt { field_types.push(value.return_type); field_vals.push(cv); } else { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } } assert!(field_types.len() == fields.len()); assert!(field_vals.len() == fields.len()); create_tuple_aggregate( lookup.engines, lookup.context, lookup.md_mgr, lookup.module, &field_types, ) .map_or(None, |tuple_ty| { let c = ConstantContent::new_struct( lookup.context, tuple_ty.get_field_types(lookup.context), field_vals .iter() .map(|fv| fv.get_content(lookup.context).clone()) .collect(), ); let c = Constant::unique(lookup.context, c); Some(c) }) } ty::TyExpressionVariant::ArrayExplicit { elem_type, contents, } => { let (mut element_types, mut element_vals): (Vec<_>, Vec<_>) = (vec![], vec![]); for value in contents { let eval_expr_opt = const_eval_typed_expr(lookup, known_consts, value)?; if let Some(cv) = eval_expr_opt { element_types.push(value.return_type); element_vals.push(cv); } else { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } } assert!(element_types.len() == contents.len()); assert!(element_vals.len() == contents.len()); create_array_from_vec(lookup, *elem_type, element_types, element_vals) } ty::TyExpressionVariant::ArrayRepeat { elem_type, value, length, } => { let constant = const_eval_typed_expr(lookup, known_consts, value)?.unwrap(); let length = const_eval_typed_expr(lookup, known_consts, length)? .unwrap() .get_content(lookup.context) .as_uint() .unwrap() as usize; let element_vals = (0..length).map(|_| constant).collect::<Vec<_>>(); let element_types = (0..length).map(|_| value.return_type).collect::<Vec<_>>(); assert!(element_types.len() == length); assert!(element_vals.len() == length); create_array_from_vec(lookup, *elem_type, element_types, element_vals) } ty::TyExpressionVariant::EnumInstantiation { enum_ref, tag, contents, variant_instantiation_span, .. } => { let enum_decl = lookup.engines.de().get_enum(enum_ref); let aggregate = create_tagged_union_type( lookup.engines, lookup.context, lookup.md_mgr, lookup.module, &enum_decl.variants, ); if let Ok(enum_ty) = aggregate { let tag_value = ConstantContent::new_uint(lookup.context, 64, *tag as u64); let mut fields: Vec<ConstantContent> = vec![tag_value]; match contents { None => fields.push(ConstantContent::new_unit(lookup.context)), Some(subexpr) => match const_eval_typed_expr(lookup, known_consts, subexpr)? { Some(constant) => fields.push(constant.get_content(lookup.context).clone()), None => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: variant_instantiation_span.clone(), }); } }, } let fields_tys = enum_ty.get_field_types(lookup.context); let c = ConstantContent::new_struct(lookup.context, fields_tys, fields); let c = Constant::unique(lookup.context, c); Some(c) } else { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } } ty::TyExpressionVariant::StructFieldAccess { prefix, field_to_access, resolved_type_of_parent, .. } => match const_eval_typed_expr(lookup, known_consts, prefix)? .map(|c| c.get_content(lookup.context).clone()) { Some(ConstantContent { value: ConstantValue::Struct(fields), .. }) => { let field_kind = ty::ProjectionKind::StructField { name: field_to_access.name.clone(), field_to_access: Some(Box::new(field_to_access.clone())), }; get_struct_name_field_index_and_type( lookup.engines.te(), lookup.engines.de(), *resolved_type_of_parent, field_kind, ) .and_then(|(_struct_name, field_idx_and_type_opt)| { field_idx_and_type_opt.map(|(field_idx, _field_type)| field_idx) }) .and_then(|field_idx| { fields .get(field_idx as usize) .cloned() .map(|c| Constant::unique(lookup.context, c)) }) } _ => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } }, ty::TyExpressionVariant::TupleElemAccess { prefix, elem_to_access_num, .. } => match const_eval_typed_expr(lookup, known_consts, prefix)? .map(|c| c.get_content(lookup.context)) { Some(ConstantContent { value: ConstantValue::Struct(fields), .. }) => fields .get(*elem_to_access_num) .cloned() .map(|c| Constant::unique(lookup.context, c)), _ => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } }, ty::TyExpressionVariant::ImplicitReturn(e) => { if let Ok(Some(constant)) = const_eval_typed_expr(lookup, known_consts, e) { Some(constant) } else { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: e.span.clone(), }); } } // we could allow non-local control flow in pure functions, but it would // require some more work and at this point it's not clear if it is too useful // for constant initializers -- the user can always refactor their pure functions // to not use the return statement ty::TyExpressionVariant::Return(exp) => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: exp.span.clone(), }); } ty::TyExpressionVariant::Panic(exp) => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: exp.span.clone(), }); } ty::TyExpressionVariant::MatchExp { desugared, .. } => { const_eval_typed_expr(lookup, known_consts, desugared)? } ty::TyExpressionVariant::IntrinsicFunction(kind) => { const_eval_intrinsic(lookup, known_consts, kind)? } ty::TyExpressionVariant::IfExp { condition, then, r#else, } => { match const_eval_typed_expr(lookup, known_consts, condition)? .map(|c| c.get_content(lookup.context)) { Some(ConstantContent { value: ConstantValue::Bool(cond), .. }) => { if *cond { const_eval_typed_expr(lookup, known_consts, then)? } else if let Some(r#else) = r#else { const_eval_typed_expr(lookup, known_consts, r#else)? } else { // missing 'else' branch: // we probably don't really care about evaluating // const expressions of the unit type None } } _ => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } } } ty::TyExpressionVariant::CodeBlock(codeblock) => { const_eval_codeblock(lookup, known_consts, codeblock)? } ty::TyExpressionVariant::ArrayIndex { prefix, index } => { let prefix = const_eval_typed_expr(lookup, known_consts, prefix)? .map(|c| c.get_content(lookup.context).clone()); let index = const_eval_typed_expr(lookup, known_consts, index)? .map(|c| c.get_content(lookup.context)); match (prefix, index) { ( Some(ConstantContent { value: ConstantValue::Array(items), .. }), Some(ConstantContent { value: ConstantValue::Uint(index), .. }), ) => { let count = items.len() as u64; if *index < count { let c = Constant::unique(lookup.context, items[*index as usize].clone()); Some(c) } else { return Err(ConstEvalError::CompileError); } } _ => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } } } ty::TyExpressionVariant::Ref(_) => { return Err(ConstEvalError::CompileError); } // We support *__elem_at(...) ty::TyExpressionVariant::Deref(expr) => { let value = expr .as_intrinsic() .filter(|x| matches!(x.kind, Intrinsic::ElemAt)) .ok_or(ConstEvalError::CompileError) .and_then(|kind| { const_eval_intrinsic(lookup, known_consts, kind) .map(|c| c.map(|c| c.get_content(lookup.context).clone())) }); if let Ok(Some(ConstantContent { value: ConstantValue::Reference(value), .. })) = value { let c = Constant::unique(lookup.context, *value.clone()); Some(c) } else { return Err(ConstEvalError::CompileError); } } ty::TyExpressionVariant::EnumTag { exp } => { let value = const_eval_typed_expr(lookup, known_consts, exp)? .map(|x| x.get_content(lookup.context).value.clone()); if let Some(ConstantValue::Struct(fields)) = value { Some(Constant::unique(lookup.context, fields[0].clone())) } else { return Err(ConstEvalError::CompileError); } } ty::TyExpressionVariant::UnsafeDowncast { exp, .. } => { let value = const_eval_typed_expr(lookup, known_consts, exp)? .map(|x| x.get_content(lookup.context).value.clone()); if let Some(ConstantValue::Struct(fields)) = value { Some(Constant::unique(lookup.context, fields[1].clone())) } else { return Err(ConstEvalError::CompileError); } } ty::TyExpressionVariant::WhileLoop { condition, body, .. } => { // Arbitrary limit of iterations to avoid infinite loops like // while true {} let mut limit = 1_000_000; while limit >= 0 { limit -= 1; let condition = const_eval_typed_expr(lookup, known_consts, condition)?; match condition.map(|x| x.get_content(lookup.context).value.clone()) { Some(ConstantValue::Bool(true)) => { // Break and continue are not implemented, so there is need for flow control here let _ = const_eval_codeblock(lookup, known_consts, body)?; } _ => break, } } None } ty::TyExpressionVariant::Reassignment(r) => { let rhs = const_eval_typed_expr(lookup, known_consts, &r.rhs)?.unwrap(); match &r.lhs { ty::TyReassignmentTarget::ElementAccess { base_name, indices, .. } => { if !indices.is_empty() { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } if let Some(lhs) = known_consts.get_mut(base_name) { *lhs = rhs; return Ok(None); } else { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } } ty::TyReassignmentTarget::DerefAccess { .. } => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } } } ty::TyExpressionVariant::FunctionParameter | ty::TyExpressionVariant::AsmExpression { .. } | ty::TyExpressionVariant::LazyOperator { .. } | ty::TyExpressionVariant::AbiCast { .. } | ty::TyExpressionVariant::StorageAccess(_) | ty::TyExpressionVariant::AbiName(_) | ty::TyExpressionVariant::Break | ty::TyExpressionVariant::Continue | ty::TyExpressionVariant::ForLoop { .. } => { return Err(ConstEvalError::CannotBeEvaluatedToConst { span: expr.span.clone(), }); } }) } // the (constant) value of a codeblock is essentially it's last expression if there is one // or if it makes sense as the last expression, e.g. a dangling let-expression in a codeblock // would be an evaluation error fn const_eval_codeblock( lookup: &mut LookupEnv, known_consts: &mut MappedStack<Ident, Constant>, codeblock: &ty::TyCodeBlock, ) -> Result<Option<Constant>, ConstEvalError> { // the current result let mut result: Result<Option<Constant>, ConstEvalError> = Ok(None); // keep track of new bindings for this codeblock let mut bindings: Vec<_> = vec![]; for ast_node in &codeblock.contents { result = match &ast_node.content { ty::TyAstNodeContent::Declaration(decl @ ty::TyDecl::VariableDecl(var_decl)) => { if let Ok(Some(rhs)) = const_eval_typed_expr(lookup, known_consts, &var_decl.body) { known_consts.push(var_decl.name.clone(), rhs); bindings.push(var_decl.name.clone()); Ok(None) } else { Err(ConstEvalError::CannotBeEvaluatedToConst { span: decl.span(lookup.engines).clone(), }) } } ty::TyAstNodeContent::Declaration(ty::TyDecl::ConstantDecl(const_decl)) => { let ty_const_decl = lookup.engines.de().get_constant(&const_decl.decl_id); if let Some(constant) = ty_const_decl .value .clone() .and_then(|expr| const_eval_typed_expr(lookup, known_consts, &expr).ok()) .flatten() { known_consts.push(ty_const_decl.name().clone(), constant); bindings.push(ty_const_decl.name().clone()); Ok(None) } else { Err(ConstEvalError::CannotBeEvaluatedToConst { span: ty_const_decl.span.clone(), }) } } ty::TyAstNodeContent::Declaration(_) => Ok(None), ty::TyAstNodeContent::Expression(e) => match e.expression { ty::TyExpressionVariant::ImplicitReturn(_) => {
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/ir_generation/purity.rs
sway-core/src/ir_generation/purity.rs
use crate::{ language::{ promote_purity, Purity::{self, *}, }, metadata::MetadataManager, }; use sway_error::{error::CompileError, handler::Handler}; use sway_error::{ error::StorageAccess, warning::{CompileWarning, Warning}, }; use sway_ir::{Context, FuelVmInstruction, Function, InstOp}; use sway_types::span::Span; use std::collections::HashMap; #[derive(Default)] pub(crate) struct PurityEnv { memos: HashMap<Function, (bool, bool)>, } /// Analyses purity annotations on functions. /// /// Designed to be called for each entry point, _prior_ to inlining or other optimizations. /// The checker will check this function and any that it calls. /// /// Returns bools for whether it (reads, writes). pub(crate) fn check_function_purity( handler: &Handler, env: &mut PurityEnv, context: &Context, md_mgr: &mut MetadataManager, function: &Function, ) -> (bool, bool) { // Iterate for each instruction in the function and gather whether we have read and/or // write storage operations: // - via the storage IR instructions, // - via ASM blocks with storage VM instructions, or // - via calls into functions with the above. let attributed_purity = md_mgr.md_to_purity(context, function.get_metadata(context)); let mut storage_access_violations = vec![]; let (reads, writes) = function.instruction_iter(context).fold( (false, false), |(reads, writes), (_block, ins_value)| { ins_value .get_instruction(context) .map(|instruction| { match &instruction.op { InstOp::FuelVm(inst) if is_store_access_fuel_vm_instruction(inst) => { let storage_access = store_access_fuel_vm_instruction_to_storage_access(inst); if violates_purity(&storage_access, &attributed_purity) { // When compiling Sway code, the only way to get FuelVM store access instructions in the IR // is via store access intrinsics. So we know that the span stored in the metadata will be // the intrinsic's call span which is suitable for error reporting. let intrinsic_call_span = md_mgr.md_to_span(context, ins_value.get_metadata(context)).unwrap_or(Span::dummy()); storage_access_violations.push((intrinsic_call_span, storage_access)); } match inst { FuelVmInstruction::StateLoadQuadWord { .. } | FuelVmInstruction::StateLoadWord(_) => (true, writes), FuelVmInstruction::StateClear { .. } | FuelVmInstruction::StateStoreQuadWord { .. } | FuelVmInstruction::StateStoreWord { .. } => (reads, true), _ => unreachable!("The FuelVM instruction is checked to be a store access instruction."), } } // Iterate for and check each instruction in the ASM block. InstOp::AsmBlock(asm_block, _args) => asm_block.body.iter().fold( (reads, writes), |(reads, writes), asm_op| { let inst = asm_op.op_name.as_str(); if is_store_access_asm_instruction(inst) { let storage_access = store_access_asm_instruction_to_storage_access(inst); if violates_purity(&storage_access, &attributed_purity) { let asm_inst_span = md_mgr.md_to_span(context, asm_op.metadata).unwrap_or(Span::dummy()); storage_access_violations.push((asm_inst_span, storage_access)); } match inst { "srw" | "srwq" => (true, writes), "scwq" | "sww" | "swwq" => (reads, true), _ => unreachable!("The ASM instruction is checked to be a store access instruction."), } } else { (reads, writes) } } ), // Recurse to find the called function purity. Use memoisation to // avoid redoing work. InstOp::Call(callee, _args) => { let (callee_reads, callee_writes) = env.memos.get(callee).copied().unwrap_or_else(|| { let r_w = check_function_purity( handler, env, context, md_mgr, callee, ); env.memos.insert(*callee, r_w); r_w }); if callee_reads || callee_writes { let callee_span = md_mgr.md_to_fn_call_path_span(context, ins_value.get_metadata(context)).unwrap_or(Span::dummy()); let storage_access = StorageAccess::ImpureFunctionCall(callee_span.clone(), callee_reads, callee_writes); if violates_purity(&storage_access, &attributed_purity) { storage_access_violations.push((callee_span, storage_access)); } } (reads || callee_reads, writes || callee_writes) } _otherwise => (reads, writes), } }) .unwrap_or_else(|| (reads, writes)) }, ); // Simple closures for each of the error types. let error = |span: Span, needed| { // We don't emit errors on the generated `__entry` function // but do on the original entry functions and all other functions. if !function.is_entry(context) || function.is_original_entry(context) { handler.emit_err(CompileError::StorageAccessMismatched { span, is_pure: matches!(attributed_purity, Pure), suggested_attributes: promote_purity(attributed_purity, needed) .to_attribute_syntax(), storage_access_violations, }); } }; let warn = |span, purity: Purity| { // Do not warn on generated code if span != Span::dummy() { handler.emit_warn(CompileWarning { warning_content: Warning::DeadStorageDeclarationForFunction { unneeded_attrib: purity.to_attribute_syntax(), }, span, }); } }; let span = md_mgr .md_to_fn_name_span(context, function.get_metadata(context)) .unwrap_or_else(Span::dummy); match (attributed_purity, reads, writes) { // Has no attributes but needs some. (Pure, true, false) => error(span, Reads), (Pure, false, true) => error(span, Writes), (Pure, true, true) => error(span, ReadsWrites), // Or the attribute must match the behavior. (Reads, _, true) => error(span, Writes), // Or we have unneeded attributes. (ReadsWrites, false, true) => warn(span, Reads), (ReadsWrites, true, false) => warn(span, Writes), (ReadsWrites, false, false) => warn(span, ReadsWrites), (Reads, false, false) => warn(span, Reads), (Writes, _, false) => warn(span, Writes), // Attributes and effects are in total agreement. (Pure, false, false) | (Reads, true, false) | (Writes, _, true) // storage(write) allows reading as well | (ReadsWrites, true, true) => (), }; (reads, writes) } fn is_store_access_fuel_vm_instruction(inst: &FuelVmInstruction) -> bool { matches!( inst, FuelVmInstruction::StateLoadWord(_) | FuelVmInstruction::StateLoadQuadWord { .. } | FuelVmInstruction::StateClear { .. } | FuelVmInstruction::StateStoreWord { .. } | FuelVmInstruction::StateStoreQuadWord { .. } ) } fn store_access_fuel_vm_instruction_to_storage_access(inst: &FuelVmInstruction) -> StorageAccess { match inst { FuelVmInstruction::StateLoadWord(_) => StorageAccess::ReadWord, FuelVmInstruction::StateLoadQuadWord { .. } => StorageAccess::ReadSlots, FuelVmInstruction::StateClear { .. } => StorageAccess::Clear, FuelVmInstruction::StateStoreWord { .. } => StorageAccess::WriteWord, FuelVmInstruction::StateStoreQuadWord { .. } => StorageAccess::WriteSlots, _ => panic!("The FuelVM instruction is not a store access instruction."), } } fn is_store_access_asm_instruction(inst: &str) -> bool { matches!(inst, "srw" | "srwq" | "scwq" | "sww" | "swwq") } fn store_access_asm_instruction_to_storage_access(inst: &str) -> StorageAccess { match inst { "srw" => StorageAccess::ReadWord, "srwq" => StorageAccess::ReadSlots, "scwq" => StorageAccess::Clear, "sww" => StorageAccess::WriteWord, "swwq" => StorageAccess::WriteSlots, _ => panic!("The ASM instruction \"{inst}\" is not a store access instruction."), } } /// Returns true if the `storage_access` violates the given expected `purity`. fn violates_purity(storage_access: &StorageAccess, purity: &Purity) -> bool { match purity { Pure => true, Reads => storage_access.is_write(), Writes => false, ReadsWrites => false, } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/debug_generation/dwarf.rs
sway-core/src/debug_generation/dwarf.rs
use std::fs::File; use std::os::unix::ffi::OsStringExt; use std::path::Path; use gimli::write::{ self, DebugLine, DebugLineStrOffsets, DebugStrOffsets, DwarfUnit, EndianVec, LineProgram, LineString, }; use gimli::{BigEndian, Encoding, LineEncoding}; use sway_error::error::CompileError; use sway_types::Span; use crate::source_map::SourceMap; use object::write::Object; pub fn write_dwarf( source_map: &SourceMap, primary_dir: &Path, primary_src: &Path, out_file: &Path, ) -> Result<(), CompileError> { let encoding = gimli::Encoding { format: gimli::Format::Dwarf64, version: 5, address_size: 8, }; let program = build_line_number_program(encoding, primary_dir, primary_src, source_map)?; program .write( &mut DebugLine::from(EndianVec::new(BigEndian)), encoding, &DebugLineStrOffsets::none(), &DebugStrOffsets::none(), ) .map_err(|err| { sway_error::error::CompileError::InternalOwned(err.to_string(), Span::dummy()) })?; let mut dwarf = DwarfUnit::new(encoding); dwarf.unit.line_program = program; // Write to new sections let mut debug_sections = write::Sections::new(EndianVec::new(BigEndian)); dwarf.write(&mut debug_sections).map_err(|err| { sway_error::error::CompileError::InternalOwned(err.to_string(), Span::dummy()) })?; // Create parent directories if they don't exist if let Some(parent) = out_file.parent() { std::fs::create_dir_all(parent).map_err(|err| { sway_error::error::CompileError::InternalOwned(err.to_string(), Span::dummy()) })?; } let file = File::create(out_file).map_err(|err| { sway_error::error::CompileError::InternalOwned(err.to_string(), Span::dummy()) })?; let mut obj = Object::new( object::BinaryFormat::Elf, object::Architecture::X86_64, object::Endianness::Big, ); debug_sections .for_each(|section_id, data| { let sec = obj.add_section( [].into(), section_id.name().into(), object::SectionKind::Other, ); obj.set_section_data(sec, data.clone().into_vec(), 8); Ok::<(), ()>(()) }) .unwrap(); obj.write_stream(file).map_err(|err| { sway_error::error::CompileError::InternalOwned(err.to_string(), Span::dummy()) })?; Ok(()) } fn build_line_number_program( encoding: Encoding, primary_dir: &Path, primary_src: &Path, source_map: &SourceMap, ) -> Result<LineProgram, CompileError> { let primary_src = primary_src.strip_prefix(primary_dir).map_err(|err| { sway_error::error::CompileError::InternalOwned(err.to_string(), Span::dummy()) })?; let mut program = LineProgram::new( encoding, LineEncoding::default(), LineString::String(primary_dir.to_path_buf().into_os_string().into_vec()), LineString::String(primary_src.to_path_buf().into_os_string().into_vec()), None, ); program.begin_sequence(Some(write::Address::Constant(0))); for (ix, span) in &source_map.map { let (path, span) = span.to_span(&source_map.paths, &source_map.dependency_paths); let dir = path .parent() .ok_or(sway_error::error::CompileError::InternalOwned( "Path doesn't have a proper prefix".to_string(), Span::dummy(), ))?; let file = path .file_name() .ok_or(sway_error::error::CompileError::InternalOwned( "Path doesn't have proper filename".to_string(), Span::dummy(), ))?; let dir_id = program.add_directory(LineString::String( dir.as_os_str().as_encoded_bytes().into(), )); let file_id = program.add_file( LineString::String(file.as_encoded_bytes().into()), dir_id, None, ); program.generate_row(); let current_row = program.row(); current_row.line = span.start.line as u64; current_row.column = span.start.col as u64; current_row.address_offset = *ix as u64; current_row.file = file_id; } program.end_sequence( source_map .map .last_key_value() .map(|(key, _)| *key) .unwrap_or_default() as u64 + 1, ); Ok(program) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/debug_generation/mod.rs
sway-core/src/debug_generation/mod.rs
pub mod dwarf; pub use dwarf::*;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/mapping.rs
sway-core/src/decl_engine/mapping.rs
use std::{collections::HashSet, fmt}; use sway_error::handler::{ErrorEmitted, Handler}; use crate::{ engine_threading::DebugWithEngines, language::ty::{TyTraitInterfaceItem, TyTraitItem}, Engines, TypeId, UnifyCheck, }; use super::{AssociatedItemDeclId, InterfaceItemMap, ItemMap}; type SourceDecl = (AssociatedItemDeclId, TypeId); type DestinationDecl = AssociatedItemDeclId; /// The [DeclMapping] is used to create a mapping between a [SourceDecl] (LHS) /// and a [DestinationDecl] (RHS). #[derive(Clone)] pub struct DeclMapping { pub mapping: Vec<(SourceDecl, DestinationDecl)>, } impl fmt::Display for DeclMapping { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DeclMapping {{ {} }}", self.mapping .iter() .map(|(source_type, dest_type)| { format!( "{} -> {}", source_type.0, match dest_type { AssociatedItemDeclId::TraitFn(decl_id) => decl_id.inner(), AssociatedItemDeclId::Function(decl_id) => decl_id.inner(), AssociatedItemDeclId::Constant(decl_id) => decl_id.inner(), AssociatedItemDeclId::Type(decl_id) => decl_id.inner(), } ) }) .collect::<Vec<_>>() .join(", ") ) } } impl fmt::Debug for DeclMapping { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DeclMapping {{ {} }}", self.mapping .iter() .map(|(source_type, dest_type)| { format!("{source_type:?} -> {dest_type:?}") }) .collect::<Vec<_>>() .join(", ") ) } } impl DebugWithEngines for DeclMapping { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { f.write_str("DeclMapping ").unwrap(); let mut map = f.debug_map(); for (source_type, dest_type) in self.mapping.iter() { let key = engines.help_out(source_type.0.clone()); let value = engines.help_out(dest_type); map.entry(&key, &value); } map.finish() } } impl DeclMapping { pub(crate) fn is_empty(&self) -> bool { self.mapping.is_empty() } pub(crate) fn extend(&mut self, other: &DeclMapping) { self.mapping.extend(other.mapping.clone()); } pub(crate) fn from_interface_and_item_and_impld_decl_refs( interface_decl_refs: InterfaceItemMap, item_decl_refs: ItemMap, impld_decl_refs: ItemMap, ) -> DeclMapping { let mut mapping: Vec<(SourceDecl, DestinationDecl)> = vec![]; for (interface_decl_name, interface_item) in interface_decl_refs.into_iter() { if let Some(new_item) = impld_decl_refs.get(&interface_decl_name) { let interface_decl_ref = match interface_item { TyTraitInterfaceItem::TraitFn(decl_ref) => { (decl_ref.id().into(), interface_decl_name.1) } TyTraitInterfaceItem::Constant(decl_ref) => { (decl_ref.id().into(), interface_decl_name.1) } TyTraitInterfaceItem::Type(decl_ref) => { (decl_ref.id().into(), interface_decl_name.1) } }; let new_decl_ref = match new_item { TyTraitItem::Fn(decl_ref) => decl_ref.id().into(), TyTraitItem::Constant(decl_ref) => decl_ref.id().into(), TyTraitItem::Type(decl_ref) => decl_ref.id().into(), }; mapping.push((interface_decl_ref, new_decl_ref)); } } for (decl_name, item) in item_decl_refs.into_iter() { if let Some(new_item) = impld_decl_refs.get(&decl_name) { let interface_decl_ref = match item { TyTraitItem::Fn(decl_ref) => (decl_ref.id().into(), decl_name.1), TyTraitItem::Constant(decl_ref) => (decl_ref.id().into(), decl_name.1), TyTraitItem::Type(decl_ref) => (decl_ref.id().into(), decl_name.1), }; let new_decl_ref = match new_item { TyTraitItem::Fn(decl_ref) => decl_ref.id().into(), TyTraitItem::Constant(decl_ref) => decl_ref.id().into(), TyTraitItem::Type(decl_ref) => decl_ref.id().into(), }; mapping.push((interface_decl_ref, new_decl_ref)); } } DeclMapping { mapping } } pub(crate) fn find_match( &self, _handler: &Handler, engines: &Engines, decl_ref: AssociatedItemDeclId, typeid: Option<TypeId>, self_typeid: Option<TypeId>, ) -> Result<Option<DestinationDecl>, ErrorEmitted> { let mut dest_decl_refs = HashSet::<DestinationDecl>::new(); if let Some(mut typeid) = typeid { if let Some(self_ty) = self_typeid { if engines.te().get(typeid).is_self_type() { // If typeid is `Self`, then we use the self_typeid instead. typeid = self_ty; } } for (source_decl_ref, dest_decl_ref) in self.mapping.iter() { let unify_check = UnifyCheck::non_dynamic_equality(engines); if source_decl_ref.0 == decl_ref && unify_check.check(source_decl_ref.1, typeid) { dest_decl_refs.insert(dest_decl_ref.clone()); } } } // At most one replacement should be found for decl_ref. /* TODO uncomment this and close issue #5540 if dest_decl_refs.len() > 1 { handler.emit_err(CompileError::InternalOwned( format!( "Multiple replacements for decl {} implemented in {}", engines.help_out(decl_ref), engines.help_out(typeid), ), dest_decl_refs.iter().last().unwrap().span(engines), )); }*/ Ok(dest_decl_refs.iter().next().cloned()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/ref.rs
sway-core/src/decl_engine/ref.rs
//! Represents the use of / syntactic reference to a declaration. //! //! ### Is a [DeclRef] effectively the same as a [DeclId]? //! //! A [DeclRef] is a smart wrapper around a [DeclId] and canonically represents //! the use / syntactic reference to a declaration. This does not include the //! syntactic locations for where declarations are declared though. For example, //! function declaration `fn my_function() { .. }` would just create a [DeclId], //! while function application `my_function()` would create a [DeclRef]. //! //! [DeclRef] contains a [DeclId] field `id`, as well as some additional helpful //! information. These additional fields include an [Ident] for the declaration //! `name` and a [Span] for the declaration `decl_span`. Note, `name` and //! `decl_span` can also be found by using `id` to get the declaration itself //! from the [DeclEngine]. But the [DeclRef] type allows Sway compiler writers //! to reduce unnecessary lookups into the [DeclEngine] when only the `name` or //! `decl_span` is desired. //! //! It is recommend to use [DeclId] for cases like function declaration //! `fn my_function() { .. }`, and to use [DeclRef] for cases like function //! application `my_function()`. use crate::{ decl_engine::*, engine_threading::*, language::ty::{ self, TyAbiDecl, TyConstantDecl, TyDeclParsedType, TyEnumDecl, TyFunctionDecl, TyImplSelfOrTrait, TyStorageDecl, TyStructDecl, TyTraitDecl, TyTraitFn, TyTraitType, }, semantic_analysis::TypeCheckContext, type_system::*, }; use serde::{Deserialize, Serialize}; use std::hash::{Hash, Hasher}; use sway_error::handler::{ErrorEmitted, Handler}; use sway_types::{Ident, Named, Span, Spanned}; pub type DeclRefFunction = DeclRef<DeclId<TyFunctionDecl>>; pub type DeclRefTrait = DeclRef<DeclId<TyTraitDecl>>; pub type DeclRefTraitFn = DeclRef<DeclId<TyTraitFn>>; pub type DeclRefTraitType = DeclRef<DeclId<TyTraitType>>; pub type DeclRefImplTrait = DeclRef<DeclId<TyImplSelfOrTrait>>; pub type DeclRefStruct = DeclRef<DeclId<TyStructDecl>>; pub type DeclRefStorage = DeclRef<DeclId<TyStorageDecl>>; pub type DeclRefAbi = DeclRef<DeclId<TyAbiDecl>>; pub type DeclRefConstant = DeclRef<DeclId<TyConstantDecl>>; pub type DeclRefEnum = DeclRef<DeclId<TyEnumDecl>>; pub type DeclRefMixedFunctional = DeclRef<AssociatedItemDeclId>; pub type DeclRefMixedInterface = DeclRef<InterfaceDeclId>; /// Represents the use of / syntactic reference to a declaration. A /// smart-wrapper around a [DeclId], containing additional information about a /// declaration. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DeclRef<I> { /// The name of the declaration. // NOTE: In the case of storage, the name is "storage". name: Ident, /// The index into the [DeclEngine]. id: I, /// The [Span] of the entire declaration. decl_span: Span, } impl<I> DeclRef<I> { pub(crate) fn new(name: Ident, id: I, decl_span: Span) -> Self { DeclRef { name, id, decl_span, } } pub fn name(&self) -> &Ident { &self.name } pub fn id(&self) -> &I { &self.id } pub fn decl_span(&self) -> &Span { &self.decl_span } } impl<T> DeclRef<DeclId<T>> { pub(crate) fn replace_id(&mut self, index: DeclId<T>) { self.id.replace_id(index); } } impl<T> DeclRef<DeclId<T>> where DeclEngine: DeclEngineIndex<T> + DeclEngineInsert<T> + DeclEngineGetParsedDeclId<T>, T: Named + Spanned + IsConcrete + SubstTypes + Clone + TyDeclParsedType, { pub(crate) fn subst_types_and_insert_new(&self, ctx: &SubstTypesContext) -> Option<Self> { let decl_engine = ctx.engines.de(); if ctx .type_subst_map .is_some_and(|tsm| tsm.source_ids_contains_concrete_type(ctx.engines)) || !decl_engine .get(&self.id) .is_concrete(ctx.handler, ctx.engines) { let mut decl = (*decl_engine.get(&self.id)).clone(); if decl.subst(ctx).has_changes() { Some(decl_engine.insert(decl, decl_engine.get_parsed_decl_id(&self.id).as_ref())) } else { None } } else { None } } } impl<T> DeclRef<DeclId<T>> where AssociatedItemDeclId: From<DeclId<T>>, { pub(crate) fn with_parent( self, decl_engine: &DeclEngine, parent: AssociatedItemDeclId, ) -> Self { let id: DeclId<T> = self.id; decl_engine.register_parent(id.into(), parent); self } } impl<T> DeclRef<DeclId<T>> where AssociatedItemDeclId: From<DeclId<T>>, DeclEngine: DeclEngineIndex<T> + DeclEngineInsert<T> + DeclEngineGetParsedDeclId<T>, T: Named + Spanned + IsConcrete + SubstTypes + Clone + TyDeclParsedType, { pub(crate) fn subst_types_and_insert_new_with_parent( &self, ctx: &SubstTypesContext, ) -> Option<Self> { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(&self.id)).clone(); if decl.subst(ctx).has_changes() { Some( decl_engine .insert(decl, decl_engine.get_parsed_decl_id(&self.id).as_ref()) .with_parent(decl_engine, self.id.into()), ) } else { None } } } impl<T> EqWithEngines for DeclRef<DeclId<T>> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + PartialEqWithEngines + EqWithEngines, { } impl<T> PartialEqWithEngines for DeclRef<DeclId<T>> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + PartialEqWithEngines, { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { let decl_engine = ctx.engines().de(); let DeclRef { name: ln, id: lid, // these fields are not used in comparison because they aren't // relevant/a reliable source of obj v. obj distinction decl_span: _, // temporarily omitted } = self; let DeclRef { name: rn, id: rid, // these fields are not used in comparison because they aren't // relevant/a reliable source of obj v. obj distinction decl_span: _, // temporarily omitted } = other; ln == rn && decl_engine.get(lid).eq(&decl_engine.get(rid), ctx) } } impl<T> HashWithEngines for DeclRef<DeclId<T>> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + HashWithEngines, { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { let decl_engine = engines.de(); let DeclRef { name, id, // these fields are not hashed because they aren't relevant/a // reliable source of obj v. obj distinction decl_span: _, } = self; name.hash(state); decl_engine.get(id).hash(state, engines); } } impl EqWithEngines for DeclRefMixedInterface {} impl PartialEqWithEngines for DeclRefMixedInterface { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { let decl_engine = ctx.engines().de(); match (&self.id, &other.id) { (InterfaceDeclId::Abi(self_id), InterfaceDeclId::Abi(other_id)) => { let left = decl_engine.get(self_id); let right = decl_engine.get(other_id); self.name == other.name && left.eq(&right, ctx) } (InterfaceDeclId::Trait(self_id), InterfaceDeclId::Trait(other_id)) => { let left = decl_engine.get(self_id); let right = decl_engine.get(other_id); self.name == other.name && left.eq(&right, ctx) } _ => false, } } } impl HashWithEngines for DeclRefMixedInterface { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { match self.id { InterfaceDeclId::Abi(id) => { state.write_u8(0); let decl_engine = engines.de(); let decl = decl_engine.get(&id); decl.hash(state, engines); } InterfaceDeclId::Trait(id) => { state.write_u8(1); let decl_engine = engines.de(); let decl = decl_engine.get(&id); decl.hash(state, engines); } } } } impl<I> Spanned for DeclRef<I> { fn span(&self) -> Span { self.decl_span.clone() } } impl<T> SubstTypes for DeclRef<DeclId<T>> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + SubstTypes + Clone, { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(&self.id)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(self.id, decl); HasChanges::Yes } else { HasChanges::No } } } impl ReplaceDecls for DeclRefFunction { fn replace_decls_inner( &mut self, decl_mapping: &DeclMapping, handler: &Handler, ctx: &mut TypeCheckContext, ) -> Result<bool, ErrorEmitted> { let engines = ctx.engines(); let decl_engine = engines.de(); let func = decl_engine.get(self); if let Some(new_decl_ref) = decl_mapping.find_match( handler, ctx.engines(), self.id.into(), func.implementing_for, ctx.self_type(), )? { return Ok( if let AssociatedItemDeclId::Function(new_decl_ref) = new_decl_ref { self.id = new_decl_ref; true } else { false }, ); } let all_parents = decl_engine.find_all_parents(engines, &self.id); for parent in all_parents.iter() { if let Some(new_decl_ref) = decl_mapping.find_match( handler, ctx.engines(), parent.clone(), func.implementing_for, ctx.self_type(), )? { return Ok( if let AssociatedItemDeclId::Function(new_decl_ref) = new_decl_ref { self.id = new_decl_ref; true } else { false }, ); } } Ok(false) } } impl ReplaceFunctionImplementingType for DeclRefFunction { fn replace_implementing_type(&mut self, engines: &Engines, implementing_type: ty::TyDecl) { let decl_engine = engines.de(); let mut decl = (*decl_engine.get(&self.id)).clone(); decl.set_implementing_type(implementing_type); decl_engine.replace(self.id, decl); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/engine.rs
sway-core/src/decl_engine/engine.rs
use parking_lot::RwLock; use std::{ collections::{HashMap, HashSet, VecDeque}, fmt::Write, sync::Arc, }; use sway_types::{Named, ProgramId, SourceId, Spanned}; use crate::{ concurrent_slab::ConcurrentSlab, decl_engine::{parsed_id::ParsedDeclId, *}, engine_threading::*, language::{ parsed::{ AbiDeclaration, ConfigurableDeclaration, ConstGenericDeclaration, ConstantDeclaration, Declaration, EnumDeclaration, FunctionDeclaration, ImplSelfOrTrait, StorageDeclaration, StructDeclaration, TraitDeclaration, TraitFn, TraitTypeDeclaration, TypeAliasDeclaration, }, ty::{ self, TyAbiDecl, TyConfigurableDecl, TyConstGenericDecl, TyConstantDecl, TyDeclParsedType, TyEnumDecl, TyFunctionDecl, TyImplSelfOrTrait, TyStorageDecl, TyStructDecl, TyTraitDecl, TyTraitFn, TyTraitType, TyTypeAliasDecl, }, }, }; /// Used inside of type inference to store declarations. #[derive(Debug, Default)] pub struct DeclEngine { function_slab: ConcurrentSlab<TyFunctionDecl>, trait_slab: ConcurrentSlab<TyTraitDecl>, trait_fn_slab: ConcurrentSlab<TyTraitFn>, trait_type_slab: ConcurrentSlab<TyTraitType>, impl_self_or_trait_slab: ConcurrentSlab<TyImplSelfOrTrait>, struct_slab: ConcurrentSlab<TyStructDecl>, storage_slab: ConcurrentSlab<TyStorageDecl>, abi_slab: ConcurrentSlab<TyAbiDecl>, constant_slab: ConcurrentSlab<TyConstantDecl>, configurable_slab: ConcurrentSlab<TyConfigurableDecl>, const_generics_slab: ConcurrentSlab<TyConstGenericDecl>, enum_slab: ConcurrentSlab<TyEnumDecl>, type_alias_slab: ConcurrentSlab<TyTypeAliasDecl>, function_parsed_decl_id_map: RwLock<HashMap<DeclId<TyFunctionDecl>, ParsedDeclId<FunctionDeclaration>>>, trait_parsed_decl_id_map: RwLock<HashMap<DeclId<TyTraitDecl>, ParsedDeclId<TraitDeclaration>>>, trait_fn_parsed_decl_id_map: RwLock<HashMap<DeclId<TyTraitFn>, ParsedDeclId<TraitFn>>>, trait_type_parsed_decl_id_map: RwLock<HashMap<DeclId<TyTraitType>, ParsedDeclId<TraitTypeDeclaration>>>, impl_self_or_trait_parsed_decl_id_map: RwLock<HashMap<DeclId<TyImplSelfOrTrait>, ParsedDeclId<ImplSelfOrTrait>>>, struct_parsed_decl_id_map: RwLock<HashMap<DeclId<TyStructDecl>, ParsedDeclId<StructDeclaration>>>, storage_parsed_decl_id_map: RwLock<HashMap<DeclId<TyStorageDecl>, ParsedDeclId<StorageDeclaration>>>, abi_parsed_decl_id_map: RwLock<HashMap<DeclId<TyAbiDecl>, ParsedDeclId<AbiDeclaration>>>, constant_parsed_decl_id_map: RwLock<HashMap<DeclId<TyConstantDecl>, ParsedDeclId<ConstantDeclaration>>>, const_generic_parsed_decl_id_map: RwLock<HashMap<DeclId<TyConstGenericDecl>, ParsedDeclId<ConstGenericDeclaration>>>, configurable_parsed_decl_id_map: RwLock<HashMap<DeclId<TyConfigurableDecl>, ParsedDeclId<ConfigurableDeclaration>>>, const_generics_parsed_decl_id_map: RwLock<HashMap<DeclId<TyConstGenericDecl>, ParsedDeclId<ConstGenericDeclaration>>>, enum_parsed_decl_id_map: RwLock<HashMap<DeclId<TyEnumDecl>, ParsedDeclId<EnumDeclaration>>>, type_alias_parsed_decl_id_map: RwLock<HashMap<DeclId<TyTypeAliasDecl>, ParsedDeclId<TypeAliasDeclaration>>>, parents: RwLock<HashMap<AssociatedItemDeclId, Vec<AssociatedItemDeclId>>>, } impl Clone for DeclEngine { fn clone(&self) -> Self { DeclEngine { function_slab: self.function_slab.clone(), trait_slab: self.trait_slab.clone(), trait_fn_slab: self.trait_fn_slab.clone(), trait_type_slab: self.trait_type_slab.clone(), impl_self_or_trait_slab: self.impl_self_or_trait_slab.clone(), struct_slab: self.struct_slab.clone(), storage_slab: self.storage_slab.clone(), abi_slab: self.abi_slab.clone(), constant_slab: self.constant_slab.clone(), configurable_slab: self.configurable_slab.clone(), const_generics_slab: self.const_generics_slab.clone(), enum_slab: self.enum_slab.clone(), type_alias_slab: self.type_alias_slab.clone(), function_parsed_decl_id_map: RwLock::new( self.function_parsed_decl_id_map.read().clone(), ), trait_parsed_decl_id_map: RwLock::new(self.trait_parsed_decl_id_map.read().clone()), trait_fn_parsed_decl_id_map: RwLock::new( self.trait_fn_parsed_decl_id_map.read().clone(), ), trait_type_parsed_decl_id_map: RwLock::new( self.trait_type_parsed_decl_id_map.read().clone(), ), impl_self_or_trait_parsed_decl_id_map: RwLock::new( self.impl_self_or_trait_parsed_decl_id_map.read().clone(), ), struct_parsed_decl_id_map: RwLock::new(self.struct_parsed_decl_id_map.read().clone()), storage_parsed_decl_id_map: RwLock::new(self.storage_parsed_decl_id_map.read().clone()), abi_parsed_decl_id_map: RwLock::new(self.abi_parsed_decl_id_map.read().clone()), constant_parsed_decl_id_map: RwLock::new( self.constant_parsed_decl_id_map.read().clone(), ), const_generic_parsed_decl_id_map: RwLock::new( self.const_generic_parsed_decl_id_map.read().clone(), ), configurable_parsed_decl_id_map: RwLock::new( self.configurable_parsed_decl_id_map.read().clone(), ), const_generics_parsed_decl_id_map: RwLock::new( self.const_generics_parsed_decl_id_map.read().clone(), ), enum_parsed_decl_id_map: RwLock::new(self.enum_parsed_decl_id_map.read().clone()), type_alias_parsed_decl_id_map: RwLock::new( self.type_alias_parsed_decl_id_map.read().clone(), ), parents: RwLock::new(self.parents.read().clone()), } } } pub trait DeclEngineGet<I, U> { fn get(&self, index: &I) -> Arc<U>; fn map<R>(&self, index: &I, f: impl FnOnce(&U) -> R) -> R; } pub trait DeclEngineGetParsedDeclId<T> where T: TyDeclParsedType, { fn get_parsed_decl_id(&self, decl_id: &DeclId<T>) -> Option<ParsedDeclId<T::ParsedType>>; } pub trait DeclEngineGetParsedDecl<T> where T: TyDeclParsedType, { fn get_parsed_decl(&self, decl_id: &DeclId<T>) -> Option<Declaration>; } pub trait DeclEngineInsert<T> where T: Named + Spanned + TyDeclParsedType, { fn insert( &self, decl: T, parsed_decl_id: Option<&ParsedDeclId<T::ParsedType>>, ) -> DeclRef<DeclId<T>>; } pub trait DeclEngineInsertArc<T> where T: Named + Spanned + TyDeclParsedType, { fn insert_arc( &self, decl: Arc<T>, parsed_decl_id: Option<&ParsedDeclId<T::ParsedType>>, ) -> DeclRef<DeclId<T>>; } pub trait DeclEngineReplace<T> { fn replace(&self, index: DeclId<T>, decl: T); } pub trait DeclEngineIndex<T>: DeclEngineGet<DeclId<T>, T> + DeclEngineReplace<T> where T: Named + Spanned, { } macro_rules! decl_engine_get { ($slab:ident, $decl:ty) => { impl DeclEngineGet<DeclId<$decl>, $decl> for DeclEngine { fn get(&self, index: &DeclId<$decl>) -> Arc<$decl> { self.$slab.get(index.inner()) } fn map<R>(&self, index: &DeclId<$decl>, f: impl FnOnce(&$decl) -> R) -> R { self.$slab.map(index.inner(), f) } } impl DeclEngineGet<DeclRef<DeclId<$decl>>, $decl> for DeclEngine { fn get(&self, index: &DeclRef<DeclId<$decl>>) -> Arc<$decl> { self.$slab.get(index.id().inner()) } fn map<R>(&self, index: &DeclRef<DeclId<$decl>>, f: impl FnOnce(&$decl) -> R) -> R { self.$slab.map(index.id().inner(), f) } } }; } decl_engine_get!(function_slab, ty::TyFunctionDecl); decl_engine_get!(trait_slab, ty::TyTraitDecl); decl_engine_get!(trait_fn_slab, ty::TyTraitFn); decl_engine_get!(trait_type_slab, ty::TyTraitType); decl_engine_get!(impl_self_or_trait_slab, ty::TyImplSelfOrTrait); decl_engine_get!(struct_slab, ty::TyStructDecl); decl_engine_get!(storage_slab, ty::TyStorageDecl); decl_engine_get!(abi_slab, ty::TyAbiDecl); decl_engine_get!(constant_slab, ty::TyConstantDecl); decl_engine_get!(configurable_slab, ty::TyConfigurableDecl); decl_engine_get!(const_generics_slab, ty::TyConstGenericDecl); decl_engine_get!(enum_slab, ty::TyEnumDecl); decl_engine_get!(type_alias_slab, ty::TyTypeAliasDecl); macro_rules! decl_engine_insert { ($slab:ident, $parsed_slab:ident, $decl:ty) => { impl DeclEngineInsert<$decl> for DeclEngine { fn insert( &self, decl: $decl, parsed_decl_id: Option<&ParsedDeclId<<$decl as TyDeclParsedType>::ParsedType>>, ) -> DeclRef<DeclId<$decl>> { let span = decl.span(); let decl_name = decl.name().clone(); let decl_id = DeclId::new(self.$slab.insert(decl)); if let Some(parsed_decl_id) = parsed_decl_id { self.$parsed_slab .write() .insert(decl_id, parsed_decl_id.clone()); } DeclRef::new(decl_name, decl_id, span) } } impl DeclEngineInsertArc<$decl> for DeclEngine { fn insert_arc( &self, decl: Arc<$decl>, parsed_decl_id: Option<&ParsedDeclId<<$decl as TyDeclParsedType>::ParsedType>>, ) -> DeclRef<DeclId<$decl>> { let span = decl.span(); let decl_name = decl.name().clone(); let decl_id = DeclId::new(self.$slab.insert_arc(decl)); if let Some(parsed_decl_id) = parsed_decl_id { self.$parsed_slab .write() .insert(decl_id, parsed_decl_id.clone()); } DeclRef::new(decl_name, decl_id, span) } } }; } decl_engine_insert!( function_slab, function_parsed_decl_id_map, ty::TyFunctionDecl ); decl_engine_insert!(trait_slab, trait_parsed_decl_id_map, ty::TyTraitDecl); decl_engine_insert!(trait_fn_slab, trait_fn_parsed_decl_id_map, ty::TyTraitFn); decl_engine_insert!( trait_type_slab, trait_type_parsed_decl_id_map, ty::TyTraitType ); decl_engine_insert!( impl_self_or_trait_slab, impl_self_or_trait_parsed_decl_id_map, ty::TyImplSelfOrTrait ); decl_engine_insert!(struct_slab, struct_parsed_decl_id_map, ty::TyStructDecl); decl_engine_insert!(storage_slab, storage_parsed_decl_id_map, ty::TyStorageDecl); decl_engine_insert!(abi_slab, abi_parsed_decl_id_map, ty::TyAbiDecl); decl_engine_insert!( constant_slab, constant_parsed_decl_id_map, ty::TyConstantDecl ); decl_engine_insert!( configurable_slab, configurable_parsed_decl_id_map, ty::TyConfigurableDecl ); decl_engine_insert!( const_generics_slab, const_generics_parsed_decl_id_map, ty::TyConstGenericDecl ); decl_engine_insert!(enum_slab, enum_parsed_decl_id_map, ty::TyEnumDecl); decl_engine_insert!( type_alias_slab, type_alias_parsed_decl_id_map, ty::TyTypeAliasDecl ); macro_rules! decl_engine_parsed_decl_id { ($slab:ident, $decl:ty) => { impl DeclEngineGetParsedDeclId<$decl> for DeclEngine { fn get_parsed_decl_id( &self, decl_id: &DeclId<$decl>, ) -> Option<ParsedDeclId<<$decl as TyDeclParsedType>::ParsedType>> { let parsed_decl_id_map = self.$slab.read(); if let Some(parsed_decl_id) = parsed_decl_id_map.get(&decl_id) { return Some(parsed_decl_id.clone()); } else { None } } } }; } decl_engine_parsed_decl_id!(function_parsed_decl_id_map, ty::TyFunctionDecl); decl_engine_parsed_decl_id!(trait_parsed_decl_id_map, ty::TyTraitDecl); decl_engine_parsed_decl_id!(trait_fn_parsed_decl_id_map, ty::TyTraitFn); decl_engine_parsed_decl_id!(trait_type_parsed_decl_id_map, ty::TyTraitType); decl_engine_parsed_decl_id!(impl_self_or_trait_parsed_decl_id_map, ty::TyImplSelfOrTrait); decl_engine_parsed_decl_id!(struct_parsed_decl_id_map, ty::TyStructDecl); decl_engine_parsed_decl_id!(storage_parsed_decl_id_map, ty::TyStorageDecl); decl_engine_parsed_decl_id!(abi_parsed_decl_id_map, ty::TyAbiDecl); decl_engine_parsed_decl_id!(constant_parsed_decl_id_map, ty::TyConstantDecl); decl_engine_parsed_decl_id!(const_generic_parsed_decl_id_map, ty::TyConstGenericDecl); decl_engine_parsed_decl_id!(configurable_parsed_decl_id_map, ty::TyConfigurableDecl); decl_engine_parsed_decl_id!(enum_parsed_decl_id_map, ty::TyEnumDecl); decl_engine_parsed_decl_id!(type_alias_parsed_decl_id_map, ty::TyTypeAliasDecl); macro_rules! decl_engine_parsed_decl { ($slab:ident, $decl:ty, $ctor:expr) => { impl DeclEngineGetParsedDecl<$decl> for DeclEngine { fn get_parsed_decl(&self, decl_id: &DeclId<$decl>) -> Option<Declaration> { let parsed_decl_id_map = self.$slab.read(); if let Some(parsed_decl_id) = parsed_decl_id_map.get(&decl_id) { return Some($ctor(parsed_decl_id.clone())); } else { None } } } }; } decl_engine_parsed_decl!( function_parsed_decl_id_map, ty::TyFunctionDecl, Declaration::FunctionDeclaration ); decl_engine_parsed_decl!( trait_parsed_decl_id_map, ty::TyTraitDecl, Declaration::TraitDeclaration ); decl_engine_parsed_decl!( trait_fn_parsed_decl_id_map, ty::TyTraitFn, Declaration::TraitFnDeclaration ); decl_engine_parsed_decl!( trait_type_parsed_decl_id_map, ty::TyTraitType, Declaration::TraitTypeDeclaration ); decl_engine_parsed_decl!( impl_self_or_trait_parsed_decl_id_map, ty::TyImplSelfOrTrait, Declaration::ImplSelfOrTrait ); decl_engine_parsed_decl!( struct_parsed_decl_id_map, ty::TyStructDecl, Declaration::StructDeclaration ); decl_engine_parsed_decl!( storage_parsed_decl_id_map, ty::TyStorageDecl, Declaration::StorageDeclaration ); decl_engine_parsed_decl!( abi_parsed_decl_id_map, ty::TyAbiDecl, Declaration::AbiDeclaration ); decl_engine_parsed_decl!( constant_parsed_decl_id_map, ty::TyConstantDecl, Declaration::ConstantDeclaration ); decl_engine_parsed_decl!( const_generic_parsed_decl_id_map, ty::TyConstGenericDecl, Declaration::ConstGenericDeclaration ); decl_engine_parsed_decl!( configurable_parsed_decl_id_map, ty::TyConfigurableDecl, Declaration::ConfigurableDeclaration ); decl_engine_parsed_decl!( enum_parsed_decl_id_map, ty::TyEnumDecl, Declaration::EnumDeclaration ); decl_engine_parsed_decl!( type_alias_parsed_decl_id_map, ty::TyTypeAliasDecl, Declaration::TypeAliasDeclaration ); macro_rules! decl_engine_replace { ($slab:ident, $decl:ty) => { impl DeclEngineReplace<$decl> for DeclEngine { fn replace(&self, index: DeclId<$decl>, decl: $decl) { self.$slab.replace(index.inner(), decl); } } }; } decl_engine_replace!(function_slab, ty::TyFunctionDecl); decl_engine_replace!(trait_slab, ty::TyTraitDecl); decl_engine_replace!(trait_fn_slab, ty::TyTraitFn); decl_engine_replace!(trait_type_slab, ty::TyTraitType); decl_engine_replace!(impl_self_or_trait_slab, ty::TyImplSelfOrTrait); decl_engine_replace!(struct_slab, ty::TyStructDecl); decl_engine_replace!(storage_slab, ty::TyStorageDecl); decl_engine_replace!(abi_slab, ty::TyAbiDecl); decl_engine_replace!(constant_slab, ty::TyConstantDecl); decl_engine_replace!(configurable_slab, ty::TyConfigurableDecl); decl_engine_replace!(enum_slab, ty::TyEnumDecl); decl_engine_replace!(type_alias_slab, ty::TyTypeAliasDecl); macro_rules! decl_engine_index { ($slab:ident, $decl:ty) => { impl DeclEngineIndex<$decl> for DeclEngine {} }; } decl_engine_index!(function_slab, ty::TyFunctionDecl); decl_engine_index!(trait_slab, ty::TyTraitDecl); decl_engine_index!(trait_fn_slab, ty::TyTraitFn); decl_engine_index!(trait_type_slab, ty::TyTraitType); decl_engine_index!(impl_self_or_trait_slab, ty::TyImplSelfOrTrait); decl_engine_index!(struct_slab, ty::TyStructDecl); decl_engine_index!(storage_slab, ty::TyStorageDecl); decl_engine_index!(abi_slab, ty::TyAbiDecl); decl_engine_index!(constant_slab, ty::TyConstantDecl); decl_engine_index!(configurable_slab, ty::TyConfigurableDecl); decl_engine_index!(enum_slab, ty::TyEnumDecl); decl_engine_index!(type_alias_slab, ty::TyTypeAliasDecl); macro_rules! decl_engine_clear_program { ($($slab:ident, $decl:ty);* $(;)?) => { impl DeclEngine { pub fn clear_program(&mut self, program_id: &ProgramId) { self.parents.write().retain(|key, _| { match key { AssociatedItemDeclId::TraitFn(decl_id) => { self.get_trait_fn(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id) }, AssociatedItemDeclId::Function(decl_id) => { self.get_function(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id) }, AssociatedItemDeclId::Type(decl_id) => { self.get_type(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id) }, AssociatedItemDeclId::Constant(decl_id) => { self.get_constant(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id) }, } }); $( self.$slab.retain(|_k, ty| match ty.span().source_id() { Some(source_id) => &source_id.program_id() != program_id, None => true, }); )* } } }; } decl_engine_clear_program!( function_slab, ty::TyFunctionDecl; trait_slab, ty::TyTraitDecl; trait_fn_slab, ty::TyTraitFn; trait_type_slab, ty::TyTraitType; impl_self_or_trait_slab, ty::TyImplTrait; struct_slab, ty::TyStructDecl; storage_slab, ty::TyStorageDecl; abi_slab, ty::TyAbiDecl; constant_slab, ty::TyConstantDecl; configurable_slab, ty::TyConfigurableDecl; enum_slab, ty::TyEnumDecl; type_alias_slab, ty::TyTypeAliasDecl; ); macro_rules! decl_engine_clear_module { ($($slab:ident, $decl:ty);* $(;)?) => { impl DeclEngine { pub fn clear_module(&mut self, source_id: &SourceId) { self.parents.write().retain(|key, _| { match key { AssociatedItemDeclId::TraitFn(decl_id) => { self.get_trait_fn(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id) }, AssociatedItemDeclId::Function(decl_id) => { self.get_function(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id) }, AssociatedItemDeclId::Type(decl_id) => { self.get_type(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id) }, AssociatedItemDeclId::Constant(decl_id) => { self.get_constant(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id) }, } }); $( self.$slab.retain(|_k, ty| match ty.span().source_id() { Some(src_id) => src_id != source_id, None => true, }); )* } } }; } decl_engine_clear_module!( function_slab, ty::TyFunctionDecl; trait_slab, ty::TyTraitDecl; trait_fn_slab, ty::TyTraitFn; trait_type_slab, ty::TyTraitType; impl_self_or_trait_slab, ty::TyImplTrait; struct_slab, ty::TyStructDecl; storage_slab, ty::TyStorageDecl; abi_slab, ty::TyAbiDecl; constant_slab, ty::TyConstantDecl; configurable_slab, ty::TyConfigurableDecl; enum_slab, ty::TyEnumDecl; type_alias_slab, ty::TyTypeAliasDecl; ); impl DeclEngine { /// Given a [DeclRef] `index`, finds all the parents of `index` and all the /// recursive parents of those parents, and so on. Does not perform /// duplicated computation---if the parents of a [DeclRef] have already been /// found, we do not find them again. #[allow(clippy::map_entry)] pub(crate) fn find_all_parents<'a, T>( &self, engines: &Engines, index: &'a T, ) -> Vec<AssociatedItemDeclId> where AssociatedItemDeclId: From<&'a T>, { let index: AssociatedItemDeclId = AssociatedItemDeclId::from(index); let parents = self.parents.read(); let mut acc_parents: HashMap<AssociatedItemDeclId, AssociatedItemDeclId> = HashMap::new(); let mut already_checked: HashSet<AssociatedItemDeclId> = HashSet::new(); let mut left_to_check: VecDeque<AssociatedItemDeclId> = VecDeque::from([index]); while let Some(curr) = left_to_check.pop_front() { if !already_checked.insert(curr.clone()) { continue; } if let Some(curr_parents) = parents.get(&curr) { for curr_parent in curr_parents.iter() { if !acc_parents.contains_key(curr_parent) { acc_parents.insert(curr_parent.clone(), curr_parent.clone()); } if !left_to_check.iter().any(|x| match (x, curr_parent) { ( AssociatedItemDeclId::TraitFn(x_id), AssociatedItemDeclId::TraitFn(curr_parent_id), ) => self.get(x_id).eq( &self.get(curr_parent_id), &PartialEqWithEnginesContext::new(engines), ), ( AssociatedItemDeclId::Function(x_id), AssociatedItemDeclId::Function(curr_parent_id), ) => self.get(x_id).eq( &self.get(curr_parent_id), &PartialEqWithEnginesContext::new(engines), ), _ => false, }) { left_to_check.push_back(curr_parent.clone()); } } } } acc_parents.values().cloned().collect() } pub(crate) fn register_parent<I>( &self, index: AssociatedItemDeclId, parent: AssociatedItemDeclId, ) where AssociatedItemDeclId: From<DeclId<I>>, { let mut parents = self.parents.write(); parents .entry(index) .and_modify(|e| e.push(parent.clone())) .or_insert_with(|| vec![parent]); } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_function<I>(&self, index: &I) -> Arc<ty::TyFunctionDecl> where DeclEngine: DeclEngineGet<I, ty::TyFunctionDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_trait<I>(&self, index: &I) -> Arc<ty::TyTraitDecl> where DeclEngine: DeclEngineGet<I, ty::TyTraitDecl>, { self.get(index) } /// Returns all the [ty::TyTraitDecl]s whose name is the same as `trait_name`. /// /// The method does a linear search over all the declared traits and is meant /// to be used only for diagnostic purposes. pub fn get_traits_by_name(&self, trait_name: &Ident) -> Vec<ty::TyTraitDecl> { let mut vec = vec![]; for trait_decl in self.trait_slab.values() { if trait_decl.name == *trait_name { vec.push((*trait_decl).clone()) } } vec } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_trait_fn<I>(&self, index: &I) -> Arc<ty::TyTraitFn> where DeclEngine: DeclEngineGet<I, ty::TyTraitFn>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_impl_self_or_trait<I>(&self, index: &I) -> Arc<ty::TyImplSelfOrTrait> where DeclEngine: DeclEngineGet<I, ty::TyImplSelfOrTrait>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_struct<I>(&self, index: &I) -> Arc<ty::TyStructDecl> where DeclEngine: DeclEngineGet<I, ty::TyStructDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine]. /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_storage<I>(&self, index: &I) -> Arc<ty::TyStorageDecl> where DeclEngine: DeclEngineGet<I, ty::TyStorageDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_abi<I>(&self, index: &I) -> Arc<ty::TyAbiDecl> where DeclEngine: DeclEngineGet<I, ty::TyAbiDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_constant<I>(&self, index: &I) -> Arc<ty::TyConstantDecl> where DeclEngine: DeclEngineGet<I, ty::TyConstantDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_configurable<I>(&self, index: &I) -> Arc<ty::TyConfigurableDecl> where DeclEngine: DeclEngineGet<I, ty::TyConfigurableDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_const_generic<I>(&self, index: &I) -> Arc<ty::TyConstGenericDecl> where DeclEngine: DeclEngineGet<I, ty::TyConstGenericDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_type<I>(&self, index: &I) -> Arc<ty::TyTraitType> where DeclEngine: DeclEngineGet<I, ty::TyTraitType>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_enum<I>(&self, index: &I) -> Arc<ty::TyEnumDecl> where DeclEngine: DeclEngineGet<I, ty::TyEnumDecl>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [DeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_type_alias<I>(&self, index: &I) -> Arc<ty::TyTypeAliasDecl> where DeclEngine: DeclEngineGet<I, ty::TyTypeAliasDecl>, { self.get(index) } /// Pretty print method for printing the [DeclEngine]. This method is /// manually implemented to avoid implementation overhead regarding using /// [DisplayWithEngines]. pub fn pretty_print(&self, engines: &Engines) -> String { let mut builder = String::new(); let mut list = String::with_capacity(1024 * 1024); let funcs = self.function_slab.values(); for (i, func) in funcs.iter().enumerate() { list.push_str(&format!("{i} - {:?}\n", engines.help_out(func))); } write!(builder, "DeclEngine {{\n{list}\n}}").unwrap(); builder } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/replace_decls.rs
sway-core/src/decl_engine/replace_decls.rs
use sway_error::handler::{ErrorEmitted, Handler}; use crate::{ engine_threading::Engines, language::ty::{self, TyDecl, TyExpression}, semantic_analysis::TypeCheckContext, }; use super::DeclMapping; pub trait ReplaceDecls { fn replace_decls_inner( &mut self, decl_mapping: &DeclMapping, handler: &Handler, ctx: &mut TypeCheckContext, ) -> Result<bool, ErrorEmitted>; fn replace_decls( &mut self, decl_mapping: &DeclMapping, handler: &Handler, ctx: &mut TypeCheckContext, ) -> Result<bool, ErrorEmitted> { if !decl_mapping.is_empty() { self.replace_decls_inner(decl_mapping, handler, ctx) } else { Ok(false) } } } impl<T: ReplaceDecls + Clone> ReplaceDecls for std::sync::Arc<T> { fn replace_decls_inner( &mut self, decl_mapping: &DeclMapping, handler: &Handler, ctx: &mut TypeCheckContext, ) -> Result<bool, ErrorEmitted> { if let Some(item) = std::sync::Arc::get_mut(self) { item.replace_decls_inner(decl_mapping, handler, ctx) } else { let mut item = self.as_ref().clone(); let r = item.replace_decls_inner(decl_mapping, handler, ctx)?; *self = std::sync::Arc::new(item); Ok(r) } } } pub(crate) trait ReplaceFunctionImplementingType { fn replace_implementing_type(&mut self, engines: &Engines, implementing_type: ty::TyDecl); } pub(crate) trait UpdateConstantExpression { fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl); } impl<T: UpdateConstantExpression + Clone> UpdateConstantExpression for std::sync::Arc<T> { fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl) { if let Some(item) = std::sync::Arc::get_mut(self) { item.update_constant_expression(engines, implementing_type); } else { let mut item = self.as_ref().clone(); item.update_constant_expression(engines, implementing_type); *self = std::sync::Arc::new(item); } } } // Iterate the tree searching for references to a const generic, // and initialize its value with the passed value pub(crate) trait MaterializeConstGenerics { fn materialize_const_generics( &mut self, engines: &Engines, handler: &Handler, name: &str, value: &TyExpression, ) -> Result<(), ErrorEmitted>; } impl<T: MaterializeConstGenerics + Clone> MaterializeConstGenerics for std::sync::Arc<T> { fn materialize_const_generics( &mut self, engines: &Engines, handler: &Handler, name: &str, value: &TyExpression, ) -> Result<(), ErrorEmitted> { if let Some(item) = std::sync::Arc::get_mut(self) { item.materialize_const_generics(engines, handler, name, value) } else { let mut item = self.as_ref().clone(); let r = item.materialize_const_generics(engines, handler, name, value); *self = std::sync::Arc::new(item); r } } } impl<T: MaterializeConstGenerics> MaterializeConstGenerics for Vec<T> { fn materialize_const_generics( &mut self, engines: &Engines, handler: &Handler, name: &str, value: &TyExpression, ) -> Result<(), ErrorEmitted> { for item in self.iter_mut() { item.materialize_const_generics(engines, handler, name, value)?; } Ok(()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/parsed_id.rs
sway-core/src/decl_engine/parsed_id.rs
use super::{ parsed_engine::{ParsedDeclEngine, ParsedDeclEngineGet, ParsedDeclEngineIndex}, DeclUniqueId, }; use crate::{ engine_threading::{ DebugWithEngines, EqWithEngines, HashWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext, }, Engines, }; use serde::{Deserialize, Serialize}; use std::{ hash::{DefaultHasher, Hasher}, marker::PhantomData, {fmt, hash::Hash}, }; use sway_types::{Named, Spanned}; pub type ParsedDeclIdIndexType = usize; /// An ID used to refer to an item in the [ParsedDeclEngine](super::decl_engine::ParsedDeclEngine) pub struct ParsedDeclId<T>(ParsedDeclIdIndexType, PhantomData<T>); impl<T> fmt::Debug for ParsedDeclId<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("ParsedDeclId").field(&self.0).finish() } } impl<T> ParsedDeclId<T> { pub(crate) fn inner(&self) -> ParsedDeclIdIndexType { self.0 } pub fn unique_id(&self) -> DeclUniqueId where T: 'static, { let mut hasher = DefaultHasher::default(); std::any::TypeId::of::<T>().hash(&mut hasher); self.0.hash(&mut hasher); DeclUniqueId(hasher.finish()) } } impl<T> Copy for ParsedDeclId<T> {} impl<T> Clone for ParsedDeclId<T> { fn clone(&self) -> Self { *self } } impl<T> Eq for ParsedDeclId<T> {} impl<T> PartialEq for ParsedDeclId<T> { fn eq(&self, other: &Self) -> bool { self.0.eq(&other.0) } } impl<T> DebugWithEngines for ParsedDeclId<T> where ParsedDeclEngine: ParsedDeclEngineIndex<T>, T: Named + Spanned + DebugWithEngines, { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { let decl = engines.pe().get(self); DebugWithEngines::fmt(&decl, f, engines) } } impl<T> EqWithEngines for ParsedDeclId<T> {} impl<T> PartialEqWithEngines for ParsedDeclId<T> { fn eq(&self, other: &Self, _ctx: &PartialEqWithEnginesContext) -> bool { self.0 == other.0 } } impl<T> Hash for ParsedDeclId<T> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.hash(state) } } impl<T> HashWithEngines for ParsedDeclId<T> where ParsedDeclEngine: ParsedDeclEngineIndex<T>, T: Named + Spanned + HashWithEngines, { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { let decl_engine = engines.pe(); let decl = decl_engine.get(self); decl.name().hash(state); decl.hash(state, engines); } } impl<T> PartialOrd for ParsedDeclId<T> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl<T> Ord for ParsedDeclId<T> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) } } impl<T> Serialize for ParsedDeclId<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de, T> Deserialize<'de> for ParsedDeclId<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let id = usize::deserialize(deserializer)?; Ok(ParsedDeclId::new(id)) } } impl<T> ParsedDeclId<T> { pub(crate) fn new(id: usize) -> Self { ParsedDeclId(id, PhantomData) } #[allow(dead_code)] pub(crate) fn replace_id(&mut self, index: Self) { self.0 = index.0; } #[allow(dead_code)] pub(crate) fn dummy() -> Self { // we assume that `usize::MAX` id is not possible in practice Self(usize::MAX, PhantomData) } } #[allow(clippy::from_over_into)] impl<T> Into<usize> for ParsedDeclId<T> { fn into(self) -> usize { self.0 } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/interface_decl_id.rs
sway-core/src/decl_engine/interface_decl_id.rs
use super::{parsed_engine::ParsedDeclEngineGet, parsed_id::ParsedDeclId}; use crate::{ decl_engine::*, engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext}, language::{ parsed::{AbiDeclaration, TraitDeclaration}, ty, }, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum ParsedInterfaceDeclId { Abi(ParsedDeclId<AbiDeclaration>), Trait(ParsedDeclId<TraitDeclaration>), } impl EqWithEngines for ParsedInterfaceDeclId {} impl PartialEqWithEngines for ParsedInterfaceDeclId { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { let decl_engine = ctx.engines().pe(); match (self, other) { (ParsedInterfaceDeclId::Abi(lhs), ParsedInterfaceDeclId::Abi(rhs)) => { decl_engine.get(lhs).eq(&decl_engine.get(rhs), ctx) } (ParsedInterfaceDeclId::Trait(lhs), ParsedInterfaceDeclId::Trait(rhs)) => { decl_engine.get(lhs).eq(&decl_engine.get(rhs), ctx) } _ => false, } } } impl From<ParsedDeclId<AbiDeclaration>> for ParsedInterfaceDeclId { fn from(id: ParsedDeclId<AbiDeclaration>) -> Self { Self::Abi(id) } } impl From<ParsedDeclId<TraitDeclaration>> for ParsedInterfaceDeclId { fn from(id: ParsedDeclId<TraitDeclaration>) -> Self { Self::Trait(id) } } #[derive(Debug, Eq, PartialEq, Hash, Clone, Serialize, Deserialize)] pub enum InterfaceDeclId { Abi(DeclId<ty::TyAbiDecl>), Trait(DeclId<ty::TyTraitDecl>), } impl From<DeclId<ty::TyAbiDecl>> for InterfaceDeclId { fn from(id: DeclId<ty::TyAbiDecl>) -> Self { Self::Abi(id) } } impl From<DeclId<ty::TyTraitDecl>> for InterfaceDeclId { fn from(id: DeclId<ty::TyTraitDecl>) -> Self { Self::Trait(id) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/id.rs
sway-core/src/decl_engine/id.rs
use crate::{ decl_engine::*, engine_threading::*, language::ty::{ TyConstantDecl, TyDeclParsedType, TyEnumDecl, TyFunctionDecl, TyImplSelfOrTrait, TyStructDecl, TyTraitDecl, TyTraitFn, TyTraitType, TyTypeAliasDecl, }, type_system::*, }; use serde::{Deserialize, Serialize}; use std::{ collections::hash_map::DefaultHasher, fmt, hash::{Hash, Hasher}, marker::PhantomData, }; use sway_types::{Named, Spanned}; pub type DeclIdIndexType = usize; /// An ID used to refer to an item in the [DeclEngine](super::decl_engine::DeclEngine) pub struct DeclId<T>(DeclIdIndexType, PhantomData<T>); impl<T> fmt::Debug for DeclId<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("DeclId").field(&self.0).finish() } } #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Serialize, Deserialize)] pub struct DeclUniqueId(pub(crate) u64); impl<T> DeclId<T> { pub(crate) fn inner(&self) -> DeclIdIndexType { self.0 } pub fn unique_id(&self) -> DeclUniqueId where T: 'static, { let mut hasher = DefaultHasher::default(); std::any::TypeId::of::<T>().hash(&mut hasher); self.0.hash(&mut hasher); DeclUniqueId(hasher.finish()) } } impl<T> Copy for DeclId<T> {} impl<T> Clone for DeclId<T> { fn clone(&self) -> Self { *self } } impl<T> Eq for DeclId<T> {} impl<T> Hash for DeclId<T> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.hash(state) } } impl<T> PartialEq for DeclId<T> { fn eq(&self, other: &Self) -> bool { self.0.eq(&other.0) } } impl<T> PartialOrd for DeclId<T> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl<T> Ord for DeclId<T> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) } } impl<T> DeclId<T> { pub(crate) fn new(id: usize) -> Self { DeclId(id, PhantomData) } pub(crate) fn replace_id(&mut self, index: Self) { self.0 = index.0; } pub(crate) fn dummy() -> Self { // we assume that `usize::MAX` id is not possible in practice Self(usize::MAX, PhantomData) } } #[allow(clippy::from_over_into)] impl<T> Into<usize> for DeclId<T> { fn into(self) -> usize { self.0 } } impl<T> DebugWithEngines for DeclId<T> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + DebugWithEngines, { fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result { let decl = engines.de().get(self); DebugWithEngines::fmt(&decl, f, engines) } } impl<T> EqWithEngines for DeclId<T> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + PartialEqWithEngines + EqWithEngines, { } impl<T> PartialEqWithEngines for DeclId<T> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + PartialEqWithEngines, { fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool { let decl_engine = ctx.engines().de(); let l_decl = decl_engine.get(self); let r_decl = decl_engine.get(other); l_decl.name() == r_decl.name() && l_decl.eq(&r_decl, ctx) } } impl<T> HashWithEngines for DeclId<T> where DeclEngine: DeclEngineIndex<T>, T: Named + Spanned + HashWithEngines, { fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) { let decl_engine = engines.de(); let decl = decl_engine.get(self); decl.name().hash(state); decl.hash(state, engines); } } impl SubstTypes for DeclId<TyFunctionDecl> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } impl SubstTypes for DeclId<TyTraitDecl> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } impl SubstTypes for DeclId<TyTraitFn> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } impl SubstTypes for DeclId<TyImplSelfOrTrait> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } impl SubstTypes for DeclId<TyStructDecl> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } impl SubstTypes for DeclId<TyEnumDecl> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } impl SubstTypes for DeclId<TyTypeAliasDecl> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } impl SubstTypes for DeclId<TyTraitType> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { decl_engine.replace(*self, decl); HasChanges::Yes } else { HasChanges::No } } } // This implementation deviates from all other DeclId<...> implementations. // For more, see https://github.com/FuelLabs/sway/pull/7440#discussion_r2428833840. // A better solution will be implemented in the future. // // TL;DR: // When a constant is declared inside a function, its value is shared by every // “version” of that function—that is, by all monomorphizations. If we “replace” the // constant, as other implementations do, we would change its value in *every* version, // which is incorrect. impl SubstTypes for DeclId<TyConstantDecl> { fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { *self = *decl_engine .insert(decl, decl_engine.get_parsed_decl_id(self).as_ref()) .id(); HasChanges::Yes } else { HasChanges::No } } } impl<T> DeclId<T> where DeclEngine: DeclEngineIndex<T> + DeclEngineInsert<T> + DeclEngineGetParsedDeclId<T>, T: Named + Spanned + SubstTypes + Clone + TyDeclParsedType, { pub(crate) fn subst_types_and_insert_new( &self, ctx: &SubstTypesContext, ) -> Option<DeclRef<Self>> { let decl_engine = ctx.engines.de(); let mut decl = (*decl_engine.get(self)).clone(); if decl.subst(ctx).has_changes() { Some(decl_engine.insert(decl, decl_engine.get_parsed_decl_id(self).as_ref())) } else { None } } } impl<T> Serialize for DeclId<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de, T> Deserialize<'de> for DeclId<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let id = DeclIdIndexType::deserialize(deserializer)?; Ok(DeclId::new(id)) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/mod.rs
sway-core/src/decl_engine/mod.rs
//! The [DeclEngine](engine::DeclEngine) allows the compiler to add a layer of //! separation between [AST nodes](crate::semantic_analysis::ast_node) and //! declarations. //! //! As an interface, you can think of the [DeclEngine](engine::DeclEngine) as a //! mapping from [DeclId](id::DeclId) to [DeclWrapper](wrapper::DeclWrapper). //! When a [DeclWrapper](wrapper::DeclWrapper) is inserted into the //! [DeclEngine](engine::DeclEngine), a [DeclId](id::DeclId) is generated, which //! is then used to refer to the declaration. pub mod associated_item_decl_id; #[allow(clippy::module_inception)] pub(crate) mod engine; pub mod id; pub(crate) mod interface_decl_id; pub(crate) mod mapping; pub(crate) mod parsed_engine; pub mod parsed_id; pub(crate) mod r#ref; pub(crate) mod replace_decls; use std::collections::BTreeMap; pub(crate) use associated_item_decl_id::*; pub use engine::*; pub(crate) use id::*; pub use interface_decl_id::*; pub(crate) use mapping::*; pub use parsed_engine::*; pub use r#ref::*; pub(crate) use replace_decls::*; use sway_types::Ident; use crate::{ language::ty::{TyTraitInterfaceItem, TyTraitItem}, TypeId, }; pub(crate) type InterfaceItemMap = BTreeMap<(Ident, TypeId), TyTraitInterfaceItem>; pub(crate) type ItemMap = BTreeMap<(Ident, TypeId), TyTraitItem>;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/parsed_engine.rs
sway-core/src/decl_engine/parsed_engine.rs
use crate::{ concurrent_slab::ConcurrentSlab, language::parsed::{ AbiDeclaration, ConfigurableDeclaration, ConstGenericDeclaration, ConstantDeclaration, EnumDeclaration, EnumVariant, FunctionDeclaration, ImplSelfOrTrait, StorageDeclaration, StructDeclaration, TraitDeclaration, TraitFn, TraitTypeDeclaration, TypeAliasDeclaration, VariableDeclaration, }, }; use std::sync::Arc; use sway_types::{ProgramId, SourceId, Spanned}; use super::parsed_id::ParsedDeclId; /// Used inside of type inference to store declarations. #[derive(Clone, Debug, Default)] pub struct ParsedDeclEngine { variable_slab: ConcurrentSlab<VariableDeclaration>, function_slab: ConcurrentSlab<FunctionDeclaration>, trait_slab: ConcurrentSlab<TraitDeclaration>, trait_fn_slab: ConcurrentSlab<TraitFn>, trait_type_slab: ConcurrentSlab<TraitTypeDeclaration>, impl_self_or_trait_slab: ConcurrentSlab<ImplSelfOrTrait>, struct_slab: ConcurrentSlab<StructDeclaration>, storage_slab: ConcurrentSlab<StorageDeclaration>, abi_slab: ConcurrentSlab<AbiDeclaration>, constant_slab: ConcurrentSlab<ConstantDeclaration>, configurable_slab: ConcurrentSlab<ConfigurableDeclaration>, const_generic_slab: ConcurrentSlab<ConstGenericDeclaration>, enum_slab: ConcurrentSlab<EnumDeclaration>, enum_variant_slab: ConcurrentSlab<EnumVariant>, type_alias_slab: ConcurrentSlab<TypeAliasDeclaration>, } pub trait ParsedDeclEngineGet<I, U> { fn get(&self, index: &I) -> Arc<U>; fn map<R>(&self, index: &I, f: impl FnOnce(&U) -> R) -> R; } pub trait ParsedDeclEngineInsert<T> { fn insert(&self, decl: T) -> ParsedDeclId<T>; } #[allow(unused)] pub trait ParsedDeclEngineReplace<T> { fn replace(&self, index: ParsedDeclId<T>, decl: T); } #[allow(unused)] pub trait ParsedDeclEngineIndex<T>: ParsedDeclEngineGet<ParsedDeclId<T>, T> + ParsedDeclEngineInsert<T> + ParsedDeclEngineReplace<T> { } macro_rules! decl_engine_get { ($slab:ident, $decl:ty) => { impl ParsedDeclEngineGet<ParsedDeclId<$decl>, $decl> for ParsedDeclEngine { fn get(&self, index: &ParsedDeclId<$decl>) -> Arc<$decl> { self.$slab.get(index.inner()) } fn map<R>(&self, index: &ParsedDeclId<$decl>, f: impl FnOnce(&$decl) -> R) -> R { self.$slab.map(index.inner(), f) } } }; } decl_engine_get!(variable_slab, VariableDeclaration); decl_engine_get!(function_slab, FunctionDeclaration); decl_engine_get!(trait_slab, TraitDeclaration); decl_engine_get!(trait_fn_slab, TraitFn); decl_engine_get!(trait_type_slab, TraitTypeDeclaration); decl_engine_get!(impl_self_or_trait_slab, ImplSelfOrTrait); decl_engine_get!(struct_slab, StructDeclaration); decl_engine_get!(storage_slab, StorageDeclaration); decl_engine_get!(abi_slab, AbiDeclaration); decl_engine_get!(constant_slab, ConstantDeclaration); decl_engine_get!(configurable_slab, ConfigurableDeclaration); decl_engine_get!(const_generic_slab, ConstGenericDeclaration); decl_engine_get!(enum_slab, EnumDeclaration); decl_engine_get!(enum_variant_slab, EnumVariant); decl_engine_get!(type_alias_slab, TypeAliasDeclaration); macro_rules! decl_engine_insert { ($slab:ident, $decl:ty) => { impl ParsedDeclEngineInsert<$decl> for ParsedDeclEngine { fn insert(&self, decl: $decl) -> ParsedDeclId<$decl> { ParsedDeclId::new(self.$slab.insert(decl)) } } }; } decl_engine_insert!(variable_slab, VariableDeclaration); decl_engine_insert!(function_slab, FunctionDeclaration); decl_engine_insert!(trait_slab, TraitDeclaration); decl_engine_insert!(trait_fn_slab, TraitFn); decl_engine_insert!(trait_type_slab, TraitTypeDeclaration); decl_engine_insert!(impl_self_or_trait_slab, ImplSelfOrTrait); decl_engine_insert!(struct_slab, StructDeclaration); decl_engine_insert!(storage_slab, StorageDeclaration); decl_engine_insert!(abi_slab, AbiDeclaration); decl_engine_insert!(constant_slab, ConstantDeclaration); decl_engine_insert!(configurable_slab, ConfigurableDeclaration); decl_engine_insert!(const_generic_slab, ConstGenericDeclaration); decl_engine_insert!(enum_slab, EnumDeclaration); decl_engine_insert!(enum_variant_slab, EnumVariant); decl_engine_insert!(type_alias_slab, TypeAliasDeclaration); macro_rules! decl_engine_replace { ($slab:ident, $decl:ty) => { impl ParsedDeclEngineReplace<$decl> for ParsedDeclEngine { fn replace(&self, index: ParsedDeclId<$decl>, decl: $decl) { self.$slab.replace(index.inner(), decl); } } }; } decl_engine_replace!(variable_slab, VariableDeclaration); decl_engine_replace!(function_slab, FunctionDeclaration); decl_engine_replace!(trait_slab, TraitDeclaration); decl_engine_replace!(trait_fn_slab, TraitFn); decl_engine_replace!(trait_type_slab, TraitTypeDeclaration); decl_engine_replace!(impl_self_or_trait_slab, ImplSelfOrTrait); decl_engine_replace!(struct_slab, StructDeclaration); decl_engine_replace!(storage_slab, StorageDeclaration); decl_engine_replace!(abi_slab, AbiDeclaration); decl_engine_replace!(configurable_slab, ConfigurableDeclaration); decl_engine_replace!(constant_slab, ConstantDeclaration); decl_engine_replace!(enum_slab, EnumDeclaration); decl_engine_replace!(type_alias_slab, TypeAliasDeclaration); macro_rules! decl_engine_clear { ($($slab:ident, $decl:ty);* $(;)?) => { impl ParsedDeclEngine { pub fn clear(&self) { $( self.$slab.clear(); )* } } }; } macro_rules! decl_engine_index { ($slab:ident, $decl:ty) => { impl ParsedDeclEngineIndex<$decl> for ParsedDeclEngine {} }; } decl_engine_index!(variable_slab, VariableDeclaration); decl_engine_index!(function_slab, FunctionDeclaration); decl_engine_index!(trait_slab, TraitDeclaration); decl_engine_index!(trait_fn_slab, TraitFn); decl_engine_index!(trait_type_slab, TraitTypeDeclaration); decl_engine_index!(impl_self_or_trait_slab, ImplSelfOrTrait); decl_engine_index!(struct_slab, StructDeclaration); decl_engine_index!(storage_slab, StorageDeclaration); decl_engine_index!(abi_slab, AbiDeclaration); decl_engine_index!(configurable_slab, ConfigurableDeclaration); decl_engine_index!(constant_slab, ConstantDeclaration); decl_engine_index!(enum_slab, EnumDeclaration); decl_engine_index!(type_alias_slab, TypeAliasDeclaration); decl_engine_clear!( variable_slab, VariableDeclaration; function_slab, FunctionDeclaration; trait_slab, TraitDeclaration; trait_fn_slab, TraitFn; trait_type_slab, TraitTypeDeclaration; impl_self_or_trait_slab, ImplTrait; struct_slab, StructDeclaration; storage_slab, StorageDeclaration; abi_slab, AbiDeclaration; constant_slab, ConstantDeclaration; enum_slab, EnumDeclaration; type_alias_slab, TypeAliasDeclaration; ); macro_rules! decl_engine_clear_program { ($(($slab:ident, $getter:expr)),* $(,)?) => { impl ParsedDeclEngine { pub fn clear_program(&mut self, program_id: &ProgramId) { $( self.$slab.retain(|_k, item| { #[allow(clippy::redundant_closure_call)] let span = $getter(item); match span.source_id() { Some(source_id) => &source_id.program_id() != program_id, None => true, } }); )* } } }; } decl_engine_clear_program!( (variable_slab, |item: &VariableDeclaration| item.name.span()), (function_slab, |item: &FunctionDeclaration| item.name.span()), (trait_slab, |item: &TraitDeclaration| item.name.span()), (trait_fn_slab, |item: &TraitFn| item.name.span()), (trait_type_slab, |item: &TraitTypeDeclaration| item .name .span()), (impl_self_or_trait_slab, |item: &ImplSelfOrTrait| item .block_span .clone()), (struct_slab, |item: &StructDeclaration| item.name.span()), (storage_slab, |item: &StorageDeclaration| item.span.clone()), (abi_slab, |item: &AbiDeclaration| item.name.span()), (constant_slab, |item: &ConstantDeclaration| item.name.span()), (enum_slab, |item: &EnumDeclaration| item.name.span()), (type_alias_slab, |item: &TypeAliasDeclaration| item .name .span()), ); macro_rules! decl_engine_clear_module { ($(($slab:ident, $getter:expr)),* $(,)?) => { impl ParsedDeclEngine { pub fn clear_module(&mut self, program_id: &SourceId) { $( self.$slab.retain(|_k, item| { #[allow(clippy::redundant_closure_call)] let span = $getter(item); match span.source_id() { Some(src_id) => src_id != program_id, None => true, } }); )* } } }; } decl_engine_clear_module!( (variable_slab, |item: &VariableDeclaration| item.name.span()), (function_slab, |item: &FunctionDeclaration| item.name.span()), (trait_slab, |item: &TraitDeclaration| item.name.span()), (trait_fn_slab, |item: &TraitFn| item.name.span()), (trait_type_slab, |item: &TraitTypeDeclaration| item .name .span()), (impl_self_or_trait_slab, |item: &ImplSelfOrTrait| item .block_span .clone()), (struct_slab, |item: &StructDeclaration| item.name.span()), (storage_slab, |item: &StorageDeclaration| item.span.clone()), (abi_slab, |item: &AbiDeclaration| item.name.span()), (constant_slab, |item: &ConstantDeclaration| item.name.span()), (enum_slab, |item: &EnumDeclaration| item.name.span()), (type_alias_slab, |item: &TypeAliasDeclaration| item .name .span()), ); impl ParsedDeclEngine { /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_function<I>(&self, index: &I) -> Arc<FunctionDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, FunctionDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [DeclEngineGet] for [DeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_trait<I>(&self, index: &I) -> Arc<TraitDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, TraitDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_trait_fn<I>(&self, index: &I) -> Arc<TraitFn> where ParsedDeclEngine: ParsedDeclEngineGet<I, TraitFn>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_impl_self_or_trait<I>(&self, index: &I) -> Arc<ImplSelfOrTrait> where ParsedDeclEngine: ParsedDeclEngineGet<I, ImplSelfOrTrait>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_struct<I>(&self, index: &I) -> Arc<StructDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, StructDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine]. /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_storage<I>(&self, index: &I) -> Arc<StorageDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, StorageDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_abi<I>(&self, index: &I) -> Arc<AbiDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, AbiDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_constant<I>(&self, index: &I) -> Arc<ConstantDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, ConstantDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_configurable<I>(&self, index: &I) -> Arc<ConfigurableDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, ConfigurableDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_const_generic<I>(&self, index: &I) -> Arc<ConstGenericDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, ConstGenericDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_trait_type<I>(&self, index: &I) -> Arc<TraitTypeDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, TraitTypeDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_enum<I>(&self, index: &I) -> Arc<EnumDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, EnumDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_enum_variant<I>(&self, index: &I) -> Arc<EnumVariant> where ParsedDeclEngine: ParsedDeclEngineGet<I, EnumVariant>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_type_alias<I>(&self, index: &I) -> Arc<TypeAliasDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, TypeAliasDeclaration>, { self.get(index) } /// Friendly helper method for calling the `get` method from the /// implementation of [ParsedDeclEngineGet] for [ParsedDeclEngine] /// /// Calling [ParsedDeclEngine][get] directly is equivalent to this method, but /// this method adds additional syntax that some users may find helpful. pub fn get_variable<I>(&self, index: &I) -> Arc<VariableDeclaration> where ParsedDeclEngine: ParsedDeclEngineGet<I, VariableDeclaration>, { self.get(index) } pub fn pretty_print(&self) -> String { use std::fmt::Write; let mut s = String::new(); let _ = write!( &mut s, "Function Count: {}", self.function_slab.values().len() ); for f in self.function_slab.values() { let _ = write!(&mut s, "Function: {}", f.name); for node in f.body.contents.iter() { let _ = write!(&mut s, " Node: {node:#?}"); } } s } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/decl_engine/associated_item_decl_id.rs
sway-core/src/decl_engine/associated_item_decl_id.rs
use sway_error::error::CompileError; use sway_types::{Named, Span, Spanned}; use crate::{ decl_engine::*, engine_threading::{DebugWithEngines, DisplayWithEngines}, language::ty::{self, TyFunctionDecl}, Engines, }; #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum AssociatedItemDeclId { TraitFn(DeclId<ty::TyTraitFn>), Function(DeclId<ty::TyFunctionDecl>), Constant(DeclId<ty::TyConstantDecl>), Type(DeclId<ty::TyTraitType>), } impl AssociatedItemDeclId { pub fn span(&self, engines: &Engines) -> Span { match self { Self::TraitFn(decl_id) => engines.de().get(decl_id).span(), Self::Function(decl_id) => engines.de().get(decl_id).span(), Self::Constant(decl_id) => engines.de().get(decl_id).span(), Self::Type(decl_id) => engines.de().get(decl_id).span(), } } } impl From<DeclId<ty::TyFunctionDecl>> for AssociatedItemDeclId { fn from(val: DeclId<ty::TyFunctionDecl>) -> Self { Self::Function(val) } } impl From<&DeclId<ty::TyFunctionDecl>> for AssociatedItemDeclId { fn from(val: &DeclId<ty::TyFunctionDecl>) -> Self { Self::Function(*val) } } impl From<&mut DeclId<ty::TyFunctionDecl>> for AssociatedItemDeclId { fn from(val: &mut DeclId<ty::TyFunctionDecl>) -> Self { Self::Function(*val) } } impl From<DeclId<ty::TyTraitFn>> for AssociatedItemDeclId { fn from(val: DeclId<ty::TyTraitFn>) -> Self { Self::TraitFn(val) } } impl From<&DeclId<ty::TyTraitFn>> for AssociatedItemDeclId { fn from(val: &DeclId<ty::TyTraitFn>) -> Self { Self::TraitFn(*val) } } impl From<&mut DeclId<ty::TyTraitFn>> for AssociatedItemDeclId { fn from(val: &mut DeclId<ty::TyTraitFn>) -> Self { Self::TraitFn(*val) } } impl From<DeclId<ty::TyTraitType>> for AssociatedItemDeclId { fn from(val: DeclId<ty::TyTraitType>) -> Self { Self::Type(val) } } impl From<&DeclId<ty::TyTraitType>> for AssociatedItemDeclId { fn from(val: &DeclId<ty::TyTraitType>) -> Self { Self::Type(*val) } } impl From<&mut DeclId<ty::TyTraitType>> for AssociatedItemDeclId { fn from(val: &mut DeclId<ty::TyTraitType>) -> Self { Self::Type(*val) } } impl From<DeclId<ty::TyConstantDecl>> for AssociatedItemDeclId { fn from(val: DeclId<ty::TyConstantDecl>) -> Self { Self::Constant(val) } } impl From<&DeclId<ty::TyConstantDecl>> for AssociatedItemDeclId { fn from(val: &DeclId<ty::TyConstantDecl>) -> Self { Self::Constant(*val) } } impl From<&mut DeclId<ty::TyConstantDecl>> for AssociatedItemDeclId { fn from(val: &mut DeclId<ty::TyConstantDecl>) -> Self { Self::Constant(*val) } } impl std::fmt::Display for AssociatedItemDeclId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::TraitFn(_) => { write!(f, "decl(trait function)",) } Self::Function(_) => { write!(f, "decl(function)",) } Self::Constant(_) => { write!(f, "decl(constant)",) } Self::Type(_) => { write!(f, "decl(type)",) } } } } impl DisplayWithEngines for AssociatedItemDeclId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result { match self { Self::TraitFn(decl_id) => { write!( f, "decl(trait function {})", engines.de().get(decl_id).name() ) } Self::Function(decl_id) => { write!(f, "decl(function {})", engines.de().get(decl_id).name()) } Self::Constant(decl_id) => { write!(f, "decl(constant {})", engines.de().get(decl_id).name()) } Self::Type(decl_id) => { write!(f, "decl(type {})", engines.de().get(decl_id).name()) } } } } impl DebugWithEngines for AssociatedItemDeclId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result { match self { Self::TraitFn(decl_id) => { let decl = engines.de().get(decl_id); write!(f, "decl(trait function {:?})", engines.help_out(decl)) } Self::Function(decl_id) => { write!( f, "decl(function {:?})", engines.help_out(engines.de().get(decl_id)) ) } Self::Constant(decl_id) => { write!( f, "decl(constant {:?})", engines.help_out(engines.de().get(decl_id)) ) } Self::Type(decl_id) => { write!( f, "decl(type {:?})", engines.help_out(engines.de().get(decl_id)) ) } } } } impl TryFrom<DeclRefMixedFunctional> for DeclRefFunction { type Error = CompileError; fn try_from(value: DeclRefMixedFunctional) -> Result<Self, Self::Error> { match value.id().clone() { AssociatedItemDeclId::Function(id) => Ok(DeclRef::new( value.name().clone(), id, value.decl_span().clone(), )), actually @ AssociatedItemDeclId::TraitFn(_) => Err(CompileError::DeclIsNotAFunction { actually: actually.to_string(), span: value.decl_span().clone(), }), actually @ AssociatedItemDeclId::Constant(_) => Err(CompileError::DeclIsNotAFunction { actually: actually.to_string(), span: value.decl_span().clone(), }), actually @ AssociatedItemDeclId::Type(_) => Err(CompileError::DeclIsNotAFunction { actually: actually.to_string(), span: value.decl_span().clone(), }), } } } impl TryFrom<&DeclRefMixedFunctional> for DeclRefFunction { type Error = CompileError; fn try_from(value: &DeclRefMixedFunctional) -> Result<Self, Self::Error> { value.clone().try_into() } } impl TryFrom<AssociatedItemDeclId> for DeclId<TyFunctionDecl> { type Error = CompileError; fn try_from(value: AssociatedItemDeclId) -> Result<Self, Self::Error> { match value { AssociatedItemDeclId::Function(id) => Ok(id), actually @ AssociatedItemDeclId::TraitFn(_) => Err(CompileError::DeclIsNotAFunction { actually: actually.to_string(), span: Span::dummy(), // FIXME }), actually @ AssociatedItemDeclId::Constant(_) => Err(CompileError::DeclIsNotAFunction { actually: actually.to_string(), span: Span::dummy(), // FIXME }), actually @ AssociatedItemDeclId::Type(_) => Err(CompileError::DeclIsNotAFunction { actually: actually.to_string(), span: Span::dummy(), // FIXME }), } } } impl TryFrom<&AssociatedItemDeclId> for DeclId<TyFunctionDecl> { type Error = CompileError; fn try_from(value: &AssociatedItemDeclId) -> Result<Self, Self::Error> { value.clone().try_into() } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/types/collect_types_metadata.rs
sway-core/src/types/collect_types_metadata.rs
//! This module handles the process of iterating through the typed AST and ensuring that all types //! are well-defined and well-formed. This process is run on the AST before we pass it into the IR, //! as the IR assumes all types are well-formed and will throw an ICE (internal compiler error) if //! that is not the case. use std::{ collections::HashMap, sync::{Arc, Mutex}, }; use crate::{ abi_generation::abi_str::AbiStrContext, language::ty::{TyExpression, TyExpressionVariant}, type_system::TypeId, Engines, }; use sha2::{Digest, Sha256}; use sway_error::{ error::CompileError, formatting, handler::{ErrorEmitted, Handler}, }; use sway_features::ExperimentalFeatures; use sway_types::{Ident, Span}; /// If any types contained by this node are unresolved or have yet to be inferred, throw an /// error to signal to the user that more type information is needed. #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] pub struct LogId { pub hash_id: u64, } impl LogId { pub fn new(string: String) -> LogId { let mut hasher = Sha256::new(); hasher.update(string); let result = hasher.finalize(); let hash_id = u64::from_be_bytes(result[0..8].try_into().unwrap()); LogId { hash_id } } } #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] pub struct MessageId(usize); impl std::ops::Deref for MessageId { type Target = usize; fn deref(&self) -> &Self::Target { &self.0 } } impl MessageId { pub fn new(index: usize) -> MessageId { MessageId(index) } } #[allow(clippy::enum_variant_names)] #[derive(Debug, Clone)] pub enum TypeMetadata { // UnresolvedType receives the Ident of the type and a call site span. UnresolvedType(Ident, Option<Span>), // A log with a unique log ID and the type ID of the type of the value being logged LoggedType(LogId, TypeId), // An smo with a unique message ID and the type ID of the type of the message data being sent MessageType(MessageId, TypeId), } impl TypeMetadata { /// Returns the [TypeId] of the actual type being logged. /// When the "new_encoding" is off, this is the actual type of /// the `logged_expr`. E.g., when calling `__log(<logged_expr>)`, /// or `panic <logged_expr>;` it will be the type of the `__log` /// or `panic` argument, respectively. When "new_encoding" is on, /// it is actually the type of the argument passed to the `encode` /// function. In this case, when `is_new_encoding` is true, `logged_expr` /// must represent a [TyExpressionVariant::FunctionApplication] call to `encode`. pub(crate) fn get_logged_type_id( logged_expr: &TyExpression, is_new_encoding: bool, ) -> Result<TypeId, CompileError> { Self::get_logged_expression(logged_expr, is_new_encoding) .map(|logged_expr| logged_expr.return_type) } /// Returns the [TyExpression] that is actually being logged. /// When the "new_encoding" is off, this is the `logged_expr` itself. /// E.g., when calling `__log(<logged_expr>)`, or `panic <logged_expr>;` /// it will be the expression of the `__log` or `panic` argument, /// respectively. When "new_encoding" is on, it is the expression /// of the argument passed to the `encode` function. /// In this case, when `is_new_encoding` is true, `logged_expr` /// must represent a [TyExpressionVariant::FunctionApplication] call to `encode`. pub(crate) fn get_logged_expression( logged_expr: &TyExpression, is_new_encoding: bool, ) -> Result<&TyExpression, CompileError> { if is_new_encoding { match &logged_expr.expression { TyExpressionVariant::FunctionApplication { call_path, arguments, .. } if call_path.suffix.as_str() == "encode" => { if arguments.len() != 1 { Err(CompileError::InternalOwned( format!("The \"encode\" function must have exactly one argument but it had {}.", formatting::num_to_str(arguments.len())), logged_expr.span.clone(), )) } else { Ok(&arguments[0].1) } } _ => Err(CompileError::Internal( "In case of the new encoding, the \"logged_expr\" must be a call to an \"encode\" function.", logged_expr.span.clone() )) } } else { Ok(logged_expr) } } pub(crate) fn new_logged_type( handler: &Handler, engines: &Engines, type_id: TypeId, program_name: String, ) -> Result<Self, ErrorEmitted> { Ok(TypeMetadata::LoggedType( LogId::new(type_id.get_abi_type_str( handler, &AbiStrContext { program_name, abi_with_callpaths: true, abi_with_fully_specified_types: true, abi_root_type_without_generic_type_parameters: false, }, engines, type_id, )?), type_id, )) } } // A simple context that only contains a single counter for now but may expand in the future. pub struct CollectTypesMetadataContext<'cx> { // Consume this and update it via the methods implemented for CollectTypesMetadataContext to // obtain a unique ID for a given smo instance. message_id_counter: usize, call_site_spans: Vec<Arc<Mutex<HashMap<TypeId, Span>>>>, pub(crate) engines: &'cx Engines, pub(crate) program_name: String, pub experimental: ExperimentalFeatures, } impl<'cx> CollectTypesMetadataContext<'cx> { pub fn message_id_counter(&self) -> usize { self.message_id_counter } pub fn message_id_counter_mut(&mut self) -> &mut usize { &mut self.message_id_counter } pub fn call_site_push(&mut self) { self.call_site_spans .push(Arc::new(Mutex::new(HashMap::new()))); } pub fn call_site_pop(&mut self) { self.call_site_spans.pop(); } pub fn call_site_insert(&mut self, type_id: TypeId, span: Span) { self.call_site_spans .last() .and_then(|h| h.lock().ok()) .and_then(|mut l| l.insert(type_id, span)); } pub fn call_site_get(&mut self, type_id: &TypeId) -> Option<Span> { for lock in &self.call_site_spans { if let Ok(hash_map) = lock.lock() { let opt = hash_map.get(type_id).cloned(); if opt.is_some() { return opt; } } } None } pub fn new( engines: &'cx Engines, experimental: ExperimentalFeatures, program_name: String, ) -> Self { let mut ctx = Self { engines, message_id_counter: 0, call_site_spans: vec![], experimental, program_name, }; ctx.call_site_push(); ctx } } pub(crate) trait CollectTypesMetadata { fn collect_types_metadata( &self, handler: &Handler, ctx: &mut CollectTypesMetadataContext, ) -> Result<Vec<TypeMetadata>, ErrorEmitted>; }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/types/mod.rs
sway-core/src/types/mod.rs
mod collect_types_metadata; pub(crate) use collect_types_metadata::*;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/abi_generation/evm_abi.rs
sway-core/src/abi_generation/evm_abi.rs
use sway_types::{integer_bits::IntegerBits, Named}; use crate::{ asm_generation::EvmAbiResult, ast_elements::type_argument::GenericTypeArgument, decl_engine::DeclId, language::ty::{TyFunctionDecl, TyProgram, TyProgramKind}, Engines, TypeId, TypeInfo, }; pub fn generate_abi_program(program: &TyProgram, engines: &Engines) -> EvmAbiResult { match &program.kind { TyProgramKind::Contract { abi_entries, .. } => abi_entries .iter() .map(|x| generate_abi_function(x, engines)) .collect(), TyProgramKind::Script { entry_function, .. } | TyProgramKind::Predicate { entry_function, .. } => { vec![generate_abi_function(entry_function, engines)] } _ => vec![], } } /// Gives back a string that represents the type, considering what it resolves to fn get_type_str(type_id: &TypeId, engines: &Engines, resolved_type_id: TypeId) -> String { let type_engine = engines.te(); if type_id.is_generic_parameter(engines, resolved_type_id) { format!("generic {}", abi_str(&type_engine.get(*type_id), engines)) } else { match ( &*type_engine.get(*type_id), &*type_engine.get(resolved_type_id), ) { (TypeInfo::Custom { .. }, TypeInfo::Struct { .. }) => { format!("struct {}", abi_str(&type_engine.get(*type_id), engines)) } (TypeInfo::Custom { .. }, TypeInfo::Enum { .. }) => { format!("enum {}", abi_str(&type_engine.get(*type_id), engines)) } (TypeInfo::Tuple(fields), TypeInfo::Tuple(resolved_fields)) => { assert_eq!(fields.len(), resolved_fields.len()); let field_strs = fields .iter() .map(|_| "_".to_string()) .collect::<Vec<String>>(); format!("({})", field_strs.join(", ")) } (TypeInfo::Array(_, length), TypeInfo::Array(_, resolved_length)) => { assert_eq!( length.expr().as_literal_val().unwrap(), resolved_length.expr().as_literal_val().unwrap() ); format!("[_; {:?}]", engines.help_out(length.expr())) } (TypeInfo::Slice(_), TypeInfo::Slice(_)) => "__slice[_]".into(), (TypeInfo::Custom { .. }, _) => { format!("generic {}", abi_str(&type_engine.get(*type_id), engines)) } _ => abi_str(&type_engine.get(*type_id), engines), } } } pub fn abi_str(type_info: &TypeInfo, engines: &Engines) -> String { use TypeInfo::*; let decl_engine = engines.de(); match type_info { Unknown => "unknown".into(), Never => "never".into(), UnknownGeneric { name, .. } => name.to_string(), Placeholder(_) => "_".to_string(), TypeParam(param) => format!("typeparam({})", param.name()), StringSlice => "str".into(), StringArray(length) => format!("str[{:?}]", engines.help_out(length.expr())), UnsignedInteger(x) => match x { IntegerBits::Eight => "uint8", IntegerBits::Sixteen => "uint16", IntegerBits::ThirtyTwo => "uint32", IntegerBits::SixtyFour => "uint64", IntegerBits::V256 => "uint256", } .into(), Boolean => "bool".into(), Custom { qualified_call_path: call_path, .. } => call_path.call_path.suffix.to_string(), Tuple(fields) => { let field_strs = fields .iter() .map(|field| abi_str_type_arg(field, engines)) .collect::<Vec<String>>(); format!("({})", field_strs.join(", ")) } B256 => "uint256".into(), Numeric => "u64".into(), // u64 is the default Contract => "contract".into(), ErrorRecovery(_) => "unknown due to error".into(), UntypedEnum(decl_id) => { let decl = engines.pe().get_enum(decl_id); format!("untyped enum {}", decl.name) } UntypedStruct(decl_id) => { let decl = engines.pe().get_struct(decl_id); format!("untyped struct {}", decl.name) } Enum(decl_ref) => { let decl = decl_engine.get_enum(decl_ref); format!("enum {}", decl.call_path.suffix) } Struct(decl_ref) => { let decl = decl_engine.get_struct(decl_ref); format!("struct {}", decl.call_path.suffix) } ContractCaller { abi_name, .. } => { format!("contract caller {abi_name}") } Array(elem_ty, length) => { format!( "{}[{:?}]", abi_str_type_arg(elem_ty, engines), engines.help_out(length.expr()), ) } RawUntypedPtr => "raw untyped ptr".into(), RawUntypedSlice => "raw untyped slice".into(), Ptr(ty) => { format!("__ptr {}", abi_str_type_arg(ty, engines)) } Slice(ty) => { format!("__slice {}", abi_str_type_arg(ty, engines)) } Alias { ty, .. } => abi_str_type_arg(ty, engines), TraitType { name, implemented_in: _, } => format!("trait type {name}"), Ref { to_mutable_value, referenced_type, } => { format!( "__ref {}{}", // TODO: (REFERENCES) No references in ABIs according to the RFC. Or we want to have them? if *to_mutable_value { "mut " } else { "" }, abi_str_type_arg(referenced_type, engines) ) } } } pub fn abi_param_type(type_info: &TypeInfo, engines: &Engines) -> ethabi::ParamType { use TypeInfo::*; let type_engine = engines.te(); let decl_engine = engines.de(); match type_info { StringArray(length) => ethabi::ParamType::FixedArray( Box::new(ethabi::ParamType::String), length.expr().as_literal_val().unwrap(), ), UnsignedInteger(x) => match x { IntegerBits::Eight => ethabi::ParamType::Uint(8), IntegerBits::Sixteen => ethabi::ParamType::Uint(16), IntegerBits::ThirtyTwo => ethabi::ParamType::Uint(32), IntegerBits::SixtyFour => ethabi::ParamType::Uint(64), IntegerBits::V256 => ethabi::ParamType::Uint(256), }, Boolean => ethabi::ParamType::Bool, B256 => ethabi::ParamType::Uint(256), Contract => ethabi::ParamType::Address, Enum { .. } => ethabi::ParamType::Uint(8), Tuple(fields) => ethabi::ParamType::Tuple( fields .iter() .map(|f| abi_param_type(&type_engine.get(f.type_id), engines)) .collect::<Vec<ethabi::ParamType>>(), ), Struct(decl_ref) => { let decl = decl_engine.get_struct(decl_ref); ethabi::ParamType::Tuple( decl.fields .iter() .map(|f| abi_param_type(&type_engine.get(f.type_argument.type_id), engines)) .collect::<Vec<ethabi::ParamType>>(), ) } Array(elem_ty, ..) => ethabi::ParamType::Array(Box::new(abi_param_type( &type_engine.get(elem_ty.type_id), engines, ))), _ => panic!("cannot convert type to Solidity ABI param type: {type_info:?}",), } } fn generate_abi_function( fn_decl_id: &DeclId<TyFunctionDecl>, engines: &Engines, ) -> ethabi::operation::Operation { let decl_engine = engines.de(); let fn_decl = decl_engine.get_function(fn_decl_id); // A list of all `ethabi::Param`s needed for inputs let input_types = fn_decl .parameters .iter() .map(|x| ethabi::Param { name: x.name.to_string(), kind: ethabi::ParamType::Address, internal_type: Some(get_type_str( &x.type_argument.type_id, engines, x.type_argument.type_id, )), }) .collect::<Vec<_>>(); // The single `ethabi::Param` needed for the output let output_type = ethabi::Param { name: String::default(), kind: ethabi::ParamType::Address, internal_type: Some(get_type_str( &fn_decl.return_type.type_id, engines, fn_decl.return_type.type_id, )), }; // Generate the ABI data for the function #[allow(deprecated)] ethabi::operation::Operation::Function(ethabi::Function { name: fn_decl.name.as_str().to_string(), inputs: input_types, outputs: vec![output_type], constant: None, state_mutability: ethabi::StateMutability::Payable, }) } fn abi_str_type_arg(type_arg: &GenericTypeArgument, engines: &Engines) -> String { abi_str(&engines.te().get(type_arg.type_id), engines) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/abi_generation/abi_str.rs
sway-core/src/abi_generation/abi_str.rs
use crate::{ ast_elements::type_argument::GenericTypeArgument, language::CallPath, transform, Engines, TypeId, TypeInfo, }; use sway_error::handler::{ErrorEmitted, Handler}; use sway_types::{integer_bits::IntegerBits, Ident, Named}; #[derive(Clone)] pub struct AbiStrContext { pub program_name: String, pub abi_with_callpaths: bool, pub abi_with_fully_specified_types: bool, pub abi_root_type_without_generic_type_parameters: bool, } impl TypeId { /// Gives back a string that represents the type, considering what it resolves to pub fn get_abi_type_str( &self, handler: &Handler, ctx: &AbiStrContext, engines: &Engines, resolved_type_id: TypeId, ) -> Result<String, ErrorEmitted> { let type_engine = engines.te(); let self_abi_str = type_engine .get(*self) .abi_str(handler, ctx, engines, true)?; if self.is_generic_parameter(engines, resolved_type_id) { Ok(format!("generic {self_abi_str}")) } else { match ( &*type_engine.get(*self), &*type_engine.get(resolved_type_id), ) { (TypeInfo::Custom { .. }, TypeInfo::Struct { .. }) | (TypeInfo::Custom { .. }, TypeInfo::Enum { .. }) => type_engine .get(resolved_type_id) .abi_str(handler, ctx, engines, true), (_, TypeInfo::Alias { ty, .. }) => ty .type_id .get_abi_type_str(handler, ctx, engines, ty.type_id), (TypeInfo::Tuple(fields), TypeInfo::Tuple(resolved_fields)) => { assert_eq!(fields.len(), resolved_fields.len()); let field_strs = resolved_fields .iter() .map(|f| { if ctx.abi_with_fully_specified_types { type_engine .get(f.type_id) .abi_str(handler, ctx, engines, false) } else { Ok("_".to_string()) } }) .collect::<Result<Vec<String>, _>>()?; Ok(format!("({})", field_strs.join(", "))) } (TypeInfo::Array(_, length), TypeInfo::Array(type_arg, resolved_length)) => { assert_eq!( length.expr().as_literal_val(), resolved_length.expr().as_literal_val(), "{:?} {:?}", length.expr().as_literal_val(), resolved_length.expr().as_literal_val() ); let inner_type = if ctx.abi_with_fully_specified_types { type_engine .get(type_arg.type_id) .abi_str(handler, ctx, engines, false)? } else { "_".to_string() }; Ok(format!( "[{}; {:?}]", inner_type, engines.help_out(length.expr()) )) } (TypeInfo::Slice(type_arg), TypeInfo::Slice(_)) => { let inner_type = if ctx.abi_with_fully_specified_types { type_engine .get(type_arg.type_id) .abi_str(handler, ctx, engines, false)? } else { "_".to_string() }; Ok(format!("[{inner_type}]")) } (TypeInfo::Custom { .. }, _) => Ok(format!("generic {self_abi_str}")), _ => type_engine .get(resolved_type_id) .abi_str(handler, ctx, engines, true), } } } } impl TypeInfo { pub fn abi_str( &self, handler: &Handler, ctx: &AbiStrContext, engines: &Engines, is_root: bool, ) -> Result<String, ErrorEmitted> { use TypeInfo::*; let decl_engine = engines.de(); match self { Unknown => Ok("unknown".into()), Never => Ok("never".into()), UnknownGeneric { name, .. } => Ok(name.to_string()), Placeholder(_) => Ok("_".to_string()), TypeParam(param) => Ok(format!("typeparam({})", param.name())), StringSlice => Ok("str".into()), StringArray(length) => Ok(format!("str[{:?}]", engines.help_out(length.expr()))), UnsignedInteger(x) => Ok(match x { IntegerBits::Eight => "u8", IntegerBits::Sixteen => "u16", IntegerBits::ThirtyTwo => "u32", IntegerBits::SixtyFour => "u64", IntegerBits::V256 => "u256", } .into()), Boolean => Ok("bool".into()), Custom { qualified_call_path: call_path, .. } => Ok(call_path.call_path.suffix.to_string()), Tuple(fields) => { let field_strs = fields .iter() .map(|field| field.abi_str(handler, ctx, engines, false)) .collect::<Result<Vec<String>, ErrorEmitted>>()?; Ok(format!("({})", field_strs.join(", "))) } B256 => Ok("b256".into()), Numeric => Ok("u64".into()), // u64 is the default Contract => Ok("contract".into()), ErrorRecovery(_) => Ok("unknown due to error".into()), UntypedEnum(decl_id) => { let decl = engines.pe().get_enum(decl_id); Ok(format!("untyped enum {}", decl.name)) } UntypedStruct(decl_id) => { let decl = engines.pe().get_struct(decl_id); Ok(format!("untyped struct {}", decl.name)) } Enum(decl_ref) => { let decl = decl_engine.get_enum(decl_ref); let type_params = if (ctx.abi_root_type_without_generic_type_parameters && is_root) || decl.generic_parameters.is_empty() { "" } else { let params = decl .generic_parameters .iter() .map(|p| p.abi_str(handler, engines, ctx, false)) .collect::<Result<Vec<_>, _>>()?; &format!("<{}>", params.join(",")) }; let abi_call_path = get_abi_call_path(handler, &decl.call_path, &decl.attributes)?; Ok(format!( "enum {}{}", call_path_display(ctx, &abi_call_path), type_params )) } Struct(decl_ref) => { let decl = decl_engine.get_struct(decl_ref); let type_params = if (ctx.abi_root_type_without_generic_type_parameters && is_root) || decl.generic_parameters.is_empty() { "".into() } else { let params = decl .generic_parameters .iter() .map(|p| p.abi_str(handler, engines, ctx, false)) .collect::<Result<Vec<_>, _>>()?; format!("<{}>", params.join(",")) }; let abi_call_path = get_abi_call_path(handler, &decl.call_path, &decl.attributes)?; Ok(format!( "struct {}{}", call_path_display(ctx, &abi_call_path), type_params )) } ContractCaller { abi_name, .. } => Ok(format!("contract caller {abi_name}")), Array(elem_ty, length) => Ok(format!( "[{}; {:?}]", elem_ty.abi_str(handler, ctx, engines, false)?, engines.help_out(length.expr()) )), RawUntypedPtr => Ok("raw untyped ptr".into()), RawUntypedSlice => Ok("raw untyped slice".into()), Ptr(ty) => Ok(format!( "__ptr {}", ty.abi_str(handler, ctx, engines, false)? )), Slice(ty) => Ok(format!( "__slice {}", ty.abi_str(handler, ctx, engines, false)? )), Alias { ty, .. } => Ok(ty.abi_str(handler, ctx, engines, false)?), TraitType { name, implemented_in: _, } => Ok(format!("trait type {name}")), Ref { to_mutable_value, referenced_type, } => { Ok(format!( "__ref {}{}", // TODO: (REFERENCES) No references in ABIs according to the RFC. Or we want to have them? if *to_mutable_value { "mut " } else { "" }, referenced_type.abi_str(handler, ctx, engines, false)? )) } } } } fn get_abi_call_path( handler: &Handler, call_path: &CallPath, attributes: &transform::Attributes, ) -> Result<CallPath, ErrorEmitted> { let mut abi_call_path = call_path.clone(); if let Some(abi_name_attr) = attributes.abi_name() { let name = abi_name_attr.args.first().unwrap(); let ident = Ident::new_no_span(name.get_string(handler, abi_name_attr)?.clone()); abi_call_path.suffix = ident; } Ok(abi_call_path) } /// `call_path_display` returns the provided `call_path` without the first prefix in case it is equal to the program name. /// If the program name is `my_program` and the `call_path` is `my_program::MyStruct` then this function returns only `MyStruct`. fn call_path_display(ctx: &AbiStrContext, call_path: &CallPath) -> String { if !ctx.abi_with_callpaths { return call_path.suffix.as_str().to_string(); } let mut buf = String::new(); for (index, prefix) in call_path.prefixes.iter().enumerate() { if index == 0 && prefix.as_str() == ctx.program_name { continue; } buf.push_str(prefix.as_str()); buf.push_str("::"); } buf.push_str(&call_path.suffix.to_string()); buf } impl GenericTypeArgument { pub(self) fn abi_str( &self, handler: &Handler, ctx: &AbiStrContext, engines: &Engines, is_root: bool, ) -> Result<String, ErrorEmitted> { engines .te() .get(self.type_id) .abi_str(handler, ctx, engines, is_root) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/abi_generation/mod.rs
sway-core/src/abi_generation/mod.rs
pub mod abi_str; pub mod evm_abi; pub mod fuel_abi;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/abi_generation/fuel_abi.rs
sway-core/src/abi_generation/fuel_abi.rs
use fuel_abi_types::abi::program::{ self as program_abi, ConcreteTypeId, ErrorDetails, ErrorPosition, MetadataTypeId, PanickingCall, TypeConcreteDeclaration, }; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, HashMap, HashSet}; use sway_error::{ error::CompileError, handler::{ErrorEmitted, Handler}, }; use sway_parse::is_valid_identifier_or_path; use sway_types::{BaseIdent, Named, Span, Spanned}; use crate::{ ast_elements::type_parameter::GenericTypeParameter, language::ty::{TyFunctionDecl, TyProgram, TyProgramKind}, transform::Attributes, AbiEncodeSizeHint, Engines, PanicOccurrences, PanickingCallOccurrences, TypeId, TypeInfo, }; use super::abi_str::AbiStrContext; #[derive(Clone, Debug)] pub enum AbiNameDiagnosticSpan { Attribute(Span), Type(Span), } impl AbiNameDiagnosticSpan { pub fn span(self) -> Span { match self { Self::Attribute(span) | Self::Type(span) => span, } } } pub struct AbiContext<'a> { pub program: &'a TyProgram, pub panic_occurrences: &'a PanicOccurrences, pub panicking_call_occurrences: &'a PanickingCallOccurrences, pub abi_with_callpaths: bool, pub type_ids_to_full_type_str: HashMap<String, String>, pub unique_names: HashMap<String, AbiNameDiagnosticSpan>, } impl AbiContext<'_> { fn to_str_context(&self) -> AbiStrContext { AbiStrContext { program_name: self.program.namespace.current_package_name().to_string(), abi_with_callpaths: self.abi_with_callpaths, abi_with_fully_specified_types: false, abi_root_type_without_generic_type_parameters: true, } } } pub fn extract_abi_name_inner(span: &Span) -> Option<Span> { let text = &span.src().text; let full_attr = span.as_str(); // Find the "name" key. let name_key_pos = full_attr.find("name")?; let after_name = &full_attr[name_key_pos..]; // Find the '=' after "name". let eq_offset_rel = after_name.find('=')?; let after_eq = &after_name[eq_offset_rel + 1..]; // Find the opening quote of the literal. let first_quote_rel = after_eq.find('"')?; let ident_abs_start = span.start() + name_key_pos + eq_offset_rel + 1 // move past '=' + first_quote_rel + 1; // move past the opening '"' // Starting at ident_abs_start, locate the closing quote. let rest_after_ident = &text[ident_abs_start..span.end()]; let second_quote_rel = rest_after_ident.find('"')?; let ident_abs_end = ident_abs_start + second_quote_rel; Span::new( span.src().clone(), ident_abs_start - 1, ident_abs_end + 1, span.source_id().cloned(), ) } impl TypeId { fn get_abi_name_and_span_from_type_id( engines: &Engines, type_id: TypeId, ) -> Result<Option<(String, Span)>, ErrorEmitted> { let handler = Handler::default(); match *engines.te().get(type_id) { TypeInfo::Enum(decl_id) => { let enum_decl = engines.de().get_enum(&decl_id); match enum_decl.attributes.abi_name() { Some(abi_name_attr) => { let name = abi_name_attr .args .first() .unwrap() .get_string(&handler, abi_name_attr)?; Ok(Some((name.clone(), abi_name_attr.span.clone()))) } None => Ok(None), } } TypeInfo::Struct(decl_id) => { let struct_decl = engines.de().get_struct(&decl_id); match struct_decl.attributes.abi_name() { Some(abi_name_attr) => { let name = abi_name_attr .args .first() .unwrap() .get_string(&handler, abi_name_attr)?; Ok(Some((name.clone(), abi_name_attr.span.clone()))) } None => Ok(None), } } _ => Ok(None), } } fn get_abi_type_field_and_concrete_id( &self, handler: &Handler, ctx: &mut AbiContext, engines: &Engines, resolved_type_id: TypeId, ) -> Result<(String, ConcreteTypeId), ErrorEmitted> { let type_str = self.get_abi_type_str( handler, &AbiStrContext { program_name: ctx.program.namespace.current_package_name().to_string(), abi_with_callpaths: true, abi_with_fully_specified_types: true, abi_root_type_without_generic_type_parameters: false, }, engines, resolved_type_id, )?; let mut err: Option<ErrorEmitted> = None; // Right now ABI renaming is only supported for enum and struct types. let should_check_name = matches!( *engines.te().get(resolved_type_id), TypeInfo::Enum(_) | TypeInfo::Struct(_) ); if should_check_name { let (has_abi_name_attribute, name, attribute_span) = match Self::get_abi_name_and_span_from_type_id(engines, resolved_type_id)? { Some(res) => (true, res.0, res.1), None => (false, String::new(), Span::dummy()), }; let attribute_name_span = extract_abi_name_inner(&attribute_span).unwrap_or(attribute_span.clone()); let type_span = match *engines.te().get(resolved_type_id) { TypeInfo::Enum(decl_id) => engines.de().get_enum(&decl_id).name().span(), TypeInfo::Struct(decl_id) => engines.de().get_struct(&decl_id).name().span(), _ => unreachable!(), }; let insert_span = if has_abi_name_attribute { AbiNameDiagnosticSpan::Attribute(attribute_span.clone()) } else { AbiNameDiagnosticSpan::Type(type_span.clone()) }; let prev_span_opt = if ctx.unique_names.contains_key(&type_str) { ctx.unique_names.get(&type_str).cloned() } else { ctx.unique_names.insert(type_str.clone(), insert_span) }; if has_abi_name_attribute { if name.is_empty() || !is_valid_identifier_or_path(name.as_str()) || name.starts_with("::") { err = Some(handler.emit_err(CompileError::ABIInvalidName { span: attribute_name_span.clone(), name, })); } if let Some(prev_span) = prev_span_opt { let is_attribute = matches!(prev_span, AbiNameDiagnosticSpan::Attribute(_)); err = Some(handler.emit_err(CompileError::ABIDuplicateName { span: attribute_name_span.clone(), other_span: prev_span.span(), is_attribute, })); } } } let mut hasher = Sha256::new(); hasher.update(type_str.clone()); let result = hasher.finalize(); let type_id = format!("{result:x}"); if let Some(old_type_str) = ctx .type_ids_to_full_type_str .insert(type_id.clone(), type_str.clone()) { if old_type_str != type_str { err = Some( handler.emit_err(sway_error::error::CompileError::ABIHashCollision { span: Span::dummy(), hash: type_id.clone(), first_type: old_type_str, second_type: type_str.clone(), }), ); } } match err { Some(err) => Err(err), None => Ok((type_str, ConcreteTypeId(type_id))), } } } fn insert_unique_type(ctx: &mut AbiContext, name: String, span: Span) { let _ = ctx .unique_names .insert(name, AbiNameDiagnosticSpan::Type(span)); } fn process_type_name(ctx: &mut AbiContext, engines: &Engines, type_id: TypeId) { match &*engines.te().get(type_id) { TypeInfo::Enum(decl_id) => { let enum_decl = engines.de().get_enum(decl_id); insert_unique_type( ctx, format!("enum {}", enum_decl.name()), enum_decl.name().span(), ); } TypeInfo::Struct(decl_id) => { let struct_decl = engines.de().get_struct(decl_id); insert_unique_type( ctx, format!("struct {}", struct_decl.name()), struct_decl.name().span(), ); } TypeInfo::Alias { name: _, ty } => process_type_name(ctx, engines, ty.type_id), _ => {} } } fn process_type_names_from_function( ctx: &mut AbiContext, engines: &Engines, function: &TyFunctionDecl, ) { process_type_name(ctx, engines, function.return_type.type_id); for param in &function.parameters { process_type_name(ctx, engines, param.type_argument.type_id); } } pub fn generate_program_abi( handler: &Handler, ctx: &mut AbiContext, engines: &Engines, encoding_version: program_abi::Version, spec_version: program_abi::Version, ) -> Result<program_abi::ProgramABI, ErrorEmitted> { let decl_engine = engines.de(); let metadata_types: &mut Vec<program_abi::TypeMetadataDeclaration> = &mut vec![]; let concrete_types: &mut Vec<program_abi::TypeConcreteDeclaration> = &mut vec![]; match &ctx.program.kind { TyProgramKind::Contract { abi_entries, .. } => { abi_entries.iter().for_each(|x| { let fn_decl = decl_engine.get_function(x); process_type_names_from_function(ctx, engines, &fn_decl); }); } TyProgramKind::Script { main_function, .. } => { let main_function = decl_engine.get_function(main_function); process_type_names_from_function(ctx, engines, &main_function); } TyProgramKind::Predicate { main_function, .. } => { let main_function = decl_engine.get_function(main_function); process_type_names_from_function(ctx, engines, &main_function); } TyProgramKind::Library { .. } => {} }; let mut program_abi = handler.scope(|handler| match &ctx.program.kind { TyProgramKind::Contract { abi_entries, .. } => { let functions = abi_entries .iter() .map(|x| { let fn_decl = decl_engine.get_function(x); fn_decl.generate_abi_function( handler, ctx, engines, metadata_types, concrete_types, ) }) .collect::<Vec<_>>(); let logged_types = generate_logged_types(handler, ctx, engines, metadata_types, concrete_types)?; let messages_types = generate_messages_types(handler, ctx, engines, metadata_types, concrete_types)?; let configurables = generate_configurables(handler, ctx, engines, metadata_types, concrete_types)?; let error_codes = generate_error_codes(ctx.panic_occurrences); let panicking_calls = generate_panicking_calls(ctx.panicking_call_occurrences); Ok(program_abi::ProgramABI { program_type: "contract".to_string(), spec_version, encoding_version, metadata_types: metadata_types.to_vec(), concrete_types: concrete_types.to_vec(), functions: functions.into_iter().collect::<Result<Vec<_>, _>>()?, logged_types: Some(logged_types), messages_types: Some(messages_types), configurables: Some(configurables), error_codes: Some(error_codes), panicking_calls: Some(panicking_calls), }) } TyProgramKind::Script { main_function, .. } => { let main_function = decl_engine.get_function(main_function); let functions = vec![main_function.generate_abi_function( handler, ctx, engines, metadata_types, concrete_types, )?]; let logged_types = generate_logged_types(handler, ctx, engines, metadata_types, concrete_types)?; let messages_types = generate_messages_types(handler, ctx, engines, metadata_types, concrete_types)?; let configurables = generate_configurables(handler, ctx, engines, metadata_types, concrete_types)?; let error_codes = generate_error_codes(ctx.panic_occurrences); let panicking_calls = generate_panicking_calls(ctx.panicking_call_occurrences); Ok(program_abi::ProgramABI { program_type: "script".to_string(), spec_version, encoding_version, metadata_types: metadata_types.to_vec(), concrete_types: concrete_types.to_vec(), functions, logged_types: Some(logged_types), messages_types: Some(messages_types), configurables: Some(configurables), error_codes: Some(error_codes), panicking_calls: Some(panicking_calls), }) } TyProgramKind::Predicate { main_function, .. } => { let main_function = decl_engine.get_function(main_function); let functions = vec![main_function.generate_abi_function( handler, ctx, engines, metadata_types, concrete_types, )?]; let logged_types = generate_logged_types(handler, ctx, engines, metadata_types, concrete_types)?; let messages_types = generate_messages_types(handler, ctx, engines, metadata_types, concrete_types)?; let configurables = generate_configurables(handler, ctx, engines, metadata_types, concrete_types)?; let error_codes = generate_error_codes(ctx.panic_occurrences); let panicking_calls = generate_panicking_calls(ctx.panicking_call_occurrences); Ok(program_abi::ProgramABI { program_type: "predicate".to_string(), spec_version, encoding_version, metadata_types: metadata_types.to_vec(), concrete_types: concrete_types.to_vec(), functions, logged_types: Some(logged_types), messages_types: Some(messages_types), configurables: Some(configurables), error_codes: Some(error_codes), panicking_calls: Some(panicking_calls), }) } TyProgramKind::Library { .. } => { let logged_types = generate_logged_types(handler, ctx, engines, metadata_types, concrete_types)?; let messages_types = generate_messages_types(handler, ctx, engines, metadata_types, concrete_types)?; let error_codes = generate_error_codes(ctx.panic_occurrences); let panicking_calls = generate_panicking_calls(ctx.panicking_call_occurrences); Ok(program_abi::ProgramABI { program_type: "library".to_string(), spec_version, encoding_version, metadata_types: metadata_types.to_vec(), concrete_types: concrete_types.to_vec(), functions: vec![], logged_types: Some(logged_types), messages_types: Some(messages_types), configurables: None, error_codes: Some(error_codes), panicking_calls: Some(panicking_calls), }) } })?; standardize_json_abi_types(&mut program_abi); Ok(program_abi) } /// Standardize the JSON ABI data structure by eliminating duplicate types. This is an iterative /// process because every time two types are merged, new opportunities for more merging arise. fn standardize_json_abi_types(json_abi_program: &mut program_abi::ProgramABI) { // Dedup TypeMetadataDeclaration loop { // If type with id_1 is a duplicate of type with id_2, then keep track of the mapping // between id_1 and id_2 in the HashMap below. let mut old_to_new_id: HashMap<MetadataTypeId, program_abi::TypeId> = HashMap::new(); // A vector containing unique `program_abi::TypeMetadataDeclaration`s. // // Two `program_abi::TypeMetadataDeclaration` are deemed the same if the have the same // `type_field`, `components`, and `type_parameters` (even if their `type_id`s are // different). let mut deduped_types: Vec<program_abi::TypeMetadataDeclaration> = Vec::new(); // Insert values in `deduped_types` if they haven't been inserted before. Otherwise, create // an appropriate mapping between type IDs in the HashMap `old_to_new_id`. for decl in &json_abi_program.metadata_types { // First replace metadata_type_id with concrete_type_id when possible if let Some(ty) = json_abi_program.concrete_types.iter().find(|d| { d.type_field == decl.type_field && decl.components.is_none() && decl.type_parameters.is_none() }) { old_to_new_id.insert( decl.metadata_type_id.clone(), program_abi::TypeId::Concrete(ty.concrete_type_id.clone()), ); } else { // Second replace metadata_type_id with metadata_type_id when possible if let Some(ty) = deduped_types.iter().find(|d| { d.type_field == decl.type_field && d.components == decl.components && d.type_parameters == decl.type_parameters }) { old_to_new_id.insert( decl.metadata_type_id.clone(), program_abi::TypeId::Metadata(ty.metadata_type_id.clone()), ); } else { deduped_types.push(decl.clone()); } } } // Nothing to do if the hash map is empty as there are not merge opportunities. We can now // exit the loop. if old_to_new_id.is_empty() { break; } json_abi_program.metadata_types = deduped_types; update_all_types(json_abi_program, &old_to_new_id); } // Dedup TypeConcreteDeclaration let mut concrete_declarations_map: HashMap<ConcreteTypeId, TypeConcreteDeclaration> = HashMap::new(); for decl in &json_abi_program.concrete_types { concrete_declarations_map.insert(decl.concrete_type_id.clone(), decl.clone()); } json_abi_program.concrete_types = concrete_declarations_map.values().cloned().collect(); // Sort the `program_abi::TypeMetadataDeclaration`s json_abi_program .metadata_types .sort_by(|t1, t2| t1.type_field.cmp(&t2.type_field)); // Sort the `program_abi::TypeConcreteDeclaration`s json_abi_program .concrete_types .sort_by(|t1, t2| t1.type_field.cmp(&t2.type_field)); // Standardize IDs (i.e. change them to 0,1,2,... according to the alphabetical order above let mut old_to_new_id: HashMap<MetadataTypeId, program_abi::TypeId> = HashMap::new(); for (ix, decl) in json_abi_program.metadata_types.iter_mut().enumerate() { old_to_new_id.insert( decl.metadata_type_id.clone(), program_abi::TypeId::Metadata(MetadataTypeId(ix)), ); decl.metadata_type_id = MetadataTypeId(ix); } update_all_types(json_abi_program, &old_to_new_id); } /// Recursively updates the type IDs used in a program_abi::ProgramABI fn update_all_types( json_abi_program: &mut program_abi::ProgramABI, old_to_new_id: &HashMap<MetadataTypeId, program_abi::TypeId>, ) { // Update all `program_abi::TypeMetadataDeclaration` for decl in &mut json_abi_program.metadata_types { update_json_type_metadata_declaration(decl, old_to_new_id); } // Update all `program_abi::TypeConcreteDeclaration` for decl in &mut json_abi_program.concrete_types { update_json_type_concrete_declaration(decl, old_to_new_id); } } /// Recursively updates the type IDs used in a `program_abi::TypeApplication` given a HashMap from /// old to new IDs fn update_json_type_application( type_application: &mut program_abi::TypeApplication, old_to_new_id: &HashMap<MetadataTypeId, program_abi::TypeId>, ) { if let fuel_abi_types::abi::program::TypeId::Metadata(metadata_type_id) = &type_application.type_id { if let Some(new_id) = old_to_new_id.get(metadata_type_id) { type_application.type_id = new_id.clone(); } } if let Some(args) = &mut type_application.type_arguments { for arg in args.iter_mut() { update_json_type_application(arg, old_to_new_id); } } } /// Recursively updates the metadata type IDs used in a `program_abi::TypeMetadataDeclaration` given a HashMap from /// old to new IDs fn update_json_type_metadata_declaration( type_declaration: &mut program_abi::TypeMetadataDeclaration, old_to_new_id: &HashMap<MetadataTypeId, program_abi::TypeId>, ) { if let Some(params) = &mut type_declaration.type_parameters { for param in params.iter_mut() { if let Some(fuel_abi_types::abi::program::TypeId::Metadata(new_id)) = old_to_new_id.get(param) { *param = new_id.clone(); } } } if let Some(components) = &mut type_declaration.components { for component in components.iter_mut() { update_json_type_application(component, old_to_new_id); } } } /// Updates the metadata type IDs used in a `program_abi::TypeConcreteDeclaration` given a HashMap from /// old to new IDs fn update_json_type_concrete_declaration( type_declaration: &mut program_abi::TypeConcreteDeclaration, old_to_new_id: &HashMap<MetadataTypeId, program_abi::TypeId>, ) { if let Some(metadata_type_id) = &mut type_declaration.metadata_type_id { if let Some(fuel_abi_types::abi::program::TypeId::Metadata(new_id)) = old_to_new_id.get(metadata_type_id) { *metadata_type_id = new_id.clone(); } } } fn generate_concrete_type_declaration( handler: &Handler, ctx: &mut AbiContext, engines: &Engines, metadata_types: &mut Vec<program_abi::TypeMetadataDeclaration>, concrete_types: &mut Vec<program_abi::TypeConcreteDeclaration>, type_id: TypeId, resolved_type_id: TypeId, ) -> Result<ConcreteTypeId, ErrorEmitted> { let mut new_metadata_types_to_add = Vec::<program_abi::TypeMetadataDeclaration>::new(); let type_metadata_decl = program_abi::TypeMetadataDeclaration { metadata_type_id: MetadataTypeId(type_id.index()), type_field: type_id.get_abi_type_str( handler, &ctx.to_str_context(), engines, resolved_type_id, )?, components: type_id.get_abi_type_components( handler, ctx, engines, metadata_types, concrete_types, resolved_type_id, &mut new_metadata_types_to_add, )?, type_parameters: type_id.get_abi_type_parameters( handler, ctx, engines, metadata_types, concrete_types, resolved_type_id, &mut new_metadata_types_to_add, )?, }; let metadata_type_id = if type_metadata_decl.type_parameters.is_some() || type_metadata_decl.components.is_some() { Some(type_metadata_decl.metadata_type_id.clone()) } else { None }; let type_arguments = handler.scope(|handler| { let type_arguments = if type_metadata_decl.type_parameters.is_some() { type_id.get_abi_type_arguments_as_concrete_type_ids( handler, ctx, engines, metadata_types, concrete_types, resolved_type_id, )? } else { None }; Ok(type_arguments) })?; metadata_types.push(type_metadata_decl); metadata_types.extend(new_metadata_types_to_add); let (type_field, concrete_type_id) = type_id.get_abi_type_field_and_concrete_id(handler, ctx, engines, resolved_type_id)?; let concrete_type_decl = TypeConcreteDeclaration { type_field, concrete_type_id: concrete_type_id.clone(), metadata_type_id, type_arguments, alias_of: None, }; concrete_types.push(concrete_type_decl); Ok(concrete_type_id) } #[allow(clippy::too_many_arguments)] fn generate_type_metadata_declaration( handler: &Handler, ctx: &mut AbiContext, engines: &Engines, metadata_types: &mut Vec<program_abi::TypeMetadataDeclaration>, concrete_types: &mut Vec<program_abi::TypeConcreteDeclaration>, type_id: TypeId, resolved_type_id: TypeId, metadata_types_to_add: &mut Vec<program_abi::TypeMetadataDeclaration>, ) -> Result<(), ErrorEmitted> { let mut new_metadata_types_to_add = Vec::<program_abi::TypeMetadataDeclaration>::new(); let components = type_id.get_abi_type_components( handler, ctx, engines, metadata_types, concrete_types, resolved_type_id, &mut new_metadata_types_to_add, )?; let type_parameters = type_id.get_abi_type_parameters( handler, ctx, engines, metadata_types, concrete_types, resolved_type_id, &mut new_metadata_types_to_add, )?; let type_metadata_decl = program_abi::TypeMetadataDeclaration { metadata_type_id: MetadataTypeId(type_id.index()), type_field: type_id.get_abi_type_str( handler, &ctx.to_str_context(), engines, resolved_type_id, )?, components, type_parameters, }; metadata_types_to_add.push(type_metadata_decl.clone()); metadata_types_to_add.extend(new_metadata_types_to_add); Ok(()) } fn generate_logged_types( handler: &Handler, ctx: &mut AbiContext, engines: &Engines, metadata_types: &mut Vec<program_abi::TypeMetadataDeclaration>, concrete_types: &mut Vec<program_abi::TypeConcreteDeclaration>, ) -> Result<Vec<program_abi::LoggedType>, ErrorEmitted> { // Generate the JSON data for the logged types let mut log_ids: HashSet<u64> = HashSet::default(); Ok(ctx .program .logged_types .iter() .map(|(log_id, type_id)| { let log_id = log_id.hash_id; if log_ids.contains(&log_id) { Ok(None) } else { log_ids.insert(log_id); Ok(Some(program_abi::LoggedType { log_id: log_id.to_string(), concrete_type_id: generate_concrete_type_declaration( handler, ctx, engines, metadata_types, concrete_types, *type_id, *type_id, )?, })) } }) .collect::<Result<Vec<_>, _>>()? .into_iter() .flatten() .collect()) } fn generate_messages_types( handler: &Handler, ctx: &mut AbiContext, engines: &Engines, metadata_types: &mut Vec<program_abi::TypeMetadataDeclaration>, concrete_types: &mut Vec<program_abi::TypeConcreteDeclaration>, ) -> Result<Vec<program_abi::MessageType>, ErrorEmitted> { // Generate the JSON data for the messages types ctx.program .messages_types .iter() .map(|(message_id, type_id)| { Ok(program_abi::MessageType { message_id: (**message_id as u64).to_string(), concrete_type_id: generate_concrete_type_declaration( handler, ctx, engines, metadata_types, concrete_types, *type_id, *type_id, )?, }) }) .collect::<Result<Vec<_>, _>>() } fn generate_configurables( handler: &Handler, ctx: &mut AbiContext, engines: &Engines, metadata_types: &mut Vec<program_abi::TypeMetadataDeclaration>, concrete_types: &mut Vec<program_abi::TypeConcreteDeclaration>, ) -> Result<Vec<program_abi::Configurable>, ErrorEmitted> { // Generate the JSON data for the configurables types ctx.program .configurables .iter() .map(|decl| { Ok(program_abi::Configurable { name: decl.call_path.suffix.to_string(), concrete_type_id: generate_concrete_type_declaration( handler, ctx, engines, metadata_types, concrete_types, decl.type_ascription.type_id, decl.type_ascription.type_id, )?, offset: 0, indirect: false, }) }) .collect::<Result<Vec<_>, _>>() } fn generate_error_codes(panic_occurrences: &PanicOccurrences) -> BTreeMap<u64, ErrorDetails> { panic_occurrences .iter() .map(|(panic_occurrence, &panic_error_code)| { ( panic_error_code, ErrorDetails { pos: ErrorPosition { function: panic_occurrence.function.clone(), pkg: panic_occurrence.loc.pkg.clone(), file: panic_occurrence.loc.file.clone(), line: panic_occurrence.loc.loc.line as u64, column: panic_occurrence.loc.loc.col as u64, }, log_id: panic_occurrence .log_id .map(|log_id| log_id.hash_id.to_string()), msg: panic_occurrence.msg.clone(), }, ) }) .collect() } fn generate_panicking_calls( panicking_call_occurrences: &PanickingCallOccurrences, ) -> BTreeMap<u64, PanickingCall> { panicking_call_occurrences .iter() .map(|(panicking_call_occurrence, panicking_call_id)| { ( *panicking_call_id, PanickingCall { pos: ErrorPosition { function: panicking_call_occurrence.caller_function.clone(), pkg: panicking_call_occurrence.loc.pkg.clone(), file: panicking_call_occurrence.loc.file.clone(), line: panicking_call_occurrence.loc.loc.line as u64, column: panicking_call_occurrence.loc.loc.col as u64, }, function: panicking_call_occurrence.function.clone(), }, ) }) .collect() } impl TypeId { /// Return the type parameters of a given (potentially generic) type while considering what it /// actually resolves to. These parameters are essentially of type of `usize` which are /// basically the IDs of some set of `program_abi::TypeMetadataDeclaration`s. The method below also /// updates the provide list of `program_abi::TypeMetadataDeclaration`s to add the newly discovered /// types. #[allow(clippy::too_many_arguments)] pub(self) fn get_abi_type_parameters( &self, handler: &Handler,
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/transform/attribute.rs
sway-core/src/transform/attribute.rs
//! Each item may have a list of attributes, each with a name and a list of zero or more args. //! Attributes may be specified more than once in which case we use the union of their args. //! //! E.g., //! //! ```ignore //! #[foo(bar)] //! #[foo(baz, xyzzy)] //! ``` //! //! is essentially equivalent to //! //! ```ignore //! #[foo(bar, baz, xyzzy)] //! ``` //! //! and duplicates like //! //! ```ignore //! #[foo(bar)] //! #[foo(bar)] //! ``` //! //! are equivalent to //! //! ```ignore //! #[foo(bar, bar)] //! ``` //! //! Attribute args can have values: //! //! ```ignore //! #[foo(bar = "some value", baz = true)] //! ``` //! //! All attributes have the following common properties: //! - targets: items that they can annotate. E.g., `#[inline]` can annotate only functions. //! - multiplicity: if they can be applied multiple time on an item. E.g., `#[inline]` can //! be applied only once, but `#[cfg]` multiple times. //! - arguments multiplicity: how many arguments they can have. //! - arguments expectance: which arguments are expected and accepted as valid. //! //! All attribute arguments have the following common properties: //! - value expectance: if they must have values specified. //! //! Individual arguments might impose their own additional constraints. use indexmap::IndexMap; use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::{hash::Hash, sync::Arc}; use sway_ast::{ attribute::*, AttributeDecl, ImplItemParent, ItemImplItem, ItemKind, ItemTraitItem, Literal, }; use sway_error::{ convert_parse_tree_error::ConvertParseTreeError, handler::{ErrorEmitted, Handler}, }; use sway_features::Feature; use sway_types::{Ident, Span, Spanned}; use crate::language::{Inline, Purity, Trace}; #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct AttributeArg { pub name: Ident, pub value: Option<Literal>, pub span: Span, } impl AttributeArg { /// Returns a mandatory [String] value from `self`, /// or an error if the value does not exist or is not of type [String]. /// /// `attribute` is the parent [Attribute] of `self`. pub fn get_string( &self, handler: &Handler, attribute: &Attribute, ) -> Result<&String, ErrorEmitted> { match &self.value { Some(literal) => match literal { Literal::String(lit_string) => Ok(&lit_string.parsed), _ => Err(handler.emit_err( ConvertParseTreeError::InvalidAttributeArgValueType { span: literal.span(), arg: self.name.clone(), expected_type: "str", received_type: literal.friendly_type_name(), } .into(), )), }, None => Err(handler.emit_err( ConvertParseTreeError::InvalidAttributeArgExpectsValue { attribute: attribute.name.clone(), arg: (&self.name).into(), value_span: None, } .into(), )), } } /// Returns an optional [String] value from `self`, /// or an error if the value exists but is not of type [String]. pub fn get_string_opt(&self, handler: &Handler) -> Result<Option<&String>, ErrorEmitted> { match &self.value { Some(literal) => match literal { Literal::String(lit_string) => Ok(Some(&lit_string.parsed)), _ => Err(handler.emit_err( ConvertParseTreeError::InvalidAttributeArgValueType { span: literal.span(), arg: self.name.clone(), expected_type: "str", received_type: literal.friendly_type_name(), } .into(), )), }, None => Ok(None), } } /// Returns a mandatory `bool` value from `self`, /// or an error if the value does not exist or is not of type `bool`. /// /// `attribute` is the parent [Attribute] of `self`. pub fn get_bool(&self, handler: &Handler, attribute: &Attribute) -> Result<bool, ErrorEmitted> { match &self.value { Some(literal) => match literal { Literal::Bool(lit_bool) => Ok(lit_bool.kind.into()), _ => Err(handler.emit_err( ConvertParseTreeError::InvalidAttributeArgValueType { span: literal.span(), arg: self.name.clone(), expected_type: "bool", received_type: literal.friendly_type_name(), } .into(), )), }, None => Err(handler.emit_err( ConvertParseTreeError::InvalidAttributeArgExpectsValue { attribute: attribute.name.clone(), arg: (&self.name).into(), value_span: None, } .into(), )), } } pub fn is_allow_dead_code(&self) -> bool { self.name.as_str() == ALLOW_DEAD_CODE_ARG_NAME } pub fn is_allow_deprecated(&self) -> bool { self.name.as_str() == ALLOW_DEPRECATED_ARG_NAME } pub fn is_cfg_target(&self) -> bool { self.name.as_str() == CFG_TARGET_ARG_NAME } pub fn is_cfg_program_type(&self) -> bool { self.name.as_str() == CFG_PROGRAM_TYPE_ARG_NAME } pub fn is_cfg_experimental(&self) -> bool { Feature::CFG.contains(&self.name.as_str()) } pub fn is_deprecated_note(&self) -> bool { self.name.as_str() == DEPRECATED_NOTE_ARG_NAME } pub fn is_test_should_revert(&self) -> bool { self.name.as_str() == TEST_SHOULD_REVERT_ARG_NAME } pub fn is_error_message(&self) -> bool { self.name.as_str() == ERROR_M_ARG_NAME } } impl Spanned for AttributeArg { fn span(&self) -> Span { self.span.clone() } } // TODO: Currently we do not support arbitrary inner attributes. // Only compiler-generated `doc-comment` attributes for `//!` // can currently be inner attributes. // All of the below properties assume we are inspecting // outer attributes. // Extend the infrastructure for attribute properties to // support inner attributes, once we fully support them. // See: https://github.com/FuelLabs/sway/issues/6924 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct Attribute { /// Attribute direction, taken from the enclosing [crate::AttributeDecl]. /// All attributes within the same [crate::AttributeDecl] will have the /// same direction. pub direction: AttributeDirection, pub name: Ident, pub args: Vec<AttributeArg>, pub span: Span, pub kind: AttributeKind, } #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum AttributeDirection { Inner, Outer, } impl From<&AttributeHashKind> for AttributeDirection { fn from(value: &AttributeHashKind) -> Self { match value { AttributeHashKind::Inner(_) => Self::Inner, AttributeHashKind::Outer(_) => Self::Outer, } } } /// Defines the minimum and the maximum number of [AttributeArg]s /// that an [Attribute] can have. pub struct ArgsMultiplicity { min: usize, max: usize, } impl ArgsMultiplicity { pub fn zero() -> Self { Self { min: 0, max: 0 } } pub fn arbitrary() -> Self { Self { min: 0, max: usize::MAX, } } pub fn exactly(num: usize) -> Self { Self { min: num, max: num } } pub fn at_least(num: usize) -> Self { Self { min: num, max: usize::MAX, } } pub fn at_most(num: usize) -> Self { Self { min: 0, max: num } } pub fn between(min: usize, max: usize) -> Self { assert!( min <= max, "min must be less than or equal to max; min was {min}, max was {max}" ); Self { min, max } } pub fn contains(&self, value: usize) -> bool { self.min <= value && value <= self.max } } impl From<&ArgsMultiplicity> for (usize, usize) { fn from(value: &ArgsMultiplicity) -> Self { (value.min, value.max) } } /// Defines which [AttributeArg]s an [Attribute] expects. pub enum ExpectedArgs { /// The [Attribute] does not expect any [AttributeArg]s. None, /// The [Attribute] can accept any argument. The `doc-comment` /// attribute is such an attribute - every documentation line /// becomes an [AttributeArg] and is accepted as valid. Any, /// An [AttributeArg::name] **must be** one from the provided list. /// If it is not, an error will be emitted. MustBeIn(Vec<&'static str>), /// An [AttributeArg::name] **should be** one from the provided list. /// If it is not, a warning will be emitted. ShouldBeIn(Vec<&'static str>), } impl ExpectedArgs { /// Returns expected argument names, if any specific names are /// expected, or an empty [Vec] if no names are expected or /// if the [Attribute] can accept any argument name. pub(crate) fn args_names(&self) -> Vec<&'static str> { match self { ExpectedArgs::None | ExpectedArgs::Any => vec![], ExpectedArgs::MustBeIn(expected_args) | ExpectedArgs::ShouldBeIn(expected_args) => { expected_args.clone() } } } } /// Defines if [AttributeArg]s within the same [Attribute] /// can or must have a value specified. /// /// E.g., `#[attribute(arg = <value>)`. /// /// We consider the expected types of individual values not to be /// the part of the [AttributeArg]'s metadata. Final consumers of /// the attribute will check for the expected type and emit an error /// if a wrong type is provided. /// /// E.g., `#[cfg(target = 42)]` will emit an error during the /// cfg-evaluation. pub enum ArgsExpectValues { /// Each argument, if any, must have a value specified. /// Specified values can be of different types. /// /// E.g.: `#[cfg(target = "fuel", experimental_new_encoding = false)]`. Yes, /// None of the arguments can have values specified, or the /// [Attribute] does not expect any arguments. /// /// E.g.: `#[storage(read, write)]`, `#[fallback]`. No, /// Each argument, if any, can have a value specified, but must not /// necessarily have one. /// /// E.g.: `#[some_attribute(arg_1 = 5, arg_2)]`. Maybe, } /// Kinds of attributes supported by the compiler. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] pub enum AttributeKind { /// Represents an [Attribute] unknown to the compiler. /// We generate warnings for such attributes but in /// general support them and pass them to the typed /// tree. This allows third-party static analysis to /// utilized proprietary attributes and inspect them /// in the typed tree. Unknown, DocComment, Storage, Inline, Test, Payable, Allow, Cfg, Deprecated, Fallback, ErrorType, Error, Trace, AbiName, Event, Indexed, } /// Denotes if an [ItemTraitItem] belongs to an ABI or to a trait. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TraitItemParent { Abi, Trait, } /// Denotes if a [sway_ast::TypeField] belongs to a struct or to an enum. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StructOrEnumField { StructField, EnumField, } impl AttributeKind { pub fn from_attribute_name(name: &str) -> Self { match name { DOC_COMMENT_ATTRIBUTE_NAME => AttributeKind::DocComment, STORAGE_ATTRIBUTE_NAME => AttributeKind::Storage, INLINE_ATTRIBUTE_NAME => AttributeKind::Inline, TEST_ATTRIBUTE_NAME => AttributeKind::Test, PAYABLE_ATTRIBUTE_NAME => AttributeKind::Payable, ALLOW_ATTRIBUTE_NAME => AttributeKind::Allow, CFG_ATTRIBUTE_NAME => AttributeKind::Cfg, DEPRECATED_ATTRIBUTE_NAME => AttributeKind::Deprecated, FALLBACK_ATTRIBUTE_NAME => AttributeKind::Fallback, ERROR_TYPE_ATTRIBUTE_NAME => AttributeKind::ErrorType, ERROR_ATTRIBUTE_NAME => AttributeKind::Error, TRACE_ATTRIBUTE_NAME => AttributeKind::Trace, ABI_NAME_ATTRIBUTE_NAME => AttributeKind::AbiName, EVENT_ATTRIBUTE_NAME => AttributeKind::Event, INDEXED_ATTRIBUTE_NAME => AttributeKind::Indexed, _ => AttributeKind::Unknown, } } /// True if multiple attributes of a this [AttributeKind] can /// annotate the same item at the same time. E.g., the `inline` /// attribute can be applied only once on an item and does not /// allow multiple, while the `cfg` attribute can be applied /// arbitrary many times. /// /// Currently we assume that the multiplicity does not depend /// on the annotated item, but is an inherent property of /// the [AttributeKind]. pub fn allows_multiple(&self) -> bool { use AttributeKind::*; match self { Unknown => true, DocComment => true, Storage => false, Inline => false, Test => false, Payable => false, Allow => true, Cfg => true, Deprecated => false, Fallback => false, ErrorType => false, Error => false, Trace => false, AbiName => false, Event => false, Indexed => false, } } } impl Attribute { pub fn is_doc_comment(&self) -> bool { self.kind == AttributeKind::DocComment } pub fn is_inner(&self) -> bool { self.direction == AttributeDirection::Inner } pub fn is_outer(&self) -> bool { self.direction == AttributeDirection::Outer } pub(crate) fn args_multiplicity(&self) -> ArgsMultiplicity { use ArgsMultiplicity as Multiplicity; use AttributeKind::*; match self.kind { Unknown => Multiplicity::arbitrary(), // Each `doc-comment` attribute contains exactly one argument // whose name is the actual documentation text and whose value is `None`. // Thus, we expect exactly one argument. DocComment => Multiplicity::exactly(1), // `storage(read, write)`. Storage => Multiplicity::between(1, 2), // `inline(never)` or `inline(always)`. Inline => Multiplicity::exactly(1), // `test`, `test(should_revert)`. Test => Multiplicity::at_most(1), Payable => Multiplicity::zero(), Allow => Multiplicity::at_least(1), Cfg => Multiplicity::exactly(1), // `deprecated`, `deprecated(note = "note")`. Deprecated => Multiplicity::at_most(1), Fallback => Multiplicity::zero(), ErrorType => Multiplicity::zero(), Error => Multiplicity::exactly(1), // `trace(never)` or `trace(always)`. Trace => Multiplicity::exactly(1), AbiName => Multiplicity::exactly(1), Event => Multiplicity::zero(), Indexed => Multiplicity::zero(), } } pub(crate) fn check_args_multiplicity(&self, handler: &Handler) -> Result<(), ErrorEmitted> { if !self.args_multiplicity().contains(self.args.len()) { Err(handler.emit_err( ConvertParseTreeError::InvalidAttributeArgsMultiplicity { span: if self.args.is_empty() { self.name.span() } else { Span::join( self.args.first().unwrap().span(), &self.args.last().unwrap().span, ) }, attribute: self.name.clone(), args_multiplicity: (&self.args_multiplicity()).into(), num_of_args: self.args.len(), } .into(), )) } else { Ok(()) } } pub(crate) fn can_have_arguments(&self) -> bool { let args_multiplicity = self.args_multiplicity(); args_multiplicity.min != 0 || args_multiplicity.max != 0 } pub(crate) fn expected_args(&self) -> ExpectedArgs { use AttributeKind::*; use ExpectedArgs::*; match self.kind { Unknown => Any, DocComment => Any, Storage => MustBeIn(vec![STORAGE_READ_ARG_NAME, STORAGE_WRITE_ARG_NAME]), Inline => MustBeIn(vec![INLINE_ALWAYS_ARG_NAME, INLINE_NEVER_ARG_NAME]), Test => MustBeIn(vec![TEST_SHOULD_REVERT_ARG_NAME]), Payable => None, Allow => ShouldBeIn(vec![ALLOW_DEAD_CODE_ARG_NAME, ALLOW_DEPRECATED_ARG_NAME]), Cfg => { let mut args = vec![ // Arguments, ordered alphabetically. CFG_PROGRAM_TYPE_ARG_NAME, CFG_TARGET_ARG_NAME, ]; args.extend(Feature::CFG.iter().sorted()); MustBeIn(args) } Deprecated => MustBeIn(vec![DEPRECATED_NOTE_ARG_NAME]), Fallback => None, ErrorType => None, Error => MustBeIn(vec![ERROR_M_ARG_NAME]), Trace => MustBeIn(vec![TRACE_ALWAYS_ARG_NAME, TRACE_NEVER_ARG_NAME]), AbiName => MustBeIn(vec![ABI_NAME_NAME_ARG_NAME]), Event => None, Indexed => None, } } pub(crate) fn args_expect_values(&self) -> ArgsExpectValues { use ArgsExpectValues::*; use AttributeKind::*; match self.kind { Unknown => Maybe, // The actual documentation line is in the name of the attribute. DocComment => No, Storage => No, Inline => No, // `test(should_revert)`, `test(should_revert = "18446744073709486084")`. Test => Maybe, Payable => No, Allow => No, Cfg => Yes, // `deprecated(note = "note")`. Deprecated => Yes, Fallback => No, ErrorType => No, // `error(msg = "msg")`. Error => Yes, Trace => No, AbiName => Yes, Event => No, Indexed => No, } } pub(crate) fn can_annotate_module_kind(&self) -> bool { use AttributeKind::*; match self.kind { Unknown => false, DocComment => self.direction == AttributeDirection::Inner, Storage => false, Inline => false, Test => false, Payable => false, Allow => false, Cfg => false, // TODO: Change to true once https://github.com/FuelLabs/sway/issues/6942 is implemented. // Deprecating the module kind will mean deprecating all its items. Deprecated => false, Fallback => false, ErrorType => false, Error => false, Trace => false, AbiName => false, Event => false, Indexed => false, } } pub(crate) fn can_annotate_item_kind(&self, item_kind: &ItemKind) -> bool { // TODO: Except for `DocComment`, we assume outer annotation here. // A separate check emits not-implemented error for all inner attributes. // Until we fully support inner attributes, this approach is sufficient. // See: https://github.com/FuelLabs/sway/issues/6924 // TODO: Currently we do not support any attributes on `mod`s, including doc comments. // See: https://github.com/FuelLabs/sway/issues/6879 // See: https://github.com/FuelLabs/sway/issues/6925 // We accept all attribute kinds on the `ItemKind::Error`. if matches!(item_kind, ItemKind::Error(..)) { return true; } use AttributeKind::*; match self.kind { Unknown => !matches!(item_kind, ItemKind::Submodule(_)), // We allow doc comments on all items including `storage` and `configurable`. DocComment => { self.direction == AttributeDirection::Outer && !matches!(item_kind, ItemKind::Submodule(_)) } Storage => matches!(item_kind, ItemKind::Fn(_)), Inline => matches!(item_kind, ItemKind::Fn(_)), Test => matches!(item_kind, ItemKind::Fn(_)), Payable => false, Allow => !matches!(item_kind, ItemKind::Submodule(_)), Cfg => !matches!(item_kind, ItemKind::Submodule(_)), // TODO: Adapt once https://github.com/FuelLabs/sway/issues/6942 is implemented. Deprecated => match item_kind { ItemKind::Submodule(_) => false, ItemKind::Use(_) => false, ItemKind::Struct(_) => true, ItemKind::Enum(_) => true, ItemKind::Fn(_) => true, ItemKind::Trait(_) => false, ItemKind::Impl(_) => false, ItemKind::Abi(_) => false, ItemKind::Const(_) => true, ItemKind::Storage(_) => false, // TODO: Currently, only single configurables can be deprecated. // Change to true once https://github.com/FuelLabs/sway/issues/6942 is implemented. ItemKind::Configurable(_) => false, ItemKind::TypeAlias(_) => false, ItemKind::Error(_, _) => true, }, Fallback => matches!(item_kind, ItemKind::Fn(_)), ErrorType => matches!(item_kind, ItemKind::Enum(_)), Error => false, Trace => matches!(item_kind, ItemKind::Fn(_)), AbiName => matches!(item_kind, ItemKind::Struct(_) | ItemKind::Enum(_)), Event => matches!(item_kind, ItemKind::Struct(_) | ItemKind::Enum(_)), Indexed => false, } } // TODO: Add `can_annotated_nested_item_kind`, once we properly support nested items. // E.g., the `#[test]` attribute can annotate module functions (`ItemKind::Fn`), // but will not be allowed on nested functions. pub(crate) fn can_annotate_struct_or_enum_field( &self, struct_or_enum_field: StructOrEnumField, ) -> bool { use AttributeKind::*; match self.kind { Unknown => true, DocComment => self.direction == AttributeDirection::Outer, Storage => false, Inline => false, Test => false, Payable => false, Allow => true, Cfg => true, Deprecated => true, Fallback => false, ErrorType => false, Error => struct_or_enum_field == StructOrEnumField::EnumField, Trace => false, AbiName => false, Event => false, Indexed => matches!(struct_or_enum_field, StructOrEnumField::StructField), } } pub(crate) fn can_annotate_abi_or_trait_item( &self, item: &ItemTraitItem, parent: TraitItemParent, ) -> bool { use AttributeKind::*; match self.kind { Unknown => true, DocComment => self.direction == AttributeDirection::Outer, Storage => matches!(item, ItemTraitItem::Fn(..)), // Functions in the trait or ABI interface surface cannot be marked as inlined // because they don't have implementation. Inline => false, Test => false, Payable => parent == TraitItemParent::Abi && matches!(item, ItemTraitItem::Fn(..)), Allow => true, Cfg => true, // TODO: Change to true once https://github.com/FuelLabs/sway/issues/6942 is implemented. Deprecated => false, Fallback => false, ErrorType => false, Error => false, // Functions in the trait or ABI interface surface cannot be marked as traced // because they don't have implementation. Trace => false, AbiName => false, Event => false, Indexed => false, } } pub(crate) fn can_annotate_impl_item( &self, item: &ItemImplItem, parent: ImplItemParent, ) -> bool { use AttributeKind::*; match self.kind { Unknown => true, DocComment => self.direction == AttributeDirection::Outer, Storage => matches!(item, ItemImplItem::Fn(..)), Inline => matches!(item, ItemImplItem::Fn(..)), Test => false, Payable => parent == ImplItemParent::Contract, Allow => true, Cfg => true, Deprecated => !matches!(item, ItemImplItem::Type(_)), Fallback => false, ErrorType => false, Error => false, Trace => matches!(item, ItemImplItem::Fn(..)), AbiName => false, Event => false, Indexed => false, } } pub(crate) fn can_annotate_abi_or_trait_item_fn( &self, abi_or_trait_item: TraitItemParent, ) -> bool { use AttributeKind::*; match self.kind { Unknown => true, DocComment => self.direction == AttributeDirection::Outer, Storage => true, Inline => true, Test => false, Payable => abi_or_trait_item == TraitItemParent::Abi, Allow => true, Cfg => true, Deprecated => true, Fallback => false, ErrorType => false, Error => false, Trace => true, AbiName => false, Event => false, Indexed => false, } } pub(crate) fn can_annotate_storage_entry(&self) -> bool { use AttributeKind::*; match self.kind { Unknown => true, DocComment => self.direction == AttributeDirection::Outer, Storage => false, Inline => false, Test => false, Payable => false, Allow => true, Cfg => true, // TODO: Change to true once https://github.com/FuelLabs/sway/issues/6942 is implemented. Deprecated => false, Fallback => false, ErrorType => false, Error => false, Trace => false, AbiName => false, Event => false, Indexed => false, } } pub(crate) fn can_annotate_configurable_field(&self) -> bool { use AttributeKind::*; match self.kind { Unknown => true, DocComment => self.direction == AttributeDirection::Outer, Storage => false, Inline => false, Test => false, Payable => false, Allow => true, Cfg => true, Deprecated => true, Fallback => false, ErrorType => false, Error => false, Trace => false, AbiName => false, Event => false, Indexed => false, } } pub(crate) fn can_only_annotate_help(&self, target_friendly_name: &str) -> Vec<&'static str> { // Using strings to identify targets is not ideal, but there // is no real need for a more complex and type-safe identification here. use AttributeKind::*; let help = match self.kind { Unknown => vec![], DocComment => match self.direction { AttributeDirection::Inner => vec![ "Inner doc comments (`//!`) can only document modules and must be", "at the beginning of the module file, before the module kind.", ], AttributeDirection::Outer => if target_friendly_name.starts_with("module kind") { vec![ "To document modules, use inner doc comments (`//!`). E.g.:", "//! This doc comment documents a module.", ] } else { vec![] }, }, Storage => { if target_friendly_name == "function signature" { vec![ "\"storage\" attribute can only annotate functions that have an implementation.", "Function signatures in ABI and trait declarations do not have implementations.", ] } else { vec![ "\"storage\" attribute can only annotate functions.", ] } }, Inline => vec!["\"inline\" attribute can only annotate functions."], Test => vec!["\"test\" attribute can only annotate module functions."], Payable => vec![ "\"payable\" attribute can only annotate:", " - ABI function signatures and their implementations in contracts,", " - provided ABI functions.", ], Allow => vec![], Cfg => vec![], // TODO: Remove this help lines once https://github.com/FuelLabs/sway/issues/6942 is implemented. Deprecated => vec![ "\"deprecated\" attribute is currently not implemented for all elements that could be deprecated.", ], Fallback => vec!["\"fallback\" attribute can only annotate module functions in a contract module."], ErrorType => vec!["\"error_type\" attribute can only annotate enums."], Error => vec!["\"error\" attribute can only annotate enum variants of enums annotated with the \"error_type\" attribute."], Trace => vec!["\"trace\" attribute can only annotate functions."], AbiName => vec![ "\"abi_name\" attribute can only annotate structs and enums.", ], Event => vec![ "\"event\" attribute can only annotate structs or enums.", ], Indexed => vec![ "\"indexed\" attribute can only annotate struct fields.", ], }; if help.is_empty() && target_friendly_name.starts_with("module kind") { vec!["Annotating module kinds (contract, script, predicate, or library) is currently not implemented."] } else { help } } } /// Stores the [Attribute]s that annotate an element. /// /// Note that once stored in the [Attributes], the [Attribute]s lose /// the information about their enclosing [AttributeDecl]. /// /// The map can contain erroneous attributes. A typical example s containing /// several attributes of an [AttributeKind] that allows only a single attribute /// to be applied, like, e.g., `#[deprecated]`, or `#[test]`. /// /// When retrieving such attributes, we follow the last-wins approach /// and return the last attribute in the order of declaration. #[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct Attributes { // Note that we don't need a map here, to store attributes because: // - Attributes will mostly be empty. // - Per `AttributeKind` there will usually be just one element. // - The only exception are comments, that anyhow need to be traversed sequentially // and will dominate in the list of attributes or mostly be the only attributes. // - Most of the analysis requires traversing all attributes regardless of the `AttributeKind`. // - Analysis that is interested in `AttributeKind` anyhow needs to apply a filter first. // - Attributes are accessed only once, when checking the declaration of the annotated element. /// [Attribute]s, in the order of their declaration. attributes: Arc<Vec<Attribute>>, // `#[deprecated]` is the only attribute requested on call sites, // and we provide a O(1) access to it. /// The index of the last `#[deprecated]` attribute, if any. deprecated_attr_index: Option<usize>, } impl Attributes {
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/transform/mod.rs
sway-core/src/transform/mod.rs
mod attribute; pub(crate) mod to_parsed_lang; pub use attribute::*;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/transform/to_parsed_lang/convert_parse_tree.rs
sway-core/src/transform/to_parsed_lang/convert_parse_tree.rs
use crate::{ ast_elements::type_parameter::ConstGenericParameter, attr_decls_to_attributes, compiler_generated::{ generate_destructured_struct_var_name, generate_matched_value_var_name, generate_tuple_var_name, }, decl_engine::{parsed_engine::ParsedDeclEngineInsert, parsed_id::ParsedDeclId}, language::{parsed::*, *}, transform::{attribute::*, to_parsed_lang::context::Context}, type_system::*, BuildTarget, Engines, }; use ast_elements::{ type_argument::{GenericConstArgument, GenericTypeArgument}, type_parameter::{ConstGenericExpr, GenericTypeParameter}, }; use itertools::Itertools; use std::{collections::HashSet, convert::TryFrom, iter, mem::MaybeUninit, str::FromStr}; use sway_ast::{ assignable::ElementAccess, expr::{LoopControlFlow, ReassignmentOp, ReassignmentOpVariant}, generics::GenericParam, ty::TyTupleDescriptor, AbiCastArgs, AngleBrackets, AsmBlock, Assignable, Braces, CodeBlockContents, CommaToken, DoubleColonToken, Expr, ExprArrayDescriptor, ExprStructField, ExprTupleDescriptor, FnArg, FnArgs, FnSignature, GenericArgs, GenericParams, IfCondition, IfExpr, Instruction, Intrinsic, Item, ItemAbi, ItemConfigurable, ItemConst, ItemEnum, ItemFn, ItemImpl, ItemKind, ItemStorage, ItemStruct, ItemTrait, ItemTraitItem, ItemTypeAlias, ItemUse, LitInt, LitIntType, MatchBranchKind, Module, ModuleKind, Parens, PathExpr, PathExprSegment, PathType, PathTypeSegment, Pattern, PatternStructField, PubToken, Punctuated, QualifiedPathRoot, Statement, StatementLet, Submodule, TraitType, Traits, Ty, TypeField, UseTree, WhereClause, }; use sway_error::handler::{ErrorEmitted, Handler}; use sway_error::{convert_parse_tree_error::ConvertParseTreeError, error::CompileError}; use sway_features::ExperimentalFeatures; use sway_types::{integer_bits::IntegerBits, BaseIdent}; use sway_types::{style::to_upper_camel_case, Ident, Span, Spanned}; pub fn convert_parse_tree( context: &mut Context, handler: &Handler, engines: &Engines, module: Module, ) -> Result<(TreeType, ParseTree), ErrorEmitted> { let tree_type = convert_module_kind(&module.kind); context.set_program_type(tree_type); let tree = module_to_sway_parse_tree(context, handler, engines, module)?; Ok((tree_type, tree)) } /// Converts the module kind of the AST to the tree type of the parsed tree. pub fn convert_module_kind(kind: &ModuleKind) -> TreeType { match kind { ModuleKind::Script { .. } => TreeType::Script, ModuleKind::Contract { .. } => TreeType::Contract, ModuleKind::Predicate { .. } => TreeType::Predicate, ModuleKind::Library { .. } => TreeType::Library, } } pub fn module_to_sway_parse_tree( context: &mut Context, handler: &Handler, engines: &Engines, module: Module, ) -> Result<ParseTree, ErrorEmitted> { let span = module.span(); let root_nodes = { let mut root_nodes: Vec<AstNode> = vec![]; let mut item_can_be_submodule = true; for item in module.items { let previous_item_is_submodule = matches!(item.value, ItemKind::Submodule(_)); let ast_nodes = item_to_ast_nodes(context, handler, engines, item, item_can_be_submodule, None)?; root_nodes.extend(ast_nodes); item_can_be_submodule = previous_item_is_submodule; } root_nodes }; Ok(ParseTree { span, root_nodes }) } pub fn item_to_ast_nodes( context: &mut Context, handler: &Handler, engines: &Engines, item: Item, // Submodules (`mod`) must be at the beginning of a file before any other items. // If an other non-`mod` item already appeared before this `item`, // or if the `item` is not a module item at all, but a nested one, // this parameter will be false. item_can_be_submodule: bool, override_kind: Option<FunctionDeclarationKind>, ) -> Result<Vec<AstNode>, ErrorEmitted> { let (attributes_handler, attributes) = attr_decls_to_attributes( &item.attributes, |attr| attr.can_annotate_item_kind(&item.value), item.value.friendly_name_with_acronym(), ); // TODO: Remove the special handling for submodules (`mod`) once // https://github.com/FuelLabs/sway/issues/6879 is fixed. if !matches!(item.value, ItemKind::Submodule(_)) && !cfg_eval(context, handler, &attributes, context.experimental)? { return Ok(vec![]); } let attributes_error_emitted = handler.append(attributes_handler); let decl = |d| vec![AstNodeContent::Declaration(d)]; let span = item.span(); let contents = match item.value { ItemKind::Submodule(submodule) => { if !item_can_be_submodule { return Err(handler.emit_err( (ConvertParseTreeError::ExpectedModuleAtBeginning { span: submodule.span(), }) .into(), )); } let incl_stmt = submodule_to_include_statement(&submodule); vec![AstNodeContent::IncludeStatement(incl_stmt)] } ItemKind::Use(item_use) => item_use_to_use_statements(context, handler, item_use)? .into_iter() .map(AstNodeContent::UseStatement) .collect(), ItemKind::Struct(item_struct) => { let struct_decl = Declaration::StructDeclaration(item_struct_to_struct_declaration( context, handler, engines, item_struct, attributes, )?); context.implementing_type = Some(struct_decl.clone()); decl(struct_decl) } ItemKind::Enum(item_enum) => decl(Declaration::EnumDeclaration( item_enum_to_enum_declaration(context, handler, engines, item_enum, attributes)?, )), ItemKind::Fn(item_fn) => { let function_declaration_decl_id = item_fn_to_function_declaration( context, handler, engines, item_fn, attributes, None, None, override_kind, )?; let function_declaration = engines.pe().get_function(&function_declaration_decl_id); error_if_self_param_is_not_allowed( context, handler, engines, &function_declaration.parameters, "a free function", )?; decl(Declaration::FunctionDeclaration( function_declaration_decl_id, )) } ItemKind::Trait(item_trait) => { let trait_decl = Declaration::TraitDeclaration(item_trait_to_trait_declaration( context, handler, engines, item_trait, attributes, )?); context.implementing_type = Some(trait_decl.clone()); decl(trait_decl) } ItemKind::Impl(item_impl) => { match handle_impl_contract(context, handler, engines, item_impl.clone(), span.clone()) { Ok(contents) if !contents.is_empty() => contents, _ => { let impl_decl = item_impl_to_declaration(context, handler, engines, item_impl)?; decl(impl_decl) } } } ItemKind::Abi(item_abi) => { let abi_decl = Declaration::AbiDeclaration(item_abi_to_abi_declaration( context, handler, engines, item_abi, attributes, )?); context.implementing_type = Some(abi_decl.clone()); decl(abi_decl) } ItemKind::Const(item_const) => decl(Declaration::ConstantDeclaration({ item_const_to_constant_declaration( context, handler, engines, item_const, Visibility::Private, attributes, true, )? })), ItemKind::Storage(item_storage) => decl(Declaration::StorageDeclaration( item_storage_to_storage_declaration( context, handler, engines, item_storage, attributes, )?, )), ItemKind::Configurable(item_configurable) => { item_configurable_to_configurable_declarations( context, handler, engines, item_configurable, &attributes, )? .into_iter() .map(|decl| AstNodeContent::Declaration(Declaration::ConfigurableDeclaration(decl))) .collect() } ItemKind::TypeAlias(item_type_alias) => decl(Declaration::TypeAliasDeclaration( item_type_alias_to_type_alias_declaration( context, handler, engines, item_type_alias, attributes, )?, )), ItemKind::Error(spans, error) => { vec![AstNodeContent::Error(spans, error)] } }; match attributes_error_emitted { Some(err) => Err(err), None => Ok(contents .into_iter() .map(|content| AstNode { span: span.clone(), content, }) .collect()), } } fn item_use_to_use_statements( _context: &mut Context, handler: &Handler, item_use: ItemUse, ) -> Result<Vec<UseStatement>, ErrorEmitted> { let mut ret = Vec::new(); let mut prefix = Vec::new(); let item_span = item_use.span(); use_tree_to_use_statements( item_use.tree, item_use.root_import.is_some(), pub_token_opt_to_visibility(item_use.visibility), &mut prefix, &mut ret, item_span, ); // Check that all use statements have a call_path // This is not the case for `use foo;`, which is currently not supported for use_stmt in ret.iter() { if use_stmt.call_path.is_empty() { let error = ConvertParseTreeError::ImportsWithoutItemsNotSupported { span: use_stmt.span.clone(), }; return Err(handler.emit_err(error.into())); } } debug_assert!(prefix.is_empty()); Ok(ret) } fn use_tree_to_use_statements( use_tree: UseTree, is_relative_to_package_root: bool, reexport: Visibility, path: &mut Vec<Ident>, ret: &mut Vec<UseStatement>, item_span: Span, ) { match use_tree { UseTree::Group { imports } => { for use_tree in imports.into_inner() { use_tree_to_use_statements( use_tree, is_relative_to_package_root, reexport, path, ret, item_span.clone(), ); } } UseTree::Name { name } => { let import_type = if name.as_str() == "self" { ImportType::SelfImport(name.span()) } else { ImportType::Item(name) }; ret.push(UseStatement { call_path: path.clone(), span: item_span, import_type, is_relative_to_package_root, reexport, alias: None, }); } UseTree::Rename { name, alias, .. } => { let import_type = if name.as_str() == "self" { ImportType::SelfImport(name.span()) } else { ImportType::Item(name) }; ret.push(UseStatement { call_path: path.clone(), span: item_span, import_type, is_relative_to_package_root, reexport, alias: Some(alias), }); } UseTree::Glob { .. } => { ret.push(UseStatement { call_path: path.clone(), span: item_span, import_type: ImportType::Star, is_relative_to_package_root, reexport, alias: None, }); } UseTree::Path { prefix, suffix, .. } => { path.push(prefix); use_tree_to_use_statements( *suffix, is_relative_to_package_root, reexport, path, ret, item_span, ); path.pop().unwrap(); } UseTree::Error { .. } => { // parsing error, nothing to push to the use statements collection } } } // TODO: Remove all usages of `emit_all` and replace the manual collection of errors with // the `Handler::scope`. fn emit_all(handler: &Handler, errors: Vec<ConvertParseTreeError>) -> Option<ErrorEmitted> { errors .into_iter() .fold(None, |_, error| Some(handler.emit_err(error.into()))) } fn item_struct_to_struct_declaration( context: &mut Context, handler: &Handler, engines: &Engines, item_struct: ItemStruct, attributes: Attributes, ) -> Result<ParsedDeclId<StructDeclaration>, ErrorEmitted> { let span = item_struct.span(); let fields = item_struct .fields .into_inner() .into_iter() .map(|type_field| { let (attributes_handler, attributes) = attr_decls_to_attributes( &type_field.attributes, |attr| attr.can_annotate_struct_or_enum_field(StructOrEnumField::StructField), "struct field", ); if !cfg_eval(context, handler, &attributes, context.experimental)? { return Ok(None); } let attributes_error_emitted = handler.append(attributes_handler); let struct_field = type_field_to_struct_field( context, handler, engines, type_field.value, attributes, )?; match attributes_error_emitted { Some(err) => Err(err), None => Ok(Some(struct_field)), } }) .filter_map_ok(|field| field) .collect::<Result<Vec<_>, _>>()?; handler.scope(|handler| { if fields.iter().any( |field| matches!(&&*engines.te().get(field.type_argument.type_id), TypeInfo::Custom { qualified_call_path, ..} if qualified_call_path.call_path.suffix == item_struct.name), ) { handler.emit_err(ConvertParseTreeError::RecursiveType { span: span.clone() }.into()); } // Make sure each struct field is declared once let mut names_of_fields = std::collections::HashSet::new(); for field in &fields { if !names_of_fields.insert(field.name.clone()) { handler.emit_err(ConvertParseTreeError::DuplicateStructField { name: field.name.clone(), span: field.name.span(), }.into()); } } Ok(()) })?; let generic_parameters = generic_params_opt_to_type_parameters( context, handler, engines, item_struct.generics, item_struct.where_clause_opt, )?; let struct_declaration_id = engines.pe().insert(StructDeclaration { name: item_struct.name, attributes, fields, type_parameters: generic_parameters, visibility: pub_token_opt_to_visibility(item_struct.visibility), span, }); Ok(struct_declaration_id) } fn item_enum_to_enum_declaration( context: &mut Context, handler: &Handler, engines: &Engines, item_enum: ItemEnum, attributes: Attributes, ) -> Result<ParsedDeclId<EnumDeclaration>, ErrorEmitted> { let span = item_enum.span(); let variants = item_enum .fields .into_inner() .into_iter() .enumerate() .map(|(tag, type_field)| { let (attributes_handler, attributes) = attr_decls_to_attributes( &type_field.attributes, |attr| attr.can_annotate_struct_or_enum_field(StructOrEnumField::EnumField), "enum variant", ); if !cfg_eval(context, handler, &attributes, context.experimental)? { return Ok(None); } let attributes_error_emitted = handler.append(attributes_handler); let enum_variant = type_field_to_enum_variant( context, handler, engines, type_field.value, attributes, tag, )?; match attributes_error_emitted { Some(err) => Err(err), None => Ok(Some(enum_variant)), } }) .filter_map_ok(|field| field) .collect::<Result<Vec<_>, _>>()?; handler.scope(|handler| { if variants.iter().any(|variant| { matches!(&&*engines.te().get(variant.type_argument.type_id), TypeInfo::Custom { qualified_call_path, ..} if qualified_call_path.call_path.suffix == item_enum.name) }) { handler.emit_err(ConvertParseTreeError::RecursiveType { span: span.clone() }.into()); } // Make sure each enum variant is declared once let mut names_of_variants = std::collections::HashSet::new(); for v in variants.iter() { if !names_of_variants.insert(v.name.clone()) { handler.emit_err(ConvertParseTreeError::DuplicateEnumVariant { name: v.name.clone(), span: v.name.span(), }.into()); } } Ok(()) })?; let type_parameters = generic_params_opt_to_type_parameters( context, handler, engines, item_enum.generics, item_enum.where_clause_opt, )?; let enum_declaration_id = engines.pe().insert(EnumDeclaration { name: item_enum.name, type_parameters, variants, span, visibility: pub_token_opt_to_visibility(item_enum.visibility), attributes, }); Ok(enum_declaration_id) } #[allow(clippy::too_many_arguments)] pub fn item_fn_to_function_declaration( context: &mut Context, handler: &Handler, engines: &Engines, item_fn: ItemFn, attributes: Attributes, parent_generic_params_opt: Option<GenericParams>, parent_where_clause_opt: Option<WhereClause>, override_kind: Option<FunctionDeclarationKind>, ) -> Result<ParsedDeclId<FunctionDeclaration>, ErrorEmitted> { let span = item_fn.span(); let return_type = match item_fn.fn_signature.return_type_opt { Some((_right_arrow, ty)) => { let span = ty.span(); let arg = ty_to_generic_argument(context, handler, engines, ty)?; arg.as_type_argument() .ok_or_else(|| handler.emit_err(CompileError::UnknownType { span })) .cloned()? } None => { let type_id = engines.te().id_of_unit(); GenericTypeArgument { type_id, initial_type_id: type_id, span: item_fn.fn_signature.span(), call_path_tree: None, } } }; // TODO: This is a bug. We have to check if the function is actually a main function of a // script or a predicate. // See: https://github.com/FuelLabs/sway/issues/7371 let kind = if item_fn.fn_signature.name.as_str() == "main" { FunctionDeclarationKind::Main } else { FunctionDeclarationKind::Default }; let kind = override_kind.unwrap_or(kind); let implementing_type = context.implementing_type.clone(); let mut generic_parameters = generic_params_opt_to_type_parameters_with_parent( context, handler, engines, item_fn.fn_signature.generics, parent_generic_params_opt, item_fn.fn_signature.where_clause_opt.clone(), parent_where_clause_opt, )?; for p in generic_parameters.iter_mut() { match p { TypeParameter::Type(_) => {} TypeParameter::Const(p) => { p.id = Some(engines.pe().insert(ConstGenericDeclaration { name: p.name.clone(), ty: p.ty, span: p.span.clone(), })); } } } let fn_decl = FunctionDeclaration { purity: attributes.purity(), attributes, name: item_fn.fn_signature.name, visibility: pub_token_opt_to_visibility(item_fn.fn_signature.visibility), body: braced_code_block_contents_to_code_block(context, handler, engines, item_fn.body)?, parameters: fn_args_to_function_parameters( context, handler, engines, item_fn.fn_signature.arguments.into_inner(), )?, span, return_type, type_parameters: generic_parameters, where_clause: item_fn .fn_signature .where_clause_opt .map(|where_clause| { where_clause_to_trait_constraints(context, handler, engines, where_clause) }) .transpose()? .unwrap_or(vec![]), kind, implementing_type, }; let decl_id = engines.pe().insert(fn_decl); Ok(decl_id) } fn where_clause_to_trait_constraints( context: &mut Context, handler: &Handler, engines: &Engines, where_clause: WhereClause, ) -> Result<Vec<(Ident, Vec<TraitConstraint>)>, ErrorEmitted> { where_clause .bounds .into_iter() .map(|bound| { Ok(( bound.ty_name, traits_to_trait_constraints(context, handler, engines, bound.bounds)?, )) }) .collect() } fn item_trait_to_trait_declaration( context: &mut Context, handler: &Handler, engines: &Engines, item_trait: ItemTrait, attributes: Attributes, ) -> Result<ParsedDeclId<TraitDeclaration>, ErrorEmitted> { let span = item_trait.span(); let type_parameters = generic_params_opt_to_type_parameters( context, handler, engines, item_trait.generics.clone(), item_trait.where_clause_opt.clone(), )?; let interface_surface = item_trait .trait_items .into_inner() .into_iter() .map(|annotated| { let (attributes_handler, attributes) = attr_decls_to_attributes( &annotated.attributes, |attr| { attr.can_annotate_abi_or_trait_item(&annotated.value, TraitItemParent::Trait) }, annotated.value.friendly_name(), ); if !cfg_eval(context, handler, &attributes, context.experimental)? { return Ok(None); } let attributes_error_emitted = handler.append(attributes_handler); let trait_item = match annotated.value { ItemTraitItem::Fn(fn_sig, _) => { fn_signature_to_trait_fn(context, handler, engines, fn_sig, attributes) .map(TraitItem::TraitFn) } ItemTraitItem::Const(const_decl, _) => item_const_to_constant_declaration( context, handler, engines, const_decl, Visibility::Public, attributes, false, ) .map(TraitItem::Constant), ItemTraitItem::Type(trait_type, _) => trait_type_to_trait_type_declaration( context, handler, engines, trait_type, attributes, ) .map(TraitItem::Type), ItemTraitItem::Error(spans, error) => Ok(TraitItem::Error(spans, error)), }?; match attributes_error_emitted { Some(err) => Err(err), None => Ok(Some(trait_item)), } }) .filter_map_ok(|item| item) .collect::<Result<_, _>>()?; let methods = match item_trait.trait_defs_opt { None => Vec::new(), Some(trait_defs) => trait_defs .into_inner() .into_iter() .map(|item_fn| { let (attributes_handler, attributes) = attr_decls_to_attributes( &item_fn.attributes, |attr| attr.can_annotate_abi_or_trait_item_fn(TraitItemParent::Trait), "provided trait function", ); if !cfg_eval(context, handler, &attributes, context.experimental)? { return Ok(None); } let attributes_error_emitted = handler.append(attributes_handler); let function_declaration_id = item_fn_to_function_declaration( context, handler, engines, item_fn.value, attributes, item_trait.generics.clone(), item_trait.where_clause_opt.clone(), None, )?; match attributes_error_emitted { Some(err) => Err(err), None => Ok(Some(function_declaration_id)), } }) .filter_map_ok(|fn_decl| fn_decl) .collect::<Result<_, _>>()?, }; let supertraits = match item_trait.super_traits { None => Vec::new(), Some((_colon_token, traits)) => traits_to_supertraits(context, handler, traits)?, }; let visibility = pub_token_opt_to_visibility(item_trait.visibility); let trait_decl_id = engines.pe().insert(TraitDeclaration { name: item_trait.name, type_parameters, interface_surface, methods, supertraits, visibility, attributes, span, }); Ok(trait_decl_id) } pub fn item_impl_to_declaration( context: &mut Context, handler: &Handler, engines: &Engines, item_impl: ItemImpl, ) -> Result<Declaration, ErrorEmitted> { let block_span = item_impl.span(); let span = item_impl.ty.span(); let arg = ty_to_generic_argument(context, handler, engines, item_impl.ty)?; let implementing_for = arg .as_type_argument() .ok_or_else(|| handler.emit_err(CompileError::UnknownType { span })) .cloned()?; let impl_item_parent = (&*engines.te().get(implementing_for.type_id)).into(); let items = item_impl .contents .into_inner() .into_iter() .map(|item| { let (attributes_handler, attributes) = attr_decls_to_attributes( &item.attributes, |attr| attr.can_annotate_impl_item(&item.value, impl_item_parent), item.value.friendly_name(impl_item_parent), ); if !cfg_eval(context, handler, &attributes, context.experimental)? { return Ok(None); } let attributes_error_emitted = handler.append(attributes_handler); let impl_item = match item.value { sway_ast::ItemImplItem::Fn(fn_item) => item_fn_to_function_declaration( context, handler, engines, fn_item, attributes, item_impl.generic_params_opt.clone(), item_impl.where_clause_opt.clone(), None, ) .map(ImplItem::Fn), sway_ast::ItemImplItem::Const(const_item) => item_const_to_constant_declaration( context, handler, engines, const_item, Visibility::Private, attributes, false, ) .map(ImplItem::Constant), sway_ast::ItemImplItem::Type(type_item) => trait_type_to_trait_type_declaration( context, handler, engines, type_item, attributes, ) .map(ImplItem::Type), }?; match attributes_error_emitted { Some(err) => Err(err), None => Ok(Some(impl_item)), } }) .filter_map_ok(|item| item) .collect::<Result<_, _>>()?; let mut impl_type_parameters = generic_params_opt_to_type_parameters( context, handler, engines, item_impl.generic_params_opt, item_impl.where_clause_opt, )?; for p in impl_type_parameters.iter_mut() { match p { TypeParameter::Type(_) => {} TypeParameter::Const(p) => { p.id = Some(engines.pe().insert(ConstGenericDeclaration { name: p.name.clone(), ty: p.ty, span: p.span.clone(), })); } } } match item_impl.trait_opt { Some((path_type, _)) => { let (trait_name, trait_type_arguments) = path_type_to_call_path_and_type_arguments(context, handler, engines, path_type)?; let impl_trait = ImplSelfOrTrait { is_self: false, impl_type_parameters, trait_name: trait_name.to_call_path(handler)?, trait_type_arguments, trait_decl_ref: None, implementing_for, items, block_span, }; let impl_trait = engines.pe().insert(impl_trait); Ok(Declaration::ImplSelfOrTrait(impl_trait)) } None => { let impl_self = ImplSelfOrTrait { is_self: true, trait_name: CallPath { callpath_type: CallPathType::Ambiguous, prefixes: vec![], suffix: BaseIdent::dummy(), }, trait_decl_ref: None, trait_type_arguments: vec![], implementing_for, impl_type_parameters, items, block_span, }; let impl_self = engines.pe().insert(impl_self); Ok(Declaration::ImplSelfOrTrait(impl_self)) } } } fn handle_impl_contract( context: &mut Context, handler: &Handler, engines: &Engines, item_impl: ItemImpl, span: Span, ) -> Result<Vec<AstNodeContent>, ErrorEmitted> { let implementing_for = { let span = item_impl.ty.span(); let arg = ty_to_generic_argument(context, handler, engines, item_impl.ty)?; arg.as_type_argument() .ok_or_else(|| handler.emit_err(CompileError::UnknownType { span })) .cloned()? }; // Only handle if this is an impl Contract block if let TypeInfo::Contract = &*engines.te().get(implementing_for.type_id) { // Check if there's an explicit trait being implemented match item_impl.trait_opt { Some((_, _)) => return Ok(vec![]), None => { // Generate ABI name using package name with "Abi" suffix // Package name can contain hyphens, so we replace them with underscores let contract_name = to_upper_camel_case(&context.package_name.replace('-', "_")); let anon_abi_name = Ident::new_with_override(format!("{contract_name}Abi"), span.clone()); // Convert the methods to ABI interface let mut interface_surface = Vec::new(); for item in &item_impl.contents.inner { let (_, attributes) = attr_decls_to_attributes( &item.attributes, |attr| { attr.can_annotate_impl_item( &item.value, sway_ast::ImplItemParent::Contract, ) }, item.value.friendly_name(sway_ast::ImplItemParent::Contract), ); match &item.value { sway_ast::ItemImplItem::Fn(fn_item) => {
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/transform/to_parsed_lang/mod.rs
sway-core/src/transform/to_parsed_lang/mod.rs
mod context; mod convert_parse_tree; pub(crate) use context::*; pub(crate) use convert_parse_tree::*;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/transform/to_parsed_lang/context.rs
sway-core/src/transform/to_parsed_lang/context.rs
use sway_features::ExperimentalFeatures; use crate::{ build_config::DbgGeneration, language::parsed::{Declaration, TreeType}, BuildTarget, }; pub struct Context { pub experimental: ExperimentalFeatures, /// Indicates whether the module being parsed has a `configurable` block. module_has_configurable_block: bool, /// Unique suffix used to generate unique names for destructured structs. destructured_struct_unique_suffix: usize, /// Unique suffix used to generate unique names for destructured tuples. destructured_tuple_unique_suffix: usize, /// Unique suffix used to generate unique names for variables /// that store values matched in match expressions. match_expression_matched_value_unique_suffix: usize, /// Unique suffix used to generate unique names for for loops. for_unique_suffix: usize, /// The build target. build_target: BuildTarget, /// Indicates whether the `__dbg` intrinsic generates code or not dbg_generation: DbgGeneration, /// The program type. program_type: Option<TreeType>, /// Keeps track of the implementing type as we convert the tree. pub(crate) implementing_type: Option<Declaration>, /// Used to name anonymous impl contracts pub package_name: String, } impl Context { /// Create a new context. pub fn new( build_target: BuildTarget, dbg_generation: DbgGeneration, experimental: ExperimentalFeatures, package_name: &str, ) -> Self { Self { build_target, dbg_generation, experimental, module_has_configurable_block: std::default::Default::default(), destructured_struct_unique_suffix: std::default::Default::default(), destructured_tuple_unique_suffix: std::default::Default::default(), match_expression_matched_value_unique_suffix: std::default::Default::default(), for_unique_suffix: std::default::Default::default(), program_type: std::default::Default::default(), implementing_type: None, package_name: package_name.to_string(), } } /// Updates the value of `module_has_configurable_block`. pub fn set_module_has_configurable_block(&mut self, val: bool) { self.module_has_configurable_block = val; } /// Returns whether the module being parsed has a `configurable` block. pub fn module_has_configurable_block(&self) -> bool { self.module_has_configurable_block } /// Returns a unique suffix used to generate a unique name for a destructured struct. pub fn next_destructured_struct_unique_suffix(&mut self) -> usize { self.destructured_struct_unique_suffix += 1; self.destructured_struct_unique_suffix } /// Returns a unique suffix used to generate a unique name for a destructured tuple pub fn next_destructured_tuple_unique_suffix(&mut self) -> usize { self.destructured_tuple_unique_suffix += 1; self.destructured_tuple_unique_suffix } /// Returns a unique suffix used to generate a unique name for a variable /// that stores the value matched in a match expression. pub fn next_match_expression_matched_value_unique_suffix(&mut self) -> usize { self.match_expression_matched_value_unique_suffix += 1; self.match_expression_matched_value_unique_suffix } /// Returns a unique suffix used to generate a unique name for a destructured struct. pub fn next_for_unique_suffix(&mut self) -> usize { self.for_unique_suffix += 1; self.for_unique_suffix } /// Returns the build target. pub fn build_target(&self) -> BuildTarget { self.build_target } pub fn is_dbg_generation_full(&self) -> bool { matches!(self.dbg_generation, DbgGeneration::Full) } /// Returns the program type. pub fn program_type(&self) -> Option<TreeType> { self.program_type } /// Updates the value of `program_type`. pub fn set_program_type(&mut self, program_type: TreeType) { self.program_type = Some(program_type); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/asm_lang/virtual_ops.rs
sway-core/src/asm_lang/virtual_ops.rs
//! This module contains abstracted versions of bytecode primitives that the compiler uses to //! ensure correctness and safety. //! //! The immediate types are used to safely construct numbers that are within their bounds, and the //! ops are clones of the actual opcodes, but with the safe primitives as arguments. use indexmap::IndexMap; use super::{ allocated_ops::{AllocatedInstruction, AllocatedRegister}, virtual_immediate::*, virtual_register::*, Op, }; use crate::asm_generation::fuel::{data_section::DataId, register_allocator::RegisterPool}; use std::collections::{BTreeSet, HashMap}; use std::fmt; /// This enum is unfortunately a redundancy of the [fuel_asm::Opcode] enum. This variant, however, /// allows me to use the compiler's internal [VirtualRegister] types and maintain type safety /// between virtual ops and the real opcodes. A bit of copy/paste seemed worth it for that safety, /// so here it is. #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Debug)] pub(crate) enum VirtualOp { /* Arithmetic/Logic (ALU) Instructions */ ADD(VirtualRegister, VirtualRegister, VirtualRegister), ADDI(VirtualRegister, VirtualRegister, VirtualImmediate12), AND(VirtualRegister, VirtualRegister, VirtualRegister), ANDI(VirtualRegister, VirtualRegister, VirtualImmediate12), DIV(VirtualRegister, VirtualRegister, VirtualRegister), DIVI(VirtualRegister, VirtualRegister, VirtualImmediate12), EQ(VirtualRegister, VirtualRegister, VirtualRegister), EXP(VirtualRegister, VirtualRegister, VirtualRegister), EXPI(VirtualRegister, VirtualRegister, VirtualImmediate12), GT(VirtualRegister, VirtualRegister, VirtualRegister), LT(VirtualRegister, VirtualRegister, VirtualRegister), MLOG(VirtualRegister, VirtualRegister, VirtualRegister), MOD(VirtualRegister, VirtualRegister, VirtualRegister), MODI(VirtualRegister, VirtualRegister, VirtualImmediate12), MOVE(VirtualRegister, VirtualRegister), MOVI(VirtualRegister, VirtualImmediate18), MROO(VirtualRegister, VirtualRegister, VirtualRegister), MUL(VirtualRegister, VirtualRegister, VirtualRegister), MULI(VirtualRegister, VirtualRegister, VirtualImmediate12), NOOP, NOT(VirtualRegister, VirtualRegister), OR(VirtualRegister, VirtualRegister, VirtualRegister), ORI(VirtualRegister, VirtualRegister, VirtualImmediate12), SLL(VirtualRegister, VirtualRegister, VirtualRegister), SLLI(VirtualRegister, VirtualRegister, VirtualImmediate12), SRL(VirtualRegister, VirtualRegister, VirtualRegister), SRLI(VirtualRegister, VirtualRegister, VirtualImmediate12), SUB(VirtualRegister, VirtualRegister, VirtualRegister), SUBI(VirtualRegister, VirtualRegister, VirtualImmediate12), XOR(VirtualRegister, VirtualRegister, VirtualRegister), XORI(VirtualRegister, VirtualRegister, VirtualImmediate12), WQOP( VirtualRegister, VirtualRegister, VirtualRegister, VirtualImmediate06, ), WQML( VirtualRegister, VirtualRegister, VirtualRegister, VirtualImmediate06, ), WQDV( VirtualRegister, VirtualRegister, VirtualRegister, VirtualImmediate06, ), WQMD( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), WQCM( VirtualRegister, VirtualRegister, VirtualRegister, VirtualImmediate06, ), WQAM( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), WQMM( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), /* Control Flow Instructions */ JMP(VirtualRegister), JI(VirtualImmediate24), JNE(VirtualRegister, VirtualRegister, VirtualRegister), JNEI(VirtualRegister, VirtualRegister, VirtualImmediate12), JNZI(VirtualRegister, VirtualImmediate18), JMPB(VirtualRegister, VirtualImmediate18), JMPF(VirtualRegister, VirtualImmediate18), JNZB(VirtualRegister, VirtualRegister, VirtualImmediate12), JNZF(VirtualRegister, VirtualRegister, VirtualImmediate12), JNEB( VirtualRegister, VirtualRegister, VirtualRegister, VirtualImmediate06, ), JNEF( VirtualRegister, VirtualRegister, VirtualRegister, VirtualImmediate06, ), JAL(VirtualRegister, VirtualRegister, VirtualImmediate12), RET(VirtualRegister), /* Memory Instructions */ ALOC(VirtualRegister, VirtualRegister), CFEI(VirtualRegister, VirtualImmediate24), CFSI(VirtualRegister, VirtualImmediate24), CFE(VirtualRegister, VirtualRegister), CFS(VirtualRegister, VirtualRegister), LB(VirtualRegister, VirtualRegister, VirtualImmediate12), LW(VirtualRegister, VirtualRegister, VirtualImmediate12), MCL(VirtualRegister, VirtualRegister), MCLI(VirtualRegister, VirtualImmediate18), MCP(VirtualRegister, VirtualRegister, VirtualRegister), MCPI(VirtualRegister, VirtualRegister, VirtualImmediate12), MEQ( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), SB(VirtualRegister, VirtualRegister, VirtualImmediate12), SW(VirtualRegister, VirtualRegister, VirtualImmediate12), /* Contract Instructions */ BAL(VirtualRegister, VirtualRegister, VirtualRegister), BHEI(VirtualRegister), BHSH(VirtualRegister, VirtualRegister), BURN(VirtualRegister, VirtualRegister), CALL( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), CB(VirtualRegister), CCP( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), CROO(VirtualRegister, VirtualRegister), CSIZ(VirtualRegister, VirtualRegister), BSIZ(VirtualRegister, VirtualRegister), LDC( VirtualRegister, VirtualRegister, VirtualRegister, VirtualImmediate06, ), BLDD( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), LOG( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), LOGD( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), MINT(VirtualRegister, VirtualRegister), RETD(VirtualRegister, VirtualRegister), RVRT(VirtualRegister), SMO( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), SCWQ(VirtualRegister, VirtualRegister, VirtualRegister), SRW(VirtualRegister, VirtualRegister, VirtualRegister), SRWQ( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), SWW(VirtualRegister, VirtualRegister, VirtualRegister), SWWQ( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), TIME(VirtualRegister, VirtualRegister), TR(VirtualRegister, VirtualRegister, VirtualRegister), TRO( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), /* Cryptographic Instructions */ ECK1(VirtualRegister, VirtualRegister, VirtualRegister), ECR1(VirtualRegister, VirtualRegister, VirtualRegister), ED19( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), K256(VirtualRegister, VirtualRegister, VirtualRegister), S256(VirtualRegister, VirtualRegister, VirtualRegister), ECOP( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), EPAR( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), /* Other Instructions */ ECAL( VirtualRegister, VirtualRegister, VirtualRegister, VirtualRegister, ), FLAG(VirtualRegister), GM(VirtualRegister, VirtualImmediate18), GTF(VirtualRegister, VirtualRegister, VirtualImmediate12), /* Non-VM Instructions */ BLOB(VirtualImmediate24), ConfigurablesOffsetPlaceholder, DataSectionOffsetPlaceholder, // LoadDataId takes a virtual register and a DataId, which points to a labeled piece // of data in the data section. Note that the ASM op corresponding to a LW is // subtly complex: $rB is in bytes and points to some mem address. The immediate // third argument is a _word_ offset from that byte address. LoadDataId(VirtualRegister, DataId), AddrDataId(VirtualRegister, DataId), Undefined, } impl VirtualOp { pub(crate) fn registers(&self) -> BTreeSet<&VirtualRegister> { use VirtualOp::*; (match self { /* Arithmetic/Logic (ALU) Instructions */ ADD(r1, r2, r3) => vec![r1, r2, r3], ADDI(r1, r2, _i) => vec![r1, r2], AND(r1, r2, r3) => vec![r1, r2, r3], ANDI(r1, r2, _i) => vec![r1, r2], DIV(r1, r2, r3) => vec![r1, r2, r3], DIVI(r1, r2, _i) => vec![r1, r2], EQ(r1, r2, r3) => vec![r1, r2, r3], EXP(r1, r2, r3) => vec![r1, r2, r3], EXPI(r1, r2, _i) => vec![r1, r2], GT(r1, r2, r3) => vec![r1, r2, r3], LT(r1, r2, r3) => vec![r1, r2, r3], MLOG(r1, r2, r3) => vec![r1, r2, r3], MOD(r1, r2, r3) => vec![r1, r2, r3], MODI(r1, r2, _i) => vec![r1, r2], MOVE(r1, r2) => vec![r1, r2], MOVI(r1, _i) => vec![r1], MROO(r1, r2, r3) => vec![r1, r2, r3], MUL(r1, r2, r3) => vec![r1, r2, r3], MULI(r1, r2, _i) => vec![r1, r2], NOOP => vec![], NOT(r1, r2) => vec![r1, r2], OR(r1, r2, r3) => vec![r1, r2, r3], ORI(r1, r2, _i) => vec![r1, r2], SLL(r1, r2, r3) => vec![r1, r2, r3], SLLI(r1, r2, _i) => vec![r1, r2], SRL(r1, r2, r3) => vec![r1, r2, r3], SRLI(r1, r2, _i) => vec![r1, r2], SUB(r1, r2, r3) => vec![r1, r2, r3], SUBI(r1, r2, _i) => vec![r1, r2], XOR(r1, r2, r3) => vec![r1, r2, r3], XORI(r1, r2, _i) => vec![r1, r2], WQOP(r1, r2, r3, _) => vec![r1, r2, r3], WQML(r1, r2, r3, _) => vec![r1, r2, r3], WQDV(r1, r2, r3, _) => vec![r1, r2, r3], WQMD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], WQCM(r1, r2, r3, _) => vec![r1, r2, r3], WQAM(r1, r2, r3, r4) => vec![r1, r2, r3, r4], WQMM(r1, r2, r3, r4) => vec![r1, r2, r3, r4], /* Control Flow Instructions */ JMP(r1) => vec![r1], JI(_im) => vec![], JNE(r1, r2, r3) => vec![r1, r2, r3], JNEI(r1, r2, _i) => vec![r1, r2], JNZI(r1, _i) => vec![r1], JMPB(r1, _i) => vec![r1], JMPF(r1, _i) => vec![r1], JNZB(r1, r2, _i) => vec![r1, r2], JNZF(r1, r2, _i) => vec![r1, r2], JNEB(r1, r2, r3, _i) => vec![r1, r2, r3], JNEF(r1, r2, r3, _i) => vec![r1, r2, r3], JAL(r1, r2, _i) => vec![r1, r2], RET(r1) => vec![r1], /* Memory Instructions */ ALOC(hp, r1) => vec![hp, r1], CFEI(sp, _imm) => vec![sp], CFSI(sp, _imm) => vec![sp], CFE(sp, r1) => vec![sp, r1], CFS(sp, r1) => vec![sp, r1], LB(r1, r2, _i) => vec![r1, r2], LW(r1, r2, _i) => vec![r1, r2], MCL(r1, r2) => vec![r1, r2], MCLI(r1, _imm) => vec![r1], MCP(r1, r2, r3) => vec![r1, r2, r3], MCPI(r1, r2, _imm) => vec![r1, r2], MEQ(r1, r2, r3, r4) => vec![r1, r2, r3, r4], SB(r1, r2, _i) => vec![r1, r2], SW(r1, r2, _i) => vec![r1, r2], /* Contract Instructions */ BAL(r1, r2, r3) => vec![r1, r2, r3], BHEI(r1) => vec![r1], BHSH(r1, r2) => vec![r1, r2], BURN(r1, r2) => vec![r1, r2], CALL(r1, r2, r3, r4) => vec![r1, r2, r3, r4], CB(r1) => vec![r1], CCP(r1, r2, r3, r4) => vec![r1, r2, r3, r4], CROO(r1, r2) => vec![r1, r2], CSIZ(r1, r2) => vec![r1, r2], BSIZ(r1, r2) => vec![r1, r2], LDC(r1, r2, r3, _i0) => vec![r1, r2, r3], BLDD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], LOG(r1, r2, r3, r4) => vec![r1, r2, r3, r4], LOGD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], MINT(r1, r2) => vec![r1, r2], RETD(r1, r2) => vec![r1, r2], RVRT(r1) => vec![r1], SMO(r1, r2, r3, r4) => vec![r1, r2, r3, r4], SCWQ(r1, r2, r3) => vec![r1, r2, r3], SRW(r1, r2, r3) => vec![r1, r2, r3], SRWQ(r1, r2, r3, r4) => vec![r1, r2, r3, r4], SWW(r1, r2, r3) => vec![r1, r2, r3], SWWQ(r1, r2, r3, r4) => vec![r1, r2, r3, r4], TIME(r1, r2) => vec![r1, r2], TR(r1, r2, r3) => vec![r1, r2, r3], TRO(r1, r2, r3, r4) => vec![r1, r2, r3, r4], /* Cryptographic Instructions */ ECK1(r1, r2, r3) => vec![r1, r2, r3], ECR1(r1, r2, r3) => vec![r1, r2, r3], ED19(r1, r2, r3, r4) => vec![r1, r2, r3, r4], K256(r1, r2, r3) => vec![r1, r2, r3], S256(r1, r2, r3) => vec![r1, r2, r3], ECOP(r1, r2, r3, r4) => vec![r1, r2, r3, r4], EPAR(r1, r2, r3, r4) => vec![r1, r2, r3, r4], /* Other Instructions */ ECAL(r1, r2, r3, r4) => vec![r1, r2, r3, r4], FLAG(r1) => vec![r1], GM(r1, _imm) => vec![r1], GTF(r1, r2, _i) => vec![r1, r2], /* Non-VM Instructions */ BLOB(_imm) => vec![], DataSectionOffsetPlaceholder => vec![], ConfigurablesOffsetPlaceholder => vec![], LoadDataId(r1, _i) => vec![r1], AddrDataId(r1, _) => vec![r1], Undefined => vec![], }) .into_iter() .collect() } /// Does this op do anything other than just compute something? /// (and hence if the result is dead, the OP can safely be deleted). pub(crate) fn has_side_effect(&self) -> bool { use VirtualOp::*; match self { // Arithmetic and logical ADD(_, _, _) | ADDI(_, _, _) | AND(_, _, _) | ANDI(_, _, _) | DIV(_, _, _) | DIVI(_, _, _) | EQ(_, _, _) | EXP(_, _, _) | EXPI(_, _, _) | GT(_, _, _) | LT(_, _, _) | MLOG(_, _, _) | MOD(_, _, _) | MODI(_, _, _) | MOVE(_, _) | MOVI(_, _) | MROO(_, _, _) | MUL(_, _, _) | MULI(_, _, _) | NOOP | NOT(_, _) | OR(_, _, _) | ORI(_, _, _) | SLL(_, _, _) | SLLI(_, _, _) | SRL(_, _, _) | SRLI(_, _, _) | SUB(_, _, _) | SUBI(_, _, _) | XOR(_, _, _) | XORI(_, _, _) // Memory load | LB(_, _, _) | LW(_, _, _) // Blockchain read | BAL(_, _, _) | BHEI(_) | CSIZ(_, _) | BSIZ(_, _) | SRW(_, _, _) | TIME(_, _) | GM(_, _) | GTF(_, _, _) | EPAR(_, _, _, _) // Virtual OPs | LoadDataId(_, _) | AddrDataId(_, _) => self.def_registers().iter().any(|vreg| matches!(vreg, VirtualRegister::Constant(_))), // Memory write and jump WQOP(_, _, _, _) | WQML(_, _, _, _) | WQDV(_, _, _, _) | WQMD(_, _, _, _) | WQCM(_, _, _, _) | WQAM(_, _, _, _) | WQMM(_, _, _, _) | JMP(_) | JI(_) | JNE(_, _, _) | JNEI(_, _, _) | JNZI(_, _) | JMPB(_, _) | JMPF(_, _) | JNZB(_, _, _) | JNZF(_, _, _) | JNEB(_, _, _, _) | JNEF(_, _, _, _) | JAL(_, _, _) | RET(_) | ALOC(..) | CFEI(..) | CFSI(..) | CFE(..) | CFS(..) | MCL(_, _) | MCLI(_, _) | MCP(_, _, _) | MCPI(_, _, _) | MEQ(_, _, _, _) | SB(_, _, _) | SW(_, _, _) // Other blockchain etc ... | BHSH(_, _) | BURN(_, _) | CALL(_, _, _, _) | CB(_) | CCP(_, _, _, _) | CROO(_, _) | LDC(_, _, _, _) | BLDD(_, _, _, _) | LOG(_, _, _, _) | LOGD(_, _, _, _) | MINT(_, _) | RETD(_, _) | RVRT(_) | SMO(_, _, _, _) | SCWQ(_, _, _) | SRWQ(_, _, _, _) | SWW(_, _, _) | SWWQ(_, _, _, _) | TR(_, _, _) | TRO(_, _, _, _) | ECK1(_, _, _) | ECR1(_, _, _) | ED19(_, _, _, _) | K256(_, _, _) | S256(_, _, _) | ECOP(_, _, _, _) // Other instructions | ECAL(_, _, _, _) | FLAG(_) // Virtual OPs | BLOB(_) | DataSectionOffsetPlaceholder | ConfigurablesOffsetPlaceholder | Undefined => true } } // What are the special registers that an OP may set. pub(crate) fn def_const_registers(&self) -> BTreeSet<&VirtualRegister> { use ConstantRegister::*; use VirtualOp::*; (match self { // Arithmetic and logical ADD(_, _, _) | ADDI(_, _, _) | AND(_, _, _) | ANDI(_, _, _) | DIV(_, _, _) | DIVI(_, _, _) | EQ(_, _, _) | EXP(_, _, _) | EXPI(_, _, _) | GT(_, _, _) | LT(_, _, _) | MLOG(_, _, _) | MOD(_, _, _) | MODI(_, _, _) | MOVE(_, _) | MOVI(_, _) | MROO(_, _, _) | MUL(_, _, _) | MULI(_, _, _) | NOOP | NOT(_, _) | OR(_, _, _) | ORI(_, _, _) | SLL(_, _, _) | SLLI(_, _, _) | SRL(_, _, _) | SRLI(_, _, _) | SUB(_, _, _) | SUBI(_, _, _) | XOR(_, _, _) | XORI(_, _, _) | WQOP(_, _, _, _) | WQML(_, _, _, _) | WQDV(_, _, _, _) | WQMD(_, _, _, _) | WQCM(_, _, _, _) | WQAM(_, _, _, _) | WQMM(_, _, _, _) // Cryptographic | ECK1(_, _, _) | ECR1(_, _, _) | ED19(_, _, _, _) => vec![&VirtualRegister::Constant(Overflow), &VirtualRegister::Constant(Error)], FLAG(_) => vec![&VirtualRegister::Constant(Flags)], | ALOC(hp, _) => vec![hp], | CFEI(sp, _) | CFSI(sp, _) | CFE(sp, _) | CFS(sp, _) => vec![sp], JMP(_) | JI(_) | JNE(_, _, _) | JNEI(_, _, _) | JNZI(_, _) | JMPB(_, _) | JMPF(_, _) | JNZB(_, _, _) | JNZF(_, _, _) | JNEB(_, _, _, _) | JNEF(_, _, _, _) | JAL(_, _, _) | RET(_) | LB(_, _, _) | LW(_, _, _) | MCL(_, _) | MCLI(_, _) | MCP(_, _, _) | MCPI(_, _, _) | MEQ(_, _, _, _) | SB(_, _, _) | SW(_, _, _) | BAL(_, _, _) | BHEI(_) | BHSH(_, _) | BURN(_, _) | CALL(_, _, _, _) | CB(_) | CCP(_, _, _, _) | CROO(_, _) | CSIZ(_, _) | BSIZ(_, _) | LDC(_, _, _, _) | BLDD(_, _, _, _) | LOG(_, _, _, _) | LOGD(_, _, _, _) | MINT(_, _) | RETD(_, _) | RVRT(_) | SMO(_, _, _, _) | SCWQ(_, _, _) | SRW(_, _, _) | SRWQ(_, _, _, _) | SWW(_, _, _) | SWWQ(_, _, _, _) | TIME(_, _) | TR(_, _, _) | TRO(_, _, _, _) | K256(_, _, _) | S256(_, _, _) | ECOP(_, _, _, _) | EPAR(_, _, _, _) | ECAL(_, _, _, _) | GM(_, _) | GTF(_, _, _) | BLOB(_) | DataSectionOffsetPlaceholder | ConfigurablesOffsetPlaceholder | LoadDataId(_, _) | AddrDataId(_, _) | Undefined => vec![], }) .into_iter() .collect() } /// Returns a list of all registers *read* by instruction `self`. pub(crate) fn use_registers(&self) -> BTreeSet<&VirtualRegister> { use VirtualOp::*; (match self { /* Arithmetic/Logic (ALU) Instructions */ ADD(_r1, r2, r3) => vec![r2, r3], ADDI(_r1, r2, _i) => vec![r2], AND(_r1, r2, r3) => vec![r2, r3], ANDI(_r1, r2, _i) => vec![r2], DIV(_r1, r2, r3) => vec![r2, r3], DIVI(_r1, r2, _i) => vec![r2], EQ(_r1, r2, r3) => vec![r2, r3], EXP(_r1, r2, r3) => vec![r2, r3], EXPI(_r1, r2, _i) => vec![r2], GT(_r1, r2, r3) => vec![r2, r3], LT(_r1, r2, r3) => vec![r2, r3], MLOG(_r1, r2, r3) => vec![r2, r3], MOD(_r1, r2, r3) => vec![r2, r3], MODI(_r1, r2, _i) => vec![r2], MOVE(_r1, r2) => vec![r2], MOVI(_r1, _i) => vec![], MROO(_r1, r2, r3) => vec![r2, r3], MUL(_r1, r2, r3) => vec![r2, r3], MULI(_r1, r2, _i) => vec![r2], NOOP => vec![], NOT(_r1, r2) => vec![r2], OR(_r1, r2, r3) => vec![r2, r3], ORI(_r1, r2, _i) => vec![r2], SLL(_r1, r2, r3) => vec![r2, r3], SLLI(_r1, r2, _i) => vec![r2], SRL(_r1, r2, r3) => vec![r2, r3], SRLI(_r1, r2, _i) => vec![r2], SUB(_r1, r2, r3) => vec![r2, r3], SUBI(_r1, r2, _i) => vec![r2], XOR(_r1, r2, r3) => vec![r2, r3], XORI(_r1, r2, _i) => vec![r2], // Note that most of the `WQ..` instructions *read* from the `r1` result register, // because the register itself does not contain the result, but provides the // memory address at which the result will be stored. WQOP(r1, r2, r3, _) => vec![r1, r2, r3], WQML(r1, r2, r3, _) => vec![r1, r2, r3], WQDV(r1, r2, r3, _) => vec![r1, r2, r3], WQMD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], WQCM(_, r2, r3, _) => vec![r2, r3], WQAM(r1, r2, r3, r4) => vec![r1, r2, r3, r4], WQMM(r1, r2, r3, r4) => vec![r1, r2, r3, r4], /* Control Flow Instructions */ JMP(r1) => vec![r1], JI(_im) => vec![], JNE(r1, r2, r3) => vec![r1, r2, r3], JNEI(r1, r2, _i) => vec![r1, r2], JNZI(r1, _i) => vec![r1], JMPB(r1, _i) => vec![r1], JMPF(r1, _i) => vec![r1], JNZB(r1, r2, _i) => vec![r1, r2], JNZF(r1, r2, _i) => vec![r1, r2], JNEB(r1, r2, r3, _i) => vec![r1, r2, r3], JNEF(r1, r2, r3, _i) => vec![r1, r2, r3], JAL(_r1, r2, _i) => vec![r2], RET(r1) => vec![r1], /* Memory Instructions */ ALOC(hp, r1) => vec![hp, r1], CFEI(sp, _imm) => vec![sp], CFSI(sp, _imm) => vec![sp], CFE(sp, r1) => vec![sp, r1], CFS(sp, r1) => vec![sp, r1], LB(_r1, r2, _i) => vec![r2], LW(_r1, r2, _i) => vec![r2], MCL(r1, r2) => vec![r1, r2], MCLI(r1, _imm) => vec![r1], MCP(r1, r2, r3) => vec![r1, r2, r3], MCPI(r1, r2, _imm) => vec![r1, r2], MEQ(_r1, r2, r3, r4) => vec![r2, r3, r4], SB(r1, r2, _i) => vec![r1, r2], SW(r1, r2, _i) => vec![r1, r2], /* Contract Instructions */ BAL(_r1, r2, r3) => vec![r2, r3], BHEI(_r1) => vec![], BHSH(r1, r2) => vec![r1, r2], BURN(r1, r2) => vec![r1, r2], CALL(r1, r2, r3, r4) => vec![r1, r2, r3, r4], CB(r1) => vec![r1], CCP(r1, r2, r3, r4) => vec![r1, r2, r3, r4], CROO(r1, r2) => vec![r1, r2], CSIZ(_r1, r2) => vec![r2], BSIZ(_r1, r2) => vec![r2], LDC(r1, r2, r3, _i0) => vec![r1, r2, r3], BLDD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], LOG(r1, r2, r3, r4) => vec![r1, r2, r3, r4], LOGD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], MINT(r1, r2) => vec![r1, r2], RETD(r1, r2) => vec![r1, r2], RVRT(r1) => vec![r1], SMO(r1, r2, r3, r4) => vec![r1, r2, r3, r4], SCWQ(r1, _r2, r3) => vec![r1, r3], SRW(_r1, _r2, r3) => vec![r3], SRWQ(r1, _r2, r3, r4) => vec![r1, r3, r4], SWW(r1, _r2, r3) => vec![r1, r3], SWWQ(r1, _r2, r3, r4) => vec![r1, r3, r4], TIME(_r1, r2) => vec![r2], TR(r1, r2, r3) => vec![r1, r2, r3], TRO(r1, r2, r3, r4) => vec![r1, r2, r3, r4], /* Cryptographic Instructions */ ECK1(r1, r2, r3) => vec![r1, r2, r3], ECR1(r1, r2, r3) => vec![r1, r2, r3], ED19(r1, r2, r3, r4) => vec![r1, r2, r3, r4], K256(r1, r2, r3) => vec![r1, r2, r3], S256(r1, r2, r3) => vec![r1, r2, r3], ECOP(r1, r2, r3, r4) => vec![r1, r2, r3, r4], EPAR(_r1, r2, r3, r4) => vec![r2, r3, r4], /* Other Instructions */ ECAL(r1, r2, r3, r4) => vec![r1, r2, r3, r4], FLAG(r1) => vec![r1], GM(_r1, _imm) => vec![], GTF(_r1, r2, _i) => vec![r2], /* Non-VM Instructions */ BLOB(_imm) => vec![], DataSectionOffsetPlaceholder => vec![], ConfigurablesOffsetPlaceholder => vec![], LoadDataId(_r1, _i) => vec![], AddrDataId(_r1, _i) => vec![], Undefined => vec![], }) .into_iter() .collect() } /// Returns a list of all registers *read* by instruction `self`. pub(crate) fn use_registers_mut(&mut self) -> BTreeSet<&mut VirtualRegister> { use VirtualOp::*; (match self { /* Arithmetic/Logic (ALU) Instructions */ ADD(_r1, r2, r3) => vec![r2, r3], ADDI(_r1, r2, _i) => vec![r2], AND(_r1, r2, r3) => vec![r2, r3], ANDI(_r1, r2, _i) => vec![r2], DIV(_r1, r2, r3) => vec![r2, r3], DIVI(_r1, r2, _i) => vec![r2], EQ(_r1, r2, r3) => vec![r2, r3], EXP(_r1, r2, r3) => vec![r2, r3], EXPI(_r1, r2, _i) => vec![r2], GT(_r1, r2, r3) => vec![r2, r3], LT(_r1, r2, r3) => vec![r2, r3], MLOG(_r1, r2, r3) => vec![r2, r3], MOD(_r1, r2, r3) => vec![r2, r3], MODI(_r1, r2, _i) => vec![r2], MOVE(_r1, r2) => vec![r2], MOVI(_r1, _i) => vec![], MROO(_r1, r2, r3) => vec![r2, r3], MUL(_r1, r2, r3) => vec![r2, r3], MULI(_r1, r2, _i) => vec![r2], NOOP => vec![], NOT(_r1, r2) => vec![r2], OR(_r1, r2, r3) => vec![r2, r3], ORI(_r1, r2, _i) => vec![r2], SLL(_r1, r2, r3) => vec![r2, r3], SLLI(_r1, r2, _i) => vec![r2], SRL(_r1, r2, r3) => vec![r2, r3], SRLI(_r1, r2, _i) => vec![r2], SUB(_r1, r2, r3) => vec![r2, r3], SUBI(_r1, r2, _i) => vec![r2], XOR(_r1, r2, r3) => vec![r2, r3], XORI(_r1, r2, _i) => vec![r2], // Note that most of the `WQ..` instructions *read* from the `r1` result register, // because the register itself does not contain the result, but provides the // memory address at which the result will be stored. WQOP(r1, r2, r3, _) => vec![r1, r2, r3], WQML(r1, r2, r3, _) => vec![r1, r2, r3], WQDV(r1, r2, r3, _) => vec![r1, r2, r3], WQMD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], WQCM(_, r2, r3, _) => vec![r2, r3], WQAM(r1, r2, r3, r4) => vec![r1, r2, r3, r4], WQMM(r1, r2, r3, r4) => vec![r1, r2, r3, r4], /* Control Flow Instructions */ JMP(r1) => vec![r1], JI(_im) => vec![], JNE(r1, r2, r3) => vec![r1, r2, r3], JNEI(r1, r2, _i) => vec![r1, r2], JNZI(r1, _i) => vec![r1], JMPB(r1, _i) => vec![r1], JMPF(r1, _i) => vec![r1], JNZB(r1, r2, _i) => vec![r1, r2], JNZF(r1, r2, _i) => vec![r1, r2], JNEB(r1, r2, r3, _i) => vec![r1, r2, r3], JNEF(r1, r2, r3, _i) => vec![r1, r2, r3], JAL(_r1, r2, _i) => vec![r2], RET(r1) => vec![r1], /* Memory Instructions */ ALOC(hp, r1) => vec![hp, r1], CFEI(sp, _imm) => vec![sp], CFSI(sp, _imm) => vec![sp], CFE(sp, r1) => vec![sp, r1], CFS(sp, r1) => vec![sp, r1], LB(_r1, r2, _i) => vec![r2], LW(_r1, r2, _i) => vec![r2], MCL(r1, r2) => vec![r1, r2], MCLI(r1, _imm) => vec![r1], MCP(r1, r2, r3) => vec![r1, r2, r3], MCPI(r1, r2, _imm) => vec![r1, r2], MEQ(_r1, r2, r3, r4) => vec![r2, r3, r4], SB(r1, r2, _i) => vec![r1, r2], SW(r1, r2, _i) => vec![r1, r2], /* Contract Instructions */ BAL(_r1, r2, r3) => vec![r2, r3], BHEI(_r1) => vec![], BHSH(r1, r2) => vec![r1, r2], BURN(r1, r2) => vec![r1, r2], CALL(r1, r2, r3, r4) => vec![r1, r2, r3, r4], CB(r1) => vec![r1], CCP(r1, r2, r3, r4) => vec![r1, r2, r3, r4], CROO(r1, r2) => vec![r1, r2], CSIZ(_r1, r2) => vec![r2], BSIZ(_r1, r2) => vec![r2], LDC(r1, r2, r3, _i0) => vec![r1, r2, r3], BLDD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], LOG(r1, r2, r3, r4) => vec![r1, r2, r3, r4], LOGD(r1, r2, r3, r4) => vec![r1, r2, r3, r4], MINT(r1, r2) => vec![r1, r2], RETD(r1, r2) => vec![r1, r2], RVRT(r1) => vec![r1], SMO(r1, r2, r3, r4) => vec![r1, r2, r3, r4], SCWQ(r1, _r2, r3) => vec![r1, r3], SRW(_r1, _r2, r3) => vec![r3], SRWQ(r1, _r2, r3, r4) => vec![r1, r3, r4], SWW(r1, _r2, r3) => vec![r1, r3], SWWQ(r1, _r2, r3, r4) => vec![r1, r3, r4], TIME(_r1, r2) => vec![r2], TR(r1, r2, r3) => vec![r1, r2, r3], TRO(r1, r2, r3, r4) => vec![r1, r2, r3, r4], /* Cryptographic Instructions */ ECK1(r1, r2, r3) => vec![r1, r2, r3], ECR1(r1, r2, r3) => vec![r1, r2, r3], ED19(r1, r2, r3, r4) => vec![r1, r2, r3, r4], K256(r1, r2, r3) => vec![r1, r2, r3], S256(r1, r2, r3) => vec![r1, r2, r3], ECOP(r1, r2, r3, r4) => vec![r1, r2, r3, r4], EPAR(_r1, r2, r3, r4) => vec![r2, r3, r4], /* Other Instructions */ ECAL(r1, r2, r3, r4) => vec![r1, r2, r3, r4], FLAG(r1) => vec![r1], GM(_r1, _imm) => vec![], GTF(_r1, r2, _i) => vec![r2], /* Non-VM Instructions */ BLOB(_imm) => vec![], DataSectionOffsetPlaceholder => vec![], ConfigurablesOffsetPlaceholder => vec![], LoadDataId(_r1, _i) => vec![], AddrDataId(_r1, _i) => vec![], Undefined => vec![], }) .into_iter() .collect() }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/asm_lang/virtual_immediate.rs
sway-core/src/asm_lang/virtual_immediate.rs
use crate::asm_generation::fuel::compiler_constants; use fuel_vm::fuel_asm::Imm18; use sway_error::error::CompileError; use sway_types::span::Span; use std::convert::TryInto; use std::fmt; #[repr(u8)] pub enum WideOperations { Add = 0, Sub = 1, Not = 2, Or = 3, Xor = 4, And = 5, Lsh = 6, Rsh = 7, } #[repr(u8)] pub enum WideCmp { Equality = 0, LessThan = 2, GreaterThan = 3, } /// 6-bit immediate value type #[derive(Clone, Debug)] pub struct VirtualImmediate06 { value: u8, } impl VirtualImmediate06 { pub(crate) fn try_new(raw: u64, err_msg_span: Span) -> Result<Self, CompileError> { if raw > compiler_constants::SIX_BITS { Err(CompileError::Immediate06TooLarge { val: raw, span: err_msg_span, }) } else { Ok(Self { value: raw.try_into().unwrap(), }) } } pub(crate) fn new(raw: u64) -> Self { Self::try_new(raw, Span::dummy()).unwrap_or_else(|_| panic!("{} cannot fit in 6 bits", raw)) } pub fn wide_op(op: WideOperations, rhs_indirect: bool) -> VirtualImmediate06 { VirtualImmediate06 { value: (op as u8) | if rhs_indirect { 32u8 } else { 0 }, } } pub fn wide_cmp(op: WideCmp, rhs_indirect: bool) -> VirtualImmediate06 { VirtualImmediate06 { value: (op as u8) | if rhs_indirect { 32u8 } else { 0 }, } } pub fn wide_mul(lhs_indirect: bool, rhs_indirect: bool) -> VirtualImmediate06 { let lhs = if lhs_indirect { 16u8 } else { 0 }; let rhs = if rhs_indirect { 32u8 } else { 0 }; VirtualImmediate06 { value: lhs | rhs } } pub fn wide_div(rhs_indirect: bool) -> VirtualImmediate06 { let rhs = if rhs_indirect { 32u8 } else { 0 }; VirtualImmediate06 { value: rhs } } pub fn value(&self) -> u8 { self.value } } impl fmt::Display for VirtualImmediate06 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "i{}", self.value) } } /// 12-bits immediate value type #[derive(Clone, Debug)] pub struct VirtualImmediate12 { value: u16, } impl VirtualImmediate12 { pub(crate) fn try_new(raw: u64, err_msg_span: Span) -> Result<Self, CompileError> { if raw > compiler_constants::TWELVE_BITS { Err(CompileError::Immediate12TooLarge { val: raw, span: err_msg_span, }) } else { Ok(Self { value: raw.try_into().unwrap(), }) } } pub(crate) fn new(raw: u64) -> Self { Self::try_new(raw, Span::dummy()) .unwrap_or_else(|_| panic!("{} cannot fit in 12 bits", raw)) } pub fn value(&self) -> u16 { self.value } } impl fmt::Display for VirtualImmediate12 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "i{}", self.value) } } /// 18-bits immediate value type #[derive(Clone, Debug)] pub struct VirtualImmediate18 { value: u32, } impl VirtualImmediate18 { pub(crate) fn try_new(raw: u64, err_msg_span: Span) -> Result<Self, CompileError> { if raw > compiler_constants::EIGHTEEN_BITS { Err(CompileError::Immediate18TooLarge { val: raw, span: err_msg_span, }) } else { Ok(Self { value: raw.try_into().unwrap(), }) } } pub(crate) fn new(raw: u64) -> Self { Self::try_new(raw, Span::dummy()) .unwrap_or_else(|_| panic!("{} cannot fit in 18 bits", raw)) } pub fn value(&self) -> u32 { self.value } pub fn as_imm18(&self) -> Option<Imm18> { Imm18::new_checked(self.value) } } impl fmt::Display for VirtualImmediate18 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "i{}", self.value) } } /// 24-bits immediate value type #[derive(Clone, Debug)] pub struct VirtualImmediate24 { value: u32, } impl VirtualImmediate24 { pub(crate) fn try_new(raw: u64, err_msg_span: Span) -> Result<Self, CompileError> { if raw > compiler_constants::TWENTY_FOUR_BITS { Err(CompileError::Immediate24TooLarge { val: raw, span: err_msg_span, }) } else { Ok(Self { value: raw.try_into().unwrap(), }) } } pub(crate) fn new(raw: u64) -> Self { Self::try_new(raw, Span::dummy()) .unwrap_or_else(|_| panic!("{} cannot fit in 24 bits", raw)) } pub fn value(&self) -> u32 { self.value } } impl fmt::Display for VirtualImmediate24 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "i{}", self.value) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false