From 712fde5a6fce0e7bee3615ab5c7545ce442bf034 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 24 Dec 2023 20:19:37 -0800 Subject: [PATCH] Fix ToTokens for PatTuple to insert trailing comma --- src/pat.rs | 9 +++++++++ tests/test_pat.rs | 9 ++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/pat.rs b/src/pat.rs index df7da5bbe4..249960459a 100644 --- a/src/pat.rs +++ b/src/pat.rs @@ -856,6 +856,15 @@ mod printing { tokens.append_all(self.attrs.outer()); self.paren_token.surround(tokens, |tokens| { self.elems.to_tokens(tokens); + // If there is only one element, a trailing comma is needed to + // distinguish PatTuple from PatParen, unless this is `(..)` + // which is a tuple pattern even without comma. + if self.elems.len() == 1 + && !self.elems.trailing_punct() + && !matches!(self.elems[0], Pat::Rest { .. }) + { + ::default().to_tokens(tokens); + } }); } } diff --git a/tests/test_pat.rs b/tests/test_pat.rs index 89033083c3..7b5f8b0257 100644 --- a/tests/test_pat.rs +++ b/tests/test_pat.rs @@ -107,10 +107,13 @@ fn test_tuple_comma() { snapshot!(expr.to_token_stream() as Pat, @"Pat::Tuple"); expr.elems.push_value(parse_quote!(_)); - // FIXME: must parse to Pat::Tuple, not Pat::Paren + // Must not parse to Pat::Paren snapshot!(expr.to_token_stream() as Pat, @r###" - Pat::Paren { - pat: Pat::Wild, + Pat::Tuple { + elems: [ + Pat::Wild, + Token![,], + ], } "###);