From 0b7e1baa58dea7cfb1170a361e12c3dec8e76840 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 21 Jan 2022 13:13:13 -0800 Subject: [PATCH] Add trailing comma support --- compiler/rustc_ast_pretty/src/pp.rs | 12 ++++++---- .../rustc_ast_pretty/src/pp/convenience.rs | 22 ++++++++++++++++--- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pp.rs b/compiler/rustc_ast_pretty/src/pp.rs index d567c8dae43..2433b8fb74f 100644 --- a/compiler/rustc_ast_pretty/src/pp.rs +++ b/compiler/rustc_ast_pretty/src/pp.rs @@ -148,7 +148,7 @@ pub enum Breaks { Inconsistent, } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq)] enum IndentStyle { /// Vertically aligned under whatever column this block begins at. /// @@ -164,19 +164,20 @@ enum IndentStyle { Block { offset: isize }, } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Default, PartialEq)] pub struct BreakToken { offset: isize, blank_space: isize, + pre_break: Option, } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq)] pub struct BeginToken { indent: IndentStyle, breaks: Breaks, } -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub enum Token { // In practice a string token contains either a `&'static str` or a // `String`. `Cow` is overkill for this because we never modify the data, @@ -415,6 +416,9 @@ impl Printer { self.pending_indentation += token.blank_space; self.space -= token.blank_space; } else { + if let Some(pre_break) = token.pre_break { + self.out.push(pre_break); + } self.out.push('\n'); let indent = self.indent as isize + token.offset; self.pending_indentation = indent; diff --git a/compiler/rustc_ast_pretty/src/pp/convenience.rs b/compiler/rustc_ast_pretty/src/pp/convenience.rs index 1b9ac705883..b9bfafa52ae 100644 --- a/compiler/rustc_ast_pretty/src/pp/convenience.rs +++ b/compiler/rustc_ast_pretty/src/pp/convenience.rs @@ -25,7 +25,11 @@ impl Printer { } pub fn break_offset(&mut self, n: usize, off: isize) { - self.scan_break(BreakToken { offset: off, blank_space: n as isize }) + self.scan_break(BreakToken { + offset: off, + blank_space: n as isize, + ..BreakToken::default() + }); } pub fn end(&mut self) { @@ -66,12 +70,24 @@ impl Printer { } pub fn hardbreak_tok_offset(off: isize) -> Token { - Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY }) + Token::Break(BreakToken { + offset: off, + blank_space: SIZE_INFINITY, + ..BreakToken::default() + }) + } + + pub fn trailing_comma(&mut self) { + self.scan_break(BreakToken { + blank_space: 1, + pre_break: Some(','), + ..BreakToken::default() + }); } } impl Token { pub fn is_hardbreak_tok(&self) -> bool { - matches!(self, Token::Break(BreakToken { offset: 0, blank_space: SIZE_INFINITY })) + *self == Printer::hardbreak_tok_offset(0) } }