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

Make use of implicit format string arguments #1266

Merged
merged 1 commit into from
Jun 16, 2022
Merged
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
2 changes: 1 addition & 1 deletion examples/rondpoint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ impl Stringifier {
value.to_string()
}
fn well_known_string(&self, value: String) -> String {
format!("uniffi 💚 {}!", value)
format!("uniffi 💚 {value}!")
}
}

Expand Down
10 changes: 5 additions & 5 deletions fixtures/coverall/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,15 +159,15 @@ impl Coveralls {
}

fn fallible_panic(&self, message: String) -> Result<()> {
panic!("{}", message);
panic!("{message}");
}

fn get_name(&self) -> String {
self.name.clone()
}

fn panicing_new(message: String) -> Self {
panic!("{}", message);
panic!("{message}");
}

fn maybe_throw(&self, should_throw: bool) -> Result<bool> {
Expand Down Expand Up @@ -201,7 +201,7 @@ impl Coveralls {
}

fn panic(&self, message: String) {
panic!("{}", message);
panic!("{message}");
}

fn strong_count(self: Arc<Self>) -> u64 {
Expand All @@ -221,7 +221,7 @@ impl Coveralls {
}

fn take_other_panic(self: Arc<Self>, message: String) {
panic!("{}", message);
panic!("{message}");
}

fn clone_me(&self) -> Arc<Self> {
Expand All @@ -235,7 +235,7 @@ impl Coveralls {
}

fn get_status(&self, status: String) -> String {
format!("status: {}", status)
format!("status: {status}")
}

fn get_dict(&self, key: String, value: u64) -> HashMap<String, u64> {
Expand Down
4 changes: 2 additions & 2 deletions fixtures/reexport-scaffolding-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ mod tests {
let output = std::io::BufReader::new(child.stdout.take().unwrap());
let artifacts = Message::parse_stream(output)
.filter_map(|message| match message {
Err(e) => panic!("{}", e),
Err(e) => panic!("{e}"),
Ok(Message::CompilerArtifact(artifact)) => {
if artifact.target.name == "reexport_scaffolding_macro"
&& artifact.target.kind.iter().any(|item| item == "cdylib")
Expand All @@ -39,7 +39,7 @@ mod tests {
}
let artifact = match artifacts.len() {
1 => &artifacts[0],
n => panic!("Found {} artfiacts from cargo build", n),
n => panic!("Found {n} artfiacts from cargo build"),
};
let cdylib_files: Vec<_> = artifact
.filenames
Expand Down
4 changes: 2 additions & 2 deletions uniffi/src/ffi/rustcalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ mod test {
fn function(a: u8) -> i8 {
match a {
0 => 100,
x => panic!("Unexpected value: {}", x),
x => panic!("Unexpected value: {x}"),
}
}

Expand Down Expand Up @@ -240,7 +240,7 @@ mod test {
match a {
0 => Ok(100),
1 => Err(TestError("Error".to_owned())),
x => panic!("Unexpected value: {}", x),
x => panic!("Unexpected value: {x}"),
}
}

Expand Down
9 changes: 4 additions & 5 deletions uniffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,10 @@ pub unsafe trait FfiConverter: Sized {
/// helper function to instead return an explicit error, to help with debugging.
pub fn check_remaining(buf: &[u8], num_bytes: usize) -> Result<()> {
if buf.remaining() < num_bytes {
bail!(format!(
"not enough bytes remaining in buffer ({} < {})",
bail!(
"not enough bytes remaining in buffer ({} < {num_bytes})",
buf.remaining(),
num_bytes
));
);
}
Ok(())
}
Expand Down Expand Up @@ -640,7 +639,7 @@ where
{
match err.downcast::<ErrConverter::RustType>() {
Ok(actual_error) => ErrConverter::lower(actual_error),
Err(ohno) => panic!("Failed to convert arg '{}': {}", arg_name, ohno),
Err(ohno) => panic!("Failed to convert arg '{arg_name}': {ohno}"),
}
}

Expand Down
2 changes: 1 addition & 1 deletion uniffi/src/panichook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub fn ensure_setup() {
// in the future.
("<unknown>", 0)
};
log::error!("### Rust `panic!` hit at file '{}', line {}", file, line);
log::error!("### Rust `panic!` hit at file '{file}', line {line}");
#[cfg(all(feature = "log_backtraces", not(target_os = "android")))]
{
log::error!(" Complete stack trace:\n{:?}", backtrace::Backtrace::new());
Expand Down
8 changes: 3 additions & 5 deletions uniffi/src/testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,13 @@ pub fn ensure_compiled_cdylib(pkg_dir: &str) -> Result<Utf8PathBuf> {
{
Some(cdylib) => {
log::warn!(
"Crate produced multiple cdylibs, using the one produced by {}",
pkg_dir
"Crate produced multiple cdylibs, using the one produced by {pkg_dir}",
);
cdylib
}
None => {
bail!(
"Crate produced multiple cdylibs, none of which is produced by {}",
pkg_dir
"Crate produced multiple cdylibs, none of which is produced by {pkg_dir}",
);
}
}
Expand Down Expand Up @@ -145,7 +143,7 @@ fn run_uniffi_bindgen_test(out_dir: &str, udl_files: &[&str], test_file: &str) -
.args(&["test", out_dir, &udl_files, test_file])
.status()?;
if !status.success() {
bail!("Error while running tests: {}", status);
bail!("Error while running tests: {status}");
}
Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion uniffi_bindgen/src/interface/callbacks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl CallbackInterface {
}

pub(super) fn derive_ffi_funcs(&mut self, ci_prefix: &str) {
self.ffi_init_callback.name = format!("ffi_{}_{}_init_callback", ci_prefix, self.name);
self.ffi_init_callback.name = format!("ffi_{ci_prefix}_{}_init_callback", self.name);
self.ffi_init_callback.arguments = vec![FFIArgument {
name: "callback_stub".to_string(),
type_: FFIType::ForeignCallback,
Expand Down
2 changes: 1 addition & 1 deletion uniffi_bindgen/src/interface/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl Function {
// The name is already set if the function is defined in a proc-macro-generated JSON file
// rather than in UDL. Don't overwrite it in that case.
if self.ffi_func.name.is_empty() {
self.ffi_func.name = format!("{}_{}", ci_prefix, self.name);
self.ffi_func.name = format!("{ci_prefix}_{}", self.name);
}

self.ffi_func.arguments = self.arguments.iter().map(|arg| arg.into()).collect();
Expand Down
2 changes: 1 addition & 1 deletion uniffi_bindgen/src/interface/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl ComponentInterface {
let (remaining, defns) = weedle::Definitions::parse(idl.trim()).unwrap();
if !remaining.is_empty() {
println!("Error parsing the IDL. Text remaining to be parsed is:");
println!("{}", remaining);
println!("{remaining}");
bail!("parse error");
}
// Unconditionally add the String type, which is used by the panic handling
Expand Down
8 changes: 4 additions & 4 deletions uniffi_bindgen/src/interface/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl Object {
let matches: Vec<_> = self.methods.iter().filter(|m| m.name() == name).collect();
match matches.len() {
1 => matches[0].clone(),
n => panic!("{} methods named {}", n, name),
n => panic!("{n} methods named {name}"),
}
}

Expand All @@ -155,7 +155,7 @@ impl Object {
}

pub fn derive_ffi_funcs(&mut self, ci_prefix: &str) -> Result<()> {
self.ffi_func_free.name = format!("ffi_{}_{}_object_free", ci_prefix, self.name);
self.ffi_func_free.name = format!("ffi_{ci_prefix}_{}_object_free", self.name);
self.ffi_func_free.arguments = vec![FFIArgument {
name: "ptr".to_string(),
type_: FFIType::RustArcPtr(self.name().to_string()),
Expand Down Expand Up @@ -276,7 +276,7 @@ impl Constructor {
}

fn derive_ffi_func(&mut self, ci_prefix: &str, obj_name: &str) {
self.ffi_func.name = format!("{}_{}_{}", ci_prefix, obj_name, self.name);
self.ffi_func.name = format!("{ci_prefix}_{obj_name}_{}", self.name);
self.ffi_func.arguments = self.arguments.iter().map(Into::into).collect();
self.ffi_func.return_type = Some(FFIType::RustArcPtr(obj_name.to_string()));
}
Expand Down Expand Up @@ -389,7 +389,7 @@ impl Method {
}

pub fn derive_ffi_func(&mut self, ci_prefix: &str, obj_prefix: &str) -> Result<()> {
self.ffi_func.name = format!("{}_{}_{}", ci_prefix, obj_prefix, self.name);
self.ffi_func.name = format!("{ci_prefix}_{obj_prefix}_{}", self.name);
self.ffi_func.arguments = self.full_arguments().iter().map(Into::into).collect();
self.ffi_func.return_type = self.return_type.as_ref().map(Into::into);
Ok(())
Expand Down
19 changes: 9 additions & 10 deletions uniffi_bindgen/src/interface/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ impl Type {
// cases like a record named `SequenceRecord` interfering with `sequence<Record>`.
// However, types that support importing all end up with the same prefix of "Type", so
// that the import handling code knows how to find the remote reference.
Type::Object(nm) => format!("Type{}", nm),
Type::Error(nm) => format!("Type{}", nm),
Type::Enum(nm) => format!("Type{}", nm),
Type::Record(nm) => format!("Type{}", nm),
Type::CallbackInterface(nm) => format!("CallbackInterface{}", nm),
Type::Object(nm) => format!("Type{nm}"),
Type::Error(nm) => format!("Type{nm}"),
Type::Enum(nm) => format!("Type{nm}"),
Type::Record(nm) => format!("Type{nm}"),
Type::CallbackInterface(nm) => format!("CallbackInterface{nm}"),
Type::Timestamp => "Timestamp".into(),
Type::Duration => "Duration".into(),
// Recursive types.
Expand All @@ -117,7 +117,7 @@ impl Type {
v.canonical_name().to_upper_camel_case()
),
// A type that exists externally.
Type::External { name, .. } | Type::Custom { name, .. } => format!("Type{}", name),
Type::External { name, .. } | Type::Custom { name, .. } => format!("Type{name}"),
}
}

Expand Down Expand Up @@ -217,14 +217,13 @@ impl TypeUniverse {
pub fn add_type_definition(&mut self, name: &str, type_: Type) -> Result<()> {
if resolve_builtin_type(name).is_some() {
bail!(
"please don't shadow builtin types ({}, {})",
name,
type_.canonical_name()
"please don't shadow builtin types ({name}, {})",
type_.canonical_name(),
);
}
let type_ = self.add_known_type(type_)?;
match self.type_definitions.entry(name.to_string()) {
Entry::Occupied(_) => bail!("Conflicting type definition for \"{}\"", name),
Entry::Occupied(_) => bail!("Conflicting type definition for \"{name}\""),
Entry::Vacant(e) => {
e.insert(type_);
Ok(())
Expand Down
16 changes: 7 additions & 9 deletions uniffi_bindgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,9 @@ fn load_bindings_config_toml<BC: BindingGeneratorConfig>(
}

let contents = fs::read_to_string(&config_path)
.with_context(|| format!("Failed to read config file from {}", config_path))?;
.with_context(|| format!("Failed to read config file from {config_path}"))?;
let full_config = toml::Value::from_str(&contents)
.with_context(|| format!("Failed to parse config file {}", config_path))?;
.with_context(|| format!("Failed to parse config file {config_path}"))?;

Ok(full_config
.get("bindings")
Expand Down Expand Up @@ -286,7 +286,7 @@ pub fn generate_component_scaffolding(
config_file_override,
);
let file_stem = udl_file.file_stem().context("not a file")?;
let filename = format!("{}.uniffi.rs", file_stem);
let filename = format!("{file_stem}.uniffi.rs");
let out_dir = get_out_dir(udl_file, out_dir_override)?.join(filename);
let mut f = File::create(&out_dir)?;
write!(f, "{}", RustScaffolding::new(&component)).context("Failed to write output file")?;
Expand Down Expand Up @@ -418,9 +418,9 @@ fn get_config(
match config_file {
Some(path) => {
let contents = fs::read_to_string(&path)
.with_context(|| format!("Failed to read config file from {}", &path))?;
.with_context(|| format!("Failed to read config file from {path}"))?;
let loaded_config: Config = toml::de::from_str(&contents)
.with_context(|| format!("Failed to generate config from file {}", &path))?;
.with_context(|| format!("Failed to generate config from file {path}"))?;
Ok(loaded_config.merge_with(&default_config))
}
None => Ok(default_config),
Expand All @@ -443,7 +443,7 @@ fn get_out_dir(udl_file: &Utf8Path, out_dir_override: Option<&Utf8Path>) -> Resu

fn parse_udl(udl_file: &Utf8Path) -> Result<ComponentInterface> {
let udl = fs::read_to_string(udl_file)
.with_context(|| format!("Failed to read UDL from {}", &udl_file))?;
.with_context(|| format!("Failed to read UDL from {udl_file}"))?;
ComponentInterface::from_webidl(&udl).context("Failed to parse UDL")
}

Expand Down Expand Up @@ -478,9 +478,7 @@ fn rebuild_metadata(crate_root: &Utf8Path) -> anyhow::Result<()> {
.to_string_lossy();
ensure!(
filename.ends_with(".json"),
"all files in `{}` must have `.json` file endings, found `{}`",
metadata_dir,
filename,
"all files in `{metadata_dir}` must have `.json` file endings, found `{filename}`",
);

fs::remove_file(path)?;
Expand Down
6 changes: 1 addition & 5 deletions uniffi_bindgen/src/macro_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ pub(crate) fn add_macro_metadata(
.map_err(|_| anyhow!("non-utf8 file names are not supported"))?;

let file_basename = file_name.strip_suffix(".json").ok_or_else(|| {
anyhow!(
"expected only JSON files in `{}`, found `{}`",
metadata_dir,
file_name
)
anyhow!("expected only JSON files in `{metadata_dir}`, found `{file_name}`")
})?;

let mut segments = match file_basename.strip_prefix("mod.") {
Expand Down
2 changes: 1 addition & 1 deletion uniffi_build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use std::env;
pub fn generate_scaffolding(udl_file: impl AsRef<Utf8Path>) -> Result<()> {
let udl_file = udl_file.as_ref();

println!("cargo:rerun-if-changed={}", udl_file);
println!("cargo:rerun-if-changed={udl_file}");
// The UNIFFI_TESTS_DISABLE_EXTENSIONS variable disables some bindings, but it is evaluated
// at *build* time, so we need to rebuild when it changes.
println!("cargo:rerun-if-env-changed=UNIFFI_TESTS_DISABLE_EXTENSIONS");
Expand Down
2 changes: 1 addition & 1 deletion uniffi_macros/src/export/metadata/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub(super) fn gen_fn_metadata(item: syn::ItemFn, mod_path: &[String]) -> syn::Re
));

let tracked_file = write_json_metadata(&path, &meta)
.map_err(|e| syn::Error::new(Span::call_site(), format!("failed to write file: {}", e)))?;
.map_err(|e| syn::Error::new(Span::call_site(), format!("failed to write file: {e}")))?;

Ok(ExportItem::Function {
item,
Expand Down
4 changes: 2 additions & 2 deletions uniffi_macros/src/export/scaffolding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn gen_fn_scaffolding(
}
FnArg::Typed(pat_ty) => {
let ty = &pat_ty.ty;
let name = format_ident!("arg{}", i);
let name = format_ident!("arg{i}");

params.push(quote! { #name: <#ty as ::uniffi::FfiConverter>::FfiType });

Expand All @@ -58,7 +58,7 @@ fn gen_fn_scaffolding(
format!("Failed to convert arg '{}': {{}}", i.ident)
}
_ => {
format!("Failed to convert arg #{}: {{}}", i)
format!("Failed to convert arg #{i}: {{}}")
}
};
args.push(quote! {
Expand Down
2 changes: 1 addition & 1 deletion uniffi_macros/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub fn mod_path() -> syn::Result<Vec<String>> {
let cargo_toml_bytes =
fs::read(Path::new(&manifest_dir).join("Cargo.toml")).map_err(|e| e.to_string())?;
let cargo_toml = toml::from_slice::<CargoToml>(&cargo_toml_bytes)
.map_err(|e| format!("Failed to parse `Cargo.toml`: {}", e))?;
.map_err(|e| format!("Failed to parse `Cargo.toml`: {e}"))?;

let lib_crate_name = cargo_toml
.lib
Expand Down
Loading