1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//! Tuple, unit, and parenthesized expression parsing for Nash.
//!
//! Ported from Elm's tuple parsing in `Parse/Expression.hs`.
//!
//! Handles:
//! - `()` → Unit
//! - `(expr)` → parenthesized expression (returned unwrapped)
//! - `(a, b)`, `(a, b, c, ...)` → Tuple
use bumpalo::collections::Vec as BumpVec;
use nash_region::{Located, Position};
use nash_source::Expr;
use crate::Parser;
use crate::error::{self, Tuple};
impl<'a> Parser<'a> {
/// Parse a tuple, unit, or parenthesized expression.
///
/// Mirrors Elm's `tuple`:
/// ```haskell
/// tuple start@(A.Position row col) =
/// inContext E.Tuple (word1 0x28 {-(-} E.Start) $
/// do ...
/// ```
pub(crate) fn tuple(
&mut self,
start: Position,
) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
self.in_context(
// Wrap Tuple errors with Expr::Tuple context
|bump, tuple_err, row, col| error::Expr::Tuple(bump.alloc(tuple_err), row, col),
// Start parser: parse '('
|p| p.word1(0x28, error::Expr::Start),
// Body parser: parse tuple contents
|p| p.tuple_body(start),
)
}
/// Parse the body of a tuple after the opening '('.
///
/// Returns `Tuple` errors which get wrapped by `in_context`.
///
/// Handles:
/// - `()` → Unit
/// - `(expr)` → parenthesized expression
/// - `(a, b, ...)` → Tuple
/// - `(+)` → Operator section (Op)
/// - `(-expr)` → Parenthesized negation (parsed as expression)
fn tuple_body(&mut self, start: Position) -> Result<&'a Located<Expr<'a>>, Tuple<'a>> {
self.chomp_and_check_indent(Tuple::Space, Tuple::IndentExpr1)?;
self.one_of(
Tuple::IndentExpr1,
vec![
Box::new(|p: &mut Parser<'a>| {
let op = p.operator(Tuple::IndentExpr1, Tuple::OperatorReserved)?;
if p.peek() == Some(b')') {
p.advance();
return Ok(p.add_end(start, Expr::Op(op)));
}
if op == "-" {
p.chomp_and_check_indent(Tuple::Space, Tuple::IndentExpr1)?;
let inner = p.specialize(
|bump, error, row, col| Tuple::Expr(bump.alloc(error), row, col),
|p| p.term(),
)?;
let neg_end = p.get_position();
let neg_start = Position::new(start.line, start.column + 1);
let negated = p.alloc(Located::at(
nash_region::Region::new(neg_start, neg_end),
Expr::Negate(inner),
));
p.chomp(Tuple::Space)?;
let (full, end) = p.specialize(
|bump, error, row, col| Tuple::Expr(bump.alloc(error), row, col),
|p| p.chomp_expr_end(start, negated, vec![], neg_end),
)?;
p.check_indent(end.line, end.column, Tuple::IndentEnd)?;
return p.chomp_tuple_end(start, full);
}
p.chomp_and_check_indent(Tuple::Space, Tuple::IndentExpr1)?;
let (right, end) = p.tuple_expr()?;
p.check_indent(end.line, end.column, Tuple::IndentEnd)?;
p.chomp(Tuple::Space)?;
p.word1(b')', Tuple::OperatorClose)?;
Ok(p.add_end(
start,
Expr::RightSection {
operator: op,
right,
},
))
}),
Box::new(|p: &mut Parser<'a>| {
p.word1(b')', Tuple::IndentExpr1)?;
Ok(p.add_end(start, Expr::Unit))
}),
Box::new(|p: &mut Parser<'a>| {
let (first, end) = p.tuple_expr()?;
p.check_indent(end.line, end.column, Tuple::IndentEnd)?;
p.chomp_tuple_end(start, first)
}),
],
)
}
/// Parse a tuple entry expression.
///
/// In Elm this uses `specialize E.TupleExpr expression`.
/// Returns both the expression and its end position for indent checking.
fn tuple_expr(&mut self) -> Result<(&'a Located<Expr<'a>>, Position), Tuple<'a>> {
self.specialize(
|bump, expr_err, row, col| Tuple::Expr(bump.alloc(expr_err), row, col),
|p| p.expression(),
)
}
/// Parse the rest of a tuple after the first expression.
///
/// Mirrors Elm's `chompTupleEnd`:
/// ```haskell
/// chompTupleEnd start firstExpr revExprs =
/// oneOf E.TupleEnd
/// [ do word1 0x2C {-,-} E.TupleEnd
/// ...
/// chompTupleEnd start firstExpr (entry : revExprs)
/// , do word1 0x29 {-)-} E.TupleEnd
/// case reverse revExprs of
/// [] -> return firstExpr -- parenthesized
/// secondExpr : otherExprs ->
/// addEnd start (Src.Tuple firstExpr secondExpr otherExprs)
/// ]
/// ```
fn chomp_tuple_end(
&mut self,
start: Position,
first: &'a Located<Expr<'a>>,
) -> Result<&'a Located<Expr<'a>>, Tuple<'a>> {
let mut rest: BumpVec<'a, &'a Located<Expr<'a>>> = BumpVec::new_in(self.bump);
loop {
// Chomp whitespace
self.chomp(Tuple::Space)?;
let saved = self.save_state();
match self.operator(Tuple::End, Tuple::OperatorReserved) {
Ok(operator) => {
self.chomp(Tuple::Space)?;
if self.word1(b')', Tuple::OperatorClose).is_ok() {
return Ok(self.add_end(
start,
Expr::LeftSection {
left: first,
operator,
},
));
}
self.restore_state(saved);
}
Err(error) => {
if self.pos != saved.pos {
return Err(error);
}
self.restore_state(saved);
}
}
// Expect comma or closing paren
let done = self.one_of(
Tuple::End,
vec![
// Comma - parse another expression
Box::new(|p: &mut Parser<'a>| {
p.word1(0x2C, Tuple::End)?;
// Chomp whitespace and check indent after comma
p.chomp_and_check_indent(Tuple::Space, Tuple::IndentExprN)?;
// Parse the expression
let (elem, end) = p.tuple_expr()?;
rest.push(elem);
// Check indent using expression's end position
p.check_indent(end.line, end.column, Tuple::IndentEnd)?;
Ok(false) // Not done, continue loop
}),
// Closing paren - done
Box::new(|p: &mut Parser<'a>| {
p.word1(0x29, Tuple::End)?;
Ok(true) // Done
}),
],
)?;
if done {
break;
}
}
// Determine what we parsed
if rest.is_empty() {
// Just parenthesized expression - return unwrapped
Ok(first)
} else {
// Tuple: need at least 2 elements
let second = rest.remove(0);
let others = rest.into_bump_slice();
Ok(self.add_end(
start,
Expr::Tuple {
first,
second,
rest: others,
},
))
}
}
}
#[cfg(test)]
mod tests {
use crate::expression::{
assert_expr_error_snapshot, assert_expr_snapshot, assert_expression_snapshot,
assert_indented_expr_snapshot,
};
#[test]
fn unit() {
assert_expr_snapshot!("()");
}
#[test]
fn parenthesized() {
assert_expr_snapshot!("(42)");
}
#[test]
fn pair() {
assert_expr_snapshot!("(1, 2)");
}
#[test]
fn triple() {
assert_expr_snapshot!("(1, 2, 3)");
}
#[test]
fn with_whitespace() {
assert_expr_snapshot!("( 1 , 2 , 3 )");
}
#[test]
fn nested() {
assert_expr_snapshot!("((1, 2), 3)");
}
#[test]
fn nested_list() {
assert_expr_snapshot!("([1, 2], [3, 4])");
}
#[test]
fn multiline() {
assert_indented_expr_snapshot!(
"(
1,
2,
3
)"
);
}
#[test]
fn error_unclosed() {
assert_expr_error_snapshot!("(1, 2");
}
#[test]
fn error_trailing_comma() {
assert_expr_error_snapshot!("(1, 2,)");
}
#[test]
fn error_empty_comma() {
assert_expr_error_snapshot!("(,)");
}
#[test]
fn right_section() {
assert_expr_snapshot!("(> 5)");
}
#[test]
fn left_section() {
assert_expr_snapshot!("(5 >)");
}
#[test]
fn call_left_section() {
assert_expr_snapshot!("(f x |> )");
}
#[test]
fn operator_application() {
assert_expr_snapshot!("((+) 1)");
}
#[test]
fn minus_operator() {
assert_expr_snapshot!("(-)");
}
#[test]
fn parenthesized_negative() {
assert_expr_snapshot!("(-1)");
}
#[test]
fn spaced_parenthesized_negative() {
assert_expr_snapshot!("(- 1)");
}
#[test]
fn minus_left_section() {
assert_expr_snapshot!("(1 -)");
}
#[test]
fn applied_section() {
assert_expression_snapshot!("(> 5) 10");
}
#[test]
fn error_section_unclosed() {
assert_expr_error_snapshot!("(> 5");
}
#[test]
fn error_reserved_section_operator() {
assert_expr_error_snapshot!("(=> 5)");
}
#[test]
fn error_section_missing_operand() {
assert_expr_error_snapshot!("(> ,)");
}
}