diff --git a/analysis/runtime/src/events.rs b/analysis/runtime/src/events.rs index 9338119b3..e6a6e11a4 100644 --- a/analysis/runtime/src/events.rs +++ b/analysis/runtime/src/events.rs @@ -89,31 +89,31 @@ impl Debug for EventKind { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use EventKind::*; match *self { - CopyPtr(ptr) => write!(f, "copy(0x{:x})", ptr), - Field(ptr, id) => write!(f, "field(0x{:x}, {})", ptr, id), + CopyPtr(ptr) => write!(f, "copy(0x{ptr:x})"), + Field(ptr, id) => write!(f, "field(0x{ptr:x}, {id})"), Alloc { size, ptr } => { - write!(f, "malloc({}) -> 0x{:x}", size, ptr) + write!(f, "malloc({size}) -> 0x{ptr:x}") } - Free { ptr } => write!(f, "free(0x{:x})", ptr), + Free { ptr } => write!(f, "free(0x{ptr:x})"), Realloc { old_ptr, size, new_ptr, - } => write!(f, "realloc(0x{:x}, {}) -> 0x{:x}", old_ptr, size, new_ptr), - Ret(ptr) => write!(f, "ret(0x{:x})", ptr), + } => write!(f, "realloc(0x{old_ptr:x}, {size}) -> 0x{new_ptr:x}"), + Ret(ptr) => write!(f, "ret(0x{ptr:x})"), Done => write!(f, "done"), BeginFuncBody => write!(f, "begin func body"), - LoadAddr(ptr) => write!(f, "load(0x{:x})", ptr), - StoreAddr(ptr) => write!(f, "store(0x{:x})", ptr), - StoreAddrTaken(ptr) => write!(f, "store(0x{:x})", ptr), + LoadAddr(ptr) => write!(f, "load(0x{ptr:x})"), + StoreAddr(ptr) => write!(f, "store(0x{ptr:x})"), + StoreAddrTaken(ptr) => write!(f, "store(0x{ptr:x})"), CopyRef => write!(f, "copy_ref"), - AddrOfLocal(ptr, _) => write!(f, "addr_of_local = 0x{:x}", ptr), - ToInt(ptr) => write!(f, "to_int(0x{:x})", ptr), - FromInt(ptr) => write!(f, "from_int(0x{:x})", ptr), - LoadValue(ptr) => write!(f, "load_value(0x{:x})", ptr), - StoreValue(ptr) => write!(f, "store_value(0x{:x})", ptr), + AddrOfLocal(ptr, _) => write!(f, "addr_of_local = 0x{ptr:x}"), + ToInt(ptr) => write!(f, "to_int(0x{ptr:x})"), + FromInt(ptr) => write!(f, "from_int(0x{ptr:x})"), + LoadValue(ptr) => write!(f, "load_value(0x{ptr:x})"), + StoreValue(ptr) => write!(f, "store_value(0x{ptr:x})"), Offset(ptr, offset, new_ptr) => { - write!(f, "offset(0x{:x}, {:?}, 0x{:x})", ptr, offset, new_ptr) + write!(f, "offset(0x{ptr:x}, {offset:?}, 0x{new_ptr:x})") } } } diff --git a/analysis/runtime/src/handlers.rs b/analysis/runtime/src/handlers.rs index 70718317b..456bbafd3 100644 --- a/analysis/runtime/src/handlers.rs +++ b/analysis/runtime/src/handlers.rs @@ -115,21 +115,21 @@ pub fn ptr_field(mir_loc: MirLocId, ptr: usize, field_id: u32) { pub fn ptr_copy(mir_loc: MirLocId, ptr: usize) { RUNTIME.send_event(Event { mir_loc, - kind: EventKind::CopyPtr(ptr as usize), + kind: EventKind::CopyPtr(ptr), }); } pub fn ptr_contrive(mir_loc: MirLocId, ptr: usize) { RUNTIME.send_event(Event { mir_loc, - kind: EventKind::FromInt(ptr as usize), + kind: EventKind::FromInt(ptr), }); } pub fn ptr_to_int(mir_loc: MirLocId, ptr: usize) { RUNTIME.send_event(Event { mir_loc, - kind: EventKind::ToInt(ptr as usize), + kind: EventKind::ToInt(ptr), }); } diff --git a/analysis/runtime/src/mir_loc.rs b/analysis/runtime/src/mir_loc.rs index 7b8ca4a07..23c6f603d 100644 --- a/analysis/runtime/src/mir_loc.rs +++ b/analysis/runtime/src/mir_loc.rs @@ -81,7 +81,7 @@ impl Display for MirPlace { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{:?}", self.local)?; for p in &self.projection { - write!(f, ".{}", p)?; + write!(f, ".{p}")?; } Ok(()) } @@ -89,7 +89,7 @@ impl Display for MirPlace { impl Debug for MirPlace { fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } diff --git a/analysis/runtime/src/runtime/backend.rs b/analysis/runtime/src/runtime/backend.rs index 4feca7d48..a560e3097 100644 --- a/analysis/runtime/src/runtime/backend.rs +++ b/analysis/runtime/src/runtime/backend.rs @@ -120,7 +120,7 @@ impl Detect for LogBackend { .write(true) .append(append) .truncate(!append) - .open(&path)?; + .open(path)?; let writer = BufWriter::new(file); Ok(Self { writer }) } diff --git a/c2rust-analyze/src/borrowck/def_use.rs b/c2rust-analyze/src/borrowck/def_use.rs index e92ecceef..e776cff4e 100644 --- a/c2rust-analyze/src/borrowck/def_use.rs +++ b/c2rust-analyze/src/borrowck/def_use.rs @@ -157,7 +157,7 @@ impl<'tcx> Visitor<'tcx> for DefUseVisitor<'tcx, '_> { fn visit_statement(&mut self, stmt: &Statement<'tcx>, location: Location) { self.super_statement(stmt, location); - eprintln!("visit stmt {:?} at {:?}", stmt, location); + eprintln!("visit stmt {stmt:?} at {location:?}"); if let StatementKind::StorageDead(local) = stmt.kind { // Observed: `StorageDead` emits `path_moved_at_base` at the `Mid` point. diff --git a/c2rust-analyze/src/borrowck/dump.rs b/c2rust-analyze/src/borrowck/dump.rs index be9fa0348..6e71e0a36 100644 --- a/c2rust-analyze/src/borrowck/dump.rs +++ b/c2rust-analyze/src/borrowck/dump.rs @@ -205,7 +205,7 @@ impl OutputTable for FxHashMap { impl OutputTable for bool { fn write(&self, out: &mut dyn Write, _maps: &AtomMaps) -> Result<(), Box> { - writeln!(out, "{}", self)?; + writeln!(out, "{self}")?; Ok(()) } } @@ -332,7 +332,7 @@ impl Render for Loan { impl Render for Point { fn to_string(&self, maps: &AtomMaps) -> String { let (bb, idx, sub) = maps.get_point(*self); - format!("{:?}({:?}[{}])", sub, bb, idx) + format!("{sub:?}({bb:?}[{idx}])") } } diff --git a/c2rust-analyze/src/borrowck/mod.rs b/c2rust-analyze/src/borrowck/mod.rs index c46df3b2e..d86b3d761 100644 --- a/c2rust-analyze/src/borrowck/mod.rs +++ b/c2rust-analyze/src/borrowck/mod.rs @@ -82,7 +82,7 @@ pub enum OriginArg<'tcx> { impl<'tcx> Debug for OriginArg<'tcx> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match &self { - OriginArg::Actual(r) => write!(f, "{:}", r), + OriginArg::Actual(r) => write!(f, "{r:}"), OriginArg::Hypothetical(h) => write!(f, "'h{h:?}"), } } @@ -150,27 +150,24 @@ pub fn borrowck_mir<'tcx>( .iter() .find(|&&(_, l, _)| l == loan) .map(|&(_, _, point)| point) - .unwrap_or_else(|| panic!("loan {:?} was never issued?", loan)); + .unwrap_or_else(|| panic!("loan {loan:?} was never issued?")); let issued_loc = maps.get_point_location(issued_point); let stmt = mir.stmt_at(issued_loc).left().unwrap_or_else(|| { - panic!( - "loan {:?} was issued by a terminator (at {:?})?", - loan, issued_loc - ); + panic!("loan {loan:?} was issued by a terminator (at {issued_loc:?})?"); }); let ptr = match stmt.kind { StatementKind::Assign(ref x) => match describe_rvalue(&x.1) { Some(RvalueDesc::Project { base, proj: _ }) => acx .ptr_of(base) - .unwrap_or_else(|| panic!("missing pointer ID for {:?}", base)), + .unwrap_or_else(|| panic!("missing pointer ID for {base:?}")), Some(RvalueDesc::AddrOfLocal { local, proj: _ }) => { acx.addr_of_local[local] } None => panic!("loan {:?} was issued by unknown rvalue {:?}?", loan, x.1), }, - _ => panic!("loan {:?} was issued by non-assign stmt {:?}?", loan, stmt), + _ => panic!("loan {loan:?} was issued by non-assign stmt {stmt:?}?"), }; - eprintln!("want to drop UNIQUE from pointer {:?}", ptr); + eprintln!("want to drop UNIQUE from pointer {ptr:?}"); if hypothesis[ptr].contains(PermissionSet::UNIQUE) { hypothesis[ptr].remove(PermissionSet::UNIQUE); @@ -216,8 +213,8 @@ fn run_polonius<'tcx>( //pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut std::io::stdout()).unwrap(); // Populate `cfg_edge` - for (bb, bb_data) in mir.basic_blocks().iter_enumerated() { - eprintln!("{:?}:", bb); + for (bb, bb_data) in mir.basic_blocks.iter_enumerated() { + eprintln!("{bb:?}:"); for idx in 0..bb_data.statements.len() { eprintln!(" {}: {:?}", idx, bb_data.statements[idx]); @@ -319,10 +316,10 @@ fn run_polonius<'tcx>( // Populate `var_defined/used/dropped_at` and `path_assigned/accessed_at_base`. def_use::visit(&mut facts, &mut maps, mir); - dump::dump_facts_to_dir(&facts, &maps, format!("inspect/{}", name)).unwrap(); + dump::dump_facts_to_dir(&facts, &maps, format!("inspect/{name}")).unwrap(); let output = polonius_engine::Output::compute(&facts, polonius_engine::Algorithm::Naive, true); - dump::dump_output_to_dir(&output, &maps, format!("inspect/{}", name)).unwrap(); + dump::dump_output_to_dir(&output, &maps, format!("inspect/{name}")).unwrap(); (facts, maps, output) } diff --git a/c2rust-analyze/src/borrowck/type_check.rs b/c2rust-analyze/src/borrowck/type_check.rs index f3249bfc3..829cbe4ae 100644 --- a/c2rust-analyze/src/borrowck/type_check.rs +++ b/c2rust-analyze/src/borrowck/type_check.rs @@ -155,7 +155,7 @@ impl<'tcx> TypeChecker<'tcx, '_> { for proj in pl.projection { lty = util::lty_project(lty, &proj, &mut adt_func); } - eprintln!("final label for {pl:?}: {:?}", lty); + eprintln!("final label for {pl:?}: {lty:?}"); lty } @@ -182,7 +182,7 @@ impl<'tcx> TypeChecker<'tcx, '_> { .push((path, loan, borrow_kind)); let point = self.current_point(SubPoint::Mid); self.facts.loan_issued_at.push((origin, loan, point)); - eprintln!("issued loan {:?} = {:?} ({:?})", loan, pl, borrow_kind); + eprintln!("issued loan {loan:?} = {pl:?} ({borrow_kind:?})"); origin } @@ -289,7 +289,7 @@ impl<'tcx> TypeChecker<'tcx, '_> { // relations between the regions of the array and the regions of its elements self.ltcx.label(ty, &mut |_ty| Label::default()) } - _ => panic!("unsupported rvalue AggregateKind {:?}", kind), + _ => panic!("unsupported rvalue AggregateKind {kind:?}"), }, Rvalue::Len(..) => { @@ -299,12 +299,12 @@ impl<'tcx> TypeChecker<'tcx, '_> { Rvalue::UnaryOp(_, ref op) => self.visit_operand(op), - ref rv => panic!("unsupported rvalue {:?}", rv), + ref rv => panic!("unsupported rvalue {rv:?}"), } } fn do_assign(&mut self, pl_lty: LTy<'tcx>, rv_lty: LTy<'tcx>) { - eprintln!("assign {:?} = {:?}", pl_lty, rv_lty); + eprintln!("assign {pl_lty:?} = {rv_lty:?}"); let mut add_subset_base = |pl: Origin, rv: Origin| { let point = self.current_point(SubPoint::Mid); @@ -433,7 +433,7 @@ pub fn visit_body<'tcx>( adt_metadata, }; - for (bb, bb_data) in mir.basic_blocks().iter_enumerated() { + for (bb, bb_data) in mir.basic_blocks.iter_enumerated() { for (idx, stmt) in bb_data.statements.iter().enumerate() { tc.current_location = Location { block: bb, diff --git a/c2rust-analyze/src/context.rs b/c2rust-analyze/src/context.rs index e74b41ec6..543290de3 100644 --- a/c2rust-analyze/src/context.rs +++ b/c2rust-analyze/src/context.rs @@ -261,10 +261,7 @@ impl<'a, 'tcx> AnalysisCtxt<'a, 'tcx> { let (pointee_lty, proj, ptr) = match desc { RvalueDesc::Project { base, proj } => { let base_lty = self.type_of(base); - eprintln!( - "rvalue = {:?}, desc = {:?}, base_lty = {:?}", - rv, desc, base_lty - ); + eprintln!("rvalue = {rv:?}, desc = {desc:?}, base_lty = {base_lty:?}"); ( self.project(base_lty, &PlaceElem::Deref), proj, @@ -502,8 +499,7 @@ fn label_no_pointers<'tcx>(acx: &AnalysisCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> LTy<'t acx.lcx().label(ty, &mut |inner_ty| { assert!( !matches!(inner_ty.kind(), TyKind::Ref(..) | TyKind::RawPtr(..)), - "unexpected pointer type in {:?}", - ty, + "unexpected pointer type in {ty:?}", ); PointerId::NONE }) diff --git a/c2rust-analyze/src/dataflow/mod.rs b/c2rust-analyze/src/dataflow/mod.rs index f1a0e2f9b..37fe0ca92 100644 --- a/c2rust-analyze/src/dataflow/mod.rs +++ b/c2rust-analyze/src/dataflow/mod.rs @@ -40,11 +40,11 @@ impl DataflowConstraints { eprintln!("=== propagating ==="); eprintln!("constraints:"); for c in &self.constraints { - eprintln!(" {:?}", c); + eprintln!(" {c:?}"); } eprintln!("hypothesis:"); for (id, p) in hypothesis.iter() { - eprintln!(" {}: {:?}", id, p); + eprintln!(" {id}: {p:?}"); } struct PropagatePerms; diff --git a/c2rust-analyze/src/dataflow/type_check.rs b/c2rust-analyze/src/dataflow/type_check.rs index 9ada18d41..d71df2b0b 100644 --- a/c2rust-analyze/src/dataflow/type_check.rs +++ b/c2rust-analyze/src/dataflow/type_check.rs @@ -50,7 +50,7 @@ impl<'tcx> TypeChecker<'tcx, '_> { } fn record_access(&mut self, ptr: PointerId, mutbl: Mutability) { - eprintln!("record_access({:?}, {:?})", ptr, mutbl); + eprintln!("record_access({ptr:?}, {mutbl:?})"); if ptr == PointerId::NONE { return; } @@ -155,7 +155,7 @@ impl<'tcx> TypeChecker<'tcx, '_> { } } - _ => panic!("TODO: handle assignment of {:?}", rv), + _ => panic!("TODO: handle assignment of {rv:?}"), } } @@ -211,7 +211,7 @@ impl<'tcx> TypeChecker<'tcx, '_> { self.acx.tcx().erase_regions(lty2.ty) ); for (sub_lty1, sub_lty2) in lty1.iter().zip(lty2.iter()) { - eprintln!("equate {:?} = {:?}", sub_lty1, sub_lty2); + eprintln!("equate {sub_lty1:?} = {sub_lty2:?}"); if sub_lty1.label != PointerId::NONE || sub_lty2.label != PointerId::NONE { assert!(sub_lty1.label != PointerId::NONE); assert!(sub_lty2.label != PointerId::NONE); @@ -221,7 +221,7 @@ impl<'tcx> TypeChecker<'tcx, '_> { } pub fn visit_statement(&mut self, stmt: &Statement<'tcx>, loc: Location) { - eprintln!("visit_statement({:?})", stmt); + eprintln!("visit_statement({stmt:?})"); // TODO(spernsteiner): other `StatementKind`s will be handled in the future #[allow(clippy::single_match)] match stmt.kind { @@ -383,7 +383,7 @@ pub fn visit<'tcx>( equiv_constraints: Vec::new(), }; - for (bb, bb_data) in mir.basic_blocks().iter_enumerated() { + for (bb, bb_data) in mir.basic_blocks.iter_enumerated() { for (i, stmt) in bb_data.statements.iter().enumerate() { tc.visit_statement( stmt, diff --git a/c2rust-analyze/src/expr_rewrite.rs b/c2rust-analyze/src/expr_rewrite.rs index dd5946b01..ac0c13089 100644 --- a/c2rust-analyze/src/expr_rewrite.rs +++ b/c2rust-analyze/src/expr_rewrite.rs @@ -140,7 +140,7 @@ impl<'a, 'tcx> ExprRewriteVisitor<'a, 'tcx> { StatementKind::Retag(..) => {} StatementKind::AscribeUserType(..) => {} StatementKind::Coverage(..) => {} - StatementKind::CopyNonOverlapping(..) => todo!("statement {:?}", stmt), + StatementKind::Intrinsic(..) => todo!("statement {:?}", stmt), StatementKind::Nop => {} } } @@ -402,7 +402,7 @@ pub fn gen_expr_rewrites<'tcx>( let mut v = ExprRewriteVisitor::new(acx, asn, &mut out, mir); - for (bb_id, bb) in mir.basic_blocks().iter_enumerated() { + for (bb_id, bb) in mir.basic_blocks.iter_enumerated() { for (i, stmt) in bb.statements.iter().enumerate() { let loc = Location { block: bb_id, diff --git a/c2rust-analyze/src/main.rs b/c2rust-analyze/src/main.rs index defc841a5..025ebf9d0 100644 --- a/c2rust-analyze/src/main.rs +++ b/c2rust-analyze/src/main.rs @@ -306,7 +306,7 @@ impl<'tcx> Debug for AdtMetadataTable<'tcx> { let params = lty .label .iter() - .map(|p| format!("{:?}", p)) + .map(|p| format!("{p:?}")) .into_iter() .chain(args.into_iter()) .collect::>() @@ -335,7 +335,7 @@ impl<'tcx> Debug for AdtMetadataTable<'tcx> { let lifetime_params_str = adt .lifetime_params .iter() - .map(|p| format!("{:?}", p)) + .map(|p| format!("{p:?}")) .collect::>() .join(","); write!(f, "{lifetime_params_str:}")?; @@ -387,7 +387,7 @@ fn run(tcx: TyCtxt) { let all_fn_ldids = fn_body_owners_postorder(tcx); eprintln!("callgraph traversal order:"); for &ldid in &all_fn_ldids { - eprintln!(" {:?}", ldid); + eprintln!(" {ldid:?}"); } // Assign global `PointerId`s for all pointers that appear in function signatures. @@ -449,7 +449,7 @@ fn run(tcx: TyCtxt) { assert_eq!(local, l); } - for (bb, bb_data) in mir.basic_blocks().iter_enumerated() { + for (bb, bb_data) in mir.basic_blocks.iter_enumerated() { for (i, stmt) in bb_data.statements.iter().enumerate() { let rv = match stmt.kind { StatementKind::Assign(ref x) => &x.1, @@ -565,7 +565,7 @@ fn run(tcx: TyCtxt) { break; } } - eprintln!("reached fixpoint in {} iterations", loop_count); + eprintln!("reached fixpoint in {loop_count} iterations"); // Print results for each function in `all_fn_ldids`, going in declaration order. Concretely, // we iterate over `body_owners()`, which is a superset of `all_fn_ldids`, and filter based on @@ -586,7 +586,7 @@ fn run(tcx: TyCtxt) { // Print labeling and rewrites for the current function. - eprintln!("\nfinal labeling for {:?}:", name); + eprintln!("\nfinal labeling for {name:?}:"); let lcx1 = crate::labeled_ty::LabeledTyCtxt::new(tcx); let lcx2 = crate::labeled_ty::LabeledTyCtxt::new(tcx); for (local, decl) in mir.local_decls.iter_enumerated() { @@ -633,7 +633,7 @@ fn run(tcx: TyCtxt) { ); } - eprintln!("\ntype assignment for {:?}:", name); + eprintln!("\ntype assignment for {name:?}:"); for (local, decl) in mir.local_decls.iter_enumerated() { // TODO: apply `Cell` if `addr_of_local` indicates it's needed let ty = type_desc::convert_type(&acx, acx.local_tys[local], &asn); @@ -650,7 +650,7 @@ fn run(tcx: TyCtxt) { rw.loc.sub, ); for kind in &rw.kinds { - eprintln!(" {:?}", kind); + eprintln!(" {kind:?}"); } } } @@ -721,7 +721,7 @@ fn describe_span(tcx: TyCtxt, span: Span) -> String { (&s[..], "", "") }; let line = tcx.sess.source_map().lookup_char_pos(span.lo()).line; - format!("{}: {}{}{}", line, src1, src2, src3) + format!("{line}: {src1}{src2}{src3}") } /// Return all `LocalDefId`s for all `fn`s that are `body_owners`, ordered according to a postorder @@ -743,10 +743,7 @@ fn fn_body_owners_postorder(tcx: TyCtxt) -> Vec { match tcx.def_kind(root_ldid) { DefKind::Fn | DefKind::AssocFn => {} DefKind::AnonConst | DefKind::Const => continue, - dk => panic!( - "unexpected def_kind {:?} for body_owner {:?}", - dk, root_ldid - ), + dk => panic!("unexpected def_kind {dk:?} for body_owner {root_ldid:?}"), } stack.push(Visit::Pre(root_ldid)); diff --git a/c2rust-analyze/src/pointer_id.rs b/c2rust-analyze/src/pointer_id.rs index 0c90b3f71..0819ad57e 100644 --- a/c2rust-analyze/src/pointer_id.rs +++ b/c2rust-analyze/src/pointer_id.rs @@ -56,7 +56,7 @@ impl fmt::Display for PointerId { impl fmt::Debug for PointerId { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "{}", self) + write!(fmt, "{self}") } } diff --git a/c2rust-analyze/src/type_desc.rs b/c2rust-analyze/src/type_desc.rs index 3fe3f2ebe..2596104e4 100644 --- a/c2rust-analyze/src/type_desc.rs +++ b/c2rust-analyze/src/type_desc.rs @@ -73,7 +73,7 @@ fn mk_cell<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { .expect("failed to find module `core::cell`"); let cell_mod = match cell_mod_child.res { Res::Def(DefKind::Mod, did) => did, - ref r => panic!("unexpected resolution {:?} for `core::cell`", r), + ref r => panic!("unexpected resolution {r:?} for `core::cell`"), }; let cell_struct_child = tcx @@ -83,7 +83,7 @@ fn mk_cell<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { .expect("failed to find struct `core::cell::Cell`"); let cell_struct = match cell_struct_child.res { Res::Def(DefKind::Struct, did) => did, - ref r => panic!("unexpected resolution {:?} for `core::cell::Cell`", r), + ref r => panic!("unexpected resolution {r:?} for `core::cell::Cell`"), }; let cell_adt = tcx.adt_def(cell_struct); diff --git a/c2rust-analyze/src/util.rs b/c2rust-analyze/src/util.rs index ccb69b009..69b944855 100644 --- a/c2rust-analyze/src/util.rs +++ b/c2rust-analyze/src/util.rs @@ -278,7 +278,7 @@ pub fn lty_project<'tcx, L: Debug>( ProjectionElem::Field(f, _) => match lty.kind() { TyKind::Tuple(_) => lty.args[f.index()], TyKind::Adt(def, _) => adt_func(lty, *def, f), - _ => panic!("Field projection is unsupported on type {:?}", lty), + _ => panic!("Field projection is unsupported on type {lty:?}"), }, ProjectionElem::Index(..) | ProjectionElem::ConstantIndex { .. } => { assert!(matches!(lty.kind(), TyKind::Array(..) | TyKind::Slice(..))); @@ -287,5 +287,6 @@ pub fn lty_project<'tcx, L: Debug>( } ProjectionElem::Subslice { .. } => todo!("type_of Subslice"), ProjectionElem::Downcast(..) => todo!("type_of Downcast"), + ProjectionElem::OpaqueCast(..) => todo!("type_of OpaqueCast"), } } diff --git a/c2rust-analyze/tests/filecheck.rs b/c2rust-analyze/tests/filecheck.rs index dc46d8eb7..ec22a239e 100644 --- a/c2rust-analyze/tests/filecheck.rs +++ b/c2rust-analyze/tests/filecheck.rs @@ -15,7 +15,7 @@ fn filecheck() { .unwrap_or_else(|| { let llvm_config = find_llvm_config().expect("llvm-config not found"); let output = Command::new(llvm_config) - .args(&["--bindir"]) + .args(["--bindir"]) .output() .ok() .filter(|output| output.status.success()) diff --git a/c2rust-ast-builder/src/builder.rs b/c2rust-ast-builder/src/builder.rs index 252339c98..a2b20b928 100644 --- a/c2rust-ast-builder/src/builder.rs +++ b/c2rust-ast-builder/src/builder.rs @@ -225,7 +225,7 @@ impl<'a> Make for &'a str { in_token: None, path: Box::new(mk().path("super")), }), - _ => panic!("unrecognized string for Visibility: {:?}", self), + _ => panic!("unrecognized string for Visibility: {self:?}"), } } } @@ -257,7 +257,7 @@ impl<'a> Make for &'a str { match self { "" | "imm" | "immut" | "immutable" => Mutability::Immutable, "mut" | "mutable" => Mutability::Mutable, - _ => panic!("unrecognized string for Mutability: {:?}", self), + _ => panic!("unrecognized string for Mutability: {self:?}"), } } } @@ -267,7 +267,7 @@ impl<'a> Make for &'a str { match self { "" | "safe" | "normal" => Unsafety::Normal, "unsafe" => Unsafety::Unsafe, - _ => panic!("unrecognized string for Unsafety: {:?}", self), + _ => panic!("unrecognized string for Unsafety: {self:?}"), } } } @@ -277,7 +277,7 @@ impl<'a> Make for &'a str { match self { "" | "normal" | "not-const" => Constness::NotConst, "const" => Constness::Const, - _ => panic!("unrecognized string for Constness: {:?}", self), + _ => panic!("unrecognized string for Constness: {self:?}"), } } } @@ -288,7 +288,7 @@ impl<'a> Make for &'a str { "deref" | "*" => UnOp::Deref(Default::default()), "not" | "!" => UnOp::Not(Default::default()), "neg" | "-" => UnOp::Neg(Default::default()), - _ => panic!("unrecognized string for UnOp: {:?}", self), + _ => panic!("unrecognized string for UnOp: {self:?}"), } } } @@ -777,10 +777,7 @@ impl Builder { match a { GenericArgument::Type(t) => GenericMethodArgument::Type(t), GenericArgument::Const(c) => GenericMethodArgument::Const(c), - _ => panic!( - "non-type-or-const generic argument found in method arguments: {:?}", - a - ), + _ => panic!("non-type-or-const generic argument found in method arguments: {a:?}"), } } let turbofish = match seg.arguments { @@ -1101,15 +1098,15 @@ impl Builder { // Literals pub fn int_lit(self, i: u128, ty: &str) -> Lit { - Lit::Int(LitInt::new(&format!("{}{}", i, ty), self.span)) + Lit::Int(LitInt::new(&format!("{i}{ty}"), self.span)) } pub fn int_unsuffixed_lit(self, i: u128) -> Lit { - Lit::Int(LitInt::new(&format!("{}", i), self.span)) + Lit::Int(LitInt::new(&format!("{i}"), self.span)) } pub fn float_lit(self, s: &str, ty: &str) -> Lit { - Lit::Float(LitFloat::new(&format!("{}{}", s, ty), self.span)) + Lit::Float(LitFloat::new(&format!("{s}{ty}"), self.span)) } pub fn float_unsuffixed_lit(self, s: &str) -> Lit { diff --git a/c2rust-ast-exporter/build.rs b/c2rust-ast-exporter/build.rs index c9c15a9fb..3df976438 100644 --- a/c2rust-ast-exporter/build.rs +++ b/c2rust-ast-exporter/build.rs @@ -21,9 +21,9 @@ fn main() { // Generate ast_tags and ExportResult bindings if let Err(e) = generate_bindings() { - eprintln!("{}", e); + eprintln!("{e}"); if let Err(e) = check_clang_version() { - eprintln!("{}", e); + eprintln!("{e}"); } process::exit(1); } @@ -48,12 +48,10 @@ fn check_clang_version() -> Result<(), String> { return Err(format!( " Bindgen requires a matching libclang and clang installation. Bindgen is using -libclang version ({libclang}) which does not match the autodetected clang -version ({clang}). If you have clang version {libclang} installed, please set +libclang version ({libclang_version_str}) which does not match the autodetected clang +version ({clang_version_str}). If you have clang version {libclang_version_str} installed, please set the `CLANG_PATH` environment variable to the path of this version of the clang binary.", - libclang = libclang_version_str, - clang = clang_version_str, )); } } @@ -83,7 +81,7 @@ fn generate_bindings() -> Result<(), &'static str> { .clang_arg("-xc++") // Finish the builder and generate the bindings. .generate() - .or(Err("Unable to generate AST bindings"))?; + .map_err(|_| "Unable to generate AST bindings")?; let cppbindings = bindgen::Builder::default() .header("src/ExportResult.hpp") @@ -95,7 +93,7 @@ fn generate_bindings() -> Result<(), &'static str> { .clang_arg("-std=c++11") // Finish the builder and generate the bindings. .generate() - .or(Err("Unable to generate ExportResult bindings"))?; + .map_err(|_| "Unable to generate ExportResult bindings")?; // Write the bindings to the $OUT_DIR/bindings.rs file. let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); @@ -121,14 +119,14 @@ fn build_native(llvm_info: &LLVMInfo) { match env::var("C2RUST_AST_EXPORTER_LIB_DIR") { Ok(libdir) => { - println!("cargo:rustc-link-search=native={}", libdir); + println!("cargo:rustc-link-search=native={libdir}"); } _ => { // Build libclangAstExporter.a with cmake let dst = Config::new("src") // Where to find LLVM/Clang CMake files - .define("LLVM_DIR", &format!("{}/cmake/llvm", llvm_lib_dir)) - .define("Clang_DIR", &format!("{}/cmake/clang", llvm_lib_dir)) + .define("LLVM_DIR", &format!("{llvm_lib_dir}/cmake/llvm")) + .define("Clang_DIR", &format!("{llvm_lib_dir}/cmake/clang")) // What to build .build_target("clangAstExporter") .build(); @@ -136,8 +134,8 @@ fn build_native(llvm_info: &LLVMInfo) { let out_dir = dst.display(); // Set up search path for newly built tinycbor.a and libclangAstExporter.a - println!("cargo:rustc-link-search=native={}/build/lib", out_dir); - println!("cargo:rustc-link-search=native={}/build", out_dir); + println!("cargo:rustc-link-search=native={out_dir}/build/lib"); + println!("cargo:rustc-link-search=native={out_dir}/build"); } }; @@ -145,7 +143,7 @@ fn build_native(llvm_info: &LLVMInfo) { println!("cargo:rustc-link-lib=static=tinycbor"); println!("cargo:rustc-link-lib=static=clangAstExporter"); - println!("cargo:rustc-link-search=native={}", llvm_lib_dir); + println!("cargo:rustc-link-search=native={llvm_lib_dir}"); // Some distro's, including arch and Fedora, no longer build with // BUILD_SHARED_LIBS=ON; programs linking to clang are required to @@ -193,7 +191,7 @@ fn build_native(llvm_info: &LLVMInfo) { } for lib in &clang_libs { - println!("cargo:rustc-link-lib={}", lib); + println!("cargo:rustc-link-lib={lib}"); } } @@ -201,7 +199,7 @@ fn build_native(llvm_info: &LLVMInfo) { // IMPORTANT: We cannot specify static= or dylib= here because rustc // will reorder those libs before the clang libs above which don't have // static or dylib. - println!("cargo:rustc-link-lib={}", lib); + println!("cargo:rustc-link-lib={lib}"); } // Link against the C++ std library. @@ -253,7 +251,7 @@ impl LLVMInfo { let lib_dir = { let path_str = env::var("LLVM_LIB_DIR") .ok() - .or_else(|| invoke_command(llvm_config.as_deref(), &["--libdir"])) + .or_else(|| invoke_command(llvm_config.as_deref(), ["--libdir"])) .expect(llvm_config_missing); String::from( Path::new(&path_str) @@ -263,7 +261,7 @@ impl LLVMInfo { ) }; - let llvm_shared_libs = invoke_command(llvm_config.as_deref(), &["--libs", "--link-shared"]); + let llvm_shared_libs = invoke_command(llvm_config.as_deref(), ["--libs", "--link-shared"]); // /lib/rustlib//lib/ contains a libLLVM DSO for the // rust compiler. On MacOS, this lib is named libLLVM.dylib, which will @@ -288,7 +286,7 @@ impl LLVMInfo { dylib_file.push_str(dylib_suffix); let sysroot = invoke_command( env::var_os("RUSTC").map(PathBuf::from).as_deref(), - &["--print=sysroot"], + ["--print=sysroot"], ) .unwrap(); @@ -312,7 +310,7 @@ impl LLVMInfo { } else { vec!["--shared-mode"] }; - invoke_command(llvm_config.as_deref(), &args).map_or(false, |c| c == "static") + invoke_command(llvm_config.as_deref(), args).map_or(false, |c| c == "static") }; let link_mode = if link_statically { @@ -323,8 +321,8 @@ impl LLVMInfo { let llvm_major_version = { let version = - invoke_command(llvm_config.as_deref(), &["--version"]).expect(llvm_config_missing); - let emsg = format!("invalid version string {}", version); + invoke_command(llvm_config.as_deref(), ["--version"]).expect(llvm_config_missing); + let emsg = format!("invalid version string {version}"); version .split('.') .next() @@ -362,7 +360,7 @@ impl LLVMInfo { libs.extend( env::var("LLVM_SYSTEM_LIBS") .ok() - .or_else(|| invoke_command(llvm_config.as_deref(), &["--system-libs", link_mode])) + .or_else(|| invoke_command(llvm_config.as_deref(), ["--system-libs", link_mode])) .unwrap_or_default() .split_whitespace() .map(|lib| String::from(lib.trim_start_matches("-l"))), diff --git a/c2rust-ast-exporter/src/lib.rs b/c2rust-ast-exporter/src/lib.rs index 9f2903430..ecad1a7fa 100644 --- a/c2rust-ast-exporter/src/lib.rs +++ b/c2rust-ast-exporter/src/lib.rs @@ -39,7 +39,7 @@ pub fn get_untyped_ast( match clang_ast::process(items) { Ok(cxt) => Ok(cxt), - Err(e) => Err(Error::new(ErrorKind::InvalidData, format!("{:}", e))), + Err(e) => Err(Error::new(ErrorKind::InvalidData, format!("{e:}"))), } } @@ -112,7 +112,7 @@ unsafe fn marshal_result(result: *const ffi::ExportResult) -> HashMap Result { .iter() .map(|field_ident| { let span = Span::call_site().into(); - let setter_name = &format!("set_{}", field_ident); + let setter_name = &format!("set_{field_ident}"); Ident::new(setter_name, span) }) diff --git a/c2rust-build-paths/src/lib.rs b/c2rust-build-paths/src/lib.rs index 16828e610..88c61d4b3 100644 --- a/c2rust-build-paths/src/lib.rs +++ b/c2rust-build-paths/src/lib.rs @@ -21,7 +21,7 @@ impl SysRoot { pub fn resolve() -> Self { let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); let output = Command::new(rustc) - .args(&["--print", "sysroot"]) + .args(["--print", "sysroot"]) .output() .expect("could not invoke `rustc` to find rust sysroot"); // trim, but `str::trim` doesn't exist on `[u8]` diff --git a/c2rust-transpile/src/build_files/mod.rs b/c2rust-transpile/src/build_files/mod.rs index 2f9dea8af..40192cf8f 100644 --- a/c2rust-transpile/src/build_files/mod.rs +++ b/c2rust-transpile/src/build_files/mod.rs @@ -67,10 +67,10 @@ pub struct CrateConfig<'lcmd> { /// Emit `Cargo.toml` and `lib.rs` for a library or `main.rs` for a binary. /// Returns the path to `lib.rs` or `main.rs` (or `None` if the output file /// existed already). -pub fn emit_build_files<'lcmd>( +pub fn emit_build_files( tcfg: &TranspilerConfig, build_dir: &Path, - crate_cfg: Option>, + crate_cfg: Option, workspace_members: Option>, ) -> Option { let mut reg = Handlebars::new(); @@ -83,7 +83,7 @@ pub fn emit_build_files<'lcmd>( .unwrap(); if !build_dir.exists() { - fs::create_dir_all(&build_dir) + fs::create_dir_all(build_dir) .unwrap_or_else(|_| panic!("couldn't create build directory: {}", build_dir.display())); } @@ -264,11 +264,11 @@ fn emit_rust_toolchain(tcfg: &TranspilerConfig, build_dir: &Path) { maybe_write_to_file(&output_path, output, tcfg.overwrite_existing); } -fn emit_cargo_toml<'lcmd>( +fn emit_cargo_toml( tcfg: &TranspilerConfig, reg: &Handlebars, build_dir: &Path, - crate_cfg: &Option>, + crate_cfg: &Option, workspace_members: Option>, ) { // rust_checks_path is gone because we don't want to refer to the source @@ -316,13 +316,13 @@ fn maybe_write_to_file(output_path: &Path, output: String, overwrite: bool) -> O return None; } - let mut file = match File::create(&output_path) { + let mut file = match File::create(output_path) { Ok(file) => file, - Err(e) => panic!("Unable to open file for writing: {}", e), + Err(e) => panic!("Unable to open file for writing: {e}"), }; match file.write_all(output.as_bytes()) { Ok(()) => (), - Err(e) => panic!("Unable to write translation to file: {}", e), + Err(e) => panic!("Unable to write translation to file: {e}"), }; Some(PathBuf::from(output_path)) diff --git a/c2rust-transpile/src/c_ast/conversion.rs b/c2rust-transpile/src/c_ast/conversion.rs index 26033bf0a..f8d30d15d 100644 --- a/c2rust-transpile/src/c_ast/conversion.rs +++ b/c2rust-transpile/src/c_ast/conversion.rs @@ -89,8 +89,7 @@ impl IdMapper { let inserted = self.old_to_new.insert(old_id, new_id).is_some(); assert!( !inserted, - "get_or_create_new: overwrote an old id at {}", - old_id + "get_or_create_new: overwrote an old id at {old_id}" ); new_id } @@ -109,8 +108,7 @@ impl IdMapper { let inserted = self.old_to_new.insert(other_old_id, new_id).is_some(); assert!( !inserted, - "get_or_create_new: overwrote an old id at {}", - other_old_id + "get_or_create_new: overwrote an old id at {other_old_id}" ); new_id }) @@ -162,7 +160,7 @@ fn parse_cast_kind(kind: &str) -> CastKind { "BuiltinFnToFnPtr" => CastKind::BuiltinFnToFnPtr, "ConstCast" => CastKind::ConstCast, "VectorSplat" => CastKind::VectorSplat, - k => panic!("Unsupported implicit cast: {}", k), + k => panic!("Unsupported implicit cast: {k}"), } } @@ -263,7 +261,7 @@ impl ConversionContext { "{}", TranslationError::new( None, - err_msg(format!("Missing top-level node with id: {}", top_node)).context( + err_msg(format!("Missing top-level node with id: {top_node}")).context( TranslationErrorKind::InvalidClangAst( ClangAstParseErrorKind::MissingNode, ) @@ -282,10 +280,11 @@ impl ConversionContext { "{}", TranslationError::new( display_loc(untyped_context, &Some(node.loc)), - err_msg(format!("Missing child {} of node {:?}", child, node,)) - .context(TranslationErrorKind::InvalidClangAst( + err_msg(format!("Missing child {child} of node {node:?}",)).context( + TranslationErrorKind::InvalidClangAst( ClangAstParseErrorKind::MissingChild, - )), + ) + ), ), ); invalid_clang_ast = true; @@ -300,10 +299,11 @@ impl ConversionContext { "{}", TranslationError::new( display_loc(untyped_context, &Some(node.loc)), - err_msg(format!("Missing type {} for node: {:?}", type_id, node,)) - .context(TranslationErrorKind::InvalidClangAst( + err_msg(format!("Missing type {type_id} for node: {node:?}",)).context( + TranslationErrorKind::InvalidClangAst( ClangAstParseErrorKind::MissingType, - )), + ) + ), ), ); invalid_clang_ast = true; @@ -752,7 +752,7 @@ impl ConversionContext { Some("noreturn") => Some(Attribute::NoReturn), Some("nullable") => Some(Attribute::Nullable), Some("notnull") => Some(Attribute::NotNull), - Some(other) => panic!("Unknown type attribute: {}", other), + Some(other) => panic!("Unknown type attribute: {other}"), }; let ty = CTypeKind::Attributed(ty, kind); @@ -815,10 +815,7 @@ impl ConversionContext { self.processed_nodes.insert(new_id, OTHER_TYPE); } - t => panic!( - "Type conversion not implemented for {:?} expecting {:?}", - t, expected_ty - ), + t => panic!("Type conversion not implemented for {t:?} expecting {expected_ty:?}"), } } else { // Convert the node @@ -945,7 +942,7 @@ impl ConversionContext { Some("fallthrough") | Some("__fallthrough__") => { attributes.push(Attribute::Fallthrough) } - Some(str) => panic!("Unknown statement attribute: {}", str), + Some(str) => panic!("Unknown statement attribute: {str}"), None => panic!("Invalid statement attribute"), }; @@ -1017,8 +1014,7 @@ impl ConversionContext { .insert(CStmtId(new_id), label_name.clone()) { panic!( - "Duplicate label name with id {}. Old name: {}. New name: {}", - new_id, old_label_name, label_name, + "Duplicate label name with id {new_id}. Old name: {old_label_name}. New name: {label_name}", ); } @@ -1178,7 +1174,7 @@ impl ConversionContext { 8 => IntBase::Oct, 10 => IntBase::Dec, 16 => IntBase::Hex, - _ => panic!("Invalid base: {}", base), + _ => panic!("Invalid base: {base}"), }; let ty_old = node.type_id.expect("Expected expression to have type"); @@ -1258,7 +1254,7 @@ impl ConversionContext { "__imag" => UnOp::Imag, "__extension__" => UnOp::Extension, "co_await" => UnOp::Coawait, - o => panic!("Unexpected operator: {}", o), + o => panic!("Unexpected operator: {o}"), }; let operand_old = node.children[0].expect("Expected operand"); @@ -1500,7 +1496,7 @@ impl ConversionContext { "sizeof" => UnTypeOp::SizeOf, "alignof" => UnTypeOp::AlignOf, "preferredalignof" => UnTypeOp::PreferredAlignOf, - str => panic!("Unsupported operation: {}", str), + str => panic!("Unsupported operation: {str}"), }; let arg_ty = from_value(node.extras[1].clone()).expect("expected type id"); @@ -1601,7 +1597,7 @@ impl ConversionContext { from_value(entry[1].clone()).expect("expected array start"), from_value(entry[2].clone()).expect("expected array end"), ), - n => panic!("invalid designator tag: {}", n), + n => panic!("invalid designator tag: {n}"), } }) .collect(); @@ -1921,8 +1917,7 @@ impl ConversionContext { assert!( has_static_duration || has_thread_duration || !is_externally_visible, - "Variable cannot be extern without also being static or thread-local: {}", - ident + "Variable cannot be extern without also being static or thread-local: {ident}" ); let initializer = node @@ -2140,7 +2135,7 @@ impl ConversionContext { self.add_decl(new_id, located(node, static_assert)); } - t => panic!("Could not translate node {:?} as type {}", t, expected_ty), + t => panic!("Could not translate node {t:?} as type {expected_ty}"), } } } diff --git a/c2rust-transpile/src/c_ast/mod.rs b/c2rust-transpile/src/c_ast/mod.rs index e879ae461..ff4266852 100644 --- a/c2rust-transpile/src/c_ast/mod.rs +++ b/c2rust-transpile/src/c_ast/mod.rs @@ -834,7 +834,7 @@ impl Index for TypedAstContext { fn index(&self, index: CTypeId) -> &CType { match self.c_types.get(&index) { - None => panic!("Could not find {:?} in TypedAstContext", index), + None => panic!("Could not find {index:?} in TypedAstContext"), Some(ty) => ty, } } @@ -866,7 +866,7 @@ impl Index for TypedAstContext { fn index(&self, index: CDeclId) -> &CDecl { match self.c_decls.get(&index) { - None => panic!("Could not find {:?} in TypedAstContext", index), + None => panic!("Could not find {index:?} in TypedAstContext"), Some(ty) => ty, } } @@ -877,7 +877,7 @@ impl Index for TypedAstContext { fn index(&self, index: CStmtId) -> &CStmt { match self.c_stmts.get(&index) { - None => panic!("Could not find {:?} in TypedAstContext", index), + None => panic!("Could not find {index:?} in TypedAstContext"), Some(ty) => ty, } } diff --git a/c2rust-transpile/src/c_ast/print.rs b/c2rust-transpile/src/c_ast/print.rs index 1c2c23d2d..250a481c1 100644 --- a/c2rust-transpile/src/c_ast/print.rs +++ b/c2rust-transpile/src/c_ast/print.rs @@ -77,7 +77,7 @@ impl Printer { .c_exprs .get(&expr_id) .map(|l| &l.kind) - .unwrap_or_else(|| panic!("Could not find expression with ID {:?}", expr_id)); + .unwrap_or_else(|| panic!("Could not find expression with ID {expr_id:?}")); use CExprKind::*; match expr { BadExpr => { @@ -114,7 +114,7 @@ impl Printer { use OffsetOfKind::*; match kind { Constant(val) => { - self.writer.write_fmt(format_args!("{}", val))?; + self.writer.write_fmt(format_args!("{val}"))?; } Variable(qty, decl_id, expr_id) => { self.writer.write_all(b"offset_of!(")?; @@ -259,7 +259,7 @@ impl Printer { weak, .. } => { - self.writer.write_fmt(format_args!("{}(", name))?; + self.writer.write_fmt(format_args!("{name}("))?; self.print_expr(ptr, context)?; if let Some(val1) = val1 { @@ -298,11 +298,9 @@ impl Printer { pub fn print_lit(&mut self, lit: &CLiteral, _context: &TypedAstContext) -> Result<()> { use CLiteral::*; match *lit { - Integer(i, _) => self.writer.write_fmt(format_args!("{}", i)), - Floating(f, ref str) if str.is_empty() => self.writer.write_fmt(format_args!("{}", f)), - Floating(_, ref str) if str.is_empty() => { - self.writer.write_fmt(format_args!("{}", str)) - } + Integer(i, _) => self.writer.write_fmt(format_args!("{i}")), + Floating(f, ref str) if str.is_empty() => self.writer.write_fmt(format_args!("{f}")), + Floating(_, ref str) if str.is_empty() => self.writer.write_fmt(format_args!("{str}")), _ => unimplemented!("Printer::print_lit"), } } @@ -322,7 +320,7 @@ impl Printer { .c_stmts .get(&stmt_id) .map(|l| &l.kind) - .unwrap_or_else(|| panic!("Could not find statement with ID {:?}", stmt_id)); + .unwrap_or_else(|| panic!("Could not find statement with ID {stmt_id:?}")); use CStmtKind::*; match stmt { @@ -500,7 +498,7 @@ impl Printer { .c_decls .get(&decl_id) .map(|l| &l.kind) - .unwrap_or_else(|| panic!("Could not find declaration with ID {:?}", decl_id)); + .unwrap_or_else(|| panic!("Could not find declaration with ID {decl_id:?}")); use CDeclKind::*; match decl { @@ -515,7 +513,7 @@ impl Printer { self.writer.write_all(b"static ")?; } // TODO typ - self.writer.write_fmt(format_args!("{}", name))?; + self.writer.write_fmt(format_args!("{name}"))?; self.writer.write_all(b"(\n")?; self.indent(); for parameter in parameters { @@ -567,7 +565,7 @@ impl Printer { } Typedef { name, typ, .. } => { - self.writer.write_fmt(format_args!("typedef {} = ", name))?; + self.writer.write_fmt(format_args!("typedef {name} = "))?; self.print_qtype(*typ, None, context)?; if newline { self.writer.write_all(b"\n")?; @@ -577,7 +575,7 @@ impl Printer { Enum { name, variants, .. } => { self.writer.write_all(b"enum ")?; match name { - Some(n) => self.writer.write_fmt(format_args!("{} {{\n", n))?, + Some(n) => self.writer.write_fmt(format_args!("{n} {{\n"))?, None => self.writer.write_all(b"{\n")?, } @@ -595,8 +593,7 @@ impl Printer { } EnumConstant { name, value, .. } => { - self.writer - .write_fmt(format_args!("{} = {:?},", name, value))?; + self.writer.write_fmt(format_args!("{name} = {value:?},"))?; if newline { self.writer.write_all(b"\n")?; } @@ -605,7 +602,7 @@ impl Printer { Struct { name, fields, .. } => { self.writer.write_all(b"struct ")?; match name { - Some(n) => self.writer.write_fmt(format_args!("{} {{", n))?, + Some(n) => self.writer.write_fmt(format_args!("{n} {{"))?, None => self.writer.write_all(b"{\n")?, } self.indent(); @@ -624,7 +621,7 @@ impl Printer { Union { name, fields, .. } => { self.writer.write_all(b"union ")?; match name { - Some(n) => self.writer.write_fmt(format_args!("{} {{", n))?, + Some(n) => self.writer.write_fmt(format_args!("{n} {{"))?, None => self.writer.write_all(b"{\n")?, } self.indent(); @@ -649,11 +646,11 @@ impl Printer { } MacroObject { name } => { - self.writer.write_fmt(format_args!("#define {} ", name))?; + self.writer.write_fmt(format_args!("#define {name} "))?; } MacroFunction { name, .. } => { - self.writer.write_fmt(format_args!("#define {}() ", name))?; + self.writer.write_fmt(format_args!("#define {name}() "))?; } &NonCanonicalDecl { canonical_decl } => { @@ -663,7 +660,7 @@ impl Printer { .map(|s| s.as_str()) .unwrap_or(""); self.writer - .write_fmt(format_args!("// non-canonical decl for {}", name))?; + .write_fmt(format_args!("// non-canonical decl for {name}"))?; } StaticAssert { .. } => { @@ -683,8 +680,8 @@ impl Printer { match name { None => self .writer - .write_fmt(format_args!("", decl_id)), - Some(s) => self.writer.write_fmt(format_args!("{}", s)), + .write_fmt(format_args!("")), + Some(s) => self.writer.write_fmt(format_args!("{s}")), } } @@ -698,14 +695,14 @@ impl Printer { .c_types .get(&type_id) .map(|l| &l.kind) - .unwrap_or_else(|| panic!("Could not find type with ID {:?}", type_id)); + .unwrap_or_else(|| panic!("Could not find type with ID {type_id:?}")); use CTypeKind::*; match ty { Pointer(ref qual_ty) => { self.print_qtype(*qual_ty, None, context)?; self.writer.write_all(b"*")?; if let Some(i) = ident { - self.writer.write_fmt(format_args!("{}", i))?; + self.writer.write_fmt(format_args!("{i}"))?; } } &ConstantArray(typ, len) => { @@ -736,12 +733,12 @@ impl Printer { match decl { CDeclKind::Enum { name: Some(ref n), .. - } => self.writer.write_fmt(format_args!(" {}", n))?, + } => self.writer.write_fmt(format_args!(" {n}"))?, CDeclKind::Enum { name: None, .. } => unimplemented!(), _ => panic!("An enum type is supposed to point to an enum decl"), } if let Some(i) = ident { - self.writer.write_fmt(format_args!(" {}", i))?; + self.writer.write_fmt(format_args!(" {i}"))?; } } @@ -749,7 +746,7 @@ impl Printer { self.writer.write_all(ty.as_str().as_bytes())?; if let Some(i) = ident { - self.writer.write_fmt(format_args!(" {}", i))?; + self.writer.write_fmt(format_args!(" {i}"))?; } } }; diff --git a/c2rust-transpile/src/cfg/loops.rs b/c2rust-transpile/src/cfg/loops.rs index 05fb151f4..0e38f122f 100644 --- a/c2rust-transpile/src/cfg/loops.rs +++ b/c2rust-transpile/src/cfg/loops.rs @@ -133,7 +133,7 @@ impl LoopId { /// this to be usable as a loop label. pub fn pretty_print(&self) -> String { let &LoopId(loop_id) = self; - format!("l_{}", loop_id) + format!("l_{loop_id}") } } @@ -243,7 +243,7 @@ impl LoopInfo { &self .loops .get(&id) - .unwrap_or_else(|| panic!("There is no loop with id {:?}", id)) + .unwrap_or_else(|| panic!("There is no loop with id {id:?}")) .0 } } diff --git a/c2rust-transpile/src/cfg/mod.rs b/c2rust-transpile/src/cfg/mod.rs index 7b2440d79..e719e4a4e 100644 --- a/c2rust-transpile/src/cfg/mod.rs +++ b/c2rust-transpile/src/cfg/mod.rs @@ -73,8 +73,8 @@ impl Label { pub fn pretty_print(&self) -> String { match self { Label::FromC(_, Some(s)) => format!("_{}", s.as_ref()), - Label::FromC(CStmtId(label_id), None) => format!("c_{}", label_id), - Label::Synthetic(syn_id) => format!("s_{}", syn_id), + Label::FromC(CStmtId(label_id), None) => format!("c_{label_id}"), + Label::Synthetic(syn_id) => format!("s_{syn_id}"), } } @@ -343,7 +343,7 @@ impl Serialize for GenTerminator { ref cases, } => { let mut cases_sane: Vec<(String, &L)> = vec![]; - for &(ref p, ref l) in cases { + for (p, l) in cases { let pat: String = pprust::pat_to_string(p); cases_sane.push((pat, l)); } @@ -568,10 +568,7 @@ impl Cfg { _ => None, }) { - c_label_to_goto - .entry(target) - .or_insert(IndexSet::new()) - .insert(x); + c_label_to_goto.entry(target).or_default().insert(x); } let mut cfg_builder = CfgBuilder::new(c_label_to_goto); @@ -1090,9 +1087,8 @@ impl DeclStmtStore { /// Extract the Rust statements for the full declaration and initializers. DEBUGGING ONLY. pub fn peek_decl_and_assign(&self, decl_id: CDeclId) -> TranslationResult> { - let &DeclStmtInfo { - ref decl_and_assign, - .. + let DeclStmtInfo { + decl_and_assign, .. } = self .store .get(&decl_id) @@ -1175,7 +1171,7 @@ impl CfgBuilder { .insert(lbl.clone(), bb) { None => {} - Some(_) => panic!("Label {:?} cannot identify two basic blocks", lbl), + Some(_) => panic!("Label {lbl:?} cannot identify two basic blocks"), } if let Some((_, loop_vec)) = self.loops.last_mut() { @@ -1212,7 +1208,7 @@ impl CfgBuilder { /// know the terminators of a block by visiting it. fn update_terminator(&mut self, lbl: Label, new_term: GenTerminator