Skip to content

Commit

Permalink
use a better name for patterns with a single unlabelled field
Browse files Browse the repository at this point in the history
Instead of being called `value_0` it just uses `value` which looks way
better when there's just a single unlabelled field:

  let Wibble(value) = arg
  // instead of
  let Wibble(value_0) = arg
  • Loading branch information
giacomocavalieri committed Jan 8, 2025
1 parent 5116c2b commit 3196ea3
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 6 deletions.
21 changes: 15 additions & 6 deletions compiler-core/src/language_server/code_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3398,12 +3398,21 @@ where
}

pattern.push('(');
let args = (0..*constructor_arity as u32)
.map(|i| match index_to_label.get(&i) {
Some(label) => format!("{label}:"),
None => format!("value_{i}"),
})
.join(", ");
let args = if *constructor_arity <= 1 && index_to_label.get(&0).is_none() {
// If there's a single argument and its not labelled we don't add a
// number suffix to it and just call it "value".
String::from("value")
} else {
// Otherwise all unlabelled arguments will be called "value_<n>".
// Labelled arguments, on the other hand, will always use the
// shorthand syntax.
(0..*constructor_arity as u32)
.map(|i| match index_to_label.get(&i) {
Some(label) => format!("{label}:"),
None => format!("value_{i}"),
})
.join(", ")
};
pattern.push_str(&args);
pattern.push(')');
Some(pattern)
Expand Down
15 changes: 15 additions & 0 deletions compiler-core/src/language_server/tests/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4606,3 +4606,18 @@ fn pattern_match_on_argument_nicely_formats_code_when_used_on_function_with_empt
find_position_of("arg").to_selection()
);
}

#[test]
fn pattern_match_on_argument_single_unlabelled_field_is_not_numbered() {
assert_code_action!(
PATTERN_MATCH_ON_ARGUMENT,
"
pub type Wibble {
Wibble(Int)
}
pub fn main(arg: Wibble) {}
",
find_position_of(":").to_selection()
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
source: compiler-core/src/language_server/tests/action.rs
expression: "\npub type Wibble {\n Wibble(Int)\n}\n\npub fn main(arg: Wibble) {}\n"
---
----- BEFORE ACTION

pub type Wibble {
Wibble(Int)
}

pub fn main(arg: Wibble) {}


----- AFTER ACTION

pub type Wibble {
Wibble(Int)
}

pub fn main(arg: Wibble) {
let Wibble(value) = arg
}

0 comments on commit 3196ea3

Please sign in to comment.