Fix six formatter bugs; case table grows to 200 with zero skips

All five briefed bugs fixed, plus a sixth found during the work:

1. Block-comment continuation drift: token::Comment gained line/col;
   continuation lines are dedented by the comment's original column
   before re-indenting, making reformatting a true fixed point while
   preserving the author's relative indentation inside the comment.
2. Comments inside expression groups (concat, parens, call args,
   assignment patterns, binary operands) now force the group to break
   instead of being lifted out.
3. Closing block labels preserved for end/join*/endfunction/endtask/
   endpackage, matching endmodule.
4. Multi-instance declarations fit on one line when they fit and
   indent their continuations when they break.
5. @( /* c */ * ) keeps its comments (SensList::Star before/after).
6. Multi-line `define/attribute bodies no longer drift (RawText.col).

verify.rs comparison logic untouched (diagnostic positions only) —
QA audited the diff to confirm the safety net was not weakened.
All four #SKIP cases un-skipped verbatim as spec; 17 cases added
(183 -> 200, 0 skipped). QA triple-formatted 204 inputs with zero
regressions. Clippy is now fully silent workspace-wide.

Remaining comment-placement refusals (4) and a pre-existing @(* )
lexer limitation are documented as open items, not hacked around.

Dev: Opus agent; QA: Sonnet agent; review in
docs/features/formatter-bug-fixes/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 00:15:50 -07:00
1 parent 0a6c365ec2
commit 9f1a6cf1d2
15 files changed
+1277 -213

No files matched your search

+56 -9
View File
@@ -12,7 +12,17 @@ pub struct Meta {
pub trailing: Option<String>,
pub blank_before: bool,
/// Attribute instances `(* ... *)` that preceded the node, verbatim.
pub attrs: Vec<String>,
pub attrs: Vec<RawText>,
}
/// Source text passed through verbatim: a compiler directive or an attribute
/// instance. `col` is the 1-based column it started in, which is what lets the
/// formatter re-indent continuation lines of a multi-line one without drifting
/// further right on every pass.
#[derive(Debug, Clone)]
pub struct RawText {
pub text: String,
pub col: u32,
}
#[derive(Debug)]
@@ -36,8 +46,10 @@ pub enum ItemKind {
name: String,
items: Vec<Item>,
dangling: Vec<Comment>,
/// Label after `endpackage :`.
end_label: Option<String>,
},
Directive(String),
Directive(RawText),
Import(Vec<String>),
Timeunit(String),
Typedef(Typedef),
@@ -242,8 +254,14 @@ pub struct AssignPair {
#[derive(Debug)]
pub enum SensList {
/// `@*` or `@(*)`
Star,
/// `@*` or `@(*)`, with any comments written next to the `*` so the
/// formatter can print them back in the same place.
Star {
/// Comments between the `@`/`(` and the `*`.
before: Vec<Comment>,
/// Comments between the `*` and the closing `)`.
after: Vec<Comment>,
},
List(Vec<SensItem>),
}
@@ -350,6 +368,8 @@ pub struct GenBlock {
pub is_block: bool,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
/// Label after `end :`.
pub end_label: Option<String>,
}
#[derive(Debug)]
@@ -362,6 +382,8 @@ pub struct FunctionDecl {
pub args: Vec<TfArg>,
pub stmts: Vec<Stmt>,
pub dangling: Vec<Comment>,
/// Label after `endfunction :`.
pub end_label: Option<String>,
}
#[derive(Debug)]
@@ -373,6 +395,8 @@ pub struct TaskDecl {
pub args: Vec<TfArg>,
pub stmts: Vec<Stmt>,
pub dangling: Vec<Comment>,
/// Label after `endtask :`.
pub end_label: Option<String>,
}
#[derive(Debug)]
@@ -397,12 +421,16 @@ pub enum StmtKind {
label: Option<String>,
stmts: Vec<Stmt>,
dangling: Vec<Comment>,
/// Label after `end :`.
end_label: Option<String>,
},
ForkJoin {
label: Option<String>,
join_kw: String,
stmts: Vec<Stmt>,
dangling: Vec<Comment>,
/// Label after `join :` (any join kind).
end_label: Option<String>,
},
If {
qualifier: Option<String>,
@@ -478,7 +506,7 @@ pub enum StmtKind {
Break,
Continue,
Disable(String),
Directive(String),
Directive(RawText),
/// Immediate assertion: kept simple — `assert (expr) stmt else stmt;`
Assert {
kw: String,
@@ -540,6 +568,9 @@ pub enum Expr {
lhs: Box<Expr>,
op: String,
rhs: Box<Expr>,
/// Comments written between the left operand and the operator. They
/// force the chain to break, with the operator starting the new line.
comments: Vec<Comment>,
},
Ternary {
cond: Box<Expr>,
@@ -548,7 +579,7 @@ pub enum Expr {
},
Call {
callee: Box<Expr>,
args: Vec<Expr>,
args: Vec<ExprItem>,
},
Index {
base: Box<Expr>,
@@ -568,12 +599,18 @@ pub enum Expr {
base: Box<Expr>,
name: String,
},
Concat(Vec<Expr>),
Concat(Vec<ExprItem>),
Repl {
count: Box<Expr>,
inner: Vec<Expr>,
},
Paren(Box<Expr>),
Paren {
inner: Box<Expr>,
/// Comments written just inside the `(`.
before: Vec<Comment>,
/// Comments left over just before the `)`.
after: Vec<Comment>,
},
/// `ty'(expr)` cast; `ty` kept as raw text.
Cast {
ty: String,
@@ -587,7 +624,7 @@ pub enum Expr {
},
Inside {
lhs: Box<Expr>,
ranges: Vec<Expr>,
ranges: Vec<ExprItem>,
},
/// `[a:b]` inside an `inside` range list or value range.
ValueRange {
@@ -606,7 +643,17 @@ pub enum Expr {
#[derive(Debug, Clone)]
pub struct PatternItem {
pub meta: Meta,
/// `key: value` (key may be `default`, a type, or an expression).
pub key: Option<Expr>,
pub value: Expr,
}
/// One element of a bracketed expression list (a concatenation, a call
/// argument list, an `inside` set), with the comments written around it. A
/// comment on an element is what forces its list to break one per line.
#[derive(Debug, Clone)]
pub struct ExprItem {
pub meta: Meta,
pub expr: Expr,
}
+23 -8
View File
@@ -561,21 +561,24 @@ pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
RawKind::LineComment | RawKind::BlockComment => {
let same_line_as_prev =
raw.newlines_before == 0 && !tokens.is_empty() && pending.is_empty();
let comment = Comment {
text: raw.text,
blank_before: raw.newlines_before > 1 || pending_blank,
line: raw.line,
col: raw.col,
};
if same_line_as_prev {
// Trailing comment for the previous real token.
let prev = tokens.last_mut().unwrap();
match &mut prev.trailing {
Some(existing) => {
existing.push(' ');
existing.push_str(&raw.text);
existing.text.push(' ');
existing.text.push_str(&comment.text);
}
None => prev.trailing = Some(raw.text),
None => prev.trailing = Some(comment),
}
} else {
pending.push(Comment {
text: raw.text,
blank_before: raw.newlines_before > 1 || pending_blank,
});
pending.push(comment);
pending_blank = false;
}
}
@@ -632,7 +635,9 @@ mod tests {
fn trailing_comment_attaches() {
let toks = tokenize("assign x = y; // comment\nwire z;").unwrap();
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
assert_eq!(semi.trailing.as_deref(), Some("// comment"));
let trailing = semi.trailing.as_ref().expect("trailing comment");
assert_eq!(trailing.text, "// comment");
assert_eq!((trailing.line, trailing.col), (1, 15));
}
#[test]
@@ -640,6 +645,16 @@ mod tests {
let toks = tokenize("// header\n\n// second\nmodule m; endmodule").unwrap();
assert_eq!(toks[0].leading.len(), 2);
assert!(toks[0].leading[1].blank_before);
assert_eq!((toks[0].leading[1].line, toks[0].leading[1].col), (3, 1));
}
#[test]
fn comment_records_its_own_column() {
let toks = tokenize("module m;\n /* doc\n more */\n wire w;\nendmodule").unwrap();
let wire = toks.iter().find(|t| t.is_kw("wire")).unwrap();
let doc = &wire.leading[0];
assert_eq!((doc.line, doc.col), (2, 3));
assert!(doc.text.starts_with("/* doc"));
}
#[test]
+183 -91
View File
@@ -61,7 +61,7 @@ pub struct Parser {
tokens: Vec<Token>,
pos: usize,
pending_leading: Vec<Comment>,
pending_trailing: Vec<String>,
pending_trailing: Vec<Comment>,
}
pub fn parse(tokens: Vec<Token>) -> PResult<SourceFile> {
@@ -155,9 +155,7 @@ impl Parser {
let mut leading: Vec<Comment> = Vec::new();
// Unharvested trailing comments from earlier tokens become leading
// comments here so they are never lost.
for tr in self.pending_trailing.drain(..) {
leading.push(Comment { text: tr, blank_before: false });
}
leading.append(&mut self.pending_trailing);
leading.append(&mut self.pending_leading);
let tok = &mut self.tokens[self.pos];
leading.append(&mut tok.leading);
@@ -171,23 +169,79 @@ impl Parser {
if self.pending_trailing.is_empty() {
None
} else {
Some(self.pending_trailing.drain(..).collect::<Vec<_>>().join(" "))
Some(self.pending_trailing.drain(..).map(|c| c.text).collect::<Vec<_>>().join(" "))
}
}
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
/// ...) — they belong inside the enclosing construct.
fn take_dangling(&mut self) -> Vec<Comment> {
let mut out: Vec<Comment> = Vec::new();
for tr in self.pending_trailing.drain(..) {
out.push(Comment { text: tr, blank_before: false });
}
let mut out: Vec<Comment> = std::mem::take(&mut self.pending_trailing);
out.append(&mut self.pending_leading);
let tok = &mut self.tokens[self.pos];
out.append(&mut tok.leading);
out
}
/// One element of a bracketed expression list, with the comments written
/// before it. The caller harvests the trailing comment after the comma.
fn parse_expr_item(&mut self) -> PResult<ExprItem> {
let meta = self.take_meta();
let expr = self.parse_expr()?;
Ok(ExprItem { meta, expr })
}
/// Continue a comma-separated expression list whose first element is
/// already parsed, harvesting the comment written after each comma and
/// the one before the closing bracket.
fn parse_expr_list(&mut self, first: ExprItem) -> PResult<Vec<ExprItem>> {
let mut items = vec![first];
loop {
let more = self.eat_sym(",");
if let Some(last) = items.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
if !more {
return Ok(items);
}
items.push(self.parse_expr_item()?);
}
}
/// Consume the current token as verbatim text, keeping the column it
/// started in.
fn take_raw_text(&mut self) -> RawText {
let col = self.cur().col;
RawText { text: self.bump().text, col }
}
/// Take the comments the lexer attached *before* the current token,
/// bypassing the usual pending-comment plumbing so a construct can keep
/// them itself. Must be called before the token is consumed.
fn take_leading_here(&mut self) -> Vec<Comment> {
std::mem::take(&mut self.tokens[self.pos].leading)
}
/// Same for the comment written *after* the current token on its line.
fn take_trailing_here(&mut self) -> Vec<Comment> {
match self.tokens[self.pos].trailing.take() {
Some(comment) => vec![comment],
None => Vec::new(),
}
}
/// The `: name` after a closing keyword (`end`, `join`, `endfunction`,
/// ...), if present. Kept on the node so the formatter can print it back.
fn parse_end_label(&mut self) -> PResult<Option<String>> {
if self.eat_sym(":") {
Ok(Some(self.expect_ident()?))
} else {
Ok(None)
}
}
/// Given `self.tokens[i]` == an opening bracket, return the index just
/// past its matching close. Used for disambiguating lookahead only.
fn scan_matching(&self, mut i: usize, open: &str, close: &str) -> usize {
@@ -226,7 +280,7 @@ impl Parser {
fn parse_item(&mut self) -> PResult<Item> {
let mut meta = self.take_meta();
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.bump().text);
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
@@ -240,7 +294,7 @@ impl Parser {
fn parse_item_kind(&mut self) -> PResult<ItemKind> {
let t = self.cur();
match t.kind {
TokenKind::Directive => Ok(ItemKind::Directive(self.bump().text)),
TokenKind::Directive => Ok(ItemKind::Directive(self.take_raw_text())),
TokenKind::Keyword => self.parse_keyword_item(),
TokenKind::Ident => self.parse_ident_item(),
_ => self.error("expected item"),
@@ -385,10 +439,8 @@ impl Parser {
}
let dangling = self.take_dangling();
self.expect_kw("endpackage")?;
if self.eat_sym(":") {
self.expect_ident()?;
}
Ok(ItemKind::Package { kw, name, items, dangling })
let end_label = self.parse_end_label()?;
Ok(ItemKind::Package { kw, name, items, dangling, end_label })
}
fn parse_import_list(&mut self) -> PResult<Vec<String>> {
@@ -445,7 +497,7 @@ impl Parser {
}
let dangling = self.take_dangling();
self.expect_kw("endmodule")?;
let end_label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
let end_label = self.parse_end_label()?;
Ok(Module { kw, name, imports, param_ports, ports, items, dangling, end_label })
}
@@ -544,14 +596,14 @@ impl Parser {
None
}
};
let net = if NET_KEYWORDS.contains(&self.cur().text.as_str())
&& self.cur().kind == TokenKind::Keyword
{
Some(self.bump().text)
} else if self.cur().is_kw("var") {
Some(self.bump().text)
} else {
None
let net = {
let t = self.cur();
let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str());
if is_net || t.is_kw("var") {
Some(self.bump().text)
} else {
None
}
};
let ty = self.parse_opt_data_type()?;
let name = self.expect_ident()?;
@@ -686,14 +738,14 @@ impl Parser {
fn parse_port_decl(&mut self) -> PResult<PortDecl> {
let dir = self.bump().text;
let net = if NET_KEYWORDS.contains(&self.cur().text.as_str())
&& self.cur().kind == TokenKind::Keyword
{
Some(self.bump().text)
} else if self.cur().is_kw("var") {
Some(self.bump().text)
} else {
None
let net = {
let t = self.cur();
let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str());
if is_net || t.is_kw("var") {
Some(self.bump().text)
} else {
None
}
};
let ty = self.parse_opt_data_type()?;
let declarators = self.parse_declarators()?;
@@ -818,7 +870,7 @@ impl Parser {
first
};
self.expect_sym(")")?;
Ok(Expr::Paren(Box::new(expr)))
Ok(Expr::Paren { inner: Box::new(expr), before: Vec::new(), after: Vec::new() })
} else {
self.parse_primary()
}
@@ -1076,13 +1128,17 @@ impl Parser {
}
let dangling = self.take_dangling();
self.expect_kw("end")?;
if self.eat_sym(":") {
self.expect_ident()?;
}
Ok(GenBlock { label, is_block: true, items, dangling })
let end_label = self.parse_end_label()?;
Ok(GenBlock { label, is_block: true, items, dangling, end_label })
} else {
let item = self.parse_item()?;
Ok(GenBlock { label: None, is_block: false, items: vec![item], dangling: Vec::new() })
Ok(GenBlock {
label: None,
is_block: false,
items: vec![item],
dangling: Vec::new(),
end_label: None,
})
}
}
@@ -1114,8 +1170,8 @@ impl Parser {
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports()?;
self.expect_sym(";")?;
let (stmts, dangling) = self.parse_tf_body("endfunction")?;
Ok(FunctionDecl { qualifiers, ret, name, has_parens, args, stmts, dangling })
let (stmts, dangling, end_label) = self.parse_tf_body("endfunction")?;
Ok(FunctionDecl { qualifiers, ret, name, has_parens, args, stmts, dangling, end_label })
}
fn parse_task(&mut self) -> PResult<TaskDecl> {
@@ -1128,8 +1184,8 @@ impl Parser {
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports()?;
self.expect_sym(";")?;
let (stmts, dangling) = self.parse_tf_body("endtask")?;
Ok(TaskDecl { qualifiers, name, has_parens, args, stmts, dangling })
let (stmts, dangling, end_label) = self.parse_tf_body("endtask")?;
Ok(TaskDecl { qualifiers, name, has_parens, args, stmts, dangling, end_label })
}
fn parse_tf_ports(&mut self) -> PResult<Vec<TfArg>> {
@@ -1166,17 +1222,18 @@ impl Parser {
Ok(args)
}
fn parse_tf_body(&mut self, end_kw: &str) -> PResult<(Vec<Stmt>, Vec<Comment>)> {
fn parse_tf_body(
&mut self,
end_kw: &str,
) -> PResult<(Vec<Stmt>, Vec<Comment>, Option<String>)> {
let mut stmts = Vec::new();
while !self.cur().is_kw(end_kw) && !self.at_eof() {
stmts.push(self.parse_stmt()?);
}
let dangling = self.take_dangling();
self.expect_kw(end_kw)?;
if self.eat_sym(":") {
self.expect_ident()?;
}
Ok((stmts, dangling))
let end_label = self.parse_end_label()?;
Ok((stmts, dangling, end_label))
}
// ------------------------------------------------------------------
@@ -1186,7 +1243,7 @@ impl Parser {
fn parse_stmt(&mut self) -> PResult<Stmt> {
let mut meta = self.take_meta();
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.bump().text);
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
@@ -1200,7 +1257,7 @@ impl Parser {
fn parse_stmt_kind(&mut self) -> PResult<StmtKind> {
let t = self.cur();
if t.kind == TokenKind::Directive {
return Ok(StmtKind::Directive(self.bump().text));
return Ok(StmtKind::Directive(self.take_raw_text()));
}
if t.is_sym(";") {
self.bump();
@@ -1243,10 +1300,8 @@ impl Parser {
}
let dangling = self.take_dangling();
self.expect_kw("end")?;
if self.eat_sym(":") {
self.expect_ident()?;
}
Ok(StmtKind::Block { label, stmts, dangling })
let end_label = self.parse_end_label()?;
Ok(StmtKind::Block { label, stmts, dangling, end_label })
}
"fork" => {
self.bump();
@@ -1261,10 +1316,8 @@ impl Parser {
}
let dangling = self.take_dangling();
let join_kw = self.bump().text;
if self.eat_sym(":") {
self.expect_ident()?;
}
Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling })
let end_label = self.parse_end_label()?;
Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label })
}
"unique" | "unique0" | "priority" => {
let qualifier = Some(self.bump().text);
@@ -1557,19 +1610,30 @@ impl Parser {
}
fn parse_sens_list(&mut self) -> PResult<SensList> {
if self.eat_sym("*") {
return Ok(SensList::Star);
if self.cur().is_sym("*") {
// `@*` without parens.
let before = self.take_leading_here();
self.bump();
return Ok(SensList::Star { before, after: Vec::new() });
}
if self.cur().kind == TokenKind::Ident {
// `@ident` without parens.
let name = self.expect_ident()?;
return Ok(SensList::List(vec![SensItem { edge: None, expr: Expr::Ident(name) }]));
}
self.expect_sym("(")?;
if self.eat_sym("*") {
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
// to whatever node comes next.
let mut before = self.take_trailing_here();
self.bump(); // (
before.append(&mut self.take_leading_here());
let mut after = self.take_trailing_here();
self.bump(); // *
after.append(&mut self.take_leading_here());
self.expect_sym(")")?;
return Ok(SensList::Star);
return Ok(SensList::Star { before, after });
}
self.expect_sym("(")?;
let mut items = Vec::new();
loop {
let edge = {
@@ -1638,6 +1702,7 @@ impl Parser {
}
fn parse_binary(&mut self, min_prec: u8) -> PResult<Expr> {
let mark = self.pending_trailing.len();
let mut lhs = self.parse_unary()?;
while let Some(prec) = self.binary_prec() {
if prec < min_prec {
@@ -1646,29 +1711,44 @@ impl Parser {
if self.cur().is_kw("inside") {
self.bump();
self.expect_sym("{")?;
let mut ranges = Vec::new();
let mut ranges: Vec<ExprItem> = Vec::new();
loop {
if self.cur().is_sym("[") {
let mut meta = self.take_meta();
let expr = if self.cur().is_sym("[") {
self.bump();
let lo = self.parse_expr()?;
self.expect_sym(":")?;
let hi = self.parse_expr()?;
self.expect_sym("]")?;
ranges.push(Expr::ValueRange { lo: Box::new(lo), hi: Box::new(hi) });
Expr::ValueRange { lo: Box::new(lo), hi: Box::new(hi) }
} else {
ranges.push(self.parse_expr()?);
self.parse_expr()?
};
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
if !self.eat_sym(",") {
ranges.push(ExprItem { meta, expr });
if !more {
break;
}
}
if let Some(last) = ranges.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
self.expect_sym("}")?;
lhs = Expr::Inside { lhs: Box::new(lhs), ranges };
continue;
}
// Comments between the operand and the operator belong to this
// node; left where they are they would drift past the operator.
let mut comments = self.pending_trailing.split_off(mark);
comments.append(&mut self.take_leading_here());
let op = self.bump().text;
let rhs = self.parse_binary(prec + 1)?;
lhs = Expr::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs) };
lhs = Expr::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs), comments };
}
Ok(lhs)
}
@@ -1722,12 +1802,9 @@ impl Parser {
self.bump();
let mut args = Vec::new();
if !self.cur().is_sym(")") {
loop {
args.push(self.parse_expr_or_type()?);
if !self.eat_sym(",") {
break;
}
}
let meta = self.take_meta();
let first = ExprItem { meta, expr: self.parse_expr_or_type()? };
args = self.parse_expr_list(first)?;
}
self.expect_sym(")")?;
expr = Expr::Call { callee: Box::new(expr), args };
@@ -1786,28 +1863,36 @@ impl Parser {
let sym = t.text.clone();
match sym.as_str() {
"(" => {
// Comments written just inside the parens stay there;
// anything else would move them across a token.
let mut before = self.take_trailing_here();
self.bump();
before.append(&mut self.take_leading_here());
let mark = self.pending_trailing.len();
let inner = self.parse_expr()?;
if self.eat_sym(":") {
let inner = if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expect_sym(")")?;
return Ok(Expr::Paren(Box::new(Expr::MinTypMax {
Expr::MinTypMax {
min: Box::new(inner),
typ: Box::new(typ),
max: Box::new(max),
})));
}
}
} else {
inner
};
let mut after = self.pending_trailing.split_off(mark);
after.append(&mut self.take_leading_here());
self.expect_sym(")")?;
Ok(Expr::Paren(Box::new(inner)))
Ok(Expr::Paren { inner: Box::new(inner), before, after })
}
"{" => {
self.bump();
if self.cur().is_sym("}") {
return self.error("empty concatenation");
}
let first = self.parse_expr()?;
let first = self.parse_expr_item()?;
if self.cur().is_sym("{") {
// Replication {N{a, b}}
self.bump();
@@ -1817,12 +1902,9 @@ impl Parser {
}
self.expect_sym("}")?;
self.expect_sym("}")?;
return Ok(Expr::Repl { count: Box::new(first), inner });
}
let mut items = vec![first];
while self.eat_sym(",") {
items.push(self.parse_expr()?);
return Ok(Expr::Repl { count: Box::new(first.expr), inner });
}
let items = self.parse_expr_list(first)?;
self.expect_sym("}")?;
Ok(Expr::Concat(items))
}
@@ -1831,22 +1913,32 @@ impl Parser {
let mut items = Vec::new();
if !self.cur().is_sym("}") {
loop {
let mut meta = self.take_meta();
let key_or_val = if self.cur().is_kw("default") {
self.bump();
Expr::Ident("default".to_string())
} else {
self.parse_expr_or_type()?
};
if self.eat_sym(":") {
let value = self.parse_expr()?;
items.push(PatternItem { key: Some(key_or_val), value });
let (key, value) = if self.eat_sym(":") {
(Some(key_or_val), self.parse_expr()?)
} else {
items.push(PatternItem { key: None, value: key_or_val });
(None, key_or_val)
};
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
if !self.eat_sym(",") {
items.push(PatternItem { meta, key, value });
if !more {
break;
}
}
if let Some(last) = items.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
}
self.expect_sym("}")?;
Ok(Expr::AssignPattern(items))
+9 -1
View File
@@ -33,6 +33,13 @@ pub struct Comment {
/// True if at least one blank line separated this comment from whatever
/// preceded it.
pub blank_before: bool,
/// 1-based source line of the opening `//` or `/*`.
pub line: u32,
/// 1-based source column of the opening `//` or `/*`. The formatter
/// dedents the continuation lines of a multi-line comment by this much
/// before re-indenting them, which is what keeps re-formatting a fixed
/// point.
pub col: u32,
}
#[derive(Debug, Clone)]
@@ -47,7 +54,8 @@ pub struct Token {
/// earlier lines).
pub leading: Vec<Comment>,
/// A comment that appeared after this token on the same source line.
pub trailing: Option<String>,
/// Several such comments are merged into one, joined by a space.
pub trailing: Option<Comment>,
/// True if at least one blank line separated this token from the previous
/// token or comment.
pub blank_before: bool,