Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rust: Inline format args #1030

Open
wants to merge 1 commit into
base: rust
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions drivers/gpio/gpio_pl061_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,7 @@ impl irq::Chip for PL061Device {
{
dev_err!(
data.dev,
"trying to configure line {} for both level and edge detection, choose one!\n",
offset
"trying to configure line {offset} for both level and edge detection, choose one!\n",
);
return Err(EINVAL);
}
Expand Down Expand Up @@ -172,8 +171,7 @@ impl irq::Chip for PL061Device {
irq_data.set_level_handler();
dev_dbg!(
data.dev,
"line {}: IRQ on {} level\n",
offset,
"line {offset}: IRQ on {} level\n",
if polarity { "HIGH" } else { "LOW" }
);
} else if (trigger & irq::Type::EDGE_BOTH) == irq::Type::EDGE_BOTH {
Expand All @@ -182,7 +180,7 @@ impl irq::Chip for PL061Device {
// Select both edges, settings this makes GPIOEV be ignored.
gpioibe |= bit;
irq_data.set_edge_handler();
dev_dbg!(data.dev, "line {}: IRQ on both edges\n", offset);
dev_dbg!(data.dev, "line {offset}: IRQ on both edges\n");
} else if trigger & (irq::Type::EDGE_RISING | irq::Type::EDGE_FALLING) != 0 {
let rising = trigger & irq::Type::EDGE_RISING != 0;

Expand All @@ -199,8 +197,7 @@ impl irq::Chip for PL061Device {
irq_data.set_edge_handler();
dev_dbg!(
data.dev,
"line {}: IRQ on {} edge\n",
offset,
"line {offset}: IRQ on {} edge\n",
if rising { "RISING" } else { "FALLING}" }
);
} else {
Expand All @@ -209,7 +206,7 @@ impl irq::Chip for PL061Device {
gpioibe &= !bit;
gpioiev &= !bit;
irq_data.set_bad_handler();
dev_warn!(data.dev, "no trigger selected for line {}\n", offset);
dev_warn!(data.dev, "no trigger selected for line {offset}\n");
}

pl061.base.writeb(gpiois, GPIOIS);
Expand Down
2 changes: 2 additions & 0 deletions rust/build_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,7 @@
#[export_name = "rust_build_error"]
#[track_caller]
pub const fn build_error(msg: &'static str) -> ! {
// This uses const context expansion panic! special case:
// https://github.com/rust-lang/rust/issues/108595
panic!("{}", msg);
}
5 changes: 1 addition & 4 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,7 @@ impl Error {
pub(crate) fn from_kernel_errno(errno: core::ffi::c_int) -> Error {
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
// TODO: Make it a `WARN_ONCE` once available.
crate::pr_warn!(
"attempted to create `Error` with out of range `errno`: {}",
errno
);
crate::pr_warn!("attempted to create `Error` with out of range `errno`: {errno}");
return code::EINVAL;
}

Expand Down
2 changes: 1 addition & 1 deletion rust/kernel/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ macro_rules! container_of {
#[cfg(not(any(testlib, test)))]
#[panic_handler]
fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
pr_emerg!("{}\n", info);
pr_emerg!("{info}\n");
// SAFETY: FFI call.
unsafe { bindings::BUG() };
// Bindgen currently does not recognize `__noreturn` so `BUG` returns `()`
Expand Down
6 changes: 3 additions & 3 deletions rust/kernel/module_param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ impl<T: Copy, const N: usize> ArrayParam<T, { N }> {
impl<T: core::fmt::Display, const N: usize> core::fmt::Display for ArrayParam<T, { N }> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for val in self.values() {
write!(f, "{},", val)?;
write!(f, "{val},")?;
}
Ok(())
}
Expand Down Expand Up @@ -462,8 +462,8 @@ impl core::fmt::Display for StringParam {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let bytes = self.bytes();
match core::str::from_utf8(bytes) {
Ok(utf8) => write!(f, "{}", utf8),
Err(_) => write!(f, "{:?}", bytes),
Ok(utf8) => write!(f, "{utf8}"),
Err(_) => write!(f, "{bytes:?}"),
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions rust/kernel/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,11 @@ impl fmt::Display for CStr {
/// # use kernel::str::CStr;
/// # use kernel::str::CString;
/// let penguin = c_str!("🐧");
/// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap();
/// let s = CString::try_from_fmt(fmt!("{penguin}")).unwrap();
/// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes());
///
/// let ascii = c_str!("so \"cool\"");
/// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap();
/// let s = CString::try_from_fmt(fmt!("{ascii}")).unwrap();
/// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes());
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand All @@ -222,7 +222,7 @@ impl fmt::Display for CStr {
// Printable character.
f.write_char(c as char)?;
} else {
write!(f, "\\x{:02x}", c)?;
write!(f, "\\x{c:02x}")?;
}
}
Ok(())
Expand All @@ -237,12 +237,12 @@ impl fmt::Debug for CStr {
/// # use kernel::str::CStr;
/// # use kernel::str::CString;
/// let penguin = c_str!("🐧");
/// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap();
/// let s = CString::try_from_fmt(fmt!("{penguin:?}")).unwrap();
/// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes());
///
/// // Embedded double quotes are escaped.
/// let ascii = c_str!("so \"cool\"");
/// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap();
/// let s = CString::try_from_fmt(fmt!("{ascii:?}")).unwrap();
/// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes());
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand All @@ -252,7 +252,7 @@ impl fmt::Debug for CStr {
// Printable characters.
b'\"' => f.write_str("\\\"")?,
0x20..=0x7e => f.write_char(c as char)?,
_ => write!(f, "\\x{:02x}", c)?,
_ => write!(f, "\\x{c:02x}")?,
}
}
f.write_str("\"")
Expand Down
2 changes: 1 addition & 1 deletion rust/kernel/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ define_unsigned_number_traits!(usize);
///
/// fn print_bits(x: usize) {
/// for bit in bits_iter(x) {
/// pr_info!("{}\n", bit);
/// pr_info!("{bit}\n");
/// }
/// }
///
Expand Down
2 changes: 1 addition & 1 deletion rust/kernel/workqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ macro_rules! init_work_item_adapter {
///
/// kernel::impl_self_work_adapter!(Example, work, |w| {
/// let count = w.count.fetch_add(1, Ordering::Relaxed);
/// pr_info!("Called with count={}\n", count);
/// pr_info!("Called with count={count}\n");
///
/// // Queue again if the count is less than 10.
/// if count < 10 {
Expand Down
23 changes: 7 additions & 16 deletions rust/macros/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ fn param_ops_path(param_type: &str) -> &'static str {
"isize" => "kernel::module_param::PARAM_OPS_ISIZE",
"usize" => "kernel::module_param::PARAM_OPS_USIZE",
"str" => "kernel::module_param::PARAM_OPS_STR",
t => panic!("Unrecognized type {}", t),
t => panic!("Unrecognized type {t}"),
}
}

Expand All @@ -151,7 +151,7 @@ fn try_simple_param_val(
"bool" => Box::new(try_ident),
"str" => Box::new(|param_it| {
try_byte_string(param_it)
.map(|s| format!("kernel::module_param::StringParam::Ref(b\"{}\")", s))
.map(|s| format!("kernel::module_param::StringParam::Ref(b\"{s}\")"))
}),
_ => Box::new(try_literal),
}
Expand Down Expand Up @@ -247,10 +247,7 @@ impl ModuleInfo {
};

if seen_keys.contains(&key) {
panic!(
"Duplicated key \"{}\". Keys can only be specified once.",
key
);
panic!("Duplicated key \"{key}\". Keys can only be specified once.");
}

assert_eq!(expect_punct(it), ':');
Expand All @@ -266,10 +263,7 @@ impl ModuleInfo {
info.alias = Some(format!("rtnl-link-{}", expect_string_ascii(it)))
}
"params" => info.params = Some(expect_group(it)),
_ => panic!(
"Unknown key \"{}\". Valid keys are: {:?}.",
key, EXPECTED_KEYS
),
_ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."),
}

assert_eq!(expect_punct(it), ',');
Expand All @@ -281,7 +275,7 @@ impl ModuleInfo {

for key in REQUIRED_KEYS {
if !seen_keys.iter().any(|e| e == key) {
panic!("Missing required key \"{}\".", key);
panic!("Missing required key \"{key}\".");
}
}

Expand All @@ -293,10 +287,7 @@ impl ModuleInfo {
}

if seen_keys != ordered_keys {
panic!(
"Keys are not ordered as expected. Order them like: {:?}.",
ordered_keys
);
panic!("Keys are not ordered as expected. Order them like: {ordered_keys:?}.");
}

info
Expand Down Expand Up @@ -364,7 +355,7 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
} => {
array_types_to_generate.push((vals.clone(), max_length));
(
format!("__rust_array_param_{}_{}", vals, max_length),
format!("__rust_array_param_{vals}_{max_length}"),
generated_array_ops_name(vals, max_length),
)
}
Expand Down
2 changes: 1 addition & 1 deletion samples/rust/hostprogs/a.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
//! Rust single host program sample: module `a`.

pub(crate) fn f(x: i32) {
println!("The number is {}.", x);
println!("The number is {x}.");
}
12 changes: 6 additions & 6 deletions scripts/generate_rust_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ type Object = Vec<(String, Value)>;
impl Display for Value {
fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
match self {
Value::Boolean(boolean) => write!(formatter, "{}", boolean),
Value::Number(number) => write!(formatter, "{}", number),
Value::String(string) => write!(formatter, "\"{}\"", string),
Value::Boolean(boolean) => write!(formatter, "{boolean}"),
Value::Number(number) => write!(formatter, "{number}"),
Value::String(string) => write!(formatter, "\"{string}\""),
Value::Object(object) => {
formatter.write_str("{")?;
if let [ref rest @ .., ref last] = object[..] {
for (key, value) in rest {
write!(formatter, "\"{}\": {},", key, value)?;
write!(formatter, "\"{key}\": {value},")?;
}
write!(formatter, "\"{}\": {}", last.0, last.1)?;
}
Expand Down Expand Up @@ -95,7 +95,7 @@ impl Display for TargetSpec {
formatter.write_str("{\n")?;
if let [ref rest @ .., ref last] = self.0[..] {
for (key, value) in rest {
write!(formatter, " \"{}\": {},\n", key, value)?;
write!(formatter, " \"{key}\": {value},\n")?;
}
write!(formatter, " \"{}\": {}\n", last.0, last.1)?;
}
Expand Down Expand Up @@ -228,5 +228,5 @@ fn main() {
ts.push("target-endian", "big");
}

println!("{}", ts);
println!("{ts}");
}