lang: Add a source pretty printer

5b76d29df4863e0206726a3e866a014ef61ec833ccf7e57a7951f2837098b3aa
Retain source comments and trivia during parsing, and format the AST
through a bounded layout engine. Support width-based layout choices,
expression precedence, call arguments, records, patterns, and control
flow while preserving source meaning.

Treat the width as a maximum: keep the line breaks, one-item-per-line
lists, compact declarations, and `throws` layout that the source
already uses when they fit. Align trailing comments and match arrows,
keep one blank line between functions, and drop blank lines after
closing braces inside functions.

Expose source formatting through the compiler's -fmt option, with
-fmt.wrap to set the width (100 columns by default), and report parse
errors on standard error so that the formatted output holds only
source text. Add `make fmt` to format the standard library and kernel
sources in place. Check format stability and parsed output with unit
and executable tests.

Assisted-by: Codex:gpt-6
Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent 42fb200e
Makefile +8 -1
32 32
$(BIN_DIR):
33 33
	@mkdir -p $@
34 34
35 35
include test/Makefile
36 36
37 +
# Format the standard library and kernel sources in place. Set `FMT_SRC` to
38 +
# format other files.
39 +
FMT_SRC ?= $(STD_TEST_LIB) $(shell find kernel -name '*.rad' | sort)
40 +
41 +
fmt: $(RAD_BIN) scripts/fmt
42 +
	@sh scripts/fmt $(FMT_SRC)
43 +
37 44
seed:
38 45
	seed/update
39 46
40 47
clean-rad:
41 48
	rm -rf bin/*
42 49
	rm -f seed/radiance.rv64.s[0-9]*
43 50
44 51
clean: clean-std-test clean-bin-test clean-rad
45 52
46 -
.PHONY: default seed clean clean-rad test
53 +
.PHONY: default seed clean clean-rad test fmt
47 54
.SUFFIXES:
48 55
.DELETE_ON_ERROR:
49 56
.SILENT:
compiler/radiance.rad +82 -3
5 5
use std::mem;
6 6
use std::fmt;
7 7
use std::io;
8 8
use std::lang::alloc;
9 9
use std::lang::ast;
10 +
use std::lang::layout;
10 11
use std::lang::parser;
12 +
use std::lang::pretty;
11 13
use std::lang::scanner;
12 14
use std::lang::resolver;
13 15
use std::lang::module;
14 16
use std::lang::strings;
15 17
use std::lang::package;
59 61
/// entries and 21.3 MB with them. The compiler and the test build of the
60 62
/// standard library fill at most 26% of the code list and 59% of the function
61 63
/// list, so no list grows past its reservation. The rest of the region absorbs
62 64
/// the doubling of any one relocation list of a larger program.
63 65
constant EMITTER_SIZE: u32 = 33554432;
64 -
/// Main arena size (128 MB) - lives throughout compilation.
66 +
/// Main arena size (144 MB) - lives throughout compilation.
65 67
/// Used for: resolver data, types, symbols, global IL data, and assembled modules.
66 -
constant MAIN_ARENA_SIZE: u32 = 134217728;
68 +
constant MAIN_ARENA_SIZE: u32 = 150994944;
67 69
/// Driver table arena size (2 MB). It holds the resolver error buffer, the
68 70
/// resolver package list, the module path copies, and the test descriptors for
69 71
/// the whole compilation.
70 72
constant DRIVER_ARENA_SIZE: u32 = 2097152;
71 73
74 +
/// Default line width of formatted source, in columns. `-fmt.wrap` overrides
75 +
/// it.
76 +
constant FORMAT_WIDTH: u32 = 100;
77 +
/// Spaces per indentation level of formatted source.
78 +
constant FORMAT_INDENT: u32 = 4;
79 +
72 80
/// Debug info file extension.
73 81
constant DEBUG_EXT: *[u8] = ".debug";
74 82
75 83
/// Maximum rodata size (4MB).
76 84
constant MAX_RO_DATA_SIZE: u32 = 4194304;
86 94
/// Symbol name exported for startup code to call the semantic entry function.
87 95
export constant DEFAULT_ENTRY_SYMBOL: *[u8] = "::default";
88 96
89 97
/// Usage string.
90 98
constant USAGE: *[u8] =
91 -
    "usage: radiance -pkg <name> [-start <input.ras>] -mod <input>.. [-pkg <name> -mod <input>..] -entry <pkg> [-o <output> | -ril <directory>]\n-mod accepts a source path or logical/path=source.rad relative to the package root.\n";
99 +
    "usage: radiance -pkg <name> [-start <input.ras>] -mod <input>.. [-pkg <name> -mod <input>..] -entry <pkg> [-o <output> | -ril <directory>]\n-mod accepts a source path or logical/path=source.rad relative to the package root.\n       radiance -fmt [-fmt.wrap <columns>] <input.rad>\n-fmt prints the source of a module in the canonical style, wrapped at 100 columns unless -fmt.wrap sets another width.\n";
92 100
93 101
/// Compiler error.
94 102
union Error: Copy {
95 103
    Other,
96 104
}
1423 1431
        try writeDebugInfo(result.debugEntries, modules, outPath, &mut low.resolver.arena);
1424 1432
    }
1425 1433
    pkgLog(&entryPkg, &["ok", "(", outPath, ")"]);
1426 1434
}
1427 1435
1436 +
/// Parse a positive integer that fits in `u32`.
1437 +
fn parseWidth(text: *[u8]) -> ?u32 {
1438 +
    let literal = try? fmt::parseInt(text) else {
1439 +
        return nil;
1440 +
    };
1441 +
    if literal.magnitude == 0 or literal.magnitude > 0xFFFFFFFF {
1442 +
        return nil;
1443 +
    }
1444 +
    return literal.magnitude as u32;
1445 +
}
1446 +
1447 +
/// Print the module at `path` in the canonical source style, wrapped at `width`
1448 +
/// columns.
1449 +
///
1450 +
/// The text is built in the IL text buffer, which no other pass uses here, and
1451 +
/// printed at once.
1452 +
fn formatModule(storage: *mut Storage, path: *[u8], width: u32) throws (Error) {
1453 +
    let mut sourceArena = alloc::new(&mut storage.moduleSources[..]);
1454 +
    let nodes = ast::nodeArena(&mut storage.ast[..]);
1455 +
    let pool = strings::freshPool(&mut storage.poolTable[..]);
1456 +
    let mut frontend = parser::newParser(nodes, pool);
1457 +
    set frontend.triviaMode = parser::TriviaMode::Keep;
1458 +
1459 +
    let source = try readModuleSource(&mut sourceArena, path);
1460 +
    let location = scanner::SourceLoc::File(path);
1461 +
    let root = try parser::parseModule(&mut frontend, location, source) catch {
1462 +
        throw Error::Other;
1463 +
    };
1464 +
    let mut layoutArena = alloc::new(&mut storage.main[..]);
1465 +
    let trivia = frontend.trivia.take();
1466 +
    let tree = try pretty::module(root, trivia, &mut layoutArena) catch {
1467 +
        throw error(&["fatal:", "layout arena exhausted"]);
1468 +
    };
1469 +
    let mut text = sexpr::Buffer { buf: &mut storage.ilText[..], pos: 0 };
1470 +
    let options = layout::text::Options {
1471 +
        width, indent: FORMAT_INDENT
1472 +
    };
1473 +
    {
1474 +
        let sink: &mut opaque sexpr::Output = &mut text;
1475 +
        layout::text::render(tree, options, sink);
1476 +
    }
1477 +
    if text.pos >= text.buf.len {
1478 +
        throw error(&["fatal:", "formatted text exceeds the output buffer"]);
1479 +
    }
1480 +
    io::print(&text.buf[..text.pos]);
1481 +
}
1482 +
1428 1483
/// Compile the packages named on the command line.
1429 1484
///
1430 1485
/// `storage` is the memory of the process. `main` splits it by field, and each
1431 1486
/// buffer has one owner: the arenas and tables move to the parser, the module
1432 1487
/// graph, the resolver, and the lowering and code generation passes, and the
1433 1488
/// output buffers are lent to the one pass that runs.
1434 1489
@default fn main(env: *sys::Env, storage: *mut Storage) -> i32 {
1490 +
    if env.args.len > 0 and mem::eq(env.args[0], "-fmt") {
1491 +
        let mut width = FORMAT_WIDTH;
1492 +
        let mut first: u32 = 1;
1493 +
        if env.args.len > 1 and mem::eq(env.args[1], "-fmt.wrap") {
1494 +
            if env.args.len < 3 {
1495 +
                io::printError(USAGE);
1496 +
                return 1;
1497 +
            }
1498 +
            let columns = parseWidth(env.args[2]) else {
1499 +
                io::printError(USAGE);
1500 +
                return 1;
1501 +
            };
1502 +
            set width = columns;
1503 +
            set first = 3;
1504 +
        }
1505 +
        if env.args.len <> first + 1 {
1506 +
            io::printError(USAGE);
1507 +
            return 1;
1508 +
        }
1509 +
        try formatModule(storage, env.args[first], width) catch {
1510 +
            return 1;
1511 +
        };
1512 +
        return 0;
1513 +
    }
1435 1514
    let mut driverArena = alloc::new(&mut storage.driver[..]);
1436 1515
    let mut sourceArena = alloc::new(&mut storage.moduleSources[..]);
1437 1516
    let mut graph = module::moduleGraph(&mut storage.moduleEntries[..]);
1438 1517
    let nodes = ast::nodeArena(&mut storage.ast[..]);
1439 1518
    let pool = strings::freshPool(&mut storage.poolTable[..]);
lib/std/lang.rad +2 -0
3 3
export mod sexpr;
4 4
export mod types;
5 5
export mod strings;
6 6
export mod scanner;
7 7
export mod ast;
8 +
export mod layout;
8 9
export mod parser;
10 +
export mod pretty;
9 11
export mod module;
10 12
export mod resolver;
11 13
export mod package;
12 14
export mod il;
13 15
export mod lower;
lib/std/lang/ast.rad +175 -0
82 82
    Signed,
83 83
    /// Unsigned, eg. `u32`.
84 84
    Unsigned,
85 85
}
86 86
87 +
/// Source name of an integer type, eg. `u32`.
88 +
export fn integerName(width: u8, sign: Signedness) -> *[u8] {
89 +
    if sign == Signedness::Signed {
90 +
        match width {
91 +
            case 1 => return "i8",
92 +
            case 2 => return "i16",
93 +
            case 4 => return "i32",
94 +
            case 8 => return "i64",
95 +
            else => panic "integerName: invalid width",
96 +
        }
97 +
    }
98 +
    match width {
99 +
        case 1 => return "u8",
100 +
        case 2 => return "u16",
101 +
        case 4 => return "u32",
102 +
        case 8 => return "u64",
103 +
        else => panic "integerName: invalid width",
104 +
    }
105 +
}
106 +
87 107
/// Binary operator kinds used in numeric expressions.
88 108
export union BinaryOp: Copy {
89 109
    /// Addition (`+`).
90 110
    Add,
91 111
    /// Subtraction (`-`).
126 146
    Or,
127 147
    /// Logical exclusive disjunction (`xor`).
128 148
    Xor,
129 149
}
130 150
151 +
/// Source text of a binary operator.
152 +
export fn binaryText(op: BinaryOp) -> *[u8] {
153 +
    match op {
154 +
        case BinaryOp::Add => return "+",
155 +
        case BinaryOp::Sub => return "-",
156 +
        case BinaryOp::Mul => return "*",
157 +
        case BinaryOp::Div => return "/",
158 +
        case BinaryOp::Mod => return "%",
159 +
        case BinaryOp::BitAnd => return "&",
160 +
        case BinaryOp::BitOr => return "|",
161 +
        case BinaryOp::BitXor => return "^",
162 +
        case BinaryOp::Shl => return "<<",
163 +
        case BinaryOp::Shr => return ">>",
164 +
        case BinaryOp::Eq => return "==",
165 +
        case BinaryOp::Ne => return "<>",
166 +
        case BinaryOp::Lt => return "<",
167 +
        case BinaryOp::Gt => return ">",
168 +
        case BinaryOp::Lte => return "<=",
169 +
        case BinaryOp::Gte => return ">=",
170 +
        case BinaryOp::And => return "and",
171 +
        case BinaryOp::Or => return "or",
172 +
        case BinaryOp::Xor => return "xor",
173 +
    }
174 +
}
175 +
176 +
/// Precedence of a binary operator, from 0 for the loosest to 7 for the
177 +
/// tightest. The parser groups operators by this value.
178 +
export fn precedence(op: BinaryOp) -> u32 {
179 +
    match op {
180 +
        case BinaryOp::Mul, BinaryOp::Div, BinaryOp::Mod => return 7,
181 +
        case BinaryOp::Add, BinaryOp::Sub => return 6,
182 +
        case BinaryOp::Shl, BinaryOp::Shr => return 5,
183 +
        case BinaryOp::BitAnd => return 4,
184 +
        case BinaryOp::BitXor => return 3,
185 +
        case BinaryOp::BitOr => return 2,
186 +
        case BinaryOp::Eq,
187 +
            BinaryOp::Ne,
188 +
            BinaryOp::Lt,
189 +
            BinaryOp::Gt,
190 +
            BinaryOp::Lte,
191 +
            BinaryOp::Gte =>
192 +
            return 1,
193 +
        case BinaryOp::And, BinaryOp::Or, BinaryOp::Xor => return 0,
194 +
    }
195 +
}
196 +
131 197
/// Unary operator kinds used in expressions.
132 198
export union UnaryOp: Copy {
133 199
    /// Logical negation (`not`).
134 200
    Not,
135 201
    /// Arithmetic negation (`-`).
136 202
    Neg,
137 203
    /// Bitwise NOT (`~`).
138 204
    BitNot,
139 205
}
140 206
207 +
/// Source text of a unary operator.
208 +
export fn unaryText(op: UnaryOp) -> *[u8] {
209 +
    match op {
210 +
        case UnaryOp::Not => return "not",
211 +
        case UnaryOp::Neg => return "-",
212 +
        case UnaryOp::BitNot => return "~",
213 +
    }
214 +
}
215 +
141 216
/// Builtin function kind.
142 217
export union Builtin: Copy {
143 218
    /// Size of type in bytes (`@sizeOf`).
144 219
    SizeOf,
145 220
    /// Alignment requirement of type (`@alignOf`).
147 222
    /// Construct a slice from pointer, length, and optional capacity (`@sliceOf`).
148 223
    /// The pointer must not be null, even when the length is zero.
149 224
    SliceOf,
150 225
}
151 226
227 +
/// Source name of a builtin, eg. `@sizeOf`.
228 +
export fn builtinText(kind: Builtin) -> *[u8] {
229 +
    match kind {
230 +
        case Builtin::SizeOf => return "@sizeOf",
231 +
        case Builtin::AlignOf => return "@alignOf",
232 +
        case Builtin::SliceOf => return "@sliceOf",
233 +
    }
234 +
}
235 +
152 236
/// Source extent for a node measured in bytes.
153 237
export record Span: Copy {
154 238
    /// Byte offset from the start of the source file.
155 239
    offset: u32,
156 240
    /// Length of the node in bytes.
157 241
    length: u32,
158 242
}
159 243
244 +
/// Comment, blank line, or source layout choice that a parser keeps for source
245 +
/// printers.
246 +
export union TriviaKind: Copy {
247 +
    /// Line comment from `//` to the end of the line, without the line break
248 +
    /// or trailing whitespace.
249 +
    Comment(*[u8]),
250 +
    /// One or more empty lines.
251 +
    BlankLine,
252 +
    /// The `throws` clause of a function, method, or trait method signature
253 +
    /// started on a later line than the token before it. Attached as closing
254 +
    /// trivia to the node that owns the signature.
255 +
    StackedThrows,
256 +
    /// The source broke a construct of the node across lines, at the given
257 +
    /// place. Printers keep such a construct broken when it fits on one line.
258 +
    /// Attached as trivia only by a parser that keeps trivia.
259 +
    Broken(BrokenSite),
260 +
}
261 +
262 +
/// Place in a node where the source has a line break that a printer keeps.
263 +
export union BrokenSite: Copy {
264 +
    /// The closing delimiter of the node's list of items is on a later line
265 +
    /// than the opening one: arguments, array items, record fields, or the
266 +
    /// parameters of a function.
267 +
    List,
268 +
    /// Same as [`BrokenSite::List`], for the `throws` list of a function or
269 +
    /// function type.
270 +
    Throws,
271 +
    /// The operands of a binary operation, or the parts of a conditional
272 +
    /// expression, are on different lines. A binary chain is marked on each
273 +
    /// operation that has a break.
274 +
    Chain,
275 +
    /// The node's list has two or more items, and every item starts on a line
276 +
    /// of its own. The list is marked [`BrokenSite::List`] too. A printer
277 +
    /// keeps one item per line.
278 +
    Items,
279 +
    /// An array item starts on a new source line. Attached as leading trivia
280 +
    /// to the item.
281 +
    ItemLine,
282 +
    /// The node, such as a union variant, starts on the line where the item
283 +
    /// before it in its list ends.
284 +
    Joined,
285 +
    /// The value of a statement or prong starts on a later line than the
286 +
    /// `=`, assignment operator, or `=>` before it. Attached to the statement
287 +
    /// or prong.
288 +
    Value,
289 +
}
290 +
291 +
/// Position of trivia relative to the node it is attached to.
292 +
export union TriviaPlacement: Copy {
293 +
    /// On lines before the node.
294 +
    Leading,
295 +
    /// After the node, on the line where the node ends.
296 +
    Trailing,
297 +
    /// Inside the node, after its last child and before its closing delimiter.
298 +
    Closing,
299 +
}
300 +
301 +
/// Comment, blank line, or layout mark attached to a node.
302 +
export record Trivia: Copy {
303 +
    /// Node that the trivia is attached to.
304 +
    node: *Node,
305 +
    /// Position relative to `node`.
306 +
    placement: TriviaPlacement,
307 +
    /// Comment, blank line, or layout mark.
308 +
    kind: TriviaKind,
309 +
}
310 +
160 311
/// Type signature node.
161 312
export union TypeSig: Copy {
162 313
    /// Absence of type.
163 314
    Void,
164 315
    /// A function return type with no possible value.
815 966
    span: Span,
816 967
    /// Variant-specific payload for the node.
817 968
    value: NodeValue,
818 969
}
819 970
971 +
/// Check whether a statement is followed by `;`.
972 +
///
973 +
/// Statements that end with a block are not. All other statements are.
974 +
export fn needsSemicolon(stmt: *Node) -> bool {
975 +
    match stmt.value {
976 +
        case NodeValue::If(_),
977 +
            NodeValue::IfLet(_),
978 +
            NodeValue::While(_),
979 +
            NodeValue::WhileLet(_),
980 +
            NodeValue::For(_),
981 +
            NodeValue::Loop { .. },
982 +
            NodeValue::Match(_),
983 +
            NodeValue::Block(_),
984 +
            NodeValue::FnDecl(_),
985 +
            NodeValue::RecordDecl(_),
986 +
            NodeValue::UnionDecl(_),
987 +
            NodeValue::TraitDecl { .. },
988 +
            NodeValue::InstanceDecl { .. },
989 +
            NodeValue::MethodDecl { .. } =>
990 +
            return false,
991 +
        else => return true,
992 +
    }
993 +
}
994 +
820 995
/// Check whether a node is a place expression.
821 996
///
822 997
/// Place expressions have persistent storage and can appear on the left side
823 998
/// of `set` assignments.
824 999
export fn isPlaceExpr(node: *Node) -> bool {
lib/std/lang/ast/printer.rad +104 -91
3 3
use std::io;
4 4
use std::lang::sexpr;
5 5
use std::lang::alloc;
6 6
use std::lang::types;
7 7
8 -
/// Return the symbol for a binary operator.
9 -
fn binOpName(op: super::BinaryOp) -> *[u8] {
10 -
    match op {
11 -
        case super::BinaryOp::Add => return "+",
12 -
        case super::BinaryOp::Sub => return "-",
13 -
        case super::BinaryOp::Mul => return "*",
14 -
        case super::BinaryOp::Div => return "/",
15 -
        case super::BinaryOp::Mod => return "%",
16 -
        case super::BinaryOp::BitAnd => return "&",
17 -
        case super::BinaryOp::BitOr => return "|",
18 -
        case super::BinaryOp::BitXor => return "^",
19 -
        case super::BinaryOp::Shl => return "<<",
20 -
        case super::BinaryOp::Shr => return ">>",
21 -
        case super::BinaryOp::Eq => return "==",
22 -
        case super::BinaryOp::Ne => return "<>",
23 -
        case super::BinaryOp::Lt => return "<",
24 -
        case super::BinaryOp::Gt => return ">",
25 -
        case super::BinaryOp::Lte => return "<=",
26 -
        case super::BinaryOp::Gte => return ">=",
27 -
        case super::BinaryOp::And => return "and",
28 -
        case super::BinaryOp::Or => return "or",
29 -
        case super::BinaryOp::Xor => return "xor",
30 -
    }
31 -
}
32 -
33 -
/// Return the symbol for a unary operator.
34 -
fn unOpName(op: super::UnaryOp) -> *[u8] {
35 -
    match op {
36 -
        case super::UnaryOp::Not => return "not",
37 -
        case super::UnaryOp::Neg => return "-",
38 -
        case super::UnaryOp::BitNot => return "~",
39 -
    }
40 -
}
41 -
42 -
/// Return the name for a builtin.
43 -
fn builtinName(kind: super::Builtin) -> *[u8] {
44 -
    match kind {
45 -
        case super::Builtin::SizeOf => return "@sizeOf",
46 -
        case super::Builtin::AlignOf => return "@alignOf",
47 -
        case super::Builtin::SliceOf => return "@sliceOf",
48 -
    }
49 -
}
50 -
51 -
/// Return the name for an integer type.
52 -
fn intTypeName(width: u8, sign: super::Signedness) -> *[u8] {
53 -
    if let case super::Signedness::Signed = sign {
54 -
        match width {
55 -
            case 1 => return "i8",
56 -
            case 2 => return "i16",
57 -
            case 4 => return "i32",
58 -
            case 8 => return "i64",
59 -
            else => panic,
60 -
        }
61 -
    } else {
62 -
        match width {
63 -
            case 1 => return "u8",
64 -
            case 2 => return "u16",
65 -
            case 4 => return "u32",
66 -
            case 8 => return "u64",
67 -
            else => panic,
68 -
        }
69 -
    }
70 -
}
71 -
72 8
/// Return the S-expression head for a pointer class.
73 9
fn pointerClassHead(
74 10
    class: types::PointerClass,
75 11
    ownedHead: *[u8],
76 12
    refHead: *[u8],
88 24
    match sig {
89 25
        case super::TypeSig::Void => return sexpr::sym("void"),
90 26
        case super::TypeSig::Never => return sexpr::sym("!"),
91 27
        case super::TypeSig::Opaque => return sexpr::sym("opaque"),
92 28
        case super::TypeSig::Bool => return sexpr::sym("bool"),
93 -
        case super::TypeSig::Integer { width, sign } => return sexpr::sym(intTypeName(width, sign)),
29 +
        case super::TypeSig::Integer { width, sign } => return sexpr::sym(super::integerName(width, sign)),
94 30
        case super::TypeSig::Array { itemType, length } =>
95 31
            return sexpr::list(a, "array", &[toExpr(a, itemType), toExpr(a, length)]),
96 32
        case super::TypeSig::Slice { class, itemType, mutable } => {
97 33
            let head = pointerClassHead(class, "slice", "slice-ref", "unsafe-slice");
98 34
            return sexpr::list(a, head, &[sexpr::sym("mut"), toExpr(a, itemType)]) if mutable
104 40
                else sexpr::list(a, head, &[toExpr(a, valueType)]);
105 41
        }
106 42
        case super::TypeSig::Optional { valueType } =>
107 43
            return sexpr::list(a, "?", &[toExpr(a, valueType)]),
108 44
        case super::TypeSig::Nominal(name) => return toExpr(a, name),
109 -
        case super::TypeSig::Record { fields, .. } =>
110 -
            return sexpr::list(a, "record", nodeListToExprs(a, fields)),
45 +
        case super::TypeSig::Record { fields, labeled } =>
46 +
            return sexpr::list(
47 +
                a, "record" if labeled else "tuple", nodeListToExprs(a, fields)
48 +
            ),
111 49
        case super::TypeSig::Fn { sig, isUnsafe } => {
112 50
            let mut ret = sexpr::sym("void");
113 51
            if let rt = sig.returnType {
114 52
                set ret = toExpr(a, rt);
115 53
            }
116 54
            let head = "unsafe-fn" if isUnsafe else "fn";
117 -
            return sexpr::list(a, head, &[sexpr::list(a, "params", nodeListToExprs(a, sig.params)), ret]);
55 +
            let params = nodeListToExprs(a, sig.params);
56 +
            return sexpr::list(a, head, &[
57 +
                sexpr::list(a, "params", params), ret, throwsToExpr(a, sig)
58 +
            ]);
118 59
        }
119 60
        case super::TypeSig::TraitObject { class, traitName, mutable } => {
120 61
            let head = pointerClassHead(class, "obj", "obj-ref", "unsafe-obj");
121 62
            return sexpr::list(a, head, &[sexpr::sym("mut"), toExpr(a, traitName)]) if mutable
122 63
                else sexpr::list(a, head, &[toExpr(a, traitName)]);
143 84
        set exprs = nodeListToExprs(a, list.list);
144 85
    }
145 86
    return sexpr::list(a, "attrs", exprs);
146 87
}
147 88
89 +
/// Convert a throw list to a `throws` expression.
90 +
fn throwsToExpr(a: &mut opaque alloc::Allocator, sig: super::FnSig)
91 +
    -> sexpr::Expr {
92 +
    return sexpr::list(a, "throws", nodeListToExprs(a, sig.throwList));
93 +
}
94 +
95 +
/// Convert the kind of a pattern match to an expression, or `Null` for the
96 +
/// binding kind.
97 +
fn patternKindExpr(kind: super::PatternKind) -> sexpr::Expr {
98 +
    if kind == super::PatternKind::Case {
99 +
        return sexpr::sym("case");
100 +
    }
101 +
    return sexpr::Expr::Null;
102 +
}
103 +
148 104
/// Convert an optional node to an expression, or return placeholder.
149 105
fn toExprOpt(a: &mut opaque alloc::Allocator, opt: ?*super::Node) -> sexpr::Expr {
150 106
    if let n = opt {
151 107
        return toExpr(a, n);
152 108
    }
237 193
    }
238 194
    return buf;
239 195
}
240 196
241 197
/// Convert a union variant to an S-expression.
242 -
fn variantToExpr(a: &mut opaque alloc::Allocator, name: *super::Node, type: ?*super::Node)
243 -
    -> sexpr::Expr {
244 -
    return sexpr::list(a, "variant", &[toExpr(a, name), toExprOrNull(a, type)]);
198 +
fn variantToExpr(
199 +
    a: &mut opaque alloc::Allocator,
200 +
    name: *super::Node,
201 +
    type: ?*super::Node,
202 +
    value: ?*super::Node
203 +
) -> sexpr::Expr {
204 +
    return sexpr::list(a, "variant", &[
205 +
        toExpr(a, name), toExprOrNull(a, type), toExprOrNull(a, value)
206 +
    ]);
245 207
}
246 208
247 209
/// Convert a list of union variants to expressions.
248 210
fn variantListToExprs(a: &mut opaque alloc::Allocator, nodes: &[*super::Node]) -> *[sexpr::Expr] {
249 211
    if nodes.len == 0 {
251 213
    }
252 214
    let buf = try! sexpr::allocExprs(a, nodes.len as u32);
253 215
    for node, i in nodes {
254 216
        match node.value {
255 217
            case super::NodeValue::UnionDeclVariant(v) => {
256 -
                set buf[i] = variantToExpr(a, v.name, v.type);
218 +
                set buf[i] = variantToExpr(a, v.name, v.type, v.value);
257 219
            }
258 220
            else => {
259 221
                set buf[i] = sexpr::sym("<invalid>");
260 222
            }
261 223
        }
283 245
        case super::NodeValue::Break => return sexpr::list(a, "break", &[]),
284 246
        case super::NodeValue::Continue => return sexpr::list(a, "continue", &[]),
285 247
        case super::NodeValue::Range(r) =>
286 248
            return sexpr::list(a, "range", &[toExprOpt(a, r.start), toExprOpt(a, r.end)]),
287 249
        case super::NodeValue::BinOp(b) =>
288 -
            return sexpr::list(a, binOpName(b.op), &[toExpr(a, b.left), toExpr(a, b.right)]),
250 +
            return sexpr::list(a, super::binaryText(b.op), &[toExpr(a, b.left), toExpr(a, b.right)]),
289 251
        case super::NodeValue::UnOp(u) =>
290 -
            return sexpr::list(a, unOpName(u.op), &[toExpr(a, u.value)]),
252 +
            return sexpr::list(a, super::unaryText(u.op), &[toExpr(a, u.value)]),
291 253
        case super::NodeValue::Call(c) => {
292 254
            let buf = try! sexpr::allocExprs(a, c.args.len as u32 + 1);
293 255
            set buf[0] = toExpr(a, c.callee);
294 256
            for arg, i in c.args { set buf[i + 1] = toExpr(a, arg); }
295 257
            return sexpr::Expr::List { head: "call", tail: buf, multiline: false };
296 258
        }
297 259
        case super::NodeValue::BuiltinCall { kind, args } =>
298 -
            return sexpr::list(a, builtinName(kind), nodeListToExprs(a, args)),
260 +
            return sexpr::list(a, super::builtinText(kind), nodeListToExprs(a, args)),
299 261
        case super::NodeValue::Subscript { container, index } =>
300 262
            return sexpr::list(a, "[]", &[toExpr(a, container), toExpr(a, index)]),
301 263
        case super::NodeValue::FieldAccess(acc) =>
302 264
            return sexpr::list(a, ".", &[toExpr(a, acc.parent), toExpr(a, acc.child)]),
303 265
        case super::NodeValue::ScopeAccess(acc) =>
316 278
        case super::NodeValue::RecordLit(lit) => {
317 279
            let mut total: u32 = lit.fields.len as u32;
318 280
            if let _ = lit.typeName {
319 281
                set total += 1;
320 282
            }
283 +
            if lit.ignoreRest {
284 +
                set total += 1;
285 +
            }
321 286
            let buf = try! sexpr::allocExprs(a, total);
322 287
            let mut idx: u32 = 0;
323 288
            if let tn = lit.typeName {
324 289
                set buf[idx] = toExpr(a, tn); set idx = idx + 1;
325 290
            }
326 291
            for field, i in lit.fields {
327 292
                set buf[idx + i] = toExpr(a, field);
328 293
            }
294 +
            if lit.ignoreRest {
295 +
                set buf[total - 1] = sexpr::sym("..");
296 +
            }
329 297
            return sexpr::Expr::List { head: "record-lit", tail: buf, multiline: lit.fields.len > 2 };
330 298
        }
331 299
        case super::NodeValue::RecordLitField(f) =>
332 300
            return sexpr::list(a, "field", &[toExprOpt(a, f.label), toExpr(a, f.value)]),
333 301
        case super::NodeValue::TypeSig(sig) => return typeSigToExpr(a, sig),
345 313
            }
346 314
        }
347 315
        case super::NodeValue::Try(t) => {
348 316
            let mut head = "try";
349 317
            if t.shouldPanic { set head = "try!"; }
318 +
            if t.returnsOptional { set head = "try?"; }
350 319
            if t.catches.len > 0 {
351 320
                let catches = nodeListToExprs(a, t.catches);
352 321
                return sexpr::list(a, head, &[toExpr(a, t.expr), sexpr::block(a, "catches", &[], catches)]);
353 322
            }
354 323
            return sexpr::list(a, head, &[toExpr(a, t.expr)]);
378 347
            let mut head = "let";
379 348
            if decl.mutable { set head = "let-mut"; }
380 349
            return sexpr::list(a, head, &[
381 350
                toExpr(a, decl.ident),
382 351
                toExprOrNull(a, decl.type),
383 -
                toExpr(a, decl.value)
352 +
                toExpr(a, decl.value),
353 +
                toExprOrNull(a, decl.alignment)
384 354
            ]);
385 355
        }
386 356
        case super::NodeValue::ConstDecl(decl) =>
387 -
            return sexpr::list(a, "constant", &[toExpr(a, decl.ident), toExpr(a, decl.type), toExpr(a, decl.value)]),
357 +
            return sexpr::list(a, "constant", &[
358 +
                toExpr(a, decl.ident), toExpr(a, decl.type),
359 +
                toExpr(a, decl.value), attributesToExpr(a, decl.attrs)
360 +
            ]),
388 361
        case super::NodeValue::StaticDecl(decl) =>
389 -
            return sexpr::list(a, "static", &[toExpr(a, decl.ident), toExpr(a, decl.type), toExpr(a, decl.value)]),
362 +
            return sexpr::list(a, "static", &[
363 +
                toExpr(a, decl.ident), toExpr(a, decl.type),
364 +
                toExpr(a, decl.value), attributesToExpr(a, decl.attrs)
365 +
            ]),
390 366
        case super::NodeValue::Assign(a_) =>
391 367
            return sexpr::list(a, "assign", &[toExpr(a, a_.left), toExpr(a, a_.right)]),
392 368
        case super::NodeValue::Return { value } =>
393 369
            return sexpr::list(a, "return", &[toExprOrNull(a, value)]),
394 370
        case super::NodeValue::Throw { expr } =>
403 379
        case super::NodeValue::IfLet(c) => {
404 380
            let label = "if-let-mut" if c.pattern.mutable else "if-let";
405 381
            return sexpr::block(a, label, &[
406 382
                toExpr(a, c.pattern.pattern),
407 383
                toExpr(a, c.pattern.scrutinee),
408 -
                guardExpr(a, c.pattern.guard)
384 +
                guardExpr(a, c.pattern.guard),
385 +
                patternKindExpr(c.pattern.kind)
409 386
            ], &[
410 387
                toExpr(a, c.thenBranch),
411 388
                toExprOrNull(a, c.elseBranch)
412 389
            ]);
413 390
        }
414 391
        case super::NodeValue::LetElse(l) => {
415 392
            let label = "let-mut-else" if l.pattern.mutable else "let-else";
416 393
            return sexpr::block(a, label, &[
417 394
                toExpr(a, l.pattern.pattern),
418 395
                toExpr(a, l.pattern.scrutinee),
419 -
                guardExpr(a, l.pattern.guard)
396 +
                guardExpr(a, l.pattern.guard),
397 +
                patternKindExpr(l.pattern.kind)
420 398
            ], &[toExpr(a, l.elseBranch)]);
421 399
        }
422 400
        case super::NodeValue::While(w) =>
423 401
            return sexpr::block(a, "while", &[
424 402
                toExpr(a, w.condition)
429 407
        case super::NodeValue::WhileLet(w) => {
430 408
            let label = "while-let-mut" if w.pattern.mutable else "while-let";
431 409
            return sexpr::block(a, label, &[
432 410
                toExpr(a, w.pattern.pattern),
433 411
                toExpr(a, w.pattern.scrutinee),
434 -
                guardExpr(a, w.pattern.guard)
412 +
                guardExpr(a, w.pattern.guard),
413 +
                patternKindExpr(w.pattern.kind)
435 414
            ], &[
436 415
                toExpr(a, w.body),
437 416
                toExprOrNull(a, w.elseBranch)
438 417
            ]);
439 418
        }
453 432
            return prongToExpr(a, p);
454 433
        }
455 434
        case super::NodeValue::FnDecl(f) => {
456 435
            let params = sexpr::list(a, "params", nodeListToExprs(a, f.sig.params));
457 436
            let ret = toExprOrNull(a, f.sig.returnType);
437 +
            let attrs = attributesToExpr(a, f.attrs);
438 +
            let thrown = throwsToExpr(a, f.sig);
458 439
            if let body = f.body {
459 -
                return sexpr::block(a, "fn", &[toExpr(a, f.name), params, ret], &[toExpr(a, body)]);
440 +
                return sexpr::block(a, "fn", &[
441 +
                    toExpr(a, f.name), params, ret, attrs, thrown
442 +
                ], &[toExpr(a, body)]);
460 443
            }
461 -
            return sexpr::list(a, "fn", &[toExpr(a, f.name), params, ret]);
444 +
            return sexpr::list(a, "fn", &[
445 +
                toExpr(a, f.name), params, ret, attrs, thrown
446 +
            ]);
447 +
        }
448 +
        case super::NodeValue::Mod(m) =>
449 +
            return sexpr::list(a, "mod", &[
450 +
                toExpr(a, m.name), attributesToExpr(a, m.attrs)
451 +
            ]),
452 +
        case super::NodeValue::Use(u_) => {
453 +
            let wildcard = sexpr::sym("*") if u_.wildcard
454 +
                else sexpr::Expr::Null;
455 +
            return sexpr::list(a, "use", &[
456 +
                toExpr(a, u_.path), wildcard, attributesToExpr(a, u_.attrs)
457 +
            ]);
462 458
        }
463 -
        case super::NodeValue::Mod(m) => return sexpr::list(a, "mod", &[toExpr(a, m.name)]),
464 -
        case super::NodeValue::Use(u_) => return sexpr::list(a, "use", &[toExpr(a, u_.path)]),
465 459
        case super::NodeValue::RecordDecl(r) => {
466 460
            let children = fieldListToExprs(a, r.fields);
467 461
            let mut head = "record";
468 462
            if let attrs = r.attrs;
469 463
            super::attributesContains(&attrs, super::Attribute::Opaque) {
470 464
                set head = "opaque-record";
471 465
            }
472 -
            return sexpr::block(a, head, &[toExpr(a, r.name)], children);
466 +
            let derives = nodeListToExprs(a, r.derives);
467 +
            let unlabeled = sexpr::Expr::Null if r.labeled
468 +
                else sexpr::sym("tuple");
469 +
            return sexpr::block(a, head, &[
470 +
                toExpr(a, r.name), attributesToExpr(a, r.attrs),
471 +
                sexpr::list(a, "derives", derives), unlabeled
472 +
            ], children);
473 473
        }
474 474
        case super::NodeValue::RecordField { field, type, value } => {
475 475
            return fieldToExpr(a, field, type, value);
476 476
        }
477 477
        case super::NodeValue::UnionDecl(u_) => {
478 478
            let children = variantListToExprs(a, u_.variants);
479 -
            return sexpr::block(a, "union", &[toExpr(a, u_.name)], children);
479 +
            return sexpr::block(a, "union", &[
480 +
                toExpr(a, u_.name), attributesToExpr(a, u_.attrs),
481 +
                sexpr::list(a, "derives", nodeListToExprs(a, u_.derives))
482 +
            ], children);
480 483
        }
481 484
        case super::NodeValue::UnionDeclVariant(v) => {
482 -
            return variantToExpr(a, v.name, v.type);
485 +
            return variantToExpr(a, v.name, v.type, v.value);
483 486
        }
484 487
        case super::NodeValue::ExprStmt(e) => return toExpr(a, e),
485 -
        case super::NodeValue::TraitDecl { name, supertraits, methods, .. } => {
488 +
        case super::NodeValue::TraitDecl {
489 +
            name, supertraits, methods, attrs
490 +
        } => {
486 491
            let children = nodeListToExprs(a, methods);
487 492
            let supers = sexpr::list(a, "supertraits", nodeListToExprs(a, supertraits));
488 -
            return sexpr::block(a, "trait", &[toExpr(a, name), supers], children);
493 +
            return sexpr::block(a, "trait", &[
494 +
                toExpr(a, name), supers, attributesToExpr(a, attrs)
495 +
            ], children);
489 496
        }
490 497
        case super::NodeValue::TraitMethodSig { name, receiver, sig, attrs } => {
491 498
            let params = sexpr::list(a, "params", nodeListToExprs(a, sig.params));
492 499
            let ret = toExprOrNull(a, sig.returnType);
493 500
            let attributes = attributesToExpr(a, attrs);
494 501
            return sexpr::list(
495 502
                a,
496 503
                "methodSig",
497 -
                &[attributes, toExpr(a, receiver), toExpr(a, name), params, ret],
504 +
                &[
505 +
                    attributes, toExpr(a, receiver), toExpr(a, name), params,
506 +
                    ret, throwsToExpr(a, sig),
507 +
                ],
498 508
            );
499 509
        }
500 510
        case super::NodeValue::InstanceDecl { traitName, targetType, methods } => {
501 511
            let children = nodeListToExprs(a, methods);
502 512
            return sexpr::block(a, "instance", &[toExpr(a, traitName), toExpr(a, targetType)], children);
515 525
                    toExpr(a, receiverType),
516 526
                    toExpr(a, receiverName),
517 527
                    toExpr(a, name),
518 528
                    params,
519 529
                    ret,
530 +
                    throwsToExpr(a, sig),
520 531
                ],
521 532
                &[toExpr(a, body)],
522 533
            );
523 534
        }
535 +
        case super::NodeValue::Align { value } =>
536 +
            return sexpr::list(a, "align", &[toExpr(a, value)]),
524 537
        else => return sexpr::sym("?"),
525 538
    }
526 539
}
527 540
528 541
/// Dump the tree rooted at `root`, allocating the expression tree from `a`.
lib/std/lang/layout.rad added +133 -0
1 +
//! Renderer-independent source layout.
2 +
//!
3 +
//! A layout is a tree of boxes. Each child of a box states where it goes
4 +
//! relative to the previous sibling: on the same line, on a new line, or on a
5 +
//! new line one level deeper. Soft placements let a renderer choose between a
6 +
//! flat and a broken form of each box, by its own measure of width, and
7 +
//! choices let it pick between whole alternative layouts. Tab stops line up
8 +
//! the content of consecutive rows. Layouts hold no output state, so text
9 +
//! printers, editors, and other views can render the same layout.
10 +
11 +
use std::lang::alloc;
12 +
use std::lang::ast;
13 +
14 +
export mod text;
15 +
@test mod tests;
16 +
17 +
/// Number of columns that tab stops can line up.
18 +
export constant CELL_COLUMNS: u32 = 2;
19 +
20 +
/// Purpose of a text fragment, for renderers that style or select text.
21 +
export union Role: Copy {
22 +
    /// Reserved word, eg. `fn` or `match`.
23 +
    Keyword,
24 +
    /// Identifier, eg. a variable, type, or field name.
25 +
    Name,
26 +
    /// Number, string, character, boolean, or `nil` literal.
27 +
    Literal,
28 +
    /// Operator, eg. `+`, `==`, `and`, or `=`.
29 +
    Operator,
30 +
    /// Punctuation, eg. `(`, `,`, or `;`.
31 +
    Punct,
32 +
    /// Line comment, including the leading `//`.
33 +
    Comment,
34 +
}
35 +
36 +
/// Horizontal gap between a child and the content before it on the same line.
37 +
export union Gap: Copy {
38 +
    /// No gap.
39 +
    None,
40 +
    /// One space.
41 +
    Space,
42 +
}
43 +
44 +
/// Where a child goes relative to the previous sibling in its box.
45 +
///
46 +
/// The first child of a box goes relative to the content before the box.
47 +
export union Placement: Copy {
48 +
    /// On the same line.
49 +
    Inline(Gap),
50 +
    /// On a new line at the box indentation.
51 +
    Line,
52 +
    /// On a new line one level deeper than the box indentation.
53 +
    Indent,
54 +
    /// `Inline` when the box is flat, otherwise `Line`.
55 +
    SoftLine(Gap),
56 +
    /// `Inline` when the box is flat, otherwise `Indent`.
57 +
    SoftIndent(Gap),
58 +
}
59 +
60 +
/// Child of a box with its placement.
61 +
export record Child: Copy {
62 +
    /// Where the child goes relative to the previous sibling.
63 +
    placement: Placement,
64 +
    /// Child layout.
65 +
    layout: *Layout,
66 +
}
67 +
68 +
/// Layout element.
69 +
export union Item: Copy {
70 +
    /// Text fragment without line breaks.
71 +
    Text {
72 +
        /// Text bytes.
73 +
        text: *[u8],
74 +
        /// Purpose of the text.
75 +
        role: Role,
76 +
    },
77 +
    /// Box of children whose soft placements are all flat or all broken.
78 +
    ///
79 +
    /// A box has the indentation of its parent, plus one level when it is
80 +
    /// placed with `Indent`, or with `SoftIndent` in a broken parent.
81 +
    Box(*[Child]),
82 +
    /// Text that is present only when the parent box is broken, eg. the
83 +
    /// trailing comma of a vertical list.
84 +
    BrokenText {
85 +
        /// Text bytes.
86 +
        text: *[u8],
87 +
        /// Purpose of the text.
88 +
        role: Role,
89 +
    },
90 +
    /// Empty line. Placed with `Line` or `Indent`.
91 +
    Blank,
92 +
    /// Alternative layouts of the same content, in order of preference.
93 +
    ///
94 +
    /// A renderer takes the first alternative that fits, and the last one when
95 +
    /// none does. Content before a choice can break where its alternative that
96 +
    /// breaks first does. Alternatives may share layouts.
97 +
    Choice(*[*Layout]),
98 +
    /// Tab stop of a column, eg. after the pattern of a match prong or after
99 +
    /// the code that a trailing comment follows.
100 +
    ///
101 +
    /// A row is a child that starts a line and the children after it on the
102 +
    /// same line, with everything inside them. A renderer takes consecutive
103 +
    /// rows that each fit on one line as a run, and pads each row at its tab
104 +
    /// stop of a column to the widest column in the run, so that the content
105 +
    /// after the stops starts in one column. It leaves a run unpadded if the
106 +
    /// padding would put content at or past the line width. A row that does
107 +
    /// not fit on one line, a blank line, and a line on its own end a run. A
108 +
    /// stop takes no space itself. A row has at most one stop of a column,
109 +
    /// and the stops of lower columns come first.
110 +
    Tab(u32),
111 +
    /// Box that is broken whether or not it fits, eg. the last argument of a
112 +
    /// call that opens on the line of the call. A choice measures it up to
113 +
    /// its earliest possible line break.
114 +
    Broken(*Layout),
115 +
}
116 +
117 +
/// Layout tree node.
118 +
export record Layout: Copy {
119 +
    /// AST node that this layout presents, if any.
120 +
    source: ?*ast::Node,
121 +
    /// Layout element.
122 +
    item: Item,
123 +
}
124 +
125 +
/// Allocate a layout node with the given source node and item.
126 +
export fn new(
127 +
    a: &mut opaque alloc::Allocator, source: ?*ast::Node, item: Item
128 +
) -> *Layout throws (alloc::AllocError) {
129 +
    let mut nodes: *mut [Layout] = &mut [];
130 +
    try nodes.append(Layout { source, item }, a);
131 +
132 +
    return &nodes[0];
133 +
}
lib/std/lang/layout/tests.rad added +637 -0
1 +
//! Tests for the text renderer.
2 +
3 +
use std::io;
4 +
use std::mem;
5 +
use std::testing;
6 +
use std::lang::alloc;
7 +
use std::lang::sexpr;
8 +
9 +
use std::lang::layout;
10 +
use std::lang::layout::Child;
11 +
use std::lang::layout::Gap;
12 +
use std::lang::layout::Item;
13 +
use std::lang::layout::Layout;
14 +
use std::lang::layout::Placement;
15 +
use std::lang::layout::Role;
16 +
17 +
/// Placement on the same line with no gap.
18 +
fn none() -> Placement {
19 +
    return Placement::Inline(Gap::None);
20 +
}
21 +
22 +
/// Placement on the same line after a space.
23 +
fn space() -> Placement {
24 +
    return Placement::Inline(Gap::Space);
25 +
}
26 +
27 +
/// Soft placement with no gap, on the same line when flat.
28 +
fn soft() -> Placement {
29 +
    return Placement::SoftLine(Gap::None);
30 +
}
31 +
32 +
/// Soft placement with a space, on the same line when flat.
33 +
fn softSpace() -> Placement {
34 +
    return Placement::SoftLine(Gap::Space);
35 +
}
36 +
37 +
/// Soft indented placement with no gap.
38 +
fn softIndent() -> Placement {
39 +
    return Placement::SoftIndent(Gap::None);
40 +
}
41 +
42 +
/// Allocate a text layout with the given role.
43 +
fn leaf(a: &mut opaque alloc::Allocator, s: *[u8], role: Role) -> *Layout {
44 +
    return try! layout::new(a, nil, Item::Text { text: s, role });
45 +
}
46 +
47 +
/// Allocate a name text layout.
48 +
fn text(a: &mut opaque alloc::Allocator, s: *[u8]) -> *Layout {
49 +
    return leaf(a, s, Role::Name);
50 +
}
51 +
52 +
/// Allocate a comment text layout.
53 +
fn comment(a: &mut opaque alloc::Allocator, s: *[u8]) -> *Layout {
54 +
    return leaf(a, s, Role::Comment);
55 +
}
56 +
57 +
/// Allocate a text layout that is present only in a broken box.
58 +
fn brokenText(a: &mut opaque alloc::Allocator, s: *[u8]) -> *Layout {
59 +
    let item = Item::BrokenText { text: s, role: Role::Punct };
60 +
    return try! layout::new(a, nil, item);
61 +
}
62 +
63 +
/// Allocate a blank line layout.
64 +
fn blank(a: &mut opaque alloc::Allocator) -> *Layout {
65 +
    return try! layout::new(a, nil, Item::Blank);
66 +
}
67 +
68 +
/// Allocate a choice between the given alternatives.
69 +
fn choice(a: &mut opaque alloc::Allocator, alts: &[*Layout]) -> *Layout {
70 +
    let mut copy: *mut [*Layout] = &mut [];
71 +
    for alt in alts {
72 +
        try! copy.append(alt, a);
73 +
    }
74 +
    return try! layout::new(a, nil, Item::Choice(copy));
75 +
}
76 +
77 +
/// Allocate a box layout that is always broken.
78 +
fn broken(a: &mut opaque alloc::Allocator, inner: *Layout) -> *Layout {
79 +
    return try! layout::new(a, nil, Item::Broken(inner));
80 +
}
81 +
82 +
/// Allocate a box layout with a copy of the given children.
83 +
fn box(a: &mut opaque alloc::Allocator, kids: &[Child]) -> *Layout {
84 +
    let mut copy: *mut [Child] = &mut [];
85 +
    for kid in kids {
86 +
        try! copy.append(kid, a);
87 +
    }
88 +
    return try! layout::new(a, nil, Item::Box(copy));
89 +
}
90 +
91 +
/// Build a child.
92 +
fn at(placement: Placement, layout: *Layout) -> Child {
93 +
    return Child { placement, layout };
94 +
}
95 +
96 +
/// Render the layout and check the output text.
97 +
unsafe fn expectRender(
98 +
    root: *Layout, width: u32, indent: u32, expected: *[u8]
99 +
) throws (testing::TestError) {
100 +
    static OUT: [u8; 512] = [0; 512];
101 +
    let mut buf = sexpr::Buffer { buf: &mut OUT[..], pos: 0 };
102 +
    {
103 +
        let sink: &mut opaque sexpr::Output = &mut buf;
104 +
        let options = layout::text::Options { width, indent };
105 +
        layout::text::render(root, options, sink);
106 +
    }
107 +
    if not mem::eq(&OUT[..buf.pos], expected) {
108 +
        io::print("--- expected\n");
109 +
        io::print(expected);
110 +
        io::print("--- actual\n");
111 +
        io::print(&OUT[..buf.pos]);
112 +
        io::print("---\n");
113 +
        throw testing::TestError::Failed;
114 +
    }
115 +
}
116 +
117 +
/// Build `call(aaaa, bbbb, cccc)` with soft breaks, followed by `;`.
118 +
fn call(a: &mut opaque alloc::Allocator, tail: *[u8]) -> *Layout {
119 +
    let args = box(a, &[
120 +
        at(none(), text(a, "aaaa,")),
121 +
        at(softSpace(), text(a, "bbbb,")),
122 +
        at(softSpace(), text(a, "cccc"))
123 +
    ]);
124 +
    let callee = box(a, &[
125 +
        at(none(), text(a, "call(")),
126 +
        at(softIndent(), args),
127 +
        at(soft(), text(a, ")"))
128 +
    ]);
129 +
    return box(a, &[at(none(), callee), at(none(), text(a, tail))]);
130 +
}
131 +
132 +
/// Test that a box that fits stays flat.
133 +
@test unsafe fn testFlatWhenFits() throws (testing::TestError) {
134 +
    static STORAGE: [u8; 4096] = [0; 4096];
135 +
    let mut arena = alloc::new(&mut STORAGE[..]);
136 +
    let a: &mut opaque alloc::Allocator = &mut arena;
137 +
    let root = call(a, "");
138 +
139 +
    try expectRender(root, 80, 4, "call(aaaa, bbbb, cccc)\n");
140 +
}
141 +
142 +
/// Test the exact-fit boundary, with and without following content.
143 +
@test unsafe fn testExactFitBoundary() throws (testing::TestError) {
144 +
    static STORAGE: [u8; 4096] = [0; 4096];
145 +
    let mut arena = alloc::new(&mut STORAGE[..]);
146 +
    let a: &mut opaque alloc::Allocator = &mut arena;
147 +
    let bare = call(a, "");
148 +
    let semi = call(a, ";");
149 +
150 +
    try expectRender(bare, 22, 4, "call(aaaa, bbbb, cccc)\n");
151 +
    try expectRender(bare, 21, 4, "call(\n    aaaa, bbbb, cccc\n)\n");
152 +
    try expectRender(semi, 23, 4, "call(aaaa, bbbb, cccc);\n");
153 +
    try expectRender(semi, 22, 4, "call(\n    aaaa, bbbb, cccc\n);\n");
154 +
}
155 +
156 +
/// Test that a broken box can contain flat boxes and broken ones.
157 +
@test unsafe fn testNestedBoxesDecideIndependently()
158 +
    throws (testing::TestError)
159 +
{
160 +
    static STORAGE: [u8; 4096] = [0; 4096];
161 +
    let mut arena = alloc::new(&mut STORAGE[..]);
162 +
    let a: &mut opaque alloc::Allocator = &mut arena;
163 +
    let root = call(a, "");
164 +
165 +
    try expectRender(root, 20, 4, "call(\n    aaaa, bbbb, cccc\n)\n");
166 +
    try expectRender(root, 15, 4, "call(\n    aaaa,\n    bbbb,\n    cccc\n)\n");
167 +
168 +
    let inner = box(a, &[
169 +
        at(none(), text(a, "bb")),
170 +
        at(softSpace(), text(a, "cc"))
171 +
    ]);
172 +
    let outer = box(a, &[
173 +
        at(none(), text(a, "aaaaaaaa")),
174 +
        at(softSpace(), inner),
175 +
        at(softSpace(), text(a, "dddddddd"))
176 +
    ]);
177 +
    try expectRender(outer, 23, 4, "aaaaaaaa bb cc dddddddd\n");
178 +
    try expectRender(outer, 20, 4, "aaaaaaaa\nbb cc\ndddddddd\n");
179 +
    try expectRender(outer, 4, 4, "aaaaaaaa\nbb\ncc\ndddddddd\n");
180 +
}
181 +
182 +
/// Test indentation levels for `Indent` and `SoftIndent` children.
183 +
@test unsafe fn testIndentLevels() throws (testing::TestError) {
184 +
    static STORAGE: [u8; 4096] = [0; 4096];
185 +
    let mut arena = alloc::new(&mut STORAGE[..]);
186 +
    let a: &mut opaque alloc::Allocator = &mut arena;
187 +
    let deep = box(a, &[
188 +
        at(none(), text(a, "y")),
189 +
        at(Placement::Indent, text(a, "z"))
190 +
    ]);
191 +
    let root = box(a, &[
192 +
        at(none(), text(a, "x")),
193 +
        at(Placement::Indent, deep),
194 +
        at(Placement::Line, text(a, "w"))
195 +
    ]);
196 +
    try expectRender(root, 80, 4, "x\n    y\n        z\nw\n");
197 +
    try expectRender(root, 80, 2, "x\n  y\n    z\nw\n");
198 +
199 +
    let flat = box(a, &[
200 +
        at(none(), text(a, "ab")),
201 +
        at(softIndent(), text(a, "cd")),
202 +
        at(soft(), text(a, "ef"))
203 +
    ]);
204 +
    try expectRender(flat, 6, 4, "abcdef\n");
205 +
    try expectRender(flat, 5, 4, "ab\n    cd\nef\n");
206 +
}
207 +
208 +
/// Test lazy indentation, blank lines, and the final newline.
209 +
@test unsafe fn testBlankLinesAndWhitespace() throws (testing::TestError) {
210 +
    static STORAGE: [u8; 4096] = [0; 4096];
211 +
    let mut arena = alloc::new(&mut STORAGE[..]);
212 +
    let a: &mut opaque alloc::Allocator = &mut arena;
213 +
214 +
    let gap = box(a, &[
215 +
        at(none(), text(a, "a")),
216 +
        at(Placement::Line, blank(a)),
217 +
        at(Placement::Line, text(a, "b"))
218 +
    ]);
219 +
    try expectRender(gap, 80, 4, "a\n\nb\n");
220 +
221 +
    let indented = box(a, &[
222 +
        at(none(), text(a, "a")),
223 +
        at(Placement::Indent, blank(a)),
224 +
        at(Placement::Indent, text(a, "b"))
225 +
    ]);
226 +
    try expectRender(indented, 80, 4, "a\n\n    b\n");
227 +
228 +
    let trailing = box(a, &[
229 +
        at(none(), text(a, "a")),
230 +
        at(Placement::Line, blank(a)),
231 +
        at(Placement::Line, blank(a))
232 +
    ]);
233 +
    try expectRender(trailing, 80, 4, "a\n");
234 +
235 +
    let leading = box(a, &[
236 +
        at(Placement::Line, blank(a)),
237 +
        at(space(), text(a, "a"))
238 +
    ]);
239 +
    try expectRender(leading, 80, 4, "a\n");
240 +
241 +
    let dropped = box(a, &[
242 +
        at(none(), text(a, "a")),
243 +
        at(Placement::Line, box(a, &[at(space(), text(a, "b"))]))
244 +
    ]);
245 +
    try expectRender(dropped, 80, 4, "a\nb\n");
246 +
247 +
    try expectRender(box(a, &[]), 80, 4, "");
248 +
}
249 +
250 +
/// Test that a comment forces the content after it onto a new line.
251 +
@test unsafe fn testCommentForcesBreak() throws (testing::TestError) {
252 +
    static STORAGE: [u8; 4096] = [0; 4096];
253 +
    let mut arena = alloc::new(&mut STORAGE[..]);
254 +
    let a: &mut opaque alloc::Allocator = &mut arena;
255 +
256 +
    let after = box(a, &[
257 +
        at(none(), text(a, "x")),
258 +
        at(space(), comment(a, "// c")),
259 +
        at(space(), text(a, "y"))
260 +
    ]);
261 +
    try expectRender(after, 80, 4, "x // c\ny\n");
262 +
263 +
    let args = box(a, &[
264 +
        at(none(), text(a, "a,")),
265 +
        at(softSpace(), comment(a, "// c")),
266 +
        at(softSpace(), text(a, "b"))
267 +
    ]);
268 +
    let call = box(a, &[
269 +
        at(none(), text(a, "f(")),
270 +
        at(softIndent(), args),
271 +
        at(soft(), text(a, ")"))
272 +
    ]);
273 +
    try expectRender(call, 80, 4, "f(\n    a,\n    // c\n    b\n)\n");
274 +
275 +
    let indented = box(a, &[
276 +
        at(none(), text(a, "{")),
277 +
        at(Placement::Indent, box(a, &[
278 +
            at(none(), comment(a, "// c")),
279 +
            at(space(), text(a, "z"))
280 +
        ]))
281 +
    ]);
282 +
    try expectRender(indented, 80, 4, "{\n    // c\n    z\n");
283 +
}
284 +
285 +
/// Test that a trailing comment before a line break does not break the box.
286 +
@test unsafe fn testTrailingCommentFits() throws (testing::TestError) {
287 +
    static STORAGE: [u8; 4096] = [0; 4096];
288 +
    let mut arena = alloc::new(&mut STORAGE[..]);
289 +
    let a: &mut opaque alloc::Allocator = &mut arena;
290 +
    let inner = box(a, &[
291 +
        at(none(), text(a, "a")),
292 +
        at(softSpace(), text(a, "b")),
293 +
        at(space(), comment(a, "// c"))
294 +
    ]);
295 +
    let root = box(a, &[
296 +
        at(none(), inner),
297 +
        at(Placement::Line, text(a, "d"))
298 +
    ]);
299 +
    try expectRender(root, 80, 4, "a b // c\nd\n");
300 +
}
301 +
302 +
/// Test that a comment takes no width, even when it is longer than the width.
303 +
@test unsafe fn testCommentWidth() throws (testing::TestError) {
304 +
    static STORAGE: [u8; 4096] = [0; 4096];
305 +
    let mut arena = alloc::new(&mut STORAGE[..]);
306 +
    let a: &mut opaque alloc::Allocator = &mut arena;
307 +
    let long = "// a comment past the width";
308 +
309 +
    let trailing = box(a, &[
310 +
        at(none(), call(a, ";")),
311 +
        at(space(), comment(a, long))
312 +
    ]);
313 +
    try expectRender(
314 +
        trailing, 24, 4, "call(aaaa, bbbb, cccc); // a comment past the width\n"
315 +
    );
316 +
317 +
    let alone = box(a, &[at(none(), comment(a, long))]);
318 +
    try expectRender(alone, 24, 4, "// a comment past the width\n");
319 +
320 +
    // Content after the comment on the same line still cannot fit.
321 +
    let args = box(a, &[
322 +
        at(none(), text(a, "a,")),
323 +
        at(space(), comment(a, long)),
324 +
        at(softSpace(), text(a, "b"))
325 +
    ]);
326 +
    let after = box(a, &[
327 +
        at(none(), text(a, "f(")),
328 +
        at(softIndent(), args),
329 +
        at(soft(), text(a, ")"))
330 +
    ]);
331 +
    try expectRender(
332 +
        after, 24, 4, "f(\n    a, // a comment past the width\n    b\n)\n"
333 +
    );
334 +
}
335 +
336 +
/// Build `if cond {` with a soft brace followed by a body.
337 +
fn ifStmt(a: &mut opaque alloc::Allocator) -> *Layout {
338 +
    let header = box(a, &[
339 +
        at(none(), text(a, "if")),
340 +
        at(space(), text(a, "cond")),
341 +
        at(softSpace(), text(a, "{"))
342 +
    ]);
343 +
    return box(a, &[
344 +
        at(none(), header),
345 +
        at(Placement::Indent, text(a, "x;")),
346 +
        at(Placement::Line, text(a, "}"))
347 +
    ]);
348 +
}
349 +
350 +
/// Test that the brace stays on the header line when it fits.
351 +
@test unsafe fn testIfBraceBehavior() throws (testing::TestError) {
352 +
    static STORAGE: [u8; 4096] = [0; 4096];
353 +
    let mut arena = alloc::new(&mut STORAGE[..]);
354 +
    let a: &mut opaque alloc::Allocator = &mut arena;
355 +
    let root = ifStmt(a);
356 +
357 +
    try expectRender(root, 9, 4, "if cond {\n    x;\n}\n");
358 +
    try expectRender(root, 8, 4, "if cond\n{\n    x;\n}\n");
359 +
}
360 +
361 +
/// Test that broken-only text appears only in a broken box, and counts for
362 +
/// the fit of a box that is flat.
363 +
@test unsafe fn testBrokenText() throws (testing::TestError) {
364 +
    static STORAGE: [u8; 4096] = [0; 4096];
365 +
    let mut arena = alloc::new(&mut STORAGE[..]);
366 +
    let a: &mut opaque alloc::Allocator = &mut arena;
367 +
    let list = box(a, &[
368 +
        at(none(), text(a, "ab")),
369 +
        at(softSpace(), text(a, "cd")),
370 +
        at(none(), brokenText(a, ","))
371 +
    ]);
372 +
    try expectRender(list, 5, 4, "ab cd\n");
373 +
    try expectRender(list, 4, 4, "ab\ncd,\n");
374 +
375 +
    // A flat box nested in a broken one omits its own broken text.
376 +
    let inner = box(a, &[
377 +
        at(none(), text(a, "x")),
378 +
        at(softSpace(), text(a, "y")),
379 +
        at(none(), brokenText(a, ";"))
380 +
    ]);
381 +
    let outer = box(a, &[
382 +
        at(none(), text(a, "aaaa")),
383 +
        at(softSpace(), inner),
384 +
        at(none(), brokenText(a, ","))
385 +
    ]);
386 +
    try expectRender(outer, 8, 4, "aaaa x y\n");
387 +
    try expectRender(outer, 7, 4, "aaaa\nx y,\n");
388 +
    try expectRender(outer, 2, 4, "aaaa\nx\ny;,\n");
389 +
}
390 +
391 +
/// Test that a box fits when the content after it can break before the end
392 +
/// of the line, even if that content does not fit flat.
393 +
@test unsafe fn testLaterBreaksCount() throws (testing::TestError) {
394 +
    static STORAGE: [u8; 4096] = [0; 4096];
395 +
    let mut arena = alloc::new(&mut STORAGE[..]);
396 +
    let a: &mut opaque alloc::Allocator = &mut arena;
397 +
    let chain = box(a, &[
398 +
        at(none(), text(a, "aa +")),
399 +
        at(softSpace(), text(a, "bb"))
400 +
    ]);
401 +
    let root = box(a, &[at(none(), chain), at(space(), call(a, ";"))]);
402 +
403 +
    try expectRender(root, 40, 4, "aa + bb call(aaaa, bbbb, cccc);\n");
404 +
    try expectRender(root, 20, 4, "aa + bb call(\n    aaaa, bbbb, cccc\n);\n");
405 +
    try expectRender(
406 +
        root, 12, 4, "aa +\nbb call(\n    aaaa,\n    bbbb,\n    cccc\n);\n"
407 +
    );
408 +
}
409 +
410 +
/// Build `lhs ==` followed by `rhs` on the same line if it fits, or on the
411 +
/// next line, then `tail`.
412 +
fn pair(a: &mut opaque alloc::Allocator, tail: *[u8]) -> *Layout {
413 +
    let same = box(a, &[at(space(), text(a, "rhs"))]);
414 +
    let next = box(a, &[at(Placement::Indent, text(a, "rhs"))]);
415 +
    return box(a, &[
416 +
        at(none(), text(a, "lhs ==")),
417 +
        at(none(), choice(a, &[same, next])),
418 +
        at(none(), text(a, tail))
419 +
    ]);
420 +
}
421 +
422 +
/// Test that a choice takes its first alternative that fits, else its last.
423 +
@test unsafe fn testChoice() throws (testing::TestError) {
424 +
    static STORAGE: [u8; 4096] = [0; 4096];
425 +
    let mut arena = alloc::new(&mut STORAGE[..]);
426 +
    let a: &mut opaque alloc::Allocator = &mut arena;
427 +
428 +
    try expectRender(pair(a, ""), 10, 4, "lhs == rhs\n");
429 +
    try expectRender(pair(a, ""), 9, 4, "lhs ==\n    rhs\n");
430 +
    try expectRender(pair(a, ";"), 11, 4, "lhs == rhs;\n");
431 +
    try expectRender(pair(a, ";"), 10, 4, "lhs ==\n    rhs;\n");
432 +
433 +
    // Content before a choice can break at its last alternative.
434 +
    let chain = box(a, &[
435 +
        at(none(), text(a, "aaaa,")),
436 +
        at(softSpace(), text(a, "bbbb"))
437 +
    ]);
438 +
    let same = box(a, &[at(space(), text(a, "rhs"))]);
439 +
    let next = box(a, &[at(Placement::Indent, text(a, "rhs"))]);
440 +
    let root = box(a, &[
441 +
        at(none(), chain),
442 +
        at(space(), text(a, "==")),
443 +
        at(none(), choice(a, &[same, next]))
444 +
    ]);
445 +
    try expectRender(root, 13, 4, "aaaa, bbbb ==\n    rhs\n");
446 +
447 +
    // An enclosing box measures a choice by its first alternative.
448 +
    let list = box(a, &[
449 +
        at(none(), text(a, "f(")),
450 +
        at(softIndent(), pair(a, "")),
451 +
        at(soft(), text(a, ")"))
452 +
    ]);
453 +
    try expectRender(list, 13, 4, "f(lhs == rhs)\n");
454 +
    try expectRender(list, 12, 4, "f(\n    lhs ==\n        rhs\n)\n");
455 +
}
456 +
457 +
/// Test that a broken box breaks even when it fits, and that a choice
458 +
/// measures it up to its first break.
459 +
@test unsafe fn testBroken() throws (testing::TestError) {
460 +
    static STORAGE: [u8; 4096] = [0; 4096];
461 +
    let mut arena = alloc::new(&mut STORAGE[..]);
462 +
    let a: &mut opaque alloc::Allocator = &mut arena;
463 +
    let fields = box(a, &[
464 +
        at(none(), text(a, "a: 1,")),
465 +
        at(softSpace(), text(a, "b: 2"))
466 +
    ]);
467 +
    let rec = box(a, &[
468 +
        at(none(), text(a, "R {")),
469 +
        at(Placement::SoftIndent(Gap::Space), fields),
470 +
        at(Placement::SoftLine(Gap::Space), text(a, "}"))
471 +
    ]);
472 +
    try expectRender(broken(a, rec), 80, 4, "R {\n    a: 1, b: 2\n}\n");
473 +
474 +
    let flat = box(a, &[
475 +
        at(none(), text(a, "f(x, ")),
476 +
        at(none(), rec),
477 +
        at(none(), text(a, ")"))
478 +
    ]);
479 +
    let hug = box(a, &[
480 +
        at(none(), text(a, "f(x, ")),
481 +
        at(none(), broken(a, rec)),
482 +
        at(none(), text(a, ")"))
483 +
    ]);
484 +
    let root = choice(a, &[flat, hug, text(a, "vertical")]);
485 +
    try expectRender(root, 22, 4, "f(x, R { a: 1, b: 2 })\n");
486 +
    try expectRender(root, 14, 4, "f(x, R {\n    a: 1, b: 2\n})\n");
487 +
    try expectRender(root, 12, 4, "f(x, R {\n    a: 1,\n    b: 2\n})\n");
488 +
    try expectRender(root, 7, 4, "vertical\n");
489 +
}
490 +
491 +
/// Test that a choice measures an alternative that starts on a new line on
492 +
/// that line.
493 +
@test unsafe fn testChoiceOnNewLine() throws (testing::TestError) {
494 +
    static STORAGE: [u8; 4096] = [0; 4096];
495 +
    let mut arena = alloc::new(&mut STORAGE[..]);
496 +
    let a: &mut opaque alloc::Allocator = &mut arena;
497 +
    let value = box(a, &[
498 +
        at(none(), text(a, "aaaa +")),
499 +
        at(Placement::SoftIndent(Gap::Space), text(a, "bbbb"))
500 +
    ]);
501 +
    let same = box(a, &[at(space(), value)]);
502 +
    let next = box(a, &[at(Placement::Indent, value)]);
503 +
    let root = box(a, &[
504 +
        at(none(), text(a, "x =")),
505 +
        at(none(), choice(a, &[same, next, same])),
506 +
        at(none(), text(a, ";"))
507 +
    ]);
508 +
    try expectRender(root, 16, 2, "x = aaaa + bbbb;\n");
509 +
    try expectRender(root, 15, 2, "x =\n  aaaa + bbbb;\n");
510 +
    try expectRender(root, 10, 2, "x = aaaa +\n  bbbb;\n");
511 +
}
512 +
513 +
/// Allocate a tab stop of the given column.
514 +
fn tab(a: &mut opaque alloc::Allocator, column: u32) -> *Layout {
515 +
    return try! layout::new(a, nil, Item::Tab(column));
516 +
}
517 +
518 +
/// Build a row of `name`, a tab stop of column 0, and the text `rest` after a
519 +
/// space.
520 +
fn arrow(
521 +
    a: &mut opaque alloc::Allocator, name: *[u8], rest: *[u8]
522 +
) -> *Layout {
523 +
    return box(a, &[
524 +
        at(none(), text(a, name)),
525 +
        at(none(), tab(a, 0)),
526 +
        at(space(), text(a, rest))
527 +
    ]);
528 +
}
529 +
530 +
/// Build the rows of `rows` on lines of their own.
531 +
fn table(a: &mut opaque alloc::Allocator, rows: &[*Layout]) -> *Layout {
532 +
    let mut kids: *mut [Child] = &mut [];
533 +
    for row in rows {
534 +
        try! kids.append(Child { placement: Placement::Line, layout: row }, a);
535 +
    }
536 +
    return try! layout::new(a, nil, Item::Box(kids));
537 +
}
538 +
539 +
/// Test that the cells of consecutive rows are padded to the widest one.
540 +
@test unsafe fn testAlignedCells() throws (testing::TestError) {
541 +
    static STORAGE: [u8; 4096] = [0; 4096];
542 +
    let mut arena = alloc::new(&mut STORAGE[..]);
543 +
    let a: &mut opaque alloc::Allocator = &mut arena;
544 +
    let root = table(a, &[
545 +
        arrow(a, "a", "=> x"),
546 +
        arrow(a, "bbb", "=> y"),
547 +
        arrow(a, "cc", "=> z")
548 +
    ]);
549 +
    try expectRender(root, 80, 4, "a   => x\nbbb => y\ncc  => z\n");
550 +
}
551 +
552 +
/// Test that a run is not aligned when the padding would pass the width.
553 +
@test unsafe fn testAlignedCellsWidth() throws (testing::TestError) {
554 +
    static STORAGE: [u8; 4096] = [0; 4096];
555 +
    let mut arena = alloc::new(&mut STORAGE[..]);
556 +
    let a: &mut opaque alloc::Allocator = &mut arena;
557 +
    let root = table(a, &[
558 +
        arrow(a, "a", "=> x"),
559 +
        arrow(a, "bbb", "=> yy")
560 +
    ]);
561 +
    try expectRender(root, 9, 4, "a   => x\nbbb => yy\n");
562 +
    try expectRender(root, 8, 4, "a => x\nbbb => yy\n");
563 +
}
564 +
565 +
/// Test that a row that does not fit on one line, a blank line, and a line on
566 +
/// its own end a run.
567 +
@test unsafe fn testAlignedRuns() throws (testing::TestError) {
568 +
    static STORAGE: [u8; 4096] = [0; 4096];
569 +
    let mut arena = alloc::new(&mut STORAGE[..]);
570 +
    let a: &mut opaque alloc::Allocator = &mut arena;
571 +
    let long = box(a, &[
572 +
        at(none(), text(a, "cccccc")),
573 +
        at(none(), tab(a, 0)),
574 +
        at(space(), box(a, &[
575 +
            at(none(), text(a, "=>")),
576 +
            at(softIndent(), text(a, "zzzzzzzzzzzzzzzz"))
577 +
        ]))
578 +
    ]);
579 +
    let root = table(a, &[
580 +
        arrow(a, "a", "=> x"),
581 +
        arrow(a, "bb", "=> y"),
582 +
        long,
583 +
        arrow(a, "d", "=> x"),
584 +
        arrow(a, "ee", "=> y"),
585 +
        blank(a),
586 +
        arrow(a, "f", "=> x"),
587 +
        arrow(a, "gg", "=> y"),
588 +
        text(a, "// own line"),
589 +
        arrow(a, "h", "=> x"),
590 +
        arrow(a, "ii", "=> y")
591 +
    ]);
592 +
    try expectRender(
593 +
        root,
594 +
        16,
595 +
        4,
596 +
        "a  => x\nbb => y\ncccccc =>\n    zzzzzzzzzzzzzzzz\nd  => x\nee => y\n\nf  => x\ngg => y\n// own line\nh  => x\nii => y\n"
597 +
    );
598 +
}
599 +
600 +
/// Test that cells of two columns are padded one inside the other, and that a
601 +
/// trailing comment column counts the padding of the cell inside it.
602 +
@test unsafe fn testAlignedColumns() throws (testing::TestError) {
603 +
    static STORAGE: [u8; 4096] = [0; 4096];
604 +
    let mut arena = alloc::new(&mut STORAGE[..]);
605 +
    let a: &mut opaque alloc::Allocator = &mut arena;
606 +
    let row1 = box(a, &[
607 +
        at(none(), arrow(a, "a", "=> x")),
608 +
        at(none(), tab(a, 1)),
609 +
        at(space(), comment(a, "// one"))
610 +
    ]);
611 +
    let row2 = box(a, &[
612 +
        at(none(), arrow(a, "bbb", "=> yy")),
613 +
        at(none(), tab(a, 1)),
614 +
        at(space(), comment(a, "// two"))
615 +
    ]);
616 +
    let root = table(a, &[row1, row2, arrow(a, "c", "=> z")]);
617 +
    try expectRender(
618 +
        root, 80, 4, "a   => x  // one\nbbb => yy // two\nc   => z\n"
619 +
    );
620 +
}
621 +
622 +
/// Test that a row can be a child and the children after it on its line.
623 +
@test unsafe fn testAlignedSiblings() throws (testing::TestError) {
624 +
    static STORAGE: [u8; 4096] = [0; 4096];
625 +
    let mut arena = alloc::new(&mut STORAGE[..]);
626 +
    let a: &mut opaque alloc::Allocator = &mut arena;
627 +
    let root = box(a, &[
628 +
        at(Placement::Line, text(a, "a,")),
629 +
        at(none(), tab(a, 1)),
630 +
        at(space(), comment(a, "// one")),
631 +
        at(Placement::Line, text(a, "bbb,")),
632 +
        at(none(), tab(a, 1)),
633 +
        at(space(), comment(a, "// two")),
634 +
        at(Placement::Line, text(a, "cc,"))
635 +
    ]);
636 +
    try expectRender(root, 80, 4, "a,   // one\nbbb, // two\ncc,\n");
637 +
}
lib/std/lang/layout/text.rad added +798 -0
1 +
//! Text renderer for layouts.
2 +
//!
3 +
//! Renders a layout as plain text with a line width and an indentation unit.
4 +
//! Each box is flat if it fits and broken otherwise. A box fits if, with it and
5 +
//! every box nested in it flat, the line stays within the width up to the next
6 +
//! line break, counting the content that follows the box. Boxes in that
7 +
//! content can break at their first soft placement. The content is summarized
8 +
//! by a [`Span`] that each box passes to its children, so rendering does not
9 +
//! allocate.
10 +
//!
11 +
//! Comments do not count toward the width, because they cannot move. A comment
12 +
//! longer than the width does not stop the content before it from fitting. Any
13 +
//! content after a comment on the same line cannot fit.
14 +
//!
15 +
//! A choice takes its first alternative that fits as a box does, and its last
16 +
//! alternative otherwise. An alternative that starts on a new line fits if
17 +
//! its first line fits.
18 +
//!
19 +
//! Consecutive rows that have a tab stop of a column, and that each fit on
20 +
//! one line, are a run. The rows of a run are padded with spaces at the stop
21 +
//! to the widest one, unless a line of the run would then pass the width, or
22 +
//! the column after the padding would be at or past it. Each row of the run
23 +
//! is measured once to find the run, so rendering allocates nothing.
24 +
//!
25 +
//! Newlines and indentation are written lazily, before the next text on a
26 +
//! line, so the output has no trailing whitespace and empty lines are empty.
27 +
28 +
use std::lang::sexpr;
29 +
30 +
/// Text rendering options.
31 +
export record Options {
32 +
    /// Maximum line width in columns.
33 +
    width: u32,
34 +
    /// Spaces per indentation level.
35 +
    indent: u32,
36 +
}
37 +
38 +
/// Decision for the soft placements of the children of a box.
39 +
union Mode: Copy {
40 +
    /// Soft placements stay on the line.
41 +
    Flat,
42 +
    /// Soft placements start a new line.
43 +
    Broken,
44 +
}
45 +
46 +
/// What ended the text written or measured on the current line so far.
47 +
union Tail: Copy {
48 +
    /// Code, which later content may follow on the same line.
49 +
    Code,
50 +
    /// A comment, which runs to the end of the line.
51 +
    Comment,
52 +
}
53 +
54 +
/// How a measured span of a line ends.
55 +
union Status: Copy {
56 +
    /// The span ends where more content may follow on the same line.
57 +
    Open,
58 +
    /// The span ends at a line break.
59 +
    Closed,
60 +
    /// The span cannot fit in the width at any start column.
61 +
    Bad,
62 +
}
63 +
64 +
/// Measure of flat content on one line, relative to its start column.
65 +
record Span: Copy {
66 +
    /// Columns from the start to the end of the last text, which is not a
67 +
    /// comment.
68 +
    reach: u32,
69 +
    /// Columns from the start to the end, including trailing gaps.
70 +
    end: u32,
71 +
    /// What ended the last text, including a comment.
72 +
    tail: Tail,
73 +
    /// How the span ends.
74 +
    status: Status,
75 +
}
76 +
77 +
/// Output position and pending whitespace.
78 +
record State {
79 +
    /// Rendering options.
80 +
    options: Options,
81 +
    /// Column after the pending whitespace, counting an indented line start.
82 +
    col: u32,
83 +
    /// Newlines not written yet.
84 +
    newlines: u32,
85 +
    /// Spaces not written yet, between text on one line.
86 +
    spaces: u32,
87 +
    /// Number of bytes of text written.
88 +
    written: u32,
89 +
    /// What ended the line so far.
90 +
    tail: Tail,
91 +
    /// Spaces that the tab stop of each column adds, set for the row that is
92 +
    /// rendered.
93 +
    pads: [u32; super::CELL_COLUMNS],
94 +
}
95 +
96 +
/// Rows of consecutive children whose tab stops of one column line up.
97 +
record Run: Copy {
98 +
    /// Index of the child after the last row of the run.
99 +
    end: u32,
100 +
    /// Width that the rows are padded to at the stop.
101 +
    target: u32,
102 +
    /// Whether the rows are padded.
103 +
    aligned: bool,
104 +
}
105 +
106 +
/// Render a layout as text.
107 +
///
108 +
/// Boxes are flat when they fit in `options.width` columns. The output ends
109 +
/// with one newline if anything was written.
110 +
export fn render(
111 +
    root: *super::Layout, options: Options, out: &mut opaque sexpr::Output
112 +
) {
113 +
    let mut st = State {
114 +
        options,
115 +
        col: 0,
116 +
        newlines: 0,
117 +
        spaces: 0,
118 +
        written: 0,
119 +
        tail: Tail::Code,
120 +
        pads: [0; super::CELL_COLUMNS],
121 +
    };
122 +
    renderLayout(&mut st, out, root, 0, emptySpan());
123 +
    if st.written > 0 {
124 +
        out.write("\n");
125 +
    }
126 +
}
127 +
128 +
/// Number of columns of a gap.
129 +
fn gapWidth(gap: super::Gap) -> u32 {
130 +
    match gap {
131 +
        case super::Gap::None => return 0,
132 +
        case super::Gap::Space => return 1,
133 +
    }
134 +
}
135 +
136 +
/// Gap before a child placed with `placement` in a box with the given mode,
137 +
/// or nil if the placement starts a new line.
138 +
fn inlineGap(placement: super::Placement, mode: Mode) -> ?super::Gap {
139 +
    match placement {
140 +
        case super::Placement::Inline(gap) => return gap,
141 +
        case super::Placement::SoftLine(gap) => {
142 +
            if mode == Mode::Flat {
143 +
                return gap;
144 +
            }
145 +
            return nil;
146 +
        }
147 +
        case super::Placement::SoftIndent(gap) => {
148 +
            if mode == Mode::Flat {
149 +
                return gap;
150 +
            }
151 +
            return nil;
152 +
        }
153 +
        else => return nil,
154 +
    }
155 +
}
156 +
157 +
/// Span of no content.
158 +
fn emptySpan() -> Span {
159 +
    return Span { reach: 0, end: 0, tail: Tail::Code, status: Status::Open };
160 +
}
161 +
162 +
/// Span of `b` placed after `a` with a gap of `gap` columns, where `a` is open.
163 +
fn join(a: Span, gap: u32, b: Span, width: u32) -> Span {
164 +
    let mut reach = a.reach;
165 +
    let mut tail = a.tail;
166 +
    let mut status = b.status;
167 +
    if b.reach > 0 {
168 +
        set reach = a.end + gap + b.reach;
169 +
        set tail = b.tail;
170 +
        // A comment runs to the end of the line.
171 +
        if a.tail == Tail::Comment or reach > width {
172 +
            set status = Status::Bad;
173 +
        }
174 +
    } else if b.tail == Tail::Comment {
175 +
        // A comment alone takes no width, and ends the line.
176 +
        set tail = Tail::Comment;
177 +
        if a.tail == Tail::Comment {
178 +
            set status = Status::Bad;
179 +
        }
180 +
    }
181 +
    if a.status == Status::Bad {
182 +
        set status = Status::Bad;
183 +
    }
184 +
    return Span { reach, end: a.end + gap + b.end, tail, status };
185 +
}
186 +
187 +
/// Measure a text fragment. A comment takes no width.
188 +
fn measureText(text: *[u8], role: super::Role, width: u32) -> Span {
189 +
    if role == super::Role::Comment {
190 +
        return Span {
191 +
            reach: 0, end: 0, tail: Tail::Comment, status: Status::Open
192 +
        };
193 +
    }
194 +
    return Span {
195 +
        reach: text.len,
196 +
        end: text.len,
197 +
        tail: Tail::Comment if role == super::Role::Comment else Tail::Code,
198 +
        status: Status::Bad if text.len > width else Status::Open,
199 +
    };
200 +
}
201 +
202 +
/// Children of the box that a broken layout wraps.
203 +
fn brokenChildren(inner: *super::Layout) -> *[super::Child] {
204 +
    let case super::Item::Box(children) = inner.item else {
205 +
        panic "brokenChildren: broken layout is not a box";
206 +
    };
207 +
    return children;
208 +
}
209 +
210 +
/// Measure a layout with every nested box flat, every choice at its first
211 +
/// alternative, and every broken box up to its earliest possible line break.
212 +
fn measureLayout(layout: *super::Layout, width: u32) -> Span {
213 +
    match layout.item {
214 +
        case super::Item::Text { text, role } =>
215 +
            return measureText(text, role, width),
216 +
        case super::Item::Box(children) =>
217 +
            return measureChildren(children, 0, Mode::Flat, Mode::Flat, width),
218 +
        case super::Item::BrokenText { .. } => return emptySpan(),
219 +
        case super::Item::Blank => {
220 +
            let mut span = emptySpan();
221 +
            set span.status = Status::Closed;
222 +
            return span;
223 +
        }
224 +
        case super::Item::Choice(alts) => return measureLayout(alts[0], width),
225 +
        case super::Item::Tab(_) => return emptySpan(),
226 +
        case super::Item::Broken(_) => return measureOpening(layout, width),
227 +
    }
228 +
}
229 +
230 +
/// Measure a layout up to its earliest possible line break, with every
231 +
/// nested box broken, and every choice at the alternative that breaks first.
232 +
fn measureOpening(layout: *super::Layout, width: u32) -> Span {
233 +
    match layout.item {
234 +
        case super::Item::Box(children) =>
235 +
            return measureChildren(
236 +
                children, 0, Mode::Broken, Mode::Broken, width
237 +
            ),
238 +
        case super::Item::Choice(alts) => {
239 +
            let mut first = measureOpening(alts[0], width);
240 +
            for i in 1..alts.len {
241 +
                let span = measureOpening(alts[i], width);
242 +
                if breaksBefore(span, first) {
243 +
                    set first = span;
244 +
                }
245 +
            }
246 +
            return first;
247 +
        }
248 +
        case super::Item::Broken(inner) => return measureOpening(inner, width),
249 +
        else => return measureLayout(layout, width),
250 +
    }
251 +
}
252 +
253 +
/// Whether the span `a` leaves more room on the line than `b`: it ends at a
254 +
/// line break where `b` does not, `b` cannot fit, or it ends earlier in the
255 +
/// same way.
256 +
fn breaksBefore(a: Span, b: Span) -> bool {
257 +
    if a.status == b.status {
258 +
        return a.end < b.end;
259 +
    }
260 +
    return a.status == Status::Closed or b.status == Status::Bad;
261 +
}
262 +
263 +
/// Measure the children from index `from` on, up to the first line break,
264 +
/// in a box with the given mode. Nested boxes are measured flat when `nested`
265 +
/// is flat, or up to their earliest possible line break otherwise.
266 +
fn measureChildren(
267 +
    children: *[super::Child],
268 +
    from: u32,
269 +
    mode: Mode,
270 +
    nested: Mode,
271 +
    width: u32
272 +
) -> Span {
273 +
    let mut span = emptySpan();
274 +
    for i in from..children.len {
275 +
        let child = children[i];
276 +
        if mode == Mode::Flat {
277 +
            if let case super::Item::BrokenText { .. } = child.layout.item {
278 +
                continue;
279 +
            }
280 +
        }
281 +
        // A child on a new line ends the line before it, so it is not measured.
282 +
        let gap = inlineGap(child.placement, mode) else {
283 +
            set span.status = Status::Closed;
284 +
            return span;
285 +
        };
286 +
        let mut part = emptySpan();
287 +
        if let case super::Item::BrokenText { text, role } = child.layout.item {
288 +
            set part = measureText(text, role, width);
289 +
        } else if nested == Mode::Flat {
290 +
            set part = measureLayout(child.layout, width);
291 +
        } else {
292 +
            set part = measureOpening(child.layout, width);
293 +
        }
294 +
        set span = join(span, gapWidth(gap), part, width);
295 +
        if span.status <> Status::Open {
296 +
            return span;
297 +
        }
298 +
    }
299 +
    return span;
300 +
}
301 +
302 +
/// Check whether a layout fits when flat at `col`, given the span `rest` of
303 +
/// the content that follows it.
304 +
fn fits(
305 +
    layout: *super::Layout, width: u32, col: u32, tail: Tail, rest: Span
306 +
) -> bool {
307 +
    let start = Span { reach: col, end: col, tail, status: Status::Open };
308 +
    let mut span = join(start, 0, measureLayout(layout, width), width);
309 +
    if span.status == Status::Open {
310 +
        set span = join(span, 0, rest, width);
311 +
    }
312 +
    return span.status <> Status::Bad;
313 +
}
314 +
315 +
/// Indentation level of a child that starts a new line whatever the mode of
316 +
/// its box, if it does.
317 +
fn lineLevel(placement: super::Placement, indent: u32) -> ?u32 {
318 +
    match placement {
319 +
        case super::Placement::Line => return indent,
320 +
        case super::Placement::Indent => return indent + 1,
321 +
        else => return nil,
322 +
    }
323 +
}
324 +
325 +
/// Check whether the alternative `alt` of a choice fits at the current
326 +
/// column, in a box at indentation `indent`. An alternative that starts on a
327 +
/// new line is measured from the start of that line.
328 +
fn fitsAlternative(
329 +
    alt: *super::Layout, st: &State, indent: u32, rest: Span
330 +
) -> bool {
331 +
    let width = st.options.width;
332 +
    if let case super::Item::Box(children) = alt.item; children.len > 0 {
333 +
        if let level = lineLevel(children[0].placement, indent) {
334 +
            let mut after = measureChildren(
335 +
                children, 1, Mode::Flat, Mode::Flat, width
336 +
            );
337 +
            if after.status == Status::Open {
338 +
                set after = join(after, 0, rest, width);
339 +
            }
340 +
            let col = level * st.options.indent;
341 +
            return fits(children[0].layout, width, col, Tail::Code, after);
342 +
        }
343 +
    }
344 +
    return fits(alt, width, st.col, st.tail, rest);
345 +
}
346 +
347 +
/// Start a new line at the given indentation level.
348 +
fn newline(st: &mut State, level: u32) {
349 +
    set st.newlines += 1;
350 +
    set st.spaces = 0;
351 +
    set st.col = level * st.options.indent;
352 +
    set st.tail = Tail::Code;
353 +
}
354 +
355 +
/// Write text, preceded by the pending newlines, indentation and spaces.
356 +
fn writeText(
357 +
    st: &mut State,
358 +
    out: &mut opaque sexpr::Output,
359 +
    text: *[u8],
360 +
    role: super::Role
361 +
) {
362 +
    if text.len == 0 {
363 +
        return;
364 +
    }
365 +
    if st.newlines > 0 or st.written == 0 {
366 +
        if st.written > 0 {
367 +
            for _ in 0..st.newlines {
368 +
                out.write("\n");
369 +
            }
370 +
        }
371 +
        for _ in 0..st.col {
372 +
            out.write(" ");
373 +
        }
374 +
        set st.newlines = 0;
375 +
    } else {
376 +
        for _ in 0..st.spaces {
377 +
            out.write(" ");
378 +
        }
379 +
    }
380 +
    out.write(text);
381 +
    set st.spaces = 0;
382 +
    set st.col += text.len;
383 +
    set st.written += text.len;
384 +
    set st.tail = Tail::Comment if role == super::Role::Comment
385 +
        else Tail::Code;
386 +
}
387 +
388 +
/// Apply the placement of a child in a box at indentation `indent`.
389 +
/// Returns the indentation level of the child.
390 +
fn place(
391 +
    st: &mut State,
392 +
    placement: super::Placement,
393 +
    mode: Mode,
394 +
    indent: u32
395 +
) -> u32 {
396 +
    if let gap = inlineGap(placement, mode) {
397 +
        if st.tail == Tail::Comment {
398 +
            newline(st, indent);
399 +
        } else if st.newlines == 0 and st.written > 0 {
400 +
            set st.spaces += gapWidth(gap);
401 +
            set st.col += gapWidth(gap);
402 +
        }
403 +
        return indent;
404 +
    }
405 +
    match placement {
406 +
        case super::Placement::Indent, super::Placement::SoftIndent(_) => {
407 +
            newline(st, indent + 1);
408 +
            return indent + 1;
409 +
        }
410 +
        else => {
411 +
            newline(st, indent);
412 +
            return indent;
413 +
        }
414 +
    }
415 +
}
416 +
417 +
/// Render a layout whose box indentation is `indent`. `rest` describes the
418 +
/// content that follows the layout.
419 +
fn renderLayout(
420 +
    st: &mut State,
421 +
    out: &mut opaque sexpr::Output,
422 +
    layout: *super::Layout,
423 +
    indent: u32,
424 +
    rest: Span
425 +
) {
426 +
    match layout.item {
427 +
        case super::Item::Text { text, role } => writeText(st, out, text, role),
428 +
        case super::Item::Blank, super::Item::BrokenText { .. } => {}
429 +
        case super::Item::Box(children) => {
430 +
            let mode = Mode::Flat
431 +
                if fits(layout, st.options.width, st.col, st.tail, rest)
432 +
                else Mode::Broken;
433 +
            renderChildren(st, out, children, mode, indent, rest);
434 +
        }
435 +
        case super::Item::Broken(inner) =>
436 +
            renderChildren(
437 +
                st, out, brokenChildren(inner), Mode::Broken, indent, rest
438 +
            ),
439 +
        case super::Item::Tab(column) => {
440 +
            let pad = st.pads[column];
441 +
            set st.pads[column] = 0;
442 +
            set st.spaces += pad;
443 +
            set st.col += pad;
444 +
        }
445 +
        case super::Item::Choice(alts) => {
446 +
            let mut pick = alts[alts.len - 1];
447 +
            for alt in &alts[..alts.len - 1] {
448 +
                if fitsAlternative(alt, st, indent, rest) {
449 +
                    set pick = alt;
450 +
                    break;
451 +
                }
452 +
            }
453 +
            renderLayout(st, out, pick, indent, rest);
454 +
        }
455 +
    }
456 +
}
457 +
458 +
/// Indentation level of a child that starts a line in a box with the given
459 +
/// mode and indentation, if it does.
460 +
fn rowLevel(placement: super::Placement, mode: Mode, indent: u32) -> ?u32 {
461 +
    match placement {
462 +
        case super::Placement::Line => return indent,
463 +
        case super::Placement::Indent => return indent + 1,
464 +
        case super::Placement::SoftLine(_) => {
465 +
            if mode == Mode::Broken {
466 +
                return indent;
467 +
            }
468 +
            return nil;
469 +
        }
470 +
        case super::Placement::SoftIndent(_) => {
471 +
            if mode == Mode::Broken {
472 +
                return indent + 1;
473 +
            }
474 +
            return nil;
475 +
        }
476 +
        else => return nil,
477 +
    }
478 +
}
479 +
480 +
/// Indentation level of the child `at` if it starts a line: by its placement,
481 +
/// or because it is the first child of a box that starts at the start of a
482 +
/// line, as the items of a broken list do.
483 +
fn rowStart(
484 +
    st: &State, children: *[super::Child], at: u32, mode: Mode, indent: u32
485 +
) -> ?u32 {
486 +
    if let level = rowLevel(children[at].placement, mode, indent) {
487 +
        return level;
488 +
    }
489 +
    if at == 0 and st.newlines > 0 and st.options.indent > 0 {
490 +
        return st.col / st.options.indent;
491 +
    }
492 +
    return nil;
493 +
}
494 +
495 +
/// Index of the child after the row that starts at the child `from`: the
496 +
/// first child that starts a line.
497 +
fn rowEnd(
498 +
    children: *[super::Child], from: u32, mode: Mode, indent: u32
499 +
) -> u32 {
500 +
    let mut end = from + 1;
501 +
    while end < children.len
502 +
        and rowLevel(children[end].placement, mode, indent) == nil {
503 +
        set end += 1;
504 +
    }
505 +
    return end;
506 +
}
507 +
508 +
/// Whether a layout holds the tab stop of `column`.
509 +
fn hasTab(layout: *super::Layout, column: u32) -> bool {
510 +
    match layout.item {
511 +
        case super::Item::Tab(found) => return found == column,
512 +
        case super::Item::Box(children) => {
513 +
            for child in children {
514 +
                if hasTab(child.layout, column) {
515 +
                    return true;
516 +
                }
517 +
            }
518 +
            return false;
519 +
        }
520 +
        else => return false,
521 +
    }
522 +
}
523 +
524 +
/// Whether the row `from..end` has the tab stop of `column`.
525 +
fn rowHasTab(
526 +
    children: *[super::Child], from: u32, end: u32, column: u32
527 +
) -> bool {
528 +
    for k in from..end {
529 +
        if hasTab(children[k].layout, column) {
530 +
            return true;
531 +
        }
532 +
    }
533 +
    return false;
534 +
}
535 +
536 +
/// Measure the row `from..end` flat, up to its first line break.
537 +
fn measureRow(
538 +
    children: *[super::Child], from: u32, end: u32, mode: Mode, width: u32
539 +
) -> Span {
540 +
    let mut span = emptySpan();
541 +
    for k in from..end {
542 +
        let child = children[k];
543 +
        let mut gap: u32 = 0;
544 +
        if k > from {
545 +
            if let g = inlineGap(child.placement, mode) {
546 +
                set gap = gapWidth(g);
547 +
            }
548 +
        }
549 +
        let mut part = emptySpan();
550 +
        if let case super::Item::BrokenText { text, role } = child.layout.item {
551 +
            if mode == Mode::Flat {
552 +
                continue;
553 +
            }
554 +
            set part = measureText(text, role, width);
555 +
        } else {
556 +
            set part = measureLayout(child.layout, width);
557 +
        }
558 +
        set span = join(span, gap, part, width);
559 +
        if span.status <> Status::Open {
560 +
            return span;
561 +
        }
562 +
    }
563 +
    return span;
564 +
}
565 +
566 +
/// Measure the content of the layouts `children` before the tab stop of
567 +
/// `column`, flat, or nil if there is no such stop. The first child has a gap
568 +
/// before it only if `gapFirst`.
569 +
fn measureToTab(
570 +
    children: *[super::Child],
571 +
    from: u32,
572 +
    end: u32,
573 +
    gapFirst: bool,
574 +
    mode: Mode,
575 +
    column: u32,
576 +
    width: u32
577 +
) -> ?Span {
578 +
    let mut span = emptySpan();
579 +
    for k in from..end {
580 +
        let child = children[k];
581 +
        let mut gap: u32 = 0;
582 +
        if k > from or gapFirst {
583 +
            if let g = inlineGap(child.placement, mode) {
584 +
                set gap = gapWidth(g);
585 +
            }
586 +
        }
587 +
        if let case super::Item::Tab(found) = child.layout.item {
588 +
            if found == column {
589 +
                return span;
590 +
            }
591 +
        }
592 +
        if let case super::Item::BrokenText { text, role } = child.layout.item {
593 +
            if mode == Mode::Broken {
594 +
                let part = measureText(text, role, width);
595 +
                set span = join(span, gap, part, width);
596 +
            }
597 +
            continue;
598 +
        }
599 +
        if let case super::Item::Box(inner) = child.layout.item;
600 +
            hasTab(child.layout, column)
601 +
        {
602 +
            let before = measureToTab(
603 +
                inner, 0, inner.len, true, Mode::Flat, column, width
604 +
            );
605 +
            if let found = before {
606 +
                return join(span, gap, found, width);
607 +
            }
608 +
        }
609 +
        set span = join(span, gap, measureLayout(child.layout, width), width);
610 +
    }
611 +
    return nil;
612 +
}
613 +
614 +
/// Width of the row `from..end` before its tab stop of `column`, with the
615 +
/// padding at the stops of lower columns. Zero if the row has no such stop.
616 +
fn stopWidth(
617 +
    children: *[super::Child],
618 +
    from: u32,
619 +
    end: u32,
620 +
    mode: Mode,
621 +
    column: u32,
622 +
    runs: &[Run],
623 +
    at: u32,
624 +
    width: u32
625 +
) -> u32 {
626 +
    let before = measureToTab(
627 +
        children, from, end, false, mode, column, width
628 +
    ) else {
629 +
        return 0;
630 +
    };
631 +
    let mut total = before.end;
632 +
    for lower in 0..column {
633 +
        set total += stopPad(children, from, end, mode, lower, runs, at, width);
634 +
    }
635 +
    return total;
636 +
}
637 +
638 +
/// Spaces that the row `from..end` adds at its tab stop of `column`, given the
639 +
/// run of the column, where the row is the child `at`.
640 +
fn stopPad(
641 +
    children: *[super::Child],
642 +
    from: u32,
643 +
    end: u32,
644 +
    mode: Mode,
645 +
    column: u32,
646 +
    runs: &[Run],
647 +
    at: u32,
648 +
    width: u32
649 +
) -> u32 {
650 +
    let run = runs[column];
651 +
    if not run.aligned or at >= run.end {
652 +
        return 0;
653 +
    }
654 +
    if not rowHasTab(children, from, end, column) {
655 +
        return 0;
656 +
    }
657 +
    return run.target
658 +
        - stopWidth(children, from, end, mode, column, runs, at, width);
659 +
}
660 +
661 +
/// Find the run of rows that starts at the child `from`, for the tab stops of
662 +
/// `column`. A child that is not a row with such a stop, or does not fit on
663 +
/// one line, is a run of its own that is not aligned.
664 +
fn scanRun(
665 +
    st: &State,
666 +
    children: *[super::Child],
667 +
    from: u32,
668 +
    mode: Mode,
669 +
    indent: u32,
670 +
    column: u32,
671 +
    runs: &[Run]
672 +
) -> Run {
673 +
    let alone = Run { end: from + 1, target: 0, aligned: false };
674 +
    let level = rowStart(st, children, from, mode, indent) else {
675 +
        return alone;
676 +
    };
677 +
    let width = st.options.width;
678 +
    let start = level * st.options.indent;
679 +
    let mut j = from;
680 +
    let mut target: u32 = 0;
681 +
    let mut after: u32 = 0;
682 +
    while j < children.len {
683 +
        if j > from {
684 +
            let here = rowLevel(children[j].placement, mode, indent) else {
685 +
                break;
686 +
            };
687 +
            if here <> level {
688 +
                break;
689 +
            }
690 +
        }
691 +
        let end = rowEnd(children, j, mode, indent);
692 +
        if not rowHasTab(children, j, end, column) {
693 +
            break;
694 +
        }
695 +
        let span = measureRow(children, j, end, mode, width);
696 +
        // The row fits on the line where it is.
697 +
        if span.status <> Status::Open or start + span.reach > width {
698 +
            break;
699 +
        }
700 +
        let w = stopWidth(children, j, end, mode, column, runs, j, width);
701 +
        let own = measureToTab(children, j, end, false, mode, column, width);
702 +
        let mut before = w;
703 +
        if let found = own {
704 +
            set before = found.end;
705 +
        }
706 +
        // The padding of lower columns lengthens the row.
707 +
        let reach = span.reach + w - before;
708 +
        if w > target {
709 +
            set target = w;
710 +
        }
711 +
        if reach > w and reach - w > after {
712 +
            set after = reach - w;
713 +
        }
714 +
        set j = end;
715 +
    }
716 +
    if j == from {
717 +
        return alone;
718 +
    }
719 +
    return Run {
720 +
        end: j,
721 +
        target,
722 +
        aligned: start + target + 1 < width and start + target + after <= width,
723 +
    };
724 +
}
725 +
726 +
/// Set the spaces that the tab stops of the row that starts at the child `at`
727 +
/// add, finding the runs that it starts.
728 +
fn padRow(
729 +
    st: &mut State,
730 +
    children: *[super::Child],
731 +
    at: u32,
732 +
    mode: Mode,
733 +
    indent: u32,
734 +
    runs: &mut [Run]
735 +
) {
736 +
    if rowStart(st, children, at, mode, indent) == nil {
737 +
        return;
738 +
    }
739 +
    let end = rowEnd(children, at, mode, indent);
740 +
    for column in 0..super::CELL_COLUMNS {
741 +
        if not rowHasTab(children, at, end, column) {
742 +
            continue;
743 +
        }
744 +
        if at >= runs[column].end {
745 +
            set runs[column] = scanRun(
746 +
                st, children, at, mode, indent, column, runs
747 +
            );
748 +
        }
749 +
        // A box that starts a row finds the pad of the row it is in.
750 +
        let pad = stopPad(
751 +
            children, at, end, mode, column, runs, at, st.options.width
752 +
        );
753 +
        if pad > 0 {
754 +
            set st.pads[column] = pad;
755 +
        }
756 +
    }
757 +
}
758 +
759 +
/// Render the children of a box with the given mode.
760 +
fn renderChildren(
761 +
    st: &mut State,
762 +
    out: &mut opaque sexpr::Output,
763 +
    children: *[super::Child],
764 +
    mode: Mode,
765 +
    indent: u32,
766 +
    rest: Span
767 +
) {
768 +
    let mut runs = [
769 +
        Run { end: 0, target: 0, aligned: false }; super::CELL_COLUMNS
770 +
    ];
771 +
    for i in 0..children.len {
772 +
        let child = children[i];
773 +
        match child.layout.item {
774 +
            case super::Item::BrokenText { text, role } => {
775 +
                if mode == Mode::Broken {
776 +
                    place(st, child.placement, mode, indent);
777 +
                    writeText(st, out, text, role);
778 +
                }
779 +
            }
780 +
            case super::Item::Text { .. }, super::Item::Blank => {
781 +
                let level = place(st, child.placement, mode, indent);
782 +
                padRow(st, children, i, mode, indent, &mut runs[..]);
783 +
                renderLayout(st, out, child.layout, level, emptySpan());
784 +
            }
785 +
            else => {
786 +
                let level = place(st, child.placement, mode, indent);
787 +
                padRow(st, children, i, mode, indent, &mut runs[..]);
788 +
                let mut next = measureChildren(
789 +
                    children, i + 1, mode, Mode::Broken, st.options.width
790 +
                );
791 +
                if next.status == Status::Open {
792 +
                    set next = join(next, 0, rest, st.options.width);
793 +
                }
794 +
                renderLayout(st, out, child.layout, level, next);
795 +
            }
796 +
        }
797 +
    }
798 +
}
lib/std/lang/parser.rad +675 -180
56 56
    type: ?*ast::Node,
57 57
    /// The optional initialization value.
58 58
    value: ?*ast::Node,
59 59
    /// The optional alignment specifier.
60 60
    alignment: ?*ast::Node,
61 +
    /// Whether the value starts on a later line than the `=`. Always false
62 +
    /// when trivia is discarded.
63 +
    valueBroken: bool,
61 64
}
62 65
63 66
/// Behavioural differences when parsing record field lists.
64 67
union RecordFieldMode: Copy {
65 68
    /// Labeled fields, allows for default values.
66 69
    Labeled,
67 70
    /// Unlabeled fields.
68 71
    Unlabeled,
69 72
}
70 73
74 +
/// Whether the parser keeps comments and blank lines.
75 +
export union TriviaMode: Copy {
76 +
    /// Skip comments and blank lines without recording them.
77 +
    Discard,
78 +
    /// Record comments and blank lines into [`Parser::trivia`].
79 +
    Keep,
80 +
}
81 +
82 +
/// Where a pending comment starts relative to the token before it.
83 +
union PendingLine: Copy {
84 +
    /// On the line where the previous token ends.
85 +
    SameLine,
86 +
    /// On a later line than the previous token.
87 +
    NewLine,
88 +
}
89 +
90 +
/// Trivia that was scanned but is not attached to a node yet.
91 +
record Pending: Copy {
92 +
    /// Comment or blank line.
93 +
    kind: ast::TriviaKind,
94 +
    /// Line of the trivia relative to the previous token.
95 +
    line: PendingLine,
96 +
    /// Source offset of the comment, or of the line break of a blank line.
97 +
    offset: u32,
98 +
}
99 +
100 +
/// A function signature with the trivia before the `)` that ends its
101 +
/// parameters, and whether its `throws` clause starts a line.
102 +
record ParsedSig: Copy {
103 +
    /// The function signature.
104 +
    sig: ast::FnSig,
105 +
    /// Trivia before the `)` of the parameters. The node that holds the
106 +
    /// signature attaches it as closing trivia once created.
107 +
    closing: *[Pending],
108 +
    /// Whether the `throws` clause starts on a later line than the token before
109 +
    /// it. Always false when trivia is discarded.
110 +
    stacked: bool,
111 +
    /// Whether the source breaks the `throws` list across lines. Always false
112 +
    /// when trivia is discarded.
113 +
    brokenThrows: bool,
114 +
}
115 +
71 116
/// Parser context differentiates between regular expressions and
72 117
/// conditional contexts where `{` begins a block.
73 118
union Context: Copy {
74 119
    /// Normal expression context where `{` may start a record literal
75 120
    /// and `if` may start a conditional expression.
102 147
record OpInfo: Copy {
103 148
    op: ast::BinaryOp,
104 149
    prec: i32,
105 150
}
106 151
107 -
/// Get operator info for a token kind using match-based dispatch.
108 -
/// Returns nil if the token is not a binary operator.
109 -
fn getOpInfo(kind: scanner::TokenKind) -> ?OpInfo {
152 +
/// Binary operator that a token kind spells, if any.
153 +
fn binaryOp(kind: scanner::TokenKind) -> ?ast::BinaryOp {
110 154
    match kind {
111 -
        case scanner::TokenKind::Star =>
112 -
            return { op: ast::BinaryOp::Mul, prec: 7 },
113 -
        case scanner::TokenKind::Slash =>
114 -
            return { op: ast::BinaryOp::Div, prec: 7 },
115 -
        case scanner::TokenKind::Percent =>
116 -
            return { op: ast::BinaryOp::Mod, prec: 7 },
117 -
        case scanner::TokenKind::Plus =>
118 -
            return { op: ast::BinaryOp::Add, prec: 6 },
119 -
        case scanner::TokenKind::Minus =>
120 -
            return { op: ast::BinaryOp::Sub, prec: 6 },
121 -
        case scanner::TokenKind::LtLt =>
122 -
            return { op: ast::BinaryOp::Shl, prec: 5 },
123 -
        case scanner::TokenKind::GtGt =>
124 -
            return { op: ast::BinaryOp::Shr, prec: 5 },
125 -
        case scanner::TokenKind::Amp =>
126 -
            return { op: ast::BinaryOp::BitAnd, prec: 4 },
127 -
        case scanner::TokenKind::Caret =>
128 -
            return { op: ast::BinaryOp::BitXor, prec: 3 },
129 -
        case scanner::TokenKind::Pipe =>
130 -
            return { op: ast::BinaryOp::BitOr, prec: 2 },
131 -
        case scanner::TokenKind::EqualEqual =>
132 -
            return { op: ast::BinaryOp::Eq, prec: 1 },
133 -
        case scanner::TokenKind::LtGt =>
134 -
            return { op: ast::BinaryOp::Ne, prec: 1 },
135 -
        case scanner::TokenKind::Lt =>
136 -
            return { op: ast::BinaryOp::Lt, prec: 1 },
137 -
        case scanner::TokenKind::Gt =>
138 -
            return { op: ast::BinaryOp::Gt, prec: 1 },
139 -
        case scanner::TokenKind::LtEqual =>
140 -
            return { op: ast::BinaryOp::Lte, prec: 1 },
141 -
        case scanner::TokenKind::GtEqual =>
142 -
            return { op: ast::BinaryOp::Gte, prec: 1 },
143 -
        case scanner::TokenKind::And =>
144 -
            return { op: ast::BinaryOp::And, prec: 0 },
145 -
        case scanner::TokenKind::Or =>
146 -
            return { op: ast::BinaryOp::Or, prec: 0 },
147 -
        else =>
148 -
            return nil,
155 +
        case scanner::TokenKind::Star => return ast::BinaryOp::Mul,
156 +
        case scanner::TokenKind::Slash => return ast::BinaryOp::Div,
157 +
        case scanner::TokenKind::Percent => return ast::BinaryOp::Mod,
158 +
        case scanner::TokenKind::Plus => return ast::BinaryOp::Add,
159 +
        case scanner::TokenKind::Minus => return ast::BinaryOp::Sub,
160 +
        case scanner::TokenKind::LtLt => return ast::BinaryOp::Shl,
161 +
        case scanner::TokenKind::GtGt => return ast::BinaryOp::Shr,
162 +
        case scanner::TokenKind::Amp => return ast::BinaryOp::BitAnd,
163 +
        case scanner::TokenKind::Caret => return ast::BinaryOp::BitXor,
164 +
        case scanner::TokenKind::Pipe => return ast::BinaryOp::BitOr,
165 +
        case scanner::TokenKind::EqualEqual => return ast::BinaryOp::Eq,
166 +
        case scanner::TokenKind::LtGt => return ast::BinaryOp::Ne,
167 +
        case scanner::TokenKind::Lt => return ast::BinaryOp::Lt,
168 +
        case scanner::TokenKind::Gt => return ast::BinaryOp::Gt,
169 +
        case scanner::TokenKind::LtEqual => return ast::BinaryOp::Lte,
170 +
        case scanner::TokenKind::GtEqual => return ast::BinaryOp::Gte,
171 +
        case scanner::TokenKind::And => return ast::BinaryOp::And,
172 +
        case scanner::TokenKind::Or => return ast::BinaryOp::Or,
173 +
        else => return nil,
149 174
    }
150 175
}
151 176
152 177
/// Parser state. A parser owns its node arena and string pool, and it parses
153 178
/// one module at a time through [`parseModule`].
164 189
    arena: ast::NodeArena,
165 190
    /// String pool used to intern identifiers and literals.
166 191
    pool: strings::Pool,
167 192
    /// Current parsing context (normal or conditional).
168 193
    context: Context,
194 +
    /// Whether comments and blank lines are kept. Set it before parsing a
195 +
    /// module. Comment text points into the module's source.
196 +
    triviaMode: TriviaMode,
197 +
    /// Trivia attached to nodes of the current module in [`TriviaMode::Keep`],
198 +
    /// ordered by node id.
199 +
    trivia: *mut [ast::Trivia],
200 +
    /// Trivia scanned since the last list boundary, ordered by offset.
201 +
    pending: *mut [Pending],
202 +
    /// Index in [`Parser::pending`] where the trivia of the innermost open
203 +
    /// list starts. Earlier entries belong to the constructs that enclose the
204 +
    /// list, and only the item that holds them takes them.
205 +
    base: u32,
206 +
    /// Trivia before the closing delimiter of the list that was parsed last,
207 +
    /// until [`attachClosing`] gives it to the list's node.
208 +
    closing: *mut [Pending],
169 209
}
170 210
171 211
/// Create an error list that holds no errors.
172 212
///
173 213
/// Slots past `count` hold an empty error and are never read.
188 228
        previous: scanner::invalid(0, ""),
189 229
        errors: emptyErrorList(),
190 230
        arena,
191 231
        pool: owned,
192 232
        context: Context::Normal,
233 +
        triviaMode: TriviaMode::Discard,
234 +
        trivia: &mut [],
235 +
        pending: &mut [],
236 +
        base: 0,
237 +
        closing: &mut [],
193 238
    };
194 239
}
195 240
196 241
/// Emit a `true` or `false` literal node.
197 242
fn nodeBool(p: &mut Parser, value: bool) -> *ast::Node {
267 312
/// Parse an array literal: `[a, b, c]` or `[item; count]`.
268 313
fn parseArrayLiteral(p: &mut Parser) -> *ast::Node
269 314
    throws (ParseError)
270 315
{
271 316
    try expect(p, scanner::TokenKind::LBracket, "expected `[`");
272 -
    if consume(p, scanner::TokenKind::RBracket) { // Empty array: `[]`.
317 +
    let mut outer = openList(p);
318 +
    if check(p, scanner::TokenKind::RBracket) { // Empty array: `[]`.
273 319
        let empty: *mut [*ast::Node] = &mut [];
274 -
        return node(p, ast::NodeValue::ArrayLit(empty));
320 +
        closeList(p, outer, &[]);
321 +
        advance(p);
322 +
        let lit: *ast::Node = node(p, ast::NodeValue::ArrayLit(empty));
323 +
        attachClosing(p, lit);
324 +
325 +
        return lit;
275 326
    }
327 +
    let firstLeading = takePending(p, &[]);
328 +
    noteItem(p, &mut outer);
276 329
    let firstExpr = try parseNormalExpr(p);
330 +
    attachLeading(p, firstExpr, firstLeading);
277 331
278 332
    if consume(p, scanner::TokenKind::Semicolon) {
279 -
        // Array repeat literal: `[item; count]`.
333 +
        // Array repeat literal: `[item; count]`. It has no list of items, so
334 +
        // its trivia stays with the enclosing item.
335 +
        set p.base = outer.base;
280 336
        let count = try parseNormalExpr(p);
337 +
        let broken = spansLines(p, outer);
281 338
        try expect(p, scanner::TokenKind::RBracket, "expected `]` after array repeat count");
282 -
283 -
        return node(p, ast::NodeValue::ArrayRepeatLit(
339 +
        let repeat: *ast::Node = node(p, ast::NodeValue::ArrayRepeatLit(
284 340
            ast::ArrayRepeatLit { item: firstExpr, count }
285 341
        ));
342 +
        markBroken(p, repeat, broken, ast::BrokenSite::List);
343 +
344 +
        return repeat;
286 345
    }
287 346
    // Regular array literal: `[a, b, ...]`.
288 347
    let mut items = try! ast::nodeSlice(&mut p.arena,
289 348
        INITIAL_ITEMS).append(firstExpr, &mut p.arena);
290 349
291 350
    while consume(p, scanner::TokenKind::Comma) and not check(p, scanner::TokenKind::RBracket) {
351 +
        let leading = takePending(p, &items[..]);
352 +
        let itemLine = startsLine(p) and p.triviaMode == TriviaMode::Keep;
353 +
        noteItem(p, &mut outer);
292 354
        let elem = try parseNormalExpr(p);
355 +
        attachLeading(p, elem, leading);
356 +
        if itemLine {
357 +
            attachOne(p, elem, ast::TriviaPlacement::Leading,
358 +
                ast::TriviaKind::Broken(ast::BrokenSite::ItemLine));
359 +
        }
293 360
        try! items.append(elem, &mut p.arena);
294 361
    }
362 +
    closeSoftList(p, outer, &items[..]);
295 363
    try expect(p, scanner::TokenKind::RBracket, "expected `]` after array elements");
364 +
    let lit: *ast::Node = node(p, ast::NodeValue::ArrayLit(items));
365 +
    attachClosing(p, lit);
296 366
297 -
    return node(p, ast::NodeValue::ArrayLit(items));
367 +
    return lit;
298 368
}
299 369
300 370
/// Parse a function call expression.
301 371
fn parseCall(p: &mut Parser, callee: *ast::Node) -> *ast::Node
302 372
    throws (ParseError)
303 373
{
304 -
    let args = try parseList(
305 -
        p,
306 -
        scanner::TokenKind::LParen,
307 -
        scanner::TokenKind::RParen,
308 -
        parseNormalExpr
374 +
    try expect(p, scanner::TokenKind::LParen, "expected `(`");
375 +
    let mut outer = openList(p);
376 +
    let args = try parseItems(
377 +
        p, scanner::TokenKind::RParen, parseNormalExpr, &mut outer
309 378
    );
310 -
    return node(p, ast::NodeValue::Call(
379 +
    closeSoftList(p, outer, &args[..]);
380 +
    try expect(p, scanner::TokenKind::RParen, "expected `)`");
381 +
    let call: *ast::Node = node(p, ast::NodeValue::Call(
311 382
        ast::Call { callee, args }
312 383
    ));
384 +
    attachClosing(p, call);
385 +
386 +
    return call;
313 387
}
314 388
315 389
/// Parse zero or more trailing `as` casts applied to `expr`.
316 390
fn parseAsCast(p: &mut Parser, expr: *ast::Node) -> *ast::Node
317 391
    throws (ParseError)
339 413
    // Only parse conditional expressions in normal context.
340 414
    // In conditional context, `if` is used for guards.
341 415
    if p.context <> Context::Normal {
342 416
        return thenExpr;
343 417
    }
418 +
    let beforeIf = startsLine(p);
344 419
    if not consume(p, scanner::TokenKind::If) {
345 420
        return thenExpr;
346 421
    }
347 422
    let condition = try parseCond(p);
423 +
    let beforeElse = startsLine(p);
348 424
    try expect(p, scanner::TokenKind::Else, "expected `else` in conditional expression");
349 425
    let elseExpr = try parseExpr(p);
350 -
351 -
    return node(p, ast::NodeValue::CondExpr(
426 +
    let cond: *ast::Node = node(p, ast::NodeValue::CondExpr(
352 427
        ast::CondExpr { condition, thenExpr, elseExpr }
353 428
    ));
429 +
    markBroken(p, cond, beforeIf or beforeElse, ast::BrokenSite::Chain);
430 +
431 +
    return cond;
354 432
}
355 433
356 434
/// Parse array subscript or slice expression after `[`.
357 435
fn parseSubscriptOrSlice(p: &mut Parser, container: *ast::Node) -> *ast::Node
358 436
    throws (ParseError)
489 567
}
490 568
491 569
/// Find the operator info for a token if it has precedence greater than the
492 570
/// given minimum.
493 571
fn findNextOp(kind: scanner::TokenKind, minPrec: i32) -> ?OpInfo {
494 -
    if let opInfo = getOpInfo(kind) {
495 -
        if opInfo.prec > minPrec {
496 -
            return opInfo;
497 -
        }
572 +
    let op = binaryOp(kind) else {
573 +
        return nil;
574 +
    };
575 +
    let prec = ast::precedence(op) as i32;
576 +
    if prec > minPrec {
577 +
        return { op, prec };
498 578
    }
499 579
    return nil;
500 580
}
501 581
502 582
/// Determine whether the current token can terminate a range expression.
542 622
        if p.current.kind == scanner::TokenKind::DotDot {
543 623
            advance(p);
544 624
            set result = try parseRangeExpr(p, result);
545 625
        } else {
546 626
            let opInfo = findNextOp(p.current.kind, minPrec) else break;
627 +
            let beforeOp = startsLine(p);
547 628
            advance(p);
629 +
            let afterOp = startsLine(p);
548 630
549 631
            let mut right = try parseUnary(p);
550 632
551 633
            while let _ = findNextOp(p.current.kind, opInfo.prec)  {
552 634
                set right = try parseBinary(p, right, opInfo.prec);
553 635
            }
554 636
            set result = node(p, ast::NodeValue::BinOp(ast::BinOp {
555 637
                op: opInfo.op, left: result, right,
556 638
            }));
639 +
            markBroken(p, result, beforeOp or afterOp, ast::BrokenSite::Chain);
557 640
        }
558 641
    }
559 642
    return result;
560 643
}
561 644
574 657
            return true,
575 658
        else =>
576 659
            return false,
577 660
    }
578 661
}
579 -
/// Check if a statement requires a semicolon after it.
580 -
///
581 -
/// Statements that end with blocks don't require semicolons.
582 -
/// All other statements do.
583 -
fn expectsSemicolon(stmt: *ast::Node) -> bool {
584 -
    match stmt.value {
585 -
        case ast::NodeValue::If(_),
586 -
             ast::NodeValue::IfLet(_),
587 -
             ast::NodeValue::While(_),
588 -
             ast::NodeValue::WhileLet(_),
589 -
             ast::NodeValue::For(_),
590 -
             ast::NodeValue::Loop { .. },
591 -
             ast::NodeValue::Match(_),
592 -
             ast::NodeValue::Block(_),
593 -
             ast::NodeValue::FnDecl(_),
594 -
             ast::NodeValue::RecordDecl(_),
595 -
             ast::NodeValue::UnionDecl(_),
596 -
             ast::NodeValue::TraitDecl { .. },
597 -
             ast::NodeValue::InstanceDecl { .. },
598 -
             ast::NodeValue::MethodDecl { .. } => return false,
599 -
        else => return true,
600 -
    }
601 -
}
602 662
603 663
/// Parse a primary leaf expression without postfix operators.
604 664
fn parseLeaf(p: &mut Parser) -> *ast::Node
605 665
    throws (ParseError)
606 666
{
719 779
    let mut args = ast::nodeSlice(&mut p.arena, 4);
720 780
721 781
    if kind == ast::Builtin::SliceOf {
722 782
        // Parse comma-separated expressions until closing paren.
723 783
        // Argument count validation is done in semantic analysis.
784 +
        let mut outer = openList(p);
724 785
        while not check(p, scanner::TokenKind::RParen) {
725 -
            try! args.append(try parseExpr(p), &mut p.arena);
786 +
            let leading = takePending(p, &args[..]);
787 +
            noteItem(p, &mut outer);
788 +
            let arg = try parseExpr(p);
789 +
            attachLeading(p, arg, leading);
790 +
            try! args.append(arg, &mut p.arena);
726 791
            if not consume(p, scanner::TokenKind::Comma) {
727 792
                break;
728 793
            }
729 794
        }
795 +
        closeSoftList(p, outer, &args[..]);
730 796
    } else {
731 797
        try! args.append(try parseType(p), &mut p.arena);
732 798
    }
733 799
    try expect(p, scanner::TokenKind::RParen, "expected `)` after builtin argument");
800 +
    let call: *ast::Node = node(p, ast::NodeValue::BuiltinCall { kind, args });
801 +
    attachClosing(p, call);
734 802
735 -
    return node(p, ast::NodeValue::BuiltinCall { kind, args });
803 +
    return call;
736 804
}
737 805
738 806
/// Parse a single expression.
739 807
///
740 808
/// Parses unary and binary operators using precedence climbing.
779 847
    let target = try parseUnary(p);
780 848
    if not ast::isPlaceExpr(target) {
781 849
        throw failParsing(p, "invalid assignment target");
782 850
    }
783 851
    if consume(p, scanner::TokenKind::Equal) {
852 +
        let broken = startsLine(p);
784 853
        let value = try parseExpr(p);
785 -
        return node(p, ast::NodeValue::Assign(
854 +
        let stmt: *ast::Node = node(p, ast::NodeValue::Assign(
786 855
            ast::Assign { left: target, right: value }
787 856
        ));
857 +
        markBroken(p, stmt, broken, ast::BrokenSite::Value);
858 +
859 +
        return stmt;
788 860
    }
789 861
    // Compound assignment: desugar `set x <op>= y` into `set x = x <op> y`.
790 862
    // The target node is shared with the binary operand.
791 863
    if let op = tryCompoundAssignOp(p) {
864 +
        let broken = startsLine(p);
792 865
        let rhs = try parseExpr(p);
793 866
        let binop = node(p, ast::NodeValue::BinOp(
794 867
            ast::BinOp { op, left: target, right: rhs }
795 868
        ));
796 -
        return node(p, ast::NodeValue::Assign(
869 +
        let stmt: *ast::Node = node(p, ast::NodeValue::Assign(
797 870
            ast::Assign { left: target, right: binop }
798 871
        ));
872 +
        markBroken(p, stmt, broken, ast::BrokenSite::Value);
873 +
874 +
        return stmt;
799 875
    }
800 876
    throw failParsing(p, "expected assignment after `set`");
801 877
}
802 878
803 879
/// Parse leading attributes and declaration modifiers.
971 1047
    }
972 1048
}
973 1049
974 1050
/// Parse statements until the specified ending token is encountered.
975 1051
///
976 -
/// Returns the completed immutable statement list.
1052 +
/// Returns the completed immutable statement list. The trivia before `end` is
1053 +
/// left for the block that owns the statements.
977 1054
export fn parseStmtsUntil(p: &mut Parser, end: scanner::TokenKind, capacity: u32) -> *[*ast::Node]
978 1055
    throws (ParseError)
979 1056
{
1057 +
    let outer = openList(p);
980 1058
    let mut statements = ast::nodeSlice(&mut p.arena, capacity);
981 1059
    while not check(p, end) {
1060 +
        let leading = takePending(p, &statements[..]);
982 1061
        let stmt = try parseStmt(p);
1062 +
        attachLeading(p, stmt, leading);
983 1063
        try! statements.append(stmt, &mut p.arena);
984 1064
985 1065
        if check(p, end) or check(p, scanner::TokenKind::Eof) {
986 1066
            break;
987 1067
        }
988 1068
        if not consume(p, scanner::TokenKind::Semicolon) {
989 1069
            // Only require semicolon if the statement needs one.
990 -
            if expectsSemicolon(stmt) {
1070 +
            if ast::needsSemicolon(stmt) {
991 1071
                throw failParsing(p, "expected `;` after statement");
992 1072
            }
993 1073
        }
994 1074
    }
1075 +
    closeList(p, outer, &statements[..]);
1076 +
995 1077
    return statements;
996 1078
}
997 1079
998 1080
/// Parse a block of statements enclosed in curly braces.
999 1081
export fn parseBlock(p: &mut Parser) -> *ast::Node
1013 1095
    }
1014 1096
    let statements = try parseStmtsUntil(p, scanner::TokenKind::RBrace,
1015 1097
        INITIAL_STATEMENTS);
1016 1098
    let blk = ast::Block { statements, isUnsafe };
1017 1099
    try expect(p, scanner::TokenKind::RBrace, "expected `}`");
1100 +
    let block: *ast::Node = node(p, ast::NodeValue::Block(blk));
1101 +
    attachClosing(p, block);
1018 1102
1019 -
    return node(p, ast::NodeValue::Block(blk));
1103 +
    return block;
1020 1104
}
1021 1105
1022 1106
/// Create a block containing a single statement node.
1023 1107
fn mkBlockWith(p: &mut Parser, node: *ast::Node) -> ast::Block {
1024 1108
    let stmts = try! ast::nodeSlice(&mut p.arena, 1).append(node, &mut p.arena);
1083 1167
    let token = p.current;
1084 1168
    reportError(p, token, err);
1085 1169
    return ParseError::UnexpectedToken;
1086 1170
}
1087 1171
1088 -
/// Print all errors that have been collected during parsing.
1172 +
/// Write a decimal integer to standard error.
1173 +
fn printU32Error(val: u32) {
1174 +
    let mut buffer: [u8; fmt::U32_STR_LEN] = [0; fmt::U32_STR_LEN];
1175 +
    let start = fmt::formatU32(val, &mut buffer[..]);
1176 +
    io::printError(&buffer[start..]);
1177 +
}
1178 +
1179 +
/// Print all errors that have been collected during parsing to standard error.
1089 1180
export fn printErrors(p: &Parser) {
1090 1181
    for i in 0..p.errors.count {
1091 1182
        let e = p.errors.list[i];
1092 1183
        if let loc = scanner::getLocation(
1093 1184
            p.scanner.sourceLoc, p.scanner.source, e.token.offset
1094 1185
        ) {
1095 1186
            if let case scanner::SourceLoc::File(path) = loc.source {
1096 -
                io::print(path);
1097 -
                io::print(":");
1187 +
                io::printError(path);
1188 +
                io::printError(":");
1098 1189
            }
1099 -
            io::printU32(loc.line as u32);
1100 -
            io::print(":");
1101 -
            io::printU32(loc.col as u32);
1102 -
            io::print(": error: ");
1190 +
            printU32Error(loc.line as u32);
1191 +
            io::printError(":");
1192 +
            printU32Error(loc.col as u32);
1193 +
            io::printError(": error: ");
1103 1194
        } else {
1104 -
            io::print("error: ");
1195 +
            io::printError("error: ");
1105 1196
        }
1106 -
        io::print(e.message);
1197 +
        io::printError(e.message);
1107 1198
        if e.token.kind == scanner::TokenKind::Invalid {
1108 -
            io::print(": ");
1109 -
            io::print(e.token.source);
1199 +
            io::printError(": ");
1200 +
            io::printError(e.token.source);
1110 1201
        } else {
1111 -
            io::print(", got `");
1112 -
            io::print(e.token.source);
1113 -
            io::print("`");
1202 +
            io::printError(", got `");
1203 +
            io::printError(e.token.source);
1204 +
            io::printError("`");
1114 1205
        }
1115 -
        io::print("\n");
1206 +
        io::printError("\n");
1116 1207
    }
1117 1208
}
1118 1209
1119 1210
/// Check whether the current token matches the expected kind.
1120 1211
export fn check(p: &Parser, kind: scanner::TokenKind) -> bool {
1122 1213
}
1123 1214
1124 1215
/// Advance the parser by one token.
1125 1216
export fn advance(p: &mut Parser) {
1126 1217
    set p.previous = p.current;
1218 +
    if p.triviaMode == TriviaMode::Discard {
1219 +
        set p.current = scanner::next(&mut p.scanner, &mut p.pool);
1220 +
        return;
1221 +
    }
1222 +
    let gapStart = p.scanner.cursor;
1127 1223
    set p.current = scanner::next(&mut p.scanner, &mut p.pool);
1224 +
    let gapEnd = p.scanner.token;
1225 +
    scanGap(p, gapStart, gapEnd);
1226 +
}
1227 +
1228 +
/// Record the comments and blank lines in the source between two tokens.
1229 +
///
1230 +
/// Consecutive blank lines count as one.
1231 +
fn scanGap(p: &mut Parser, start: u32, end: u32) {
1232 +
    let source = p.scanner.source;
1233 +
    let mut i = start;
1234 +
    let mut newlines: u32 = 0;
1235 +
    let mut blank = true; // Only whitespace since the last line break.
1236 +
    let mut afterBlank = false;
1237 +
1238 +
    while i < end {
1239 +
        let c = source[i];
1240 +
        if c == '\n' {
1241 +
            if newlines > 0 and blank and not afterBlank {
1242 +
                appendPending(
1243 +
                    p, ast::TriviaKind::BlankLine, PendingLine::NewLine, i
1244 +
                );
1245 +
                set afterBlank = true;
1246 +
            }
1247 +
            set newlines += 1;
1248 +
            set blank = true;
1249 +
        } else if c == '/' and i + 1 < end and source[i + 1] == '/' {
1250 +
            let mut stop = i;
1251 +
            let mut last = i;
1252 +
            while stop < end and source[stop] <> '\n' {
1253 +
                let ch = source[stop];
1254 +
                if ch <> ' ' and ch <> '\t' and ch <> '\r' {
1255 +
                    set last = stop + 1;
1256 +
                }
1257 +
                set stop += 1;
1258 +
            }
1259 +
            let line = PendingLine::SameLine if newlines == 0
1260 +
                else PendingLine::NewLine;
1261 +
            appendPending(
1262 +
                p, ast::TriviaKind::Comment(&source[i..last]), line, i
1263 +
            );
1264 +
            set blank = false;
1265 +
            set afterBlank = false;
1266 +
            set i = stop;
1267 +
            continue;
1268 +
        }
1269 +
        set i += 1;
1270 +
    }
1271 +
}
1272 +
1273 +
/// Add a scanned comment or blank line at `offset` to the pending trivia.
1274 +
fn appendPending(
1275 +
    p: &mut Parser, kind: ast::TriviaKind, line: PendingLine, offset: u32
1276 +
) {
1277 +
    try! p.pending.append(Pending { kind, line, offset }, &mut p.arena);
1278 +
}
1279 +
1280 +
/// An open list: where the trivia of the enclosing list starts, and where the
1281 +
/// opening delimiter is.
1282 +
record Open: Copy {
1283 +
    /// Index in [`Parser::pending`] where the trivia of the enclosing list
1284 +
    /// starts, which [`closeList`] and [`endList`] restore.
1285 +
    base: u32,
1286 +
    /// Source offset of the opening delimiter.
1287 +
    offset: u32,
1288 +
    /// Whether every item so far started on a later line than the token before
1289 +
    /// it. See [`noteItem`].
1290 +
    alone: bool,
1291 +
}
1292 +
1293 +
/// Start the trivia of a list, right after its opening delimiter is consumed.
1294 +
///
1295 +
/// Trivia before the delimiter stays pending for the item that holds the list.
1296 +
fn openList(p: &mut Parser) -> Open {
1297 +
    let outer = p.base;
1298 +
    let mut base = outer;
1299 +
    while base < p.pending.len and p.pending[base].offset < p.previous.offset {
1300 +
        set base += 1;
1301 +
    }
1302 +
    set p.base = base;
1303 +
1304 +
    return Open { base: outer, offset: p.previous.offset, alone: true };
1305 +
}
1306 +
1307 +
/// Attach the pending comments on the line where the last of `items` ends to
1308 +
/// it as trailing trivia. Other pending trivia of the list stays pending.
1309 +
fn trailPending(p: &mut Parser, items: &[*ast::Node]) {
1310 +
    if items.len == 0 {
1311 +
        return;
1312 +
    }
1313 +
    let last = items[items.len - 1];
1314 +
    let mut list = p.pending.take();
1315 +
    let mut kept = p.base;
1316 +
    for i in p.base..list.len {
1317 +
        let t = list[i];
1318 +
        if t.line == PendingLine::SameLine {
1319 +
            attachOne(p, last, ast::TriviaPlacement::Trailing, t.kind);
1320 +
        } else {
1321 +
            set list[kept] = t;
1322 +
            set kept += 1;
1323 +
        }
1324 +
    }
1325 +
    set p.pending = &mut list[..kept];
1326 +
}
1327 +
1328 +
/// Take the pending trivia of the list at the start of an item or the end of
1329 +
/// the list.
1330 +
///
1331 +
/// A comment on the line where the last of `items` ends is attached to it as
1332 +
/// trailing trivia. The rest of the list's trivia is returned. Trivia of the
1333 +
/// enclosing constructs stays pending.
1334 +
fn takePending(p: &mut Parser, items: &[*ast::Node]) -> *mut [Pending] {
1335 +
    trailPending(p, items);
1336 +
    let mut list = p.pending.take();
1337 +
    let mut taken: *mut [Pending] = &mut [];
1338 +
    for i in p.base..list.len {
1339 +
        try! taken.append(list[i], &mut p.arena);
1340 +
    }
1341 +
    set p.pending = &mut list[..p.base];
1342 +
1343 +
    return taken;
1344 +
}
1345 +
1346 +
/// Set aside the trivia before the closing delimiter of a list, and return to
1347 +
/// the enclosing list whose trivia started at `outer`.
1348 +
///
1349 +
/// The node that owns the list claims it with [`attachClosing`] once created.
1350 +
fn closeList(p: &mut Parser, outer: Open, items: &[*ast::Node]) {
1351 +
    assert p.closing.len == 0, "closeList: unclaimed closing trivia";
1352 +
    set p.closing = takePending(p, items);
1353 +
    set p.base = outer.base;
1354 +
}
1355 +
1356 +
/// Close a list that a printer may break or keep on one line, with the
1357 +
/// closing delimiter as the current token.
1358 +
///
1359 +
/// Like [`closeList`], and the closing trivia also holds a mark when the source
1360 +
/// breaks the list across lines. Only a parser that keeps trivia marks.
1361 +
fn closeSoftList(p: &mut Parser, outer: Open, items: &[*ast::Node]) {
1362 +
    closeList(p, outer, items);
1363 +
    if spansLines(p, outer) {
1364 +
        appendMark(p, ast::BrokenSite::List);
1365 +
        if outer.alone and items.len > 1 {
1366 +
            appendMark(p, ast::BrokenSite::Items);
1367 +
        }
1368 +
    }
1369 +
}
1370 +
1371 +
/// Add a mark of a broken list to the closing trivia that [`closeList`] set
1372 +
/// aside.
1373 +
fn appendMark(p: &mut Parser, site: ast::BrokenSite) {
1374 +
    let kind = ast::TriviaKind::Broken(site);
1375 +
    let offset = p.current.offset;
1376 +
    try! p.closing.append(
1377 +
        Pending { kind, line: PendingLine::NewLine, offset }, &mut p.arena
1378 +
    );
1379 +
}
1380 +
1381 +
/// Note the item of a list that starts at the current token. The list stays
1382 +
/// `alone` while each item starts on a line of its own.
1383 +
fn noteItem(p: &Parser, outer: &mut Open) {
1384 +
    if not startsLine(p) {
1385 +
        set outer.alone = false;
1386 +
    }
1387 +
}
1388 +
1389 +
/// Whether the source between the opening delimiter of a list and the current
1390 +
/// token has a line break. Always false when trivia is discarded.
1391 +
fn spansLines(p: &Parser, outer: Open) -> bool {
1392 +
    if p.triviaMode == TriviaMode::Discard {
1393 +
        return false;
1394 +
    }
1395 +
    for i in outer.offset..p.current.offset {
1396 +
        if p.scanner.source[i] == '\n' {
1397 +
            return true;
1398 +
        }
1399 +
    }
1400 +
    return false;
1401 +
}
1402 +
1403 +
/// End a list that has no owner node, and return to the enclosing list whose
1404 +
/// trivia started at `outer`.
1405 +
///
1406 +
/// A comment on the line where the last of `items` ends is attached to it.
1407 +
/// The remaining trivia of the list joins the enclosing item.
1408 +
fn endList(p: &mut Parser, outer: Open, items: &[*ast::Node]) {
1409 +
    trailPending(p, items);
1410 +
    set p.base = outer.base;
1411 +
}
1412 +
1413 +
/// Attach one comment or blank line to the most recently created node.
1414 +
fn attachOne(
1415 +
    p: &mut Parser,
1416 +
    target: *ast::Node,
1417 +
    placement: ast::TriviaPlacement,
1418 +
    kind: ast::TriviaKind
1419 +
) {
1420 +
    if p.trivia.len > 0 {
1421 +
        assert p.trivia[p.trivia.len - 1].node.id <= target.id,
1422 +
            "attachOne: trivia not ordered by node";
1423 +
    }
1424 +
    let trivia = ast::Trivia { node: target, placement, kind };
1425 +
    try! p.trivia.append(trivia, &mut p.arena);
1426 +
}
1427 +
1428 +
/// Attach pending trivia to the most recently created node.
1429 +
fn attachTrivia(
1430 +
    p: &mut Parser,
1431 +
    target: *ast::Node,
1432 +
    placement: ast::TriviaPlacement,
1433 +
    list: *[Pending]
1434 +
) {
1435 +
    for t in list {
1436 +
        attachOne(p, target, placement, t.kind);
1437 +
    }
1438 +
}
1439 +
1440 +
/// Attach the trivia before an item of a list to it as leading trivia.
1441 +
///
1442 +
/// Comments of the list that start before the end of the last token of the
1443 +
/// item follow. No list inside the item claimed them, so they are a part of
1444 +
/// the item, such as a comment inside an expression. Blank lines among them
1445 +
/// are dropped.
1446 +
fn attachLeading(p: &mut Parser, item: *ast::Node, leading: *[Pending]) {
1447 +
    attachTrivia(p, item, ast::TriviaPlacement::Leading, leading);
1448 +
    let end = p.previous.offset + p.previous.source.len;
1449 +
    let mut list = p.pending.take();
1450 +
    let mut inside = p.base;
1451 +
    while inside < list.len and list[inside].offset < end {
1452 +
        let t = list[inside];
1453 +
        if let case ast::TriviaKind::Comment(_) = t.kind {
1454 +
            attachOne(p, item, ast::TriviaPlacement::Leading, t.kind);
1455 +
        }
1456 +
        set inside += 1;
1457 +
    }
1458 +
    let mut kept = p.base;
1459 +
    for i in inside..list.len {
1460 +
        set list[kept] = list[i];
1461 +
        set kept += 1;
1462 +
    }
1463 +
    set p.pending = &mut list[..kept];
1464 +
}
1465 +
1466 +
/// Attach the trivia set aside by [`closeList`] to `container` as closing
1467 +
/// trivia.
1468 +
fn attachClosing(p: &mut Parser, container: *ast::Node) {
1469 +
    let closing = p.closing.take();
1470 +
    attachTrivia(p, container, ast::TriviaPlacement::Closing, closing);
1128 1471
}
1129 1472
1130 1473
/// Parse an `if let` pattern matching statement.
1131 1474
///
1132 1475
/// Syntax: `if let binding = scrutinee { ... }`
1466 1809
    try expect(p, scanner::TokenKind::Match, "expected `match`");
1467 1810
1468 1811
    let subject = try parseCond(p);
1469 1812
    try expect(p, scanner::TokenKind::LBrace, "expected `{` before match prongs");
1470 1813
1814 +
    let outer = openList(p);
1471 1815
    let mut prongs = ast::nodeSlice(&mut p.arena, INITIAL_PRONGS);
1472 1816
    while not check(p, scanner::TokenKind::RBrace) and
1473 1817
          not check(p, scanner::TokenKind::Eof) // TODO: We shouldn't have to manually check for EOF.
1474 1818
    {
1819 +
        let leading = takePending(p, &prongs[..]);
1475 1820
        let prongNode = try parseMatchProng(p);
1821 +
        attachLeading(p, prongNode, leading);
1476 1822
        try! prongs.append(prongNode, &mut p.arena);
1477 1823
        consume(p, scanner::TokenKind::Comma);
1478 1824
    }
1825 +
    closeList(p, outer, &prongs[..]);
1479 1826
    try expect(p, scanner::TokenKind::RBrace, "expected `}` after match prongs");
1480 -
1481 -
    return node(p, ast::NodeValue::Match(
1827 +
    let matchNode: *ast::Node = node(p, ast::NodeValue::Match(
1482 1828
        ast::Match { subject, prongs }
1483 1829
    ));
1830 +
    attachClosing(p, matchNode);
1831 +
1832 +
    return matchNode;
1484 1833
}
1485 1834
1486 1835
/// Parse a single `match` prong.
1487 1836
fn parseMatchProng(p: &mut Parser) -> *ast::Node
1488 1837
    throws (ParseError)
1507 1856
        }
1508 1857
        if consume(p, scanner::TokenKind::If) {
1509 1858
            set guard = try parseCond(p);
1510 1859
        }
1511 1860
        try expect(p, scanner::TokenKind::FatArrow, "expected `=>` after case pattern");
1861 +
        let broken = startsLine(p);
1512 1862
        let body = try parseStmt(p);
1513 -
1514 -
        return node(p, ast::NodeValue::MatchProng(
1863 +
        let prong: *ast::Node = node(p, ast::NodeValue::MatchProng(
1515 1864
            ast::MatchProng { arm: ast::ProngArm::Case(patterns), guard, body }
1516 1865
        ));
1866 +
        markBroken(p, prong, broken, ast::BrokenSite::Value);
1867 +
1868 +
        return prong;
1517 1869
    }
1518 1870
    // Else prong: `else if <guard> => <body>`.
1519 1871
    if consume(p, scanner::TokenKind::Else) {
1520 1872
        if consume(p, scanner::TokenKind::If) {
1521 1873
            set guard = try parseCond(p);
1522 1874
        }
1523 1875
        try expect(p, scanner::TokenKind::FatArrow, "expected `=>` after else");
1876 +
        let broken = startsLine(p);
1524 1877
        let body = try parseStmt(p);
1525 -
1526 -
        return node(p, ast::NodeValue::MatchProng(
1878 +
        let prong: *ast::Node = node(p, ast::NodeValue::MatchProng(
1527 1879
            ast::MatchProng { arm: ast::ProngArm::Else, guard, body }
1528 1880
        ));
1881 +
        markBroken(p, prong, broken, ast::BrokenSite::Value);
1882 +
1883 +
        return prong;
1529 1884
    }
1530 1885
    // Binding prong: `<ident> if <guard> => <body>` or `_ if <guard> => <body>`.
1531 1886
    let binding = try parseIdentOrPlaceholder(p, "expected `case`, `else`, or identifier");
1532 1887
1533 1888
    if consume(p, scanner::TokenKind::If) {
1534 1889
        set guard = try parseCond(p);
1535 1890
    }
1536 1891
    try expect(p, scanner::TokenKind::FatArrow, "expected `=>` after binding");
1892 +
    let broken = startsLine(p);
1537 1893
    let body = try parseStmt(p);
1538 -
1539 -
    return node(p, ast::NodeValue::MatchProng(
1894 +
    let prong: *ast::Node = node(p, ast::NodeValue::MatchProng(
1540 1895
        ast::MatchProng { arm: ast::ProngArm::Binding(binding), guard, body }
1541 1896
    ));
1897 +
    markBroken(p, prong, broken, ast::BrokenSite::Value);
1898 +
1899 +
    return prong;
1542 1900
}
1543 1901
1544 1902
/// Parse a pattern expression used by `case` constructs.
1545 1903
/// Uses `Pattern` context to allow record literals but not conditional expressions.
1546 1904
fn parseMatchPattern(p: &mut Parser) -> *ast::Node
1588 1946
    let value = try parseParenthesized(p);
1589 1947
    return node(p, ast::NodeValue::Align { value });
1590 1948
}
1591 1949
1592 1950
/// Parse a comma-separated list of record fields.
1593 -
/// The opening delimiter should already be consumed.
1951 +
/// The opening delimiter should already be consumed. The trivia before the
1952 +
/// closing delimiter is left for the node that owns the fields.
1594 1953
/// For labeled fields: `{ name: T, ... }`.
1595 1954
/// For unlabeled fields: `(T, T, ...)`.
1596 1955
fn parseRecordFields(
1597 1956
    p: &mut Parser,
1598 1957
    mode: RecordFieldMode
1599 1958
) -> *mut [*ast::Node]
1600 1959
    throws (ParseError)
1601 1960
{
1602 1961
    let terminator = scanner::TokenKind::RBrace if mode == RecordFieldMode::Labeled
1603 1962
        else scanner::TokenKind::RParen;
1963 +
    let mut outer = openList(p);
1604 1964
    let mut fields = ast::nodeSlice(&mut p.arena, MAX_RECORD_FIELDS);
1605 1965
    while not check(p, terminator) {
1966 +
        let leading = takePending(p, &fields[..]);
1967 +
        noteItem(p, &mut outer);
1606 1968
        let mut recordField: ast::NodeValue = undefined;
1607 1969
        match mode {
1608 1970
            case RecordFieldMode::Labeled => {
1609 1971
                // Allow optional `let` keyword before field name.
1610 1972
                consume(p, scanner::TokenKind::Let);
1628 1990
                set recordField = ast::NodeValue::RecordField {
1629 1991
                    field: nil, type, value: nil,
1630 1992
                };
1631 1993
            }
1632 1994
        }
1633 -
        try! fields.append(node(p, recordField), &mut p.arena);
1995 +
        let fieldNode: *ast::Node = node(p, recordField);
1996 +
        attachLeading(p, fieldNode, leading);
1997 +
        try! fields.append(fieldNode, &mut p.arena);
1634 1998
1635 1999
        if not consume(p, scanner::TokenKind::Comma) {
1636 2000
            break;
1637 2001
        }
1638 2002
    }
2003 +
    closeSoftList(p, outer, &fields[..]);
1639 2004
    try expect(p, terminator, "expected closing delimiter after record fields");
1640 2005
1641 2006
    return fields;
1642 2007
}
1643 2008
1685 2050
    throws (ParseError)
1686 2051
{
1687 2052
    let mut fields = ast::nodeSlice(&mut p.arena, MAX_RECORD_FIELDS);
1688 2053
    let mut ignoreRest = false;
1689 2054
    try expect(p, scanner::TokenKind::LBrace, "expected `{` to begin record literal");
2055 +
    let mut outer = openList(p);
1690 2056
1691 2057
    while not check(p, scanner::TokenKind::RBrace) {
1692 2058
        // Check for `..` to ignore remaining fields.
1693 2059
        if consume(p, scanner::TokenKind::DotDot) {
1694 2060
            set ignoreRest = true;
1695 2061
            break;
1696 2062
        }
2063 +
        let leading = takePending(p, &fields[..]);
2064 +
        noteItem(p, &mut outer);
1697 2065
        let field = try parseRecordLitField(p);
2066 +
        attachLeading(p, field, leading);
1698 2067
        try! fields.append(field, &mut p.arena);
1699 2068
1700 2069
        if not consume(p, scanner::TokenKind::Comma) {
1701 2070
            break;
1702 2071
        }
1703 2072
    }
2073 +
    closeSoftList(p, outer, &fields[..]);
1704 2074
    try expect(p, scanner::TokenKind::RBrace, "expected `}` to end record literal");
1705 -
1706 -
    return node(p, ast::NodeValue::RecordLit(
2075 +
    let lit: *ast::Node = node(p, ast::NodeValue::RecordLit(
1707 2076
        ast::RecordLit { typeName, fields, ignoreRest }
1708 2077
    ));
2078 +
    attachClosing(p, lit);
2079 +
2080 +
    return lit;
1709 2081
}
1710 2082
1711 2083
/// Parse a named record declaration.
1712 2084
/// `record Point { x: i32, y: i32 }`, or `record Pair(i32, i32);`
1713 2085
/// Derives follow the positional fields: `record ScopeId(u32): Copy;`.
1734 2106
1735 2107
    if consume(p, scanner::TokenKind::LParen) {
1736 2108
        let fields = try parseRecordFields(p, RecordFieldMode::Unlabeled);
1737 2109
        let derives = try parseDerives(p);
1738 2110
        try expect(p, scanner::TokenKind::Semicolon, "expected `;` after record");
1739 -
        return node(p, ast::NodeValue::RecordDecl(
2111 +
        let decl: *ast::Node = node(p, ast::NodeValue::RecordDecl(
1740 2112
            ast::RecordDecl { name, fields, attrs: recordAttrs, derives, labeled: false }
1741 2113
        ));
2114 +
        attachClosing(p, decl);
2115 +
2116 +
        return decl;
1742 2117
    } else {
1743 2118
        let derives = try parseDerives(p);
1744 2119
        try expect(p, scanner::TokenKind::LBrace, "expected `{` before record body");
1745 2120
        let fields = try parseRecordFields(p, RecordFieldMode::Labeled);
1746 -
        return node(p, ast::NodeValue::RecordDecl(
2121 +
        let decl: *ast::Node = node(p, ast::NodeValue::RecordDecl(
1747 2122
            ast::RecordDecl { name, fields, attrs: recordAttrs, derives, labeled: true }
1748 2123
        ));
2124 +
        attachClosing(p, decl);
2125 +
2126 +
        return decl;
1749 2127
    }
1750 2128
}
1751 2129
1752 2130
/// Parse a union declaration.
1753 2131
/// Example: `union Color { Red, Green, Blue = 5 }`
1758 2136
1759 2137
    let name = try parseIdent(p, "expected union name");
1760 2138
    let derives = try parseDerives(p);
1761 2139
1762 2140
    try expect(p, scanner::TokenKind::LBrace, "expected `{` before union body");
2141 +
    let outer = openList(p);
1763 2142
1764 2143
    let mut variants = ast::nodeSlice(&mut p.arena, INITIAL_VARIANTS);
1765 2144
    while not check(p, scanner::TokenKind::RBrace) {
2145 +
        let leading = takePending(p, &variants[..]);
2146 +
        let joined = variants.len > 0 and sharesLine(p);
2147 +
1766 2148
        // Allow optional `case` keyword before variant name.
1767 2149
        consume(p, scanner::TokenKind::Case);
1768 2150
1769 2151
        let variantName = try parseIdent(p, "expected variant name");
1770 2152
        let mut payloadType: ?*ast::Node = nil;
1771 2153
        let mut explicitValue: ?*ast::Node = nil;
1772 2154
1773 2155
        if consume(p, scanner::TokenKind::LParen) { // `Variant(T, U)`.
1774 2156
            let fields = try parseRecordFields(p, RecordFieldMode::Unlabeled);
1775 -
            set payloadType = node(p, ast::NodeValue::TypeSig(
2157 +
            let payload: *ast::Node = node(p, ast::NodeValue::TypeSig(
1776 2158
                ast::TypeSig::Record { fields, labeled: false }
1777 2159
            ));
2160 +
            attachClosing(p, payload);
2161 +
            set payloadType = payload;
1778 2162
        } else if consume(p, scanner::TokenKind::LBrace) { // `Variant { x: T, y: T }`.
1779 2163
            let fields = try parseRecordFields(p, RecordFieldMode::Labeled);
1780 -
            set payloadType = node(p, ast::NodeValue::TypeSig(
2164 +
            let payload: *ast::Node = node(p, ast::NodeValue::TypeSig(
1781 2165
                ast::TypeSig::Record { fields, labeled: true }
1782 2166
            ));
2167 +
            attachClosing(p, payload);
2168 +
            set payloadType = payload;
1783 2169
        } else if consume(p, scanner::TokenKind::Equal) {
1784 2170
            // TODO: Support constant expressions.
1785 2171
            try expect(p, scanner::TokenKind::Number, "expected integer literal after `=`");
1786 2172
            let source = p.previous.source;
1787 2173
            let literal = try parseIntLiteral(p, source);
1788 2174
            set explicitValue = nodeNumber(p, literal);
1789 2175
        }
1790 2176
1791 -
        let variant = node(p, ast::NodeValue::UnionDeclVariant(
2177 +
        let variant: *ast::Node = node(p, ast::NodeValue::UnionDeclVariant(
1792 2178
            ast::UnionDeclVariant {
1793 2179
                name: variantName, index: variants.len as u32, value: explicitValue, type: payloadType,
1794 2180
            }
1795 2181
        ));
2182 +
        attachLeading(p, variant, leading);
2183 +
        markBroken(p, variant, joined, ast::BrokenSite::Joined);
1796 2184
        try! variants.append(variant, &mut p.arena);
1797 2185
1798 2186
        if not consume(p, scanner::TokenKind::Comma) {
1799 2187
            break;
1800 2188
        }
1801 2189
    }
2190 +
    closeList(p, outer, &variants[..]);
1802 2191
    try expect(p, scanner::TokenKind::RBrace, "expected `}`");
1803 -
1804 -
    return node(p, ast::NodeValue::UnionDecl(
2192 +
    let decl: *ast::Node = node(p, ast::NodeValue::UnionDecl(
1805 2193
        ast::UnionDecl { name, variants, attrs, derives }
1806 2194
    ));
2195 +
    attachClosing(p, decl);
2196 +
2197 +
    return decl;
1807 2198
}
1808 2199
1809 2200
/// Parse a function parameter.
1810 2201
fn parseFnParam(p: &mut Parser) -> *ast::Node
1811 2202
    throws (ParseError)
1818 2209
        ast::FnParam { name: ntv.name, type }
1819 2210
    ));
1820 2211
}
1821 2212
1822 2213
/// Parse an optional `throws` clause and return the collected type list.
1823 -
fn parseThrowList(p: &mut Parser) -> *mut [*ast::Node]
2214 +
///
2215 +
/// Sets `broken` to whether the closing parenthesis of the list is on a later
2216 +
/// line than the opening one. It stays false when trivia is discarded.
2217 +
fn parseThrowList(p: &mut Parser, broken: &mut bool) -> *mut [*ast::Node]
1824 2218
    throws (ParseError)
1825 2219
{
1826 2220
    if not consume(p, scanner::TokenKind::Throws) {
1827 2221
        return ast::nodeSlice(&mut p.arena, 0);
1828 2222
    }
1829 -
    return try parseList(
1830 -
        p,
1831 -
        scanner::TokenKind::LParen,
1832 -
        scanner::TokenKind::RParen,
1833 -
        parseType
2223 +
    try expect(p, scanner::TokenKind::LParen, "expected `(`");
2224 +
    let mut outer = openList(p);
2225 +
    let list = try parseItems(
2226 +
        p, scanner::TokenKind::RParen, parseType, &mut outer
1834 2227
    );
2228 +
    endList(p, outer, &list[..]);
2229 +
    set *broken = spansLines(p, outer);
2230 +
    try expect(p, scanner::TokenKind::RParen, "expected `)`");
2231 +
2232 +
    return list;
1835 2233
}
1836 2234
1837 2235
/// Parse a function type signature.
1838 2236
fn parseFnType(p: &mut Parser) -> *ast::Node
1839 2237
    throws (ParseError)
1840 2238
{
1841 2239
    let isUnsafe = consume(p, scanner::TokenKind::Unsafe);
1842 2240
    try expect(p, scanner::TokenKind::Fn, "expected `fn`");
1843 -
    let params = try parseList(
1844 -
        p,
1845 -
        scanner::TokenKind::LParen,
1846 -
        scanner::TokenKind::RParen,
1847 -
        parseType
2241 +
    try expect(p, scanner::TokenKind::LParen, "expected `(`");
2242 +
    let mut outer = openList(p);
2243 +
    let params = try parseItems(
2244 +
        p, scanner::TokenKind::RParen, parseType, &mut outer
1848 2245
    );
1849 -
    let mut returnType: ?*ast::Node = nil;
2246 +
    closeSoftList(p, outer, &params[..]);
2247 +
    let closing = p.closing.take();
2248 +
    try expect(p, scanner::TokenKind::RParen, "expected `)`");
1850 2249
2250 +
    let mut returnType: ?*ast::Node = nil;
1851 2251
    if consume(p, scanner::TokenKind::Arrow) {
1852 2252
        set returnType = try parseReturnType(p);
1853 2253
    }
1854 -
    let throwList = try parseThrowList(p);
2254 +
    let mut brokenThrows = false;
2255 +
    let throwList = try parseThrowList(p, &mut brokenThrows);
1855 2256
    let sig = ast::FnSig { params, returnType, throwList };
1856 -
    return node(p, ast::NodeValue::TypeSig(
2257 +
    let type: *ast::Node = node(p, ast::NodeValue::TypeSig(
1857 2258
        ast::TypeSig::Fn { sig, isUnsafe }
1858 2259
    ));
2260 +
    attachTrivia(p, type, ast::TriviaPlacement::Closing, closing);
2261 +
    markBroken(p, type, brokenThrows, ast::BrokenSite::Throws);
2262 +
2263 +
    return type;
1859 2264
}
1860 2265
1861 2266
/// Parse a function signature following the function name.
1862 -
fn parseFnTypeSig(p: &mut Parser) -> ast::FnSig
2267 +
fn parseFnTypeSig(p: &mut Parser) -> ParsedSig
1863 2268
    throws (ParseError)
1864 2269
{
1865 2270
    try expect(p, scanner::TokenKind::LParen, "expected `(` after function name");
2271 +
    let mut outer = openList(p);
1866 2272
    let mut params = ast::nodeSlice(&mut p.arena, 8);
1867 2273
1868 2274
    while not check(p, scanner::TokenKind::RParen) {
2275 +
        let leading = takePending(p, &params[..]);
2276 +
        noteItem(p, &mut outer);
1869 2277
        let param = try parseFnParam(p);
2278 +
        attachLeading(p, param, leading);
1870 2279
        try! params.append(param, &mut p.arena);
1871 2280
1872 2281
        if not consume(p, scanner::TokenKind::Comma) {
1873 2282
            break;
1874 2283
        }
1875 2284
    }
2285 +
    closeSoftList(p, outer, &params[..]);
2286 +
    let closing: *[Pending] = p.closing.take();
1876 2287
    try expect(p, scanner::TokenKind::RParen, "expected `)` after function parameters");
1877 2288
1878 2289
    let mut returnType: ?*ast::Node = nil;
1879 2290
    if consume(p, scanner::TokenKind::Arrow) {
1880 2291
        set returnType = try parseReturnType(p);
1881 2292
    }
1882 -
    let throwList = try parseThrowList(p);
2293 +
    let stacked = check(p, scanner::TokenKind::Throws) and startsLine(p);
2294 +
    let mut brokenThrows = false;
2295 +
    let throwList = try parseThrowList(p, &mut brokenThrows);
2296 +
2297 +
    return ParsedSig {
2298 +
        sig: ast::FnSig { params, returnType, throwList },
2299 +
        closing,
2300 +
        stacked,
2301 +
        brokenThrows,
2302 +
    };
2303 +
}
2304 +
2305 +
/// Whether a line break separates the current token from the previous one.
2306 +
/// Only trivia-keeping parsers look, so that compilation does not pay for it.
2307 +
fn startsLine(p: &Parser) -> bool {
2308 +
    if p.triviaMode == TriviaMode::Discard {
2309 +
        return false;
2310 +
    }
2311 +
    let end = p.previous.offset + p.previous.source.len;
2312 +
    for i in end..p.current.offset {
2313 +
        if p.scanner.source[i] == '\n' {
2314 +
            return true;
2315 +
        }
2316 +
    }
2317 +
    return false;
2318 +
}
2319 +
2320 +
/// Whether the current token is on the line of the token before it, when
2321 +
/// trivia is kept.
2322 +
fn sharesLine(p: &Parser) -> bool {
2323 +
    return p.triviaMode == TriviaMode::Keep and not startsLine(p);
2324 +
}
2325 +
2326 +
/// Attach the trivia of a parsed signature to the node that owns it: the
2327 +
/// comments before the `)` of the parameters and the mark of broken
2328 +
/// parameters, then the stacked `throws` mark and the mark of a broken
2329 +
/// `throws` list.
2330 +
fn attachSig(p: &mut Parser, owner: *ast::Node, parsed: ParsedSig) {
2331 +
    attachTrivia(p, owner, ast::TriviaPlacement::Closing, parsed.closing);
2332 +
    if parsed.stacked {
2333 +
        let mark = ast::TriviaKind::StackedThrows;
2334 +
        attachOne(p, owner, ast::TriviaPlacement::Closing, mark);
2335 +
    }
2336 +
    markBroken(p, owner, parsed.brokenThrows, ast::BrokenSite::Throws);
2337 +
}
1883 2338
1884 -
    return ast::FnSig { params, returnType, throwList };
2339 +
/// Attach to `owner` the mark that the source breaks a construct of it across
2340 +
/// lines at `site`, if `broken`.
2341 +
fn markBroken(
2342 +
    p: &mut Parser, owner: *ast::Node, broken: bool, site: ast::BrokenSite
2343 +
) {
2344 +
    if broken {
2345 +
        let mark = ast::TriviaKind::Broken(site);
2346 +
        attachOne(p, owner, ast::TriviaPlacement::Closing, mark);
2347 +
    }
1885 2348
}
1886 2349
1887 2350
/// Parse a function return type, including the uninhabited type.
1888 2351
fn parseReturnType(p: &mut Parser) -> *ast::Node throws (ParseError) {
1889 2352
    if consume(p, scanner::TokenKind::Bang) {
1901 2364
    // Method syntax: `fn (recv: *Type) name(params) { body }`.
1902 2365
    if check(p, scanner::TokenKind::LParen) {
1903 2366
        return try parseMethodDecl(p, attrs);
1904 2367
    }
1905 2368
    let name = try parseIdent(p, "expected function name");
1906 -
    let sig = try parseFnTypeSig(p);
2369 +
    let parsed = try parseFnTypeSig(p);
1907 2370
    let mut body: ?*ast::Node = nil;
1908 2371
    let mut fnAttrs = attrs;
1909 2372
1910 2373
    if consume(p, scanner::TokenKind::Semicolon) {
1911 2374
        if let a = attrs; ast::attributesContains(&a, ast::Attribute::Extern) {
1922 2385
            set fnAttrs = ast::Attributes { list };
1923 2386
        }
1924 2387
    } else {
1925 2388
        set body = try parseBlock(p);
1926 2389
    }
1927 -
    return node(p, ast::NodeValue::FnDecl(
1928 -
        ast::FnDecl { name, sig, body, attrs: fnAttrs }
2390 +
    let decl: *ast::Node = node(p, ast::NodeValue::FnDecl(
2391 +
        ast::FnDecl { name, sig: parsed.sig, body, attrs: fnAttrs }
1929 2392
    ));
2393 +
    attachSig(p, decl, parsed);
2394 +
2395 +
    return decl;
1930 2396
}
1931 2397
1932 2398
/// Parse a pointer-like type after its ownership prefix: a pointer, slice,
1933 2399
/// pointer to an array, or trait object.
1934 2400
fn parsePointerLikeType(
2116 2582
2117 2583
        if check(p, scanner::TokenKind::Align) {
2118 2584
            set alignment = try parseAlign(p);
2119 2585
        }
2120 2586
    }
2587 +
    let mut valueBroken = false;
2121 2588
    if consume(p, scanner::TokenKind::Equal) {
2589 +
        set valueBroken = startsLine(p);
2122 2590
        set value = try parseExpr(p);
2123 2591
    }
2124 -
    return NameTypeValue { name, type, value, alignment };
2592 +
    return NameTypeValue { name, type, value, alignment, valueBroken };
2125 2593
}
2126 2594
2127 2595
/// Parse a constant declaration.
2128 2596
fn parseConst(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2129 2597
    throws (ParseError)
2134 2602
    try expect(p, scanner::TokenKind::Colon, "expected `:` after identifier");
2135 2603
2136 2604
    let type = try parseType(p);
2137 2605
    try expect(p, scanner::TokenKind::Equal, "expected `=` in constant declaration");
2138 2606
2607 +
    let broken = startsLine(p);
2139 2608
    let value = try parseExpr(p);
2140 -
2141 -
    return node(p, ast::NodeValue::ConstDecl(
2609 +
    let decl: *ast::Node = node(p, ast::NodeValue::ConstDecl(
2142 2610
        ast::ConstDecl { ident, type, value, attrs }
2143 2611
    ));
2612 +
    markBroken(p, decl, broken, ast::BrokenSite::Value);
2613 +
2614 +
    return decl;
2144 2615
}
2145 2616
2146 2617
/// Parse a static declaration.
2147 2618
fn parseStatic(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2148 2619
    throws (ParseError)
2153 2624
    try expect(p, scanner::TokenKind::Colon, "expected `:` after identifier");
2154 2625
2155 2626
    let type = try parseType(p);
2156 2627
    try expect(p, scanner::TokenKind::Equal, "expected `=` in static declaration");
2157 2628
2629 +
    let broken = startsLine(p);
2158 2630
    let value = try parseExpr(p);
2159 -
2160 -
    return node(p, ast::NodeValue::StaticDecl(
2631 +
    let decl: *ast::Node = node(p, ast::NodeValue::StaticDecl(
2161 2632
        ast::StaticDecl { ident, type, value, attrs }
2162 2633
    ));
2634 +
    markBroken(p, decl, broken, ast::BrokenSite::Value);
2635 +
2636 +
    return decl;
2163 2637
}
2164 2638
2165 2639
/// Parse a `use` declaration.
2166 2640
fn parseUse(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2167 2641
    throws (ParseError)
2251 2725
        return node(p, ast::NodeValue::LetElse(ast::LetElse {
2252 2726
            pattern: ast::PatternMatch { pattern: binding.name, scrutinee: value, guard: nil, kind: ast::PatternKind::Binding, mutable },
2253 2727
            elseBranch,
2254 2728
        }));
2255 2729
    }
2256 -
    return node(p, ast::NodeValue::Let(ast::Let {
2730 +
    let stmt: *ast::Node = node(p, ast::NodeValue::Let(ast::Let {
2257 2731
        ident: binding.name, type: binding.type, value, alignment: binding.alignment, mutable,
2258 2732
    }));
2733 +
    markBroken(p, stmt, binding.valueBroken, ast::BrokenSite::Value);
2734 +
2735 +
    return stmt;
2259 2736
}
2260 2737
2261 2738
/// Parse one module from source text into a block of top-level statements.
2262 2739
///
2263 2740
/// Scanner, token, and error state are reset for the module. Nodes and strings
2264 2741
/// accumulate in the parser's arena and pool, which the module's AST keeps using.
2265 -
export fn parseModule(p: &mut Parser, sourceLoc: scanner::SourceLoc, input: *[u8]) -> *mut ast::Node
2742 +
export fn parseModule(p: &mut Parser, sourceLoc: scanner::SourceLoc, input: *[u8]) -> *ast::Node
2266 2743
    throws (ParseError)
2267 2744
{
2268 2745
    beginModule(p, sourceLoc, input);
2269 2746
2270 2747
    return try parseTopLevel(p) catch {
2281 2758
    set p.scanner = scanner::scanner(sourceLoc, input, &mut p.pool);
2282 2759
    set p.current = scanner::invalid(0, "");
2283 2760
    set p.previous = scanner::invalid(0, "");
2284 2761
    set p.errors = emptyErrorList();
2285 2762
    set p.context = Context::Normal;
2763 +
    set p.trivia = &mut [];
2764 +
    set p.pending = &mut [];
2765 +
    set p.base = 0;
2766 +
    set p.closing = &mut [];
2286 2767
}
2287 2768
2288 2769
/// Parse the current module's tokens into a block of top-level statements.
2289 -
fn parseTopLevel(p: &mut Parser) -> *mut ast::Node
2770 +
fn parseTopLevel(p: &mut Parser) -> *ast::Node
2290 2771
    throws (ParseError)
2291 2772
{
2292 2773
    advance(p); // Set the parser up with a first token.
2293 2774
2294 2775
    let statements = try parseStmtsUntil(p, scanner::TokenKind::Eof,
2295 2776
        INITIAL_MODULE_STATEMENTS);
2296 2777
    let blk = ast::Block { statements, isUnsafe: false };
2297 2778
    consume(p, scanner::TokenKind::Eof);
2779 +
    let block: *ast::Node = node(p, ast::NodeValue::Block(blk));
2780 +
    attachClosing(p, block);
2298 2781
2299 -
    return node(p, ast::NodeValue::Block(blk));
2782 +
    return block;
2300 2783
}
2301 2784
2302 2785
/// Consume a token of the given kind if present.
2303 2786
export fn consume(p: &mut Parser, kind: scanner::TokenKind) -> bool {
2304 2787
    if check(p, kind) {
2318 2801
        throw ParseError::UnexpectedToken;
2319 2802
    }
2320 2803
    return p.previous.source;
2321 2804
}
2322 2805
2323 -
/// Return a generic expectation message for a delimiter token.
2324 -
fn listExpectMessage(kind: scanner::TokenKind) -> *[u8] {
2325 -
    match kind {
2326 -
        case scanner::TokenKind::LParen => return "expected `(`",
2327 -
        case scanner::TokenKind::RParen => return "expected `)`",
2328 -
        case scanner::TokenKind::LBracket => return "expected `[`",
2329 -
        case scanner::TokenKind::RBracket => return "expected `]`",
2330 -
        case scanner::TokenKind::LBrace => return "expected `{`",
2331 -
        case scanner::TokenKind::RBrace => return "expected `}`",
2332 -
        else => return "expected delimiter",
2333 -
    }
2334 -
}
2335 -
2336 2806
/// Parse a trait declaration.
2337 2807
/// Syntax: `trait Name { fn (*Trait) method(...) -> T; ... }`
2338 2808
fn parseTraitDecl(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2339 2809
    throws (ParseError)
2340 2810
{
2341 2811
    try expect(p, scanner::TokenKind::Trait, "expected `trait`");
2342 2812
    let name = try parseIdent(p, "expected trait name");
2343 2813
    let supertraits = try parseDerives(p);
2344 2814
    try expect(p, scanner::TokenKind::LBrace, "expected `{` after trait name");
2815 +
    let outer = openList(p);
2345 2816
2346 2817
    let mut methods = ast::nodeSlice(&mut p.arena, ast::MAX_TRAIT_METHODS);
2347 2818
    while not check(p, scanner::TokenKind::RBrace) and
2348 2819
          not check(p, scanner::TokenKind::Eof)
2349 2820
    {
2821 +
        let leading = takePending(p, &methods[..]);
2350 2822
        let method = try parseTraitMethodSig(p);
2823 +
        attachLeading(p, method, leading);
2351 2824
        try! methods.append(method, &mut p.arena);
2352 2825
    }
2826 +
    closeList(p, outer, &methods[..]);
2353 2827
    try expect(p, scanner::TokenKind::RBrace, "expected `}` after trait methods");
2828 +
    let decl: *ast::Node = node(p, ast::NodeValue::TraitDecl {
2829 +
        name, supertraits, methods, attrs,
2830 +
    });
2831 +
    attachClosing(p, decl);
2354 2832
2355 -
    return node(p, ast::NodeValue::TraitDecl { name, supertraits, methods, attrs });
2833 +
    return decl;
2356 2834
}
2357 2835
2358 2836
/// Parse a trait method signature.
2359 2837
/// Syntax: `fn (*Trait) fnord(<params>) -> ReturnType;`
2360 2838
fn parseTraitMethodSig(p: &mut Parser) -> *ast::Node
2367 2845
    let receiver = try parseType(p);
2368 2846
2369 2847
    try expect(p, scanner::TokenKind::RParen, "expected `)` after receiver");
2370 2848
2371 2849
    let name = try parseIdent(p, "expected method name");
2372 -
    let sig = try parseFnTypeSig(p);
2850 +
    let parsed = try parseFnTypeSig(p);
2373 2851
    try expect(p, scanner::TokenKind::Semicolon, "expected `;` after method signature");
2852 +
    let method: *ast::Node = node(p, ast::NodeValue::TraitMethodSig {
2853 +
        name, receiver, sig: parsed.sig, attrs,
2854 +
    });
2855 +
    attachSig(p, method, parsed);
2374 2856
2375 -
    return node(p, ast::NodeValue::TraitMethodSig { name, receiver, sig, attrs });
2857 +
    return method;
2376 2858
}
2377 2859
2378 2860
/// Parse an instance block.
2379 2861
/// Syntax: `instance Trait for Type { fn (t: *mut Type) fnord(..) {..} }`
2380 2862
///
2386 2868
    try expect(p, scanner::TokenKind::Instance, "expected `instance`");
2387 2869
    let traitName = try parseTypePath(p);
2388 2870
    try expect(p, scanner::TokenKind::For, "expected `for` after trait name");
2389 2871
    let targetType = try parseTypePath(p);
2390 2872
    try expect(p, scanner::TokenKind::LBrace, "expected `{` after target type");
2873 +
    let outer = openList(p);
2391 2874
2392 2875
    let mut methods = ast::nodeSlice(&mut p.arena, ast::MAX_TRAIT_METHODS);
2393 2876
2394 2877
    while not check(p, scanner::TokenKind::RBrace) and
2395 2878
          not check(p, scanner::TokenKind::Eof)
2396 2879
    {
2880 +
        let leading = takePending(p, &methods[..]);
2397 2881
        let attrs = parseAttributes(p);
2398 2882
        try expect(p, scanner::TokenKind::Fn, "expected `fn`");
2399 2883
        let method = try parseMethodDecl(p, attrs);
2400 2884
2885 +
        attachLeading(p, method, leading);
2401 2886
        try! methods.append(method, &mut p.arena);
2402 2887
    }
2888 +
    closeList(p, outer, &methods[..]);
2403 2889
    try expect(p, scanner::TokenKind::RBrace, "expected `}` after instance methods");
2890 +
    let decl: *ast::Node = node(p, ast::NodeValue::InstanceDecl {
2891 +
        traitName, targetType, methods,
2892 +
    });
2893 +
    attachClosing(p, decl);
2404 2894
2405 -
    return node(p, ast::NodeValue::InstanceDecl { traitName, targetType, methods });
2895 +
    return decl;
2406 2896
}
2407 2897
2408 2898
/// Parse a method declaration with a receiver.
2409 2899
/// Syntax: `fn (t: *mut Type) fnord(<params>) -> ReturnType { body }`
2410 2900
///
2420 2910
    let receiverType = try parseType(p);
2421 2911
2422 2912
    try expect(p, scanner::TokenKind::RParen, "expected `)` after receiver type");
2423 2913
2424 2914
    let name = try parseIdent(p, "expected method name");
2425 -
    let sig = try parseFnTypeSig(p);
2915 +
    let parsed = try parseFnTypeSig(p);
2426 2916
    let body = try parseBlock(p);
2427 -
2428 -
    return node(p, ast::NodeValue::MethodDecl {
2429 -
        name, receiverName, receiverType, sig, body, attrs,
2917 +
    let method: *ast::Node = node(p, ast::NodeValue::MethodDecl {
2918 +
        name, receiverName, receiverType, sig: parsed.sig, body, attrs,
2430 2919
    });
2920 +
    attachSig(p, method, parsed);
2921 +
2922 +
    return method;
2431 2923
}
2432 2924
2433 -
/// Parse a comma-separated list enclosed by the given delimiters.
2434 -
fn parseList(
2925 +
/// Parse comma-separated items up to, not including, the `close` token.
2926 +
///
2927 +
/// The opening delimiter should already be consumed and the list opened with
2928 +
/// [`openList`], whose result is `outer`. The caller ends the list.
2929 +
fn parseItems(
2435 2930
    p: &mut Parser,
2436 -
    open: scanner::TokenKind,
2437 2931
    close: scanner::TokenKind,
2438 -
    parseItem: fn (&mut Parser) -> *ast::Node throws (ParseError)
2932 +
    parseItem: fn (&mut Parser) -> *ast::Node throws (ParseError),
2933 +
    outer: &mut Open
2439 2934
) -> *mut [*ast::Node] throws (ParseError) {
2440 -
    try expect(p, open, listExpectMessage(open));
2441 2935
    let mut items = ast::nodeSlice(&mut p.arena, 8);
2442 2936
2443 2937
    while not check(p, close) {
2938 +
        let leading = takePending(p, &items[..]);
2939 +
        noteItem(p, outer);
2444 2940
        let item = try parseItem(p);
2941 +
        attachLeading(p, item, leading);
2445 2942
        try! items.append(item, &mut p.arena);
2446 2943
2447 2944
        if not consume(p, scanner::TokenKind::Comma) {
2448 2945
            break;
2449 2946
        }
2450 2947
    }
2451 -
    try expect(p, close, listExpectMessage(close));
2452 -
2453 2948
    return items;
2454 2949
}
lib/std/lang/parser/tests.rad +468 -0
3300 3300
        assert mem::eq(parser.errors.list[0].message,
3301 3301
            "reserved keyword cannot be used as an identifier"),
3302 3302
            "incorrect reserved name diagnostic";
3303 3303
    }
3304 3304
}
3305 +
3306 +
/// Parse `input` as a module with trivia retention enabled.
3307 +
unsafe fn parseKept(parser: &mut super::Parser, input: *[u8]) -> *ast::Node
3308 +
    throws (testing::TestError)
3309 +
{
3310 +
    set parser.triviaMode = super::TriviaMode::Keep;
3311 +
3312 +
    return try super::parseModule(parser, scanner::SourceLoc::String, input) catch {
3313 +
        throw testing::TestError::Failed;
3314 +
    };
3315 +
}
3316 +
3317 +
/// Return the statements of a block node.
3318 +
fn blockStmts(block: *ast::Node) -> *[*ast::Node] {
3319 +
    let case ast::NodeValue::Block(b) = block.value else {
3320 +
        panic "blockStmts: expected block";
3321 +
    };
3322 +
    return b.statements;
3323 +
}
3324 +
3325 +
/// Return the body block of a function declaration statement.
3326 +
fn fnBody(decl: *ast::Node) -> *ast::Node {
3327 +
    let case ast::NodeValue::FnDecl(f) = decl.value else {
3328 +
        panic "fnBody: expected function";
3329 +
    };
3330 +
    let body = f.body else {
3331 +
        panic "fnBody: missing body";
3332 +
    };
3333 +
    return body;
3334 +
}
3335 +
3336 +
/// Assert that the trivia attached to `node` with `placement` has exactly the
3337 +
/// given comments, in order. An empty string stands for a blank line.
3338 +
fn expectTrivia(
3339 +
    parser: &super::Parser,
3340 +
    node: *ast::Node,
3341 +
    placement: ast::TriviaPlacement,
3342 +
    expected: *[*[u8]]
3343 +
) {
3344 +
    let mut seen: u32 = 0;
3345 +
    for i in 0..parser.trivia.len {
3346 +
        let t = parser.trivia[i];
3347 +
        if t.node.id <> node.id or t.placement <> placement {
3348 +
            continue;
3349 +
        }
3350 +
        // Marks of broken constructs are not comments or blank lines.
3351 +
        if let case ast::TriviaKind::Broken(_) = t.kind {
3352 +
            continue;
3353 +
        }
3354 +
        assert seen < expected.len, "expectTrivia: unexpected trivia";
3355 +
        match t.kind {
3356 +
            case ast::TriviaKind::Comment(text) =>
3357 +
                assert mem::eq(text, expected[seen]), "expectTrivia: wrong comment",
3358 +
            case ast::TriviaKind::BlankLine =>
3359 +
                assert expected[seen].len == 0, "expectTrivia: unexpected blank line",
3360 +
            case ast::TriviaKind::StackedThrows =>
3361 +
                panic "expectTrivia: unexpected stacked throws",
3362 +
            case ast::TriviaKind::Broken(_) =>
3363 +
                panic "expectTrivia: unexpected broken mark",
3364 +
        }
3365 +
        set seen += 1;
3366 +
    }
3367 +
    assert seen == expected.len, "expectTrivia: missing trivia";
3368 +
}
3369 +
3370 +
/// Count the comments in the trivia of a parser.
3371 +
fn commentCount(parser: &super::Parser) -> u32 {
3372 +
    let mut n: u32 = 0;
3373 +
    for i in 0..parser.trivia.len {
3374 +
        if let case ast::TriviaKind::Comment(_) = parser.trivia[i].kind {
3375 +
            set n += 1;
3376 +
        }
3377 +
    }
3378 +
    return n;
3379 +
}
3380 +
3381 +
/// Trivia ordered by node id, with no entry lost.
3382 +
fn expectOrdered(parser: &super::Parser, comments: u32) {
3383 +
    let mut last: u32 = 0;
3384 +
    for i in 0..parser.trivia.len {
3385 +
        let id = parser.trivia[i].node.id;
3386 +
        assert id >= last, "expectOrdered: trivia out of order";
3387 +
        set last = id;
3388 +
    }
3389 +
    assert commentCount(parser) == comments, "expectOrdered: comment lost";
3390 +
}
3391 +
3392 +
/// Leading, trailing, and closing comments attach to statements and the module.
3393 +
@test unsafe fn triviaStatements() throws (testing::TestError) {
3394 +
    let src = "// lead\nlet a = 1; // trail\n// lead b\nlet b = 2;\n// close\n";
3395 +
    let mut parser = mkParser(src);
3396 +
    let root = try parseKept(&mut parser, src);
3397 +
    let stmts = blockStmts(root);
3398 +
3399 +
    assert stmts.len == 2;
3400 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Leading, &["// lead"]);
3401 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Trailing, &["// trail"]);
3402 +
    expectTrivia(&parser, stmts[1], ast::TriviaPlacement::Leading, &["// lead b"]);
3403 +
    expectTrivia(&parser, stmts[1], ast::TriviaPlacement::Trailing, &[]);
3404 +
    expectTrivia(&parser, root, ast::TriviaPlacement::Closing, &["// close"]);
3405 +
    expectOrdered(&parser, 4);
3406 +
}
3407 +
3408 +
/// A comment with no statements to attach to becomes closing trivia of the block.
3409 +
@test unsafe fn triviaEmptyBlock() throws (testing::TestError) {
3410 +
    let src = "fn f() {\n    // nothing\n}\n";
3411 +
    let mut parser = mkParser(src);
3412 +
    let root = try parseKept(&mut parser, src);
3413 +
    let body = fnBody(blockStmts(root)[0]);
3414 +
3415 +
    expectTrivia(&parser, body, ast::TriviaPlacement::Closing, &["// nothing"]);
3416 +
    expectOrdered(&parser, 1);
3417 +
}
3418 +
3419 +
/// Comments in a trailing same-line position after `{` lead the first statement.
3420 +
@test unsafe fn triviaFirstItemSameLine() throws (testing::TestError) {
3421 +
    let src = "fn f() { // open\n    return;\n}\n";
3422 +
    let mut parser = mkParser(src);
3423 +
    let root = try parseKept(&mut parser, src);
3424 +
    let stmts = blockStmts(fnBody(blockStmts(root)[0]));
3425 +
3426 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Leading, &["// open"]);
3427 +
    expectOrdered(&parser, 1);
3428 +
}
3429 +
3430 +
/// Consecutive blank lines collapse into one; blank lines around comments stay.
3431 +
@test unsafe fn triviaBlankLines() throws (testing::TestError) {
3432 +
    let src = "let a = 1;\n\n  \n\n\nlet b = 2;\nlet c = 3;\n\n// x\n\nlet d = 4;\n";
3433 +
    let mut parser = mkParser(src);
3434 +
    let root = try parseKept(&mut parser, src);
3435 +
    let stmts = blockStmts(root);
3436 +
3437 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Leading, &[]);
3438 +
    expectTrivia(&parser, stmts[1], ast::TriviaPlacement::Leading, &[""]);
3439 +
    expectTrivia(&parser, stmts[2], ast::TriviaPlacement::Leading, &[]);
3440 +
    expectTrivia(&parser, stmts[3], ast::TriviaPlacement::Leading, &["", "// x", ""]);
3441 +
    expectOrdered(&parser, 1);
3442 +
}
3443 +
3444 +
/// A line break after a statement is not a blank line.
3445 +
@test unsafe fn triviaNoBlankLine() throws (testing::TestError) {
3446 +
    let src = "let a = 1;   \nlet b = 2;\n";
3447 +
    let mut parser = mkParser(src);
3448 +
    let _ = try parseKept(&mut parser, src);
3449 +
3450 +
    assert parser.trivia.len == 0;
3451 +
}
3452 +
3453 +
/// Record fields take leading, trailing, and closing comments.
3454 +
@test unsafe fn triviaRecordFields() throws (testing::TestError) {
3455 +
    let src = "record P {\n    // x\n    x: i32, // tx\n    y: i32,\n    // end\n}\n";
3456 +
    let mut parser = mkParser(src);
3457 +
    let root = try parseKept(&mut parser, src);
3458 +
    let stmts = blockStmts(root);
3459 +
    let case ast::NodeValue::RecordDecl(r) = stmts[0].value
3460 +
        else throw testing::TestError::Failed;
3461 +
3462 +
    assert r.fields.len == 2;
3463 +
    expectTrivia(&parser, r.fields[0], ast::TriviaPlacement::Leading, &["// x"]);
3464 +
    expectTrivia(&parser, r.fields[0], ast::TriviaPlacement::Trailing, &["// tx"]);
3465 +
    expectTrivia(&parser, r.fields[1], ast::TriviaPlacement::Leading, &[]);
3466 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Closing, &["// end"]);
3467 +
    expectOrdered(&parser, 3);
3468 +
}
3469 +
3470 +
/// Union variants, including their payload fields, take comments.
3471 +
@test unsafe fn triviaUnionVariants() throws (testing::TestError) {
3472 +
    let src = "union U {\n    A, // ta\n    // lb\n    B(i32 // tp\n    ),\n    // end\n}\n";
3473 +
    let mut parser = mkParser(src);
3474 +
    let root = try parseKept(&mut parser, src);
3475 +
    let case ast::NodeValue::UnionDecl(u) = blockStmts(root)[0].value
3476 +
        else throw testing::TestError::Failed;
3477 +
3478 +
    expectTrivia(&parser, u.variants[0], ast::TriviaPlacement::Trailing, &["// ta"]);
3479 +
    expectTrivia(&parser, u.variants[1], ast::TriviaPlacement::Leading, &["// lb"]);
3480 +
    expectTrivia(&parser, blockStmts(root)[0], ast::TriviaPlacement::Closing, &["// end"]);
3481 +
    expectOrdered(&parser, 4);
3482 +
}
3483 +
3484 +
/// Match prongs take comments.
3485 +
@test unsafe fn triviaMatchProngs() throws (testing::TestError) {
3486 +
    let src = "fn f() {\n    match x {\n        case 1 => a(), // t1\n        // l2\n        else => b(),\n        // cl\n    }\n}\n";
3487 +
    let mut parser = mkParser(src);
3488 +
    let root = try parseKept(&mut parser, src);
3489 +
    let body = blockStmts(fnBody(blockStmts(root)[0]));
3490 +
    let case ast::NodeValue::Match(m) = body[0].value
3491 +
        else throw testing::TestError::Failed;
3492 +
3493 +
    assert m.prongs.len == 2;
3494 +
    expectTrivia(&parser, m.prongs[0], ast::TriviaPlacement::Trailing, &["// t1"]);
3495 +
    expectTrivia(&parser, m.prongs[1], ast::TriviaPlacement::Leading, &["// l2"]);
3496 +
    expectTrivia(&parser, body[0], ast::TriviaPlacement::Closing, &["// cl"]);
3497 +
    expectOrdered(&parser, 3);
3498 +
}
3499 +
3500 +
/// Call arguments take comments; the closing comment belongs to the call.
3501 +
@test unsafe fn triviaCallArgs() throws (testing::TestError) {
3502 +
    let src = "f(\n    a, // ta\n    // lb\n    b,\n    // end\n); // after\n";
3503 +
    let mut parser = mkParser(src);
3504 +
    let root = try parseKept(&mut parser, src);
3505 +
    let stmts = blockStmts(root);
3506 +
    let case ast::NodeValue::ExprStmt(e) = stmts[0].value
3507 +
        else throw testing::TestError::Failed;
3508 +
    let case ast::NodeValue::Call(c) = e.value
3509 +
        else throw testing::TestError::Failed;
3510 +
3511 +
    assert c.args.len == 2;
3512 +
    expectTrivia(&parser, c.args[0], ast::TriviaPlacement::Trailing, &["// ta"]);
3513 +
    expectTrivia(&parser, c.args[1], ast::TriviaPlacement::Leading, &["// lb"]);
3514 +
    expectTrivia(&parser, e, ast::TriviaPlacement::Closing, &["// end"]);
3515 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Trailing, &["// after"]);
3516 +
    expectOrdered(&parser, 4);
3517 +
}
3518 +
3519 +
/// Array and record literal items take comments.
3520 +
@test unsafe fn triviaLiterals() throws (testing::TestError) {
3521 +
    let src = "let a = [\n    // l0\n    1, // t0\n    2,\n    // end\n];\nlet r = P {\n    x: 1, // tx\n    // ly\n    y: 2,\n    // end2\n};\n";
3522 +
    let mut parser = mkParser(src);
3523 +
    let root = try parseKept(&mut parser, src);
3524 +
    let stmts = blockStmts(root);
3525 +
    let case ast::NodeValue::Let(a) = stmts[0].value
3526 +
        else throw testing::TestError::Failed;
3527 +
    let case ast::NodeValue::ArrayLit(items) = a.value.value
3528 +
        else throw testing::TestError::Failed;
3529 +
    let case ast::NodeValue::Let(r) = stmts[1].value
3530 +
        else throw testing::TestError::Failed;
3531 +
    let case ast::NodeValue::RecordLit(lit) = r.value.value
3532 +
        else throw testing::TestError::Failed;
3533 +
3534 +
    expectTrivia(&parser, items[0], ast::TriviaPlacement::Leading, &["// l0"]);
3535 +
    expectTrivia(&parser, items[0], ast::TriviaPlacement::Trailing, &["// t0"]);
3536 +
    expectTrivia(&parser, a.value, ast::TriviaPlacement::Closing, &["// end"]);
3537 +
    expectTrivia(&parser, lit.fields[0], ast::TriviaPlacement::Trailing, &["// tx"]);
3538 +
    expectTrivia(&parser, lit.fields[1], ast::TriviaPlacement::Leading, &["// ly"]);
3539 +
    expectTrivia(&parser, r.value, ast::TriviaPlacement::Closing, &["// end2"]);
3540 +
    expectOrdered(&parser, 6);
3541 +
}
3542 +
3543 +
/// Trait method signatures and instance methods take comments.
3544 +
@test unsafe fn triviaTraitAndInstance() throws (testing::TestError) {
3545 +
    let src = "trait T {\n    // a\n    fn (*T) a();\n    fn (*T) b(); // tb\n    // end\n}\ninstance T for S {\n    // m\n    fn (s: *S) a() {}\n    // end2\n}\n";
3546 +
    let mut parser = mkParser(src);
3547 +
    let root = try parseKept(&mut parser, src);
3548 +
    let stmts = blockStmts(root);
3549 +
    let case ast::NodeValue::TraitDecl { methods, .. } = stmts[0].value
3550 +
        else throw testing::TestError::Failed;
3551 +
    let case ast::NodeValue::InstanceDecl { methods: impls, .. } = stmts[1].value
3552 +
        else throw testing::TestError::Failed;
3553 +
3554 +
    expectTrivia(&parser, methods[0], ast::TriviaPlacement::Leading, &["// a"]);
3555 +
    expectTrivia(&parser, methods[1], ast::TriviaPlacement::Trailing, &["// tb"]);
3556 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Closing, &["// end"]);
3557 +
    expectTrivia(&parser, impls[0], ast::TriviaPlacement::Leading, &["// m"]);
3558 +
    expectTrivia(&parser, stmts[1], ast::TriviaPlacement::Closing, &["// end2"]);
3559 +
    expectOrdered(&parser, 5);
3560 +
}
3561 +
3562 +
/// Parameters take leading and trailing comments.
3563 +
@test unsafe fn triviaParams() throws (testing::TestError) {
3564 +
    let src = "fn f(\n    a: i32, // ta\n    // lb\n    b: i32\n) {}\n";
3565 +
    let mut parser = mkParser(src);
3566 +
    let root = try parseKept(&mut parser, src);
3567 +
    let case ast::NodeValue::FnDecl(f) = blockStmts(root)[0].value
3568 +
        else throw testing::TestError::Failed;
3569 +
3570 +
    expectTrivia(&parser, f.sig.params[0], ast::TriviaPlacement::Trailing, &["// ta"]);
3571 +
    expectTrivia(&parser, f.sig.params[1], ast::TriviaPlacement::Leading, &["// lb"]);
3572 +
    expectOrdered(&parser, 2);
3573 +
}
3574 +
3575 +
/// A comment inside an expression is kept as leading trivia of the statement
3576 +
/// that holds it.
3577 +
@test unsafe fn triviaInsideExpression() throws (testing::TestError) {
3578 +
    let src = "let a = 1 +\n    // mid\n    2;\nlet b = 3;\n";
3579 +
    let mut parser = mkParser(src);
3580 +
    let root = try parseKept(&mut parser, src);
3581 +
    let stmts = blockStmts(root);
3582 +
3583 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Leading, &["// mid"]);
3584 +
    expectOrdered(&parser, 1);
3585 +
3586 +
    let src2 = "let a = 1 + // mid\n    2;\nlet b = 3;\n";
3587 +
    let mut parser2 = mkParser(src2);
3588 +
    let root2 = try parseKept(&mut parser2, src2);
3589 +
3590 +
    let first = blockStmts(root2)[0];
3591 +
    expectTrivia(&parser2, first, ast::TriviaPlacement::Leading, &["// mid"]);
3592 +
    expectOrdered(&parser2, 1);
3593 +
}
3594 +
3595 +
/// Comments left pending by an inner list reach the enclosing list.
3596 +
@test unsafe fn triviaNested() throws (testing::TestError) {
3597 +
    let src = "fn f(a: i32, // p\n    b: i32) { // open\n    g(x, // ax\n    y); // after\n    // end\n}\n";
3598 +
    let mut parser = mkParser(src);
3599 +
    let root = try parseKept(&mut parser, src);
3600 +
3601 +
    expectOrdered(&parser, 5);
3602 +
    let body = fnBody(blockStmts(root)[0]);
3603 +
    let stmts = blockStmts(body);
3604 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Leading, &["// open"]);
3605 +
    expectTrivia(&parser, stmts[0], ast::TriviaPlacement::Trailing, &["// after"]);
3606 +
    expectTrivia(&parser, body, ast::TriviaPlacement::Closing, &["// end"]);
3607 +
}
3608 +
3609 +
/// Doc comments are kept as leading comments.
3610 +
@test unsafe fn triviaDocComments() throws (testing::TestError) {
3611 +
    let src = "/// Doc one.\n///\n/// Doc two.   \nfn f() {}\n";
3612 +
    let mut parser = mkParser(src);
3613 +
    let root = try parseKept(&mut parser, src);
3614 +
3615 +
    expectTrivia(
3616 +
        &parser,
3617 +
        blockStmts(root)[0],
3618 +
        ast::TriviaPlacement::Leading,
3619 +
        &["/// Doc one.", "///", "/// Doc two."]
3620 +
    );
3621 +
    expectOrdered(&parser, 3);
3622 +
}
3623 +
3624 +
/// Comments at the end of input without a newline are kept.
3625 +
@test unsafe fn triviaEndOfInput() throws (testing::TestError) {
3626 +
    let src = "let a = 1; // x\n// y";
3627 +
    let mut parser = mkParser(src);
3628 +
    let root = try parseKept(&mut parser, src);
3629 +
3630 +
    expectTrivia(&parser, blockStmts(root)[0], ast::TriviaPlacement::Trailing, &["// x"]);
3631 +
    expectTrivia(&parser, root, ast::TriviaPlacement::Closing, &["// y"]);
3632 +
}
3633 +
3634 +
/// Without `Keep`, the parser records no trivia.
3635 +
@test unsafe fn triviaDiscard() throws (testing::TestError) {
3636 +
    let src = "// a\nlet a = 1; // b\n\nlet b = f(1, // c\n    2);\n// d\n";
3637 +
    let mut parser = mkParser(src);
3638 +
    let _ = try super::parseModule(&mut parser, scanner::SourceLoc::String, src) catch {
3639 +
        throw testing::TestError::Failed;
3640 +
    };
3641 +
3642 +
    assert parser.triviaMode == super::TriviaMode::Discard;
3643 +
    assert parser.trivia.len == 0;
3644 +
    assert parser.pending.len == 0;
3645 +
}
3646 +
3647 +
/// Count the stacked `throws` marks in the trivia of a parser.
3648 +
fn stackedCount(parser: &super::Parser) -> u32 {
3649 +
    let mut n: u32 = 0;
3650 +
    for i in 0..parser.trivia.len {
3651 +
        if let case ast::TriviaKind::StackedThrows = parser.trivia[i].kind {
3652 +
            set n += 1;
3653 +
        }
3654 +
    }
3655 +
    return n;
3656 +
}
3657 +
3658 +
/// A `throws` clause that starts a line is marked on the function, method, or
3659 +
/// trait method that owns it, and only when trivia is kept.
3660 +
@test unsafe fn triviaStackedThrows() throws (testing::TestError) {
3661 +
    let one = "fn f() throws (E) {}\n";
3662 +
    let mut parser = mkParser(one);
3663 +
    let _ = try parseKept(&mut parser, one);
3664 +
    assert stackedCount(&parser) == 0;
3665 +
3666 +
    let stacked = "fn f()\n throws (E)\n{}\nfn (a: *A) g()\n throws (E)\n{}\ntrait T { fn (*T) h()\n throws (E); }\n";
3667 +
    set parser = mkParser(stacked);
3668 +
    let _ = try parseKept(&mut parser, stacked);
3669 +
    assert stackedCount(&parser) == 3;
3670 +
3671 +
    set parser = mkParser(stacked);
3672 +
    let _ = try super::parseModule(&mut parser, scanner::SourceLoc::String, stacked) catch {
3673 +
        throw testing::TestError::Failed;
3674 +
    };
3675 +
    assert parser.trivia.len == 0;
3676 +
}
3677 +
3678 +
/// Count the marks of a broken source construct at `site` in the trivia of a
3679 +
/// parser.
3680 +
fn brokenCount(parser: &super::Parser, site: ast::BrokenSite) -> u32 {
3681 +
    let mut n: u32 = 0;
3682 +
    for i in 0..parser.trivia.len {
3683 +
        if let case ast::TriviaKind::Broken(found) = parser.trivia[i].kind; found == site {
3684 +
            set n += 1;
3685 +
        }
3686 +
    }
3687 +
    return n;
3688 +
}
3689 +
3690 +
/// Assert that parsing `src` keeping trivia gives `count` marks of `site`.
3691 +
unsafe fn expectBroken(src: *[u8], site: ast::BrokenSite, count: u32)
3692 +
    throws (testing::TestError)
3693 +
{
3694 +
    let mut parser = mkParser(src);
3695 +
    let _ = try parseKept(&mut parser, src);
3696 +
3697 +
    assert brokenCount(&parser, site) == count;
3698 +
}
3699 +
3700 +
/// Constructs that the source breaks across lines are marked, and the same
3701 +
/// constructs on one line are not.
3702 +
@test unsafe fn triviaBrokenSites() throws (testing::TestError) {
3703 +
    let lists = ast::BrokenSite::List;
3704 +
    try expectBroken("f(a, b);\n[1, 2];\nP { x };\n", lists, 0);
3705 +
    try expectBroken("f(\n a);\n", lists, 1);
3706 +
    try expectBroken("[1,\n 2];\n", lists, 1);
3707 +
    try expectBroken("[a;\n n];\n", lists, 1);
3708 +
    try expectBroken("P {\n x };\n", lists, 1);
3709 +
    try expectBroken("fn f(\n a: u32) {}\n", lists, 1);
3710 +
    try expectBroken("let t: fn(\n u32) = f;\n", lists, 1);
3711 +
    try expectBroken("record R(\n u32);\n", lists, 1);
3712 +
    try expectBroken("f(g(\n x));\n", lists, 2);
3713 +
3714 +
    let thrown = ast::BrokenSite::Throws;
3715 +
    try expectBroken("fn f() throws (E, F) {}\n", thrown, 0);
3716 +
    try expectBroken("fn f() throws (\n E) {}\n", thrown, 1);
3717 +
    try expectBroken("fn f() throws (\n E) {}\n", lists, 0);
3718 +
3719 +
    let chain = ast::BrokenSite::Chain;
3720 +
    try expectBroken("let x = a + b;\n", chain, 0);
3721 +
    try expectBroken("let x = a +\n b;\n", chain, 1);
3722 +
    try expectBroken("let x = a\n + b + c;\n", chain, 1);
3723 +
    try expectBroken("let x = a if c else b;\n", chain, 0);
3724 +
    try expectBroken("let x = a if c\n else b;\n", chain, 1);
3725 +
3726 +
    let items = ast::BrokenSite::Items;
3727 +
    try expectBroken("f(a, b);\n", items, 0);
3728 +
    try expectBroken("f(\n a, b);\n", items, 0);
3729 +
    try expectBroken("f(\n a,\n b);\n", items, 1);
3730 +
    try expectBroken("f(a,\n b);\n", items, 0);
3731 +
    try expectBroken("[\n 1,\n 2];\n", items, 1);
3732 +
    try expectBroken("P {\n x,\n y };\n", items, 1);
3733 +
    try expectBroken("fn f(\n a: u32,\n b: u32) {}\n", items, 1);
3734 +
    try expectBroken("fn f(\n a: u32, b: u32) {}\n", items, 0);
3735 +
3736 +
    let joined = ast::BrokenSite::Joined;
3737 +
    try expectBroken("union U { A, B }\n", joined, 1);
3738 +
    try expectBroken("union U {\n A,\n B }\n", joined, 0);
3739 +
    try expectBroken("union U {\n A, B,\n C, D, E }\n", joined, 3);
3740 +
3741 +
    let value = ast::BrokenSite::Value;
3742 +
    try expectBroken("let x = a;\nset y = b;\nset z += c;\n", value, 0);
3743 +
    try expectBroken("let x =\n a;\n", value, 1);
3744 +
    try expectBroken("set x =\n a;\n", value, 1);
3745 +
    try expectBroken("set x +=\n a;\n", value, 1);
3746 +
    try expectBroken("constant X: u32 =\n 1;\n", value, 1);
3747 +
    try expectBroken("static X: u32 =\n 1;\n", value, 1);
3748 +
    try expectBroken("match x { case A =>\n 1, }\n", value, 1);
3749 +
    try expectBroken("match x { case A => 1, }\n", value, 0);
3750 +
}
3751 +
3752 +
/// Without `Keep`, the parser records no marks of broken constructs.
3753 +
@test unsafe fn triviaBrokenDiscard() throws (testing::TestError) {
3754 +
    let src = "f(\n a +\n b);\nlet x =\n 1;\n";
3755 +
    let mut parser = mkParser(src);
3756 +
    let _ = try super::parseModule(&mut parser, scanner::SourceLoc::String, src) catch {
3757 +
        throw testing::TestError::Failed;
3758 +
    };
3759 +
    assert parser.trivia.len == 0;
3760 +
}
3761 +
3762 +
/// Beginning a new module drops the trivia of the previous one.
3763 +
@test unsafe fn triviaResetPerModule() throws (testing::TestError) {
3764 +
    let src = "// a\nlet a = 1;\n";
3765 +
    let mut parser = mkParser(src);
3766 +
    let _ = try parseKept(&mut parser, src);
3767 +
3768 +
    assert parser.trivia.len == 1;
3769 +
    super::beginModule(&mut parser, scanner::SourceLoc::String, "let b = 1;");
3770 +
    assert parser.trivia.len == 0;
3771 +
    assert parser.pending.len == 0;
3772 +
}
lib/std/lang/pretty.rad added +2736 -0
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::lang::alloc;
21 +
use std::lang::ast;
22 +
use std::lang::layout;
23 +
use std::lang::types;
24 +
25 +
/// Placement on the same line with no gap.
26 +
constant NONE: layout::Placement = layout::Placement::Inline(layout::Gap::None);
27 +
/// Placement on the same line after a space.
28 +
constant SPACE: layout::Placement = layout::Placement::Inline(
29 +
    layout::Gap::Space
30 +
);
31 +
/// Placement on the same line when flat, otherwise on a new line.
32 +
constant SOFT: layout::Placement = layout::Placement::SoftLine(
33 +
    layout::Gap::None
34 +
);
35 +
/// Placement on the same line after a space when flat, otherwise on a new line.
36 +
constant SOFT_SPACE: layout::Placement = layout::Placement::SoftLine(
37 +
    layout::Gap::Space
38 +
);
39 +
/// Placement on the same line when flat, otherwise on a new indented line.
40 +
constant SOFT_INDENT: layout::Placement = layout::Placement::SoftIndent(
41 +
    layout::Gap::None
42 +
);
43 +
/// Placement on the same line after a space when flat, otherwise on a new
44 +
/// indented line.
45 +
constant SOFT_INDENT_SPACE: layout::Placement = layout::Placement::SoftIndent(
46 +
    layout::Gap::Space
47 +
);
48 +
49 +
/// Column of the tab stop after the pattern of a match prong, which lines up
50 +
/// the arrows.
51 +
constant COLUMN_ARROW: u32 = 0;
52 +
/// Column of the tab stop before a trailing comment.
53 +
constant COLUMN_COMMENT: u32 = 1;
54 +
55 +
/// Level of an expression that binds looser than every other expression.
56 +
constant LEVEL_COND: u32 = 0;
57 +
/// Level of a range expression.
58 +
constant LEVEL_RANGE: u32 = 1;
59 +
/// Level of a binary expression with the loosest operator. Each tighter
60 +
/// operator precedence adds one.
61 +
constant LEVEL_BINARY: u32 = 2;
62 +
/// Level of a cast, which binds tighter than every binary operator.
63 +
constant LEVEL_CAST: u32 = 10;
64 +
/// Level of prefix expressions: unary operators, dereference, address-of, and
65 +
/// `try`.
66 +
constant LEVEL_PREFIX: u32 = 11;
67 +
/// Level of postfix and primary expressions.
68 +
constant LEVEL_POSTFIX: u32 = 12;
69 +
70 +
/// Syntactic context of an expression. It decides which forms need parentheses,
71 +
/// because the parser reads some forms differently in each context.
72 +
union Ctx: Copy {
73 +
    /// Ordinary expression.
74 +
    Normal,
75 +
    /// Pattern of `case`, where `if` starts a guard and `{` follows a type
76 +
    /// name.
77 +
    Pattern,
78 +
    /// Condition or subject, where `{` always starts a block.
79 +
    Condition,
80 +
}
81 +
82 +
/// Whether the guard of a pattern follows `;` or `if`.
83 +
union GuardStyle: Copy {
84 +
    /// `if let pattern = value; guard {`.
85 +
    Semicolon,
86 +
    /// `let case pattern = value if guard else`.
87 +
    If,
88 +
}
89 +
90 +
/// State of the layout of a module.
91 +
record Printer {
92 +
    /// Trivia of the module, ordered by node id.
93 +
    trivia: *[ast::Trivia],
94 +
    /// Number of trivia entries other than marks that were placed in the
95 +
    /// layout.
96 +
    used: u32,
97 +
    /// Number of function bodies that the layout is inside of.
98 +
    fnDepth: u32,
99 +
    /// Number of marks of broken constructs that were placed in the layout.
100 +
    marks: u32,
101 +
    /// Record literal that is an array item, if any.
102 +
    tableRecord: ?*ast::Node,
103 +
}
104 +
105 +
/// Whether the items of a soft list end with a comma when they are one per
106 +
/// line.
107 +
union Commas: Copy {
108 +
    /// Commas only between items.
109 +
    Between,
110 +
    /// A comma after the last item too, when the items are one per line.
111 +
    Trailing,
112 +
}
113 +
114 +
/// Delimiters and contents around the items of a soft list.
115 +
record SoftSpec: Copy {
116 +
    /// Node that the list presents, if any.
117 +
    source: ?*ast::Node,
118 +
    /// Node that owns the closing trivia of the list, if any.
119 +
    container: ?*ast::Node,
120 +
    /// Opening delimiter.
121 +
    open: *[u8],
122 +
    /// Closing delimiter.
123 +
    close: *[u8],
124 +
    /// Gap inside the delimiters.
125 +
    pad: layout::Gap,
126 +
    /// Text that follows the last item as another item, if any.
127 +
    tail: ?*[u8],
128 +
    /// Comma after the last item.
129 +
    commas: Commas,
130 +
    /// Whether the list is broken whether or not it fits. A list whose
131 +
    /// `container` has a [`ast::BrokenSite::List`] mark is broken too.
132 +
    forced: bool,
133 +
}
134 +
135 +
/// Blank line and comment state of one vertical list.
136 +
record Flow {
137 +
    /// Whether the list has an item or comment yet.
138 +
    started: bool,
139 +
    /// Whether a blank line is waiting for the next comment or item.
140 +
    blank: bool,
141 +
    /// Whether the line before is the end of a block in a function body, which
142 +
    /// no blank line follows.
143 +
    afterBlock: bool,
144 +
}
145 +
146 +
/// Format the module `root` with its `trivia`.
147 +
///
148 +
/// `root` is the block that the parser returns for a module, and `trivia` is
149 +
/// the parser's trivia for it. Every comment and blank line of `trivia` is
150 +
/// placed in the layout. The layout is allocated from `a`.
151 +
export fn module(
152 +
    root: *ast::Node, trivia: *[ast::Trivia], a: &mut opaque alloc::Allocator
153 +
) -> *layout::Layout throws (alloc::AllocError) {
154 +
    let case ast::NodeValue::Block(blk) = root.value else {
155 +
        panic "module: root is not a block";
156 +
    };
157 +
    let mut p = Printer { trivia, used: 0, fnDepth: 0, marks: 0, tableRecord: nil };
158 +
    let mut kids: *mut [layout::Child] = &mut [];
159 +
    try lines(
160 +
        a,
161 +
        &mut p,
162 +
        &mut kids,
163 +
        blk.statements,
164 +
        root,
165 +
        layout::Placement::Line,
166 +
        stmt
167 +
    );
168 +
    assert p.used + p.marks == trivia.len, "module: trivia entry not placed";
169 +
170 +
    return try group(a, root, kids);
171 +
}
172 +
173 +
// Layout construction ////////////////////////////////////////////////////////
174 +
175 +
/// Allocate a text layout.
176 +
fn leaf(
177 +
    a: &mut opaque alloc::Allocator,
178 +
    source: ?*ast::Node,
179 +
    text: *[u8],
180 +
    role: layout::Role
181 +
) -> *layout::Layout throws (alloc::AllocError) {
182 +
    return try layout::new(a, source, layout::Item::Text { text, role });
183 +
}
184 +
185 +
/// Allocate a box layout.
186 +
///
187 +
/// A box with a broken part is broken too: the part ends a line, so the soft
188 +
/// placements after it start new lines, as they would if the box did not fit.
189 +
fn group(
190 +
    a: &mut opaque alloc::Allocator, source: ?*ast::Node, kids: *[layout::Child]
191 +
) -> *layout::Layout throws (alloc::AllocError) {
192 +
    let box = try flatGroup(a, source, kids);
193 +
    for kid in kids {
194 +
        if hasBroken(kid.layout) {
195 +
            return try broken(a, box);
196 +
        }
197 +
    }
198 +
    return box;
199 +
}
200 +
201 +
/// Allocate a box layout that is flat when it fits, even with a broken part.
202 +
fn flatGroup(
203 +
    a: &mut opaque alloc::Allocator, source: ?*ast::Node, kids: *[layout::Child]
204 +
) -> *layout::Layout throws (alloc::AllocError) {
205 +
    return try layout::new(a, source, layout::Item::Box(kids));
206 +
}
207 +
208 +
/// Allocate a box with the single child `l` at `placement`.
209 +
fn placed(
210 +
    a: &mut opaque alloc::Allocator,
211 +
    placement: layout::Placement,
212 +
    l: *layout::Layout
213 +
) -> *layout::Layout throws (alloc::AllocError) {
214 +
    let mut kids: *mut [layout::Child] = &mut [];
215 +
    try add(a, &mut kids, placement, l);
216 +
    return try flatGroup(a, nil, kids);
217 +
}
218 +
219 +
/// Allocate a box of layouts that follow each other on one line.
220 +
fn row(
221 +
    a: &mut opaque alloc::Allocator, parts: &[*layout::Layout]
222 +
) -> *layout::Layout throws (alloc::AllocError) {
223 +
    let mut kids: *mut [layout::Child] = &mut [];
224 +
    for part in parts {
225 +
        try add(a, &mut kids, NONE, part);
226 +
    }
227 +
    return try flatGroup(a, nil, kids);
228 +
}
229 +
230 +
/// Allocate a choice between alternative layouts, in order of preference.
231 +
fn choice(
232 +
    a: &mut opaque alloc::Allocator,
233 +
    source: ?*ast::Node,
234 +
    alts: &[*layout::Layout]
235 +
) -> *layout::Layout throws (alloc::AllocError) {
236 +
    let mut copy: *mut [*layout::Layout] = &mut [];
237 +
    for alt in alts {
238 +
        try copy.append(alt, a);
239 +
    }
240 +
    return try layout::new(a, source, layout::Item::Choice(copy));
241 +
}
242 +
243 +
/// Allocate a choice between `l` on the current line after a space, and `l`
244 +
/// on the next line, one level deeper.
245 +
fn sameOrNext(
246 +
    a: &mut opaque alloc::Allocator, l: *layout::Layout
247 +
) -> *layout::Layout throws (alloc::AllocError) {
248 +
    return try choice(
249 +
        a,
250 +
        nil,
251 +
        &[
252 +
            try placed(a, SPACE, l),
253 +
            try placed(a, layout::Placement::Indent, l),
254 +
        ]
255 +
    );
256 +
}
257 +
258 +
/// Copy of `kids` with every soft placement on the same line.
259 +
fn inlined(
260 +
    a: &mut opaque alloc::Allocator, kids: *[layout::Child]
261 +
) -> *[layout::Child] throws (alloc::AllocError) {
262 +
    let mut out: *mut [layout::Child] = &mut [];
263 +
    for kid in kids {
264 +
        let mut placement = kid.placement;
265 +
        match kid.placement {
266 +
            case layout::Placement::SoftLine(gap) =>
267 +
                set placement = layout::Placement::Inline(gap),
268 +
            case layout::Placement::SoftIndent(gap) =>
269 +
                set placement = layout::Placement::Inline(gap),
270 +
            else => {}
271 +
        }
272 +
        try add(a, &mut out, placement, kid.layout);
273 +
    }
274 +
    return out;
275 +
}
276 +
277 +
/// Copy of a layout that stays on one line: every soft placement on the
278 +
/// line, and every choice at its first alternative.
279 +
fn flattened(
280 +
    a: &mut opaque alloc::Allocator, l: *layout::Layout
281 +
) -> *layout::Layout throws (alloc::AllocError) {
282 +
    match l.item {
283 +
        case layout::Item::Box(children) => {
284 +
            let mut copy: *mut [layout::Child] = &mut [];
285 +
            for kid in try inlined(a, children) {
286 +
                let flat = try flattened(a, kid.layout);
287 +
                try add(a, &mut copy, kid.placement, flat);
288 +
            }
289 +
            return try group(a, l.source, copy);
290 +
        }
291 +
        case layout::Item::Choice(alts)  => return try flattened(a, alts[0]),
292 +
        case layout::Item::Broken(inner) => return try flattened(a, inner),
293 +
        else                             => return l,
294 +
    }
295 +
}
296 +
297 +
/// Allocate a layout of the box `l`, broken whether or not it fits. A layout
298 +
/// that is broken already stays as it is.
299 +
fn broken(
300 +
    a: &mut opaque alloc::Allocator, l: *layout::Layout
301 +
) -> *layout::Layout throws (alloc::AllocError) {
302 +
    if let case layout::Item::Broken(_) = l.item {
303 +
        return l;
304 +
    }
305 +
    return try layout::new(a, l.source, layout::Item::Broken(l));
306 +
}
307 +
308 +
/// Layout `l`, broken whether or not it fits when `forced`.
309 +
fn forceBroken(
310 +
    a: &mut opaque alloc::Allocator, l: *layout::Layout, forced: bool
311 +
) -> *layout::Layout throws (alloc::AllocError) {
312 +
    if forced {
313 +
        return try broken(a, l);
314 +
    }
315 +
    return l;
316 +
}
317 +
318 +
/// Copy of `kids` whose last child is broken whether or not it fits.
319 +
fn brokenLast(
320 +
    a: &mut opaque alloc::Allocator, kids: *[layout::Child]
321 +
) -> *[layout::Child] throws (alloc::AllocError) {
322 +
    let mut copy: *mut [layout::Child] = &mut [];
323 +
    for kid in kids {
324 +
        try copy.append(kid, a);
325 +
    }
326 +
    let last = copy.len - 1;
327 +
    set copy[last].layout = try broken(a, copy[last].layout);
328 +
329 +
    return copy;
330 +
}
331 +
332 +
/// Append a child to a box under construction.
333 +
fn add(
334 +
    a: &mut opaque alloc::Allocator,
335 +
    kids: &mut *mut [layout::Child],
336 +
    placement: layout::Placement,
337 +
    child: *layout::Layout
338 +
) throws (alloc::AllocError) {
339 +
    try kids.append(layout::Child { placement, layout: child }, a);
340 +
}
341 +
342 +
/// Append a text child.
343 +
fn word(
344 +
    a: &mut opaque alloc::Allocator,
345 +
    kids: &mut *mut [layout::Child],
346 +
    placement: layout::Placement,
347 +
    text: *[u8],
348 +
    role: layout::Role
349 +
) throws (alloc::AllocError) {
350 +
    try add(a, kids, placement, try leaf(a, nil, text, role));
351 +
}
352 +
353 +
/// Append a keyword.
354 +
fn keyword(
355 +
    a: &mut opaque alloc::Allocator,
356 +
    kids: &mut *mut [layout::Child],
357 +
    placement: layout::Placement,
358 +
    text: *[u8]
359 +
) throws (alloc::AllocError) {
360 +
    try word(a, kids, placement, text, layout::Role::Keyword);
361 +
}
362 +
363 +
/// Append punctuation.
364 +
fn punct(
365 +
    a: &mut opaque alloc::Allocator,
366 +
    kids: &mut *mut [layout::Child],
367 +
    placement: layout::Placement,
368 +
    text: *[u8]
369 +
) throws (alloc::AllocError) {
370 +
    try word(a, kids, placement, text, layout::Role::Punct);
371 +
}
372 +
373 +
/// Append an operator.
374 +
fn operator(
375 +
    a: &mut opaque alloc::Allocator,
376 +
    kids: &mut *mut [layout::Child],
377 +
    placement: layout::Placement,
378 +
    text: *[u8]
379 +
) throws (alloc::AllocError) {
380 +
    try word(a, kids, placement, text, layout::Role::Operator);
381 +
}
382 +
383 +
/// Append a comment.
384 +
fn comment(
385 +
    a: &mut opaque alloc::Allocator,
386 +
    kids: &mut *mut [layout::Child],
387 +
    placement: layout::Placement,
388 +
    text: *[u8]
389 +
) throws (alloc::AllocError) {
390 +
    try word(a, kids, placement, text, layout::Role::Comment);
391 +
}
392 +
393 +
/// Append a blank line.
394 +
fn blankLine(
395 +
    a: &mut opaque alloc::Allocator,
396 +
    kids: &mut *mut [layout::Child],
397 +
    placement: layout::Placement
398 +
) throws (alloc::AllocError) {
399 +
    try add(a, kids, placement, try layout::new(a, nil, layout::Item::Blank));
400 +
}
401 +
402 +
// Trivia /////////////////////////////////////////////////////////////////////
403 +
404 +
/// Find the trivia entries of `node` with the given placement.
405 +
///
406 +
/// The entries of one node are contiguous in the order closing, leading,
407 +
/// trailing, so the result is a subslice of the module's trivia.
408 +
fn entries(
409 +
    p: &Printer, node: *ast::Node, placement: ast::TriviaPlacement
410 +
) -> *[ast::Trivia] {
411 +
    let all = p.trivia;
412 +
    let mut lo: u32 = 0;
413 +
    let mut hi: u32 = all.len;
414 +
    while lo < hi {
415 +
        let mid = lo + (hi - lo) / 2;
416 +
        if all[mid].node.id < node.id {
417 +
            set lo = mid + 1;
418 +
        } else {
419 +
            set hi = mid;
420 +
        }
421 +
    }
422 +
    let mut start = lo;
423 +
    let mut end = lo;
424 +
    let mut i = lo;
425 +
    while i < all.len and all[i].node.id == node.id {
426 +
        if all[i].placement == placement {
427 +
            if start == end {
428 +
                set start = i;
429 +
            }
430 +
            set end = i + 1;
431 +
        }
432 +
        set i += 1;
433 +
    }
434 +
    return &all[start..end];
435 +
}
436 +
437 +
/// Place comments and blank lines on lines of their own.
438 +
///
439 +
/// A blank line is placed only between comments or items: not first in the
440 +
/// list, not last, and not twice in a row. It waits in `flow` until a comment
441 +
/// or item follows it.
442 +
fn comments(
443 +
    a: &mut opaque alloc::Allocator,
444 +
    kids: &mut *mut [layout::Child],
445 +
    list: *[ast::Trivia],
446 +
    level: layout::Placement,
447 +
    flow: &mut Flow
448 +
) throws (alloc::AllocError) {
449 +
    for t in list {
450 +
        match t.kind {
451 +
            case ast::TriviaKind::Comment(text) => {
452 +
                if flow.blank {
453 +
                    try blankLine(a, kids, level);
454 +
                    set flow.blank = false;
455 +
                }
456 +
                try comment(a, kids, level, text);
457 +
                set flow.started = true;
458 +
                set flow.afterBlock = false;
459 +
            }
460 +
            case ast::TriviaKind::BlankLine => {
461 +
                if not flow.afterBlock {
462 +
                    set flow.blank = flow.started;
463 +
                }
464 +
            }
465 +
            case ast::TriviaKind::StackedThrows => {}
466 +
            case ast::TriviaKind::Broken(_)     => {}
467 +
        }
468 +
    }
469 +
}
470 +
471 +
/// The line that a vertical list is adding to: the children of its box, and
472 +
/// the index of the box in the list.
473 +
record Row {
474 +
    /// Code of the items of the line, which wrap together when the line is
475 +
    /// too wide.
476 +
    kids: *mut [layout::Child],
477 +
    /// Index of the line in the list.
478 +
    at: u32,
479 +
    /// Trailing comment of the line, if any.
480 +
    comment: ?*[u8],
481 +
}
482 +
483 +
/// Append `item` as a line at `level`, or when `joined`, to the last line, with
484 +
/// its trailing `comment`.
485 +
///
486 +
/// A tab stop of the column of comments goes before the comment, so that the
487 +
/// comments of consecutive lines line up.
488 +
fn addLine(
489 +
    a: &mut opaque alloc::Allocator,
490 +
    kids: &mut *mut [layout::Child],
491 +
    level: layout::Placement,
492 +
    row: &mut Row,
493 +
    joined: bool,
494 +
    item: *layout::Layout,
495 +
    comment: ?*[u8]
496 +
) throws (alloc::AllocError) {
497 +
    if joined {
498 +
        try add(a, &mut row.kids, SOFT_SPACE, item);
499 +
    } else {
500 +
        try add(a, kids, level, item);
501 +
        set row.at = kids.len - 1;
502 +
        set row.kids = &mut [];
503 +
        try add(a, &mut row.kids, NONE, item);
504 +
    }
505 +
    set row.comment = comment;
506 +
    if not joined and comment == nil {
507 +
        return;
508 +
    }
509 +
    let mut line: *mut [layout::Child] = &mut [];
510 +
    for i in 0..row.kids.len {
511 +
        try line.append(row.kids[i], a);
512 +
    }
513 +
    let mut code = item;
514 +
    if line.len > 1 {
515 +
        set code = try group(a, nil, line);
516 +
    }
517 +
    if let text = comment {
518 +
        let mut both: *mut [layout::Child] = &mut [];
519 +
        try add(a, &mut both, NONE, code);
520 +
        try add(a, &mut both, NONE, try tab(a, COLUMN_COMMENT));
521 +
        try add(
522 +
            a, &mut both, SPACE, try leaf(a, nil, text, layout::Role::Comment)
523 +
        );
524 +
        set code = try group(a, nil, both);
525 +
    }
526 +
    set kids[row.at].layout = code;
527 +
}
528 +
529 +
/// Allocate a tab stop of `column`.
530 +
fn tab(
531 +
    a: &mut opaque alloc::Allocator, column: u32
532 +
) -> *layout::Layout throws (alloc::AllocError) {
533 +
    return try layout::new(a, nil, layout::Item::Tab(column));
534 +
}
535 +
536 +
/// Place a vertical list of items, one per line at `level`, with the comments
537 +
/// and blank lines around them. An item that the source put after another on
538 +
/// its line follows that item.
539 +
///
540 +
/// Leading trivia goes on lines before its item, and trailing comments after
541 +
/// the item on its last line. The closing trivia of `container` follows the
542 +
/// last item.
543 +
fn lines(
544 +
    a: &mut opaque alloc::Allocator,
545 +
    p: &mut Printer,
546 +
    kids: &mut *mut [layout::Child],
547 +
    items: *[*ast::Node],
548 +
    container: *ast::Node,
549 +
    level: layout::Placement,
550 +
    format: fn(
551 +
        &mut opaque alloc::Allocator, &mut Printer, *ast::Node
552 +
    ) -> *layout::Layout
553 +
        throws (alloc::AllocError)
554 +
) throws (alloc::AllocError) {
555 +
    let mut flow = Flow { started: false, blank: false, afterBlock: false };
556 +
    let mut row = Row { kids: &mut [], at: 0, comment: nil };
557 +
    let spaced = spacesFunctions(p, container);
558 +
    for item, i in items {
559 +
        if i > 0 {
560 +
            // Functions are one blank line apart. A block in a function body
561 +
            // has no blank line after it.
562 +
            if spaced and hasBody(items[i - 1]) and hasBody(item) {
563 +
                set flow.blank = true;
564 +
            }
565 +
            set flow.afterBlock = p.fnDepth > 0 and endsWithBlock(items[i - 1]);
566 +
        }
567 +
        let leading = entries(p, item, ast::TriviaPlacement::Leading);
568 +
        set p.used += leading.len;
569 +
        try comments(a, kids, leading, level, &mut flow);
570 +
        if flow.blank {
571 +
            try blankLine(a, kids, level);
572 +
            set flow.blank = false;
573 +
        }
574 +
        // An item that the source put on the line of the one before it.
575 +
        let joined = takeMark(p, item, ast::BrokenSite::Joined)
576 +
            and leading.len == 0
577 +
            and kids.len > 0;
578 +
        let core = try format(a, p, item);
579 +
        let trailing = entries(p, item, ast::TriviaPlacement::Trailing);
580 +
        set p.used += trailing.len;
581 +
        let mut text: ?*[u8] = nil;
582 +
        if trailing.len > 0 {
583 +
            if let case ast::TriviaKind::Comment(first) = trailing[0].kind {
584 +
                set text = first;
585 +
            }
586 +
        }
587 +
        try addLine(a, kids, level, &mut row, joined, core, text);
588 +
        // Another comment on the same line is read back as a comment on its
589 +
        // own line.
590 +
        for j in 1..trailing.len {
591 +
            if let case ast::TriviaKind::Comment(more) = trailing[j].kind {
592 +
                try comment(a, kids, level, more);
593 +
            }
594 +
        }
595 +
        set flow.started = true;
596 +
    }
597 +
    let closing = entries(p, container, ast::TriviaPlacement::Closing);
598 +
    countClosing(p, closing);
599 +
    if items.len > 0 {
600 +
        let last = items[items.len - 1];
601 +
        set flow.afterBlock = p.fnDepth > 0 and endsWithBlock(last);
602 +
    }
603 +
    try comments(a, kids, closing, level, &mut flow);
604 +
}
605 +
606 +
/// Whether a list with the container `container` puts one blank line between
607 +
/// functions: the top level of a module, and the methods of an instance.
608 +
fn spacesFunctions(p: &Printer, container: *ast::Node) -> bool {
609 +
    match container.value {
610 +
        case ast::NodeValue::Block(_)            => return p.fnDepth == 0,
611 +
        case ast::NodeValue::InstanceDecl { .. } => return true,
612 +
        else                                     => return false,
613 +
    }
614 +
}
615 +
616 +
/// Whether a declaration is a function or method with a body. Declarations
617 +
/// without one, such as `extern` functions, stay grouped as the source has
618 +
/// them.
619 +
fn hasBody(node: *ast::Node) -> bool {
620 +
    match node.value {
621 +
        case ast::NodeValue::FnDecl(f)         => return f.body <> nil,
622 +
        case ast::NodeValue::MethodDecl { .. } => return true,
623 +
        else                                   => return false,
624 +
    }
625 +
}
626 +
627 +
/// Whether the last line of a statement is the closing brace of a block: a
628 +
/// statement with a block body, such as `if`, `match`, or a loop, a `let else`
629 +
/// with a block, or a statement that ends with a `try catch` block. An empty
630 +
/// block, as in `if a {}`, counts.
631 +
fn endsWithBlock(node: *ast::Node) -> bool {
632 +
    match node.value {
633 +
        case ast::NodeValue::If(_),
634 +
            ast::NodeValue::IfLet(_),
635 +
            ast::NodeValue::While(_),
636 +
            ast::NodeValue::WhileLet(_),
637 +
            ast::NodeValue::For(_),
638 +
            ast::NodeValue::Loop { .. },
639 +
            ast::NodeValue::Match(_),
640 +
            ast::NodeValue::Block(_) =>
641 +
            return true,
642 +
        case ast::NodeValue::LetElse(l)  => return endsWithBlock(l.elseBranch),
643 +
        case ast::NodeValue::Let(l)      => return exprEndsWithBlock(l.value),
644 +
        case ast::NodeValue::Assign(asg) => return exprEndsWithBlock(asg.right),
645 +
        case ast::NodeValue::ExprStmt(e) => return exprEndsWithBlock(e),
646 +
        case ast::NodeValue::Return { value } => {
647 +
            if let v = value {
648 +
                return exprEndsWithBlock(v);
649 +
            }
650 +
            return false;
651 +
        }
652 +
        else => return false,
653 +
    }
654 +
}
655 +
656 +
/// Whether an expression ends with the block of a `catch` clause.
657 +
fn exprEndsWithBlock(node: *ast::Node) -> bool {
658 +
    match node.value {
659 +
        case ast::NodeValue::Try(t)     => return t.catches.len > 0,
660 +
        case ast::NodeValue::BinOp(bin) => return exprEndsWithBlock(bin.right),
661 +
        else                            => return false,
662 +
    }
663 +
}
664 +
665 +
/// Specification of a list in parentheses with no gap inside them.
666 +
fn parens(container: ?*ast::Node) -> SoftSpec {
667 +
    return SoftSpec {
668 +
        source: nil,
669 +
        container,
670 +
        open: "(",
671 +
        close: ")",
672 +
        pad: layout::Gap::None,
673 +
        tail: nil,
674 +
        commas: Commas::Between,
675 +
        forced: false,
676 +
    };
677 +
}
678 +
679 +
/// Whether `node` has a mark that the source broke a construct of it at `site`.
680 +
///
681 +
/// The mark is closing trivia of the node. Whoever formats the closing trivia
682 +
/// of the node counts it as placed, and anyone else uses [`takeMark`].
683 +
fn marked(p: &Printer, node: *ast::Node, site: ast::BrokenSite) -> bool {
684 +
    for t in entries(p, node, ast::TriviaPlacement::Closing) {
685 +
        if let case ast::TriviaKind::Broken(found) = t.kind; found == site {
686 +
            return true;
687 +
        }
688 +
    }
689 +
    return false;
690 +
}
691 +
692 +
/// Like [`marked`], and counts the mark as placed. For a node whose closing
693 +
/// trivia no list formats.
694 +
fn takeMark(p: &mut Printer, node: *ast::Node, site: ast::BrokenSite) -> bool {
695 +
    if marked(p, node, site) {
696 +
        set p.marks += 1;
697 +
        return true;
698 +
    }
699 +
    return false;
700 +
}
701 +
702 +
/// Count the closing trivia of a node as placed.
703 +
fn countClosing(p: &mut Printer, closing: *[ast::Trivia]) {
704 +
    for t in closing {
705 +
        if let case ast::TriviaKind::Broken(_) = t.kind {
706 +
            set p.marks += 1;
707 +
        } else {
708 +
            set p.used += 1;
709 +
        }
710 +
    }
711 +
}
712 +
713 +
/// Place a soft list: `open`, items separated by commas, and `close`.
714 +
///
715 +
/// When flat, the list is on one line. Otherwise the items go on one indented
716 +
/// line when they fit, or one per line. A comment in the list breaks it. Blank
717 +
/// lines in the list are dropped. A comment before the closing delimiter puts
718 +
/// the items one per line. A list that the source broke across lines is
719 +
/// broken: its items go on a line of their own between the delimiters. They
720 +
/// are one per line when each started a line in the source. Array items keep
721 +
/// the source line groups when they fit.
722 +
fn softList(
723 +
    a: &mut opaque alloc::Allocator,
724 +
    p: &mut Printer,
725 +
    spec: SoftSpec,
726 +
    items: *[*ast::Node],
727 +
    ctx: Ctx,
728 +
    format: fn(
729 +
        &mut opaque alloc::Allocator, &mut Printer, *ast::Node, Ctx
730 +
    ) -> *layout::Layout
731 +
        throws (alloc::AllocError)
732 +
) -> *layout::Layout throws (alloc::AllocError) {
733 +
    let mut forced = spec.forced;
734 +
    if let node = spec.container {
735 +
        set forced = forced or marked(p, node, ast::BrokenSite::List);
736 +
    }
737 +
    let list = try plainList(a, p, spec, items, ctx, format);
738 +
739 +
    return try forceBroken(a, list, forced);
740 +
}
741 +
742 +
/// Place a soft list as [`softList`] does, but break it only for a comment in
743 +
/// it, and one per line when the source had them so.
744 +
fn plainList(
745 +
    a: &mut opaque alloc::Allocator,
746 +
    p: &mut Printer,
747 +
    spec: SoftSpec,
748 +
    items: *[*ast::Node],
749 +
    ctx: Ctx,
750 +
    format: fn(
751 +
        &mut opaque alloc::Allocator, &mut Printer, *ast::Node, Ctx
752 +
    ) -> *layout::Layout
753 +
        throws (alloc::AllocError)
754 +
) -> *layout::Layout throws (alloc::AllocError) {
755 +
    let mut inner: *mut [layout::Child] = &mut [];
756 +
    let mut rows: *mut [layout::Child] = &mut [];
757 +
    let mut at = NONE;
758 +
    let mut closingComment = false;
759 +
    let mut array = false;
760 +
    let mut tableRecord = false;
761 +
    if let node = spec.container {
762 +
        if let case ast::NodeValue::ArrayLit(_) = node.value {
763 +
            set array = true;
764 +
        }
765 +
        set tableRecord = p.tableRecord == node;
766 +
    }
767 +
    // The source put each item on a line of its own.
768 +
    let mut perLine = false;
769 +
    if let node = spec.container {
770 +
        set perLine = marked(p, node, ast::BrokenSite::Items);
771 +
    }
772 +
    for item, i in items {
773 +
        let leading = entries(p, item, ast::TriviaPlacement::Leading);
774 +
        set p.used += leading.len;
775 +
        if array and inner.len > 0 {
776 +
            for t in leading {
777 +
                if let case ast::TriviaKind::Broken(ast::BrokenSite::ItemLine) = t.kind {
778 +
                    let rowAt = NONE if rows.len == 0 else layout::Placement::Line;
779 +
                    try add(a, &mut rows, rowAt,
780 +
                        try group(a, nil, inner));
781 +
                    set inner = &mut [];
782 +
                    set at = NONE;
783 +
                }
784 +
            }
785 +
        }
786 +
        set at = try softComments(a, &mut inner, leading, at);
787 +
        let savedRecord = p.tableRecord;
788 +
        if array {
789 +
            set p.tableRecord = item;
790 +
        }
791 +
        let core = try format(a, p, item, ctx);
792 +
        set p.tableRecord = savedRecord;
793 +
        let mut comma: ?*layout::Layout = nil;
794 +
        if i + 1 < items.len or spec.tail <> nil {
795 +
            set comma = try leaf(a, nil, ",", layout::Role::Punct);
796 +
        } else if spec.commas == Commas::Trailing {
797 +
            if array and rows.len > 0 {
798 +
                set comma = try leaf(a, nil, ",", layout::Role::Punct);
799 +
            } else {
800 +
                let text = layout::Item::BrokenText {
801 +
                    text: ",", role: layout::Role::Punct
802 +
                };
803 +
                set comma = try layout::new(a, nil, text);
804 +
            }
805 +
        }
806 +
        let trailing = entries(p, item, ast::TriviaPlacement::Trailing);
807 +
        set p.used += trailing.len;
808 +
        let mut first: ?*[u8] = nil;
809 +
        if trailing.len > 0 {
810 +
            if let case ast::TriviaKind::Comment(text) = trailing[0].kind {
811 +
                set first = text;
812 +
            }
813 +
        }
814 +
        try add(a, &mut inner, at, core);
815 +
        if let c = comma {
816 +
            try add(a, &mut inner, NONE, c);
817 +
            if tableRecord and i == 0 {
818 +
                try add(a, &mut inner, NONE, try tab(a, COLUMN_ARROW));
819 +
            }
820 +
        }
821 +
        if let text = first {
822 +
            // The comments of items on lines of their own line up.
823 +
            try add(a, &mut inner, NONE, try tab(a, COLUMN_COMMENT));
824 +
            try comment(a, &mut inner, SPACE, text);
825 +
        }
826 +
        set at = SOFT_SPACE;
827 +
        for t, j in trailing {
828 +
            if j > 0 {
829 +
                if let case ast::TriviaKind::Comment(text) = t.kind {
830 +
                    try comment(a, &mut inner, SOFT_SPACE, text);
831 +
                }
832 +
            }
833 +
        }
834 +
    }
835 +
    if rows.len > 0 {
836 +
        if inner.len > 0 {
837 +
            try add(a, &mut rows, layout::Placement::Line, try group(a, nil, inner));
838 +
        }
839 +
        set inner = rows;
840 +
    }
841 +
    if let node = spec.container {
842 +
        let closing = entries(p, node, ast::TriviaPlacement::Closing);
843 +
        countClosing(p, closing);
844 +
        for t in closing {
845 +
            if let case ast::TriviaKind::Comment(_) = t.kind {
846 +
                set closingComment = true;
847 +
            }
848 +
        }
849 +
        set at = try softComments(a, &mut inner, closing, at);
850 +
    }
851 +
    if let text = spec.tail {
852 +
        try punct(a, &mut inner, at, text);
853 +
    }
854 +
    let mut kids: *mut [layout::Child] = &mut [];
855 +
    try punct(a, &mut kids, NONE, spec.open);
856 +
    if inner.len > 0 {
857 +
        // A comment before the closing delimiter keeps its own line.
858 +
        let mut body = try group(a, nil, inner);
859 +
        if closingComment or perLine {
860 +
            set body = try broken(a, body);
861 +
        }
862 +
        try add(a, &mut kids, layout::Placement::SoftIndent(spec.pad), body);
863 +
        try punct(
864 +
            a, &mut kids, layout::Placement::SoftLine(spec.pad), spec.close
865 +
        );
866 +
    } else {
867 +
        try punct(a, &mut kids, NONE, spec.close);
868 +
    }
869 +
    let list = try group(a, spec.source, kids);
870 +
    if closingComment {
871 +
        return try broken(a, list);
872 +
    }
873 +
    return list;
874 +
}
875 +
876 +
/// Place comments inside a soft list, each on a line of its own.
877 +
///
878 +
/// Returns the placement of the child that follows.
879 +
fn softComments(
880 +
    a: &mut opaque alloc::Allocator,
881 +
    kids: &mut *mut [layout::Child],
882 +
    list: *[ast::Trivia],
883 +
    placement: layout::Placement
884 +
) -> layout::Placement throws (alloc::AllocError) {
885 +
    let mut at = placement;
886 +
    for t in list {
887 +
        if let case ast::TriviaKind::Comment(text) = t.kind {
888 +
            try comment(a, kids, at, text);
889 +
            set at = SOFT_SPACE;
890 +
        }
891 +
    }
892 +
    return at;
893 +
}
894 +
895 +
// Expressions ////////////////////////////////////////////////////////////////
896 +
897 +
/// Source text of a compound assignment operator, if `op` has one.
898 +
fn compoundText(op: ast::BinaryOp) -> ?*[u8] {
899 +
    match op {
900 +
        case ast::BinaryOp::Add    => return "+=",
901 +
        case ast::BinaryOp::Sub    => return "-=",
902 +
        case ast::BinaryOp::Mul    => return "*=",
903 +
        case ast::BinaryOp::Div    => return "/=",
904 +
        case ast::BinaryOp::Mod    => return "%=",
905 +
        case ast::BinaryOp::BitAnd => return "&=",
906 +
        case ast::BinaryOp::BitOr  => return "|=",
907 +
        case ast::BinaryOp::BitXor => return "^=",
908 +
        case ast::BinaryOp::Shl    => return "<<=",
909 +
        case ast::BinaryOp::Shr    => return ">>=",
910 +
        else                       => return nil,
911 +
    }
912 +
}
913 +
914 +
/// Binding level of an expression. An operand needs parentheses when its level
915 +
/// is below the level that its parent requires.
916 +
fn level(node: *ast::Node) -> u32 {
917 +
    match node.value {
918 +
        case ast::NodeValue::CondExpr(_) => return LEVEL_COND,
919 +
        case ast::NodeValue::Range(_)    => return LEVEL_RANGE,
920 +
        case ast::NodeValue::BinOp(bin) =>
921 +
            return LEVEL_BINARY + ast::precedence(bin.op),
922 +
        case ast::NodeValue::As(_) => return LEVEL_CAST,
923 +
        case ast::NodeValue::UnOp(_),
924 +
            ast::NodeValue::Deref(_),
925 +
            ast::NodeValue::AddressOf(_),
926 +
            ast::NodeValue::Try(_) =>
927 +
            return LEVEL_PREFIX,
928 +
        else => return LEVEL_POSTFIX,
929 +
    }
930 +
}
931 +
932 +
/// Letter that follows the backslash when `c` is escaped in a literal
933 +
/// delimited by `quote`, or nil if `c` is written as it is.
934 +
fn escapeCode(c: u8, quote: u8) -> ?u8 {
935 +
    if c == quote or c == '\\' {
936 +
        return c;
937 +
    }
938 +
    match c {
939 +
        case '\n' => return 'n',
940 +
        case '\r' => return 'r',
941 +
        case '\t' => return 't',
942 +
        case 0    => return '0',
943 +
        else      => return nil,
944 +
    }
945 +
}
946 +
947 +
/// Escape `s` as the body of a literal delimited by `quote`, and add the
948 +
/// quotes.
949 +
fn quoted(
950 +
    a: &mut opaque alloc::Allocator, s: *[u8], quote: u8
951 +
) -> *[u8] throws (alloc::AllocError) {
952 +
    let mut out: *mut [u8] = &mut [];
953 +
    try out.append(quote, a);
954 +
    for c in s {
955 +
        if let code = escapeCode(c, quote) {
956 +
            try out.append('\\', a);
957 +
            try out.append(code, a);
958 +
        } else {
959 +
            try out.append(c, a);
960 +
        }
961 +
    }
962 +
    try out.append(quote, a);
963 +
964 +
    return out;
965 +
}
966 +
967 +
/// Layout of `node` wrapped in parentheses.
968 +
fn paren(
969 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
970 +
) -> *layout::Layout throws (alloc::AllocError) {
971 +
    let mut kids: *mut [layout::Child] = &mut [];
972 +
    try punct(a, &mut kids, NONE, "(");
973 +
    try put(a, p, &mut kids, NONE, node, Ctx::Normal);
974 +
    try punct(a, &mut kids, NONE, ")");
975 +
976 +
    return try group(a, node, kids);
977 +
}
978 +
979 +
/// Layout of an operand that must bind at least as tight as `min`.
980 +
fn operand(
981 +
    a: &mut opaque alloc::Allocator,
982 +
    p: &mut Printer,
983 +
    node: *ast::Node,
984 +
    ctx: Ctx,
985 +
    min: u32
986 +
) -> *layout::Layout throws (alloc::AllocError) {
987 +
    if level(node) < min {
988 +
        return try paren(a, p, node);
989 +
    }
990 +
    return try expr(a, p, node, ctx);
991 +
}
992 +
993 +
/// Append an expression as a child.
994 +
fn put(
995 +
    a: &mut opaque alloc::Allocator,
996 +
    p: &mut Printer,
997 +
    kids: &mut *mut [layout::Child],
998 +
    placement: layout::Placement,
999 +
    node: *ast::Node,
1000 +
    ctx: Ctx
1001 +
) throws (alloc::AllocError) {
1002 +
    try add(a, kids, placement, try expr(a, p, node, ctx));
1003 +
}
1004 +
1005 +
/// Append an operand that must bind at least as tight as `min` as a child.
1006 +
fn putOperand(
1007 +
    a: &mut opaque alloc::Allocator,
1008 +
    p: &mut Printer,
1009 +
    kids: &mut *mut [layout::Child],
1010 +
    placement: layout::Placement,
1011 +
    node: *ast::Node,
1012 +
    ctx: Ctx,
1013 +
    min: u32
1014 +
) throws (alloc::AllocError) {
1015 +
    try add(a, kids, placement, try operand(a, p, node, ctx, min));
1016 +
}
1017 +
1018 +
/// Whether `op` is a bitwise or shift operator.
1019 +
fn isBitwise(op: ast::BinaryOp) -> bool {
1020 +
    match op {
1021 +
        case ast::BinaryOp::BitAnd,
1022 +
            ast::BinaryOp::BitOr,
1023 +
            ast::BinaryOp::BitXor,
1024 +
            ast::BinaryOp::Shl,
1025 +
            ast::BinaryOp::Shr =>
1026 +
            return true,
1027 +
        else => return false,
1028 +
    }
1029 +
}
1030 +
1031 +
/// Layout of an operand of the binary operator `op`, where the operand must
1032 +
/// bind at least as tight as `min`.
1033 +
///
1034 +
/// An operand of another precedence gets parentheses for readability,
1035 +
/// although the parser does not need them, when it is a bitwise or shift
1036 +
/// operation inside a comparison, or any binary operation inside a bitwise or
1037 +
/// shift operation.
1038 +
fn chainOperand(
1039 +
    a: &mut opaque alloc::Allocator,
1040 +
    p: &mut Printer,
1041 +
    node: *ast::Node,
1042 +
    ctx: Ctx,
1043 +
    op: ast::BinaryOp,
1044 +
    min: u32
1045 +
) -> *layout::Layout throws (alloc::AllocError) {
1046 +
    let prec = ast::precedence(op);
1047 +
    if let case ast::NodeValue::BinOp(inner) =
1048 +
        node.value;
1049 +
        ast::precedence(inner.op) <> prec
1050 +
            and (isBitwise(op) or (prec > 0 and isBitwise(inner.op)))
1051 +
    {
1052 +
        return try paren(a, p, node);
1053 +
    }
1054 +
    return try operand(a, p, node, ctx, min);
1055 +
}
1056 +
1057 +
/// Format the left-most operands and operators of a chain of binary
1058 +
/// operations that have the precedence `prec`.
1059 +
///
1060 +
/// The chain breaks before the operators, each of which shares a box with its
1061 +
/// right operand. Operands that bind looser than the chain get parentheses.
1062 +
/// Returns whether the source broke the chain across lines, at any of its
1063 +
/// operations.
1064 +
fn chain(
1065 +
    a: &mut opaque alloc::Allocator,
1066 +
    p: &mut Printer,
1067 +
    kids: &mut *mut [layout::Child],
1068 +
    node: *ast::Node,
1069 +
    prec: u32,
1070 +
    ctx: Ctx
1071 +
) -> bool throws (alloc::AllocError) {
1072 +
    let case ast::NodeValue::BinOp(bin) = node.value else {
1073 +
        panic "chain: not a binary operation";
1074 +
    };
1075 +
    let mut forced = takeMark(p, node, ast::BrokenSite::Chain);
1076 +
    // Logical operators have one precedence, so a chain continues only across
1077 +
    // the same operator.
1078 +
    let mut continues = false;
1079 +
    if let case ast::NodeValue::BinOp(inner) = bin.left.value {
1080 +
        set continues = ast::precedence(inner.op) == prec
1081 +
            and (prec > 0 or inner.op == bin.op);
1082 +
    }
1083 +
    if continues {
1084 +
        if try chain(a, p, kids, bin.left, prec, ctx) {
1085 +
            set forced = true;
1086 +
        }
1087 +
    } else {
1088 +
        let mut min = LEVEL_BINARY + prec;
1089 +
        if prec == 0 {
1090 +
            set min += 1;
1091 +
        }
1092 +
        try add(
1093 +
            a, kids, NONE, try chainOperand(a, p, bin.left, ctx, bin.op, min)
1094 +
        );
1095 +
    }
1096 +
    // The operator and its operand share a box, so that breaks inside the
1097 +
    // operand nest deeper than the chain.
1098 +
    let mut tail: *mut [layout::Child] = &mut [];
1099 +
    try operator(a, &mut tail, NONE, ast::binaryText(bin.op));
1100 +
    try add(
1101 +
        a,
1102 +
        &mut tail,
1103 +
        SPACE,
1104 +
        try chainOperand(
1105 +
            a, p, bin.right, ctx, bin.op, LEVEL_BINARY + prec + 1
1106 +
        )
1107 +
    );
1108 +
    try add(a, kids, SOFT_INDENT_SPACE, try group(a, nil, tail));
1109 +
    return forced;
1110 +
}
1111 +
1112 +
/// Format an expression or type.
1113 +
fn expr(
1114 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node, ctx: Ctx
1115 +
) -> *layout::Layout throws (alloc::AllocError) {
1116 +
    // Forms that the context cannot parse bare need parentheses.
1117 +
    match node.value {
1118 +
        case ast::NodeValue::CondExpr(_) if ctx <> Ctx::Normal =>
1119 +
            return try paren(a, p, node),
1120 +
        case ast::NodeValue::RecordLit(lit)
1121 +
            if ctx == Ctx::Condition
1122 +
                or (ctx == Ctx::Pattern and lit.typeName == nil) =>
1123 +
            return try paren(a, p, node),
1124 +
        case ast::NodeValue::RecordLit(lit) if ctx == Ctx::Pattern => {
1125 +
            for field in lit.fields {
1126 +
                if let case ast::NodeValue::RecordLitField(arg) =
1127 +
                    field.value;
1128 +
                    level(arg.value) == LEVEL_COND
1129 +
                {
1130 +
                    return try paren(a, p, node);
1131 +
                }
1132 +
            }
1133 +
        }
1134 +
        else => {}
1135 +
    }
1136 +
    let mut kids: *mut [layout::Child] = &mut [];
1137 +
    match node.value {
1138 +
        case ast::NodeValue::Placeholder =>
1139 +
            return try leaf(a, node, "_", layout::Role::Name),
1140 +
        case ast::NodeValue::Nil =>
1141 +
            return try leaf(a, node, "nil", layout::Role::Literal),
1142 +
        case ast::NodeValue::Undef =>
1143 +
            return try leaf(a, node, "undefined", layout::Role::Literal),
1144 +
        case ast::NodeValue::Bool(value) =>
1145 +
            return try leaf(
1146 +
                a, node, "true" if value else "false", layout::Role::Literal
1147 +
            ),
1148 +
        case ast::NodeValue::Char(c) => {
1149 +
            let mut text: *mut [u8] = &mut [];
1150 +
            try text.append(c, a);
1151 +
            return try leaf(
1152 +
                a, node, try quoted(a, text, '\''), layout::Role::Literal
1153 +
            );
1154 +
        }
1155 +
        case ast::NodeValue::String(s) =>
1156 +
            return try leaf(
1157 +
                a, node, try quoted(a, s, '"'), layout::Role::Literal
1158 +
            ),
1159 +
        case ast::NodeValue::Ident(name) =>
1160 +
            return try leaf(a, node, name, layout::Role::Name),
1161 +
        case ast::NodeValue::Number(n) =>
1162 +
            return try leaf(a, node, n.text, layout::Role::Literal),
1163 +
        case ast::NodeValue::Super =>
1164 +
            return try leaf(a, node, "super", layout::Role::Keyword),
1165 +
        case ast::NodeValue::Range(r) => {
1166 +
            if let start = r.start {
1167 +
                // The parser reads `a + b * c..d` as `a + (b * c..d)`.
1168 +
                let mut min = LEVEL_BINARY;
1169 +
                if let case ast::NodeValue::BinOp(bin) =
1170 +
                    start.value;
1171 +
                    level(bin.right) < LEVEL_CAST
1172 +
                {
1173 +
                    set min = LEVEL_CAST;
1174 +
                }
1175 +
                try putOperand(a, p, &mut kids, NONE, start, ctx, min);
1176 +
            }
1177 +
            try operator(a, &mut kids, NONE, "..");
1178 +
            if let end = r.end {
1179 +
                try putOperand(a, p, &mut kids, NONE, end, ctx, LEVEL_RANGE);
1180 +
            }
1181 +
        }
1182 +
        case ast::NodeValue::ArrayLit(items) =>
1183 +
            return try softList(
1184 +
                a,
1185 +
                p,
1186 +
                SoftSpec {
1187 +
                    source: node,
1188 +
                    container: node,
1189 +
                    open: "[",
1190 +
                    close: "]",
1191 +
                    pad: layout::Gap::None,
1192 +
                    tail: nil,
1193 +
                    commas: Commas::Trailing,
1194 +
                    forced: false,
1195 +
                },
1196 +
                items,
1197 +
                Ctx::Normal,
1198 +
                expr
1199 +
            ),
1200 +
        case ast::NodeValue::ArrayRepeatLit(rep) => {
1201 +
            let mut inner: *mut [layout::Child] = &mut [];
1202 +
            let leading = entries(p, rep.item, ast::TriviaPlacement::Leading);
1203 +
            set p.used += leading.len;
1204 +
            let at = try softComments(a, &mut inner, leading, NONE);
1205 +
            try add(a, &mut inner, at, try expr(a, p, rep.item, Ctx::Normal));
1206 +
            try punct(a, &mut inner, NONE, ";");
1207 +
            try put(a, p, &mut inner, SOFT_SPACE, rep.count, Ctx::Normal);
1208 +
            try punct(a, &mut kids, NONE, "[");
1209 +
            try add(a, &mut kids, SOFT_INDENT, try group(a, nil, inner));
1210 +
            try punct(a, &mut kids, SOFT, "]");
1211 +
            let forced = takeMark(p, node, ast::BrokenSite::List);
1212 +
            return try forceBroken(a, try group(a, node, kids), forced);
1213 +
        }
1214 +
        case ast::NodeValue::Subscript { container, index } => {
1215 +
            try putOperand(
1216 +
                a, p, &mut kids, NONE, container, ctx, LEVEL_POSTFIX
1217 +
            );
1218 +
            // An index stays whole, so that a line breaks around it.
1219 +
            try punct(a, &mut kids, NONE, "[");
1220 +
            let inner = try expr(a, p, index, Ctx::Normal);
1221 +
            try add(a, &mut kids, NONE, try flattened(a, inner));
1222 +
            try punct(a, &mut kids, NONE, "]");
1223 +
        }
1224 +
        case ast::NodeValue::BinOp(bin) => {
1225 +
            let forced = try chain(
1226 +
                a, p, &mut kids, node, ast::precedence(bin.op), ctx
1227 +
            );
1228 +
            // The operator and right operand of a pair follow the left one
1229 +
            // when they fit, even when the left one broke.
1230 +
            if kids.len == 2 and not forced {
1231 +
                set kids[1] = layout::Child {
1232 +
                    placement: NONE, layout: try sameOrNext(a, kids[1].layout)
1233 +
                };
1234 +
            }
1235 +
            return try forceBroken(a, try group(a, node, kids), forced);
1236 +
        }
1237 +
        case ast::NodeValue::UnOp(un) => {
1238 +
            let at = SPACE if un.op == ast::UnaryOp::Not else NONE;
1239 +
            try operator(a, &mut kids, NONE, ast::unaryText(un.op));
1240 +
            try putOperand(a, p, &mut kids, at, un.value, ctx, LEVEL_PREFIX);
1241 +
        }
1242 +
        case ast::NodeValue::BuiltinCall { kind, args } => {
1243 +
            try word(
1244 +
                a, &mut kids, NONE, ast::builtinText(kind), layout::Role::Name
1245 +
            );
1246 +
            try add(a, &mut kids, NONE, try callArgs(a, p, node, args));
1247 +
        }
1248 +
        case ast::NodeValue::Call(call) => {
1249 +
            try putOperand(
1250 +
                a, p, &mut kids, NONE, call.callee, ctx, LEVEL_POSTFIX
1251 +
            );
1252 +
            try add(a, &mut kids, NONE, try callArgs(a, p, node, call.args));
1253 +
        }
1254 +
        case ast::NodeValue::FieldAccess(acc) => {
1255 +
            try putOperand(
1256 +
                a, p, &mut kids, NONE, acc.parent, ctx, LEVEL_POSTFIX
1257 +
            );
1258 +
            try punct(a, &mut kids, NONE, ".");
1259 +
            try put(a, p, &mut kids, NONE, acc.child, Ctx::Normal);
1260 +
        }
1261 +
        case ast::NodeValue::ScopeAccess(acc) => {
1262 +
            try putOperand(
1263 +
                a, p, &mut kids, NONE, acc.parent, ctx, LEVEL_POSTFIX
1264 +
            );
1265 +
            try punct(a, &mut kids, NONE, "::");
1266 +
            try put(a, p, &mut kids, NONE, acc.child, Ctx::Normal);
1267 +
        }
1268 +
        case ast::NodeValue::AddressOf(addr) => {
1269 +
            let at = SPACE if addr.mutable else NONE;
1270 +
            try operator(a, &mut kids, NONE, "&mut" if addr.mutable else "&");
1271 +
            try putOperand(a, p, &mut kids, at, addr.target, ctx, LEVEL_PREFIX);
1272 +
        }
1273 +
        case ast::NodeValue::Deref(target) => {
1274 +
            try operator(a, &mut kids, NONE, "*");
1275 +
            try putOperand(a, p, &mut kids, NONE, target, ctx, LEVEL_PREFIX);
1276 +
        }
1277 +
        case ast::NodeValue::As(cast) => {
1278 +
            try putOperand(a, p, &mut kids, NONE, cast.value, ctx, LEVEL_CAST);
1279 +
            try keyword(a, &mut kids, SPACE, "as");
1280 +
            try put(a, p, &mut kids, SPACE, cast.type, Ctx::Normal);
1281 +
        }
1282 +
        case ast::NodeValue::CondExpr(cond) => {
1283 +
            let forced = takeMark(p, node, ast::BrokenSite::Chain);
1284 +
            let mut test: *mut [layout::Child] = &mut [];
1285 +
            try keyword(a, &mut test, NONE, "if");
1286 +
            try add(
1287 +
                a,
1288 +
                &mut test,
1289 +
                SPACE,
1290 +
                try operand(
1291 +
                    a, p, cond.condition, Ctx::Condition, LEVEL_COND + 1
1292 +
                )
1293 +
            );
1294 +
            let mut other: *mut [layout::Child] = &mut [];
1295 +
            try keyword(a, &mut other, NONE, "else");
1296 +
            try put(a, p, &mut other, SPACE, cond.elseExpr, ctx);
1297 +
            try add(
1298 +
                a,
1299 +
                &mut kids,
1300 +
                NONE,
1301 +
                try operand(a, p, cond.thenExpr, ctx, LEVEL_COND + 1)
1302 +
            );
1303 +
            try add(
1304 +
                a,
1305 +
                &mut kids,
1306 +
                SOFT_INDENT_SPACE,
1307 +
                try group(a, cond.condition, test)
1308 +
            );
1309 +
            try add(
1310 +
                a,
1311 +
                &mut kids,
1312 +
                SOFT_INDENT_SPACE,
1313 +
                try group(a, cond.elseExpr, other)
1314 +
            );
1315 +
            return try forceBroken(a, try group(a, node, kids), forced);
1316 +
        }
1317 +
        case ast::NodeValue::Try(t) => {
1318 +
            let name = "try!"
1319 +
                if t.shouldPanic
1320 +
                else "try?" if t.returnsOptional else "try";
1321 +
            try keyword(a, &mut kids, NONE, name);
1322 +
            try putOperand(a, p, &mut kids, SPACE, t.expr, ctx, LEVEL_PREFIX);
1323 +
            for clause in t.catches {
1324 +
                let case ast::NodeValue::CatchClause(c) = clause.value else {
1325 +
                    panic "expr: catch clause expected";
1326 +
                };
1327 +
                try keyword(a, &mut kids, SPACE, "catch");
1328 +
                if let binding = c.binding {
1329 +
                    try put(a, p, &mut kids, SPACE, binding, Ctx::Normal);
1330 +
                }
1331 +
                if let typeNode = c.typeNode {
1332 +
                    try keyword(a, &mut kids, SPACE, "as");
1333 +
                    try put(a, p, &mut kids, SPACE, typeNode, Ctx::Normal);
1334 +
                }
1335 +
                try blockBody(a, p, &mut kids, c.body, SPACE);
1336 +
            }
1337 +
        }
1338 +
        case ast::NodeValue::RecordLit(lit) => {
1339 +
            if let typeName = lit.typeName {
1340 +
                try putOperand(
1341 +
                    a, p, &mut kids, NONE, typeName, ctx, LEVEL_POSTFIX
1342 +
                );
1343 +
            }
1344 +
            let mut tail: ?*[u8] = nil;
1345 +
            if lit.ignoreRest {
1346 +
                set tail = "..";
1347 +
            }
1348 +
            let at = SPACE if lit.typeName <> nil else NONE;
1349 +
            try add(
1350 +
                a,
1351 +
                &mut kids,
1352 +
                at,
1353 +
                try softList(
1354 +
                    a,
1355 +
                    p,
1356 +
                    SoftSpec {
1357 +
                        source: nil,
1358 +
                        container: node,
1359 +
                        open: "{",
1360 +
                        close: "}",
1361 +
                        pad: layout::Gap::Space,
1362 +
                        tail,
1363 +
                        commas: Commas::Trailing,
1364 +
                        forced: false,
1365 +
                    },
1366 +
                    lit.fields,
1367 +
                    ctx,
1368 +
                    recordLitField
1369 +
                )
1370 +
            );
1371 +
        }
1372 +
        case ast::NodeValue::TypeSig(sig) =>
1373 +
            return try typeSig(a, p, node, sig),
1374 +
        case ast::NodeValue::Align { value } => {
1375 +
            try keyword(a, &mut kids, NONE, "align");
1376 +
            try punct(a, &mut kids, NONE, "(");
1377 +
            try put(a, p, &mut kids, NONE, value, Ctx::Normal);
1378 +
            try punct(a, &mut kids, NONE, ")");
1379 +
        }
1380 +
        else => panic "expr: not an expression",
1381 +
    }
1382 +
    return try group(a, node, kids);
1383 +
}
1384 +
1385 +
/// Format the arguments of a call.
1386 +
///
1387 +
/// When the arguments do not fit on the line of the call, a last record or
1388 +
/// array literal, or a call, opens on that line after the other arguments, as
1389 +
/// in `f(x, Entry {`, if the line fits. A last call that is the only argument
1390 +
/// also hugs when it is wrapped in an operator or `try`. Arguments that the
1391 +
/// source broke are never flat: they hug, or go on lines of their own.
1392 +
fn callArgs(
1393 +
    a: &mut opaque alloc::Allocator,
1394 +
    p: &mut Printer,
1395 +
    node: *ast::Node,
1396 +
    args: *[*ast::Node]
1397 +
) -> *layout::Layout throws (alloc::AllocError) {
1398 +
    let used = p.used;
1399 +
    let forced = marked(p, node, ast::BrokenSite::List);
1400 +
    let list = try plainList(a, p, parens(node), args, Ctx::Normal, expr);
1401 +
    // Comments in the list break it, and items that the source put one per
1402 +
    // line leave nothing to hug.
1403 +
    if args.len == 0
1404 +
        or p.used <> used
1405 +
        or marked(p, node, ast::BrokenSite::Items)
1406 +
    {
1407 +
        return try forceBroken(a, list, forced);
1408 +
    }
1409 +
    let last = args[args.len - 1];
1410 +
    let call = hasArgs(last);
1411 +
    if not call
1412 +
        and not endsDelimited(last)
1413 +
        and not (args.len == 1 and closesItself(last))
1414 +
    {
1415 +
        return try forceBroken(a, list, forced);
1416 +
    }
1417 +
    // A list is broken when an item has a broken part.
1418 +
    let case layout::Item::Box(kids) = unbroken(list).item else {
1419 +
        panic "callArgs: list is not a box";
1420 +
    };
1421 +
    let case layout::Item::Box(items) = unbroken(kids[1].layout).item else {
1422 +
        panic "callArgs: list items are not a box";
1423 +
    };
1424 +
    let mut tail = items[items.len - 1];
1425 +
    if call {
1426 +
        set tail.layout = try openedCall(a, tail.layout);
1427 +
    } else {
1428 +
        set tail.layout = try broken(a, tail.layout);
1429 +
    }
1430 +
    let mut hug: *mut [layout::Child] = &mut [];
1431 +
    for i in 0..items.len - 1 {
1432 +
        try hug.append(items[i], a);
1433 +
    }
1434 +
    try hug.append(tail, a);
1435 +
    let opened = try row(a, &[kids[0].layout, try flatGroup(a, nil, hug), kids[2].layout]);
1436 +
1437 +
    if forced {
1438 +
        return try choice(a, nil, &[opened, try broken(a, list)]);
1439 +
    }
1440 +
    return try choice(a, nil, &[list, opened, list]);
1441 +
}
1442 +
1443 +
/// The box that a broken layout wraps, or the layout itself.
1444 +
fn unbroken(l: *layout::Layout) -> *layout::Layout {
1445 +
    if let case layout::Item::Broken(inner) = l.item {
1446 +
        return inner;
1447 +
    }
1448 +
    return l;
1449 +
}
1450 +
1451 +
/// Whether an expression is a call with arguments.
1452 +
fn hasArgs(node: *ast::Node) -> bool {
1453 +
    match node.value {
1454 +
        case ast::NodeValue::Call(call)               => return call.args.len > 0,
1455 +
        case ast::NodeValue::BuiltinCall { args, .. } => return args.len > 0,
1456 +
        else                                          => return false,
1457 +
    }
1458 +
}
1459 +
1460 +
/// Whether a layout has a broken part, in the form that a renderer measures:
1461 +
/// the first alternative of a choice.
1462 +
fn hasBroken(l: *layout::Layout) -> bool {
1463 +
    match l.item {
1464 +
        case layout::Item::Broken(_) => return true,
1465 +
        case layout::Item::Box(children) => {
1466 +
            for child in children {
1467 +
                if hasBroken(child.layout) {
1468 +
                    return true;
1469 +
                }
1470 +
            }
1471 +
            return false;
1472 +
        }
1473 +
        case layout::Item::Choice(alts) => return hasBroken(alts[0]),
1474 +
        else                            => return false,
1475 +
    }
1476 +
}
1477 +
1478 +
/// Layout of the call `l`, a call with arguments that is the last argument of
1479 +
/// another call, broken after its opening parenthesis.
1480 +
///
1481 +
/// Its arguments go on one indented line if they fit there. Otherwise they
1482 +
/// hug a last record or call as the call alone would, and when that line does
1483 +
/// not fit either, they go one per line.
1484 +
fn openedCall(
1485 +
    a: &mut opaque alloc::Allocator, l: *layout::Layout
1486 +
) -> *layout::Layout throws (alloc::AllocError) {
1487 +
    let case layout::Item::Box(parts) = unbroken(l).item else {
1488 +
        panic "openedCall: call is not a box";
1489 +
    };
1490 +
    // The arguments are a list, alone or broken, or a choice between the list
1491 +
    // with its hugged form before it. The list is the last alternative.
1492 +
    let args = parts[parts.len - 1].layout;
1493 +
    let mut flat = args;
1494 +
    let mut hug: ?*layout::Layout = nil;
1495 +
    if let case layout::Item::Choice(choices) = args.item {
1496 +
        set flat = choices[choices.len - 1];
1497 +
        set hug = choices[choices.len - 2];
1498 +
    }
1499 +
    let case layout::Item::Box(list) = unbroken(flat).item else {
1500 +
        panic "openedCall: arguments are not a box";
1501 +
    };
1502 +
    // The closing parenthesis follows the arguments, on their line when they
1503 +
    // hug, and on its own line otherwise.
1504 +
    let mut lines: *mut [layout::Child] = &mut [];
1505 +
    try add(a, &mut lines, layout::Placement::Indent, list[1].layout);
1506 +
    try add(a, &mut lines, layout::Placement::Line, list[2].layout);
1507 +
    let stacked = try flatGroup(a, nil, lines);
1508 +
    let mut rest = stacked;
1509 +
    if let alt = hug {
1510 +
        let case layout::Item::Box(opened) = alt.item else {
1511 +
            panic "openedCall: hugged arguments are not a box";
1512 +
        };
1513 +
        let hugged = try row(a, &[opened[1].layout, opened[2].layout]);
1514 +
        // Arguments with a broken part do not fit on one line.
1515 +
        if hasBroken(list[1].layout) {
1516 +
            set rest = try choice(a, nil, &[hugged, stacked]);
1517 +
        } else {
1518 +
            set rest = try choice(a, nil, &[stacked, hugged, stacked]);
1519 +
        }
1520 +
    }
1521 +
    let mut copy: *mut [layout::Child] = &mut [];
1522 +
    for i in 0..parts.len - 1 {
1523 +
        try copy.append(parts[i], a);
1524 +
    }
1525 +
    let open = try row(a, &[list[0].layout, rest]);
1526 +
    try add(a, &mut copy, parts[parts.len - 1].placement, open);
1527 +
1528 +
    return try broken(a, try flatGroup(a, l.source, copy));
1529 +
}
1530 +
1531 +
/// Format a field of a record literal: `name: value`, or `name` when the
1532 +
/// value is the name itself.
1533 +
fn recordLitField(
1534 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node, ctx: Ctx
1535 +
) -> *layout::Layout throws (alloc::AllocError) {
1536 +
    let case ast::NodeValue::RecordLitField(arg) = node.value else {
1537 +
        panic "recordLitField: not a record literal field";
1538 +
    };
1539 +
    let label = arg.label else {
1540 +
        panic "recordLitField: field has no label";
1541 +
    };
1542 +
    if arg.value == label {
1543 +
        return try expr(a, p, label, Ctx::Normal);
1544 +
    }
1545 +
    let mut kids: *mut [layout::Child] = &mut [];
1546 +
    try put(a, p, &mut kids, NONE, label, Ctx::Normal);
1547 +
    try punct(a, &mut kids, NONE, ":");
1548 +
    try put(a, p, &mut kids, SPACE, arg.value, ctx);
1549 +
1550 +
    return try group(a, node, kids);
1551 +
}
1552 +
1553 +
// Types //////////////////////////////////////////////////////////////////////
1554 +
1555 +
/// Prefix of a pointer-like type: its ownership class and mutability.
1556 +
fn pointerPrefix(class: types::PointerClass, mutable: bool) -> *[u8] {
1557 +
    match class {
1558 +
        case types::PointerClass::Owned => return "*mut " if mutable else "*",
1559 +
        case types::PointerClass::Ref   => return "&mut " if mutable else "&",
1560 +
        case types::PointerClass::Unsafe =>
1561 +
            return "*unsafe mut " if mutable else "*unsafe ",
1562 +
    }
1563 +
}
1564 +
1565 +
/// Format the result of a function type: `-> T` and `throws (E)`.
1566 +
fn signatureTail(
1567 +
    a: &mut opaque alloc::Allocator,
1568 +
    p: &mut Printer,
1569 +
    kids: &mut *mut [layout::Child],
1570 +
    sig: ast::FnSig,
1571 +
    forced: bool
1572 +
) throws (alloc::AllocError) {
1573 +
    if let returnType = sig.returnType {
1574 +
        try operator(a, kids, SPACE, "->");
1575 +
        try put(a, p, kids, SPACE, returnType, Ctx::Normal);
1576 +
    }
1577 +
    if sig.throwList.len > 0 {
1578 +
        let mut clause: *mut [layout::Child] = &mut [];
1579 +
        let mut spec = parens(nil);
1580 +
        set spec.forced = forced;
1581 +
        try keyword(a, &mut clause, NONE, "throws");
1582 +
        try add(
1583 +
            a,
1584 +
            &mut clause,
1585 +
            SPACE,
1586 +
            try softList(a, p, spec, sig.throwList, Ctx::Normal, expr)
1587 +
        );
1588 +
        try add(a, kids, SOFT_INDENT_SPACE, try group(a, nil, clause));
1589 +
    }
1590 +
}
1591 +
1592 +
/// Format a type signature node.
1593 +
fn typeSig(
1594 +
    a: &mut opaque alloc::Allocator,
1595 +
    p: &mut Printer,
1596 +
    node: *ast::Node,
1597 +
    sig: ast::TypeSig
1598 +
) -> *layout::Layout throws (alloc::AllocError) {
1599 +
    let mut kids: *mut [layout::Child] = &mut [];
1600 +
    match sig {
1601 +
        case ast::TypeSig::Void => panic "typeSig: void has no source form",
1602 +
        case ast::TypeSig::Never =>
1603 +
            return try leaf(a, node, "!", layout::Role::Keyword),
1604 +
        case ast::TypeSig::Opaque =>
1605 +
            return try leaf(a, node, "opaque", layout::Role::Keyword),
1606 +
        case ast::TypeSig::Bool =>
1607 +
            return try leaf(a, node, "bool", layout::Role::Keyword),
1608 +
        case ast::TypeSig::Integer { width, sign } =>
1609 +
            return try leaf(
1610 +
                a, node, ast::integerName(width, sign), layout::Role::Keyword
1611 +
            ),
1612 +
        case ast::TypeSig::Array { itemType, length } => {
1613 +
            try punct(a, &mut kids, NONE, "[");
1614 +
            try put(a, p, &mut kids, NONE, itemType, Ctx::Normal);
1615 +
            try punct(a, &mut kids, NONE, ";");
1616 +
            try put(a, p, &mut kids, SPACE, length, Ctx::Normal);
1617 +
            try punct(a, &mut kids, NONE, "]");
1618 +
        }
1619 +
        case ast::TypeSig::Slice { class, itemType, mutable } => {
1620 +
            try operator(a, &mut kids, NONE, pointerPrefix(class, mutable));
1621 +
            try punct(a, &mut kids, NONE, "[");
1622 +
            try put(a, p, &mut kids, NONE, itemType, Ctx::Normal);
1623 +
            try punct(a, &mut kids, NONE, "]");
1624 +
        }
1625 +
        case ast::TypeSig::Pointer { class, valueType, mutable } => {
1626 +
            try operator(a, &mut kids, NONE, pointerPrefix(class, mutable));
1627 +
            try put(a, p, &mut kids, NONE, valueType, Ctx::Normal);
1628 +
        }
1629 +
        case ast::TypeSig::Optional { valueType } => {
1630 +
            try operator(a, &mut kids, NONE, "?");
1631 +
            try put(a, p, &mut kids, NONE, valueType, Ctx::Normal);
1632 +
        }
1633 +
        case ast::TypeSig::Nominal(path) =>
1634 +
            return try expr(a, p, path, Ctx::Normal),
1635 +
        case ast::TypeSig::Record { .. } =>
1636 +
            panic "typeSig: record type outside a variant",
1637 +
        case ast::TypeSig::Fn { sig: fnSig, isUnsafe } => {
1638 +
            if isUnsafe {
1639 +
                try keyword(a, &mut kids, NONE, "unsafe");
1640 +
            }
1641 +
            try keyword(a, &mut kids, NONE if not isUnsafe else SPACE, "fn");
1642 +
            try add(
1643 +
                a,
1644 +
                &mut kids,
1645 +
                NONE,
1646 +
                try softList(
1647 +
                    a, p, parens(node), fnSig.params, Ctx::Normal, expr
1648 +
                )
1649 +
            );
1650 +
            let thrown = marked(p, node, ast::BrokenSite::Throws);
1651 +
            try signatureTail(a, p, &mut kids, fnSig, thrown);
1652 +
        }
1653 +
        case ast::TypeSig::TraitObject { class, traitName, mutable } => {
1654 +
            try operator(a, &mut kids, NONE, pointerPrefix(class, mutable));
1655 +
            try keyword(a, &mut kids, NONE, "opaque");
1656 +
            try put(a, p, &mut kids, SPACE, traitName, Ctx::Normal);
1657 +
        }
1658 +
    }
1659 +
    return try group(a, node, kids);
1660 +
}
1661 +
1662 +
// Statements /////////////////////////////////////////////////////////////////
1663 +
1664 +
/// Append a text child after a space, or first in the box.
1665 +
fn spaced(
1666 +
    a: &mut opaque alloc::Allocator,
1667 +
    kids: &mut *mut [layout::Child],
1668 +
    text: *[u8],
1669 +
    role: layout::Role
1670 +
) throws (alloc::AllocError) {
1671 +
    let at = NONE if kids.len == 0 else SPACE;
1672 +
    try word(a, kids, at, text, role);
1673 +
}
1674 +
1675 +
/// Append the attributes of a declaration, in source order.
1676 +
fn attributes(
1677 +
    a: &mut opaque alloc::Allocator,
1678 +
    kids: &mut *mut [layout::Child],
1679 +
    attrs: ?ast::Attributes
1680 +
) throws (alloc::AllocError) {
1681 +
    let list = attrs else {
1682 +
        return;
1683 +
    };
1684 +
    for attr in list.list {
1685 +
        let case ast::NodeValue::Attribute(kind) = attr.value else {
1686 +
            panic "attributes: attribute expected";
1687 +
        };
1688 +
        match kind {
1689 +
            case ast::Attribute::Export =>
1690 +
                try spaced(a, kids, "export", layout::Role::Keyword),
1691 +
            case ast::Attribute::Unsafe =>
1692 +
                try spaced(a, kids, "unsafe", layout::Role::Keyword),
1693 +
            case ast::Attribute::Opaque =>
1694 +
                try spaced(a, kids, "opaque", layout::Role::Keyword),
1695 +
            case ast::Attribute::Default =>
1696 +
                try spaced(a, kids, "@default", layout::Role::Keyword),
1697 +
            case ast::Attribute::Test =>
1698 +
                try spaced(a, kids, "@test", layout::Role::Keyword),
1699 +
            case ast::Attribute::Intrinsic =>
1700 +
                try spaced(a, kids, "@intrinsic", layout::Role::Keyword),
1701 +
            case ast::Attribute::Extern => {}
1702 +
        }
1703 +
    }
1704 +
}
1705 +
1706 +
/// Whether a braced body has no items and no comments.
1707 +
fn isEmpty(p: &Printer, count: u32, container: *ast::Node) -> bool {
1708 +
    if count > 0 {
1709 +
        return false;
1710 +
    }
1711 +
    for t in entries(p, container, ast::TriviaPlacement::Closing) {
1712 +
        if let case ast::TriviaKind::Comment(_) = t.kind {
1713 +
            return false;
1714 +
        }
1715 +
    }
1716 +
    return true;
1717 +
}
1718 +
1719 +
/// Text of the opening brace of a body. An empty body is `{}`.
1720 +
fn brace(p: &Printer, count: u32, container: *ast::Node) -> *[u8] {
1721 +
    return "{}" if isEmpty(p, count, container) else "{";
1722 +
}
1723 +
1724 +
/// Append the items of a braced body, one per line, and the closing brace.
1725 +
fn body(
1726 +
    a: &mut opaque alloc::Allocator,
1727 +
    p: &mut Printer,
1728 +
    kids: &mut *mut [layout::Child],
1729 +
    items: *[*ast::Node],
1730 +
    container: *ast::Node,
1731 +
    format: fn(
1732 +
        &mut opaque alloc::Allocator, &mut Printer, *ast::Node
1733 +
    ) -> *layout::Layout
1734 +
        throws (alloc::AllocError)
1735 +
) throws (alloc::AllocError) {
1736 +
    try lines(a, p, kids, items, container, layout::Placement::Indent, format);
1737 +
    if not isEmpty(p, items.len, container) {
1738 +
        try punct(a, kids, layout::Placement::Line, "}");
1739 +
    }
1740 +
}
1741 +
1742 +
/// Append the braced statements of a block, with the brace placed at `at`.
1743 +
fn blockBody(
1744 +
    a: &mut opaque alloc::Allocator,
1745 +
    p: &mut Printer,
1746 +
    kids: &mut *mut [layout::Child],
1747 +
    blk: *ast::Node,
1748 +
    at: layout::Placement
1749 +
) throws (alloc::AllocError) {
1750 +
    let case ast::NodeValue::Block(b) = blk.value else {
1751 +
        panic "blockBody: block expected";
1752 +
    };
1753 +
    try punct(a, kids, at, brace(p, b.statements.len, blk));
1754 +
    try body(a, p, kids, b.statements, blk, stmt);
1755 +
}
1756 +
1757 +
/// Format a statement, with its `;` when it needs one.
1758 +
fn stmt(
1759 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
1760 +
) -> *layout::Layout throws (alloc::AllocError) {
1761 +
    let core = try stmtCore(a, p, node);
1762 +
    if not ast::needsSemicolon(node) {
1763 +
        return core;
1764 +
    }
1765 +
    let mut kids: *mut [layout::Child] = &mut [];
1766 +
    try add(a, &mut kids, NONE, core);
1767 +
    try punct(a, &mut kids, NONE, ";");
1768 +
1769 +
    return try group(a, node, kids);
1770 +
}
1771 +
1772 +
/// Format a statement without its `;`. Expressions format as themselves.
1773 +
fn stmtCore(
1774 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
1775 +
) -> *layout::Layout throws (alloc::AllocError) {
1776 +
    let mut kids: *mut [layout::Child] = &mut [];
1777 +
    match node.value {
1778 +
        case ast::NodeValue::ExprStmt(e) =>
1779 +
            return try expr(a, p, e, Ctx::Normal),
1780 +
        case ast::NodeValue::Let(l) => {
1781 +
            try spaced(a, &mut kids, "let", layout::Role::Keyword);
1782 +
            if l.mutable {
1783 +
                try spaced(a, &mut kids, "mut", layout::Role::Keyword);
1784 +
            }
1785 +
            try put(a, p, &mut kids, SPACE, l.ident, Ctx::Normal);
1786 +
            if let type = l.type {
1787 +
                try punct(a, &mut kids, NONE, ":");
1788 +
                try put(a, p, &mut kids, SPACE, type, Ctx::Normal);
1789 +
            }
1790 +
            if let alignment = l.alignment {
1791 +
                try put(a, p, &mut kids, SPACE, alignment, Ctx::Normal);
1792 +
            }
1793 +
            try assigned(a, p, &mut kids, node, "=", l.value);
1794 +
        }
1795 +
        case ast::NodeValue::LetElse(l) => {
1796 +
            let mut head: *mut [layout::Child] = &mut [];
1797 +
            try patternMatch(a, p, &mut head, l.pattern, GuardStyle::If);
1798 +
            try add(a, &mut kids, NONE, try group(a, nil, head));
1799 +
            if let case ast::NodeValue::Block(b) = l.elseBranch.value; not b.isUnsafe {
1800 +
                try keyword(a, &mut kids, SPACE, "else");
1801 +
                try blockBody(a, p, &mut kids, l.elseBranch, SPACE);
1802 +
            } else {
1803 +
                // A statement branch follows the value when it fits, and
1804 +
                // moves to its own line with `else` otherwise. The pattern
1805 +
                // stays whole when it fits.
1806 +
                let mut other: *mut [layout::Child] = &mut [];
1807 +
                try keyword(a, &mut other, NONE, "else");
1808 +
                try add(a, &mut other, SPACE, try stmtCore(a, p, l.elseBranch));
1809 +
                let branch = try group(a, nil, other);
1810 +
                try add(a, &mut kids, NONE, try sameOrNext(a, branch));
1811 +
            }
1812 +
        }
1813 +
        case ast::NodeValue::Assign(asg) => {
1814 +
            try spaced(a, &mut kids, "set", layout::Role::Keyword);
1815 +
            try put(a, p, &mut kids, SPACE, asg.left, Ctx::Normal);
1816 +
            let mut op: *[u8] = "=";
1817 +
            let mut value = asg.right;
1818 +
            if let case ast::NodeValue::BinOp(bin) = asg.right.value; bin.left == asg.left {
1819 +
                if let text = compoundText(bin.op) {
1820 +
                    set op = text;
1821 +
                    set value = bin.right;
1822 +
                }
1823 +
            }
1824 +
            try assigned(a, p, &mut kids, node, op, value);
1825 +
        }
1826 +
        case ast::NodeValue::Return { value } => {
1827 +
            try spaced(a, &mut kids, "return", layout::Role::Keyword);
1828 +
            if let v = value {
1829 +
                try put(a, p, &mut kids, SPACE, v, Ctx::Normal);
1830 +
            }
1831 +
        }
1832 +
        case ast::NodeValue::Throw { expr: thrown } => {
1833 +
            try spaced(a, &mut kids, "throw", layout::Role::Keyword);
1834 +
            try put(a, p, &mut kids, SPACE, thrown, Ctx::Normal);
1835 +
        }
1836 +
        case ast::NodeValue::Panic { message } => {
1837 +
            try spaced(a, &mut kids, "panic", layout::Role::Keyword);
1838 +
            if let m = message {
1839 +
                try put(a, p, &mut kids, SPACE, m, Ctx::Normal);
1840 +
            }
1841 +
        }
1842 +
        case ast::NodeValue::Assert { condition, message } => {
1843 +
            try spaced(a, &mut kids, "assert", layout::Role::Keyword);
1844 +
            try put(a, p, &mut kids, SPACE, condition, Ctx::Normal);
1845 +
            if let m = message {
1846 +
                try punct(a, &mut kids, NONE, ",");
1847 +
                try put(a, p, &mut kids, SOFT_INDENT_SPACE, m, Ctx::Normal);
1848 +
            }
1849 +
        }
1850 +
        case ast::NodeValue::Break =>
1851 +
            return try leaf(a, node, "break", layout::Role::Keyword),
1852 +
        case ast::NodeValue::Continue =>
1853 +
            return try leaf(a, node, "continue", layout::Role::Keyword),
1854 +
        case ast::NodeValue::ConstDecl(c) => {
1855 +
            try attributes(a, &mut kids, c.attrs);
1856 +
            try storage(
1857 +
                a, p, &mut kids, node, "constant", c.ident, c.type, c.value
1858 +
            );
1859 +
        }
1860 +
        case ast::NodeValue::StaticDecl(d) => {
1861 +
            try attributes(a, &mut kids, d.attrs);
1862 +
            try storage(
1863 +
                a, p, &mut kids, node, "static", d.ident, d.type, d.value
1864 +
            );
1865 +
        }
1866 +
        case ast::NodeValue::Mod(m) => {
1867 +
            try attributes(a, &mut kids, m.attrs);
1868 +
            try spaced(a, &mut kids, "mod", layout::Role::Keyword);
1869 +
            try put(a, p, &mut kids, SPACE, m.name, Ctx::Normal);
1870 +
        }
1871 +
        case ast::NodeValue::Use(u) => {
1872 +
            try attributes(a, &mut kids, u.attrs);
1873 +
            try spaced(a, &mut kids, "use", layout::Role::Keyword);
1874 +
            try put(a, p, &mut kids, SPACE, u.path, Ctx::Normal);
1875 +
            if u.wildcard {
1876 +
                try punct(a, &mut kids, NONE, "::*");
1877 +
            }
1878 +
        }
1879 +
        case ast::NodeValue::Block(b) => {
1880 +
            if b.isUnsafe {
1881 +
                try spaced(a, &mut kids, "unsafe", layout::Role::Keyword);
1882 +
                try blockBody(a, p, &mut kids, node, SPACE);
1883 +
            } else {
1884 +
                try blockBody(a, p, &mut kids, node, NONE);
1885 +
            }
1886 +
        }
1887 +
        case ast::NodeValue::If(_), ast::NodeValue::IfLet(_) =>
1888 +
            return try ifStmt(a, p, node),
1889 +
        case ast::NodeValue::While(_),
1890 +
            ast::NodeValue::WhileLet(_),
1891 +
            ast::NodeValue::For(_),
1892 +
            ast::NodeValue::Loop { .. } =>
1893 +
            return try loopStmt(a, p, node),
1894 +
        case ast::NodeValue::Match(m) => {
1895 +
            let mut head: *mut [layout::Child] = &mut [];
1896 +
            try spaced(a, &mut head, "match", layout::Role::Keyword);
1897 +
            try put(a, p, &mut head, SPACE, m.subject, Ctx::Condition);
1898 +
            try punct(
1899 +
                a,
1900 +
                &mut head,
1901 +
                bracePlacement(m.subject),
1902 +
                brace(p, m.prongs.len, node)
1903 +
            );
1904 +
            try add(a, &mut kids, NONE, try group(a, nil, head));
1905 +
            try body(a, p, &mut kids, m.prongs, node, prong);
1906 +
        }
1907 +
        case ast::NodeValue::FnDecl(_),
1908 +
            ast::NodeValue::MethodDecl { .. },
1909 +
            ast::NodeValue::TraitMethodSig { .. } =>
1910 +
            return try fnDecl(a, p, node),
1911 +
        case ast::NodeValue::RecordDecl(_),
1912 +
            ast::NodeValue::UnionDecl(_),
1913 +
            ast::NodeValue::TraitDecl { .. },
1914 +
            ast::NodeValue::InstanceDecl { .. } =>
1915 +
            return try typeDecl(a, p, node),
1916 +
        else => return try expr(a, p, node, Ctx::Normal),
1917 +
    }
1918 +
    return try group(a, node, kids);
1919 +
}
1920 +
1921 +
/// Append an assignment operator and its value, for the statement `owner`.
1922 +
///
1923 +
/// A value that the source put on a line of its own after the operator stays
1924 +
/// there. A value that opens a list stays on the line of the operator unless
1925 +
/// even its first line does not fit there. An operation moves to the next line
1926 +
/// when it fits there flat, and otherwise stays on the line of the operator
1927 +
/// when its first line fits. Other values, such as long strings and names,
1928 +
/// move to the next line when they do not fit.
1929 +
fn assigned(
1930 +
    a: &mut opaque alloc::Allocator,
1931 +
    p: &mut Printer,
1932 +
    kids: &mut *mut [layout::Child],
1933 +
    owner: *ast::Node,
1934 +
    op: *[u8],
1935 +
    value: *ast::Node
1936 +
) throws (alloc::AllocError) {
1937 +
    try operator(a, kids, SPACE, op);
1938 +
    if takeMark(p, owner, ast::BrokenSite::Value) {
1939 +
        try put(a, p, kids, layout::Placement::Indent, value, Ctx::Normal);
1940 +
        return;
1941 +
    }
1942 +
    let operation = isOperation(value);
1943 +
    if not operation and not closesItself(value) and not endsDelimited(value) {
1944 +
        try put(a, p, kids, valuePlacement(value), value, Ctx::Normal);
1945 +
        return;
1946 +
    }
1947 +
    let v = try expr(a, p, value, Ctx::Normal);
1948 +
    let same = try placed(a, SPACE, v);
1949 +
    let opened = try placed(a, SPACE, try broken(a, v));
1950 +
    let next = try placed(a, layout::Placement::Indent, v);
1951 +
    let mut values = try choice(a, value, &[same, opened, next]);
1952 +
    if operation {
1953 +
        set values = try choice(a, value, &[same, next, opened, next]);
1954 +
    }
1955 +
    try add(a, kids, NONE, values);
1956 +
}
1957 +
1958 +
/// Whether an expression is a binary or conditional operation.
1959 +
fn isOperation(node: *ast::Node) -> bool {
1960 +
    match node.value {
1961 +
        case ast::NodeValue::BinOp(_), ast::NodeValue::CondExpr(_) =>
1962 +
            return true,
1963 +
        else => return false,
1964 +
    }
1965 +
}
1966 +
1967 +
/// Append the name, type, and value of a `constant` or `static` declaration.
1968 +
fn storage(
1969 +
    a: &mut opaque alloc::Allocator,
1970 +
    p: &mut Printer,
1971 +
    kids: &mut *mut [layout::Child],
1972 +
    owner: *ast::Node,
1973 +
    word: *[u8],
1974 +
    ident: *ast::Node,
1975 +
    type: *ast::Node,
1976 +
    value: *ast::Node
1977 +
) throws (alloc::AllocError) {
1978 +
    try spaced(a, kids, word, layout::Role::Keyword);
1979 +
    try put(a, p, kids, SPACE, ident, Ctx::Normal);
1980 +
    try punct(a, kids, NONE, ":");
1981 +
    try put(a, p, kids, SPACE, type, Ctx::Normal);
1982 +
    try assigned(a, p, kids, owner, "=", value);
1983 +
}
1984 +
1985 +
/// Whether an expression breaks at its own delimiters, so that what follows it
1986 +
/// stays after its closing delimiter.
1987 +
fn closesItself(node: *ast::Node) -> bool {
1988 +
    match node.value {
1989 +
        case ast::NodeValue::Call(_),
1990 +
            ast::NodeValue::BuiltinCall { .. },
1991 +
            ast::NodeValue::ArrayLit(_) =>
1992 +
            return true,
1993 +
        case ast::NodeValue::UnOp(un) => return closesItself(un.value),
1994 +
        case ast::NodeValue::AddressOf(addr) =>
1995 +
            return closesItself(addr.target),
1996 +
        case ast::NodeValue::Deref(target) => return closesItself(target),
1997 +
        case ast::NodeValue::Try(t) =>
1998 +
            return t.catches.len == 0 and closesItself(t.expr),
1999 +
        else => return false,
2000 +
    }
2001 +
}
2002 +
2003 +
/// Whether an expression ends with a record or array literal.
2004 +
fn endsDelimited(node: *ast::Node) -> bool {
2005 +
    match node.value {
2006 +
        case ast::NodeValue::RecordLit(_), ast::NodeValue::ArrayLit(_) =>
2007 +
            return true,
2008 +
        case ast::NodeValue::AddressOf(addr) =>
2009 +
            return endsDelimited(addr.target),
2010 +
        else => return false,
2011 +
    }
2012 +
}
2013 +
2014 +
/// Placement of the value after `=`.
2015 +
fn valuePlacement(value: *ast::Node) -> layout::Placement {
2016 +
    if closesItself(value) {
2017 +
        return SPACE;
2018 +
    }
2019 +
    match value.value {
2020 +
        case ast::NodeValue::RecordLit(_),
2021 +
            ast::NodeValue::BinOp(_),
2022 +
            ast::NodeValue::CondExpr(_),
2023 +
            ast::NodeValue::Try(_) =>
2024 +
            return SPACE,
2025 +
        else => return SOFT_INDENT_SPACE,
2026 +
    }
2027 +
}
2028 +
2029 +
/// Placement of the brace after a header that ends with `last`.
2030 +
///
2031 +
/// A call or array literal breaks at its own delimiters, so the brace follows
2032 +
/// its closing delimiter. After other expressions, the brace moves to its own
2033 +
/// line when the header breaks.
2034 +
fn bracePlacement(last: *ast::Node) -> layout::Placement {
2035 +
    if closesItself(last) {
2036 +
        return SPACE;
2037 +
    }
2038 +
    return SOFT_SPACE;
2039 +
}
2040 +
2041 +
/// Placement of the brace after the pattern match of a header. A guard breaks
2042 +
/// the header before it, so the brace then goes on its own line.
2043 +
fn patternBrace(pm: ast::PatternMatch) -> layout::Placement {
2044 +
    if pm.guard <> nil {
2045 +
        return SOFT_SPACE;
2046 +
    }
2047 +
    return bracePlacement(pm.scrutinee);
2048 +
}
2049 +
2050 +
/// Append `let`, a pattern, `=`, and a value, as in `if let` and `let-else`.
2051 +
fn patternMatch(
2052 +
    a: &mut opaque alloc::Allocator,
2053 +
    p: &mut Printer,
2054 +
    kids: &mut *mut [layout::Child],
2055 +
    pm: ast::PatternMatch,
2056 +
    style: GuardStyle
2057 +
) throws (alloc::AllocError) {
2058 +
    try spaced(a, kids, "let", layout::Role::Keyword);
2059 +
    let mut ctx = Ctx::Condition;
2060 +
    match pm.kind {
2061 +
        case ast::PatternKind::Case => {
2062 +
            try keyword(a, kids, SPACE, "case");
2063 +
            try put(a, p, kids, SPACE, pm.pattern, Ctx::Pattern);
2064 +
        }
2065 +
        case ast::PatternKind::Binding => {
2066 +
            if pm.mutable {
2067 +
                try keyword(a, kids, SPACE, "mut");
2068 +
            }
2069 +
            try put(a, p, kids, SPACE, pm.pattern, Ctx::Normal);
2070 +
            if style == GuardStyle::If {
2071 +
                set ctx = Ctx::Normal;
2072 +
            }
2073 +
        }
2074 +
    }
2075 +
    try operator(a, kids, SPACE, "=");
2076 +
    try put(a, p, kids, valuePlacement(pm.scrutinee), pm.scrutinee, ctx);
2077 +
    if let guard = pm.guard {
2078 +
        match style {
2079 +
            case GuardStyle::Semicolon => {
2080 +
                try punct(a, kids, NONE, ";");
2081 +
                try put(a, p, kids, SOFT_INDENT_SPACE, guard, Ctx::Condition);
2082 +
            }
2083 +
            case GuardStyle::If => {
2084 +
                let mut test: *mut [layout::Child] = &mut [];
2085 +
                try keyword(a, &mut test, NONE, "if");
2086 +
                try put(a, p, &mut test, SPACE, guard, Ctx::Condition);
2087 +
                try add(a, kids, SOFT_INDENT_SPACE, try group(a, nil, test));
2088 +
            }
2089 +
        }
2090 +
    }
2091 +
}
2092 +
2093 +
/// The nested `if` of an `else if`, if `blk` is the else branch of one.
2094 +
///
2095 +
/// The parser makes `else if` a block that holds the nested `if`. A block that
2096 +
/// has the same shape, but trivia of its own, is not an `else if`.
2097 +
fn elseIf(p: &Printer, blk: *ast::Node) -> ?*ast::Node {
2098 +
    let case ast::NodeValue::Block(b) = blk.value else {
2099 +
        return nil;
2100 +
    };
2101 +
    if b.isUnsafe or b.statements.len <> 1 {
2102 +
        return nil;
2103 +
    }
2104 +
    let inner = b.statements[0];
2105 +
    if entries(p, blk, ast::TriviaPlacement::Closing).len > 0
2106 +
        or entries(p, inner, ast::TriviaPlacement::Leading).len > 0
2107 +
        or entries(p, inner, ast::TriviaPlacement::Trailing).len > 0
2108 +
    {
2109 +
        return nil;
2110 +
    }
2111 +
    match inner.value {
2112 +
        case ast::NodeValue::If(_), ast::NodeValue::IfLet(_) => return inner,
2113 +
        else                                                 => return nil,
2114 +
    }
2115 +
}
2116 +
2117 +
/// Format an `if` or `if let` statement with its `else` branches.
2118 +
fn ifStmt(
2119 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
2120 +
) -> *layout::Layout throws (alloc::AllocError) {
2121 +
    let mut kids: *mut [layout::Child] = &mut [];
2122 +
    let mut current = node;
2123 +
    let mut chained = false;
2124 +
    loop {
2125 +
        let mut head: *mut [layout::Child] = &mut [];
2126 +
        let mut thenBranch: *ast::Node = undefined;
2127 +
        let mut elseBranch: ?*ast::Node = nil;
2128 +
        let mut at = SOFT_SPACE;
2129 +
        if chained {
2130 +
            try spaced(a, &mut head, "else", layout::Role::Keyword);
2131 +
        }
2132 +
        try spaced(a, &mut head, "if", layout::Role::Keyword);
2133 +
        match current.value {
2134 +
            case ast::NodeValue::If(i) => {
2135 +
                try put(a, p, &mut head, SPACE, i.condition, Ctx::Condition);
2136 +
                set at = bracePlacement(i.condition);
2137 +
                set thenBranch = i.thenBranch;
2138 +
                set elseBranch = i.elseBranch;
2139 +
            }
2140 +
            case ast::NodeValue::IfLet(i) => {
2141 +
                try patternMatch(
2142 +
                    a, p, &mut head, i.pattern, GuardStyle::Semicolon
2143 +
                );
2144 +
                set at = patternBrace(i.pattern);
2145 +
                set thenBranch = i.thenBranch;
2146 +
                set elseBranch = i.elseBranch;
2147 +
            }
2148 +
            else => panic "ifStmt: if expected",
2149 +
        }
2150 +
        let case ast::NodeValue::Block(b) = thenBranch.value else {
2151 +
            panic "ifStmt: block expected";
2152 +
        };
2153 +
        try punct(
2154 +
            a,
2155 +
            &mut head,
2156 +
            at,
2157 +
            brace(p, b.statements.len, thenBranch)
2158 +
        );
2159 +
        try add(
2160 +
            a,
2161 +
            &mut kids,
2162 +
            SPACE if chained else NONE,
2163 +
            try group(a, current, head)
2164 +
        );
2165 +
        try body(a, p, &mut kids, b.statements, thenBranch, stmt);
2166 +
2167 +
        let els = elseBranch else {
2168 +
            break;
2169 +
        };
2170 +
        if let nested = elseIf(p, els) {
2171 +
            set current = nested;
2172 +
            set chained = true;
2173 +
            continue;
2174 +
        }
2175 +
        try keyword(a, &mut kids, SPACE, "else");
2176 +
        try blockBody(a, p, &mut kids, els, SPACE);
2177 +
        break;
2178 +
    }
2179 +
    return try group(a, node, kids);
2180 +
}
2181 +
2182 +
/// Format a `while`, `while let`, `for`, or `loop` statement with its `else`
2183 +
/// branch.
2184 +
fn loopStmt(
2185 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
2186 +
) -> *layout::Layout throws (alloc::AllocError) {
2187 +
    let mut head: *mut [layout::Child] = &mut [];
2188 +
    let mut loopBody: *ast::Node = undefined;
2189 +
    let mut elseBranch: ?*ast::Node = nil;
2190 +
    let mut at = SOFT_SPACE;
2191 +
    match node.value {
2192 +
        case ast::NodeValue::While(w) => {
2193 +
            try spaced(a, &mut head, "while", layout::Role::Keyword);
2194 +
            try put(a, p, &mut head, SPACE, w.condition, Ctx::Condition);
2195 +
            set at = bracePlacement(w.condition);
2196 +
            set loopBody = w.body;
2197 +
            set elseBranch = w.elseBranch;
2198 +
        }
2199 +
        case ast::NodeValue::WhileLet(w) => {
2200 +
            try spaced(a, &mut head, "while", layout::Role::Keyword);
2201 +
            try patternMatch(a, p, &mut head, w.pattern, GuardStyle::Semicolon);
2202 +
            set at = patternBrace(w.pattern);
2203 +
            set loopBody = w.body;
2204 +
            set elseBranch = w.elseBranch;
2205 +
        }
2206 +
        case ast::NodeValue::For(f) => {
2207 +
            try spaced(a, &mut head, "for", layout::Role::Keyword);
2208 +
            try put(a, p, &mut head, SPACE, f.binding, Ctx::Normal);
2209 +
            if let index = f.index {
2210 +
                try punct(a, &mut head, NONE, ",");
2211 +
                try put(a, p, &mut head, SPACE, index, Ctx::Normal);
2212 +
            }
2213 +
            try keyword(a, &mut head, SPACE, "in");
2214 +
            try put(a, p, &mut head, SPACE, f.iterable, Ctx::Condition);
2215 +
            set at = bracePlacement(f.iterable);
2216 +
            set loopBody = f.body;
2217 +
            set elseBranch = f.elseBranch;
2218 +
        }
2219 +
        case ast::NodeValue::Loop { body: b } => {
2220 +
            try spaced(a, &mut head, "loop", layout::Role::Keyword);
2221 +
            set loopBody = b;
2222 +
        }
2223 +
        else => panic "loopStmt: loop expected",
2224 +
    }
2225 +
    let case ast::NodeValue::Block(b) = loopBody.value else {
2226 +
        panic "loopStmt: block expected";
2227 +
    };
2228 +
    try punct(
2229 +
        a,
2230 +
        &mut head,
2231 +
        at,
2232 +
        brace(p, b.statements.len, loopBody)
2233 +
    );
2234 +
    let mut kids: *mut [layout::Child] = &mut [];
2235 +
    try add(a, &mut kids, NONE, try group(a, nil, head));
2236 +
    try body(a, p, &mut kids, b.statements, loopBody, stmt);
2237 +
    if let els = elseBranch {
2238 +
        try keyword(a, &mut kids, SPACE, "else");
2239 +
        try blockBody(a, p, &mut kids, els, SPACE);
2240 +
    }
2241 +
    return try group(a, node, kids);
2242 +
}
2243 +
2244 +
/// Format a match prong.
2245 +
///
2246 +
/// A block body follows `=>` on the same line. Another statement body ends
2247 +
/// with a comma, and goes to the next line when it does not fit, unless it
2248 +
/// ends with a block of its own.
2249 +
///
2250 +
/// A prong with several patterns whose `case` line does not fit is stacked:
2251 +
/// `case` is alone on its line, each pattern follows on a line of its own one
2252 +
/// level deeper, and `=>` follows the last pattern. A guard stays on the line
2253 +
/// of the last pattern when it fits there, and goes on a line of its own at
2254 +
/// the depth of the patterns otherwise. A block body opens on a line of its
2255 +
/// own at the depth of `case`. Another body stays after `=>` when it fits
2256 +
/// there, and goes on the next line, one level deeper than `case`, otherwise.
2257 +
/// The guard counts toward the `case` line, so a long guard stacks the
2258 +
/// patterns too. A single pattern never stacks.
2259 +
fn prong(
2260 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
2261 +
) -> *layout::Layout throws (alloc::AllocError) {
2262 +
    let case ast::NodeValue::MatchProng(pr) = node.value else {
2263 +
        panic "prong: prong expected";
2264 +
    };
2265 +
    let mut pre: *mut [layout::Child] = &mut [];
2266 +
    let mut stacked = false;
2267 +
    match pr.arm {
2268 +
        case ast::ProngArm::Case(patterns) => {
2269 +
            set stacked = patterns.len > 1;
2270 +
            try keyword(a, &mut pre, NONE, "case");
2271 +
            if stacked {
2272 +
                for pattern, i in patterns {
2273 +
                    if i > 0 {
2274 +
                        try punct(a, &mut pre, NONE, ",");
2275 +
                    }
2276 +
                    try add(
2277 +
                        a,
2278 +
                        &mut pre,
2279 +
                        SOFT_INDENT_SPACE,
2280 +
                        try expr(a, p, pattern, Ctx::Pattern)
2281 +
                    );
2282 +
                }
2283 +
            } else {
2284 +
                try add(
2285 +
                    a,
2286 +
                    &mut pre,
2287 +
                    SPACE,
2288 +
                    try expr(a, p, patterns[0], Ctx::Pattern)
2289 +
                );
2290 +
            }
2291 +
        }
2292 +
        case ast::ProngArm::Binding(binding) =>
2293 +
            try add(a, &mut pre, NONE, try expr(a, p, binding, Ctx::Normal)),
2294 +
        case ast::ProngArm::Else => try keyword(a, &mut pre, NONE, "else"),
2295 +
    }
2296 +
    if let guard = pr.guard {
2297 +
        let mut test: *mut [layout::Child] = &mut [];
2298 +
        try keyword(a, &mut test, NONE, "if");
2299 +
        try put(a, p, &mut test, SPACE, guard, Ctx::Condition);
2300 +
        let cond = try group(a, nil, test);
2301 +
        if stacked {
2302 +
            try add(a, &mut pre, NONE, try sameOrNext(a, cond));
2303 +
        } else {
2304 +
            try add(a, &mut pre, SOFT_INDENT_SPACE, cond);
2305 +
        }
2306 +
    }
2307 +
    // The arrows line up after the pattern and guard. The patterns of a
2308 +
    // stacked prong share the box of the arrow, so that their line breaks and
2309 +
    // the line of the opening brace go together.
2310 +
    let mut head: *mut [layout::Child] = &mut [];
2311 +
    if stacked {
2312 +
        set head = pre;
2313 +
        try add(a, &mut head, NONE, try tab(a, COLUMN_ARROW));
2314 +
    } else {
2315 +
        try add(a, &mut head, NONE, try group(a, nil, pre));
2316 +
        try add(a, &mut head, NONE, try tab(a, COLUMN_ARROW));
2317 +
    }
2318 +
    try operator(a, &mut head, SPACE, "=>");
2319 +
    let moved = takeMark(p, node, ast::BrokenSite::Value);
2320 +
2321 +
    let mut kids: *mut [layout::Child] = &mut [];
2322 +
    if let case ast::NodeValue::Block(b) = pr.body.value; not b.isUnsafe {
2323 +
        if stacked {
2324 +
            try punct(
2325 +
                a, &mut head, SOFT_SPACE, brace(p, b.statements.len, pr.body)
2326 +
            );
2327 +
            try add(a, &mut kids, NONE, try group(a, nil, head));
2328 +
            try body(a, p, &mut kids, b.statements, pr.body, stmt);
2329 +
        } else {
2330 +
            try add(a, &mut kids, NONE, try group(a, nil, head));
2331 +
            try blockBody(a, p, &mut kids, pr.body, SPACE);
2332 +
        }
2333 +
    } else {
2334 +
        try add(a, &mut kids, NONE, try group(a, nil, head));
2335 +
        let core = try stmtCore(a, p, pr.body);
2336 +
        if moved {
2337 +
            try add(a, &mut kids, layout::Placement::Indent, core);
2338 +
        } else if stacked and ast::needsSemicolon(pr.body) {
2339 +
            try add(a, &mut kids, NONE, try sameOrNext(a, core));
2340 +
        } else if ast::needsSemicolon(pr.body) {
2341 +
            try add(a, &mut kids, SOFT_INDENT_SPACE, core);
2342 +
        } else {
2343 +
            try add(a, &mut kids, SPACE, core);
2344 +
        }
2345 +
        try punct(a, &mut kids, NONE, ",");
2346 +
    }
2347 +
    return try group(a, node, kids);
2348 +
}
2349 +
2350 +
// Declarations ///////////////////////////////////////////////////////////////
2351 +
2352 +
/// Format a function parameter: `name: type`.
2353 +
fn paramItem(
2354 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node, ctx: Ctx
2355 +
) -> *layout::Layout throws (alloc::AllocError) {
2356 +
    let case ast::NodeValue::FnParam(param) = node.value else {
2357 +
        panic "paramItem: parameter expected";
2358 +
    };
2359 +
    let mut kids: *mut [layout::Child] = &mut [];
2360 +
    try put(a, p, &mut kids, NONE, param.name, ctx);
2361 +
    try punct(a, &mut kids, NONE, ":");
2362 +
    try put(a, p, &mut kids, SPACE, param.type, ctx);
2363 +
2364 +
    return try group(a, node, kids);
2365 +
}
2366 +
2367 +
/// Format a function, method, or trait method signature, and the body of a
2368 +
/// function or method.
2369 +
fn fnDecl(
2370 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
2371 +
) -> *layout::Layout throws (alloc::AllocError) {
2372 +
    let mut head: *mut [layout::Child] = &mut [];
2373 +
    let mut fnBody: ?*ast::Node = nil;
2374 +
    let mut sig: ast::FnSig = undefined;
2375 +
    match node.value {
2376 +
        case ast::NodeValue::FnDecl(f) => {
2377 +
            try attributes(a, &mut head, f.attrs);
2378 +
            try spaced(a, &mut head, "fn", layout::Role::Keyword);
2379 +
            try put(a, p, &mut head, SPACE, f.name, Ctx::Normal);
2380 +
            set fnBody = f.body;
2381 +
            set sig = f.sig;
2382 +
        }
2383 +
        case ast::NodeValue::MethodDecl {
2384 +
            name, receiverName, receiverType, sig: s, body: b, attrs
2385 +
        } => {
2386 +
            let mut recv: *mut [layout::Child] = &mut [];
2387 +
            try punct(a, &mut recv, NONE, "(");
2388 +
            try put(a, p, &mut recv, NONE, receiverName, Ctx::Normal);
2389 +
            try punct(a, &mut recv, NONE, ":");
2390 +
            try put(a, p, &mut recv, SPACE, receiverType, Ctx::Normal);
2391 +
            try punct(a, &mut recv, NONE, ")");
2392 +
            try attributes(a, &mut head, attrs);
2393 +
            try spaced(a, &mut head, "fn", layout::Role::Keyword);
2394 +
            try add(a, &mut head, SPACE, try group(a, nil, recv));
2395 +
            try put(a, p, &mut head, SPACE, name, Ctx::Normal);
2396 +
            set fnBody = b;
2397 +
            set sig = s;
2398 +
        }
2399 +
        case ast::NodeValue::TraitMethodSig {
2400 +
            name, receiver, sig: s, attrs
2401 +
        } => {
2402 +
            try attributes(a, &mut head, attrs);
2403 +
            try spaced(a, &mut head, "fn", layout::Role::Keyword);
2404 +
            let mut recv: *mut [layout::Child] = &mut [];
2405 +
            try punct(a, &mut recv, NONE, "(");
2406 +
            try put(a, p, &mut recv, NONE, receiver, Ctx::Normal);
2407 +
            try punct(a, &mut recv, NONE, ")");
2408 +
            try add(a, &mut head, SPACE, try group(a, nil, recv));
2409 +
            try put(a, p, &mut head, SPACE, name, Ctx::Normal);
2410 +
            set sig = s;
2411 +
        }
2412 +
        else => panic "fnDecl: function expected",
2413 +
    }
2414 +
    try add(
2415 +
        a,
2416 +
        &mut head,
2417 +
        NONE,
2418 +
        try softList(a, p, parens(node), sig.params, Ctx::Normal, paramItem)
2419 +
    );
2420 +
    let mut tail: *mut [layout::Child] = &mut [];
2421 +
    try signatureTail(a, p, &mut tail, sig, marked(
2422 +
        p, node, ast::BrokenSite::Throws
2423 +
    ));
2424 +
    let stacked = isStacked(p, node);
2425 +
    let forced = marked(p, node, ast::BrokenSite::List);
2426 +
    let mut kids: *mut [layout::Child] = &mut [];
2427 +
    if let b = fnBody {
2428 +
        let case ast::NodeValue::Block(blk) = b.value else {
2429 +
            panic "fnDecl: block expected";
2430 +
        };
2431 +
        // The brace follows a `throws` clause that moved to its own line.
2432 +
        let mut at = SPACE;
2433 +
        if sig.throwList.len > 0 {
2434 +
            set at = SOFT_SPACE;
2435 +
        }
2436 +
        try punct(a, &mut tail, at, brace(p, blk.statements.len, b));
2437 +
        let text = try signature(a, sig, stacked, forced, head, tail);
2438 +
        try add(a, &mut kids, NONE, text);
2439 +
        set p.fnDepth += 1;
2440 +
        try body(a, p, &mut kids, blk.statements, b, stmt);
2441 +
        set p.fnDepth -= 1;
2442 +
    } else {
2443 +
        try punct(a, &mut tail, NONE, ";");
2444 +
        let text = try signature(a, sig, stacked, forced, head, tail);
2445 +
        try add(a, &mut kids, NONE, text);
2446 +
    }
2447 +
    return try group(a, node, kids);
2448 +
}
2449 +
2450 +
/// Whether the source of a signature put its `throws` clause on its own line.
2451 +
fn isStacked(p: &Printer, node: *ast::Node) -> bool {
2452 +
    for t in entries(p, node, ast::TriviaPlacement::Closing) {
2453 +
        if let case ast::TriviaKind::StackedThrows = t.kind {
2454 +
            return true;
2455 +
        }
2456 +
    }
2457 +
    return false;
2458 +
}
2459 +
2460 +
/// Layout of a function signature from its `head`, which ends with the
2461 +
/// parameters, and its `tail`: the return type, `throws` clause, and brace.
2462 +
///
2463 +
/// With a `throws` clause, the signature keeps the form of the source. The
2464 +
/// clause on its own line moves the brace to the next, which keeps the
2465 +
/// parameters and return type on the first line. `stacked` is true when the
2466 +
/// source has that form, and the signature prefers it. Otherwise it prefers
2467 +
/// one line, then the stacked form. The parameters break only when neither
2468 +
/// first line fits, or when `forced`: the source broke them.
2469 +
fn signature(
2470 +
    a: &mut opaque alloc::Allocator,
2471 +
    sig: ast::FnSig,
2472 +
    stacked: bool,
2473 +
    forced: bool,
2474 +
    head: *[layout::Child],
2475 +
    tail: *[layout::Child]
2476 +
) -> *layout::Layout throws (alloc::AllocError) {
2477 +
    let start = try flatGroup(a, nil, head);
2478 +
    let soft = try flatGroup(a, nil, tail);
2479 +
    if sig.throwList.len == 0 {
2480 +
        return try row(a, &[start, soft]);
2481 +
    }
2482 +
    let line = try flatGroup(a, nil, try inlined(a, tail));
2483 +
    let apart = try broken(a, soft);
2484 +
    let end = try choice(a, nil, &[line, apart]);
2485 +
    // The parameters end the head.
2486 +
    let opened = try flatGroup(a, nil, try brokenLast(a, head));
2487 +
    // The first line of any other form would hide the tail after the
2488 +
    // parameters, which sit on lines of their own.
2489 +
    if forced {
2490 +
        return try row(a, &[opened, apart if stacked else end]);
2491 +
    }
2492 +
    if stacked {
2493 +
        return try choice(a, nil, &[try row(a, &[start, apart]), try row(a, &[opened, end])]);
2494 +
    }
2495 +
    return try choice(
2496 +
        a,
2497 +
        nil,
2498 +
        &[
2499 +
            try row(a, &[start, line]),
2500 +
            try row(a, &[start, apart]),
2501 +
            try row(a, &[opened, end]),
2502 +
        ]
2503 +
    );
2504 +
}
2505 +
2506 +
/// Format a record field of a labeled record or a variant payload, with a
2507 +
/// comma.
2508 +
fn fieldItem(
2509 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
2510 +
) -> *layout::Layout throws (alloc::AllocError) {
2511 +
    let mut kids: *mut [layout::Child] = &mut [];
2512 +
    try add(a, &mut kids, NONE, try fieldBare(a, p, node, Ctx::Normal));
2513 +
    try punct(a, &mut kids, NONE, ",");
2514 +
2515 +
    return try group(a, node, kids);
2516 +
}
2517 +
2518 +
/// Format a record field of a labeled record or a variant payload, without a
2519 +
/// comma.
2520 +
fn fieldBare(
2521 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node, ctx: Ctx
2522 +
) -> *layout::Layout throws (alloc::AllocError) {
2523 +
    let case ast::NodeValue::RecordField { field, type, value } = node.value else {
2524 +
        panic "fieldBare: record field expected";
2525 +
    };
2526 +
    let name = field else {
2527 +
        panic "fieldBare: field has no name";
2528 +
    };
2529 +
    let mut kids: *mut [layout::Child] = &mut [];
2530 +
    try put(a, p, &mut kids, NONE, name, Ctx::Normal);
2531 +
    try punct(a, &mut kids, NONE, ":");
2532 +
    try put(a, p, &mut kids, SPACE, type, Ctx::Normal);
2533 +
    if let init = value {
2534 +
        try operator(a, &mut kids, SPACE, "=");
2535 +
        try put(a, p, &mut kids, SPACE, init, Ctx::Normal);
2536 +
    }
2537 +
    return try group(a, node, kids);
2538 +
}
2539 +
2540 +
/// Append the labeled fields of `container` in braces, on one line when they
2541 +
/// fit, otherwise one per line with a trailing comma. For a body that the
2542 +
/// source wrote on one line. The fields have no comments, since a comment ends
2543 +
/// the line.
2544 +
fn compactFields(
2545 +
    a: &mut opaque alloc::Allocator,
2546 +
    p: &mut Printer,
2547 +
    kids: &mut *mut [layout::Child],
2548 +
    container: *ast::Node,
2549 +
    fields: *[*ast::Node]
2550 +
) throws (alloc::AllocError) {
2551 +
    let spec = SoftSpec {
2552 +
        source: nil,
2553 +
        container,
2554 +
        open: "{",
2555 +
        close: "}",
2556 +
        pad: layout::Gap::Space,
2557 +
        tail: nil,
2558 +
        commas: Commas::Trailing,
2559 +
        forced: false,
2560 +
    };
2561 +
    let list = try plainList(a, p, spec, fields, Ctx::Normal, fieldBare);
2562 +
    let case layout::Item::Box(parts) = unbroken(list).item else {
2563 +
        panic "compactFields: list is not a box";
2564 +
    };
2565 +
    // The same items, one per line.
2566 +
    let mut lines: *mut [layout::Child] = &mut [];
2567 +
    for part in parts {
2568 +
        try lines.append(part, a);
2569 +
    }
2570 +
    set lines[1].layout = try broken(a, parts[1].layout);
2571 +
    let vertical = try broken(a, try flatGroup(a, nil, lines));
2572 +
    try add(a, kids, SPACE, try choice(a, nil, &[list, vertical]));
2573 +
}
2574 +
2575 +
/// Whether a labeled record body or payload prints on one line when it fits:
2576 +
/// the source wrote it on one line, and it has fields.
2577 +
fn isCompact(p: &Printer, container: *ast::Node, count: u32) -> bool {
2578 +
    return count > 0 and not marked(p, container, ast::BrokenSite::List);
2579 +
}
2580 +
2581 +
/// Format the type of a positional record field.
2582 +
fn positionalItem(
2583 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node, ctx: Ctx
2584 +
) -> *layout::Layout throws (alloc::AllocError) {
2585 +
    let case ast::NodeValue::RecordField { type, .. } = node.value else {
2586 +
        panic "positionalItem: record field expected";
2587 +
    };
2588 +
    return try expr(a, p, type, ctx);
2589 +
}
2590 +
2591 +
/// Format a union variant: its name, explicit value or payload, and a comma.
2592 +
fn variantItem(
2593 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
2594 +
) -> *layout::Layout throws (alloc::AllocError) {
2595 +
    let case ast::NodeValue::UnionDeclVariant(v) = node.value else {
2596 +
        panic "variantItem: variant expected";
2597 +
    };
2598 +
    let mut kids: *mut [layout::Child] = &mut [];
2599 +
    try put(a, p, &mut kids, NONE, v.name, Ctx::Normal);
2600 +
    if let value = v.value {
2601 +
        try operator(a, &mut kids, SPACE, "=");
2602 +
        try put(a, p, &mut kids, SPACE, value, Ctx::Normal);
2603 +
    }
2604 +
    if let payload = v.type {
2605 +
        let case ast::NodeValue::TypeSig(sig) = payload.value else {
2606 +
            panic "variantItem: payload type expected";
2607 +
        };
2608 +
        let case ast::TypeSig::Record { fields, labeled } = sig else {
2609 +
            panic "variantItem: record payload expected";
2610 +
        };
2611 +
        if labeled and isCompact(p, payload, fields.len) {
2612 +
            try compactFields(a, p, &mut kids, payload, fields);
2613 +
        } else if labeled {
2614 +
            try punct(a, &mut kids, SPACE, brace(p, fields.len, payload));
2615 +
            try body(a, p, &mut kids, fields, payload, fieldItem);
2616 +
        } else {
2617 +
            try add(
2618 +
                a,
2619 +
                &mut kids,
2620 +
                NONE,
2621 +
                try softList(
2622 +
                    a,
2623 +
                    p,
2624 +
                    SoftSpec {
2625 +
                        source: payload,
2626 +
                        container: payload,
2627 +
                        open: "(",
2628 +
                        close: ")",
2629 +
                        pad: layout::Gap::None,
2630 +
                        tail: nil,
2631 +
                        commas: Commas::Between,
2632 +
                        forced: false,
2633 +
                    },
2634 +
                    fields,
2635 +
                    Ctx::Normal,
2636 +
                    positionalItem
2637 +
                )
2638 +
            );
2639 +
        }
2640 +
    }
2641 +
    try punct(a, &mut kids, NONE, ",");
2642 +
2643 +
    return try group(a, node, kids);
2644 +
}
2645 +
2646 +
/// Append `: A + B`, the traits that a type derives or a trait extends.
2647 +
fn derives(
2648 +
    a: &mut opaque alloc::Allocator,
2649 +
    p: &mut Printer,
2650 +
    kids: &mut *mut [layout::Child],
2651 +
    list: *[*ast::Node]
2652 +
) throws (alloc::AllocError) {
2653 +
    for item, i in list {
2654 +
        if i == 0 {
2655 +
            try punct(a, kids, NONE, ":");
2656 +
        } else {
2657 +
            try operator(a, kids, SPACE, "+");
2658 +
        }
2659 +
        try put(a, p, kids, SPACE, item, Ctx::Normal);
2660 +
    }
2661 +
}
2662 +
2663 +
/// Format a record, union, trait, or instance declaration.
2664 +
fn typeDecl(
2665 +
    a: &mut opaque alloc::Allocator, p: &mut Printer, node: *ast::Node
2666 +
) -> *layout::Layout throws (alloc::AllocError) {
2667 +
    let mut head: *mut [layout::Child] = &mut [];
2668 +
    let mut kids: *mut [layout::Child] = &mut [];
2669 +
    match node.value {
2670 +
        case ast::NodeValue::RecordDecl(r) => {
2671 +
            try attributes(a, &mut head, r.attrs);
2672 +
            try spaced(a, &mut head, "record", layout::Role::Keyword);
2673 +
            try put(a, p, &mut head, SPACE, r.name, Ctx::Normal);
2674 +
            if r.labeled and isCompact(p, node, r.fields.len) {
2675 +
                try derives(a, p, &mut head, r.derives);
2676 +
                try compactFields(a, p, &mut head, node, r.fields);
2677 +
                try add(a, &mut kids, NONE, try group(a, nil, head));
2678 +
            } else if r.labeled {
2679 +
                try derives(a, p, &mut head, r.derives);
2680 +
                try punct(a, &mut head, SPACE, brace(p, r.fields.len, node));
2681 +
                try add(a, &mut kids, NONE, try group(a, nil, head));
2682 +
                try body(a, p, &mut kids, r.fields, node, fieldItem);
2683 +
            } else {
2684 +
                try add(
2685 +
                    a,
2686 +
                    &mut head,
2687 +
                    NONE,
2688 +
                    try softList(
2689 +
                        a,
2690 +
                        p,
2691 +
                        parens(node),
2692 +
                        r.fields,
2693 +
                        Ctx::Normal,
2694 +
                        positionalItem
2695 +
                    )
2696 +
                );
2697 +
                try derives(a, p, &mut head, r.derives);
2698 +
                try punct(a, &mut head, NONE, ";");
2699 +
                try add(a, &mut kids, NONE, try group(a, nil, head));
2700 +
            }
2701 +
        }
2702 +
        case ast::NodeValue::UnionDecl(u) => {
2703 +
            try attributes(a, &mut head, u.attrs);
2704 +
            try spaced(a, &mut head, "union", layout::Role::Keyword);
2705 +
            try put(a, p, &mut head, SPACE, u.name, Ctx::Normal);
2706 +
            try derives(a, p, &mut head, u.derives);
2707 +
            try punct(a, &mut head, SPACE, brace(p, u.variants.len, node));
2708 +
            try add(a, &mut kids, NONE, try group(a, nil, head));
2709 +
            try body(a, p, &mut kids, u.variants, node, variantItem);
2710 +
        }
2711 +
        case ast::NodeValue::TraitDecl {
2712 +
            name, supertraits, methods, attrs
2713 +
        } => {
2714 +
            try attributes(a, &mut head, attrs);
2715 +
            try spaced(a, &mut head, "trait", layout::Role::Keyword);
2716 +
            try put(a, p, &mut head, SPACE, name, Ctx::Normal);
2717 +
            try derives(a, p, &mut head, supertraits);
2718 +
            try punct(a, &mut head, SPACE, brace(p, methods.len, node));
2719 +
            try add(a, &mut kids, NONE, try group(a, nil, head));
2720 +
            try body(a, p, &mut kids, methods, node, fnDecl);
2721 +
        }
2722 +
        case ast::NodeValue::InstanceDecl {
2723 +
            traitName, targetType, methods
2724 +
        } => {
2725 +
            try spaced(a, &mut head, "instance", layout::Role::Keyword);
2726 +
            try put(a, p, &mut head, SPACE, traitName, Ctx::Normal);
2727 +
            try keyword(a, &mut head, SPACE, "for");
2728 +
            try put(a, p, &mut head, SPACE, targetType, Ctx::Normal);
2729 +
            try punct(a, &mut head, SPACE, brace(p, methods.len, node));
2730 +
            try add(a, &mut kids, NONE, try group(a, nil, head));
2731 +
            try body(a, p, &mut kids, methods, node, stmt);
2732 +
        }
2733 +
        else => panic "typeDecl: type declaration expected",
2734 +
    }
2735 +
    return try group(a, node, kids);
2736 +
}
scripts/fmt added +29 -0
1 +
#!/bin/sh
2 +
# Format Radiance sources in place with `radiance -fmt`.
3 +
# Usage: scripts/fmt <source>...
4 +
#
5 +
# Each source is formatted into a temporary file, which replaces the source
6 +
# only if formatting succeeded and the text changed. Sources are processed in
7 +
# parallel by `JOBS` workers. A failure is reported with its diagnostics and
8 +
# does not stop the others, but makes the exit status nonzero.
9 +
set -eu
10 +
11 +
compiler=${RAD_BIN:-bin/radiance.rv64.dev}
12 +
13 +
if [ "${1:-}" = --one ]; then
14 +
    source=$2
15 +
    work=$(mktemp -d)
16 +
    trap 'rm -rf "$work"' EXIT HUP INT TERM
17 +
18 +
    if ! scripts/hosted "$compiler" -fmt "$source" > "$work/out" 2> "$work/log"; then
19 +
        printf 'fmt %s ... FAILED\n%s\n' "$source" "$(cat "$work/log")"
20 +
        exit 1
21 +
    fi
22 +
    if ! cmp -s "$source" "$work/out"; then
23 +
        cat "$work/out" > "$source"
24 +
        echo "fmt $source"
25 +
    fi
26 +
    exit 0
27 +
fi
28 +
29 +
printf '%s\n' "$@" | xargs -P "${JOBS:-1}" -n 1 sh "$0" --one
std.lib +3 -0
26 26
lib/std/lang/types.rad
27 27
lib/std/lang/strings.rad
28 28
lib/std/lang/sexpr.rad
29 29
lib/std/lang/ast.rad
30 30
lib/std/lang/ast/printer.rad
31 +
lib/std/lang/layout.rad
32 +
lib/std/lang/layout/text.rad
31 33
lib/std/lang/scanner.rad
32 34
lib/std/lang/parser.rad
35 +
lib/std/lang/pretty.rad
33 36
lib/std/lang/il.rad
34 37
lib/std/lang/il/printer.rad
35 38
lib/std/lang/il/binary.rad
36 39
lib/std/lang/il/binary/writer.rad
37 40
lib/std/lang/il/binary/reader.rad
std.lib.test +1 -0
4 4
lib/std/arch/rv64/tests.rad
5 5
lib/std/arch/rv64/asm/tests.rad
6 6
lib/std/arch/rv64/asm/scanner/tests.rad
7 7
lib/std/lang/alloc/tests.rad
8 8
lib/std/lang/sexpr/tests.rad
9 +
lib/std/lang/layout/tests.rad
9 10
lib/std/lang/il/printer/tests.rad
10 11
lib/std/lang/lower/tests.rad
11 12
lib/std/lang/parser/tests.rad
12 13
lib/std/lang/module/tests.rad
13 14
lib/std/lang/scanner/tests.rad
test/Makefile +6 -1
1 1
# Compiler and standard library test suites. Run from the repository root.
2 2
# JOBS controls workers inside test scripts.
3 3
JOBS ?= 1
4 4
export JOBS
5 -
TESTS := seed-test std-test bin-test module-test \
5 +
TESTS := seed-test std-test fmt-test bin-test module-test \
6 6
    native-test shared-test verify-test
7 7
8 8
test: $(TESTS)
9 9
.PHONY: test $(TESTS) smp-test cycles-test clean-std-test clean-bin-test
10 10
36 36
37 37
clean-std-test:
38 38
	@rm -f lib/std.test.rv64 lib/std.test.rv64.debug \
39 39
	    lib/std.test.rv64.s lib/std.test.rv64.o
40 40
41 +
# The source formatter keeps the AST of every standard library and compiler
42 +
# source, and formats its own output to itself.
43 +
fmt-test: $(RAD_BIN) test/fmt/run
44 +
	@sh test/fmt/run
45 +
41 46
# Native image execution through the configured machine-capable emulator.
42 47
native-test: $(BIN_DIR)/native.fixture.rv64
43 48
	@$${RAD_EMULATOR:-emulator} -machine -max-steps=1000000 -run $<
44 49
45 50
$(BIN_DIR)/native.fixture.rv64: test/native/build.rv64 test/Makefile
test/fmt/run added +127 -0
1 +
#!/bin/sh
2 +
# Check the source formatter on every Radiance source under the given
3 +
# directories, which default to lib and compiler, and on its error handling.
4 +
# Usage: sh test/fmt/run [<directory>...]
5 +
#
6 +
# For each source, `radiance -fmt` must succeed, and the formatted text must
7 +
# parse to the same AST as the source, and format to itself. Sources are
8 +
# checked in parallel by `JOBS` workers, which run `run --check <source>`.
9 +
set -eu
10 +
11 +
compiler=${RAD_BIN:-bin/radiance.rv64.dev}
12 +
13 +
# Run `radiance` with the given arguments. The output goes to "$work/out", the
14 +
# diagnostics to "$work/log", and the exit status to "$status".
15 +
format() {
16 +
    status=0
17 +
    scripts/hosted "$compiler" "$@" > "$work/out" 2> "$work/log" || status=$?
18 +
}
19 +
20 +
# Check one source and print a line if it fails.
21 +
checkSource() {
22 +
    source=$1
23 +
    work=$(mktemp -d)
24 +
    trap 'rm -rf "$work"' EXIT HUP INT TERM
25 +
26 +
    format -fmt "$source"
27 +
    if [ "$status" -ne 0 ]; then
28 +
        printf 'fmt %s ... FAILED (format)\n%s\n' \
29 +
            "$source" "$(cat "$work/log")"
30 +
        exit 1
31 +
    fi
32 +
    mv "$work/out" "$work/once.rad"
33 +
    format -fmt "$work/once.rad"
34 +
    if [ "$status" -ne 0 ]; then
35 +
        printf 'fmt %s ... FAILED (format of the output)\n%s\n' \
36 +
            "$source" "$(cat "$work/log")"
37 +
        exit 1
38 +
    fi
39 +
    if ! cmp -s "$work/once.rad" "$work/out"; then
40 +
        printf 'fmt %s ... FAILED (not idempotent)\n%s\n' "$source" \
41 +
            "$(diff "$work/once.rad" "$work/out" | head -20)"
42 +
        exit 1
43 +
    fi
44 +
    format -pkg fmt -mod "$source" -dump ast
45 +
    if [ "$status" -ne 0 ]; then
46 +
        printf 'fmt %s ... FAILED (AST dump)\n%s\n' \
47 +
            "$source" "$(cat "$work/log")"
48 +
        exit 1
49 +
    fi
50 +
    mv "$work/out" "$work/source.ast"
51 +
    format -pkg fmt -mod "$work/once.rad" -dump ast
52 +
    if [ "$status" -ne 0 ]; then
53 +
        printf 'fmt %s ... FAILED (AST dump of the output)\n%s\n' \
54 +
            "$source" "$(cat "$work/log")"
55 +
        exit 1
56 +
    fi
57 +
    if ! cmp -s "$work/source.ast" "$work/out"; then
58 +
        printf 'fmt %s ... FAILED (AST changed)\n%s\n' "$source" \
59 +
            "$(diff "$work/source.ast" "$work/out" | head -20)"
60 +
        exit 1
61 +
    fi
62 +
}
63 +
64 +
if [ "${1:-}" = --check ]; then
65 +
    checkSource "$2"
66 +
    exit 0
67 +
fi
68 +
69 +
if [ $# -eq 0 ]; then
70 +
    set -- lib compiler
71 +
fi
72 +
work=$(mktemp -d)
73 +
trap 'rm -rf "$work"' EXIT HUP INT TERM
74 +
75 +
find "$@" -name '*.rad' | sort > "$work/sources"
76 +
workers=0
77 +
xargs -P "${JOBS:-1}" -n 1 sh test/fmt/run --check < "$work/sources" \
78 +
    > "$work/report" || workers=$?
79 +
cat "$work/report"
80 +
total=$(wc -l < "$work/sources")
81 +
failed=$(grep -c '^fmt .* \.\.\. FAILED' "$work/report" || true)
82 +
broken=0
83 +
84 +
# A syntax error exits with status 1 and is reported on standard error only,
85 +
# so that standard output holds nothing but formatted text.
86 +
printf 'let x = ;\n' > "$work/bad.rad"
87 +
format -fmt "$work/bad.rad"
88 +
if [ "$status" -ne 1 ] || [ -s "$work/out" ] ||
89 +
    ! grep -q 'error: ' "$work/log"; then
90 +
    echo "fmt syntax error ... FAILED (status $status, or stdout output)"
91 +
    cat "$work/out" "$work/log"
92 +
    broken=$((broken + 1))
93 +
fi
94 +
95 +
# A wrong number of arguments exits with status 1 and prints the usage.
96 +
expectUsage() {
97 +
    format -fmt "$@"
98 +
    if [ "$status" -ne 1 ] || ! grep -q '^usage:' "$work/log"; then
99 +
        echo "fmt $* ... FAILED (status $status, or no usage)"
100 +
        cat "$work/out" "$work/log"
101 +
        broken=$((broken + 1))
102 +
    fi
103 +
}
104 +
expectUsage
105 +
expectUsage "$work/bad.rad" "$work/bad.rad"
106 +
expectUsage -fmt.wrap 0 "$work/bad.rad"
107 +
expectUsage -fmt.wrap x "$work/bad.rad"
108 +
expectUsage -fmt.wrap
109 +
110 +
# The width defaults to 100 columns and `-fmt.wrap` sets it. This statement
111 +
# is 95 columns wide, so it wraps at 80 only.
112 +
printf 'fn f() {\n    call(%s);\n}\n' \
113 +
    "$(printf 'argument, %.0s' 1 2 3 4 5 6 7 8)last" > "$work/wide.rad"
114 +
format -fmt "$work/wide.rad"
115 +
lines=$(wc -l < "$work/out")
116 +
format -fmt -fmt.wrap 80 "$work/wide.rad"
117 +
if [ "$lines" -ne 3 ] || [ "$(wc -l < "$work/out")" -le 3 ]; then
118 +
    echo "fmt wrap ... FAILED (default $lines lines)"
119 +
    broken=$((broken + 1))
120 +
fi
121 +
if [ "$workers" -ne 0 ] && [ "$failed" -eq 0 ]; then
122 +
    echo "fmt: workers exited with status $workers"
123 +
    broken=$((broken + 1))
124 +
fi
125 +
echo "fmt: $((total - failed)) source files round-trip," \
126 +
    "$((failed + broken)) failed"
127 +
test "$((failed + broken))" -eq 0