m2-syn 0.1.0

Typed syntax trees, traversal, and parser adapters for Macaulay2
Documentation
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use m2_syn::{
    AnyCell, BinaryOperator, Collection, Expr, LiteralKind, NativeParseError, OperatorExpr,
    SourceId, Spanned, ToCells, ToTokens, TokenTree, lex_str, parse_native, parse_with,
};

fn expression(source: &str) -> Expr {
    let mut file = parse_native(source, SourceId(31)).unwrap();
    assert_eq!(file.elements.len(), 1);
    let AnyCell::ExpressionCell(cell) = file.elements.pop().unwrap() else {
        panic!("expected one expression cell");
    };
    *cell.value
}

fn adjacent(expression: &Expr) -> (&Expr, &Expr) {
    let Expr::OperatorExpr(OperatorExpr::BinaryExpression(expression)) = expression else {
        panic!("expected implicit application, found {expression:?}");
    };
    assert!(matches!(expression.operator, BinaryOperator::Space(_)));
    (&expression.left, &expression.right)
}

fn binary(expression: &Expr) -> (&Expr, &BinaryOperator, &Expr) {
    let Expr::OperatorExpr(OperatorExpr::BinaryExpression(expression)) = expression else {
        panic!("expected a binary expression, found {expression:?}");
    };
    (&expression.left, &expression.operator, &expression.right)
}

#[test]
fn binding_strength_relative_to_precedence_controls_associativity() {
    let left = expression("a * b * c");
    let (left_operand, operator, _) = binary(&left);
    assert_eq!(operator.spelling(), "*");
    assert_eq!(binary(left_operand).1.spelling(), "*");

    let right = expression("a @ b @ c");
    let (_, operator, right_operand) = binary(&right);
    assert_eq!(operator.spelling(), "@");
    assert_eq!(binary(right_operand).1.spelling(), "@");
}

#[test]
fn implicit_application_uses_the_consumed_tokens_unary_handler_at_level_61() {
    let application = expression("b c d");
    let (_, right) = adjacent(&application);
    adjacent(right);

    let prefixed = expression("# f x");
    let Expr::OperatorExpr(OperatorExpr::PrefixExpression(prefix)) = prefixed else {
        panic!("expected prefix expression");
    };
    assert_eq!(prefix.operator.spelling(), "#");
    adjacent(&prefix.operand);
}

#[test]
fn bracket_precedence_differs_from_parenthesis_precedence() {
    let indexed_quotient = expression("R / I [x]");
    let (left, right) = adjacent(&indexed_quotient);
    assert_eq!(binary(left).1.spelling(), "/");
    assert!(matches!(right, Expr::Collection(Collection::Array(_))));

    let bracket = expression("a x []");
    let (left, right) = adjacent(&bracket);
    adjacent(left);
    assert!(matches!(right, Expr::Collection(Collection::Array(_))));

    let parenthesis = expression("a x ()");
    let (_, right) = adjacent(&parenthesis);
    let (_, call) = adjacent(right);
    assert!(matches!(
        call,
        Expr::Collection(Collection::ParenthesizedExpression(_))
    ));
}

#[test]
fn chained_delimiters_inherit_the_application_floor() {
    let low_then_high = expression("a [] ()");
    let (_, right) = adjacent(&low_then_high);
    let (array, parenthesis) = adjacent(right);
    assert!(matches!(array, Expr::Collection(Collection::Array(_))));
    assert!(matches!(
        parenthesis,
        Expr::Collection(Collection::ParenthesizedExpression(_))
    ));

    let high_then_low = expression("a () []");
    let (left, array) = adjacent(&high_then_low);
    let (_, parenthesis) = adjacent(left);
    assert!(matches!(
        parenthesis,
        Expr::Collection(Collection::ParenthesizedExpression(_))
    ));
    assert!(matches!(array, Expr::Collection(Collection::Array(_))));
}

#[test]
fn physical_newlines_are_cell_boundaries_but_required_operands_cross_them() {
    assert_eq!(
        parse_native("1\n1", SourceId(32)).unwrap().elements.len(),
        2
    );
    assert_eq!(
        parse_native("1 +\n1", SourceId(32)).unwrap().elements.len(),
        1
    );
    assert_eq!(
        parse_native("1 -* comment\n*- 1", SourceId(32))
            .unwrap()
            .elements
            .len(),
        2
    );
    assert!(matches!(
        parse_native("(1\n1)", SourceId(32)),
        Err(NativeParseError::NewlineInApplication { .. })
    ));

    for source in ["(1 SPACE\n1)", "(1\nSPACE 1)", "(1 +\n1)", "(1\n+ 1)"] {
        parse_native(source, SourceId(32))
            .unwrap_or_else(|error| panic!("`{source}` should parse, but failed with {error}"));
    }
}

#[test]
fn paired_top_level_semicolons_create_muted_cells() {
    let file = parse_native("2;2;2", SourceId(33)).unwrap();
    assert_eq!(file.elements.len(), 3);
    assert!(matches!(file.elements[0], AnyCell::MutedCell(_)));
    assert!(matches!(file.elements[1], AnyCell::MutedCell(_)));
    assert!(matches!(file.elements[2], AnyCell::ExpressionCell(_)));
}

#[test]
fn semicolons_cannot_delimit_empty_statements() {
    for source in [";", "1;;2", "(;)", "(1;;2)"] {
        parse_native(source, SourceId(33))
            .expect_err(&format!("`{source}` should reject an empty statement"));
    }
}

#[test]
fn implicit_and_explicit_space_remain_distinct_typed_forms() {
    let implicit = expression("f x");
    adjacent(&implicit);
    assert_eq!(implicit.to_code(), "f x");

    let explicit = expression("f SPACE x");
    assert!(matches!(binary(&explicit).1, BinaryOperator::Space(_)));
    assert_eq!(explicit.to_code(), "f SPACE x");
}

#[test]
fn compiler_edge_case_examples_reach_the_precedence_parser() {
    for source in [
        r#""1!!!1_!!!_!^^1!!(*)!(*()(*))1!Core$not$1$\\Core$symbol((*)""#,
        r#""1>>#####<<<<<<><>1>>> > > 1""#,
        r#"1!!!1_!!!_!^^1!!(*)!(()!(*))1!Core$not$1$Core$%symbol(*)"#,
        r#"1.p1e-00.00p1e-1_!!_!...1.e1"#,
    ] {
        parse_native(source, SourceId(34))
            .unwrap_or_else(|error| panic!("`{source}` failed with {error:?}"));
    }
}

#[test]
fn precedence_parser_consumes_the_shared_token_stream_directly() {
    let tokens = lex_str("a @ b @ c", SourceId(35)).unwrap();
    let mut parser = m2_syn::NativeParser::new();
    let file = parse_with(&mut parser, tokens).unwrap();
    assert_eq!(file.to_code(), "a @ b @ c");
}

#[test]
fn typed_tokens_and_cells_round_trip_through_the_native_parser() {
    let source_id = SourceId(351);
    let lexed = lex_str("a * b;\nreturn c", source_id).unwrap();
    let expected_multiply_span = lexed
        .iter()
        .flat_map(|cell| cell.stream().iter())
        .find_map(|tree| match tree {
            TokenTree::Punct(token) if token.text() == "*" => Some(token.span()),
            _ => None,
        })
        .expect("the lexer should emit the shared raw punctuation atom");

    let mut parser = m2_syn::NativeParser::new();
    let file = parse_with(&mut parser, lexed).unwrap();
    assert!(file.to_token_stream().into_iter().any(|tree| {
        matches!(tree, TokenTree::Punct(token)
            if token.text() == "*" && token.span() == expected_multiply_span)
    }));

    let cells = file.to_cell_stream(source_id);
    assert_eq!(cells.cells().len(), 2);
    assert_eq!(cells.to_string(), file.to_code());

    let reparsed = parse_with(&mut parser, cells).unwrap();
    assert_eq!(reparsed.to_code(), file.to_code());
}

#[test]
fn typed_strings_emit_literal_tokens_instead_of_delimiter_groups() {
    for (source, expected_kind) in [
        (r#""a\n""#, LiteralKind::String),
        ("///a//b///", LiteralKind::RawString),
    ] {
        let file = parse_native(source, SourceId(36)).unwrap();
        let tokens = file.to_token_stream().into_iter().collect::<Vec<_>>();
        assert_eq!(tokens.len(), 1);
        let TokenTree::Literal(literal) = &tokens[0] else {
            panic!("`{source}` emitted a non-literal token: {:?}", tokens[0]);
        };
        assert_eq!(literal.kind, expected_kind);
        assert_eq!(literal.text(), source);
    }
}

#[test]
fn prefix_control_statements_respect_optional_values_and_cell_boundaries() {
    let Expr::BreakStatement(statement) = expression("break") else {
        panic!("expected a break statement");
    };
    assert!(statement.value.is_none());

    let Expr::ContinueStatement(statement) = expression("continue x") else {
        panic!("expected a continue statement");
    };
    assert!(matches!(statement.value.as_deref(), Some(Expr::Symbol(_))));

    let Expr::ReturnStatement(statement) = expression("return 1 + 2") else {
        panic!("expected a return statement");
    };
    assert_eq!(
        binary(
            statement
                .value
                .as_deref()
                .expect("return should have a value")
        )
        .1
        .spelling(),
        "+"
    );

    assert_eq!(
        parse_native("return\n1", SourceId(37))
            .unwrap()
            .elements
            .len(),
        2
    );
    let Expr::CatchStatement(_) = expression("catch\n1") else {
        panic!("catch should require its value across a physical line break");
    };

    for keyword in ["catch", "throw", "trap"] {
        assert!(matches!(
            parse_native(keyword, SourceId(38)),
            Err(NativeParseError::MissingOperand { operator, .. }) if operator == keyword
        ));
    }
}

#[test]
fn clause_control_forms_build_the_existing_typed_nodes() {
    let Expr::IfStatement(statement) = expression("if a > 0 then b else c") else {
        panic!("expected an if statement");
    };
    assert_eq!(binary(&statement.condition).1.spelling(), ">");
    assert!(statement.else_clause.is_some());

    let Expr::ForLoop(statement) = expression("for i from 0 to 4 when i > 1 list i do print i")
    else {
        panic!("expected a for loop");
    };
    let range = statement.range.as_deref().expect("expected a range");
    assert!(range.range_start.is_some());
    assert!(range.range_end.is_some());
    assert!(statement.filter.is_some());
    assert!(statement.body.listed_value.is_some());
    assert!(statement.body.ignored_value.is_some());

    let Expr::WhileLoop(statement) = expression("while x < 10 do x = x + 1") else {
        panic!("expected a while loop");
    };
    assert_eq!(binary(&statement.condition).1.spelling(), "<");
    assert!(statement.body.ignored_value.is_some());

    let Expr::TryStatement(statement) = expression("try x then y except err do err") else {
        panic!("expected a try statement");
    };
    assert!(statement.then_clause.is_some());
    assert!(matches!(
        statement.fallback.as_deref(),
        Some(m2_syn::TryFallback::ExceptClause(_))
    ));
}

#[test]
fn nested_control_clauses_follow_their_12_and_16_stopper_levels() {
    for source in [
        "if a then if b then x else y",
        "if a then x else if b then y else z",
        "if try x then y else z then 1",
        "while for i in L list 1 do 2 do 3",
        "for i in L list for j in L list j do print 2",
        "p = x -> toString if instance(x, Package) then x else if package x =!= null then package x else Core",
    ] {
        let file = parse_native(source, SourceId(39))
            .unwrap_or_else(|error| panic!("`{source}` failed with {error:?}"));
        let normalized = file.to_code();
        parse_native(&normalized, SourceId(40)).unwrap_or_else(|error| {
            panic!("normalized `{normalized}` from `{source}` failed with {error:?}")
        });
    }
}

#[test]
fn incomplete_control_clauses_report_the_missing_component() {
    for source in [
        "if x",
        "if x then",
        "for i in list x",
        "while x",
        "try x except do x",
    ] {
        assert!(
            parse_native(source, SourceId(41)).is_err(),
            "`{source}` should be rejected"
        );
    }
}

#[test]
fn new_statement_parses_its_ordered_optional_clauses() {
    let Expr::NewStatement(statement) = expression("new HashTable of MutableHashTable from pairs")
    else {
        panic!("expected a new statement");
    };
    assert!(matches!(statement.class.as_ref(), Expr::Symbol(_)));
    assert!(matches!(statement.parent.as_deref(), Some(Expr::Symbol(_))));
    assert!(matches!(
        statement.instance.as_deref(),
        Some(Expr::Symbol(_))
    ));

    for source in ["new A", "new A of B", "new A from C"] {
        let file = parse_native(source, SourceId(42))
            .unwrap_or_else(|error| panic!("`{source}` failed with {error:?}"));
        let normalized = file.to_code();
        parse_native(&normalized, SourceId(43)).unwrap_or_else(|error| {
            panic!("normalized `{normalized}` from `{source}` failed with {error:?}")
        });
    }

    for source in ["new", "new A of", "new A from"] {
        assert!(
            matches!(
                parse_native(source, SourceId(44)),
                Err(NativeParseError::MissingOperand { .. })
            ),
            "`{source}` should require its missing operand"
        );
    }
}

#[test]
fn debug_clauses_distinguish_nullable_and_required_operands() {
    for source in ["step", "finish"] {
        let Expr::DebugClause(clause) = expression(source) else {
            panic!("`{source}` should be a debug clause");
        };
        assert!(clause.value.is_none());
    }

    for source in [
        "step x",
        "finish x",
        "shield x",
        "TEST x",
        "time x",
        "timing x",
        "breakpoint x",
        "elapsedTime x",
        "elapsedTiming x",
        "profile x",
    ] {
        let Expr::DebugClause(clause) = expression(source) else {
            panic!("`{source}` should be a debug clause");
        };
        assert!(clause.value.is_some());
    }

    for keyword in [
        "shield",
        "TEST",
        "time",
        "timing",
        "breakpoint",
        "elapsedTime",
        "elapsedTiming",
        "profile",
    ] {
        assert!(matches!(
            parse_native(keyword, SourceId(45)),
            Err(NativeParseError::MissingOperand { operator, .. }) if operator == keyword
        ));

        let source = format!("{keyword}\nx");
        assert_eq!(
            parse_native(&source, SourceId(46)).unwrap().elements.len(),
            1,
            "`{keyword}` should take its required value across a newline"
        );
    }
}

#[test]
fn quote_specifiers_turn_keyword_spellings_into_symbols() {
    let Expr::QuoteExpression(quote) = expression("symbol if") else {
        panic!("expected a quote expression");
    };
    let symbol = quote.token;
    assert_eq!(symbol.text, "if");
}

#[test]
fn core_keyword_aliases_share_their_unqualified_parse_behavior() {
    let Expr::IfStatement(statement) = expression("Core$if x Core$then y Core$else z") else {
        panic!("Core$if should parse as an if statement");
    };
    assert!(statement.else_clause.is_some());

    let Expr::ForLoop(_) = expression("Core$for i Core$in L Core$list i") else {
        panic!("qualified loop keywords should retain their parser behavior");
    };

    let Expr::NewStatement(statement) = expression("Core$new A Core$of B Core$from C") else {
        panic!("Core$new should parse as a new statement");
    };
    assert!(statement.parent.is_some());
    assert!(statement.instance.is_some());

    let Expr::QuoteExpression(quote) = expression("Core$symbol if") else {
        panic!("Core$symbol should parse as a quote specifier");
    };
    assert_eq!(quote.token.text, "if");
}

#[test]
fn core_aliases_affect_cells_without_aliasing_operators_or_recursive_names() {
    let file = parse_native("Core$if x\nCore$then y", SourceId(47)).unwrap();
    assert_eq!(file.elements.len(), 1);
    assert!(matches!(file.elements[0], AnyCell::ExpressionCell(_)));

    let ordinary = expression("Core$not x");
    let (left, _) = adjacent(&ordinary);
    assert!(matches!(left, Expr::Symbol(symbol) if symbol.text == "Core$not"));

    let recursive = expression("Core$Core$if x");
    let (left, _) = adjacent(&recursive);
    assert!(matches!(left, Expr::Symbol(symbol) if symbol.text == "Core$Core$if"));
}