| @@ -1,23 +1,46 @@ |
| 1 | | −//! `louise fmt`, v0: a conservative formatter. |
| 1 | +//! `louise fmt`: a pretty printer in the style of Gleam (ADR 0059). |
| 2 | 2 | //! |
| 3 | | −//! It only changes whitespace between tokens: |
| 4 | | −//! - a line is indented one step deeper than the line that opened the |
| 5 | | −//! innermost open `{`, `(`, `[` or HTML element (brackets opened on the |
| 6 | | −//! same line count once), and as deep as that line when it starts by |
| 7 | | −//! closing it; |
| 8 | | −//! - a line starting with an infix operator, or following a line that |
| 9 | | −//! ends with `->`, `=` or `<-`, is indented one more step (continuation); |
| 10 | | −//! - trailing whitespace is removed, blank lines are limited to one, and |
| 11 | | −//! the file ends with a single newline. Spacing within a line is kept. |
| 3 | +//! Fixed rules, no configuration: 80 columns, two-space indents, at most |
| 4 | +//! one blank line, a single trailing newline. A construct that fits on one |
| 5 | +//! line is joined; one that does not breaks fully, one item per line, with |
| 6 | +//! a *leading* comma aligned with the brackets: |
| 12 | 7 | //! |
| 13 | | −//! Tokens are never reordered or rewritten. As a safety net, the result is |
| 14 | | −//! re-parsed and its tokens compared with the input's; on any difference |
| 15 | | −//! formatting is refused. Text in multi-line strings is never touched |
| 16 | | −//! (strings are single tokens); HTML text keeps its words and only has its |
| 17 | | −//! line indentation changed, which JSX whitespace rules ignore. |
| 8 | +//! ```louise |
| 9 | +//! let req = Request( |
| 10 | +//! "GET" |
| 11 | +//! , "/" |
| 12 | +//! , headers |
| 13 | +//! ) |
| 14 | +//! ``` |
| 15 | +//! |
| 16 | +//! Match arms, handler clauses and effect rows keep their trailing commas. |
| 17 | +//! Block statements, match arms, handler clauses, effect operations and |
| 18 | +//! trait/impl members always break, one per line, as do function bodies |
| 19 | +//! and multi-variant types. Pipes and binary operators break before the |
| 20 | +//! operator, one indent in. Comments stay where they were (leading on |
| 21 | +//! their own line, trailing at the end of one) and force the group they |
| 22 | +//! are in to break; blank lines between statements and items are kept (at |
| 23 | +//! most one). String and template text is never touched, interpolation |
| 24 | +//! holes are formatted as code, and HTML literals are only re-indented. |
| 25 | +//! Two normalizations go beyond whitespace: a trailing comma before a |
| 26 | +//! closing bracket is dropped in leading-comma lists (a one-element tuple |
| 27 | +//! keeps its significant comma), and an empty `{ }` after a type name is |
| 28 | +//! dropped. |
| 29 | +//! |
| 30 | +//! Safety: formatting is refused when the input has syntax errors, and the |
| 31 | +//! result is re-parsed and its significant tokens compared with the |
| 32 | +//! input's, up to the two normalizations; comments must match, in order, |
| 33 | +//! up to sliding across a comma. On any other difference, formatting is |
| 34 | +//! refused. |
| 35 | + |
| 36 | +use std::borrow::Cow; |
| 37 | +use std::collections::VecDeque; |
| 38 | + |
| 39 | +use rowan::NodeOrToken; |
| 18 | 40 | |
| 19 | 41 | use crate::SyntaxKind::{self, *}; |
| 20 | | −use crate::{SyntaxNode, parse}; |
| 42 | +use crate::pretty::{self, Doc}; |
| 43 | +use crate::{SyntaxElement, SyntaxNode, SyntaxToken, parse}; |
| 21 | 44 | |
| 22 | 45 | #[derive(Debug, PartialEq)] |
| 23 | 46 | pub enum FormatError { |
| @@ -27,33 +50,83 @@ pub enum FormatError { |
| 27 | 50 | Unsafe, |
| 28 | 51 | } |
| 29 | 52 | |
| 30 | | −const INDENT: &str = " "; |
| 53 | +/// The one and only line width. |
| 54 | +const WIDTH: usize = 80; |
| 31 | 55 | |
| 32 | 56 | pub fn format(text: &str) -> Result<String, FormatError> { |
| 57 | + format_with_width(text, WIDTH) |
| 58 | +} |
| 59 | + |
| 60 | +/// Tests render at narrow widths to exercise breaking; users get [`WIDTH`]. |
| 61 | +fn format_with_width(text: &str, width: usize) -> Result<String, FormatError> { |
| 33 | 62 | let parse = parse(text); |
| 34 | 63 | if !parse.errors().is_empty() { |
| 35 | 64 | return Err(FormatError::SyntaxErrors); |
| 36 | 65 | } |
| 37 | | − let formatted = format_tree(&parse.syntax()); |
| 38 | | − if significant_tokens(&formatted) != significant_tokens(text) { |
| 66 | + let doc = Printer::new(text).source_file(&parse.syntax()); |
| 67 | + let formatted = finish(pretty::render(&doc, width)); |
| 68 | + if significant_tokens(&formatted) != significant_tokens(text) |
| 69 | + || comments(&formatted) != comments(text) |
| 70 | + { |
| 39 | 71 | return Err(FormatError::Unsafe); |
| 40 | 72 | } |
| 41 | 73 | Ok(formatted) |
| 42 | 74 | } |
| 43 | 75 | |
| 76 | +/// Trailing whitespace, and exactly one newline at the end of the file. |
| 77 | +/// Blank lines carry no indentation. |
| 78 | +fn finish(rendered: String) -> String { |
| 79 | + let mut out = String::with_capacity(rendered.len() + 1); |
| 80 | + for line in rendered.split('\n') { |
| 81 | + out.push_str(line.trim_end()); |
| 82 | + out.push('\n'); |
| 83 | + } |
| 84 | + let out = out.trim_end().to_owned(); |
| 85 | + if out.is_empty() { |
| 86 | + "\n".to_owned() |
| 87 | + } else { |
| 88 | + out + "\n" |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +/// A `{ }` after a type name holding nothing (no variants, no comments): |
| 93 | +/// printed as nothing. |
| 94 | +fn empty_variant_list(node: &SyntaxNode) -> bool { |
| 95 | + node.kind() == VARIANT_LIST |
| 96 | + && !node |
| 97 | + .children_with_tokens() |
| 98 | + .any(|c| matches!(c.kind(), VARIANT | COMMENT | DOC_COMMENT)) |
| 99 | +} |
| 100 | + |
| 44 | 101 | /// The lexical content that formatting must preserve: significant tokens, |
| 45 | | −/// with HTML text reduced to its words. |
| 102 | +/// with HTML text reduced to its words and commas directly before a |
| 103 | +/// closing bracket ignored (the printer drops those in leading-comma |
| 104 | +/// lists; a one-element tuple keeps its own). Comments are compared |
| 105 | +/// separately (see [`comments`]): they may slide across a comma. |
| 46 | 106 | fn significant_tokens(text: &str) -> Vec<(SyntaxKind, String)> { |
| 47 | | − parse(text) |
| 107 | + let tokens: Vec<_> = parse(text) |
| 48 | 108 | .syntax() |
| 49 | 109 | .descendants_with_tokens() |
| 50 | 110 | .filter_map(|e| e.into_token()) |
| 51 | 111 | .filter(|t| !t.kind().is_trivia()) |
| 52 | | − .map(|t| { |
| 53 | | − let text = if t.kind() == HTML_TEXT { |
| 54 | | − t.text().split_whitespace().collect::<Vec<_>>().join(" ") |
| 55 | | − } else { |
| 56 | | − t.text().to_owned() |
| 112 | + .filter(|t| { |
| 113 | + // An empty variant list's braces are dropped (`type T {}` → |
| 114 | + // `type T`). |
| 115 | + !(matches!(t.kind(), L_BRACE | R_BRACE) |
| 116 | + && t.parent().is_some_and(|p| empty_variant_list(&p))) |
| 117 | + }) |
| 118 | + .collect(); |
| 119 | + let is_closer = |k: SyntaxKind| matches!(k, R_PAREN | R_BRACK | R_BRACE | GT); |
| 120 | + tokens |
| 121 | + .iter() |
| 122 | + .enumerate() |
| 123 | + .filter(|(i, t)| { |
| 124 | + !(t.kind() == COMMA && tokens.get(i + 1).is_some_and(|n| is_closer(n.kind()))) |
| 125 | + }) |
| 126 | + .map(|(_, t)| { |
| 127 | + let text = match t.kind() { |
| 128 | + HTML_TEXT => t.text().split_whitespace().collect::<Vec<_>>().join(" "), |
| 129 | + _ => t.text().to_owned(), |
| 57 | 130 | }; |
| 58 | 131 | (t.kind(), text) |
| 59 | 132 | }) |
| @@ -61,162 +134,1718 @@ fn significant_tokens(text: &str) -> Vec<(SyntaxKind, String)> { |
| 61 | 134 | .collect() |
| 62 | 135 | } |
| 63 | 136 | |
| 64 | | −fn is_continuation_start(kind: SyntaxKind) -> bool { |
| 65 | | − matches!( |
| 66 | | − kind, |
| 67 | | − PIPE_GT |
| 68 | | − | LT_GT |
| 69 | | − | AMP2 |
| 70 | | − | PIPE2 |
| 71 | | − | PLUS |
| 72 | | − | STAR |
| 73 | | − | SLASH |
| 74 | | − | PERCENT |
| 75 | | − | DOT |
| 76 | | − | EQ2 |
| 77 | | − | NEQ |
| 78 | | − | LTEQ |
| 79 | | − | GTEQ |
| 80 | | − ) |
| 137 | +/// The file's comments, in order, trimmed of trailing whitespace. Compared |
| 138 | +/// apart from the significant tokens: a comment may move across a comma |
| 139 | +/// but may never be dropped, duplicated, edited or reordered. |
| 140 | +fn comments(text: &str) -> Vec<String> { |
| 141 | + parse(text) |
| 142 | + .syntax() |
| 143 | + .descendants_with_tokens() |
| 144 | + .filter_map(|e| e.into_token()) |
| 145 | + .filter(|t| matches!(t.kind(), COMMENT | DOC_COMMENT)) |
| 146 | + .map(|t| t.text().trim_end().to_owned()) |
| 147 | + .collect() |
| 81 | 148 | } |
| 82 | 149 | |
| 83 | | −fn ends_line_open(kind: SyntaxKind) -> bool { |
| 84 | | − matches!(kind, ARROW | EQ | L_ARROW) |
| 150 | +// --------------------------------------------------------------------------- |
| 151 | +// The printer |
| 152 | + |
| 153 | +struct Printer<'a> { |
| 154 | + src: &'a str, |
| 155 | + /// Byte offset of each line's start, for same-line tests (comments). |
| 156 | + line_starts: Vec<usize>, |
| 85 | 157 | } |
| 86 | 158 | |
| 87 | | −struct Formatter { |
| 88 | | − out: String, |
| 89 | | − /// For each open bracket or HTML element: the indentation of lines |
| 90 | | − /// inside it (one more than the line that opened it). |
| 91 | | − stack: Vec<usize>, |
| 92 | | − /// Indentation of the line being written. |
| 93 | | − line_indent: usize, |
| 94 | | − in_open_tag: bool, |
| 95 | | − in_close_tag: bool, |
| 96 | | − /// The last significant token, and whether the current line is still |
| 97 | | − /// waiting for its first significant token (with the indent to use). |
| 98 | | − last: Option<SyntaxKind>, |
| 99 | | − pending_newlines: usize, |
| 159 | +/// One significant child of a node, with the comments around it. |
| 160 | +struct Item { |
| 161 | + el: SyntaxElement, |
| 162 | + /// Comments on their own lines above the element, each with whether a |
| 163 | + /// blank line precedes it. |
| 164 | + leading: Vec<(SyntaxToken, bool)>, |
| 165 | + /// A comment on the same line, after the element. |
| 166 | + trailing: Option<SyntaxToken>, |
| 167 | + /// A blank line separates this element from the previous one (or from |
| 168 | + /// its last leading comment). |
| 169 | + blank_before: bool, |
| 100 | 170 | } |
| 101 | 171 | |
| 102 | | −fn format_tree(root: &SyntaxNode) -> String { |
| 103 | | − let tokens: Vec<_> = root |
| 104 | | − .descendants_with_tokens() |
| 105 | | − .filter_map(|e| e.into_token()) |
| 106 | | − .collect(); |
| 107 | | − let mut f = Formatter { |
| 108 | | − out: String::new(), |
| 109 | | − stack: Vec::new(), |
| 110 | | − line_indent: 0, |
| 111 | | − in_open_tag: false, |
| 112 | | − in_close_tag: false, |
| 113 | | − last: None, |
| 114 | | − pending_newlines: 0, |
| 115 | | − }; |
| 116 | | − for tok in &tokens { |
| 117 | | − let kind = tok.kind(); |
| 118 | | − let text = tok.text(); |
| 119 | | − if kind == WHITESPACE { |
| 120 | | − let newlines = text.matches('\n').count(); |
| 121 | | − if newlines > 0 { |
| 122 | | − f.pending_newlines += newlines; |
| 123 | | − } else if f.pending_newlines == 0 && !f.out.is_empty() { |
| 124 | | − // Spacing within a line is the author's (alignment, two |
| 125 | | − // spaces between constructors); trailing spaces are not. |
| 126 | | − f.out.push_str(text); |
| 127 | | − } |
| 128 | | − continue; |
| 129 | | − } |
| 130 | | − if kind == HTML_TEXT { |
| 131 | | − f.html_text(text); |
| 132 | | − continue; |
| 133 | | − } |
| 134 | | − f.flush_line(kind); |
| 135 | | − f.out.push_str(text); |
| 136 | | − f.track(kind); |
| 137 | | − if !kind.is_trivia() { |
| 138 | | − f.last = Some(kind); |
| 139 | | − } |
| 140 | | − } |
| 141 | | − let mut out = f.out.trim_end().to_owned(); |
| 142 | | − out.push('\n'); |
| 143 | | − out |
| 172 | +/// The significant children of a node, in order, with comments attached. |
| 173 | +struct Seq { |
| 174 | + items: VecDeque<Item>, |
| 175 | + /// Comments after the last significant child (before the closer, or at |
| 176 | + /// the end of the file). |
| 177 | + end_comments: Vec<SyntaxToken>, |
| 144 | 178 | } |
| 145 | 179 | |
| 146 | | −impl Formatter { |
| 147 | | − /// Indentation for a line whose first token is `first`. |
| 148 | | − fn indent_for(&self, first: SyntaxKind) -> usize { |
| 149 | | − let inside = self.stack.last().copied().unwrap_or(0); |
| 150 | | − if matches!(first, R_BRACE | R_PAREN | R_BRACK | HTML_LT_SLASH) { |
| 151 | | − return inside.saturating_sub(1); |
| 180 | +/// One entry in a comma list: an item (which gets a leading comma when |
| 181 | +/// broken) or a comment on its own line (which does not). |
| 182 | +enum ListEntry<'a> { |
| 183 | + Item(Doc<'a>), |
| 184 | + Comment(Doc<'a>), |
| 185 | +} |
| 186 | + |
| 187 | +impl<'a> Printer<'a> { |
| 188 | + fn new(src: &'a str) -> Self { |
| 189 | + let line_starts = std::iter::once(0) |
| 190 | + .chain(src.match_indices('\n').map(|(i, _)| i + 1)) |
| 191 | + .collect(); |
| 192 | + Printer { src, line_starts } |
| 193 | + } |
| 194 | + |
| 195 | + fn line_of(&self, offset: usize) -> usize { |
| 196 | + self.line_starts.partition_point(|&s| s <= offset) - 1 |
| 197 | + } |
| 198 | + |
| 199 | + /// Walk a node's children: significant tokens and nodes become items; |
| 200 | + /// whitespace only feeds blank-line and same-line detection. |
| 201 | + fn seq(&self, parent: &SyntaxNode) -> Seq { |
| 202 | + let mut items: VecDeque<Item> = VecDeque::new(); |
| 203 | + let mut pending: Vec<(SyntaxToken, bool)> = Vec::new(); |
| 204 | + let mut newlines = 0usize; |
| 205 | + // A blank line: a whitespace run of two newlines or more. |
| 206 | + let mut blank_seen = false; |
| 207 | + let mut prev_end: Option<usize> = None; |
| 208 | + for child in parent.children_with_tokens() { |
| 209 | + let (kind, range) = (child.kind(), child.text_range()); |
| 210 | + let start: usize = range.start().into(); |
| 211 | + match &child { |
| 212 | + NodeOrToken::Token(tok) if kind == WHITESPACE => { |
| 213 | + let n = tok.text().matches('\n').count(); |
| 214 | + blank_seen |= n >= 2; |
| 215 | + newlines += n; |
| 216 | + } |
| 217 | + NodeOrToken::Token(tok) if matches!(kind, COMMENT | DOC_COMMENT) => { |
| 218 | + if newlines == 0 |
| 219 | + && prev_end.is_some_and(|end| self.line_of(end) == self.line_of(start)) |
| 220 | + && !items.is_empty() |
| 221 | + { |
| 222 | + items.back_mut().unwrap().trailing = Some(tok.clone()); |
| 223 | + } else { |
| 224 | + pending.push((tok.clone(), blank_seen)); |
| 225 | + blank_seen = false; |
| 226 | + } |
| 227 | + } |
| 228 | + NodeOrToken::Token(_) | NodeOrToken::Node(_) => { |
| 229 | + let has_pending = !pending.is_empty(); |
| 230 | + items.push_back(Item { |
| 231 | + el: child, |
| 232 | + leading: std::mem::take(&mut pending), |
| 233 | + trailing: None, |
| 234 | + blank_before: blank_seen && (!items.is_empty() || has_pending), |
| 235 | + }); |
| 236 | + prev_end = Some(range.end().into()); |
| 237 | + newlines = 0; |
| 238 | + blank_seen = false; |
| 239 | + } |
| 240 | + } |
| 241 | + } |
| 242 | + Seq { |
| 243 | + items, |
| 244 | + end_comments: pending.into_iter().map(|(c, _)| c).collect(), |
| 245 | + } |
| 246 | + } |
| 247 | + |
| 248 | + // ---- leaves ---------------------------------------------------------- |
| 249 | + |
| 250 | + fn t(&self, s: &'a str) -> Doc<'a> { |
| 251 | + Doc::Text(Cow::Borrowed(s)) |
| 252 | + } |
| 253 | + |
| 254 | + fn s(&self, s: impl Into<String>) -> Doc<'a> { |
| 255 | + Doc::Text(Cow::Owned(s.into())) |
| 256 | + } |
| 257 | + |
| 258 | + /// A token, verbatim. |
| 259 | + fn tok(&self, tok: &SyntaxToken) -> Doc<'a> { |
| 260 | + self.s(tok.text()) |
| 261 | + } |
| 262 | + |
| 263 | + /// A comment, trimmed of trailing whitespace (the token check does the |
| 264 | + /// same before comparing). |
| 265 | + fn comment(&self, tok: &SyntaxToken) -> Doc<'a> { |
| 266 | + self.s(tok.text().trim_end()) |
| 267 | + } |
| 268 | + |
| 269 | + /// The node's source text, untouched (fallback for shapes the printer |
| 270 | + /// does not expect, and the base of HTML re-indentation). |
| 271 | + fn raw(&self, node: &SyntaxNode) -> Doc<'a> { |
| 272 | + let range = node.text_range(); |
| 273 | + self.t(&self.src[usize::from(range.start())..usize::from(range.end())]) |
| 274 | + } |
| 275 | + |
| 276 | + /// An element with its comments: leading ones above on their own |
| 277 | + /// lines (blank lines between them kept), a trailing one at the end of |
| 278 | + /// its line. Either kind forces the enclosing groups to break. |
| 279 | + fn with_comments(&self, item: &Item, doc: Doc<'a>) -> Doc<'a> { |
| 280 | + let mut docs = Vec::new(); |
| 281 | + let mut first = true; |
| 282 | + for (c, blank) in &item.leading { |
| 283 | + // A blank before the first comment is the caller's to emit |
| 284 | + // (it separates this item from the previous one). |
| 285 | + if *blank && !first { |
| 286 | + docs.push(Doc::HardLine); |
| 287 | + } |
| 288 | + first = false; |
| 289 | + docs.push(self.comment(c)); |
| 290 | + docs.push(Doc::HardLine); |
| 291 | + } |
| 292 | + if item.blank_before && !item.leading.is_empty() { |
| 293 | + // A blank line between the last comment and the element. |
| 294 | + docs.push(Doc::HardLine); |
| 295 | + } |
| 296 | + docs.push(doc); |
| 297 | + if let Some(c) = &item.trailing { |
| 298 | + docs.push(self.t(" ")); |
| 299 | + docs.push(self.comment(c)); |
| 300 | + docs.push(Doc::HardLineSoft); |
| 301 | + } |
| 302 | + pretty::cat(docs) |
| 303 | + } |
| 304 | + |
| 305 | + /// Item with its comments, the common case. |
| 306 | + fn item_doc(&self, item: &Item) -> Doc<'a> { |
| 307 | + self.with_comments(item, self.el_doc(&item.el)) |
| 308 | + } |
| 309 | + |
| 310 | + /// A punctuation/keyword item printed as fixed text, keeping any |
| 311 | + /// comments around it: leading ones above, a trailing one at the end |
| 312 | + /// of the line (which then breaks: a comment ends its line). |
| 313 | + fn punct(&self, item: &Item, text: &'static str) -> Doc<'a> { |
| 314 | + let mut docs = Vec::new(); |
| 315 | + for (c, _) in &item.leading { |
| 316 | + docs.push(self.comment(c)); |
| 317 | + docs.push(Doc::HardLine); |
| 318 | + } |
| 319 | + docs.push(self.t(text)); |
| 320 | + if let Some(c) = &item.trailing { |
| 321 | + if !text.ends_with(' ') { |
| 322 | + docs.push(self.t(" ")); |
| 323 | + } |
| 324 | + docs.push(self.comment(c)); |
| 325 | + docs.push(Doc::HardLine); |
| 326 | + } |
| 327 | + pretty::cat(docs) |
| 328 | + } |
| 329 | + |
| 330 | + /// An item that is not printed (a keyword or punctuation the printer |
| 331 | + /// skips), so its comments are not silently dropped. |
| 332 | + fn skipped(&self, item: &Item) -> Doc<'a> { |
| 333 | + self.punct(item, "") |
| 334 | + } |
| 335 | + |
| 336 | + fn el_doc(&self, el: &SyntaxElement) -> Doc<'a> { |
| 337 | + match el { |
| 338 | + NodeOrToken::Node(n) => self.node_doc(n), |
| 339 | + NodeOrToken::Token(t) => self.tok(t), |
| 340 | + } |
| 341 | + } |
| 342 | + |
| 343 | + // ---- sequences ------------------------------------------------------- |
| 344 | + |
| 345 | + /// Statements/members/arms, one per line, keeping blank lines (max 1). |
| 346 | + /// `end_comments` print after the last entry. |
| 347 | + fn seq_stacked(&self, items: Vec<Item>, end_comments: &[SyntaxToken]) -> Doc<'a> { |
| 348 | + let mut docs = Vec::new(); |
| 349 | + let mut first = true; |
| 350 | + for item in items { |
| 351 | + // A blank line precedes the item, or its first comment. |
| 352 | + let starts_blank = item |
| 353 | + .leading |
| 354 | + .first() |
| 355 | + .map(|(_, b)| *b) |
| 356 | + .unwrap_or(item.blank_before); |
| 357 | + if !first { |
| 358 | + docs.push(Doc::HardLineSoft); |
| 359 | + if starts_blank { |
| 360 | + docs.push(Doc::HardLine); |
| 361 | + } |
| 362 | + } |
| 363 | + first = false; |
| 364 | + docs.push(self.item_doc(&item)); |
| 365 | + } |
| 366 | + for c in end_comments { |
| 367 | + if !first { |
| 368 | + docs.push(Doc::HardLineSoft); |
| 369 | + } |
| 370 | + first = false; |
| 371 | + docs.push(self.comment(c)); |
| 372 | + } |
| 373 | + pretty::cat(docs) |
| 374 | + } |
| 375 | + |
| 376 | + // ---- comma-separated lists ------------------------------------------- |
| 377 | + |
| 378 | + /// `[a, b]` flat, or broken with leading commas aligned with the |
| 379 | + /// brackets: |
| 380 | + /// |
| 381 | + /// ```text |
| 382 | + /// [ |
| 383 | + /// a |
| 384 | + /// , b |
| 385 | + /// ] |
| 386 | + /// ``` |
| 387 | + /// |
| 388 | + /// `keep_trailing_comma` preserves a meaningful trailing comma (the |
| 389 | + /// one-element tuple `(a,)`); other source trailing commas are dropped |
| 390 | + /// (the token check ignores them). |
| 391 | + fn list_group( |
| 392 | + &self, |
| 393 | + open: Doc<'a>, |
| 394 | + entries: Vec<ListEntry<'a>>, |
| 395 | + close: Doc<'a>, |
| 396 | + keep_trailing_comma: bool, |
| 397 | + ) -> Doc<'a> { |
| 398 | + if entries.is_empty() { |
| 399 | + return pretty::cat([open, close]); |
| 400 | + } |
| 401 | + let mut inner = vec![Doc::SoftLine]; |
| 402 | + let mut first_item = true; |
| 403 | + let mut first_entry = true; |
| 404 | + let mut prev_was_comment = false; |
| 405 | + for entry in entries { |
| 406 | + match entry { |
| 407 | + ListEntry::Item(doc) => { |
| 408 | + if first_item { |
| 409 | + first_item = false; |
| 410 | + if prev_was_comment { |
| 411 | + // A comment ends its line. |
| 412 | + inner.push(Doc::HardLine); |
| 413 | + } |
| 414 | + } else { |
| 415 | + inner.push(Doc::LeadComma); |
| 416 | + } |
| 417 | + inner.push(doc); |
| 418 | + prev_was_comment = false; |
| 419 | + } |
| 420 | + ListEntry::Comment(doc) => { |
| 421 | + // The following LeadComma (or the closing SoftLine) |
| 422 | + // provides the break after the comment. |
| 423 | + if !first_entry { |
| 424 | + inner.push(Doc::Line); |
| 425 | + } |
| 426 | + inner.push(doc); |
| 427 | + prev_was_comment = true; |
| 428 | + } |
| 429 | + } |
| 430 | + first_entry = false; |
| 431 | + } |
| 432 | + if keep_trailing_comma { |
| 433 | + inner.push(self.t(",")); |
| 434 | + } |
| 435 | + pretty::group_opaque(pretty::cat([ |
| 436 | + open, |
| 437 | + pretty::nest(1, pretty::cat(inner)), |
| 438 | + Doc::SoftLine, |
| 439 | + close, |
| 440 | + ])) |
| 441 | + } |
| 442 | + /// The middle of a bracketed list: element entries, with comments kept |
| 443 | + /// on their own lines (a trailing comment of a comma belongs to the |
| 444 | + /// item before it), and whether a comma directly preceded the closer. |
| 445 | + /// `open`/`close` are the bracket tokens' kinds. |
| 446 | + /// Returns (open doc, entries, close doc, had trailing comma). |
| 447 | + fn bracket_parts( |
| 448 | + &self, |
| 449 | + node: &SyntaxNode, |
| 450 | + open: SyntaxKind, |
| 451 | + close: SyntaxKind, |
| 452 | + ) -> Option<(Doc<'a>, Vec<ListEntry<'a>>, Doc<'a>, bool)> { |
| 453 | + let Seq { mut items, .. } = self.seq(node); |
| 454 | + let close_item = items.pop_back()?; |
| 455 | + if close_item.el.kind() != close { |
| 456 | + return None; |
| 457 | + } |
| 458 | + let open_item = items.pop_front()?; |
| 459 | + if open_item.el.kind() != open { |
| 460 | + return None; |
| 461 | + } |
| 462 | + let mut entries: Vec<ListEntry<'a>> = Vec::new(); |
| 463 | + let mut trailing_comma = false; |
| 464 | + for item in items { |
| 465 | + match item.el.kind() { |
| 466 | + COMMA => { |
| 467 | + trailing_comma = true; |
| 468 | + // A comment on a comma line belongs to the item before. |
| 469 | + if let Some(c) = item.trailing |
| 470 | + && let Some(ListEntry::Item(last)) = entries.last_mut() |
| 471 | + { |
| 472 | + *last = pretty::cat([ |
| 473 | + std::mem::replace(last, Doc::Nil), |
| 474 | + self.t(" "), |
| 475 | + self.comment(&c), |
| 476 | + Doc::HardLineSoft, |
| 477 | + ]); |
| 478 | + continue; |
| 479 | + } |
| 480 | + for (c, _) in item.leading { |
| 481 | + entries.push(ListEntry::Comment(self.comment(&c))); |
| 482 | + } |
| 483 | + } |
| 484 | + _ => { |
| 485 | + trailing_comma = false; |
| 486 | + for (c, _) in &item.leading { |
| 487 | + entries.push(ListEntry::Comment(pretty::cat([ |
| 488 | + self.comment(c), |
| 489 | + Doc::HardLineSoft, |
| 490 | + ]))); |
| 491 | + } |
| 492 | + let doc = self.el_doc(&item.el); |
| 493 | + let doc = match &item.trailing { |
| 494 | + Some(c) => { |
| 495 | + pretty::cat([doc, self.t(" "), self.comment(c), Doc::HardLineSoft]) |
| 496 | + } |
| 497 | + None => doc, |
| 498 | + }; |
| 499 | + entries.push(ListEntry::Item(doc)); |
| 500 | + } |
| 501 | + } |
| 502 | + } |
| 503 | + // Comments before the closer. |
| 504 | + for (c, _) in close_item.leading { |
| 505 | + entries.push(ListEntry::Comment(pretty::cat([ |
| 506 | + self.comment(&c), |
| 507 | + Doc::HardLineSoft, |
| 508 | + ]))); |
| 509 | + } |
| 510 | + let open_doc = self.with_comments(&open_item, self.el_doc(&open_item.el)); |
| 511 | + Some(( |
| 512 | + open_doc, |
| 513 | + entries, |
| 514 | + self.el_doc(&close_item.el), |
| 515 | + trailing_comma, |
| 516 | + )) |
| 517 | + } |
| 518 | + |
| 519 | + /// A bracketed comma list node: `( ... )`, `[ ... ]`, `{ ... }`, |
| 520 | + /// `< ... >`, or one wrapped in a node (ARG_LIST, PARAM_LIST, ...). |
| 521 | + /// `tuple` marks the contexts where a one-element list's trailing |
| 522 | + /// comma is meaningful (`(a,)`): it is kept there. |
| 523 | + fn bracket_list( |
| 524 | + &self, |
| 525 | + node: &SyntaxNode, |
| 526 | + open: SyntaxKind, |
| 527 | + close: SyntaxKind, |
| 528 | + tuple: bool, |
| 529 | + ) -> Doc<'a> { |
| 530 | + match self.bracket_parts(node, open, close) { |
| 531 | + Some((open_doc, entries, close_doc, had_trailing_comma)) => { |
| 532 | + let item_count = entries |
| 533 | + .iter() |
| 534 | + .filter(|e| matches!(e, ListEntry::Item(_))) |
| 535 | + .count(); |
| 536 | + let keep = tuple && had_trailing_comma && item_count == 1; |
| 537 | + self.list_group(open_doc, entries, close_doc, keep) |
| 538 | + } |
| 539 | + None => self.raw(node), |
| 540 | + } |
| 541 | + } |
| 542 | + |
| 543 | + // ---- the dispatch ---------------------------------------------------- |
| 544 | + |
| 545 | + fn node_doc(&self, node: &SyntaxNode) -> Doc<'a> { |
| 546 | + match node.kind() { |
| 547 | + SOURCE_FILE => self.raw(node), // handled by `source_file` |
| 548 | + ATTR => self.attr(node), |
| 549 | + IMPORT => self.import(node), |
| 550 | + IMPORT_PATH => self.joined_tokens(node), |
| 551 | + IMPORT_LIST => self.bracket_list(node, L_BRACE, R_BRACE, false), |
| 552 | + IMPORT_ITEM => self.import_item(node), |
| 553 | + FN_DEF => self.fn_def(node), |
| 554 | + PARAM_LIST => self.bracket_list(node, L_PAREN, R_PAREN, false), |
| 555 | + PARAM => self.param(node), |
| 556 | + RET_TYPE => self.ret_type(node), |
| 557 | + EFFECT_ROW => self.effect_row(node), |
| 558 | + WHERE_CLAUSE => self.where_clause(node), |
| 559 | + TYPE_DEF => self.type_def(node), |
| 560 | + TYPE_PARAMS => self.bracket_list(node, LT, GT, false), |
| 561 | + VARIANT_LIST => self.variant_list(node), |
| 562 | + VARIANT => self.variant(node), |
| 563 | + FIELD_LIST => self.bracket_list(node, L_PAREN, R_PAREN, false), |
| 564 | + FIELD => self.field(node), |
| 565 | + VARIANT_RESULT => self.variant_result(node), |
| 566 | + EFFECT_DEF => self.effect_def(node), |
| 567 | + EFFECT_OP => self.effect_op(node), |
| 568 | + TRAIT_DEF => self.trait_def(node), |
| 569 | + IMPL_DEF => self.impl_def(node), |
| 570 | + ASSOC_TYPE => self.assoc_type(node), |
| 571 | + ASSOC_BINDING => self.assoc_binding(node), |
| 572 | + NAME | NAME_REF => self.raw(node), |
| 573 | + |
| 574 | + PATH_TYPE => self.path_type(node), |
| 575 | + TYPE_ARGS => self.bracket_list(node, LT, GT, false), |
| 576 | + FN_TYPE => self.fn_type(node), |
| 577 | + TUPLE_TYPE => self.bracket_list(node, L_PAREN, R_PAREN, true), |
| 578 | + |
| 579 | + LITERAL => self.raw(node), |
| 580 | + INTERP_STRING => self.interp_string(node), |
| 581 | + INTERP_HOLE => self.interp_hole(node), |
| 582 | + TEMPLATE_EXPR => self.template_expr(node), |
| 583 | + PATH_EXPR => self.raw(node), |
| 584 | + PAREN_EXPR => self.bracket_list(node, L_PAREN, R_PAREN, false), |
| 585 | + TUPLE_EXPR => self.bracket_list(node, L_PAREN, R_PAREN, true), |
| 586 | + LIST_EXPR => self.bracket_list(node, L_BRACK, R_BRACK, false), |
| 587 | + SPREAD => self.prefixed(node, ".."), |
| 588 | + BLOCK => self.block(node), |
| 589 | + LET_STMT => self.let_stmt(node), |
| 590 | + USE_STMT => self.use_stmt(node), |
| 591 | + DEFER_STMT => self.prefixed(node, "defer "), |
| 592 | + BIN_EXPR => self.bin_expr(node), |
| 593 | + PREFIX_EXPR => self.prefix_expr(node), |
| 594 | + CALL_EXPR => self.call_expr(node), |
| 595 | + ARG_LIST => self.bracket_list(node, L_PAREN, R_PAREN, false), |
| 596 | + ARG => self.arg(node), |
| 597 | + LABEL => self.label(node), |
| 598 | + FIELD_EXPR => self.field_expr(node), |
| 599 | + IF_EXPR => self.if_expr(node), |
| 600 | + ELSE_BRANCH => self.else_branch(node), |
| 601 | + MATCH_EXPR => self.match_expr(node), |
| 602 | + MATCH_ARM => self.match_arm(node), |
| 603 | + MATCH_GUARD => self.prefixed(node, "if "), |
| 604 | + LAMBDA_EXPR => self.lambda(node), |
| 605 | + HANDLE_EXPR => self.handle_expr(node), |
| 606 | + HANDLER_CLAUSE => self.handler_clause(node), |
| 607 | + REGION_EXPR => self.prefixed(node, "region "), |
| 608 | + RETURN_EXPR => self.return_expr(node), |
| 609 | + PLACEHOLDER_EXPR => self.raw(node), |
| 610 | + |
| 611 | + WILDCARD_PAT | BIND_PAT | LITERAL_PAT => self.raw(node), |
| 612 | + CTOR_PAT => self.ctor_pat(node), |
| 613 | + PAT_ARG_LIST => self.bracket_list(node, L_PAREN, R_PAREN, false), |
| 614 | + PAT_ARG => self.arg(node), |
| 615 | + TUPLE_PAT => self.bracket_list(node, L_PAREN, R_PAREN, true), |
| 616 | + LIST_PAT => self.bracket_list(node, L_BRACK, R_BRACK, false), |
| 617 | + REST_PAT => self.prefixed(node, ".."), |
| 618 | + ALT_PAT => self.alt_pat(node), |
| 619 | + AS_PAT => self.as_pat(node), |
| 620 | + |
| 621 | + HTML_ELEMENT => self.html_element(node), |
| 622 | + HTML_OPEN_TAG => self.html_open_tag(node), |
| 623 | + HTML_ATTR => self.html_attr(node), |
| 624 | + HTML_EXPR => self.html_expr(node), |
| 625 | + HTML_CLOSE_TAG => self.raw(node), |
| 626 | + |
| 627 | + _ => self.raw(node), |
| 628 | + } |
| 629 | + } |
| 630 | + |
| 631 | + // ---- files and items --------------------------------------------------- |
| 632 | + |
| 633 | + pub(crate) fn source_file(&self, node: &SyntaxNode) -> Doc<'a> { |
| 634 | + let Seq { |
| 635 | + items, |
| 636 | + end_comments, |
| 637 | + } = self.seq(node); |
| 638 | + self.seq_stacked(items.into_iter().collect(), &end_comments) |
| 639 | + } |
| 640 | + |
| 641 | + /// `@name` or `@name(arg, ...)`. |
| 642 | + fn attr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 643 | + let Seq { items, .. } = self.seq(node); |
| 644 | + let mut docs = vec![self.t("@")]; |
| 645 | + for item in items { |
| 646 | + match item.el.kind() { |
| 647 | + AT => docs.push(self.skipped(&item)), |
| 648 | + NAME => docs.push(self.item_doc(&item)), |
| 649 | + ATTR_ARG_LIST => docs.push(self.item_doc(&item)), |
| 650 | + _ => docs.push(self.item_doc(&item)), |
| 651 | + } |
| 652 | + } |
| 653 | + pretty::cat(docs) |
| 654 | + } |
| 655 | + |
| 656 | + /// `import a/b.{x, type T as U} as c` |
| 657 | + fn import(&self, node: &SyntaxNode) -> Doc<'a> { |
| 658 | + let Seq { items, .. } = self.seq(node); |
| 659 | + let mut docs = vec![self.t("import ")]; |
| 660 | + for item in items { |
| 661 | + match item.el.kind() { |
| 662 | + IMPORT_KW => docs.push(self.skipped(&item)), |
| 663 | + DOT => docs.push(self.item_doc(&item)), |
| 664 | + AS_KW => docs.push(self.punct(&item, " as ")), |
| 665 | + _ => docs.push(self.item_doc(&item)), |
| 666 | + } |
| 667 | + } |
| 668 | + pretty::cat(docs) |
| 669 | + } |
| 670 | + |
| 671 | + /// `type T as U`, `x`. |
| 672 | + fn import_item(&self, node: &SyntaxNode) -> Doc<'a> { |
| 673 | + let Seq { items, .. } = self.seq(node); |
| 674 | + let mut docs = Vec::new(); |
| 675 | + for item in items { |
| 676 | + match item.el.kind() { |
| 677 | + TYPE_KW => docs.push(self.punct(&item, "type ")), |
| 678 | + AS_KW => docs.push(self.punct(&item, " as ")), |
| 679 | + _ => docs.push(self.item_doc(&item)), |
| 680 | + } |
| 681 | + } |
| 682 | + pretty::cat(docs) |
| 683 | + } |
| 684 | + |
| 685 | + /// `a/b/c`: name refs joined by `/`. |
| 686 | + fn joined_tokens(&self, node: &SyntaxNode) -> Doc<'a> { |
| 687 | + let Seq { items, .. } = self.seq(node); |
| 688 | + let docs: Vec<_> = items |
| 689 | + .iter() |
| 690 | + .filter(|i| i.el.kind() != SLASH) |
| 691 | + .map(|i| self.item_doc(i)) |
| 692 | + .collect(); |
| 693 | + pretty::join(self.t("/"), docs) |
| 694 | + } |
| 695 | + |
| 696 | + /// Attributes and `pub`/`opaque` before an item's keyword. |
| 697 | + fn item_prefix(&self, items: &mut VecDeque<Item>) -> Vec<Doc<'a>> { |
| 698 | + let mut docs = Vec::new(); |
| 699 | + while let Some(front) = items.front() { |
| 700 | + match front.el.kind() { |
| 701 | + ATTR => { |
| 702 | + let item = items.pop_front().unwrap(); |
| 703 | + docs.push(self.item_doc(&item)); |
| 704 | + docs.push(Doc::HardLine); |
| 705 | + } |
| 706 | + VISIBILITY => { |
| 707 | + let item = items.pop_front().unwrap(); |
| 708 | + docs.push(self.punct(&item, "pub ")); |
| 709 | + } |
| 710 | + OPAQUE_KW => { |
| 711 | + let item = items.pop_front().unwrap(); |
| 712 | + docs.push(self.punct(&item, "opaque ")); |
| 713 | + } |
| 714 | + _ => break, |
| 715 | + } |
| 716 | + } |
| 717 | + docs |
| 718 | + } |
| 719 | + |
| 720 | + /// `fn name(params) -> T / <effects> where C { body }` |
| 721 | + fn fn_def(&self, node: &SyntaxNode) -> Doc<'a> { |
| 722 | + let Seq { mut items, .. } = self.seq(node); |
| 723 | + let mut docs = self.item_prefix(&mut items); |
| 724 | + let mut block = None; |
| 725 | + for item in items { |
| 726 | + match item.el.kind() { |
| 727 | + FN_KW => docs.push(self.punct(&item, "fn ")), |
| 728 | + PARAM_LIST => docs.push(self.item_doc(&item)), |
| 729 | + RET_TYPE | WHERE_CLAUSE => { |
| 730 | + docs.push(self.t(" ")); |
| 731 | + docs.push(self.item_doc(&item)); |
| 732 | + } |
| 733 | + BLOCK => { |
| 734 | + let doc = match &item.el { |
| 735 | + NodeOrToken::Node(n) => self.block_always(n), |
| 736 | + NodeOrToken::Token(_) => self.el_doc(&item.el), |
| 737 | + }; |
| 738 | + block = Some(self.with_comments(&item, doc)); |
| 739 | + } |
| 740 | + _ => docs.push(self.item_doc(&item)), |
| 741 | + } |
| 742 | + } |
| 743 | + if let Some(b) = block { |
| 744 | + docs.push(self.t(" ")); |
| 745 | + docs.push(b); |
| 746 | + } |
| 747 | + pretty::cat(docs) |
| 748 | + } |
| 749 | + |
| 750 | + /// `pat: T` in a parameter list. |
| 751 | + fn param(&self, node: &SyntaxNode) -> Doc<'a> { |
| 752 | + let Seq { items, .. } = self.seq(node); |
| 753 | + let mut docs = Vec::new(); |
| 754 | + for item in items { |
| 755 | + match item.el.kind() { |
| 756 | + COLON => docs.push(self.punct(&item, ": ")), |
| 757 | + _ => docs.push(self.item_doc(&item)), |
| 758 | + } |
| 759 | + } |
| 760 | + pretty::cat(docs) |
| 761 | + } |
| 762 | + |
| 763 | + /// `-> T / <row>`; the row breaks onto its own line when needed. |
| 764 | + fn ret_type(&self, node: &SyntaxNode) -> Doc<'a> { |
| 765 | + let Seq { items, .. } = self.seq(node); |
| 766 | + let mut ty = None; |
| 767 | + let mut row = None; |
| 768 | + let mut pre = Vec::new(); |
| 769 | + for item in items { |
| 770 | + match item.el.kind() { |
| 771 | + ARROW | SLASH => pre.push(self.skipped(&item)), |
| 772 | + EFFECT_ROW => row = Some(self.item_doc(&item)), |
| 773 | + _ => ty = Some(self.item_doc(&item)), |
| 774 | + } |
| 775 | + } |
| 776 | + let mut docs = pre; |
| 777 | + docs.push(self.t("-> ")); |
| 778 | + docs.push(ty.unwrap_or(Doc::Nil)); |
| 779 | + if let Some(row) = row { |
| 780 | + docs.push(pretty::nest(1, pretty::cat([Doc::Line, self.t("/ "), row]))); |
| 781 | + } |
| 782 | + pretty::group(pretty::cat(docs)) |
| 783 | + } |
| 784 | + |
| 785 | + /// `<io, fail | e>`; broken with trailing commas (rows are not lists). |
| 786 | + fn effect_row(&self, node: &SyntaxNode) -> Doc<'a> { |
| 787 | + let Seq { items, .. } = self.seq(node); |
| 788 | + let mut labels = Vec::new(); |
| 789 | + let mut tail = None; |
| 790 | + let mut after_pipe = false; |
| 791 | + for item in items { |
| 792 | + match item.el.kind() { |
| 793 | + LT | GT | COMMA => {} |
| 794 | + PIPE => after_pipe = true, |
| 795 | + _ if after_pipe => tail = Some(self.item_doc(&item)), |
| 796 | + _ => labels.push(self.item_doc(&item)), |
| 797 | + } |
| 798 | + } |
| 799 | + if labels.is_empty() && tail.is_none() { |
| 800 | + return pretty::cat([self.t("<"), self.t(">")]); |
| 801 | + } |
| 802 | + let mut inner = vec![Doc::SoftLine]; |
| 803 | + for (i, label) in labels.into_iter().enumerate() { |
| 804 | + if i > 0 { |
| 805 | + inner.push(self.t(",")); |
| 806 | + inner.push(Doc::Line); |
| 807 | + } |
| 808 | + inner.push(label); |
| 809 | + } |
| 810 | + if let Some(tail) = tail { |
| 811 | + if !inner.iter().all(|d| matches!(d, Doc::SoftLine)) { |
| 812 | + inner.push(Doc::Line); |
| 813 | + } |
| 814 | + inner.push(self.t("| ")); |
| 815 | + inner.push(tail); |
| 152 | 816 | } |
| 153 | | − if is_continuation_start(first) || self.last.is_some_and(ends_line_open) { |
| 154 | | − return inside + 1; |
| 817 | + pretty::group(pretty::cat([ |
| 818 | + self.t("<"), |
| 819 | + pretty::nest(1, pretty::cat(inner)), |
| 820 | + Doc::SoftLine, |
| 821 | + self.t(">"), |
| 822 | + ])) |
| 823 | + } |
| 824 | + |
| 825 | + /// `where Show<a>, Eq<b>`; broken with leading commas. A trailing |
| 826 | + /// comma (a variant's `where` ends at the end of the line, so its |
| 827 | + /// comma lands here) is kept. |
| 828 | + fn where_clause(&self, node: &SyntaxNode) -> Doc<'a> { |
| 829 | + let Seq { items, .. } = self.seq(node); |
| 830 | + let mut docs = Vec::new(); |
| 831 | + let mut types = Vec::new(); |
| 832 | + let mut trailing_comma = false; |
| 833 | + for item in &items { |
| 834 | + match item.el.kind() { |
| 835 | + WHERE_KW => docs.push(self.skipped(item)), |
| 836 | + COMMA => { |
| 837 | + docs.push(self.skipped(item)); |
| 838 | + trailing_comma = true; |
| 839 | + } |
| 840 | + _ => { |
| 841 | + trailing_comma = false; |
| 842 | + types.push(self.item_doc(item)); |
| 843 | + } |
| 844 | + } |
| 845 | + } |
| 846 | + let mut list = vec![pretty::join(Doc::LeadComma, types)]; |
| 847 | + if trailing_comma { |
| 848 | + list.push(self.t(",")); |
| 849 | + } |
| 850 | + docs.push(self.t("where ")); |
| 851 | + docs.push(pretty::group(pretty::nest(1, pretty::cat(list)))); |
| 852 | + pretty::cat(docs) |
| 853 | + } |
| 854 | + |
| 855 | + /// `type Name<a> { ... }`, `type Name<a> = T`, or `type Name<a>`. An |
| 856 | + /// empty `{ }` is dropped: `pub type Account {}` is `pub type |
| 857 | + /// Account` (the token check ignores those two tokens). |
| 858 | + fn type_def(&self, node: &SyntaxNode) -> Doc<'a> { |
| 859 | + let Seq { mut items, .. } = self.seq(node); |
| 860 | + let mut docs = self.item_prefix(&mut items); |
| 861 | + for item in items { |
| 862 | + match item.el.kind() { |
| 863 | + TYPE_KW => docs.push(self.punct(&item, "type ")), |
| 864 | + EQ => docs.push(self.punct(&item, " = ")), |
| 865 | + VARIANT_LIST => { |
| 866 | + if let NodeOrToken::Node(n) = &item.el |
| 867 | + && empty_variant_list(n) |
| 868 | + { |
| 869 | + docs.push(self.skipped(&item)); |
| 870 | + continue; |
| 871 | + } |
| 872 | + docs.push(self.t(" ")); |
| 873 | + docs.push(self.item_doc(&item)); |
| 874 | + } |
| 875 | + _ => docs.push(self.item_doc(&item)), |
| 876 | + } |
| 877 | + } |
| 878 | + pretty::cat(docs) |
| 879 | + } |
| 880 | + |
| 881 | + /// `{ Variant ... }`: one line when a single variant fits; otherwise |
| 882 | + /// one variant per line. Source commas between variants are kept. |
| 883 | + fn variant_list(&self, node: &SyntaxNode) -> Doc<'a> { |
| 884 | + let Seq { |
| 885 | + mut items, |
| 886 | + end_comments, |
| 887 | + } = self.seq(node); |
| 888 | + let Some(close_item) = items.pop_back() else { |
| 889 | + return self.raw(node); |
| 890 | + }; |
| 891 | + let Some(open_item) = items.pop_front() else { |
| 892 | + return self.raw(node); |
| 893 | + }; |
| 894 | + if open_item.el.kind() != L_BRACE || close_item.el.kind() != R_BRACE { |
| 895 | + return self.raw(node); |
| 896 | + } |
| 897 | + let mut variants: Vec<(Doc<'a>, bool)> = Vec::new(); |
| 898 | + for item in items { |
| 899 | + match item.el.kind() { |
| 900 | + COMMA => { |
| 901 | + if let Some((last, _)) = variants.last_mut() { |
| 902 | + let mut d = vec![std::mem::replace(last, Doc::Nil), self.t(",")]; |
| 903 | + if let Some(c) = &item.trailing { |
| 904 | + d.push(self.t(" ")); |
| 905 | + d.push(self.comment(c)); |
| 906 | + d.push(Doc::HardLineSoft); |
| 907 | + } |
| 908 | + *last = pretty::cat(d); |
| 909 | + } |
| 910 | + for (c, _) in &item.leading { |
| 911 | + variants.push((self.comment(c), false)); |
| 912 | + } |
| 913 | + } |
| 914 | + _ => { |
| 915 | + let starts_blank = item |
| 916 | + .leading |
| 917 | + .first() |
| 918 | + .map(|(_, b)| *b) |
| 919 | + .unwrap_or(item.blank_before); |
| 920 | + variants.push((self.item_doc(&item), starts_blank)); |
| 921 | + } |
| 922 | + } |
| 923 | + } |
| 924 | + let mut end: Vec<SyntaxToken> = close_item.leading.into_iter().map(|(c, _)| c).collect(); |
| 925 | + end.extend(end_comments); |
| 926 | + let open = self.with_comments(&open_item, self.t("{")); |
| 927 | + if variants.is_empty() && end.is_empty() && open_item.trailing.is_none() { |
| 928 | + return self.t("{}"); |
| 929 | + } |
| 930 | + let mut body = Vec::new(); |
| 931 | + for (i, (doc, blank)) in variants.into_iter().enumerate() { |
| 932 | + if i > 0 { |
| 933 | + body.push(Doc::HardLineSoft); |
| 934 | + if blank { |
| 935 | + body.push(Doc::HardLine); |
| 936 | + } |
| 937 | + } |
| 938 | + body.push(doc); |
| 939 | + } |
| 940 | + for c in &end { |
| 941 | + body.push(Doc::HardLineSoft); |
| 942 | + body.push(self.comment(c)); |
| 943 | + } |
| 944 | + let body = pretty::cat(body); |
| 945 | + pretty::group(pretty::cat([ |
| 946 | + open, |
| 947 | + pretty::nest(1, pretty::cat([Doc::Line, body])), |
| 948 | + Doc::Line, |
| 949 | + self.t("}"), |
| 950 | + ])) |
| 951 | + } |
| 952 | + |
| 953 | + /// `Name(field: T, U) -> Name<..> where C` |
| 954 | + fn variant(&self, node: &SyntaxNode) -> Doc<'a> { |
| 955 | + let Seq { items, .. } = self.seq(node); |
| 956 | + let mut docs = Vec::new(); |
| 957 | + for item in items { |
| 958 | + match item.el.kind() { |
| 959 | + FIELD_LIST => docs.push(self.item_doc(&item)), |
| 960 | + VARIANT_RESULT | WHERE_CLAUSE => { |
| 961 | + docs.push(pretty::nest( |
| 962 | + 1, |
| 963 | + pretty::cat([Doc::Line, self.item_doc(&item)]), |
| 964 | + )); |
| 965 | + } |
| 966 | + _ => docs.push(self.item_doc(&item)), |
| 967 | + } |
| 155 | 968 | } |
| 156 | | − inside |
| 969 | + pretty::group(pretty::cat(docs)) |
| 157 | 970 | } |
| 158 | 971 | |
| 159 | | − /// Emit pending line breaks (at most one blank line) and indentation. |
| 160 | | − fn flush_line(&mut self, first: SyntaxKind) { |
| 161 | | − if self.pending_newlines == 0 { |
| 972 | + /// `-> T` after a constructor's fields. |
| 973 | + fn variant_result(&self, node: &SyntaxNode) -> Doc<'a> { |
| 974 | + let Seq { items, .. } = self.seq(node); |
| 975 | + let mut docs = Vec::new(); |
| 976 | + for item in items { |
| 977 | + if item.el.kind() == ARROW { |
| 978 | + docs.push(self.punct(&item, "-> ")); |
| 979 | + } else { |
| 980 | + docs.push(self.item_doc(&item)); |
| 981 | + } |
| 982 | + } |
| 983 | + pretty::cat(docs) |
| 984 | + } |
| 985 | + |
| 986 | + /// `name: T` or `T` in a constructor's field list. |
| 987 | + fn field(&self, node: &SyntaxNode) -> Doc<'a> { |
| 988 | + let Seq { items, .. } = self.seq(node); |
| 989 | + let mut docs = Vec::new(); |
| 990 | + for item in items { |
| 991 | + match item.el.kind() { |
| 992 | + COLON => docs.push(self.punct(&item, ": ")), |
| 993 | + _ => docs.push(self.item_doc(&item)), |
| 994 | + } |
| 995 | + } |
| 996 | + pretty::cat(docs) |
| 997 | + } |
| 998 | + |
| 999 | + /// `effect name<a> { ops }`; operations one per line. |
| 1000 | + fn effect_def(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1001 | + let Seq { mut items, .. } = self.seq(node); |
| 1002 | + let mut docs = self.item_prefix(&mut items); |
| 1003 | + self.braced_body(&mut items, &mut docs, "effect "); |
| 1004 | + pretty::cat(docs) |
| 1005 | + } |
| 1006 | + |
| 1007 | + /// `fn op(..) -> T`, `final ctl op(..) -> T`. |
| 1008 | + fn effect_op(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1009 | + let Seq { items, .. } = self.seq(node); |
| 1010 | + let mut docs = Vec::new(); |
| 1011 | + for item in items { |
| 1012 | + match item.el.kind() { |
| 1013 | + FINAL_KW => docs.push(self.punct(&item, "final ")), |
| 1014 | + MULTI_KW => docs.push(self.punct(&item, "multi ")), |
| 1015 | + CTL_KW => docs.push(self.punct(&item, "ctl ")), |
| 1016 | + FN_KW => docs.push(self.punct(&item, "fn ")), |
| 1017 | + RET_TYPE | WHERE_CLAUSE => { |
| 1018 | + docs.push(self.t(" ")); |
| 1019 | + docs.push(self.item_doc(&item)); |
| 1020 | + } |
| 1021 | + _ => docs.push(self.item_doc(&item)), |
| 1022 | + } |
| 1023 | + } |
| 1024 | + pretty::cat(docs) |
| 1025 | + } |
| 1026 | + |
| 1027 | + /// `trait Show<a> { ... }` |
| 1028 | + fn trait_def(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1029 | + let Seq { mut items, .. } = self.seq(node); |
| 1030 | + let mut docs = self.item_prefix(&mut items); |
| 1031 | + self.braced_body(&mut items, &mut docs, "trait "); |
| 1032 | + pretty::cat(docs) |
| 1033 | + } |
| 1034 | + |
| 1035 | + /// `impl Show<Int> where C { ... }` |
| 1036 | + fn impl_def(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1037 | + let Seq { mut items, .. } = self.seq(node); |
| 1038 | + let mut docs = self.item_prefix(&mut items); |
| 1039 | + self.braced_body(&mut items, &mut docs, "impl "); |
| 1040 | + pretty::cat(docs) |
| 1041 | + } |
| 1042 | + |
| 1043 | + /// The name, parameters and `{ members }` shared by effect, trait and |
| 1044 | + /// impl definitions: members one per line, always. The leading item |
| 1045 | + /// in `items` is the keyword, printed as `kw` with its comments. |
| 1046 | + fn braced_body(&self, items: &mut VecDeque<Item>, docs: &mut Vec<Doc<'a>>, kw: &'static str) { |
| 1047 | + if let Some(kw_item) = items.pop_front() { |
| 1048 | + for (c, _) in &kw_item.leading { |
| 1049 | + docs.push(self.comment(c)); |
| 1050 | + docs.push(Doc::HardLine); |
| 1051 | + } |
| 1052 | + docs.push(self.t(kw)); |
| 1053 | + if let Some(c) = &kw_item.trailing { |
| 1054 | + docs.push(self.t(" ")); |
| 1055 | + docs.push(self.comment(c)); |
| 1056 | + docs.push(Doc::HardLineSoft); |
| 1057 | + } |
| 1058 | + } |
| 1059 | + while let Some(front) = items.front() { |
| 1060 | + if front.el.kind() == L_BRACE { |
| 1061 | + break; |
| 1062 | + } |
| 1063 | + match items.pop_front() { |
| 1064 | + Some(item) => { |
| 1065 | + if item.el.kind() == WHERE_CLAUSE { |
| 1066 | + docs.push(self.t(" ")); |
| 1067 | + } |
| 1068 | + docs.push(self.item_doc(&item)); |
| 1069 | + } |
| 1070 | + None => break, |
| 1071 | + } |
| 1072 | + } |
| 1073 | + let Some(open_item) = items.pop_front() else { |
| 1074 | + return; |
| 1075 | + }; |
| 1076 | + let Some(close_item) = items.pop_back() else { |
| 1077 | + docs.push(self.item_doc(&open_item)); |
| 1078 | + docs.extend( |
| 1079 | + items |
| 1080 | + .drain(..) |
| 1081 | + .map(|i| self.item_doc(&i)) |
| 1082 | + .collect::<Vec<_>>(), |
| 1083 | + ); |
| 162 | 1084 | return; |
| 1085 | + }; |
| 1086 | + let members: Vec<Item> = items.drain(..).collect(); |
| 1087 | + let end: Vec<SyntaxToken> = close_item.leading.into_iter().map(|(c, _)| c).collect(); |
| 1088 | + let open = self.with_comments(&open_item, self.t(" {")); |
| 1089 | + if members.is_empty() && end.is_empty() && open_item.trailing.is_none() { |
| 1090 | + docs.push(self.t(" {}")); |
| 1091 | + return; |
| 1092 | + } |
| 1093 | + docs.push(open); |
| 1094 | + docs.push(pretty::nest( |
| 1095 | + 1, |
| 1096 | + pretty::cat([Doc::HardLineSoft, self.seq_stacked(members, &end)]), |
| 1097 | + )); |
| 1098 | + docs.push(Doc::HardLineSoft); |
| 1099 | + docs.push(self.t("}")); |
| 1100 | + } |
| 1101 | + |
| 1102 | + /// `type Elem`, `type Elem = a`. |
| 1103 | + fn assoc_type(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1104 | + let Seq { items, .. } = self.seq(node); |
| 1105 | + let mut docs = vec![self.t("type ")]; |
| 1106 | + for item in items { |
| 1107 | + match item.el.kind() { |
| 1108 | + TYPE_KW => docs.push(self.skipped(&item)), |
| 1109 | + EQ => docs.push(self.punct(&item, " = ")), |
| 1110 | + _ => docs.push(self.item_doc(&item)), |
| 1111 | + } |
| 1112 | + } |
| 1113 | + pretty::cat(docs) |
| 1114 | + } |
| 1115 | + |
| 1116 | + /// `Elem = Int`, `Mapped<x> = List<x>` among type arguments. |
| 1117 | + fn assoc_binding(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1118 | + let Seq { items, .. } = self.seq(node); |
| 1119 | + let mut docs = Vec::new(); |
| 1120 | + for item in items { |
| 1121 | + match item.el.kind() { |
| 1122 | + EQ => docs.push(self.punct(&item, " = ")), |
| 1123 | + _ => docs.push(self.item_doc(&item)), |
| 1124 | + } |
| 1125 | + } |
| 1126 | + pretty::cat(docs) |
| 1127 | + } |
| 1128 | + |
| 1129 | + // ---- types ------------------------------------------------------------- |
| 1130 | + |
| 1131 | + /// `a.b.C<..>`: a dotted path with optional type arguments. |
| 1132 | + fn path_type(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1133 | + let Seq { items, .. } = self.seq(node); |
| 1134 | + let mut docs = Vec::new(); |
| 1135 | + for item in items { |
| 1136 | + match item.el.kind() { |
| 1137 | + DOT => docs.push(self.punct(&item, ".")), |
| 1138 | + _ => docs.push(self.item_doc(&item)), |
| 1139 | + } |
| 1140 | + } |
| 1141 | + pretty::cat(docs) |
| 1142 | + } |
| 1143 | + |
| 1144 | + /// `send fn(a, b) -> c / <e>` |
| 1145 | + fn fn_type(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1146 | + let Seq { mut items, .. } = self.seq(node); |
| 1147 | + let mut docs = Vec::new(); |
| 1148 | + let mut ret = None; |
| 1149 | + // The parenthesised list is not its own node: split it out. |
| 1150 | + if let Some(item) = items.pop_front_if(|i| i.el.kind() == IDENT) { |
| 1151 | + docs.push(self.item_doc(&item)); |
| 1152 | + docs.push(self.t(" ")); |
| 1153 | + } |
| 1154 | + if items.pop_front_if(|i| i.el.kind() == FN_KW).is_some() { |
| 1155 | + docs.push(self.t("fn")); |
| 1156 | + } |
| 1157 | + if let Some(item) = items.pop_back_if(|i| i.el.kind() == RET_TYPE) { |
| 1158 | + ret = Some(self.item_doc(&item)); |
| 1159 | + } |
| 1160 | + if items.front().is_some_and(|i| i.el.kind() == L_PAREN) |
| 1161 | + && items.back().is_some_and(|i| i.el.kind() == R_PAREN) |
| 1162 | + { |
| 1163 | + let open_item = items.pop_front().unwrap(); |
| 1164 | + let close_item = items.pop_back().unwrap(); |
| 1165 | + let mut types = Vec::new(); |
| 1166 | + for item in items { |
| 1167 | + if item.el.kind() != COMMA { |
| 1168 | + types.push(ListEntry::Item(self.item_doc(&item))); |
| 1169 | + } |
| 1170 | + } |
| 1171 | + for (c, _) in close_item.leading { |
| 1172 | + types.push(ListEntry::Comment(self.comment(&c))); |
| 1173 | + } |
| 1174 | + let open = self.with_comments(&open_item, self.t("(")); |
| 1175 | + docs.push(self.list_group(open, types, self.t(")"), false)); |
| 1176 | + } else { |
| 1177 | + return self.raw(node); |
| 1178 | + } |
| 1179 | + if let Some(ret) = ret { |
| 1180 | + docs.push(self.t(" ")); |
| 1181 | + docs.push(ret); |
| 1182 | + } |
| 1183 | + pretty::cat(docs) |
| 1184 | + } |
| 1185 | + |
| 1186 | + // ---- expressions --------------------------------------------------------- |
| 1187 | + |
| 1188 | + /// `"text {e} text"`: text verbatim, holes as code. |
| 1189 | + fn interp_string(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1190 | + let Seq { items, .. } = self.seq(node); |
| 1191 | + pretty::cat(items.iter().map(|i| self.item_doc(i))) |
| 1192 | + } |
| 1193 | + |
| 1194 | + /// `{e}` or `{e:?}`. |
| 1195 | + fn interp_hole(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1196 | + let Seq { items, .. } = self.seq(node); |
| 1197 | + let mut docs = vec![self.t("{")]; |
| 1198 | + for item in items { |
| 1199 | + match item.el.kind() { |
| 1200 | + L_BRACE | R_BRACE => docs.push(self.skipped(&item)), |
| 1201 | + COLON => docs.push(self.punct(&item, ":")), |
| 1202 | + _ => docs.push(self.item_doc(&item)), |
| 1203 | + } |
| 1204 | + } |
| 1205 | + docs.push(self.t("}")); |
| 1206 | + pretty::cat(docs) |
| 1207 | + } |
| 1208 | + |
| 1209 | + /// `tag\`text {e} text\``: the tag, then text verbatim, holes as code. |
| 1210 | + fn template_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1211 | + let Seq { items, .. } = self.seq(node); |
| 1212 | + pretty::cat(items.iter().map(|i| self.item_doc(i))) |
| 1213 | + } |
| 1214 | + |
| 1215 | + /// `{ stmts }`: one line when a single statement fits; otherwise one |
| 1216 | + /// statement per line. Blank lines between statements are kept. |
| 1217 | + fn block(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1218 | + self.block_as(node, false) |
| 1219 | + } |
| 1220 | + |
| 1221 | + /// A function body's block: always broken, one statement per line. |
| 1222 | + fn block_always(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1223 | + self.block_as(node, true) |
| 1224 | + } |
| 1225 | + |
| 1226 | + fn block_as(&self, node: &SyntaxNode, always: bool) -> Doc<'a> { |
| 1227 | + let Seq { |
| 1228 | + mut items, |
| 1229 | + end_comments, |
| 1230 | + } = self.seq(node); |
| 1231 | + let Some(close_item) = items.pop_back() else { |
| 1232 | + return self.raw(node); |
| 1233 | + }; |
| 1234 | + let Some(open_item) = items.pop_front() else { |
| 1235 | + return self.raw(node); |
| 1236 | + }; |
| 1237 | + if open_item.el.kind() != L_BRACE || close_item.el.kind() != R_BRACE { |
| 1238 | + return self.raw(node); |
| 1239 | + } |
| 1240 | + let mut end: Vec<SyntaxToken> = close_item.leading.into_iter().map(|(c, _)| c).collect(); |
| 1241 | + end.extend(end_comments); |
| 1242 | + let stmts: Vec<Item> = items.into_iter().collect(); |
| 1243 | + if stmts.is_empty() && end.is_empty() && open_item.trailing.is_none() { |
| 1244 | + return self.t("{}"); |
| 1245 | + } |
| 1246 | + let open = self.with_comments(&open_item, self.t("{")); |
| 1247 | + let body = self.seq_stacked(stmts, &end); |
| 1248 | + let brace_line = if always { Doc::HardLineSoft } else { Doc::Line }; |
| 1249 | + pretty::group(pretty::cat([ |
| 1250 | + open, |
| 1251 | + pretty::nest(1, pretty::cat([brace_line.clone(), body])), |
| 1252 | + brace_line, |
| 1253 | + self.t("}"), |
| 1254 | + ])) |
| 1255 | + } |
| 1256 | + |
| 1257 | + /// `let pat: T = expr`; the value hugs the `=` and breaks internally. |
| 1258 | + fn let_stmt(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1259 | + let Seq { items, .. } = self.seq(node); |
| 1260 | + let mut docs = vec![self.t("let ")]; |
| 1261 | + for item in items { |
| 1262 | + match item.el.kind() { |
| 1263 | + LET_KW => docs.push(self.skipped(&item)), |
| 1264 | + COLON => docs.push(self.punct(&item, ": ")), |
| 1265 | + EQ => docs.push(self.punct(&item, " = ")), |
| 1266 | + _ => docs.push(self.item_doc(&item)), |
| 1267 | + } |
| 1268 | + } |
| 1269 | + pretty::cat(docs) |
| 1270 | + } |
| 1271 | + |
| 1272 | + /// `use a, b <- f(x)`; bindings break with leading commas. |
| 1273 | + fn use_stmt(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1274 | + let Seq { items, .. } = self.seq(node); |
| 1275 | + let mut docs = vec![self.t("use ")]; |
| 1276 | + let mut bindings = Vec::new(); |
| 1277 | + let mut rhs = None; |
| 1278 | + let mut past_arrow = false; |
| 1279 | + for item in items { |
| 1280 | + match item.el.kind() { |
| 1281 | + USE_KW | COMMA => docs.push(self.skipped(&item)), |
| 1282 | + L_ARROW => { |
| 1283 | + docs.push(self.skipped(&item)); |
| 1284 | + past_arrow = true; |
| 1285 | + } |
| 1286 | + _ if past_arrow => rhs = Some(self.item_doc(&item)), |
| 1287 | + _ => bindings.push(self.item_doc(&item)), |
| 1288 | + } |
| 163 | 1289 | } |
| 164 | | − while self.out.ends_with(' ') { |
| 165 | | − self.out.pop(); |
| 1290 | + if !bindings.is_empty() { |
| 1291 | + docs.push(pretty::group(pretty::nest( |
| 1292 | + 1, |
| 1293 | + pretty::join(Doc::LeadComma, bindings), |
| 1294 | + ))); |
| 1295 | + docs.push(self.t(" ")); |
| 166 | 1296 | } |
| 167 | | − let breaks = self.pending_newlines.min(2); |
| 168 | | − self.pending_newlines = 0; |
| 169 | | − if self.out.is_empty() { |
| 170 | | − return; // no leading blank lines |
| 1297 | + docs.push(self.t("<- ")); |
| 1298 | + docs.push(rhs.unwrap_or(Doc::Nil)); |
| 1299 | + pretty::cat(docs) |
| 1300 | + } |
| 1301 | + |
| 1302 | + /// `a + b`; breaks before the operator, one indent in. |
| 1303 | + fn bin_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1304 | + let Seq { items, .. } = self.seq(node); |
| 1305 | + let mut it = items.into_iter(); |
| 1306 | + let (Some(lhs), Some(op), Some(rhs)) = (it.next(), it.next(), it.next()) else { |
| 1307 | + return self.raw(node); |
| 1308 | + }; |
| 1309 | + if !op.el.kind().is_token() { |
| 1310 | + return self.raw(node); |
| 171 | 1311 | } |
| 172 | | − for _ in 0..breaks { |
| 173 | | − self.out.push('\n'); |
| 1312 | + pretty::group(pretty::cat([ |
| 1313 | + self.item_doc(&lhs), |
| 1314 | + pretty::nest( |
| 1315 | + 1, |
| 1316 | + pretty::cat([ |
| 1317 | + Doc::Line, |
| 1318 | + self.item_doc(&op), |
| 1319 | + self.t(" "), |
| 1320 | + self.item_doc(&rhs), |
| 1321 | + ]), |
| 1322 | + ), |
| 1323 | + ])) |
| 1324 | + } |
| 1325 | + |
| 1326 | + /// `!x`, `-x`. |
| 1327 | + fn prefix_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1328 | + let Seq { items, .. } = self.seq(node); |
| 1329 | + pretty::cat(items.iter().map(|i| self.item_doc(i))) |
| 1330 | + } |
| 1331 | + |
| 1332 | + /// `f(a, label: b)`; the argument list hugs the callee. |
| 1333 | + fn call_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1334 | + let Seq { items, .. } = self.seq(node); |
| 1335 | + pretty::cat(items.iter().map(|i| self.item_doc(i))) |
| 1336 | + } |
| 1337 | + |
| 1338 | + /// `label: expr` or `expr` in a call. |
| 1339 | + fn arg(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1340 | + let Seq { items, .. } = self.seq(node); |
| 1341 | + pretty::cat(items.iter().map(|i| self.item_doc(i))) |
| 1342 | + } |
| 1343 | + |
| 1344 | + /// `name: ` before an argument or a pattern. |
| 1345 | + fn label(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1346 | + let Seq { items, .. } = self.seq(node); |
| 1347 | + let mut docs = Vec::new(); |
| 1348 | + for item in items { |
| 1349 | + match item.el.kind() { |
| 1350 | + COLON => docs.push(self.punct(&item, ": ")), |
| 1351 | + _ => docs.push(self.item_doc(&item)), |
| 1352 | + } |
| 174 | 1353 | } |
| 175 | | − let indent = self.indent_for(first); |
| 176 | | − self.line_indent = indent; |
| 177 | | − self.out.push_str(&INDENT.repeat(indent)); |
| 1354 | + pretty::cat(docs) |
| 178 | 1355 | } |
| 179 | 1356 | |
| 180 | | − fn track(&mut self, kind: SyntaxKind) { |
| 181 | | − match kind { |
| 182 | | − L_BRACE | L_PAREN | L_BRACK => self.stack.push(self.line_indent + 1), |
| 183 | | − R_BRACE | R_PAREN | R_BRACK => { |
| 184 | | − self.stack.pop(); |
| 1357 | + /// `a.b`, `t.0`. `1 .5` keeps its space: `1.5` would lex as a float. |
| 1358 | + fn field_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1359 | + let Seq { items, .. } = self.seq(node); |
| 1360 | + let ends_in_digit = |item: &Item| { |
| 1361 | + // Only a numeric literal can fuse with `.0` into a float. |
| 1362 | + matches!(&item.el, NodeOrToken::Node(n) if n.kind() == LITERAL) && { |
| 1363 | + let range = item.el.text_range(); |
| 1364 | + self.src[usize::from(range.start())..usize::from(range.end())] |
| 1365 | + .ends_with(|c: char| c.is_ascii_digit()) |
| 185 | 1366 | } |
| 186 | | − HTML_LT => self.in_open_tag = true, |
| 187 | | − HTML_LT_SLASH => { |
| 188 | | − self.in_close_tag = true; |
| 189 | | − self.stack.pop(); |
| 1367 | + }; |
| 1368 | + let mut docs = Vec::new(); |
| 1369 | + for (i, item) in items.iter().enumerate() { |
| 1370 | + match item.el.kind() { |
| 1371 | + DOT => { |
| 1372 | + let int_index_on_int = items |
| 1373 | + .get(i + 1) |
| 1374 | + .is_some_and(|m| matches!(&m.el, NodeOrToken::Token(t) if t.kind() == INT)) |
| 1375 | + && i > 0 |
| 1376 | + && ends_in_digit(&items[i - 1]); |
| 1377 | + docs.push(self.punct(item, if int_index_on_int { " ." } else { "." })); |
| 1378 | + } |
| 1379 | + _ => docs.push(self.item_doc(item)), |
| 190 | 1380 | } |
| 191 | | − HTML_SLASH_GT => self.in_open_tag = false, |
| 192 | | − HTML_GT if self.in_open_tag => { |
| 193 | | − self.in_open_tag = false; |
| 194 | | − self.stack.push(self.line_indent + 1); |
| 1381 | + } |
| 1382 | + pretty::cat(docs) |
| 1383 | + } |
| 1384 | + |
| 1385 | + /// `if c { a } else { b }`: one line when it fits; when it does not, |
| 1386 | + /// both branches break together (a branch of one statement inlines its |
| 1387 | + /// lines into this group; a longer branch breaks everything anyway). |
| 1388 | + fn if_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1389 | + let Seq { items, .. } = self.seq(node); |
| 1390 | + let mut docs = Vec::new(); |
| 1391 | + for item in items { |
| 1392 | + match item.el.kind() { |
| 1393 | + IF_KW => docs.push(self.punct(&item, "if ")), |
| 1394 | + ELSE_BRANCH => { |
| 1395 | + docs.push(self.t(" ")); |
| 1396 | + docs.push(self.item_doc(&item)); |
| 1397 | + } |
| 1398 | + BLOCK => { |
| 1399 | + docs.push(self.t(" ")); |
| 1400 | + match &item.el { |
| 1401 | + NodeOrToken::Node(n) => docs.push(self.inline_block(n)), |
| 1402 | + NodeOrToken::Token(_) => docs.push(self.el_doc(&item.el)), |
| 1403 | + } |
| 1404 | + } |
| 1405 | + _ => docs.push(self.item_doc(&item)), |
| 1406 | + } |
| 1407 | + } |
| 1408 | + pretty::group(pretty::cat(docs)) |
| 1409 | + } |
| 1410 | + |
| 1411 | + /// A branch block whose lines belong to the enclosing group, so `if` |
| 1412 | + /// branches break together: possible when the block holds exactly one |
| 1413 | + /// statement and no comments. Anything else keeps its own group. |
| 1414 | + fn inline_block(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1415 | + let Seq { |
| 1416 | + mut items, |
| 1417 | + end_comments, |
| 1418 | + } = self.seq(node); |
| 1419 | + let (Some(close_item), Some(open_item)) = (items.pop_back(), items.pop_front()) else { |
| 1420 | + return self.block(node); |
| 1421 | + }; |
| 1422 | + if open_item.el.kind() != L_BRACE || close_item.el.kind() != R_BRACE { |
| 1423 | + return self.block(node); |
| 1424 | + } |
| 1425 | + let inlineable = items.len() == 1 |
| 1426 | + && end_comments.is_empty() |
| 1427 | + && close_item.leading.is_empty() |
| 1428 | + && open_item.trailing.is_none(); |
| 1429 | + if !inlineable { |
| 1430 | + return self.block(node); |
| 1431 | + } |
| 1432 | + let stmt = items.pop_front().unwrap(); |
| 1433 | + pretty::cat([ |
| 1434 | + self.t("{"), |
| 1435 | + pretty::nest(1, pretty::cat([Doc::Line, self.item_doc(&stmt)])), |
| 1436 | + Doc::Line, |
| 1437 | + self.t("}"), |
| 1438 | + ]) |
| 1439 | + } |
| 1440 | + |
| 1441 | + /// `else if ...` / `else { ... }`. |
| 1442 | + fn else_branch(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1443 | + let Seq { items, .. } = self.seq(node); |
| 1444 | + let mut docs = Vec::new(); |
| 1445 | + for item in items { |
| 1446 | + match item.el.kind() { |
| 1447 | + ELSE_KW => docs.push(self.punct(&item, "else ")), |
| 1448 | + BLOCK => match &item.el { |
| 1449 | + NodeOrToken::Node(n) => docs.push(self.inline_block(n)), |
| 1450 | + NodeOrToken::Token(_) => docs.push(self.item_doc(&item)), |
| 1451 | + }, |
| 1452 | + _ => docs.push(self.item_doc(&item)), |
| 195 | 1453 | } |
| 196 | | − HTML_GT => self.in_close_tag = false, |
| 1454 | + } |
| 1455 | + pretty::cat(docs) |
| 1456 | + } |
| 1457 | + |
| 1458 | + /// `match e { arms }`; arms one per line, always. |
| 1459 | + fn match_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1460 | + let Seq { items, .. } = self.seq(node); |
| 1461 | + let mut docs = vec![self.t("match ")]; |
| 1462 | + let mut arms: Vec<Item> = Vec::new(); |
| 1463 | + let mut open = None; |
| 1464 | + let mut close = None; |
| 1465 | + for item in items { |
| 1466 | + match item.el.kind() { |
| 1467 | + MATCH_KW => {} |
| 1468 | + L_BRACE => open = Some(item), |
| 1469 | + R_BRACE => close = Some(item), |
| 1470 | + MATCH_ARM => arms.push(item), |
| 1471 | + _ => docs.push(self.item_doc(&item)), |
| 1472 | + } |
| 1473 | + } |
| 1474 | + let (Some(open), Some(close)) = (open, close) else { |
| 1475 | + return pretty::cat(docs); |
| 1476 | + }; |
| 1477 | + docs.push(self.arms_block(open, arms, close)); |
| 1478 | + pretty::cat(docs) |
| 1479 | + } |
| 1480 | + |
| 1481 | + /// ` { arms }` with the arms one per line; ` {}` when empty. |
| 1482 | + fn arms_block(&self, open: Item, arms: Vec<Item>, close: Item) -> Doc<'a> { |
| 1483 | + let end: Vec<SyntaxToken> = close.leading.into_iter().map(|(c, _)| c).collect(); |
| 1484 | + let open_doc = self.with_comments(&open, self.t(" {")); |
| 1485 | + if arms.is_empty() && end.is_empty() && open.trailing.is_none() { |
| 1486 | + return self.t(" {}"); |
| 1487 | + } |
| 1488 | + let body = self.seq_stacked(arms, &end); |
| 1489 | + pretty::cat([ |
| 1490 | + open_doc, |
| 1491 | + pretty::nest(1, pretty::cat([Doc::HardLineSoft, body])), |
| 1492 | + Doc::HardLineSoft, |
| 1493 | + self.t("}"), |
| 1494 | + ]) |
| 1495 | + } |
| 1496 | + |
| 1497 | + /// `pat | pat if guard -> body,`. A body that opens its own structure |
| 1498 | + /// (a match, a block, a list, ...) hugs the `->`; anything else moves |
| 1499 | + /// under it, one indent in, when the arm does not fit. |
| 1500 | + fn match_arm(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1501 | + let Seq { items, .. } = self.seq(node); |
| 1502 | + let mut head = Vec::new(); |
| 1503 | + let mut arrow = None; |
| 1504 | + let mut body = None; |
| 1505 | + let mut comma = None; |
| 1506 | + let mut past_arrow = false; |
| 1507 | + for item in items { |
| 1508 | + match item.el.kind() { |
| 1509 | + ARROW => { |
| 1510 | + past_arrow = true; |
| 1511 | + arrow = Some(item); |
| 1512 | + } |
| 1513 | + COMMA if past_arrow => comma = Some(item), |
| 1514 | + MATCH_GUARD => { |
| 1515 | + head.push(self.t(" ")); |
| 1516 | + head.push(self.item_doc(&item)); |
| 1517 | + } |
| 1518 | + _ if past_arrow => body = Some(item), |
| 1519 | + _ => head.push(self.item_doc(&item)), |
| 1520 | + } |
| 1521 | + } |
| 1522 | + pretty::group(self.arm_doc(head, arrow, body, comma)) |
| 1523 | + } |
| 1524 | + |
| 1525 | + /// Head, ` -> ` and body of an arm or handler clause. |
| 1526 | + fn arm_doc( |
| 1527 | + &self, |
| 1528 | + mut head: Vec<Doc<'a>>, |
| 1529 | + arrow: Option<Item>, |
| 1530 | + body: Option<Item>, |
| 1531 | + comma: Option<Item>, |
| 1532 | + ) -> Doc<'a> { |
| 1533 | + let mut docs = Vec::new(); |
| 1534 | + let mut arrow_trailing = None; |
| 1535 | + if let Some(arrow) = arrow { |
| 1536 | + for (c, _) in &arrow.leading { |
| 1537 | + head.push(self.comment(c)); |
| 1538 | + head.push(Doc::HardLine); |
| 1539 | + } |
| 1540 | + arrow_trailing = arrow.trailing; |
| 1541 | + } |
| 1542 | + docs.append(&mut head); |
| 1543 | + docs.push(self.t(" ->")); |
| 1544 | + match (arrow_trailing, body) { |
| 1545 | + // `-> // c` ends the line; the body starts the next one. |
| 1546 | + (Some(c), Some(body)) => { |
| 1547 | + docs.push(self.t(" ")); |
| 1548 | + docs.push(self.comment(&c)); |
| 1549 | + docs.push(Doc::HardLine); |
| 1550 | + docs.push(self.item_doc(&body)); |
| 1551 | + } |
| 1552 | + (None, Some(body)) => docs.push(self.arm_body(&body)), |
| 197 | 1553 | _ => {} |
| 198 | 1554 | } |
| 1555 | + if let Some(comma) = comma { |
| 1556 | + docs.push(self.punct(&comma, ",")); |
| 1557 | + } |
| 1558 | + pretty::cat(docs) |
| 199 | 1559 | } |
| 200 | 1560 | |
| 201 | | − /// Re-indent the lines of an HTML text run; keep its words. |
| 202 | | − fn html_text(&mut self, text: &str) { |
| 203 | | − let mut lines = text.split('\n'); |
| 204 | | − let first = lines.next().unwrap_or(""); |
| 1561 | + /// The body of an arm: hugged after `-> ` when it opens its own |
| 1562 | + /// structure, else on the next line one indent in when it does not |
| 1563 | + /// fit. The ` ->` itself is printed by [`Printer::arm_doc`]. |
| 1564 | + fn arm_body(&self, body: &Item) -> Doc<'a> { |
| 1565 | + let doc = self.item_doc(body); |
| 1566 | + let hug = matches!( |
| 1567 | + body.el.kind(), |
| 1568 | + MATCH_EXPR |
| 1569 | + | IF_EXPR |
| 1570 | + | BLOCK |
| 1571 | + | LAMBDA_EXPR |
| 1572 | + | HANDLE_EXPR |
| 1573 | + | LIST_EXPR |
| 1574 | + | TUPLE_EXPR |
| 1575 | + | PAREN_EXPR |
| 1576 | + | LITERAL |
| 1577 | + | INTERP_STRING |
| 1578 | + | TEMPLATE_EXPR |
| 1579 | + | PATH_EXPR |
| 1580 | + | HTML_ELEMENT |
| 1581 | + | REGION_EXPR |
| 1582 | + ); |
| 1583 | + if hug { |
| 1584 | + pretty::cat([self.t(" "), doc]) |
| 1585 | + } else { |
| 1586 | + pretty::group(pretty::nest(1, pretty::cat([Doc::Line, doc]))) |
| 1587 | + } |
| 1588 | + } |
| 1589 | + |
| 1590 | + /// `fn(params) -> T { body }` |
| 1591 | + fn lambda(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1592 | + let Seq { items, .. } = self.seq(node); |
| 1593 | + let mut docs = Vec::new(); |
| 1594 | + for item in items { |
| 1595 | + match item.el.kind() { |
| 1596 | + FN_KW => docs.push(self.punct(&item, "fn")), |
| 1597 | + BLOCK => { |
| 1598 | + docs.push(self.t(" ")); |
| 1599 | + docs.push(self.item_doc(&item)); |
| 1600 | + } |
| 1601 | + _ => docs.push(self.item_doc(&item)), |
| 1602 | + } |
| 1603 | + } |
| 1604 | + pretty::cat(docs) |
| 1605 | + } |
| 1606 | + |
| 1607 | + /// `handle { body } with { clauses }`; clauses one per line. |
| 1608 | + fn handle_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1609 | + let Seq { items, .. } = self.seq(node); |
| 1610 | + let mut docs = vec![self.t("handle ")]; |
| 1611 | + let mut clauses: Vec<Item> = Vec::new(); |
| 1612 | + let mut open = None; |
| 1613 | + let mut close = None; |
| 1614 | + for item in items { |
| 1615 | + match item.el.kind() { |
| 1616 | + HANDLE_KW => docs.push(self.skipped(&item)), |
| 1617 | + WITH_KW => docs.push(self.punct(&item, " with")), |
| 1618 | + BLOCK => docs.push(self.item_doc(&item)), |
| 1619 | + L_BRACE => open = Some(item), |
| 1620 | + R_BRACE => close = Some(item), |
| 1621 | + HANDLER_CLAUSE => clauses.push(item), |
| 1622 | + _ => docs.push(self.item_doc(&item)), |
| 1623 | + } |
| 1624 | + } |
| 1625 | + if let (Some(open), Some(close)) = (open, close) { |
| 1626 | + docs.push(self.arms_block(open, clauses, close)); |
| 1627 | + } |
| 1628 | + pretty::cat(docs) |
| 1629 | + } |
| 1630 | + |
| 1631 | + /// `op(x) -> body,` in a handler; the body follows the arm rule. |
| 1632 | + fn handler_clause(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1633 | + let Seq { items, .. } = self.seq(node); |
| 1634 | + let mut head = Vec::new(); |
| 1635 | + let mut arrow = None; |
| 1636 | + let mut body = None; |
| 1637 | + let mut comma = None; |
| 1638 | + let mut past_arrow = false; |
| 1639 | + for item in items { |
| 1640 | + match item.el.kind() { |
| 1641 | + ARROW => { |
| 1642 | + past_arrow = true; |
| 1643 | + arrow = Some(item); |
| 1644 | + } |
| 1645 | + COMMA if past_arrow => comma = Some(item), |
| 1646 | + _ if past_arrow => body = Some(item), |
| 1647 | + _ => head.push(self.item_doc(&item)), |
| 1648 | + } |
| 1649 | + } |
| 1650 | + pretty::group(self.arm_doc(head, arrow, body, comma)) |
| 1651 | + } |
| 1652 | + |
| 1653 | + /// `return e` or `return`. |
| 1654 | + fn return_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1655 | + let Seq { items, .. } = self.seq(node); |
| 1656 | + let mut docs = Vec::new(); |
| 1657 | + for item in items { |
| 1658 | + match item.el.kind() { |
| 1659 | + RETURN_KW => docs.push(self.punct(&item, "return")), |
| 1660 | + _ => { |
| 1661 | + docs.push(self.t(" ")); |
| 1662 | + docs.push(self.item_doc(&item)); |
| 1663 | + } |
| 1664 | + } |
| 1665 | + } |
| 1666 | + pretty::cat(docs) |
| 1667 | + } |
| 1668 | + |
| 1669 | + /// `..expr` / `..name` / `..` |
| 1670 | + fn prefixed(&self, node: &SyntaxNode, prefix: &'static str) -> Doc<'a> { |
| 1671 | + let Seq { items, .. } = self.seq(node); |
| 1672 | + let mut docs = vec![self.t(prefix)]; |
| 1673 | + for item in items { |
| 1674 | + match item.el.kind() { |
| 1675 | + DOT2 | DEFER_KW | REGION_KW | IF_KW => docs.push(self.skipped(&item)), |
| 1676 | + _ => docs.push(self.item_doc(&item)), |
| 1677 | + } |
| 1678 | + } |
| 1679 | + pretty::cat(docs) |
| 1680 | + } |
| 1681 | + |
| 1682 | + // ---- patterns ------------------------------------------------------------ |
| 1683 | + |
| 1684 | + /// `Name`, `mod.Name`, `Name(a, label: b, ..)` |
| 1685 | + fn ctor_pat(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1686 | + let Seq { items, .. } = self.seq(node); |
| 1687 | + let mut docs = Vec::new(); |
| 1688 | + for item in items { |
| 1689 | + match item.el.kind() { |
| 1690 | + DOT => docs.push(self.punct(&item, ".")), |
| 1691 | + _ => docs.push(self.item_doc(&item)), |
| 1692 | + } |
| 1693 | + } |
| 1694 | + pretty::cat(docs) |
| 1695 | + } |
| 1696 | + |
| 1697 | + /// `p1 | p2`; breaks before the `|`. |
| 1698 | + fn alt_pat(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1699 | + let Seq { items, .. } = self.seq(node); |
| 1700 | + let mut docs: Vec<Doc> = Vec::new(); |
| 1701 | + for item in items { |
| 1702 | + match item.el.kind() { |
| 1703 | + PIPE => {} |
| 1704 | + _ => docs.push(self.item_doc(&item)), |
| 1705 | + } |
| 1706 | + } |
| 1707 | + let mut out = vec![]; |
| 1708 | + for (i, d) in docs.into_iter().enumerate() { |
| 1709 | + if i > 0 { |
| 1710 | + out.push(Doc::Line); |
| 1711 | + out.push(self.t("| ")); |
| 1712 | + } |
| 1713 | + out.push(d); |
| 1714 | + } |
| 1715 | + pretty::group(pretty::nest(1, pretty::cat(out))) |
| 1716 | + } |
| 1717 | + |
| 1718 | + /// `pat as name`. |
| 1719 | + fn as_pat(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1720 | + let Seq { items, .. } = self.seq(node); |
| 1721 | + let mut docs = Vec::new(); |
| 1722 | + for item in items { |
| 1723 | + match item.el.kind() { |
| 1724 | + AS_KW => docs.push(self.punct(&item, " as ")), |
| 1725 | + _ => docs.push(self.item_doc(&item)), |
| 1726 | + } |
| 1727 | + } |
| 1728 | + pretty::cat(docs) |
| 1729 | + } |
| 1730 | + |
| 1731 | + // ---- HTML ------------------------------------------------------------------ |
| 1732 | + |
| 1733 | + /// An HTML literal: tags and holes formatted, text re-indented |
| 1734 | + /// keeping its words (JSX whitespace rules ignore the change), nested |
| 1735 | + /// elements one indent deeper. Attribute strings and interpolation |
| 1736 | + /// holes are never rewrapped. |
| 1737 | + fn html_element(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1738 | + let Seq { items, .. } = self.seq(node); |
| 1739 | + let mut it = items.into_iter(); |
| 1740 | + let Some(open) = it.next() else { |
| 1741 | + return self.raw(node); |
| 1742 | + }; |
| 1743 | + if open.el.kind() != HTML_OPEN_TAG { |
| 1744 | + return self.raw(node); |
| 1745 | + } |
| 1746 | + let self_closing = matches!(&open.el, NodeOrToken::Node(n) if n.children_with_tokens().last().and_then(|e| e.into_token()).is_some_and(|t| t.kind() == HTML_SLASH_GT)); |
| 1747 | + let mut docs = vec![self.item_doc(&open)]; |
| 1748 | + if self_closing { |
| 1749 | + return pretty::cat(docs); |
| 1750 | + } |
| 1751 | + let mut children = Vec::new(); |
| 1752 | + let mut close = None; |
| 1753 | + for item in it { |
| 1754 | + if item.el.kind() == HTML_CLOSE_TAG { |
| 1755 | + close = Some(item); |
| 1756 | + break; |
| 1757 | + } |
| 1758 | + children.push(item); |
| 1759 | + } |
| 1760 | + let mut child_docs: Vec<Doc<'a>> = Vec::new(); |
| 1761 | + for item in &children { |
| 1762 | + match &item.el { |
| 1763 | + NodeOrToken::Token(t) if t.kind() == HTML_TEXT => { |
| 1764 | + child_docs.extend(self.html_text(t)); |
| 1765 | + } |
| 1766 | + _ => child_docs.push(self.item_doc(item)), |
| 1767 | + } |
| 1768 | + } |
| 1769 | + // The line break before the closing tag dedents out of the |
| 1770 | + // children's nest. |
| 1771 | + let mut trailing = 0; |
| 1772 | + while matches!(child_docs.last(), Some(Doc::HardLine)) { |
| 1773 | + child_docs.pop(); |
| 1774 | + trailing += 1; |
| 1775 | + } |
| 1776 | + docs.push(pretty::nest(1, pretty::cat(child_docs))); |
| 1777 | + for _ in 0..trailing { |
| 1778 | + docs.push(Doc::HardLine); |
| 1779 | + } |
| 1780 | + if let Some(c) = close { |
| 1781 | + docs.push(self.item_doc(&c)); |
| 1782 | + } |
| 1783 | + pretty::cat(docs) |
| 1784 | + } |
| 1785 | + |
| 1786 | + /// Text between tags: single-line text is verbatim (a space can |
| 1787 | + /// matter); multi-line text keeps its words, one line per source line, |
| 1788 | + /// re-indented, blank lines capped at one. |
| 1789 | + fn html_text(&self, tok: &SyntaxToken) -> Vec<Doc<'a>> { |
| 1790 | + let text = tok.text(); |
| 1791 | + if !text.contains('\n') { |
| 1792 | + return vec![self.s(text)]; |
| 1793 | + } |
| 1794 | + let mut docs = Vec::new(); |
| 1795 | + // Newlines after the last word end the text run's line (one blank |
| 1796 | + // line kept at most). |
| 1797 | + let trailing = text[text.trim_end().len()..].matches('\n').count(); |
| 1798 | + let content = text.trim_end(); |
| 1799 | + let mut parts = content.split('\n'); |
| 1800 | + let first = parts.next().unwrap_or(""); |
| 205 | 1801 | if !first.trim().is_empty() { |
| 206 | | − self.flush_line(HTML_TEXT); |
| 207 | | − self.out.push_str(first); |
| 208 | | − } else if self.pending_newlines == 0 { |
| 209 | | − self.out.push_str(first); |
| 1802 | + docs.push(self.s(first)); |
| 210 | 1803 | } |
| 211 | | − for line in lines { |
| 212 | | − self.pending_newlines += 1; |
| 213 | | − let words = line.trim_start(); |
| 214 | | − if !words.trim().is_empty() { |
| 215 | | − self.flush_line(HTML_TEXT); |
| 216 | | − self.out.push_str(words); |
| 1804 | + let mut newlines = 1; |
| 1805 | + for part in parts { |
| 1806 | + let words = part.trim_start(); |
| 1807 | + if words.trim().is_empty() { |
| 1808 | + newlines += 1; |
| 1809 | + continue; |
| 1810 | + } |
| 1811 | + for _ in 0..newlines.min(2) { |
| 1812 | + docs.push(Doc::HardLine); |
| 1813 | + } |
| 1814 | + docs.push(self.s(words)); |
| 1815 | + newlines = 1; |
| 1816 | + } |
| 1817 | + for _ in 0..trailing.min(2) { |
| 1818 | + docs.push(Doc::HardLine); |
| 1819 | + } |
| 1820 | + docs |
| 1821 | + } |
| 1822 | + |
| 1823 | + /// `<tag attr="v" attr={e}>`: one space between attributes. |
| 1824 | + fn html_open_tag(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1825 | + let Seq { items, .. } = self.seq(node); |
| 1826 | + let mut docs = Vec::new(); |
| 1827 | + for item in items { |
| 1828 | + match item.el.kind() { |
| 1829 | + HTML_ATTR => { |
| 1830 | + docs.push(self.t(" ")); |
| 1831 | + docs.push(self.item_doc(&item)); |
| 1832 | + } |
| 1833 | + _ => docs.push(self.item_doc(&item)), |
| 217 | 1834 | } |
| 218 | 1835 | } |
| 219 | | − self.last = Some(HTML_TEXT); |
| 1836 | + pretty::cat(docs) |
| 1837 | + } |
| 1838 | + |
| 1839 | + /// `name`, `name="value"`, `name={expr}`. |
| 1840 | + fn html_attr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1841 | + let Seq { items, .. } = self.seq(node); |
| 1842 | + pretty::cat(items.iter().map(|i| self.item_doc(i)).collect::<Vec<_>>()) |
| 1843 | + } |
| 1844 | + |
| 1845 | + /// `{expr}` inside a tag or between tags. |
| 1846 | + fn html_expr(&self, node: &SyntaxNode) -> Doc<'a> { |
| 1847 | + let Seq { items, .. } = self.seq(node); |
| 1848 | + pretty::cat(items.iter().map(|i| self.item_doc(i)).collect::<Vec<_>>()) |
| 220 | 1849 | } |
| 221 | 1850 | } |
| 222 | 1851 | |
| @@ -224,40 +1853,166 @@ impl Formatter { |
| 224 | 1853 | mod tests { |
| 225 | 1854 | use super::*; |
| 226 | 1855 | |
| 1856 | + fn fmt(src: &str) -> String { |
| 1857 | + format(src).unwrap() |
| 1858 | + } |
| 1859 | + |
| 1860 | + /// Render at a narrow width (40) to exercise breaking. |
| 1861 | + fn narrow(src: &str) -> String { |
| 1862 | + format_with_width(src, 40).unwrap() |
| 1863 | + } |
| 1864 | + |
| 1865 | + #[test] |
| 1866 | + fn short_code_is_untouched() { |
| 1867 | + let src = "fn f(x) {\n let y = x\n y\n}\n"; |
| 1868 | + assert_eq!(fmt(src), src); |
| 1869 | + assert_eq!(fmt("type T { A }\n"), "type T { A }\n"); |
| 1870 | + // Variants go one per line; intra-line spacing is canonical. |
| 1871 | + assert_eq!(fmt("type T { A B }\n"), "type T {\n A\n B\n}\n"); |
| 1872 | + assert_eq!(fmt("fn f() {\n f(1,2)\n}\n"), "fn f() {\n f(1, 2)\n}\n"); |
| 1873 | + // An empty block is `{}`. |
| 1874 | + assert_eq!(fmt("fn a() {\n}\n"), "fn a() {}\n"); |
| 1875 | + // A function body always breaks, even for one short statement. |
| 1876 | + assert_eq!(fmt("fn f() { f(a, b) }\n"), "fn f() {\n f(a, b)\n}\n"); |
| 1877 | + } |
| 1878 | + |
| 1879 | + #[test] |
| 1880 | + fn refuses_broken_input() { |
| 1881 | + assert_eq!(format("fn f( {"), Err(FormatError::SyntaxErrors)); |
| 1882 | + } |
| 1883 | + |
| 1884 | + #[test] |
| 1885 | + fn broken_lists_have_leading_commas() { |
| 1886 | + let src = "fn f() {\n let xs = [aaaaaaaaaaaaaaa, bbbbbbbbbbbbbbb, ccccccccccccccc, ddddddddddddddd, eeeeeeeeeeeeeee]\n}\n"; |
| 1887 | + assert_eq!( |
| 1888 | + fmt(src), |
| 1889 | + "fn f() {\n let xs = [\n aaaaaaaaaaaaaaa\n , bbbbbbbbbbbbbbb\n , ccccccccccccccc\n , ddddddddddddddd\n , eeeeeeeeeeeeeee\n ]\n}\n" |
| 1890 | + ); |
| 1891 | + // A list that fits once its surroundings broke rejoins. |
| 1892 | + assert_eq!( |
| 1893 | + narrow("fn f() {\n g(\n a\n , [x, y]\n )\n}\n"), |
| 1894 | + narrow("fn f() {\n g(a, [x, y])\n}\n") |
| 1895 | + ); |
| 1896 | + } |
| 1897 | + |
| 1898 | + #[test] |
| 1899 | + fn calls_break_all_arguments() { |
| 1900 | + assert_eq!( |
| 1901 | + narrow("fn f() {\n request(\"GET\", \"/\", an_argument, another)\n}\n"), |
| 1902 | + "fn f() {\n request(\n \"GET\"\n , \"/\"\n , an_argument\n , another\n )\n}\n" |
| 1903 | + ); |
| 1904 | + } |
| 1905 | + |
| 1906 | + #[test] |
| 1907 | + fn a_one_element_tuple_keeps_its_comma() { |
| 1908 | + assert_eq!( |
| 1909 | + fmt("fn f() {\n let t = (1,)\n t\n}\n"), |
| 1910 | + "fn f() {\n let t = (1,)\n t\n}\n" |
| 1911 | + ); |
| 1912 | + assert_eq!( |
| 1913 | + narrow("fn f() {\n let t = (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,)\n t\n}\n"), |
| 1914 | + "fn f() {\n let t = (\n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n )\n t\n}\n" |
| 1915 | + ); |
| 1916 | + } |
| 1917 | + |
| 1918 | + #[test] |
| 1919 | + fn pipes_and_operators_break_before_the_operator() { |
| 1920 | + assert_eq!( |
| 1921 | + narrow( |
| 1922 | + "fn f() {\n xs |> list.map(double_the_number) |> list.sum |> list.fold(0, add)\n}\n" |
| 1923 | + ), |
| 1924 | + "fn f() {\n xs |> list.map(double_the_number)\n |> list.sum\n |> list.fold(0, add)\n}\n" |
| 1925 | + ); |
| 1926 | + assert_eq!( |
| 1927 | + narrow("fn f() {\n let b = aaaaaaaa && bbbbbbbb && cccccccc\n}\n"), |
| 1928 | + "fn f() {\n let b = aaaaaaaa && bbbbbbbb\n && cccccccc\n}\n" |
| 1929 | + ); |
| 1930 | + } |
| 1931 | + |
| 227 | 1932 | #[test] |
| 228 | | − fn reindents_and_normalizes_whitespace() { |
| 229 | | − let messy = "fn f(x) {\nlet y = x \n\n\n match y {\n0 -> 1,\n_ ->\n2,\n}\n}\n\n\n"; |
| 230 | | − assert_eq!(format("type T { A B }\n").unwrap(), "type T { A B }\n"); |
| 231 | | − let want = |
| 232 | | − "fn f(x) {\n let y = x\n\n match y {\n 0 -> 1,\n _ ->\n 2,\n }\n}\n"; |
| 233 | | − assert_eq!(format(messy).unwrap(), want); |
| 1933 | + fn match_arms_are_one_per_line_with_trailing_commas() { |
| 1934 | + let src = "fn f(x) {\n match x {\n Some(a) -> a,\n None -> 0,\n }\n}\n"; |
| 1935 | + assert_eq!(fmt(src), src); |
| 1936 | + // An arm body broken after `->` rejoins when it fits. |
| 1937 | + assert_eq!( |
| 1938 | + fmt("fn f(x) {\n match x {\n Some(a) ->\n a,\n }\n}\n"), |
| 1939 | + "fn f(x) {\n match x {\n Some(a) -> a,\n }\n}\n" |
| 1940 | + ); |
| 234 | 1941 | } |
| 235 | 1942 | |
| 236 | 1943 | #[test] |
| 237 | | − fn continuation_lines_and_html() { |
| 238 | | − let src = "fn f(xs) {\nxs\n|> g\n<div>\n<p>hi\nthere</p>\n</div>\n}\n"; |
| 239 | | − let want = "fn f(xs) {\n xs\n |> g\n <div>\n <p>hi\n there</p>\n </div>\n}\n"; |
| 240 | | − assert_eq!(format(src).unwrap(), want); |
| 1944 | + fn if_stays_on_one_line_when_it_fits() { |
| 1945 | + let src = "fn f(m) {\n if m { Ok(()) } else { Error(Wrong) }\n}\n"; |
| 1946 | + assert_eq!(fmt(src), src); |
| 1947 | + // When it does not fit, both branches break together. |
| 1948 | + assert_eq!( |
| 1949 | + narrow("fn f(m) {\n if m { Ok(()) } else { Error(WrongPassword) }\n}\n"), |
| 1950 | + "fn f(m) {\n if m {\n Ok(())\n } else {\n Error(WrongPassword)\n }\n}\n" |
| 1951 | + ); |
| 241 | 1952 | } |
| 242 | 1953 | |
| 243 | 1954 | #[test] |
| 244 | | − fn brackets_opened_on_one_line_indent_once() { |
| 245 | | − let src = "fn f() {\n spawn(fn() {\n work()\n })\n g(\n 1,\n )\n}\n"; |
| 246 | | − assert_eq!(format(src).unwrap(), src); |
| 1955 | + fn signatures_break_at_params_then_row() { |
| 1956 | + assert_eq!( |
| 1957 | + narrow("fn check(a: String, b: String) -> Result<(), E> / <users> {\n a\n}\n"), |
| 1958 | + "fn check(\n a: String\n, b: String\n) -> Result<(), E> / <users> {\n a\n}\n" |
| 1959 | + ); |
| 247 | 1960 | } |
| 248 | 1961 | |
| 249 | 1962 | #[test] |
| 250 | | − fn idempotent_and_refuses_broken_input() { |
| 1963 | + fn comments_keep_their_place_and_force_breaks() { |
| 1964 | + let src = "fn f() {\n // leading\n let x = 1 // trailing\n}\n"; |
| 1965 | + assert_eq!(fmt(src), src); |
| 1966 | + // A comment after a call does not break it. |
| 1967 | + assert_eq!( |
| 1968 | + fmt("fn f() {\n f([a, b]) // why\n}\n"), |
| 1969 | + "fn f() {\n f([a, b]) // why\n}\n" |
| 1970 | + ); |
| 1971 | + // A comment inside a list breaks it, and everything around it. |
| 1972 | + assert_eq!( |
| 1973 | + fmt("fn f() {\n f([a, // why\n b])\n}\n"), |
| 1974 | + "fn f() {\n f(\n [\n a // why\n , b\n ]\n )\n}\n" |
| 1975 | + ); |
| 1976 | + } |
| 1977 | + |
| 1978 | + #[test] |
| 1979 | + fn blank_lines_are_kept_up_to_one() { |
| 1980 | + let src = "fn a() {}\n\n\n\nfn b() {}\n"; |
| 1981 | + assert_eq!(fmt(src), "fn a() {}\n\nfn b() {}\n"); |
| 1982 | + } |
| 1983 | + |
| 1984 | + #[test] |
| 1985 | + fn strings_templates_and_html_are_verbatim() { |
| 251 | 1986 | let src = "fn f() {\n \"multi\n line string\"\n}\n"; |
| 252 | | − assert_eq!(format(src).unwrap(), src); |
| 253 | | − assert_eq!(format("fn f( {"), Err(FormatError::SyntaxErrors)); |
| 1987 | + assert_eq!(fmt(src), src); |
| 1988 | + let tpl = "fn f() {\n let page = pug`\n .card\n p Hello, {name}!\n `\n}\n"; |
| 1989 | + assert_eq!(fmt(tpl), tpl); |
| 1990 | + let html = "fn f() {\n <div>\n <p>hi\n there</p>\n </div>\n}\n"; |
| 1991 | + assert_eq!(fmt(html), html); |
| 1992 | + } |
| 1993 | + |
| 1994 | + #[test] |
| 1995 | + fn trailing_commas_in_lists_are_dropped() { |
| 1996 | + assert_eq!(fmt("fn f() {\n f(a, b,)\n}\n"), "fn f() {\n f(a, b)\n}\n"); |
| 1997 | + } |
| 1998 | + |
| 1999 | + #[test] |
| 2000 | + fn empty_braces_after_a_type_name_are_dropped() { |
| 2001 | + assert_eq!(fmt("pub type Account {}\n"), "pub type Account\n"); |
| 2002 | + assert_eq!(fmt("pub type Account {\n}\n"), "pub type Account\n"); |
| 2003 | + // One variant keeps the braces; comments keep them too. |
| 2004 | + assert_eq!(fmt("pub type T { A }\n"), "pub type T { A }\n"); |
| 2005 | + assert_eq!(fmt("pub type T { // c\n}\n"), "pub type T { // c\n}\n"); |
| 254 | 2006 | } |
| 255 | 2007 | |
| 256 | 2008 | #[test] |
| 257 | | − fn template_text_is_kept_verbatim() { |
| 258 | | − let src = "fn f() {\n let page = pug`\n .card\n p Hello, {name}!\n `\n}\n"; |
| 259 | | − assert_eq!(format(src).unwrap(), src); |
| 260 | | − let inline = "fn f() {\n let x = html`<p class=\"note\">{body}</p>`\n}\n"; |
| 261 | | − assert_eq!(format(inline).unwrap(), inline); |
| 2009 | + fn use_and_long_values() { |
| 2010 | + let src = "fn f() {\n use a, b <- pairs(xs)\n a\n}\n"; |
| 2011 | + assert_eq!(fmt(src), src); |
| 2012 | + // Too long: the call breaks its own argument list first. |
| 2013 | + assert_eq!( |
| 2014 | + narrow("fn f() {\n use aaaaaaaaaa, bbbbbbbbbb <- pair(a, b)\n a\n}\n"), |
| 2015 | + "fn f() {\n use aaaaaaaaaa, bbbbbbbbbb <- pair(\n a\n , b\n )\n a\n}\n" |
| 2016 | + ); |
| 262 | 2017 | } |
| 263 | 2018 | } |