rust-lang / rustfmt

Format Rust code
https://rust-lang.github.io/rustfmt/
Apache License 2.0
6.03k stars 889 forks source link

Slice indexing in long chains is separated from target element #6229

Open Sindisil opened 4 months ago

Sindisil commented 4 months ago

Formatting of slice indexing on an element in a long chain sometimes separates the index from the indexed element. See lines 299 & 300 below, where 'text' is a String member of the specified buffer line:

287     fn handle_left(&mut self) -> ControlFlow<()> {
288         if self.cursor.index == self.input_start {
289             return ControlFlow::Continue(());
290         }
291 
292         if self.cursor.index.offset == 0 {
293             self.cursor.index.line -= 1;
294             self.cursor.index.offset = self.buffer[self.cursor.index.line].len();
295             self.cursor.column = self.buffer[self.cursor.index.line].width;
296             self.cursor.line -= 1;
297         }
298 
299         if let Some((prev_idx, prev_width)) = self.buffer[self.cursor.index.line].text
300             [..self.cursor.index.offset]
301             .char_indices()
302             .map(|(i, c)| (i, c.width().unwrap_or(0)))
303             .rfind(|(_, w)| *w > 0)
304         {
305             self.cursor.index.offset = prev_idx;
306             self.cursor.column -= prev_width;
307         }
308 
309         self.adjust_viewport();
310         ControlFlow::Continue(())
311     }

Per the section of the style guide on array accesses, indexing, and slicing, I would have expected that if let expression to instead be formatted as below:

299         if let Some((prev_idx, prev_width)) = self.buffer[self.cursor.index.line]
300             .text[..self.cursor.index.offset]
301             .char_indices()
302             .map(|(i, c)| (i, c.width().unwrap_or(0)))
303             .rfind(|(_, w)| *w > 0)
304         {
305             self.cursor.index.offset = prev_idx;
306             self.cursor.column -= prev_width;
307         }

I first saw this running with max_width = 80, but this example was obtained running w/o any config file (i.e., the stock 100).

Version in use:

$ cargo --version cargo 1.80.0-beta.4 (34a6a87d8 2024-06-04) $ rustfmt --version rustfmt 1.7.0-beta (64a1fe6 2024-06-21)

ytmimi commented 4 months ago

Thanks for the report.

Per the section of the style guide on array accesses, indexing, and slicing, I would have expected that if let expression to instead be formatted as below:

When you get a chance, would you mind linking to the section of the style guide that you're referring to.

Sindisil commented 4 months ago

Sure: Array accesses, indexing, and slicing

Sorry 'bout that -- I should have included a link in my report.