Enable `clippy::useless_conversion` (#8724)

Marshall Bowers created

This PR enables the
[`clippy::useless_conversion`](https://rust-lang.github.io/rust-clippy/master/index.html#/useless_conversion)
rule and fixes the outstanding violations.

Release Notes:

- N/A

Change summary

crates/ai/src/embedding.rs                    |  2 +-
crates/channel/src/channel_buffer.rs          |  2 +-
crates/channel/src/channel_chat.rs            |  2 +-
crates/collab/src/db.rs                       |  2 +-
crates/editor/src/display_map/block_map.rs    |  2 +-
crates/editor/src/display_map/tab_map.rs      |  4 ++--
crates/editor/src/editor.rs                   |  2 +-
crates/editor/src/editor_tests.rs             |  4 ++--
crates/editor/src/element.rs                  |  7 +++----
crates/editor/src/scroll.rs                   |  2 +-
crates/language/src/outline.rs                |  6 +++---
crates/language/src/syntax_map.rs             |  2 +-
crates/language_tools/src/syntax_tree_view.rs |  2 +-
crates/lsp/src/lsp.rs                         |  2 +-
crates/project/src/project.rs                 |  4 ++--
crates/storybook/src/stories/scroll.rs        |  2 +-
crates/terminal/src/mappings/mouse.rs         |  2 +-
crates/terminal/src/terminal.rs               | 13 ++++++-------
crates/terminal_view/src/terminal_element.rs  |  6 +++---
crates/vim/src/motion.rs                      |  2 +-
tooling/xtask/src/main.rs                     | 18 ++++++++++--------
21 files changed, 44 insertions(+), 44 deletions(-)

Detailed changes

crates/ai/src/embedding.rs 🔗

@@ -112,7 +112,7 @@ mod tests {
         }
 
         fn round_to_decimals(n: OrderedFloat<f32>, decimal_places: i32) -> f32 {
-            let factor = (10.0 as f32).powi(decimal_places);
+            let factor = 10.0_f32.powi(decimal_places);
             (n * factor).round() / factor
         }
 

crates/channel/src/channel_buffer.rs 🔗

@@ -126,7 +126,7 @@ impl ChannelBuffer {
         for (_, old_collaborator) in &self.collaborators {
             if !new_collaborators.contains_key(&old_collaborator.peer_id) {
                 self.buffer.update(cx, |buffer, cx| {
-                    buffer.remove_peer(old_collaborator.replica_id as u16, cx)
+                    buffer.remove_peer(old_collaborator.replica_id, cx)
                 });
             }
         }

crates/channel/src/channel_chat.rs 🔗

@@ -681,7 +681,7 @@ pub fn mentions_to_proto(mentions: &[(Range<usize>, UserId)]) -> Vec<proto::Chat
                 start: range.start as u64,
                 end: range.end as u64,
             }),
-            user_id: *user_id as u64,
+            user_id: *user_id,
         })
         .collect()
 }

crates/collab/src/db.rs 🔗

@@ -359,7 +359,7 @@ impl Database {
         const SLEEPS: [f32; 10] = [10., 20., 40., 80., 160., 320., 640., 1280., 2560., 5120.];
         if is_serialization_error(error) && prev_attempt_count < SLEEPS.len() {
             let base_delay = SLEEPS[prev_attempt_count];
-            let randomized_delay = base_delay as f32 * self.rng.lock().await.gen_range(0.5..=2.0);
+            let randomized_delay = base_delay * self.rng.lock().await.gen_range(0.5..=2.0);
             log::info!(
                 "retrying transaction after serialization error. delay: {} ms.",
                 randomized_delay

crates/editor/src/display_map/block_map.rs 🔗

@@ -987,7 +987,7 @@ fn offset_for_row(s: &str, target: u32) -> (u32, usize) {
         if row >= target {
             break;
         }
-        offset += line.len() as usize;
+        offset += line.len();
     }
     (row, offset)
 }

crates/editor/src/display_map/tab_map.rs 🔗

@@ -296,7 +296,7 @@ impl TabSnapshot {
         let (collapsed, expanded_char_column, to_next_stop) =
             self.collapse_tabs(chars, expanded, bias);
         (
-            FoldPoint::new(output.row(), collapsed as u32),
+            FoldPoint::new(output.row(), collapsed),
             expanded_char_column,
             to_next_stop,
         )
@@ -513,7 +513,7 @@ impl<'a> Iterator for TabChunks<'a> {
                     } else {
                         self.chunk.text = &self.chunk.text[1..];
                         let tab_size = if self.input_column < self.max_expansion_column {
-                            self.tab_size.get() as u32
+                            self.tab_size.get()
                         } else {
                             1
                         };

crates/editor/src/editor.rs 🔗

@@ -4107,7 +4107,7 @@ impl Editor {
                 fold_data
                     .map(|(fold_status, buffer_row, active)| {
                         (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
-                            IconButton::new(ix as usize, ui::IconName::ChevronDown)
+                            IconButton::new(ix, ui::IconName::ChevronDown)
                                 .on_click({
                                     let view = editor_view.clone();
                                     move |_e, cx| {

crates/editor/src/editor_tests.rs 🔗

@@ -6752,8 +6752,8 @@ async fn test_following(cx: &mut gpui::TestAppContext) {
         cx.open_window(
             WindowOptions {
                 bounds: WindowBounds::Fixed(Bounds::from_corners(
-                    gpui::Point::new((0. as f64).into(), (0. as f64).into()),
-                    gpui::Point::new((10. as f64).into(), (80. as f64).into()),
+                    gpui::Point::new(0_f64.into(), 0_f64.into()),
+                    gpui::Point::new(10_f64.into(), 80_f64.into()),
                 )),
                 ..Default::default()
             },

crates/editor/src/element.rs 🔗

@@ -1586,7 +1586,7 @@ impl EditorElement {
                         let new_y = event.position.y;
                         if (track_bounds.top()..track_bounds.bottom()).contains(&y) {
                             let mut position = editor.scroll_position(cx);
-                            position.y += (new_y - y) * (max_row as f32) / height;
+                            position.y += (new_y - y) * max_row / height;
                             if position.y < 0.0 {
                                 position.y = 0.0;
                             }
@@ -1633,8 +1633,7 @@ impl EditorElement {
 
                             let y = event.position.y;
                             if y < thumb_top || thumb_bottom < y {
-                                let center_row =
-                                    ((y - top) * max_row as f32 / height).round() as u32;
+                                let center_row = ((y - top) * max_row / height).round() as u32;
                                 let top_row = center_row
                                     .saturating_sub((row_range.end - row_range.start) as u32 / 2);
                                 let mut position = editor.scroll_position(cx);
@@ -1964,7 +1963,7 @@ impl EditorElement {
                 chunks,
                 &self.style.text,
                 MAX_LINE_LEN,
-                rows.len() as usize,
+                rows.len(),
                 line_number_layouts,
                 snapshot.mode,
                 cx,

crates/editor/src/scroll.rs 🔗

@@ -470,7 +470,7 @@ impl Editor {
                 .buffer()
                 .read(cx)
                 .snapshot(cx)
-                .anchor_at(Point::new(top_row as u32, 0), Bias::Left);
+                .anchor_at(Point::new(top_row, 0), Bias::Left);
             let scroll_anchor = ScrollAnchor {
                 offset: gpui::Point::new(x, y),
                 anchor: top_anchor,

crates/language/src/outline.rs 🔗

@@ -43,7 +43,7 @@ impl<T> Outline<T> {
             let candidate_text = item
                 .name_ranges
                 .iter()
-                .map(|range| &item.text[range.start as usize..range.end as usize])
+                .map(|range| &item.text[range.start..range.end])
                 .collect::<String>();
 
             path_candidates.push(StringMatchCandidate::new(id, path_text.clone()));
@@ -97,11 +97,11 @@ impl<T> Outline<T> {
                 let mut name_range = name_ranges.next().unwrap();
                 let mut preceding_ranges_len = 0;
                 for position in &mut string_match.positions {
-                    while *position >= preceding_ranges_len + name_range.len() as usize {
+                    while *position >= preceding_ranges_len + name_range.len() {
                         preceding_ranges_len += name_range.len();
                         name_range = name_ranges.next().unwrap();
                     }
-                    *position = name_range.start as usize + (*position - preceding_ranges_len);
+                    *position = name_range.start + (*position - preceding_ranges_len);
                 }
             }
 

crates/language/src/syntax_map.rs 🔗

@@ -1421,7 +1421,7 @@ fn insert_newlines_between_ranges(
         if range_a.end_point.row < range_b.start_point.row {
             let end_point = start_point + Point::from_ts_point(range_a.end_point);
             let line_end = Point::new(end_point.row, text.line_len(end_point.row));
-            if end_point.column as u32 >= line_end.column {
+            if end_point.column >= line_end.column {
                 range_a.end_byte += 1;
                 range_a.end_point.row += 1;
                 range_a.end_point.column = 0;

crates/language_tools/src/syntax_tree_view.rs 🔗

@@ -284,7 +284,7 @@ impl Render for SyntaxTreeView {
                 move |this, range, cx| {
                     let mut items = Vec::new();
                     let mut cursor = layer.node().walk();
-                    let mut descendant_ix = range.start as usize;
+                    let mut descendant_ix = range.start;
                     cursor.goto_descendant(descendant_ix);
                     let mut depth = cursor.depth();
                     let mut visited_children = false;

crates/lsp/src/lsp.rs 🔗

@@ -977,7 +977,7 @@ impl LanguageServer {
                     Self::notify_internal::<notification::Cancel>(
                         &outbound_tx,
                         CancelParams {
-                            id: NumberOrString::Number(id as i32),
+                            id: NumberOrString::Number(id),
                         },
                     )
                     .log_err();

crates/project/src/project.rs 🔗

@@ -3665,7 +3665,7 @@ impl Project {
                                 proto::LspWorkStart {
                                     token,
                                     message: report.message,
-                                    percentage: report.percentage.map(|p| p as u32),
+                                    percentage: report.percentage.map(|p| p),
                                 },
                             ),
                         })
@@ -3691,7 +3691,7 @@ impl Project {
                                 proto::LspWorkProgress {
                                     token,
                                     message: report.message,
-                                    percentage: report.percentage.map(|p| p as u32),
+                                    percentage: report.percentage.map(|p| p),
                                 },
                             ),
                         })

crates/storybook/src/stories/scroll.rs 🔗

@@ -38,7 +38,7 @@ impl Render for ScrollStory {
                             .id(id)
                             .tooltip(move |cx| Tooltip::text(format!("{}, {}", row, column), cx))
                             .bg(bg)
-                            .size(px(100. as f32))
+                            .size(px(100_f32))
                             .when(row >= 5 && column >= 5, |d| {
                                 d.overflow_scroll()
                                     .child(div().size(px(50.)).bg(color_1))

crates/terminal/src/mappings/mouse.rs 🔗

@@ -183,7 +183,7 @@ pub fn grid_point_and_side(
     let col = min(col, cur_size.last_column());
     let mut line = (pos.y / cur_size.line_height) as i32;
     if line > cur_size.bottommost_line() {
-        line = cur_size.bottommost_line().0 as i32;
+        line = cur_size.bottommost_line().0;
         side = Side::Right;
     } else if line < 0 {
         side = Side::Left;

crates/terminal/src/terminal.rs 🔗

@@ -1294,8 +1294,7 @@ impl Terminal {
                     self.last_content.display_offset,
                 );
 
-                if let Some(scrolls) =
-                    scroll_report(point, scroll_lines as i32, e, self.last_content.mode)
+                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
                 {
                     for scroll in scrolls {
                         self.pty_tx.notify(scroll);
@@ -1554,9 +1553,9 @@ fn rgb_for_index(i: &u8) -> (u8, u8, u8) {
 
 pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
     Rgba {
-        r: (r as f32 / 255.) as f32,
-        g: (g as f32 / 255.) as f32,
-        b: (b as f32 / 255.) as f32,
+        r: (r as f32 / 255.),
+        g: (g as f32 / 255.),
+        b: (b as f32 / 255.),
         a: 1.,
     }
     .into()
@@ -1577,9 +1576,9 @@ mod tests {
 
     #[test]
     fn test_rgb_for_index() {
-        //Test every possible value in the color cube
+        // Test every possible value in the color cube.
         for i in 16..=231 {
-            let (r, g, b) = rgb_for_index(&(i as u8));
+            let (r, g, b) = rgb_for_index(&i);
             assert_eq!(i, 16 + 36 * r + 6 * g + b);
         }
     }

crates/terminal_view/src/terminal_element.rs 🔗

@@ -365,7 +365,7 @@ impl TerminalElement {
         };
 
         let mut result = TextRun {
-            len: indexed.c.len_utf8() as usize,
+            len: indexed.c.len_utf8(),
             color: fg,
             background_color: None,
             font: Font {
@@ -1015,10 +1015,10 @@ fn to_highlighted_range_lines(
         let mut line_end = layout.dimensions.columns();
 
         if line == clamped_start_line {
-            line_start = unclamped_start.column.0 as usize;
+            line_start = unclamped_start.column.0;
         }
         if line == clamped_end_line {
-            line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
+            line_end = unclamped_end.column.0 + 1; // +1 for inclusive
         }
 
         highlighted_range_lines.push(HighlightedRangeLine {

crates/vim/src/motion.rs 🔗

@@ -1176,7 +1176,7 @@ fn window_middle(
             (visible_rows as u32).min(map.max_point().row() - first_visible_line.row());
 
         let new_row =
-            (first_visible_line.row() + (max_visible_rows / 2) as u32).min(map.max_point().row());
+            (first_visible_line.row() + (max_visible_rows / 2)).min(map.max_point().row());
         let new_col = point.column().min(map.line_len(new_row));
         let new_point = DisplayPoint::new(new_row, new_col);
         (map.clip_point(new_point, Bias::Left), SelectionGoal::None)

tooling/xtask/src/main.rs 🔗

@@ -41,8 +41,8 @@ fn run_clippy(args: ClippyArgs) -> Result<()> {
     let mut clippy_command = Command::new(&cargo);
     clippy_command.arg("clippy");
 
-    if let Some(package) = args.package {
-        clippy_command.args(["--package", &package]);
+    if let Some(package) = args.package.as_ref() {
+        clippy_command.args(["--package", package]);
     } else {
         clippy_command.arg("--workspace");
     }
@@ -69,9 +69,11 @@ fn run_clippy(args: ClippyArgs) -> Result<()> {
     /// We'll want to drive this list down by either:
     /// 1. fixing violations of the rule and begin enforcing it
     /// 2. deciding we want to allow the rule permanently, at which point
-    ///    we should codify that separately in this script.
+    ///    we should codify that separately in this task.
+    ///
+    /// This list shouldn't be added to; it should only get shorter.
     const MIGRATORY_RULES_TO_ALLOW: &[&str] = &[
-        // There's a bunch of rules currently failing in the `style` group, so
+        // There are a bunch of rules currently failing in the `style` group, so
         // allow all of those, for now.
         "clippy::style",
         // Individual rules that have violations in the codebase:
@@ -129,7 +131,6 @@ fn run_clippy(args: ClippyArgs) -> Result<()> {
         "clippy::too_many_arguments",
         "clippy::type_complexity",
         "clippy::unit_arg",
-        "clippy::unnecessary_cast",
         "clippy::unnecessary_filter_map",
         "clippy::unnecessary_find_map",
         "clippy::unnecessary_operation",
@@ -140,10 +141,11 @@ fn run_clippy(args: ClippyArgs) -> Result<()> {
         "clippy::vec_init_then_push",
     ];
 
-    // When fixing violations automatically we don't care about the
-    // rules we're already violating, since it may be possible to
+    // When fixing violations automatically for a single package we don't care
+    // about the rules we're already violating, since it may be possible to
     // have them fixed automatically.
-    if !args.fix {
+    let ignore_suppressed_rules = args.fix && args.package.is_some();
+    if !ignore_suppressed_rules {
         for rule in MIGRATORY_RULES_TO_ALLOW {
             clippy_command.args(["--allow", rule]);
         }