.githooks/
compiler/
kernel/
lib/
examples/
std/
arch/
bits/
char/
collections/
fs/
hash/
lang/
alloc/
ast/
gen/
il/
layout/
lower/
manifest/
module/
parser/
resolver/
scanner/
sexpr/
alloc.rad
1.2 KiB
ast.rad
36.0 KiB
gen.rad
513 B
il.rad
48.5 KiB
layout.rad
6.9 KiB
lower.rad
487.6 KiB
manifest.rad
22.5 KiB
module.rad
17.8 KiB
package.rad
1.5 KiB
parser.rad
114.1 KiB
pretty.rad
103.6 KiB
resolver.rad
508.1 KiB
scanner.rad
19.3 KiB
sexpr.rad
7.1 KiB
strings.rad
3.3 KiB
types.rad
620 B
mem/
sys/
arch.rad
68 B
bits.rad
1.6 KiB
char.rad
1.5 KiB
collections.rad
39 B
fmt.rad
11.6 KiB
fs.rad
11.0 KiB
hash.rad
41 B
intrinsics.rad
467 B
io.rad
1.7 KiB
lang.rad
335 B
mem.rad
12.0 KiB
mem.ras
919 B
process.rad
6.2 KiB
std.manifest
4.9 KiB
std.rad
349 B
sys.rad
1.0 KiB
testing.rad
2.4 KiB
tests.rad
26.6 KiB
vec.rad
3.2 KiB
scripts/
seed/
sublime/
test/
vim/
.gitignore
333 B
.gitsigners
224 B
AGENTS.md
8.3 KiB
CONTRIBUTING
2.1 KiB
LICENSE
1.1 KiB
Makefile
2.5 KiB
README
3.4 KiB
STYLE
3.2 KiB
std.lib
2.1 KiB
std.lib.test
1.1 KiB
lib/std/lang/pretty.rad
raw
| 1 | //! Source layout of Radiance modules. |
| 2 | //! |
| 3 | //! Turns the AST of a module and its trivia (comments and blank lines) into a |
| 4 | //! [`layout::Layout`] that follows the canonical source style. The layout |
| 5 | //! states where each piece goes, and only soft placements and choices depend |
| 6 | //! on the line width. Renderers such as [`layout::text`] decide them. |
| 7 | //! Formatting a module and parsing the result gives the same AST, and |
| 8 | //! formatting that result again gives the same layout. |
| 9 | //! |
| 10 | //! The line width is a maximum. A construct that the source broke across |
| 11 | //! lines, and that the parser marked in the trivia with [`ast::BrokenSite`], |
| 12 | //! stays broken when it fits on one line. A construct that the source kept on |
| 13 | //! one line is flat when it fits. |
| 14 | //! |
| 15 | //! The AST does not record some source forms. Parentheses are placed where the |
| 16 | //! parser's precedence and context rules need them, and around mixed bitwise |
| 17 | //! operations for readability, `set x op= y` is printed |
| 18 | //! when the right side applies `op` to the very node on the left side, and |
| 19 | //! strings and characters are escaped again. |
| 20 | use std::char; |
| 21 | use std::fmt; |
| 22 | use std::lang::alloc; |
| 23 | use std::lang::ast; |
| 24 | use std::lang::layout; |
| 25 | use std::lang::module::Role; |
| 26 | use std::lang::types; |
| 27 | use std::mem::heap; |
| 28 | |
| 29 | /// Placement on the same line with no gap. |
| 30 | constant NONE: layout::Placement = layout::Placement::Inline(layout::Gap::None); |
| 31 | /// Placement on the same line after a space. |
| 32 | constant SPACE: layout::Placement = layout::Placement::Inline( |
| 33 | layout::Gap::Space |
| 34 | ); |
| 35 | /// Placement on the same line when flat, otherwise on a new line. |
| 36 | constant SOFT: layout::Placement = layout::Placement::SoftLine( |
| 37 | layout::Gap::None |
| 38 | ); |
| 39 | /// Placement on the same line after a space when flat, otherwise on a new line. |
| 40 | constant SOFT_SPACE: layout::Placement = layout::Placement::SoftLine( |
| 41 | layout::Gap::Space |
| 42 | ); |
| 43 | /// Placement on the same line when flat, otherwise on a new indented line. |
| 44 | constant SOFT_INDENT: layout::Placement = layout::Placement::SoftIndent( |
| 45 | layout::Gap::None |
| 46 | ); |
| 47 | /// Placement on the same line after a space when flat, otherwise on a new |
| 48 | /// indented line. |
| 49 | constant SOFT_INDENT_SPACE: layout::Placement = layout::Placement::SoftIndent( |
| 50 | layout::Gap::Space |
| 51 | ); |
| 52 | |
| 53 | /// Column of the tab stop after the pattern of a match prong, which lines up |
| 54 | /// the arrows. |
| 55 | constant COLUMN_ARROW: u32 = 0; |
| 56 | /// Column of the tab stop before a trailing comment. |
| 57 | constant COLUMN_COMMENT: u32 = 1; |
| 58 | |
| 59 | /// Level of an expression that binds looser than every other expression. |
| 60 | constant LEVEL_COND: u32 = 0; |
| 61 | /// Level of a range expression. |
| 62 | constant LEVEL_RANGE: u32 = 1; |
| 63 | /// Level of a binary expression with the loosest operator. Each tighter |
| 64 | /// operator precedence adds one. |
| 65 | constant LEVEL_BINARY: u32 = 2; |
| 66 | /// Level of a cast, which binds tighter than every binary operator. |
| 67 | constant LEVEL_CAST: u32 = 10; |
| 68 | /// Level of prefix expressions: unary operators, dereference, address-of, and |
| 69 | /// `try`. |
| 70 | constant LEVEL_PREFIX: u32 = 11; |
| 71 | /// Level of postfix and primary expressions. |
| 72 | constant LEVEL_POSTFIX: u32 = 12; |
| 73 | |
| 74 | /// Syntactic context of an expression. It decides which forms need parentheses, |
| 75 | /// because the parser reads some forms differently in each context. |
| 76 | union Ctx: Copy { |
| 77 | /// Ordinary expression. |
| 78 | Normal, |
| 79 | /// Pattern of `case`, where `if` starts a guard and `{` follows a type |
| 80 | /// name. |
| 81 | Pattern, |
| 82 | /// Condition or subject, where `{` always starts a block. |
| 83 | Condition, |
| 84 | } |
| 85 | |
| 86 | /// Whether the guard of a pattern follows `;` or `if`. |
| 87 | union GuardStyle: Copy { |
| 88 | /// `if let pattern = value; guard {`. |
| 89 | Semicolon, |
| 90 | /// `let case pattern = value if guard else`. |
| 91 | If, |
| 92 | } |
| 93 | |
| 94 | /// State of the layout of a module. |
| 95 | record Printer { |
| 96 | /// Source bodies or provider prototypes, with explicit foreign linkage. |
| 97 | role: Role, |
| 98 | /// Trivia of the module, ordered by node id. |
| 99 | trivia: *[ast::Trivia], |
| 100 | /// Number of trivia entries other than marks that were placed in the |
| 101 | /// layout. |
| 102 | used: u32, |
| 103 | /// Number of function bodies that the layout is inside of. |
| 104 | fnDepth: u32, |
| 105 | /// Number of marks of broken constructs that were placed in the layout. |
| 106 | marks: u32, |
| 107 | /// Record literal that is an array item, if any. |
| 108 | tableRecord: ?*ast::Node, |
| 109 | } |
| 110 | |
| 111 | /// Whether the items of a soft list end with a comma when they are one per |
| 112 | /// line. |
| 113 | union Commas: Copy { |
| 114 | /// Commas only between items. |
| 115 | Between, |
| 116 | /// A comma after the last item too, when the items are one per line. |
| 117 | Trailing, |
| 118 | } |
| 119 | |
| 120 | /// Delimiters and contents around the items of a soft list. |
| 121 | record SoftSpec: Copy { |
| 122 | /// Node that the list presents, if any. |
| 123 | source: ?*ast::Node, |
| 124 | /// Node that owns the closing trivia of the list, if any. |
| 125 | container: ?*ast::Node, |
| 126 | /// Opening delimiter. |
| 127 | open: *[u8], |
| 128 | /// Closing delimiter. |
| 129 | close: *[u8], |
| 130 | /// Gap inside the delimiters. |
| 131 | pad: layout::Gap, |
| 132 | /// Text that follows the last item as another item, if any. |
| 133 | tail: ?*[u8], |
| 134 | /// Comma after the last item. |
| 135 | commas: Commas, |
| 136 | /// Whether the list is broken whether or not it fits. A list whose |
| 137 | /// `container` has a [`ast::BrokenSite::List`] mark is broken too. |
| 138 | forced: bool, |
| 139 | } |
| 140 | |
| 141 | /// Blank line and comment state of one vertical list. |
| 142 | record Flow { |
| 143 | /// Whether the list has an item or comment yet. |
| 144 | started: bool, |
| 145 | /// Whether a blank line is waiting for the next comment or item. |
| 146 | blank: bool, |
| 147 | /// Whether the line before is the end of a block in a function body, which |
| 148 | /// no blank line follows. |
| 149 | afterBlock: bool, |
| 150 | } |
| 151 | |
| 152 | /// Format the module `root` with its `trivia`. |
| 153 | /// |
| 154 | /// `root` is the module that the parser returns, and `trivia` is |
| 155 | /// the parser's trivia for it. Every comment and blank line of `trivia` is |
| 156 | /// placed in the layout. The layout is allocated from `a`. |
| 157 | export fn module( |
| 158 | root: *ast::Node, trivia: *[ast::Trivia], a: &heap::Heap |
| 159 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 160 | return try withRole(root, trivia, Role::Source, a); |
| 161 | } |
| 162 | |
| 163 | /// Format the expression `node`, which has no trivia. |
| 164 | export fn expression( |
| 165 | node: *ast::Node, a: &heap::Heap |
| 166 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 167 | let mut p = Printer { |
| 168 | role: Role::Source, trivia: &[], used: 0, fnDepth: 0, marks: 0, tableRecord: nil |
| 169 | }; |
| 170 | return try expr(a, &mut p, node, Ctx::Normal); |
| 171 | } |
| 172 | |
| 173 | /// Format one top-level statement of a provider interface without its runtime body. |
| 174 | /// A compiler entry helper formats as nothing. Declarations keep their source |
| 175 | /// visibility and nominal ownership. |
| 176 | export fn interfaceStatement( |
| 177 | node: *ast::Node, a: &heap::Heap |
| 178 | ) -> ?*layout::Layout throws (alloc::AllocError) { |
| 179 | if isEntry(node) { |
| 180 | return nil; |
| 181 | } |
| 182 | let mut p = Printer { |
| 183 | role: Role::Interface, |
| 184 | trivia: &[], |
| 185 | used: 0, |
| 186 | fnDepth: 0, |
| 187 | marks: 0, |
| 188 | tableRecord: nil, |
| 189 | }; |
| 190 | return try stmt(a, &mut p, node); |
| 191 | } |
| 192 | |
| 193 | /// Place the layouts of interface statements one per line, as the layout of the |
| 194 | /// module `root`. This is the layout of a module of those statements without trivia. |
| 195 | export fn interfaceModule( |
| 196 | root: *ast::Node, statements: *[*layout::Layout], a: &heap::Heap |
| 197 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 198 | let mut kids: *mut [layout::Child] = &mut []; |
| 199 | for statement in statements { |
| 200 | try add(a, &mut kids, layout::Placement::Line, statement); |
| 201 | } |
| 202 | return try group(a, root, kids); |
| 203 | } |
| 204 | |
| 205 | /// Build the layout of one module in its input role. |
| 206 | export fn withRole( |
| 207 | root: *ast::Node, trivia: *[ast::Trivia], role: Role, a: &heap::Heap |
| 208 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 209 | let case ast::NodeValue::Module(blk) = root.value else { |
| 210 | panic "withRole: expected module"; |
| 211 | }; |
| 212 | let mut p = Printer { |
| 213 | role, trivia, used: 0, fnDepth: 0, marks: 0, tableRecord: nil |
| 214 | }; |
| 215 | let mut kids: *mut [layout::Child] = &mut []; |
| 216 | try lines( |
| 217 | a, |
| 218 | &mut p, |
| 219 | &mut kids, |
| 220 | blk.statements, |
| 221 | root, |
| 222 | layout::Placement::Line, |
| 223 | stmt |
| 224 | ); |
| 225 | assert p.used + p.marks == trivia.len, "module: trivia entry not placed"; |
| 226 | |
| 227 | return try group(a, root, kids); |
| 228 | } |
| 229 | |
| 230 | // Layout construction //////////////////////////////////////////////////////// |
| 231 | |
| 232 | /// Allocate a text layout. |
| 233 | fn leaf( |
| 234 | a: &heap::Heap, |
| 235 | source: ?*ast::Node, |
| 236 | text: *[u8], |
| 237 | role: layout::Role |
| 238 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 239 | return try layout::new(a, source, layout::Item::Text { text, role }); |
| 240 | } |
| 241 | |
| 242 | /// Allocate a box layout. |
| 243 | /// |
| 244 | /// A box with a broken part is broken too: the part ends a line, so the soft |
| 245 | /// placements after it start new lines, as they would if the box did not fit. |
| 246 | fn group( |
| 247 | a: &heap::Heap, source: ?*ast::Node, kids: *[layout::Child] |
| 248 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 249 | let box = try flatGroup(a, source, kids); |
| 250 | for kid in kids { |
| 251 | if hasBroken(kid.layout) { |
| 252 | return try broken(a, box); |
| 253 | } |
| 254 | } |
| 255 | return box; |
| 256 | } |
| 257 | |
| 258 | /// Allocate a box layout that is flat when it fits, even with a broken part. |
| 259 | fn flatGroup( |
| 260 | a: &heap::Heap, source: ?*ast::Node, kids: *[layout::Child] |
| 261 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 262 | return try layout::new(a, source, layout::Item::Box(kids)); |
| 263 | } |
| 264 | |
| 265 | /// Allocate a box with the single child `l` at `placement`. |
| 266 | fn placed( |
| 267 | a: &heap::Heap, |
| 268 | placement: layout::Placement, |
| 269 | l: *layout::Layout |
| 270 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 271 | let mut kids: *mut [layout::Child] = &mut []; |
| 272 | try add(a, &mut kids, placement, l); |
| 273 | return try flatGroup(a, nil, kids); |
| 274 | } |
| 275 | |
| 276 | /// Allocate a box of layouts that follow each other on one line. |
| 277 | fn row( |
| 278 | a: &heap::Heap, parts: &[*layout::Layout] |
| 279 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 280 | let mut kids: *mut [layout::Child] = &mut []; |
| 281 | for part in parts { |
| 282 | try add(a, &mut kids, NONE, part); |
| 283 | } |
| 284 | return try flatGroup(a, nil, kids); |
| 285 | } |
| 286 | |
| 287 | /// Allocate a choice between alternative layouts, in order of preference. |
| 288 | fn choice( |
| 289 | a: &heap::Heap, |
| 290 | source: ?*ast::Node, |
| 291 | alts: &[*layout::Layout] |
| 292 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 293 | let mut copy: *mut [*layout::Layout] = &mut []; |
| 294 | for alt in alts { |
| 295 | try copy.append(alt, a); |
| 296 | } |
| 297 | return try layout::new(a, source, layout::Item::Choice(copy)); |
| 298 | } |
| 299 | |
| 300 | /// Allocate a choice between `l` on the current line after a space, and `l` |
| 301 | /// on the next line, one level deeper. |
| 302 | fn sameOrNext( |
| 303 | a: &heap::Heap, l: *layout::Layout |
| 304 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 305 | return try choice( |
| 306 | a, |
| 307 | nil, |
| 308 | &[ |
| 309 | try placed(a, SPACE, l), |
| 310 | try placed(a, layout::Placement::Indent, l), |
| 311 | ] |
| 312 | ); |
| 313 | } |
| 314 | |
| 315 | /// Copy of `kids` with every soft placement on the same line. |
| 316 | fn inlined( |
| 317 | a: &heap::Heap, kids: *[layout::Child] |
| 318 | ) -> *[layout::Child] throws (alloc::AllocError) { |
| 319 | let mut out: *mut [layout::Child] = &mut []; |
| 320 | for kid in kids { |
| 321 | let mut placement = kid.placement; |
| 322 | match kid.placement { |
| 323 | case layout::Placement::SoftLine(gap) => |
| 324 | set placement = layout::Placement::Inline(gap), |
| 325 | case layout::Placement::SoftIndent(gap) => |
| 326 | set placement = layout::Placement::Inline(gap), |
| 327 | else => {} |
| 328 | } |
| 329 | try add(a, &mut out, placement, kid.layout); |
| 330 | } |
| 331 | return out; |
| 332 | } |
| 333 | |
| 334 | /// Copy of a layout that stays on one line: every soft placement on the |
| 335 | /// line, and every choice at its first alternative. |
| 336 | fn flattened( |
| 337 | a: &heap::Heap, l: *layout::Layout |
| 338 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 339 | match l.item { |
| 340 | case layout::Item::Box(children) => { |
| 341 | let mut copy: *mut [layout::Child] = &mut []; |
| 342 | for kid in try inlined(a, children) { |
| 343 | let flat = try flattened(a, kid.layout); |
| 344 | try add(a, &mut copy, kid.placement, flat); |
| 345 | } |
| 346 | return try group(a, l.source, copy); |
| 347 | } |
| 348 | case layout::Item::Choice(alts) => return try flattened(a, alts[0]), |
| 349 | case layout::Item::Broken(inner) => return try flattened(a, inner), |
| 350 | else => return l, |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | /// Allocate a layout of the box `l`, broken whether or not it fits. A layout |
| 355 | /// that is broken already stays as it is. |
| 356 | fn broken( |
| 357 | a: &heap::Heap, l: *layout::Layout |
| 358 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 359 | if let case layout::Item::Broken(_) = l.item { |
| 360 | return l; |
| 361 | } |
| 362 | return try layout::new(a, l.source, layout::Item::Broken(l)); |
| 363 | } |
| 364 | |
| 365 | /// Layout `l`, broken whether or not it fits when `forced`. |
| 366 | fn forceBroken( |
| 367 | a: &heap::Heap, l: *layout::Layout, forced: bool |
| 368 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 369 | if forced { |
| 370 | return try broken(a, l); |
| 371 | } |
| 372 | return l; |
| 373 | } |
| 374 | |
| 375 | /// Copy of `kids` whose last child is broken whether or not it fits. |
| 376 | fn brokenLast( |
| 377 | a: &heap::Heap, kids: *[layout::Child] |
| 378 | ) -> *[layout::Child] throws (alloc::AllocError) { |
| 379 | let mut copy: *mut [layout::Child] = &mut []; |
| 380 | for kid in kids { |
| 381 | try copy.append(kid, a); |
| 382 | } |
| 383 | let last = copy.len - 1; |
| 384 | set copy[last].layout = try broken(a, copy[last].layout); |
| 385 | |
| 386 | return copy; |
| 387 | } |
| 388 | |
| 389 | /// Append a child to a box under construction. |
| 390 | fn add( |
| 391 | a: &heap::Heap, |
| 392 | kids: &mut *mut [layout::Child], |
| 393 | placement: layout::Placement, |
| 394 | child: *layout::Layout |
| 395 | ) throws (alloc::AllocError) { |
| 396 | try kids.append(layout::Child { placement, layout: child }, a); |
| 397 | } |
| 398 | |
| 399 | /// Append a text child. |
| 400 | fn word( |
| 401 | a: &heap::Heap, |
| 402 | kids: &mut *mut [layout::Child], |
| 403 | placement: layout::Placement, |
| 404 | text: *[u8], |
| 405 | role: layout::Role |
| 406 | ) throws (alloc::AllocError) { |
| 407 | try add(a, kids, placement, try leaf(a, nil, text, role)); |
| 408 | } |
| 409 | |
| 410 | /// Append a keyword. |
| 411 | fn keyword( |
| 412 | a: &heap::Heap, |
| 413 | kids: &mut *mut [layout::Child], |
| 414 | placement: layout::Placement, |
| 415 | text: *[u8] |
| 416 | ) throws (alloc::AllocError) { |
| 417 | try word(a, kids, placement, text, layout::Role::Keyword); |
| 418 | } |
| 419 | |
| 420 | /// Append punctuation. |
| 421 | fn punct( |
| 422 | a: &heap::Heap, |
| 423 | kids: &mut *mut [layout::Child], |
| 424 | placement: layout::Placement, |
| 425 | text: *[u8] |
| 426 | ) throws (alloc::AllocError) { |
| 427 | try word(a, kids, placement, text, layout::Role::Punct); |
| 428 | } |
| 429 | |
| 430 | /// Append an operator. |
| 431 | fn operator( |
| 432 | a: &heap::Heap, |
| 433 | kids: &mut *mut [layout::Child], |
| 434 | placement: layout::Placement, |
| 435 | text: *[u8] |
| 436 | ) throws (alloc::AllocError) { |
| 437 | try word(a, kids, placement, text, layout::Role::Operator); |
| 438 | } |
| 439 | |
| 440 | /// Append a comment. |
| 441 | fn comment( |
| 442 | a: &heap::Heap, |
| 443 | kids: &mut *mut [layout::Child], |
| 444 | placement: layout::Placement, |
| 445 | text: *[u8] |
| 446 | ) throws (alloc::AllocError) { |
| 447 | try word(a, kids, placement, text, layout::Role::Comment); |
| 448 | } |
| 449 | |
| 450 | /// Append a blank line. |
| 451 | fn blankLine( |
| 452 | a: &heap::Heap, |
| 453 | kids: &mut *mut [layout::Child], |
| 454 | placement: layout::Placement |
| 455 | ) throws (alloc::AllocError) { |
| 456 | try add(a, kids, placement, try layout::new(a, nil, layout::Item::Blank)); |
| 457 | } |
| 458 | |
| 459 | // Trivia ///////////////////////////////////////////////////////////////////// |
| 460 | |
| 461 | /// Find the trivia entries of `node` with the given placement. |
| 462 | /// |
| 463 | /// The entries of one node are contiguous in the order closing, leading, |
| 464 | /// trailing, so the result is a subslice of the module's trivia. |
| 465 | fn entries( |
| 466 | p: &Printer, node: *ast::Node, placement: ast::TriviaPlacement |
| 467 | ) -> *[ast::Trivia] { |
| 468 | let all = p.trivia; |
| 469 | let mut lo: u32 = 0; |
| 470 | let mut hi: u32 = all.len; |
| 471 | while lo < hi { |
| 472 | let mid = lo + (hi - lo) / 2; |
| 473 | if all[mid].node.id < node.id { |
| 474 | set lo = mid + 1; |
| 475 | } else { |
| 476 | set hi = mid; |
| 477 | } |
| 478 | } |
| 479 | let mut start = lo; |
| 480 | let mut end = lo; |
| 481 | let mut i = lo; |
| 482 | while i < all.len and all[i].node.id == node.id { |
| 483 | if all[i].placement == placement { |
| 484 | if start == end { |
| 485 | set start = i; |
| 486 | } |
| 487 | set end = i + 1; |
| 488 | } |
| 489 | set i += 1; |
| 490 | } |
| 491 | return &all[start .. end]; |
| 492 | } |
| 493 | |
| 494 | /// Place comments and blank lines on lines of their own. |
| 495 | /// |
| 496 | /// A blank line is placed only between comments or items: not first in the |
| 497 | /// list, not last, and not twice in a row. It waits in `flow` until a comment |
| 498 | /// or item follows it. |
| 499 | fn comments( |
| 500 | a: &heap::Heap, |
| 501 | kids: &mut *mut [layout::Child], |
| 502 | list: *[ast::Trivia], |
| 503 | level: layout::Placement, |
| 504 | flow: &mut Flow |
| 505 | ) throws (alloc::AllocError) { |
| 506 | for t in list { |
| 507 | match t.kind { |
| 508 | case ast::TriviaKind::Comment(text) => { |
| 509 | if flow.blank { |
| 510 | try blankLine(a, kids, level); |
| 511 | set flow.blank = false; |
| 512 | } |
| 513 | try comment(a, kids, level, text); |
| 514 | set flow.started = true; |
| 515 | set flow.afterBlock = false; |
| 516 | } |
| 517 | case ast::TriviaKind::BlankLine => { |
| 518 | if not flow.afterBlock { |
| 519 | set flow.blank = flow.started; |
| 520 | } |
| 521 | } |
| 522 | case ast::TriviaKind::StackedThrows => {} |
| 523 | case ast::TriviaKind::Broken(_) => {} |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | /// The line that a vertical list is adding to: the children of its box, and |
| 529 | /// the index of the box in the list. |
| 530 | record Row { |
| 531 | /// Code of the items of the line, which wrap together when the line is |
| 532 | /// too wide. |
| 533 | kids: *mut [layout::Child], |
| 534 | /// Index of the line in the list. |
| 535 | at: u32, |
| 536 | /// Trailing comment of the line, if any. |
| 537 | comment: ?*[u8], |
| 538 | } |
| 539 | |
| 540 | /// Append `item` as a line at `level`, or when `joined`, to the last line, with |
| 541 | /// its trailing `comment`. |
| 542 | /// |
| 543 | /// A tab stop of the column of comments goes before the comment, so that the |
| 544 | /// comments of consecutive lines line up. |
| 545 | fn addLine( |
| 546 | a: &heap::Heap, |
| 547 | kids: &mut *mut [layout::Child], |
| 548 | level: layout::Placement, |
| 549 | row: &mut Row, |
| 550 | joined: bool, |
| 551 | item: *layout::Layout, |
| 552 | comment: ?*[u8] |
| 553 | ) throws (alloc::AllocError) { |
| 554 | if joined { |
| 555 | try add(a, &mut row.kids, SOFT_SPACE, item); |
| 556 | } else { |
| 557 | try add(a, kids, level, item); |
| 558 | set row.at = kids.len - 1; |
| 559 | set row.kids = &mut []; |
| 560 | try add(a, &mut row.kids, NONE, item); |
| 561 | } |
| 562 | set row.comment = comment; |
| 563 | if not joined and comment == nil { |
| 564 | return; |
| 565 | } |
| 566 | let mut line: *mut [layout::Child] = &mut []; |
| 567 | for i in 0 .. row.kids.len { |
| 568 | try line.append(row.kids[i], a); |
| 569 | } |
| 570 | let mut code = item; |
| 571 | if line.len > 1 { |
| 572 | set code = try group(a, nil, line); |
| 573 | } |
| 574 | if let text = comment { |
| 575 | let mut both: *mut [layout::Child] = &mut []; |
| 576 | try add(a, &mut both, NONE, code); |
| 577 | try add(a, &mut both, NONE, try tab(a, COLUMN_COMMENT)); |
| 578 | try add( |
| 579 | a, &mut both, SPACE, try leaf(a, nil, text, layout::Role::Comment) |
| 580 | ); |
| 581 | set code = try group(a, nil, both); |
| 582 | } |
| 583 | set kids[row.at].layout = code; |
| 584 | } |
| 585 | |
| 586 | /// Allocate a tab stop of `column`. |
| 587 | fn tab( |
| 588 | a: &heap::Heap, column: u32 |
| 589 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 590 | return try layout::new(a, nil, layout::Item::Tab(column)); |
| 591 | } |
| 592 | |
| 593 | /// Place a vertical list of items, one per line at `level`, with the comments |
| 594 | /// and blank lines around them. An item that the source put after another on |
| 595 | /// its line follows that item. |
| 596 | /// |
| 597 | /// Leading trivia goes on lines before its item, and trailing comments after |
| 598 | /// the item on its last line. The closing trivia of `container` follows the |
| 599 | /// last item. |
| 600 | fn lines( |
| 601 | a: &heap::Heap, |
| 602 | p: &mut Printer, |
| 603 | kids: &mut *mut [layout::Child], |
| 604 | items: *[*ast::Node], |
| 605 | container: *ast::Node, |
| 606 | level: layout::Placement, |
| 607 | format: fn( |
| 608 | &heap::Heap, &mut Printer, *ast::Node |
| 609 | ) -> *layout::Layout |
| 610 | throws (alloc::AllocError) |
| 611 | ) throws (alloc::AllocError) { |
| 612 | let mut flow = Flow { started: false, blank: false, afterBlock: false }; |
| 613 | let mut row = Row { kids: &mut [], at: 0, comment: nil }; |
| 614 | let spaced = p.role == Role::Source and spacesFunctions(p, container); |
| 615 | for item, i in items { |
| 616 | if p.role == Role::Interface and isEntry(item) { |
| 617 | continue; |
| 618 | } |
| 619 | if i > 0 { |
| 620 | // Functions are one blank line apart. A block in a function body |
| 621 | // has no blank line after it. |
| 622 | if spaced and hasBody(items[i - 1]) and hasBody(item) { |
| 623 | set flow.blank = true; |
| 624 | } |
| 625 | set flow.afterBlock = p.fnDepth > 0 and endsWithBlock(items[i - 1]); |
| 626 | } |
| 627 | let leading = entries(p, item, ast::TriviaPlacement::Leading); |
| 628 | set p.used += leading.len; |
| 629 | try comments(a, kids, leading, level, &mut flow); |
| 630 | if flow.blank { |
| 631 | try blankLine(a, kids, level); |
| 632 | set flow.blank = false; |
| 633 | } |
| 634 | // An item that the source put on the line of the one before it. |
| 635 | let joined = takeMark(p, item, ast::BrokenSite::Joined) |
| 636 | and leading.len == 0 |
| 637 | and kids.len > 0; |
| 638 | let core = try format(a, p, item); |
| 639 | let trailing = entries(p, item, ast::TriviaPlacement::Trailing); |
| 640 | set p.used += trailing.len; |
| 641 | let mut text: ?*[u8] = nil; |
| 642 | if trailing.len > 0 { |
| 643 | if let case ast::TriviaKind::Comment(first) = trailing[0].kind { |
| 644 | set text = first; |
| 645 | } |
| 646 | } |
| 647 | try addLine(a, kids, level, &mut row, joined, core, text); |
| 648 | // Another comment on the same line is read back as a comment on its |
| 649 | // own line. |
| 650 | for j in 1 .. trailing.len { |
| 651 | if let case ast::TriviaKind::Comment(more) = trailing[j].kind { |
| 652 | try comment(a, kids, level, more); |
| 653 | } |
| 654 | } |
| 655 | set flow.started = true; |
| 656 | } |
| 657 | let closing = entries(p, container, ast::TriviaPlacement::Closing); |
| 658 | countClosing(p, closing); |
| 659 | if items.len > 0 { |
| 660 | let last = items[items.len - 1]; |
| 661 | set flow.afterBlock = p.fnDepth > 0 and endsWithBlock(last); |
| 662 | } |
| 663 | try comments(a, kids, closing, level, &mut flow); |
| 664 | } |
| 665 | |
| 666 | /// Whether a declaration is a compiler entry helper, which has a reserved name |
| 667 | /// outside source syntax and is left out of interfaces. |
| 668 | fn isEntry(node: *ast::Node) -> bool { |
| 669 | if let case ast::NodeValue::FnDecl(decl) = node.value { |
| 670 | if let case ast::NodeValue::Ident(name) = decl.name.value { |
| 671 | return name.len > 0 and name[0] == '#'; |
| 672 | } |
| 673 | } |
| 674 | return false; |
| 675 | } |
| 676 | |
| 677 | /// Whether a list with the container `container` puts one blank line between |
| 678 | /// functions: the top level of a module, and the methods of an instance. |
| 679 | fn spacesFunctions(p: &Printer, container: *ast::Node) -> bool { |
| 680 | match container.value { |
| 681 | case ast::NodeValue::Module(_) => return true, |
| 682 | case ast::NodeValue::Block(_) => return p.fnDepth == 0, |
| 683 | case ast::NodeValue::InstanceDecl { .. } => return true, |
| 684 | else => return false, |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | /// Whether a declaration is a function or method with a body. Declarations |
| 689 | /// without one, such as `extern` functions, stay grouped as the source has |
| 690 | /// them. |
| 691 | fn hasBody(node: *ast::Node) -> bool { |
| 692 | match node.value { |
| 693 | case ast::NodeValue::FnDecl(f) => return f.body <> nil, |
| 694 | case ast::NodeValue::MethodDecl { .. } => return true, |
| 695 | else => return false, |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | /// Whether the last line of a statement is the closing brace of a block: a |
| 700 | /// statement with a block body, such as `if`, `match`, or a loop, a `let else` |
| 701 | /// with a block, or a statement that ends with a `try catch` block. An empty |
| 702 | /// block, as in `if a {}`, counts. |
| 703 | fn endsWithBlock(node: *ast::Node) -> bool { |
| 704 | match node.value { |
| 705 | case |
| 706 | ast::NodeValue::If(_), |
| 707 | ast::NodeValue::IfLet(_), |
| 708 | ast::NodeValue::While(_), |
| 709 | ast::NodeValue::WhileLet(_), |
| 710 | ast::NodeValue::For(_), |
| 711 | ast::NodeValue::Loop { .. }, |
| 712 | ast::NodeValue::Match(_), |
| 713 | ast::NodeValue::Block(_) => |
| 714 | return true, |
| 715 | case ast::NodeValue::LetElse(l) => return endsWithBlock(l.elseBranch), |
| 716 | case ast::NodeValue::Let(l) => return exprEndsWithBlock(l.value), |
| 717 | case ast::NodeValue::Assign(asg) => return exprEndsWithBlock(asg.right), |
| 718 | case ast::NodeValue::ExprStmt(e) => return exprEndsWithBlock(e), |
| 719 | case ast::NodeValue::Return { value } => { |
| 720 | if let v = value { |
| 721 | return exprEndsWithBlock(v); |
| 722 | } |
| 723 | return false; |
| 724 | } |
| 725 | else => return false, |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | /// Whether an expression ends with the block of a `catch` clause. |
| 730 | fn exprEndsWithBlock(node: *ast::Node) -> bool { |
| 731 | match node.value { |
| 732 | case ast::NodeValue::Try(t) => return t.catches.len > 0, |
| 733 | case ast::NodeValue::BinOp(bin) => return exprEndsWithBlock(bin.right), |
| 734 | else => return false, |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | /// Specification of a list in parentheses with no gap inside them. |
| 739 | fn parens(container: ?*ast::Node) -> SoftSpec { |
| 740 | return SoftSpec { |
| 741 | source: nil, |
| 742 | container, |
| 743 | open: "(", |
| 744 | close: ")", |
| 745 | pad: layout::Gap::None, |
| 746 | tail: nil, |
| 747 | commas: Commas::Between, |
| 748 | forced: false, |
| 749 | }; |
| 750 | } |
| 751 | |
| 752 | /// Whether `node` has a mark that the source broke a construct of it at `site`. |
| 753 | /// |
| 754 | /// The mark is closing trivia of the node. Whoever formats the closing trivia |
| 755 | /// of the node counts it as placed, and anyone else uses [`takeMark`]. |
| 756 | fn marked(p: &Printer, node: *ast::Node, site: ast::BrokenSite) -> bool { |
| 757 | for t in entries(p, node, ast::TriviaPlacement::Closing) { |
| 758 | if let case ast::TriviaKind::Broken(found) = t.kind; found == site { |
| 759 | return true; |
| 760 | } |
| 761 | } |
| 762 | return false; |
| 763 | } |
| 764 | |
| 765 | /// Like [`marked`], and counts the mark as placed. For a node whose closing |
| 766 | /// trivia no list formats. |
| 767 | fn takeMark(p: &mut Printer, node: *ast::Node, site: ast::BrokenSite) -> bool { |
| 768 | if marked(p, node, site) { |
| 769 | set p.marks += 1; |
| 770 | return true; |
| 771 | } |
| 772 | return false; |
| 773 | } |
| 774 | |
| 775 | /// Count the closing trivia of a node as placed. |
| 776 | fn countClosing(p: &mut Printer, closing: *[ast::Trivia]) { |
| 777 | for t in closing { |
| 778 | if let case ast::TriviaKind::Broken(_) = t.kind { |
| 779 | set p.marks += 1; |
| 780 | } else { |
| 781 | set p.used += 1; |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | /// Place a soft list: `open`, items separated by commas, and `close`. |
| 787 | /// |
| 788 | /// When flat, the list is on one line. Otherwise the items go on one indented |
| 789 | /// line when they fit, or one per line. A comment in the list breaks it. Blank |
| 790 | /// lines in the list are dropped. A comment before the closing delimiter puts |
| 791 | /// the items one per line. A list that the source broke across lines is |
| 792 | /// broken: its items go on a line of their own between the delimiters. They |
| 793 | /// are one per line when each started a line in the source. Array items keep |
| 794 | /// the source line groups when they fit. |
| 795 | fn softList( |
| 796 | a: &heap::Heap, |
| 797 | p: &mut Printer, |
| 798 | spec: SoftSpec, |
| 799 | items: *[*ast::Node], |
| 800 | ctx: Ctx, |
| 801 | format: fn( |
| 802 | &heap::Heap, &mut Printer, *ast::Node, Ctx |
| 803 | ) -> *layout::Layout |
| 804 | throws (alloc::AllocError) |
| 805 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 806 | let mut forced = spec.forced; |
| 807 | if let node = spec.container { |
| 808 | set forced = forced or marked(p, node, ast::BrokenSite::List); |
| 809 | } |
| 810 | let list = try plainList(a, p, spec, items, ctx, format); |
| 811 | |
| 812 | return try forceBroken(a, list, forced); |
| 813 | } |
| 814 | |
| 815 | /// Place a soft list as [`softList`] does, but break it only for a comment in |
| 816 | /// it, and one per line when the source had them so. |
| 817 | fn plainList( |
| 818 | a: &heap::Heap, |
| 819 | p: &mut Printer, |
| 820 | spec: SoftSpec, |
| 821 | items: *[*ast::Node], |
| 822 | ctx: Ctx, |
| 823 | format: fn( |
| 824 | &heap::Heap, &mut Printer, *ast::Node, Ctx |
| 825 | ) -> *layout::Layout |
| 826 | throws (alloc::AllocError) |
| 827 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 828 | let mut inner: *mut [layout::Child] = &mut []; |
| 829 | let mut rows: *mut [layout::Child] = &mut []; |
| 830 | let mut at = NONE; |
| 831 | let mut closingComment = false; |
| 832 | let mut array = false; |
| 833 | let mut tableRecord = false; |
| 834 | if let node = spec.container { |
| 835 | if let case ast::NodeValue::ArrayLit(_) = node.value { |
| 836 | set array = true; |
| 837 | } |
| 838 | set tableRecord = p.tableRecord == node; |
| 839 | } |
| 840 | // The source put each item on a line of its own. |
| 841 | let mut perLine = false; |
| 842 | if let node = spec.container { |
| 843 | set perLine = marked(p, node, ast::BrokenSite::Items); |
| 844 | } |
| 845 | for item, i in items { |
| 846 | let leading = entries(p, item, ast::TriviaPlacement::Leading); |
| 847 | set p.used += leading.len; |
| 848 | if array and inner.len > 0 { |
| 849 | for t in leading { |
| 850 | if let case ast::TriviaKind::Broken(ast::BrokenSite::ItemLine) = t.kind { |
| 851 | let rowAt = NONE if rows.len == 0 else layout::Placement::Line; |
| 852 | try add( |
| 853 | a, &mut rows, rowAt, try group(a, nil, inner) |
| 854 | ); |
| 855 | set inner = &mut []; |
| 856 | set at = NONE; |
| 857 | } |
| 858 | } |
| 859 | } |
| 860 | set at = try softComments(a, &mut inner, leading, at); |
| 861 | let savedRecord = p.tableRecord; |
| 862 | if array { |
| 863 | set p.tableRecord = item; |
| 864 | } |
| 865 | let core = try format(a, p, item, ctx); |
| 866 | set p.tableRecord = savedRecord; |
| 867 | let mut comma: ?*layout::Layout = nil; |
| 868 | if i + 1 < items.len or spec.tail <> nil { |
| 869 | set comma = try leaf(a, nil, ",", layout::Role::Punct); |
| 870 | } else if spec.commas == Commas::Trailing { |
| 871 | if array and rows.len > 0 { |
| 872 | set comma = try leaf(a, nil, ",", layout::Role::Punct); |
| 873 | } else { |
| 874 | let text = layout::Item::BrokenText { |
| 875 | text: ",", role: layout::Role::Punct |
| 876 | }; |
| 877 | set comma = try layout::new(a, nil, text); |
| 878 | } |
| 879 | } |
| 880 | let trailing = entries(p, item, ast::TriviaPlacement::Trailing); |
| 881 | set p.used += trailing.len; |
| 882 | let mut first: ?*[u8] = nil; |
| 883 | if trailing.len > 0 { |
| 884 | if let case ast::TriviaKind::Comment(text) = trailing[0].kind { |
| 885 | set first = text; |
| 886 | } |
| 887 | } |
| 888 | try add(a, &mut inner, at, core); |
| 889 | if let c = comma { |
| 890 | try add(a, &mut inner, NONE, c); |
| 891 | if tableRecord and i == 0 { |
| 892 | try add(a, &mut inner, NONE, try tab(a, COLUMN_ARROW)); |
| 893 | } |
| 894 | } |
| 895 | if let text = first { |
| 896 | // The comments of items on lines of their own line up. |
| 897 | try add(a, &mut inner, NONE, try tab(a, COLUMN_COMMENT)); |
| 898 | try comment(a, &mut inner, SPACE, text); |
| 899 | } |
| 900 | set at = SOFT_SPACE; |
| 901 | for t, j in trailing { |
| 902 | if j > 0 { |
| 903 | if let case ast::TriviaKind::Comment(text) = t.kind { |
| 904 | try comment(a, &mut inner, SOFT_SPACE, text); |
| 905 | } |
| 906 | } |
| 907 | } |
| 908 | } |
| 909 | if rows.len > 0 { |
| 910 | if inner.len > 0 { |
| 911 | try add(a, &mut rows, layout::Placement::Line, try group(a, nil, inner)); |
| 912 | } |
| 913 | set inner = rows; |
| 914 | } |
| 915 | if let node = spec.container { |
| 916 | let closing = entries(p, node, ast::TriviaPlacement::Closing); |
| 917 | countClosing(p, closing); |
| 918 | for t in closing { |
| 919 | if let case ast::TriviaKind::Comment(_) = t.kind { |
| 920 | set closingComment = true; |
| 921 | } |
| 922 | } |
| 923 | set at = try softComments(a, &mut inner, closing, at); |
| 924 | } |
| 925 | if let text = spec.tail { |
| 926 | try punct(a, &mut inner, at, text); |
| 927 | } |
| 928 | let mut kids: *mut [layout::Child] = &mut []; |
| 929 | try punct(a, &mut kids, NONE, spec.open); |
| 930 | if inner.len > 0 { |
| 931 | // A comment before the closing delimiter keeps its own line. |
| 932 | let mut body = try group(a, nil, inner); |
| 933 | if closingComment or perLine { |
| 934 | set body = try broken(a, body); |
| 935 | } |
| 936 | try add(a, &mut kids, layout::Placement::SoftIndent(spec.pad), body); |
| 937 | try punct( |
| 938 | a, &mut kids, layout::Placement::SoftLine(spec.pad), spec.close |
| 939 | ); |
| 940 | } else { |
| 941 | try punct(a, &mut kids, NONE, spec.close); |
| 942 | } |
| 943 | let list = try group(a, spec.source, kids); |
| 944 | if closingComment { |
| 945 | return try broken(a, list); |
| 946 | } |
| 947 | return list; |
| 948 | } |
| 949 | |
| 950 | /// Place comments inside a soft list, each on a line of its own. |
| 951 | /// |
| 952 | /// Returns the placement of the child that follows. |
| 953 | fn softComments( |
| 954 | a: &heap::Heap, |
| 955 | kids: &mut *mut [layout::Child], |
| 956 | list: *[ast::Trivia], |
| 957 | placement: layout::Placement |
| 958 | ) -> layout::Placement throws (alloc::AllocError) { |
| 959 | let mut at = placement; |
| 960 | for t in list { |
| 961 | if let case ast::TriviaKind::Comment(text) = t.kind { |
| 962 | try comment(a, kids, at, text); |
| 963 | set at = SOFT_SPACE; |
| 964 | } |
| 965 | } |
| 966 | return at; |
| 967 | } |
| 968 | |
| 969 | // Expressions //////////////////////////////////////////////////////////////// |
| 970 | |
| 971 | /// Source text of a compound assignment operator, if `op` has one. |
| 972 | fn compoundText(op: ast::BinaryOp) -> ?*[u8] { |
| 973 | match op { |
| 974 | case ast::BinaryOp::Add => return "+=", |
| 975 | case ast::BinaryOp::Sub => return "-=", |
| 976 | case ast::BinaryOp::Mul => return "*=", |
| 977 | case ast::BinaryOp::Div => return "/=", |
| 978 | case ast::BinaryOp::Mod => return "%=", |
| 979 | case ast::BinaryOp::BitAnd => return "&=", |
| 980 | case ast::BinaryOp::BitOr => return "|=", |
| 981 | case ast::BinaryOp::BitXor => return "^=", |
| 982 | case ast::BinaryOp::Shl => return "<<=", |
| 983 | case ast::BinaryOp::Shr => return ">>=", |
| 984 | else => return nil, |
| 985 | } |
| 986 | } |
| 987 | |
| 988 | /// Binding level of an expression. An operand needs parentheses when its level |
| 989 | /// is below the level that its parent requires. |
| 990 | fn level(node: *ast::Node) -> u32 { |
| 991 | match node.value { |
| 992 | case ast::NodeValue::CondExpr(_) => return LEVEL_COND, |
| 993 | case ast::NodeValue::Range(_) => return LEVEL_RANGE, |
| 994 | case ast::NodeValue::BinOp(bin) => |
| 995 | return LEVEL_BINARY + ast::precedence(bin.op), |
| 996 | case ast::NodeValue::As(_) => return LEVEL_CAST, |
| 997 | case |
| 998 | ast::NodeValue::UnOp(_), |
| 999 | ast::NodeValue::Deref(_), |
| 1000 | ast::NodeValue::AddressOf(_), |
| 1001 | ast::NodeValue::Try(_) => |
| 1002 | return LEVEL_PREFIX, |
| 1003 | else => return LEVEL_POSTFIX, |
| 1004 | } |
| 1005 | } |
| 1006 | |
| 1007 | /// Letter that follows the backslash when `c` is escaped in a literal |
| 1008 | /// delimited by `quote`, or nil if `c` is written as it is. |
| 1009 | fn escapeCode(c: u8, quote: u8) -> ?u8 { |
| 1010 | if c == quote or c == '\\' { |
| 1011 | return c; |
| 1012 | } |
| 1013 | match c { |
| 1014 | case '\n' => return 'n', |
| 1015 | case '\r' => return 'r', |
| 1016 | case '\t' => return 't', |
| 1017 | case 0 => return '0', |
| 1018 | else => return nil, |
| 1019 | } |
| 1020 | } |
| 1021 | |
| 1022 | /// Escape `s` as the body of a literal delimited by `quote`, and add the |
| 1023 | /// quotes. |
| 1024 | fn quoted( |
| 1025 | a: &heap::Heap, s: *[u8], quote: u8 |
| 1026 | ) -> *[u8] throws (alloc::AllocError) { |
| 1027 | let mut out: *mut [u8] = &mut []; |
| 1028 | try out.append(quote, a); |
| 1029 | for c in s { |
| 1030 | if let code = escapeCode(c, quote) { |
| 1031 | try out.append('\\', a); |
| 1032 | try out.append(code, a); |
| 1033 | } else if not char::isPrint(c) { |
| 1034 | let byte = [c]; |
| 1035 | let mut hex: [u8; 2] = [0; 2]; |
| 1036 | try out.extend("\\x", a); |
| 1037 | try out.extend(fmt::formatHex(&byte[..], &mut hex[..]), a); |
| 1038 | } else { |
| 1039 | try out.append(c, a); |
| 1040 | } |
| 1041 | } |
| 1042 | try out.append(quote, a); |
| 1043 | |
| 1044 | return out; |
| 1045 | } |
| 1046 | |
| 1047 | /// Layout of `node` wrapped in parentheses. |
| 1048 | fn paren( |
| 1049 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 1050 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1051 | let mut kids: *mut [layout::Child] = &mut []; |
| 1052 | try punct(a, &mut kids, NONE, "("); |
| 1053 | try put(a, p, &mut kids, NONE, node, Ctx::Normal); |
| 1054 | try punct(a, &mut kids, NONE, ")"); |
| 1055 | |
| 1056 | return try group(a, node, kids); |
| 1057 | } |
| 1058 | |
| 1059 | /// Layout of an operand that must bind at least as tight as `min`. |
| 1060 | fn operand( |
| 1061 | a: &heap::Heap, |
| 1062 | p: &mut Printer, |
| 1063 | node: *ast::Node, |
| 1064 | ctx: Ctx, |
| 1065 | min: u32 |
| 1066 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1067 | if level(node) < min { |
| 1068 | return try paren(a, p, node); |
| 1069 | } |
| 1070 | return try expr(a, p, node, ctx); |
| 1071 | } |
| 1072 | |
| 1073 | /// Append an expression as a child. |
| 1074 | fn put( |
| 1075 | a: &heap::Heap, |
| 1076 | p: &mut Printer, |
| 1077 | kids: &mut *mut [layout::Child], |
| 1078 | placement: layout::Placement, |
| 1079 | node: *ast::Node, |
| 1080 | ctx: Ctx |
| 1081 | ) throws (alloc::AllocError) { |
| 1082 | try add(a, kids, placement, try expr(a, p, node, ctx)); |
| 1083 | } |
| 1084 | |
| 1085 | /// Append an operand that must bind at least as tight as `min` as a child. |
| 1086 | fn putOperand( |
| 1087 | a: &heap::Heap, |
| 1088 | p: &mut Printer, |
| 1089 | kids: &mut *mut [layout::Child], |
| 1090 | placement: layout::Placement, |
| 1091 | node: *ast::Node, |
| 1092 | ctx: Ctx, |
| 1093 | min: u32 |
| 1094 | ) throws (alloc::AllocError) { |
| 1095 | try add(a, kids, placement, try operand(a, p, node, ctx, min)); |
| 1096 | } |
| 1097 | |
| 1098 | /// Whether `op` is a bitwise or shift operator. |
| 1099 | fn isBitwise(op: ast::BinaryOp) -> bool { |
| 1100 | match op { |
| 1101 | case |
| 1102 | ast::BinaryOp::BitAnd, |
| 1103 | ast::BinaryOp::BitOr, |
| 1104 | ast::BinaryOp::BitXor, |
| 1105 | ast::BinaryOp::Shl, |
| 1106 | ast::BinaryOp::Shr => |
| 1107 | return true, |
| 1108 | else => return false, |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | /// Layout of an operand of the binary operator `op`, where the operand must |
| 1113 | /// bind at least as tight as `min`. |
| 1114 | /// |
| 1115 | /// An operand of another precedence gets parentheses for readability, |
| 1116 | /// although the parser does not need them, when it is a bitwise or shift |
| 1117 | /// operation inside a comparison, or any binary operation inside a bitwise or |
| 1118 | /// shift operation. |
| 1119 | fn chainOperand( |
| 1120 | a: &heap::Heap, |
| 1121 | p: &mut Printer, |
| 1122 | node: *ast::Node, |
| 1123 | ctx: Ctx, |
| 1124 | op: ast::BinaryOp, |
| 1125 | min: u32 |
| 1126 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1127 | let prec = ast::precedence(op); |
| 1128 | if let case ast::NodeValue::BinOp(inner) = |
| 1129 | node.value; |
| 1130 | ast::precedence(inner.op) <> prec |
| 1131 | and (isBitwise(op) or (prec > 0 and isBitwise(inner.op))) |
| 1132 | { |
| 1133 | return try paren(a, p, node); |
| 1134 | } |
| 1135 | return try operand(a, p, node, ctx, min); |
| 1136 | } |
| 1137 | |
| 1138 | /// Format the left-most operands and operators of a chain of binary |
| 1139 | /// operations that have the precedence `prec`. |
| 1140 | /// |
| 1141 | /// The chain breaks before the operators, each of which shares a box with its |
| 1142 | /// right operand. Operands that bind looser than the chain get parentheses. |
| 1143 | /// Returns whether the source broke the chain across lines, at any of its |
| 1144 | /// operations. |
| 1145 | fn chain( |
| 1146 | a: &heap::Heap, |
| 1147 | p: &mut Printer, |
| 1148 | kids: &mut *mut [layout::Child], |
| 1149 | node: *ast::Node, |
| 1150 | prec: u32, |
| 1151 | ctx: Ctx |
| 1152 | ) -> bool throws (alloc::AllocError) { |
| 1153 | let case ast::NodeValue::BinOp(bin) = node.value else { |
| 1154 | panic "chain: not a binary operation"; |
| 1155 | }; |
| 1156 | let mut forced = takeMark(p, node, ast::BrokenSite::Chain); |
| 1157 | // Logical operators have one precedence, so a chain continues only across |
| 1158 | // the same operator. |
| 1159 | let mut continues = false; |
| 1160 | if let case ast::NodeValue::BinOp(inner) = bin.left.value { |
| 1161 | set continues = ast::precedence(inner.op) == prec |
| 1162 | and (prec > 0 or inner.op == bin.op); |
| 1163 | } |
| 1164 | if continues { |
| 1165 | if try chain(a, p, kids, bin.left, prec, ctx) { |
| 1166 | set forced = true; |
| 1167 | } |
| 1168 | } else { |
| 1169 | let mut min = LEVEL_BINARY + prec; |
| 1170 | if prec == 0 { |
| 1171 | set min += 1; |
| 1172 | } |
| 1173 | try add( |
| 1174 | a, kids, NONE, try chainOperand(a, p, bin.left, ctx, bin.op, min) |
| 1175 | ); |
| 1176 | } |
| 1177 | // The operator and its operand share a box, so that breaks inside the |
| 1178 | // operand nest deeper than the chain. |
| 1179 | let mut tail: *mut [layout::Child] = &mut []; |
| 1180 | try operator(a, &mut tail, NONE, ast::binaryText(bin.op)); |
| 1181 | try add( |
| 1182 | a, |
| 1183 | &mut tail, |
| 1184 | SPACE, |
| 1185 | try chainOperand( |
| 1186 | a, p, bin.right, ctx, bin.op, LEVEL_BINARY + prec + 1 |
| 1187 | ) |
| 1188 | ); |
| 1189 | try add(a, kids, SOFT_INDENT_SPACE, try group(a, nil, tail)); |
| 1190 | return forced; |
| 1191 | } |
| 1192 | |
| 1193 | /// Format an expression or type. |
| 1194 | fn expr( |
| 1195 | a: &heap::Heap, p: &mut Printer, node: *ast::Node, ctx: Ctx |
| 1196 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1197 | // Forms that the context cannot parse bare need parentheses. |
| 1198 | match node.value { |
| 1199 | case ast::NodeValue::CondExpr(_) if ctx <> Ctx::Normal => |
| 1200 | return try paren(a, p, node), |
| 1201 | case ast::NodeValue::RecordLit(lit) |
| 1202 | if ctx == Ctx::Condition |
| 1203 | or (ctx == Ctx::Pattern and lit.typeName == nil) => |
| 1204 | return try paren(a, p, node), |
| 1205 | case ast::NodeValue::RecordLit(lit) if ctx == Ctx::Pattern => { |
| 1206 | for field in lit.fields { |
| 1207 | if let case ast::NodeValue::RecordLitField(arg) = |
| 1208 | field.value; |
| 1209 | level(arg.value) == LEVEL_COND |
| 1210 | { |
| 1211 | return try paren(a, p, node); |
| 1212 | } |
| 1213 | } |
| 1214 | } |
| 1215 | else => {} |
| 1216 | } |
| 1217 | let mut kids: *mut [layout::Child] = &mut []; |
| 1218 | match node.value { |
| 1219 | case ast::NodeValue::Placeholder => |
| 1220 | return try leaf(a, node, "_", layout::Role::Name), |
| 1221 | case ast::NodeValue::Nil => |
| 1222 | return try leaf(a, node, "nil", layout::Role::Literal), |
| 1223 | case ast::NodeValue::Undef => |
| 1224 | return try leaf(a, node, "undefined", layout::Role::Literal), |
| 1225 | case ast::NodeValue::Bool(value) => |
| 1226 | return try leaf( |
| 1227 | a, node, "true" if value else "false", layout::Role::Literal |
| 1228 | ), |
| 1229 | case ast::NodeValue::Char(c) => { |
| 1230 | let mut text: *mut [u8] = &mut []; |
| 1231 | try text.append(c, a); |
| 1232 | return try leaf( |
| 1233 | a, node, try quoted(a, text, '\''), layout::Role::Literal |
| 1234 | ); |
| 1235 | } |
| 1236 | case ast::NodeValue::String(s) => |
| 1237 | return try leaf( |
| 1238 | a, node, try quoted(a, s, '"'), layout::Role::Literal |
| 1239 | ), |
| 1240 | case ast::NodeValue::Ident(name) => |
| 1241 | return try leaf(a, node, name, layout::Role::Name), |
| 1242 | case ast::NodeValue::Number(n) => |
| 1243 | return try leaf(a, node, n.text, layout::Role::Literal), |
| 1244 | case ast::NodeValue::Super => |
| 1245 | return try leaf(a, node, "super", layout::Role::Keyword), |
| 1246 | case ast::NodeValue::Range(r) => { |
| 1247 | if let start = r.start { |
| 1248 | // Parenthesize the start when a nested binary expression needs it. |
| 1249 | let mut min = LEVEL_BINARY; |
| 1250 | if let case ast::NodeValue::BinOp(bin) = |
| 1251 | start.value; |
| 1252 | level(bin.right) < LEVEL_CAST |
| 1253 | { |
| 1254 | set min = LEVEL_CAST; |
| 1255 | } |
| 1256 | try putOperand(a, p, &mut kids, NONE, start, ctx, min); |
| 1257 | } |
| 1258 | try operator(a, &mut kids, SPACE if r.start <> nil else NONE, ".."); |
| 1259 | if let end = r.end { |
| 1260 | try putOperand(a, p, &mut kids, SPACE, end, ctx, LEVEL_RANGE); |
| 1261 | } |
| 1262 | } |
| 1263 | case ast::NodeValue::ArrayLit(items) => |
| 1264 | return try softList( |
| 1265 | a, |
| 1266 | p, |
| 1267 | SoftSpec { |
| 1268 | source: node, |
| 1269 | container: node, |
| 1270 | open: "[", |
| 1271 | close: "]", |
| 1272 | pad: layout::Gap::None, |
| 1273 | tail: nil, |
| 1274 | commas: Commas::Trailing, |
| 1275 | forced: false, |
| 1276 | }, |
| 1277 | items, |
| 1278 | Ctx::Normal, |
| 1279 | expr |
| 1280 | ), |
| 1281 | case ast::NodeValue::ArrayRepeatLit(rep) => { |
| 1282 | let mut inner: *mut [layout::Child] = &mut []; |
| 1283 | let leading = entries(p, rep.item, ast::TriviaPlacement::Leading); |
| 1284 | set p.used += leading.len; |
| 1285 | let at = try softComments(a, &mut inner, leading, NONE); |
| 1286 | try add(a, &mut inner, at, try expr(a, p, rep.item, Ctx::Normal)); |
| 1287 | try punct(a, &mut inner, NONE, ";"); |
| 1288 | try put(a, p, &mut inner, SOFT_SPACE, rep.count, Ctx::Normal); |
| 1289 | try punct(a, &mut kids, NONE, "["); |
| 1290 | try add(a, &mut kids, SOFT_INDENT, try group(a, nil, inner)); |
| 1291 | try punct(a, &mut kids, SOFT, "]"); |
| 1292 | let forced = takeMark(p, node, ast::BrokenSite::List); |
| 1293 | return try forceBroken(a, try group(a, node, kids), forced); |
| 1294 | } |
| 1295 | case ast::NodeValue::BracketArgument(arg) => |
| 1296 | return try expr(a, p, arg, ctx), |
| 1297 | case ast::NodeValue::Bracket { base, items } => { |
| 1298 | try putOperand( |
| 1299 | a, p, &mut kids, NONE, base, ctx, LEVEL_POSTFIX |
| 1300 | ); |
| 1301 | let list = SoftSpec { |
| 1302 | source: nil, |
| 1303 | container: node, |
| 1304 | open: "[", |
| 1305 | close: "]", |
| 1306 | pad: layout::Gap::None, |
| 1307 | tail: nil, |
| 1308 | commas: Commas::Between, |
| 1309 | forced: false, |
| 1310 | }; |
| 1311 | try add( |
| 1312 | a, |
| 1313 | &mut kids, |
| 1314 | NONE, |
| 1315 | try softList( |
| 1316 | a, p, list, items, Ctx::Normal, expr |
| 1317 | ) |
| 1318 | ); |
| 1319 | } |
| 1320 | case ast::NodeValue::BinOp(bin) => { |
| 1321 | let forced = try chain( |
| 1322 | a, p, &mut kids, node, ast::precedence(bin.op), ctx |
| 1323 | ); |
| 1324 | // The operator and right operand of a pair follow the left one |
| 1325 | // when they fit, even when the left one broke. |
| 1326 | if kids.len == 2 and not forced { |
| 1327 | set kids[1] = layout::Child { |
| 1328 | placement: NONE, layout: try sameOrNext(a, kids[1].layout) |
| 1329 | }; |
| 1330 | } |
| 1331 | return try forceBroken(a, try group(a, node, kids), forced); |
| 1332 | } |
| 1333 | case ast::NodeValue::UnOp(un) => { |
| 1334 | let at = SPACE if un.op == ast::UnaryOp::Not else NONE; |
| 1335 | try operator(a, &mut kids, NONE, ast::unaryText(un.op)); |
| 1336 | try putOperand(a, p, &mut kids, at, un.value, ctx, LEVEL_PREFIX); |
| 1337 | } |
| 1338 | case ast::NodeValue::BuiltinCall { kind, args } => { |
| 1339 | try word( |
| 1340 | a, &mut kids, NONE, ast::builtinText(kind), layout::Role::Name |
| 1341 | ); |
| 1342 | try add(a, &mut kids, NONE, try callArgs(a, p, node, args)); |
| 1343 | } |
| 1344 | case ast::NodeValue::Call(call) => { |
| 1345 | try putOperand( |
| 1346 | a, p, &mut kids, NONE, call.callee, ctx, LEVEL_POSTFIX |
| 1347 | ); |
| 1348 | try add(a, &mut kids, NONE, try callArgs(a, p, node, call.args)); |
| 1349 | } |
| 1350 | case ast::NodeValue::FieldAccess(acc) => { |
| 1351 | try putOperand( |
| 1352 | a, p, &mut kids, NONE, acc.parent, ctx, LEVEL_POSTFIX |
| 1353 | ); |
| 1354 | try punct(a, &mut kids, NONE, "."); |
| 1355 | try put(a, p, &mut kids, NONE, acc.child, Ctx::Normal); |
| 1356 | } |
| 1357 | case ast::NodeValue::ScopeAccess(acc) => { |
| 1358 | try putOperand( |
| 1359 | a, p, &mut kids, NONE, acc.parent, ctx, LEVEL_POSTFIX |
| 1360 | ); |
| 1361 | try punct(a, &mut kids, NONE, "::"); |
| 1362 | try put(a, p, &mut kids, NONE, acc.child, Ctx::Normal); |
| 1363 | } |
| 1364 | case ast::NodeValue::AddressOf(addr) => { |
| 1365 | let at = SPACE if addr.mutable else NONE; |
| 1366 | try operator(a, &mut kids, NONE, "&mut" if addr.mutable else "&"); |
| 1367 | try putOperand(a, p, &mut kids, at, addr.target, ctx, LEVEL_PREFIX); |
| 1368 | } |
| 1369 | case ast::NodeValue::Deref(target) => { |
| 1370 | try operator(a, &mut kids, NONE, "*"); |
| 1371 | try putOperand(a, p, &mut kids, NONE, target, ctx, LEVEL_PREFIX); |
| 1372 | } |
| 1373 | case ast::NodeValue::As(cast) => { |
| 1374 | try putOperand(a, p, &mut kids, NONE, cast.value, ctx, LEVEL_CAST); |
| 1375 | try keyword(a, &mut kids, SPACE, "as"); |
| 1376 | try put(a, p, &mut kids, SPACE, cast.type, Ctx::Normal); |
| 1377 | } |
| 1378 | case ast::NodeValue::CondExpr(cond) => { |
| 1379 | let forced = takeMark(p, node, ast::BrokenSite::Chain); |
| 1380 | let mut test: *mut [layout::Child] = &mut []; |
| 1381 | try keyword(a, &mut test, NONE, "if"); |
| 1382 | try add( |
| 1383 | a, |
| 1384 | &mut test, |
| 1385 | SPACE, |
| 1386 | try operand( |
| 1387 | a, p, cond.condition, Ctx::Condition, LEVEL_COND + 1 |
| 1388 | ) |
| 1389 | ); |
| 1390 | let mut other: *mut [layout::Child] = &mut []; |
| 1391 | try keyword(a, &mut other, NONE, "else"); |
| 1392 | try put(a, p, &mut other, SPACE, cond.elseExpr, ctx); |
| 1393 | try add( |
| 1394 | a, |
| 1395 | &mut kids, |
| 1396 | NONE, |
| 1397 | try operand(a, p, cond.thenExpr, ctx, LEVEL_COND + 1) |
| 1398 | ); |
| 1399 | try add( |
| 1400 | a, |
| 1401 | &mut kids, |
| 1402 | SOFT_INDENT_SPACE, |
| 1403 | try group(a, cond.condition, test) |
| 1404 | ); |
| 1405 | try add( |
| 1406 | a, |
| 1407 | &mut kids, |
| 1408 | SOFT_INDENT_SPACE, |
| 1409 | try group(a, cond.elseExpr, other) |
| 1410 | ); |
| 1411 | return try forceBroken(a, try group(a, node, kids), forced); |
| 1412 | } |
| 1413 | case ast::NodeValue::Try(t) => { |
| 1414 | let name = "try!" |
| 1415 | if t.shouldPanic |
| 1416 | else "try?" if t.returnsOptional else "try"; |
| 1417 | try keyword(a, &mut kids, NONE, name); |
| 1418 | try putOperand(a, p, &mut kids, SPACE, t.expr, ctx, LEVEL_PREFIX); |
| 1419 | for clause in t.catches { |
| 1420 | let case ast::NodeValue::CatchClause(c) = clause.value else { |
| 1421 | panic "expr: catch clause expected"; |
| 1422 | }; |
| 1423 | try keyword(a, &mut kids, SPACE, "catch"); |
| 1424 | if let binding = c.binding { |
| 1425 | try put(a, p, &mut kids, SPACE, binding, Ctx::Normal); |
| 1426 | } |
| 1427 | if let typeNode = c.typeNode { |
| 1428 | try keyword(a, &mut kids, SPACE, "as"); |
| 1429 | try put(a, p, &mut kids, SPACE, typeNode, Ctx::Normal); |
| 1430 | } |
| 1431 | try blockBody(a, p, &mut kids, c.body, SPACE); |
| 1432 | } |
| 1433 | } |
| 1434 | case ast::NodeValue::RecordLit(lit) => { |
| 1435 | if let typeName = lit.typeName { |
| 1436 | try putOperand( |
| 1437 | a, p, &mut kids, NONE, typeName, ctx, LEVEL_POSTFIX |
| 1438 | ); |
| 1439 | } |
| 1440 | let mut tail: ?*[u8] = nil; |
| 1441 | if lit.ignoreRest { |
| 1442 | set tail = ".."; |
| 1443 | } |
| 1444 | let at = SPACE if lit.typeName <> nil else NONE; |
| 1445 | try add( |
| 1446 | a, |
| 1447 | &mut kids, |
| 1448 | at, |
| 1449 | try softList( |
| 1450 | a, |
| 1451 | p, |
| 1452 | SoftSpec { |
| 1453 | source: nil, |
| 1454 | container: node, |
| 1455 | open: "{", |
| 1456 | close: "}", |
| 1457 | pad: layout::Gap::Space, |
| 1458 | tail, |
| 1459 | commas: Commas::Trailing, |
| 1460 | forced: false, |
| 1461 | }, |
| 1462 | lit.fields, |
| 1463 | ctx, |
| 1464 | recordLitField |
| 1465 | ) |
| 1466 | ); |
| 1467 | } |
| 1468 | case ast::NodeValue::TypeBinder { name, bound } => { |
| 1469 | try put(a, p, &mut kids, NONE, name, Ctx::Normal); |
| 1470 | if let traitName = bound { |
| 1471 | try punct(a, &mut kids, NONE, ":"); |
| 1472 | try put(a, p, &mut kids, SPACE, traitName, Ctx::Normal); |
| 1473 | } |
| 1474 | } |
| 1475 | case ast::NodeValue::TypeSig(sig) => |
| 1476 | return try typeSig(a, p, node, sig), |
| 1477 | case ast::NodeValue::Align { value } => { |
| 1478 | try keyword(a, &mut kids, NONE, "align"); |
| 1479 | try punct(a, &mut kids, NONE, "("); |
| 1480 | try put(a, p, &mut kids, NONE, value, Ctx::Normal); |
| 1481 | try punct(a, &mut kids, NONE, ")"); |
| 1482 | } |
| 1483 | else => panic "expr: not an expression", |
| 1484 | } |
| 1485 | return try group(a, node, kids); |
| 1486 | } |
| 1487 | |
| 1488 | /// Format the arguments of a call. |
| 1489 | /// |
| 1490 | /// When the arguments do not fit on the line of the call, a last record or |
| 1491 | /// array literal, or a call, opens on that line after the other arguments, as |
| 1492 | /// in `f(x, Entry {`, if the line fits. A last call that is the only argument |
| 1493 | /// also hugs when it is wrapped in an operator or `try`. Arguments that the |
| 1494 | /// source broke are never flat: they hug, or go on lines of their own. |
| 1495 | fn callArgs( |
| 1496 | a: &heap::Heap, |
| 1497 | p: &mut Printer, |
| 1498 | node: *ast::Node, |
| 1499 | args: *[*ast::Node] |
| 1500 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1501 | let used = p.used; |
| 1502 | let forced = marked(p, node, ast::BrokenSite::List); |
| 1503 | let list = try plainList(a, p, parens(node), args, Ctx::Normal, expr); |
| 1504 | // Comments in the list break it, and items that the source put one per |
| 1505 | // line leave nothing to hug. |
| 1506 | if args.len == 0 |
| 1507 | or p.used <> used |
| 1508 | or marked(p, node, ast::BrokenSite::Items) |
| 1509 | { |
| 1510 | return try forceBroken(a, list, forced); |
| 1511 | } |
| 1512 | let last = args[args.len - 1]; |
| 1513 | let call = hasArgs(last); |
| 1514 | if not call |
| 1515 | and not endsDelimited(last) |
| 1516 | and not (args.len == 1 and closesItself(last)) |
| 1517 | { |
| 1518 | return try forceBroken(a, list, forced); |
| 1519 | } |
| 1520 | // A list is broken when an item has a broken part. |
| 1521 | let case layout::Item::Box(kids) = unbroken(list).item else { |
| 1522 | panic "callArgs: list is not a box"; |
| 1523 | }; |
| 1524 | let case layout::Item::Box(items) = unbroken(kids[1].layout).item else { |
| 1525 | panic "callArgs: list items are not a box"; |
| 1526 | }; |
| 1527 | let mut tail = items[items.len - 1]; |
| 1528 | if call { |
| 1529 | set tail.layout = try openedCall(a, tail.layout); |
| 1530 | } else { |
| 1531 | set tail.layout = try broken(a, tail.layout); |
| 1532 | } |
| 1533 | let mut hug: *mut [layout::Child] = &mut []; |
| 1534 | for i in 0 .. items.len - 1 { |
| 1535 | try hug.append(items[i], a); |
| 1536 | } |
| 1537 | try hug.append(tail, a); |
| 1538 | let opened = try row(a, &[kids[0].layout, try flatGroup(a, nil, hug), kids[2].layout]); |
| 1539 | |
| 1540 | if forced { |
| 1541 | return try choice(a, nil, &[opened, try broken(a, list)]); |
| 1542 | } |
| 1543 | return try choice(a, nil, &[list, opened, list]); |
| 1544 | } |
| 1545 | |
| 1546 | /// The box that a broken layout wraps, or the layout itself. |
| 1547 | fn unbroken(l: *layout::Layout) -> *layout::Layout { |
| 1548 | if let case layout::Item::Broken(inner) = l.item { |
| 1549 | return inner; |
| 1550 | } |
| 1551 | return l; |
| 1552 | } |
| 1553 | |
| 1554 | /// Whether an expression is a call with arguments. |
| 1555 | fn hasArgs(node: *ast::Node) -> bool { |
| 1556 | match node.value { |
| 1557 | case ast::NodeValue::Call(call) => return call.args.len > 0, |
| 1558 | case ast::NodeValue::BuiltinCall { args, .. } => return args.len > 0, |
| 1559 | else => return false, |
| 1560 | } |
| 1561 | } |
| 1562 | |
| 1563 | /// Whether a layout has a broken part, in the form that a renderer measures: |
| 1564 | /// the first alternative of a choice. |
| 1565 | fn hasBroken(l: *layout::Layout) -> bool { |
| 1566 | return l.broken; |
| 1567 | } |
| 1568 | |
| 1569 | /// Layout of the call `l`, a call with arguments that is the last argument of |
| 1570 | /// another call, broken after its opening parenthesis. |
| 1571 | /// |
| 1572 | /// Its arguments go on one indented line if they fit there. Otherwise they |
| 1573 | /// hug a last record or call as the call alone would, and when that line does |
| 1574 | /// not fit either, they go one per line. |
| 1575 | fn openedCall( |
| 1576 | a: &heap::Heap, l: *layout::Layout |
| 1577 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1578 | let case layout::Item::Box(parts) = unbroken(l).item else { |
| 1579 | panic "openedCall: call is not a box"; |
| 1580 | }; |
| 1581 | // The arguments are a list, alone or broken, or a choice between the list |
| 1582 | // with its hugged form before it. The list is the last alternative. |
| 1583 | let args = parts[parts.len - 1].layout; |
| 1584 | let mut flat = args; |
| 1585 | let mut hug: ?*layout::Layout = nil; |
| 1586 | if let case layout::Item::Choice(choices) = args.item { |
| 1587 | set flat = choices[choices.len - 1]; |
| 1588 | set hug = choices[choices.len - 2]; |
| 1589 | } |
| 1590 | let case layout::Item::Box(list) = unbroken(flat).item else { |
| 1591 | panic "openedCall: arguments are not a box"; |
| 1592 | }; |
| 1593 | // The closing parenthesis follows the arguments, on their line when they |
| 1594 | // hug, and on its own line otherwise. |
| 1595 | let mut lines: *mut [layout::Child] = &mut []; |
| 1596 | try add(a, &mut lines, layout::Placement::Indent, list[1].layout); |
| 1597 | try add(a, &mut lines, layout::Placement::Line, list[2].layout); |
| 1598 | let stacked = try flatGroup(a, nil, lines); |
| 1599 | let mut rest = stacked; |
| 1600 | if let alt = hug { |
| 1601 | let case layout::Item::Box(opened) = alt.item else { |
| 1602 | panic "openedCall: hugged arguments are not a box"; |
| 1603 | }; |
| 1604 | let hugged = try row(a, &[opened[1].layout, opened[2].layout]); |
| 1605 | // Arguments with a broken part do not fit on one line. |
| 1606 | if hasBroken(list[1].layout) { |
| 1607 | set rest = try choice(a, nil, &[hugged, stacked]); |
| 1608 | } else { |
| 1609 | set rest = try choice(a, nil, &[stacked, hugged, stacked]); |
| 1610 | } |
| 1611 | } |
| 1612 | let mut copy: *mut [layout::Child] = &mut []; |
| 1613 | for i in 0 .. parts.len - 1 { |
| 1614 | try copy.append(parts[i], a); |
| 1615 | } |
| 1616 | let open = try row(a, &[list[0].layout, rest]); |
| 1617 | try add(a, &mut copy, parts[parts.len - 1].placement, open); |
| 1618 | |
| 1619 | return try broken(a, try flatGroup(a, l.source, copy)); |
| 1620 | } |
| 1621 | |
| 1622 | /// Format a field of a record literal: `name: value`, or `name` when the |
| 1623 | /// value is the name itself. |
| 1624 | fn recordLitField( |
| 1625 | a: &heap::Heap, p: &mut Printer, node: *ast::Node, ctx: Ctx |
| 1626 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1627 | let case ast::NodeValue::RecordLitField(arg) = node.value else { |
| 1628 | panic "recordLitField: not a record literal field"; |
| 1629 | }; |
| 1630 | let label = arg.label else { |
| 1631 | panic "recordLitField: field has no label"; |
| 1632 | }; |
| 1633 | if arg.value == label { |
| 1634 | return try expr(a, p, label, Ctx::Normal); |
| 1635 | } |
| 1636 | let mut kids: *mut [layout::Child] = &mut []; |
| 1637 | try put(a, p, &mut kids, NONE, label, Ctx::Normal); |
| 1638 | try punct(a, &mut kids, NONE, ":"); |
| 1639 | try put(a, p, &mut kids, SPACE, arg.value, ctx); |
| 1640 | |
| 1641 | return try group(a, node, kids); |
| 1642 | } |
| 1643 | |
| 1644 | // Types ////////////////////////////////////////////////////////////////////// |
| 1645 | |
| 1646 | /// Prefix of a pointer-like type: its ownership class and mutability. |
| 1647 | fn pointerPrefix(class: types::PointerClass, mutable: bool) -> *[u8] { |
| 1648 | match class { |
| 1649 | case types::PointerClass::Owned => return "*mut " if mutable else "*", |
| 1650 | case types::PointerClass::Ref => return "&mut " if mutable else "&", |
| 1651 | case types::PointerClass::Unsafe => |
| 1652 | return "*unsafe mut " if mutable else "*unsafe ", |
| 1653 | } |
| 1654 | } |
| 1655 | |
| 1656 | /// Append a region name, eg. `'r`. |
| 1657 | fn regionName( |
| 1658 | a: &heap::Heap, |
| 1659 | p: &mut Printer, |
| 1660 | kids: &mut *mut [layout::Child], |
| 1661 | at: layout::Placement, |
| 1662 | region: *ast::Node |
| 1663 | ) throws (alloc::AllocError) { |
| 1664 | try put(a, p, kids, at, region, Ctx::Normal); |
| 1665 | } |
| 1666 | |
| 1667 | /// Append bracketed parameters or arguments when present. |
| 1668 | fn typeList( |
| 1669 | a: &heap::Heap, |
| 1670 | p: &mut Printer, |
| 1671 | kids: &mut *mut [layout::Child], |
| 1672 | items: *[*ast::Node] |
| 1673 | ) throws (alloc::AllocError) { |
| 1674 | if items.len == 0 { |
| 1675 | return; |
| 1676 | } |
| 1677 | try punct(a, kids, NONE, "["); |
| 1678 | for item, i in items { |
| 1679 | try put(a, p, kids, NONE if i == 0 else SPACE, item, Ctx::Normal); |
| 1680 | if i + 1 < items.len { |
| 1681 | try punct(a, kids, NONE, ","); |
| 1682 | } |
| 1683 | } |
| 1684 | try punct(a, kids, NONE, "]"); |
| 1685 | } |
| 1686 | |
| 1687 | /// Append the prefix of a pointer-like type, and return the placement of the |
| 1688 | /// type that follows it. A region separates `&` from the rest by a space. |
| 1689 | fn pointerHead( |
| 1690 | a: &heap::Heap, |
| 1691 | p: &mut Printer, |
| 1692 | kids: &mut *mut [layout::Child], |
| 1693 | class: types::PointerClass, |
| 1694 | mutable: bool, |
| 1695 | region: ?*ast::Node |
| 1696 | ) -> layout::Placement throws (alloc::AllocError) { |
| 1697 | let r = region else { |
| 1698 | try operator(a, kids, NONE, pointerPrefix(class, mutable)); |
| 1699 | return NONE; |
| 1700 | }; |
| 1701 | try operator(a, kids, NONE, "&"); |
| 1702 | try regionName(a, p, kids, NONE, r); |
| 1703 | if mutable { |
| 1704 | try keyword(a, kids, SPACE, "mut"); |
| 1705 | } |
| 1706 | return SPACE; |
| 1707 | } |
| 1708 | |
| 1709 | /// Format the result of a function type: `-> T` and `throws (E)`. |
| 1710 | fn signatureTail( |
| 1711 | a: &heap::Heap, |
| 1712 | p: &mut Printer, |
| 1713 | kids: &mut *mut [layout::Child], |
| 1714 | sig: &ast::FnSig, |
| 1715 | forced: bool |
| 1716 | ) throws (alloc::AllocError) { |
| 1717 | if let returnType = sig.returnType { |
| 1718 | try operator(a, kids, SPACE, "->"); |
| 1719 | try put(a, p, kids, SPACE, returnType, Ctx::Normal); |
| 1720 | } |
| 1721 | if sig.throwList.len > 0 { |
| 1722 | let mut clause: *mut [layout::Child] = &mut []; |
| 1723 | let mut spec = parens(nil); |
| 1724 | set spec.forced = forced; |
| 1725 | try keyword(a, &mut clause, NONE, "throws"); |
| 1726 | try add( |
| 1727 | a, |
| 1728 | &mut clause, |
| 1729 | SPACE, |
| 1730 | try softList(a, p, spec, sig.throwList, Ctx::Normal, expr) |
| 1731 | ); |
| 1732 | try add(a, kids, SOFT_INDENT_SPACE, try group(a, nil, clause)); |
| 1733 | } |
| 1734 | } |
| 1735 | |
| 1736 | /// Format a type signature node. |
| 1737 | fn typeSig( |
| 1738 | a: &heap::Heap, |
| 1739 | p: &mut Printer, |
| 1740 | node: *ast::Node, |
| 1741 | sig: ast::TypeSig |
| 1742 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1743 | let mut kids: *mut [layout::Child] = &mut []; |
| 1744 | match sig { |
| 1745 | case ast::TypeSig::Void => panic "typeSig: void has no source form", |
| 1746 | case ast::TypeSig::Never => |
| 1747 | return try leaf(a, node, "!", layout::Role::Keyword), |
| 1748 | case ast::TypeSig::Opaque => |
| 1749 | return try leaf(a, node, "opaque", layout::Role::Keyword), |
| 1750 | case ast::TypeSig::Bool => |
| 1751 | return try leaf(a, node, "bool", layout::Role::Keyword), |
| 1752 | case ast::TypeSig::Integer { width, sign } => |
| 1753 | return try leaf( |
| 1754 | a, node, ast::integerName(width, sign), layout::Role::Keyword |
| 1755 | ), |
| 1756 | case ast::TypeSig::Array { itemType, length } => { |
| 1757 | try punct(a, &mut kids, NONE, "["); |
| 1758 | try put(a, p, &mut kids, NONE, itemType, Ctx::Normal); |
| 1759 | try punct(a, &mut kids, NONE, ";"); |
| 1760 | try put(a, p, &mut kids, SPACE, length, Ctx::Normal); |
| 1761 | try punct(a, &mut kids, NONE, "]"); |
| 1762 | } |
| 1763 | case ast::TypeSig::Slice { class, itemType, mutable, region } => { |
| 1764 | let at = try pointerHead(a, p, &mut kids, class, mutable, region); |
| 1765 | try punct(a, &mut kids, at, "["); |
| 1766 | try put(a, p, &mut kids, NONE, itemType, Ctx::Normal); |
| 1767 | try punct(a, &mut kids, NONE, "]"); |
| 1768 | } |
| 1769 | case ast::TypeSig::Pointer { class, valueType, mutable, region } => { |
| 1770 | let at = try pointerHead(a, p, &mut kids, class, mutable, region); |
| 1771 | try put(a, p, &mut kids, at, valueType, Ctx::Normal); |
| 1772 | } |
| 1773 | case ast::TypeSig::Optional { valueType } => { |
| 1774 | try operator(a, &mut kids, NONE, "?"); |
| 1775 | try put(a, p, &mut kids, NONE, valueType, Ctx::Normal); |
| 1776 | } |
| 1777 | case ast::TypeSig::Nominal { path, args } => { |
| 1778 | if args.len == 0 { |
| 1779 | return try expr(a, p, path, Ctx::Normal); |
| 1780 | } |
| 1781 | try put(a, p, &mut kids, NONE, path, Ctx::Normal); |
| 1782 | try typeList(a, p, &mut kids, args); |
| 1783 | } |
| 1784 | case ast::TypeSig::Record { .. } => |
| 1785 | panic "typeSig: record type outside a variant", |
| 1786 | case ast::TypeSig::Fn { sig: fnSig, isUnsafe } => { |
| 1787 | if isUnsafe { |
| 1788 | try keyword(a, &mut kids, NONE, "unsafe"); |
| 1789 | } |
| 1790 | try keyword(a, &mut kids, NONE if not isUnsafe else SPACE, "fn"); |
| 1791 | try add( |
| 1792 | a, |
| 1793 | &mut kids, |
| 1794 | NONE, |
| 1795 | try softList( |
| 1796 | a, p, parens(node), fnSig.params, Ctx::Normal, expr |
| 1797 | ) |
| 1798 | ); |
| 1799 | let thrown = marked(p, node, ast::BrokenSite::Throws); |
| 1800 | try signatureTail(a, p, &mut kids, &fnSig, thrown); |
| 1801 | } |
| 1802 | case ast::TypeSig::TraitObject { class, traitName, mutable } => { |
| 1803 | try operator(a, &mut kids, NONE, pointerPrefix(class, mutable)); |
| 1804 | try keyword(a, &mut kids, NONE, "opaque"); |
| 1805 | try put(a, p, &mut kids, SPACE, traitName, Ctx::Normal); |
| 1806 | } |
| 1807 | } |
| 1808 | return try group(a, node, kids); |
| 1809 | } |
| 1810 | |
| 1811 | // Statements ///////////////////////////////////////////////////////////////// |
| 1812 | |
| 1813 | /// Append a text child after a space, or first in the box. |
| 1814 | fn spaced( |
| 1815 | a: &heap::Heap, |
| 1816 | kids: &mut *mut [layout::Child], |
| 1817 | text: *[u8], |
| 1818 | role: layout::Role |
| 1819 | ) throws (alloc::AllocError) { |
| 1820 | let at = NONE if kids.len == 0 else SPACE; |
| 1821 | try word(a, kids, at, text, role); |
| 1822 | } |
| 1823 | |
| 1824 | /// Append the attributes of a declaration, in source order. |
| 1825 | fn attributes( |
| 1826 | a: &heap::Heap, |
| 1827 | kids: &mut *mut [layout::Child], |
| 1828 | attrs: ?ast::Attributes |
| 1829 | ) throws (alloc::AllocError) { |
| 1830 | let list = attrs else { |
| 1831 | return; |
| 1832 | }; |
| 1833 | for attr in list.list { |
| 1834 | let case ast::NodeValue::Attribute(kind) = attr.value else { |
| 1835 | panic "attributes: attribute expected"; |
| 1836 | }; |
| 1837 | match kind { |
| 1838 | case ast::Attribute::Export => |
| 1839 | try spaced(a, kids, "export", layout::Role::Keyword), |
| 1840 | case ast::Attribute::Unsafe => |
| 1841 | try spaced(a, kids, "unsafe", layout::Role::Keyword), |
| 1842 | case ast::Attribute::Opaque => |
| 1843 | try spaced(a, kids, "opaque", layout::Role::Keyword), |
| 1844 | case ast::Attribute::Default => |
| 1845 | try spaced(a, kids, "@default", layout::Role::Keyword), |
| 1846 | case ast::Attribute::Test => |
| 1847 | try spaced(a, kids, "@test", layout::Role::Keyword), |
| 1848 | case ast::Attribute::Intrinsic => |
| 1849 | try spaced(a, kids, "@intrinsic", layout::Role::Keyword), |
| 1850 | case ast::Attribute::Language => |
| 1851 | try spaced(a, kids, "@language", layout::Role::Keyword), |
| 1852 | case ast::Attribute::Constant => |
| 1853 | try spaced(a, kids, "constant", layout::Role::Keyword), |
| 1854 | case ast::Attribute::Extern => {} |
| 1855 | } |
| 1856 | } |
| 1857 | } |
| 1858 | |
| 1859 | /// Whether a braced body has no items and no comments. |
| 1860 | fn isEmpty(p: &Printer, count: u32, container: *ast::Node) -> bool { |
| 1861 | if count > 0 { |
| 1862 | return false; |
| 1863 | } |
| 1864 | for t in entries(p, container, ast::TriviaPlacement::Closing) { |
| 1865 | if let case ast::TriviaKind::Comment(_) = t.kind { |
| 1866 | return false; |
| 1867 | } |
| 1868 | } |
| 1869 | return true; |
| 1870 | } |
| 1871 | |
| 1872 | /// Text of the opening brace of a body. An empty body is `{}`. |
| 1873 | fn brace(p: &Printer, count: u32, container: *ast::Node) -> *[u8] { |
| 1874 | return "{}" if isEmpty(p, count, container) else "{"; |
| 1875 | } |
| 1876 | |
| 1877 | /// Append the items of a braced body, one per line, and the closing brace. |
| 1878 | fn body( |
| 1879 | a: &heap::Heap, |
| 1880 | p: &mut Printer, |
| 1881 | kids: &mut *mut [layout::Child], |
| 1882 | items: *[*ast::Node], |
| 1883 | container: *ast::Node, |
| 1884 | format: fn( |
| 1885 | &heap::Heap, &mut Printer, *ast::Node |
| 1886 | ) -> *layout::Layout |
| 1887 | throws (alloc::AllocError) |
| 1888 | ) throws (alloc::AllocError) { |
| 1889 | try lines(a, p, kids, items, container, layout::Placement::Indent, format); |
| 1890 | if not isEmpty(p, items.len, container) { |
| 1891 | try punct(a, kids, layout::Placement::Line, "}"); |
| 1892 | } |
| 1893 | } |
| 1894 | |
| 1895 | /// Append the braced statements of a block, with the brace placed at `at`. |
| 1896 | fn blockBody( |
| 1897 | a: &heap::Heap, |
| 1898 | p: &mut Printer, |
| 1899 | kids: &mut *mut [layout::Child], |
| 1900 | blk: *ast::Node, |
| 1901 | at: layout::Placement |
| 1902 | ) throws (alloc::AllocError) { |
| 1903 | let case ast::NodeValue::Block(b) = blk.value else { |
| 1904 | panic "blockBody: block expected"; |
| 1905 | }; |
| 1906 | try punct(a, kids, at, brace(p, b.statements.len, blk)); |
| 1907 | try body(a, p, kids, b.statements, blk, stmt); |
| 1908 | } |
| 1909 | |
| 1910 | /// Format a statement, with its `;` when it needs one. |
| 1911 | fn stmt( |
| 1912 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 1913 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1914 | let core = try stmtCore(a, p, node); |
| 1915 | if not ast::needsSemicolon(node) { |
| 1916 | return core; |
| 1917 | } |
| 1918 | let mut kids: *mut [layout::Child] = &mut []; |
| 1919 | try add(a, &mut kids, NONE, core); |
| 1920 | try punct(a, &mut kids, NONE, ";"); |
| 1921 | |
| 1922 | return try group(a, node, kids); |
| 1923 | } |
| 1924 | |
| 1925 | /// Format a statement without its `;`. Expressions format as themselves. |
| 1926 | fn stmtCore( |
| 1927 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 1928 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 1929 | let mut kids: *mut [layout::Child] = &mut []; |
| 1930 | match node.value { |
| 1931 | case ast::NodeValue::ExprStmt(e) => |
| 1932 | return try expr(a, p, e, Ctx::Normal), |
| 1933 | case ast::NodeValue::Let(l) => { |
| 1934 | try spaced(a, &mut kids, "let", layout::Role::Keyword); |
| 1935 | if l.mutable { |
| 1936 | try spaced(a, &mut kids, "mut", layout::Role::Keyword); |
| 1937 | } |
| 1938 | try put(a, p, &mut kids, SPACE, l.ident, Ctx::Normal); |
| 1939 | if let type = l.type { |
| 1940 | try punct(a, &mut kids, NONE, ":"); |
| 1941 | try put(a, p, &mut kids, SPACE, type, Ctx::Normal); |
| 1942 | } |
| 1943 | if let alignment = l.alignment { |
| 1944 | try put(a, p, &mut kids, SPACE, alignment, Ctx::Normal); |
| 1945 | } |
| 1946 | try assigned(a, p, &mut kids, node, "=", l.value); |
| 1947 | } |
| 1948 | case ast::NodeValue::LetElse(l) => { |
| 1949 | let mut head: *mut [layout::Child] = &mut []; |
| 1950 | try patternMatch(a, p, &mut head, &l.pattern, GuardStyle::If); |
| 1951 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 1952 | if let case ast::NodeValue::Block(b) = l.elseBranch.value; not b.isUnsafe { |
| 1953 | try keyword(a, &mut kids, SPACE, "else"); |
| 1954 | try blockBody(a, p, &mut kids, l.elseBranch, SPACE); |
| 1955 | } else { |
| 1956 | // A statement branch follows the value when it fits, and |
| 1957 | // moves to its own line with `else` otherwise. The pattern |
| 1958 | // stays whole when it fits. |
| 1959 | let mut other: *mut [layout::Child] = &mut []; |
| 1960 | try keyword(a, &mut other, NONE, "else"); |
| 1961 | try add(a, &mut other, SPACE, try stmtCore(a, p, l.elseBranch)); |
| 1962 | let branch = try group(a, nil, other); |
| 1963 | try add(a, &mut kids, NONE, try sameOrNext(a, branch)); |
| 1964 | } |
| 1965 | } |
| 1966 | case ast::NodeValue::Assign(asg) => { |
| 1967 | try spaced(a, &mut kids, "set", layout::Role::Keyword); |
| 1968 | try put(a, p, &mut kids, SPACE, asg.left, Ctx::Normal); |
| 1969 | let mut op: *[u8] = "="; |
| 1970 | let mut value = asg.right; |
| 1971 | if let case ast::NodeValue::BinOp(bin) = asg.right.value; bin.left == asg.left { |
| 1972 | if let text = compoundText(bin.op) { |
| 1973 | set op = text; |
| 1974 | set value = bin.right; |
| 1975 | } |
| 1976 | } |
| 1977 | try assigned(a, p, &mut kids, node, op, value); |
| 1978 | } |
| 1979 | case ast::NodeValue::Return { value } => { |
| 1980 | try spaced(a, &mut kids, "return", layout::Role::Keyword); |
| 1981 | if let v = value { |
| 1982 | try put(a, p, &mut kids, SPACE, v, Ctx::Normal); |
| 1983 | } |
| 1984 | } |
| 1985 | case ast::NodeValue::Throw { expr: thrown } => { |
| 1986 | try spaced(a, &mut kids, "throw", layout::Role::Keyword); |
| 1987 | try put(a, p, &mut kids, SPACE, thrown, Ctx::Normal); |
| 1988 | } |
| 1989 | case ast::NodeValue::Panic { message } => { |
| 1990 | try spaced(a, &mut kids, "panic", layout::Role::Keyword); |
| 1991 | if let m = message { |
| 1992 | try put(a, p, &mut kids, SPACE, m, Ctx::Normal); |
| 1993 | } |
| 1994 | } |
| 1995 | case ast::NodeValue::Assert { condition, message } => { |
| 1996 | try spaced(a, &mut kids, "assert", layout::Role::Keyword); |
| 1997 | try put(a, p, &mut kids, SPACE, condition, Ctx::Normal); |
| 1998 | if let m = message { |
| 1999 | try punct(a, &mut kids, NONE, ","); |
| 2000 | try put(a, p, &mut kids, SOFT_INDENT_SPACE, m, Ctx::Normal); |
| 2001 | } |
| 2002 | } |
| 2003 | case ast::NodeValue::Break => |
| 2004 | return try leaf(a, node, "break", layout::Role::Keyword), |
| 2005 | case ast::NodeValue::Continue => |
| 2006 | return try leaf(a, node, "continue", layout::Role::Keyword), |
| 2007 | case ast::NodeValue::ConstDecl(c) => { |
| 2008 | try attributes(a, &mut kids, c.attrs); |
| 2009 | try storage( |
| 2010 | a, p, &mut kids, node, "constant", c.ident, c.type, c.value |
| 2011 | ); |
| 2012 | } |
| 2013 | case ast::NodeValue::StaticDecl(d) => { |
| 2014 | try attributes(a, &mut kids, d.attrs); |
| 2015 | try storage( |
| 2016 | a, p, &mut kids, node, "static", d.ident, d.type, d.value |
| 2017 | ); |
| 2018 | } |
| 2019 | case ast::NodeValue::Mod(m) => { |
| 2020 | try attributes(a, &mut kids, m.attrs); |
| 2021 | try spaced(a, &mut kids, "mod", layout::Role::Keyword); |
| 2022 | try put(a, p, &mut kids, SPACE, m.name, Ctx::Normal); |
| 2023 | } |
| 2024 | case ast::NodeValue::Use(u) => { |
| 2025 | try attributes(a, &mut kids, u.attrs); |
| 2026 | try spaced(a, &mut kids, "use", layout::Role::Keyword); |
| 2027 | try put(a, p, &mut kids, SPACE, u.path, Ctx::Normal); |
| 2028 | if u.wildcard { |
| 2029 | try punct(a, &mut kids, NONE, "::*"); |
| 2030 | } |
| 2031 | } |
| 2032 | case ast::NodeValue::Block(b) => { |
| 2033 | // A borrow block prints as its binding followed by its body. |
| 2034 | if ast::isBorrowBlock(b) { |
| 2035 | try add(a, &mut kids, NONE, try stmtCore(a, p, b.statements[0])); |
| 2036 | try blockBody(a, p, &mut kids, b.statements[1], SPACE); |
| 2037 | } else if b.isUnsafe { |
| 2038 | try spaced(a, &mut kids, "unsafe", layout::Role::Keyword); |
| 2039 | try blockBody(a, p, &mut kids, node, SPACE); |
| 2040 | } else { |
| 2041 | try blockBody(a, p, &mut kids, node, NONE); |
| 2042 | } |
| 2043 | } |
| 2044 | case ast::NodeValue::If(_), ast::NodeValue::IfLet(_) => |
| 2045 | return try ifStmt(a, p, node), |
| 2046 | case |
| 2047 | ast::NodeValue::While(_), |
| 2048 | ast::NodeValue::WhileLet(_), |
| 2049 | ast::NodeValue::For(_), |
| 2050 | ast::NodeValue::Loop { .. } => |
| 2051 | return try loopStmt(a, p, node), |
| 2052 | case ast::NodeValue::Match(m) => { |
| 2053 | let mut head: *mut [layout::Child] = &mut []; |
| 2054 | try spaced(a, &mut head, "match", layout::Role::Keyword); |
| 2055 | try put(a, p, &mut head, SPACE, m.subject, Ctx::Condition); |
| 2056 | try punct( |
| 2057 | a, |
| 2058 | &mut head, |
| 2059 | bracePlacement(m.subject), |
| 2060 | brace(p, m.prongs.len, node) |
| 2061 | ); |
| 2062 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2063 | try body(a, p, &mut kids, m.prongs, node, prong); |
| 2064 | } |
| 2065 | case |
| 2066 | ast::NodeValue::FnDecl(_), |
| 2067 | ast::NodeValue::MethodDecl { .. }, |
| 2068 | ast::NodeValue::TraitMethodSig { .. } => |
| 2069 | return try fnDecl(a, p, node), |
| 2070 | case |
| 2071 | ast::NodeValue::RecordDecl(_), |
| 2072 | ast::NodeValue::UnionDecl(_), |
| 2073 | ast::NodeValue::TraitDecl { .. }, |
| 2074 | ast::NodeValue::InstanceDecl { .. } => |
| 2075 | return try typeDecl(a, p, node), |
| 2076 | else => return try expr(a, p, node, Ctx::Normal), |
| 2077 | } |
| 2078 | return try group(a, node, kids); |
| 2079 | } |
| 2080 | |
| 2081 | /// Append an assignment operator and its value, for the statement `owner`. |
| 2082 | /// |
| 2083 | /// A value that the source put on a line of its own after the operator stays |
| 2084 | /// there. A value that opens a list stays on the line of the operator unless |
| 2085 | /// even its first line does not fit there. An operation moves to the next line |
| 2086 | /// when it fits there flat, and otherwise stays on the line of the operator |
| 2087 | /// when its first line fits. Other values, such as long strings and names, |
| 2088 | /// move to the next line when they do not fit. |
| 2089 | fn assigned( |
| 2090 | a: &heap::Heap, |
| 2091 | p: &mut Printer, |
| 2092 | kids: &mut *mut [layout::Child], |
| 2093 | owner: *ast::Node, |
| 2094 | op: *[u8], |
| 2095 | value: *ast::Node |
| 2096 | ) throws (alloc::AllocError) { |
| 2097 | try operator(a, kids, SPACE, op); |
| 2098 | if takeMark(p, owner, ast::BrokenSite::Value) { |
| 2099 | try put(a, p, kids, layout::Placement::Indent, value, Ctx::Normal); |
| 2100 | return; |
| 2101 | } |
| 2102 | let operation = isOperation(value); |
| 2103 | if not operation and not closesItself(value) and not endsDelimited(value) { |
| 2104 | try put(a, p, kids, valuePlacement(value), value, Ctx::Normal); |
| 2105 | return; |
| 2106 | } |
| 2107 | let v = try expr(a, p, value, Ctx::Normal); |
| 2108 | let same = try placed(a, SPACE, v); |
| 2109 | let opened = try placed(a, SPACE, try broken(a, v)); |
| 2110 | let next = try placed(a, layout::Placement::Indent, v); |
| 2111 | let mut values = try choice(a, value, &[same, opened, next]); |
| 2112 | if operation { |
| 2113 | set values = try choice(a, value, &[same, next, opened, next]); |
| 2114 | } |
| 2115 | try add(a, kids, NONE, values); |
| 2116 | } |
| 2117 | |
| 2118 | /// Whether an expression is a binary or conditional operation. |
| 2119 | fn isOperation(node: *ast::Node) -> bool { |
| 2120 | match node.value { |
| 2121 | case ast::NodeValue::BinOp(_), ast::NodeValue::CondExpr(_) => |
| 2122 | return true, |
| 2123 | else => return false, |
| 2124 | } |
| 2125 | } |
| 2126 | |
| 2127 | /// Append the name, type, and value of a `constant` or `static` declaration. |
| 2128 | fn storage( |
| 2129 | a: &heap::Heap, |
| 2130 | p: &mut Printer, |
| 2131 | kids: &mut *mut [layout::Child], |
| 2132 | owner: *ast::Node, |
| 2133 | word: *[u8], |
| 2134 | ident: *ast::Node, |
| 2135 | type: *ast::Node, |
| 2136 | value: *ast::Node |
| 2137 | ) throws (alloc::AllocError) { |
| 2138 | try spaced(a, kids, word, layout::Role::Keyword); |
| 2139 | try put(a, p, kids, SPACE, ident, Ctx::Normal); |
| 2140 | try punct(a, kids, NONE, ":"); |
| 2141 | try put(a, p, kids, SPACE, type, Ctx::Normal); |
| 2142 | try assigned(a, p, kids, owner, "=", value); |
| 2143 | } |
| 2144 | |
| 2145 | /// Whether an expression breaks at its own delimiters, so that what follows it |
| 2146 | /// stays after its closing delimiter. |
| 2147 | fn closesItself(node: *ast::Node) -> bool { |
| 2148 | match node.value { |
| 2149 | case |
| 2150 | ast::NodeValue::Call(_), |
| 2151 | ast::NodeValue::BuiltinCall { .. }, |
| 2152 | ast::NodeValue::ArrayLit(_) => |
| 2153 | return true, |
| 2154 | case ast::NodeValue::UnOp(un) => return closesItself(un.value), |
| 2155 | case ast::NodeValue::AddressOf(addr) => |
| 2156 | return closesItself(addr.target), |
| 2157 | case ast::NodeValue::Deref(target) => return closesItself(target), |
| 2158 | case ast::NodeValue::Try(t) => |
| 2159 | return t.catches.len == 0 and closesItself(t.expr), |
| 2160 | else => return false, |
| 2161 | } |
| 2162 | } |
| 2163 | |
| 2164 | /// Whether an expression ends with a record or array literal. |
| 2165 | fn endsDelimited(node: *ast::Node) -> bool { |
| 2166 | match node.value { |
| 2167 | case ast::NodeValue::RecordLit(_), ast::NodeValue::ArrayLit(_) => |
| 2168 | return true, |
| 2169 | case ast::NodeValue::AddressOf(addr) => |
| 2170 | return endsDelimited(addr.target), |
| 2171 | else => return false, |
| 2172 | } |
| 2173 | } |
| 2174 | |
| 2175 | /// Placement of the value after `=`. |
| 2176 | fn valuePlacement(value: *ast::Node) -> layout::Placement { |
| 2177 | if closesItself(value) { |
| 2178 | return SPACE; |
| 2179 | } |
| 2180 | match value.value { |
| 2181 | case |
| 2182 | ast::NodeValue::RecordLit(_), |
| 2183 | ast::NodeValue::BinOp(_), |
| 2184 | ast::NodeValue::CondExpr(_), |
| 2185 | ast::NodeValue::Try(_) => |
| 2186 | return SPACE, |
| 2187 | else => return SOFT_INDENT_SPACE, |
| 2188 | } |
| 2189 | } |
| 2190 | |
| 2191 | /// Placement of the brace after a header that ends with `last`. |
| 2192 | /// |
| 2193 | /// A call or array literal breaks at its own delimiters, so the brace follows |
| 2194 | /// its closing delimiter. After other expressions, the brace moves to its own |
| 2195 | /// line when the header breaks. |
| 2196 | fn bracePlacement(last: *ast::Node) -> layout::Placement { |
| 2197 | if closesItself(last) { |
| 2198 | return SPACE; |
| 2199 | } |
| 2200 | return SOFT_SPACE; |
| 2201 | } |
| 2202 | |
| 2203 | /// Placement of the brace after the pattern match of a header. A guard breaks |
| 2204 | /// the header before it, so the brace then goes on its own line. |
| 2205 | fn patternBrace(pm: &ast::PatternMatch) -> layout::Placement { |
| 2206 | if pm.guard <> nil { |
| 2207 | return SOFT_SPACE; |
| 2208 | } |
| 2209 | return bracePlacement(pm.scrutinee); |
| 2210 | } |
| 2211 | |
| 2212 | /// Append `let`, a pattern, `=`, and a value, as in `if let` and `let-else`. |
| 2213 | fn patternMatch( |
| 2214 | a: &heap::Heap, |
| 2215 | p: &mut Printer, |
| 2216 | kids: &mut *mut [layout::Child], |
| 2217 | pm: &ast::PatternMatch, |
| 2218 | style: GuardStyle |
| 2219 | ) throws (alloc::AllocError) { |
| 2220 | try spaced(a, kids, "let", layout::Role::Keyword); |
| 2221 | let mut ctx = Ctx::Condition; |
| 2222 | match pm.kind { |
| 2223 | case ast::PatternKind::Case => { |
| 2224 | try keyword(a, kids, SPACE, "case"); |
| 2225 | try put(a, p, kids, SPACE, pm.pattern, Ctx::Pattern); |
| 2226 | } |
| 2227 | case ast::PatternKind::Binding => { |
| 2228 | if pm.mutable { |
| 2229 | try keyword(a, kids, SPACE, "mut"); |
| 2230 | } |
| 2231 | try put(a, p, kids, SPACE, pm.pattern, Ctx::Normal); |
| 2232 | if style == GuardStyle::If { |
| 2233 | set ctx = Ctx::Normal; |
| 2234 | } |
| 2235 | } |
| 2236 | } |
| 2237 | try operator(a, kids, SPACE, "="); |
| 2238 | try put(a, p, kids, valuePlacement(pm.scrutinee), pm.scrutinee, ctx); |
| 2239 | if let guard = pm.guard { |
| 2240 | match style { |
| 2241 | case GuardStyle::Semicolon => { |
| 2242 | try punct(a, kids, NONE, ";"); |
| 2243 | try put(a, p, kids, SOFT_INDENT_SPACE, guard, Ctx::Condition); |
| 2244 | } |
| 2245 | case GuardStyle::If => { |
| 2246 | let mut test: *mut [layout::Child] = &mut []; |
| 2247 | try keyword(a, &mut test, NONE, "if"); |
| 2248 | try put(a, p, &mut test, SPACE, guard, Ctx::Condition); |
| 2249 | try add(a, kids, SOFT_INDENT_SPACE, try group(a, nil, test)); |
| 2250 | } |
| 2251 | } |
| 2252 | } |
| 2253 | } |
| 2254 | |
| 2255 | /// The nested `if` of an `else if`, if `blk` is the else branch of one. |
| 2256 | /// |
| 2257 | /// The parser makes `else if` a block that holds the nested `if`. A block that |
| 2258 | /// has the same shape, but trivia of its own, is not an `else if`. |
| 2259 | fn elseIf(p: &Printer, blk: *ast::Node) -> ?*ast::Node { |
| 2260 | let case ast::NodeValue::Block(b) = blk.value else { |
| 2261 | return nil; |
| 2262 | }; |
| 2263 | if b.isUnsafe or b.statements.len <> 1 { |
| 2264 | return nil; |
| 2265 | } |
| 2266 | let inner = b.statements[0]; |
| 2267 | if entries(p, blk, ast::TriviaPlacement::Closing).len > 0 |
| 2268 | or entries(p, inner, ast::TriviaPlacement::Leading).len > 0 |
| 2269 | or entries(p, inner, ast::TriviaPlacement::Trailing).len > 0 |
| 2270 | { |
| 2271 | return nil; |
| 2272 | } |
| 2273 | match inner.value { |
| 2274 | case ast::NodeValue::If(_), ast::NodeValue::IfLet(_) => return inner, |
| 2275 | else => return nil, |
| 2276 | } |
| 2277 | } |
| 2278 | |
| 2279 | /// Format an `if` or `if let` statement with its `else` branches. |
| 2280 | fn ifStmt( |
| 2281 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 2282 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2283 | let mut kids: *mut [layout::Child] = &mut []; |
| 2284 | let mut current = node; |
| 2285 | let mut chained = false; |
| 2286 | loop { |
| 2287 | let mut head: *mut [layout::Child] = &mut []; |
| 2288 | let mut thenBranch: *ast::Node = undefined; |
| 2289 | let mut elseBranch: ?*ast::Node = nil; |
| 2290 | let mut at = SOFT_SPACE; |
| 2291 | if chained { |
| 2292 | try spaced(a, &mut head, "else", layout::Role::Keyword); |
| 2293 | } |
| 2294 | try spaced(a, &mut head, "if", layout::Role::Keyword); |
| 2295 | match current.value { |
| 2296 | case ast::NodeValue::If(i) => { |
| 2297 | try put(a, p, &mut head, SPACE, i.condition, Ctx::Condition); |
| 2298 | set at = bracePlacement(i.condition); |
| 2299 | set thenBranch = i.thenBranch; |
| 2300 | set elseBranch = i.elseBranch; |
| 2301 | } |
| 2302 | case ast::NodeValue::IfLet(i) => { |
| 2303 | try patternMatch( |
| 2304 | a, p, &mut head, &i.pattern, GuardStyle::Semicolon |
| 2305 | ); |
| 2306 | set at = patternBrace(&i.pattern); |
| 2307 | set thenBranch = i.thenBranch; |
| 2308 | set elseBranch = i.elseBranch; |
| 2309 | } |
| 2310 | else => panic "ifStmt: if expected", |
| 2311 | } |
| 2312 | let case ast::NodeValue::Block(b) = thenBranch.value else { |
| 2313 | panic "ifStmt: block expected"; |
| 2314 | }; |
| 2315 | try punct( |
| 2316 | a, |
| 2317 | &mut head, |
| 2318 | at, |
| 2319 | brace(p, b.statements.len, thenBranch) |
| 2320 | ); |
| 2321 | try add( |
| 2322 | a, |
| 2323 | &mut kids, |
| 2324 | SPACE if chained else NONE, |
| 2325 | try group(a, current, head) |
| 2326 | ); |
| 2327 | try body(a, p, &mut kids, b.statements, thenBranch, stmt); |
| 2328 | |
| 2329 | let els = elseBranch else { |
| 2330 | break; |
| 2331 | }; |
| 2332 | if let nested = elseIf(p, els) { |
| 2333 | set current = nested; |
| 2334 | set chained = true; |
| 2335 | continue; |
| 2336 | } |
| 2337 | try keyword(a, &mut kids, SPACE, "else"); |
| 2338 | try blockBody(a, p, &mut kids, els, SPACE); |
| 2339 | break; |
| 2340 | } |
| 2341 | return try group(a, node, kids); |
| 2342 | } |
| 2343 | |
| 2344 | /// Format a `while`, `while let`, `for`, or `loop` statement with its `else` |
| 2345 | /// branch. |
| 2346 | fn loopStmt( |
| 2347 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 2348 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2349 | let mut head: *mut [layout::Child] = &mut []; |
| 2350 | let mut loopBody: *ast::Node = undefined; |
| 2351 | let mut elseBranch: ?*ast::Node = nil; |
| 2352 | let mut at = SOFT_SPACE; |
| 2353 | match node.value { |
| 2354 | case ast::NodeValue::While(w) => { |
| 2355 | try spaced(a, &mut head, "while", layout::Role::Keyword); |
| 2356 | try put(a, p, &mut head, SPACE, w.condition, Ctx::Condition); |
| 2357 | set at = bracePlacement(w.condition); |
| 2358 | set loopBody = w.body; |
| 2359 | set elseBranch = w.elseBranch; |
| 2360 | } |
| 2361 | case ast::NodeValue::WhileLet(w) => { |
| 2362 | try spaced(a, &mut head, "while", layout::Role::Keyword); |
| 2363 | try patternMatch(a, p, &mut head, &w.pattern, GuardStyle::Semicolon); |
| 2364 | set at = patternBrace(&w.pattern); |
| 2365 | set loopBody = w.body; |
| 2366 | set elseBranch = w.elseBranch; |
| 2367 | } |
| 2368 | case ast::NodeValue::For(f) => { |
| 2369 | try spaced(a, &mut head, "for", layout::Role::Keyword); |
| 2370 | try put(a, p, &mut head, SPACE, f.binding, Ctx::Normal); |
| 2371 | if let index = f.index { |
| 2372 | try punct(a, &mut head, NONE, ","); |
| 2373 | try put(a, p, &mut head, SPACE, index, Ctx::Normal); |
| 2374 | } |
| 2375 | try keyword(a, &mut head, SPACE, "in"); |
| 2376 | try put(a, p, &mut head, SPACE, f.iterable, Ctx::Condition); |
| 2377 | set at = bracePlacement(f.iterable); |
| 2378 | set loopBody = f.body; |
| 2379 | set elseBranch = f.elseBranch; |
| 2380 | } |
| 2381 | case ast::NodeValue::Loop { body: b } => { |
| 2382 | try spaced(a, &mut head, "loop", layout::Role::Keyword); |
| 2383 | set loopBody = b; |
| 2384 | } |
| 2385 | else => panic "loopStmt: loop expected", |
| 2386 | } |
| 2387 | let case ast::NodeValue::Block(b) = loopBody.value else { |
| 2388 | panic "loopStmt: block expected"; |
| 2389 | }; |
| 2390 | try punct( |
| 2391 | a, |
| 2392 | &mut head, |
| 2393 | at, |
| 2394 | brace(p, b.statements.len, loopBody) |
| 2395 | ); |
| 2396 | let mut kids: *mut [layout::Child] = &mut []; |
| 2397 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2398 | try body(a, p, &mut kids, b.statements, loopBody, stmt); |
| 2399 | if let els = elseBranch { |
| 2400 | try keyword(a, &mut kids, SPACE, "else"); |
| 2401 | try blockBody(a, p, &mut kids, els, SPACE); |
| 2402 | } |
| 2403 | return try group(a, node, kids); |
| 2404 | } |
| 2405 | |
| 2406 | /// Format a match prong. |
| 2407 | /// |
| 2408 | /// A block body follows `=>` on the same line. Another statement body ends |
| 2409 | /// with a comma, and goes to the next line when it does not fit, unless it |
| 2410 | /// ends with a block of its own. |
| 2411 | /// |
| 2412 | /// A prong with several patterns whose `case` line does not fit is stacked: |
| 2413 | /// `case` is alone on its line, each pattern follows on a line of its own one |
| 2414 | /// level deeper, and `=>` follows the last pattern. A guard stays on the line |
| 2415 | /// of the last pattern when it fits there, and goes on a line of its own at |
| 2416 | /// the depth of the patterns otherwise. A block body opens on a line of its |
| 2417 | /// own at the depth of `case`. Another body stays after `=>` when it fits |
| 2418 | /// there, and goes on the next line, one level deeper than `case`, otherwise. |
| 2419 | /// The guard counts toward the `case` line, so a long guard stacks the |
| 2420 | /// patterns too. A single pattern never stacks. |
| 2421 | fn prong( |
| 2422 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 2423 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2424 | let case ast::NodeValue::MatchProng(pr) = node.value else { |
| 2425 | panic "prong: prong expected"; |
| 2426 | }; |
| 2427 | let mut pre: *mut [layout::Child] = &mut []; |
| 2428 | let mut stacked = false; |
| 2429 | match pr.arm { |
| 2430 | case ast::ProngArm::Case(patterns) => { |
| 2431 | set stacked = patterns.len > 1; |
| 2432 | try keyword(a, &mut pre, NONE, "case"); |
| 2433 | if stacked { |
| 2434 | for pattern, i in patterns { |
| 2435 | if i > 0 { |
| 2436 | try punct(a, &mut pre, NONE, ","); |
| 2437 | } |
| 2438 | try add( |
| 2439 | a, |
| 2440 | &mut pre, |
| 2441 | SOFT_INDENT_SPACE, |
| 2442 | try expr(a, p, pattern, Ctx::Pattern) |
| 2443 | ); |
| 2444 | } |
| 2445 | } else { |
| 2446 | try add( |
| 2447 | a, |
| 2448 | &mut pre, |
| 2449 | SPACE, |
| 2450 | try expr(a, p, patterns[0], Ctx::Pattern) |
| 2451 | ); |
| 2452 | } |
| 2453 | } |
| 2454 | case ast::ProngArm::Binding(binding) => |
| 2455 | try add(a, &mut pre, NONE, try expr(a, p, binding, Ctx::Normal)), |
| 2456 | case ast::ProngArm::Else => try keyword(a, &mut pre, NONE, "else"), |
| 2457 | } |
| 2458 | if let guard = pr.guard { |
| 2459 | let mut test: *mut [layout::Child] = &mut []; |
| 2460 | try keyword(a, &mut test, NONE, "if"); |
| 2461 | try put(a, p, &mut test, SPACE, guard, Ctx::Condition); |
| 2462 | let cond = try group(a, nil, test); |
| 2463 | if stacked { |
| 2464 | try add(a, &mut pre, NONE, try sameOrNext(a, cond)); |
| 2465 | } else { |
| 2466 | try add(a, &mut pre, SOFT_INDENT_SPACE, cond); |
| 2467 | } |
| 2468 | } |
| 2469 | // The arrows line up after the pattern and guard. The patterns of a |
| 2470 | // stacked prong share the box of the arrow, so that their line breaks and |
| 2471 | // the line of the opening brace go together. |
| 2472 | let mut head: *mut [layout::Child] = &mut []; |
| 2473 | if stacked { |
| 2474 | set head = pre; |
| 2475 | try add(a, &mut head, NONE, try tab(a, COLUMN_ARROW)); |
| 2476 | } else { |
| 2477 | try add(a, &mut head, NONE, try group(a, nil, pre)); |
| 2478 | try add(a, &mut head, NONE, try tab(a, COLUMN_ARROW)); |
| 2479 | } |
| 2480 | try operator(a, &mut head, SPACE, "=>"); |
| 2481 | let moved = takeMark(p, node, ast::BrokenSite::Value); |
| 2482 | |
| 2483 | let mut kids: *mut [layout::Child] = &mut []; |
| 2484 | if let case ast::NodeValue::Block(b) = pr.body.value; not b.isUnsafe { |
| 2485 | if stacked { |
| 2486 | try punct(a, &mut head, SOFT_SPACE, brace( |
| 2487 | p, b.statements.len, pr.body |
| 2488 | )); |
| 2489 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2490 | try body(a, p, &mut kids, b.statements, pr.body, stmt); |
| 2491 | } else { |
| 2492 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2493 | try blockBody(a, p, &mut kids, pr.body, SPACE); |
| 2494 | } |
| 2495 | } else { |
| 2496 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2497 | let core = try stmtCore(a, p, pr.body); |
| 2498 | if moved { |
| 2499 | try add(a, &mut kids, layout::Placement::Indent, core); |
| 2500 | } else if stacked and ast::needsSemicolon(pr.body) { |
| 2501 | try add(a, &mut kids, NONE, try sameOrNext(a, core)); |
| 2502 | } else if ast::needsSemicolon(pr.body) { |
| 2503 | try add(a, &mut kids, SOFT_INDENT_SPACE, core); |
| 2504 | } else { |
| 2505 | try add(a, &mut kids, SPACE, core); |
| 2506 | } |
| 2507 | try punct(a, &mut kids, NONE, ","); |
| 2508 | } |
| 2509 | return try group(a, node, kids); |
| 2510 | } |
| 2511 | |
| 2512 | // Declarations /////////////////////////////////////////////////////////////// |
| 2513 | |
| 2514 | /// Format a function parameter: `name: type`. |
| 2515 | fn paramItem( |
| 2516 | a: &heap::Heap, p: &mut Printer, node: *ast::Node, ctx: Ctx |
| 2517 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2518 | let case ast::NodeValue::FnParam(param) = node.value else { |
| 2519 | panic "paramItem: parameter expected"; |
| 2520 | }; |
| 2521 | let mut kids: *mut [layout::Child] = &mut []; |
| 2522 | try put(a, p, &mut kids, NONE, param.name, ctx); |
| 2523 | try punct(a, &mut kids, NONE, ":"); |
| 2524 | try put(a, p, &mut kids, SPACE, param.type, ctx); |
| 2525 | |
| 2526 | return try group(a, node, kids); |
| 2527 | } |
| 2528 | |
| 2529 | /// Format a function, method, or trait method signature, and the body of a |
| 2530 | /// function or method. |
| 2531 | fn fnDecl( |
| 2532 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 2533 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2534 | let mut head: *mut [layout::Child] = &mut []; |
| 2535 | let mut fnBody: ?*ast::Node = nil; |
| 2536 | let mut sig: *ast::FnSig = undefined; |
| 2537 | match node.value { |
| 2538 | case ast::NodeValue::FnDecl(f) => { |
| 2539 | if p.role == Role::Interface { |
| 2540 | if let attrs = |
| 2541 | f.attrs; |
| 2542 | ast::attributesContains(&attrs, ast::Attribute::Extern) |
| 2543 | and not ast::attributesContains(&attrs, ast::Attribute::Intrinsic) |
| 2544 | { |
| 2545 | try spaced(a, &mut head, "@extern", layout::Role::Keyword); |
| 2546 | } |
| 2547 | } |
| 2548 | try attributes(a, &mut head, f.attrs); |
| 2549 | try spaced(a, &mut head, "fn", layout::Role::Keyword); |
| 2550 | try put(a, p, &mut head, SPACE, f.name, Ctx::Normal); |
| 2551 | try typeList(a, p, &mut head, f.binders); |
| 2552 | set fnBody = f.body; |
| 2553 | set sig = f.sig; |
| 2554 | } |
| 2555 | case ast::NodeValue::MethodDecl { |
| 2556 | name, binders, receiverName, receiverType, sig: s, body: b, attrs |
| 2557 | } => { |
| 2558 | let mut recv: *mut [layout::Child] = &mut []; |
| 2559 | try punct(a, &mut recv, NONE, "("); |
| 2560 | try put(a, p, &mut recv, NONE, receiverName, Ctx::Normal); |
| 2561 | try punct(a, &mut recv, NONE, ":"); |
| 2562 | try put(a, p, &mut recv, SPACE, receiverType, Ctx::Normal); |
| 2563 | try punct(a, &mut recv, NONE, ")"); |
| 2564 | try attributes(a, &mut head, attrs); |
| 2565 | try spaced(a, &mut head, "fn", layout::Role::Keyword); |
| 2566 | try typeList(a, p, &mut head, binders); |
| 2567 | try add(a, &mut head, SPACE, try group(a, nil, recv)); |
| 2568 | try put(a, p, &mut head, SPACE, name, Ctx::Normal); |
| 2569 | set fnBody = b; |
| 2570 | set sig = s; |
| 2571 | } |
| 2572 | case ast::NodeValue::TraitMethodSig { |
| 2573 | name, receiver, sig: s, attrs |
| 2574 | } => { |
| 2575 | try attributes(a, &mut head, attrs); |
| 2576 | try spaced(a, &mut head, "fn", layout::Role::Keyword); |
| 2577 | let mut recv: *mut [layout::Child] = &mut []; |
| 2578 | try punct(a, &mut recv, NONE, "("); |
| 2579 | try put(a, p, &mut recv, NONE, receiver, Ctx::Normal); |
| 2580 | try punct(a, &mut recv, NONE, ")"); |
| 2581 | try add(a, &mut head, SPACE, try group(a, nil, recv)); |
| 2582 | try put(a, p, &mut head, SPACE, name, Ctx::Normal); |
| 2583 | set sig = s; |
| 2584 | } |
| 2585 | else => panic "fnDecl: function expected", |
| 2586 | } |
| 2587 | try add( |
| 2588 | a, |
| 2589 | &mut head, |
| 2590 | NONE, |
| 2591 | try softList(a, p, parens(node), sig.params, Ctx::Normal, paramItem) |
| 2592 | ); |
| 2593 | let mut tail: *mut [layout::Child] = &mut []; |
| 2594 | try signatureTail(a, p, &mut tail, sig, marked( |
| 2595 | p, node, ast::BrokenSite::Throws |
| 2596 | )); |
| 2597 | let stacked = isStacked(p, node); |
| 2598 | let forced = marked(p, node, ast::BrokenSite::List); |
| 2599 | let mut kids: *mut [layout::Child] = &mut []; |
| 2600 | if let b = fnBody; p.role == Role::Source { |
| 2601 | let case ast::NodeValue::Block(blk) = b.value else { |
| 2602 | panic "fnDecl: block expected"; |
| 2603 | }; |
| 2604 | // The brace follows a `throws` clause that moved to its own line. |
| 2605 | let mut at = SPACE; |
| 2606 | if sig.throwList.len > 0 { |
| 2607 | set at = SOFT_SPACE; |
| 2608 | } |
| 2609 | try punct(a, &mut tail, at, brace(p, blk.statements.len, b)); |
| 2610 | let text = try signature(a, sig, stacked, forced, head, tail); |
| 2611 | try add(a, &mut kids, NONE, text); |
| 2612 | set p.fnDepth += 1; |
| 2613 | try body(a, p, &mut kids, blk.statements, b, stmt); |
| 2614 | set p.fnDepth -= 1; |
| 2615 | } else { |
| 2616 | try punct(a, &mut tail, NONE, ";"); |
| 2617 | let text = try signature(a, sig, stacked, forced, head, tail); |
| 2618 | try add(a, &mut kids, NONE, text); |
| 2619 | } |
| 2620 | return try group(a, node, kids); |
| 2621 | } |
| 2622 | |
| 2623 | /// Whether the source of a signature put its `throws` clause on its own line. |
| 2624 | fn isStacked(p: &Printer, node: *ast::Node) -> bool { |
| 2625 | for t in entries(p, node, ast::TriviaPlacement::Closing) { |
| 2626 | if let case ast::TriviaKind::StackedThrows = t.kind { |
| 2627 | return true; |
| 2628 | } |
| 2629 | } |
| 2630 | return false; |
| 2631 | } |
| 2632 | |
| 2633 | /// Layout of a function signature from its `head`, which ends with the |
| 2634 | /// parameters, and its `tail`: the return type, `throws` clause, and brace. |
| 2635 | /// |
| 2636 | /// With a `throws` clause, the signature keeps the form of the source. The |
| 2637 | /// clause on its own line moves the brace to the next, which keeps the |
| 2638 | /// parameters and return type on the first line. `stacked` is true when the |
| 2639 | /// source has that form, and the signature prefers it. Otherwise it prefers |
| 2640 | /// one line, then the stacked form. The parameters break only when neither |
| 2641 | /// first line fits, or when `forced`: the source broke them. |
| 2642 | fn signature( |
| 2643 | a: &heap::Heap, |
| 2644 | sig: &ast::FnSig, |
| 2645 | stacked: bool, |
| 2646 | forced: bool, |
| 2647 | head: *[layout::Child], |
| 2648 | tail: *[layout::Child] |
| 2649 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2650 | let start = try flatGroup(a, nil, head); |
| 2651 | let soft = try flatGroup(a, nil, tail); |
| 2652 | if sig.throwList.len == 0 { |
| 2653 | return try row(a, &[start, soft]); |
| 2654 | } |
| 2655 | let line = try flatGroup(a, nil, try inlined(a, tail)); |
| 2656 | let apart = try broken(a, soft); |
| 2657 | let end = try choice(a, nil, &[line, apart]); |
| 2658 | // The parameters end the head. |
| 2659 | let opened = try flatGroup(a, nil, try brokenLast(a, head)); |
| 2660 | // The first line of any other form would hide the tail after the |
| 2661 | // parameters, which sit on lines of their own. |
| 2662 | if forced { |
| 2663 | return try row(a, &[opened, apart if stacked else end]); |
| 2664 | } |
| 2665 | if stacked { |
| 2666 | return try choice(a, nil, &[try row(a, &[start, apart]), try row(a, &[opened, end])]); |
| 2667 | } |
| 2668 | return try choice( |
| 2669 | a, |
| 2670 | nil, |
| 2671 | &[ |
| 2672 | try row(a, &[start, line]), |
| 2673 | try row(a, &[start, apart]), |
| 2674 | try row(a, &[opened, end]), |
| 2675 | ] |
| 2676 | ); |
| 2677 | } |
| 2678 | |
| 2679 | /// Format a record field of a labeled record or a variant payload, with a |
| 2680 | /// comma. |
| 2681 | fn fieldItem( |
| 2682 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 2683 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2684 | let mut kids: *mut [layout::Child] = &mut []; |
| 2685 | try add(a, &mut kids, NONE, try fieldBare(a, p, node, Ctx::Normal)); |
| 2686 | try punct(a, &mut kids, NONE, ","); |
| 2687 | |
| 2688 | return try group(a, node, kids); |
| 2689 | } |
| 2690 | |
| 2691 | /// Format a record field of a labeled record or a variant payload, without a |
| 2692 | /// comma. |
| 2693 | fn fieldBare( |
| 2694 | a: &heap::Heap, p: &mut Printer, node: *ast::Node, ctx: Ctx |
| 2695 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2696 | let case ast::NodeValue::RecordField { field, type, value } = node.value else { |
| 2697 | panic "fieldBare: record field expected"; |
| 2698 | }; |
| 2699 | let name = field else { |
| 2700 | panic "fieldBare: field has no name"; |
| 2701 | }; |
| 2702 | let mut kids: *mut [layout::Child] = &mut []; |
| 2703 | try put(a, p, &mut kids, NONE, name, Ctx::Normal); |
| 2704 | try punct(a, &mut kids, NONE, ":"); |
| 2705 | try put(a, p, &mut kids, SPACE, type, Ctx::Normal); |
| 2706 | if let init = value { |
| 2707 | try operator(a, &mut kids, SPACE, "="); |
| 2708 | try put(a, p, &mut kids, SPACE, init, Ctx::Normal); |
| 2709 | } |
| 2710 | return try group(a, node, kids); |
| 2711 | } |
| 2712 | |
| 2713 | /// Append the labeled fields of `container` in braces, on one line when they |
| 2714 | /// fit, otherwise one per line with a trailing comma. For a body that the |
| 2715 | /// source wrote on one line. The fields have no comments, since a comment ends |
| 2716 | /// the line. |
| 2717 | fn compactFields( |
| 2718 | a: &heap::Heap, |
| 2719 | p: &mut Printer, |
| 2720 | kids: &mut *mut [layout::Child], |
| 2721 | container: *ast::Node, |
| 2722 | fields: *[*ast::Node] |
| 2723 | ) throws (alloc::AllocError) { |
| 2724 | let spec = SoftSpec { |
| 2725 | source: nil, |
| 2726 | container, |
| 2727 | open: "{", |
| 2728 | close: "}", |
| 2729 | pad: layout::Gap::Space, |
| 2730 | tail: nil, |
| 2731 | commas: Commas::Trailing, |
| 2732 | forced: false, |
| 2733 | }; |
| 2734 | let list = try plainList(a, p, spec, fields, Ctx::Normal, fieldBare); |
| 2735 | let case layout::Item::Box(parts) = unbroken(list).item else { |
| 2736 | panic "compactFields: list is not a box"; |
| 2737 | }; |
| 2738 | // The same items, one per line. |
| 2739 | let mut lines: *mut [layout::Child] = &mut []; |
| 2740 | for part in parts { |
| 2741 | try lines.append(part, a); |
| 2742 | } |
| 2743 | set lines[1].layout = try broken(a, parts[1].layout); |
| 2744 | let vertical = try broken(a, try flatGroup(a, nil, lines)); |
| 2745 | try add(a, kids, SPACE, try choice(a, nil, &[list, vertical])); |
| 2746 | } |
| 2747 | |
| 2748 | /// Whether a labeled record body or payload prints on one line when it fits: |
| 2749 | /// the source wrote it on one line, and it has fields. |
| 2750 | fn isCompact(p: &Printer, container: *ast::Node, count: u32) -> bool { |
| 2751 | return count > 0 and not marked(p, container, ast::BrokenSite::List); |
| 2752 | } |
| 2753 | |
| 2754 | /// Format the type of a positional record field. |
| 2755 | fn positionalItem( |
| 2756 | a: &heap::Heap, p: &mut Printer, node: *ast::Node, ctx: Ctx |
| 2757 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2758 | let case ast::NodeValue::RecordField { type, .. } = node.value else { |
| 2759 | panic "positionalItem: record field expected"; |
| 2760 | }; |
| 2761 | return try expr(a, p, type, ctx); |
| 2762 | } |
| 2763 | |
| 2764 | /// Format a union variant: its name, explicit value or payload, and a comma. |
| 2765 | fn variantItem( |
| 2766 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 2767 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2768 | let case ast::NodeValue::UnionDeclVariant(v) = node.value else { |
| 2769 | panic "variantItem: variant expected"; |
| 2770 | }; |
| 2771 | let mut kids: *mut [layout::Child] = &mut []; |
| 2772 | try put(a, p, &mut kids, NONE, v.name, Ctx::Normal); |
| 2773 | if let value = v.value { |
| 2774 | try operator(a, &mut kids, SPACE, "="); |
| 2775 | try put(a, p, &mut kids, SPACE, value, Ctx::Normal); |
| 2776 | } |
| 2777 | if let payload = v.type { |
| 2778 | let case ast::NodeValue::TypeSig(sig) = payload.value else { |
| 2779 | panic "variantItem: payload type expected"; |
| 2780 | }; |
| 2781 | let case ast::TypeSig::Record { fields, labeled } = sig else { |
| 2782 | panic "variantItem: record payload expected"; |
| 2783 | }; |
| 2784 | if labeled and isCompact(p, payload, fields.len) { |
| 2785 | try compactFields(a, p, &mut kids, payload, fields); |
| 2786 | } else if labeled { |
| 2787 | try punct(a, &mut kids, SPACE, brace(p, fields.len, payload)); |
| 2788 | try body(a, p, &mut kids, fields, payload, fieldItem); |
| 2789 | } else { |
| 2790 | try add( |
| 2791 | a, |
| 2792 | &mut kids, |
| 2793 | NONE, |
| 2794 | try softList( |
| 2795 | a, |
| 2796 | p, |
| 2797 | SoftSpec { |
| 2798 | source: payload, |
| 2799 | container: payload, |
| 2800 | open: "(", |
| 2801 | close: ")", |
| 2802 | pad: layout::Gap::None, |
| 2803 | tail: nil, |
| 2804 | commas: Commas::Between, |
| 2805 | forced: false, |
| 2806 | }, |
| 2807 | fields, |
| 2808 | Ctx::Normal, |
| 2809 | positionalItem |
| 2810 | ) |
| 2811 | ); |
| 2812 | } |
| 2813 | } |
| 2814 | try punct(a, &mut kids, NONE, ","); |
| 2815 | |
| 2816 | return try group(a, node, kids); |
| 2817 | } |
| 2818 | |
| 2819 | /// Append `: A + B`, the traits that a type derives or a trait extends. |
| 2820 | fn derives( |
| 2821 | a: &heap::Heap, |
| 2822 | p: &mut Printer, |
| 2823 | kids: &mut *mut [layout::Child], |
| 2824 | list: *[*ast::Node] |
| 2825 | ) throws (alloc::AllocError) { |
| 2826 | for item, i in list { |
| 2827 | if i == 0 { |
| 2828 | try punct(a, kids, NONE, ":"); |
| 2829 | } else { |
| 2830 | try operator(a, kids, SPACE, "+"); |
| 2831 | } |
| 2832 | try put(a, p, kids, SPACE, item, Ctx::Normal); |
| 2833 | } |
| 2834 | } |
| 2835 | |
| 2836 | /// Format a record, union, trait, or instance declaration. |
| 2837 | fn typeDecl( |
| 2838 | a: &heap::Heap, p: &mut Printer, node: *ast::Node |
| 2839 | ) -> *layout::Layout throws (alloc::AllocError) { |
| 2840 | let mut head: *mut [layout::Child] = &mut []; |
| 2841 | let mut kids: *mut [layout::Child] = &mut []; |
| 2842 | match node.value { |
| 2843 | case ast::NodeValue::RecordDecl(r) => { |
| 2844 | try attributes(a, &mut head, r.attrs); |
| 2845 | try spaced(a, &mut head, "record", layout::Role::Keyword); |
| 2846 | try put(a, p, &mut head, SPACE, r.name, Ctx::Normal); |
| 2847 | try typeList(a, p, &mut head, r.binders); |
| 2848 | if r.labeled and isCompact(p, node, r.fields.len) { |
| 2849 | try derives(a, p, &mut head, r.derives); |
| 2850 | try compactFields(a, p, &mut head, node, r.fields); |
| 2851 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2852 | } else if r.labeled { |
| 2853 | try derives(a, p, &mut head, r.derives); |
| 2854 | try punct(a, &mut head, SPACE, brace(p, r.fields.len, node)); |
| 2855 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2856 | try body(a, p, &mut kids, r.fields, node, fieldItem); |
| 2857 | } else { |
| 2858 | try add( |
| 2859 | a, |
| 2860 | &mut head, |
| 2861 | NONE, |
| 2862 | try softList( |
| 2863 | a, |
| 2864 | p, |
| 2865 | parens(node), |
| 2866 | r.fields, |
| 2867 | Ctx::Normal, |
| 2868 | positionalItem |
| 2869 | ) |
| 2870 | ); |
| 2871 | try derives(a, p, &mut head, r.derives); |
| 2872 | try punct(a, &mut head, NONE, ";"); |
| 2873 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2874 | } |
| 2875 | } |
| 2876 | case ast::NodeValue::UnionDecl(u) => { |
| 2877 | try attributes(a, &mut head, u.attrs); |
| 2878 | try spaced(a, &mut head, "union", layout::Role::Keyword); |
| 2879 | try put(a, p, &mut head, SPACE, u.name, Ctx::Normal); |
| 2880 | try typeList(a, p, &mut head, u.binders); |
| 2881 | try derives(a, p, &mut head, u.derives); |
| 2882 | try punct(a, &mut head, SPACE, brace(p, u.variants.len, node)); |
| 2883 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2884 | try body(a, p, &mut kids, u.variants, node, variantItem); |
| 2885 | } |
| 2886 | case ast::NodeValue::TraitDecl { |
| 2887 | name, binders, supertraits, methods, attrs |
| 2888 | } => { |
| 2889 | try attributes(a, &mut head, attrs); |
| 2890 | try spaced(a, &mut head, "trait", layout::Role::Keyword); |
| 2891 | try put(a, p, &mut head, SPACE, name, Ctx::Normal); |
| 2892 | try typeList(a, p, &mut head, binders); |
| 2893 | try derives(a, p, &mut head, supertraits); |
| 2894 | try punct(a, &mut head, SPACE, brace(p, methods.len, node)); |
| 2895 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2896 | try body(a, p, &mut kids, methods, node, fnDecl); |
| 2897 | } |
| 2898 | case ast::NodeValue::InstanceDecl { |
| 2899 | binders, traitName, targetType, methods |
| 2900 | } => { |
| 2901 | try spaced(a, &mut head, "instance", layout::Role::Keyword); |
| 2902 | try typeList(a, p, &mut head, binders); |
| 2903 | try put(a, p, &mut head, SPACE, traitName, Ctx::Normal); |
| 2904 | try keyword(a, &mut head, SPACE, "for"); |
| 2905 | try put(a, p, &mut head, SPACE, targetType, Ctx::Normal); |
| 2906 | try punct(a, &mut head, SPACE, brace(p, methods.len, node)); |
| 2907 | try add(a, &mut kids, NONE, try group(a, nil, head)); |
| 2908 | try body(a, p, &mut kids, methods, node, stmt); |
| 2909 | } |
| 2910 | else => panic "typeDecl: type declaration expected", |
| 2911 | } |
| 2912 | return try group(a, node, kids); |
| 2913 | } |