Add trailing comma support

This commit is contained in:
David Tolnay 2022-01-21 13:13:13 -08:00
parent 4e8fb743cc
commit 0b7e1baa58
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
2 changed files with 27 additions and 7 deletions

View File

@ -148,7 +148,7 @@ pub enum Breaks {
Inconsistent, Inconsistent,
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy, PartialEq)]
enum IndentStyle { enum IndentStyle {
/// Vertically aligned under whatever column this block begins at. /// Vertically aligned under whatever column this block begins at.
/// ///
@ -164,19 +164,20 @@ enum IndentStyle {
Block { offset: isize }, Block { offset: isize },
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy, Default, PartialEq)]
pub struct BreakToken { pub struct BreakToken {
offset: isize, offset: isize,
blank_space: isize, blank_space: isize,
pre_break: Option<char>,
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy, PartialEq)]
pub struct BeginToken { pub struct BeginToken {
indent: IndentStyle, indent: IndentStyle,
breaks: Breaks, breaks: Breaks,
} }
#[derive(Clone)] #[derive(Clone, PartialEq)]
pub enum Token { pub enum Token {
// In practice a string token contains either a `&'static str` or a // In practice a string token contains either a `&'static str` or a
// `String`. `Cow` is overkill for this because we never modify the data, // `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.pending_indentation += token.blank_space;
self.space -= token.blank_space; self.space -= token.blank_space;
} else { } else {
if let Some(pre_break) = token.pre_break {
self.out.push(pre_break);
}
self.out.push('\n'); self.out.push('\n');
let indent = self.indent as isize + token.offset; let indent = self.indent as isize + token.offset;
self.pending_indentation = indent; self.pending_indentation = indent;

View File

@ -25,7 +25,11 @@ impl Printer {
} }
pub fn break_offset(&mut self, n: usize, off: isize) { 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) { pub fn end(&mut self) {
@ -66,12 +70,24 @@ impl Printer {
} }
pub fn hardbreak_tok_offset(off: isize) -> Token { 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 { impl Token {
pub fn is_hardbreak_tok(&self) -> bool { pub fn is_hardbreak_tok(&self) -> bool {
matches!(self, Token::Break(BreakToken { offset: 0, blank_space: SIZE_INFINITY })) *self == Printer::hardbreak_tok_offset(0)
} }
} }