Skip to content

Commit 26bb4e6

Browse files
committed
Skip parenthesis around tuple struct field calls
1 parent c95f9f5 commit 26bb4e6

File tree

4 files changed

+11
-3
lines changed

4 files changed

+11
-3
lines changed

compiler/rustc_ast_pretty/src/pprust/state/expr.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,9 @@ impl<'a> State<'a> {
213213

214214
fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>], fixup: FixupContext) {
215215
let needs_paren = match func.kind {
216-
ast::ExprKind::Field(..) => true,
216+
// In order to call a named field, needs parens: `(self.fun)()`
217+
// But not for an unnamed field: `self.0()`
218+
ast::ExprKind::Field(_, name) => !name.is_numeric(),
217219
_ => func.precedence() < ExprPrecedence::Unambiguous,
218220
};
219221

compiler/rustc_parse/src/parser/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1336,7 +1336,7 @@ impl<'a> Parser<'a> {
13361336
) -> bool {
13371337
if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
13381338
if let ExprKind::Field(_, ident) = l1.kind
1339-
&& ident.as_str().parse::<i32>().is_err()
1339+
&& !ident.is_numeric()
13401340
&& !matches!(r1.kind, ExprKind::Lit(_))
13411341
{
13421342
// The parser has encountered `foo.bar<baz`, the likelihood of the turbofish

compiler/rustc_span/src/symbol.rs

+6
Original file line numberDiff line numberDiff line change
@@ -2707,6 +2707,12 @@ impl Ident {
27072707
pub fn is_raw_guess(self) -> bool {
27082708
self.name.can_be_raw() && self.is_reserved()
27092709
}
2710+
2711+
/// Whether this would be the identifier for a tuple field like `self.0`, as
2712+
/// opposed to a named field like `self.thing`.
2713+
pub fn is_numeric(self) -> bool {
2714+
!self.name.is_empty() && self.as_str().bytes().all(|b| b.is_ascii_digit())
2715+
}
27102716
}
27112717

27122718
/// Collect all the keywords in a given edition into a vector.

tests/ui-fulldeps/pprust-parenthesis-insertion.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ static EXPRS: &[&str] = &[
7979
"if let _ = (true && false) {}",
8080
// Parentheses to call a named field, but not an unnamed field.
8181
"(self.fun)()",
82-
"(self.0)()", // FIXME: no parenthesis needed.
82+
"self.0()",
8383
// Conditions end at the first curly brace, so struct expressions need to be
8484
// parenthesized. Except in a match guard, where conditions end at arrow.
8585
"if let _ = (Struct {}) {}",

0 commit comments

Comments
 (0)