1
use std::collections::VecDeque;
2

            
3
use crate::diagnostics::diagnostics_api::SymbolKind;
4
use crate::diagnostics::source_map::{HoverInfo, span_with_hover};
5
use crate::errors::{FatalParseError, RecoverableParseError};
6
use crate::expression::{parse_annotation_expression, parse_binary_expression, parse_expression};
7
use crate::parser::ParseContext;
8
use crate::parser::abstract_literal::parse_abstract;
9
use crate::parser::comprehension::parse_comprehension;
10
use crate::parser::domain::parse_domain;
11
use crate::parser::dominance::parse_pareto_expression;
12
use crate::parser::global_constraints::ELEMENT_ID;
13
use crate::util::{TypecheckingContext, named_children};
14
use crate::{field, named_child};
15

            
16
use conjure_cp_core::ast::{
17
    Atom, DeclarationKind, DeclarationPtr, Expression, GroundDomain, Literal, Metadata, Moo, Name,
18
    ReturnType, Typeable,
19
};
20

            
21
use tree_sitter::Node;
22
use ustr::Ustr;
23

            
24
26897345
pub fn parse_atom(
25
26897345
    ctx: &mut ParseContext,
26
26897345
    node: &Node,
27
26897345
) -> Result<Option<Expression>, FatalParseError> {
28
26897345
    match node.kind() {
29
        "atom" | "primary_atom" | "sub_atom_expr" => {
30
12844016
            let Some(inner) = named_child!(recover, ctx, node) else {
31
                return Ok(None);
32
            };
33
12844016
            parse_atom(ctx, &inner)
34
        }
35
        "metavar" => {
36
2769
            let Some(ident) = field!(recover, ctx, node, "identifier") else {
37
                return Ok(None);
38
            };
39
2769
            let name_str = &ctx.source_code[ident.start_byte()..ident.end_byte()];
40
2769
            Ok(Some(Expression::Metavar(
41
2769
                Metadata::new(),
42
2769
                Ustr::from(name_str),
43
2769
            )))
44
        }
45
        "identifier" => {
46
5912170
            let Some(var) = parse_variable(ctx, node)? else {
47
796
                return Ok(None);
48
            };
49
5911374
            Ok(Some(Expression::Atomic(Metadata::new(), var)))
50
        }
51
        "from_solution" => {
52
27459
            if ctx.root.kind() != "dominance_relation" {
53
                ctx.record_error(RecoverableParseError::new(
54
                    "fromSolution only allowed inside dominance relations".to_string(),
55
                    Some(node.range()),
56
                ));
57
                return Ok(None);
58
27459
            }
59

            
60
27459
            let Some(var_node) = field!(recover, ctx, node, "variable") else {
61
                return Ok(None);
62
            };
63
27459
            let Some(inner) = parse_variable(ctx, &var_node)? else {
64
                return Ok(None);
65
            };
66

            
67
27459
            Ok(Some(Expression::FromSolution(
68
27459
                Metadata::new(),
69
27459
                Moo::new(inner),
70
27459
            )))
71
        }
72
10155
        "pareto_expression" => parse_pareto_expression(ctx, node),
73
        "constant" => {
74
4983285
            let Some(lit) = parse_constant(ctx, node)? else {
75
270
                return Ok(None);
76
            };
77
4983015
            Ok(Some(Expression::Atomic(
78
4983015
                Metadata::new(),
79
4983015
                Atom::Literal(lit),
80
4983015
            )))
81
        }
82
        "matrix"
83
        | "record"
84
        | "variant"
85
        | "tuple"
86
        | "set_literal"
87
        | "mset_literal"
88
        | "sequence_literal"
89
        | "function_literal"
90
        | "relation_literal"
91
        | "partition_literal"
92
        | "permutation_literal" => {
93
1993551
            let Some(abs) = parse_abstract(ctx, node)? else {
94
297
                return Ok(None);
95
            };
96
1993254
            Ok(Some(Expression::AbstractLiteral(Metadata::new(), abs)))
97
        }
98
36234
        "flatten" => parse_flatten(ctx, node),
99
3915
        "element_id" => parse_element_id(ctx, node),
100
161650
        "table" | "negative_table" | "short_table" => parse_table(ctx, node),
101
775497
        "index_or_slice" => parse_index_or_slice(ctx, node),
102
67
        "annotation_expr" => parse_annotation_expression(ctx, node),
103
        // for now, assume is binary since powerset isn't implemented
104
        // TODO: add powerset support under "set_operation"
105
10695
        "set_operation" => parse_binary_expression(ctx, node),
106
69465
        "comprehension" => parse_comprehension(ctx, node),
107
        "defined_expr" | "range_expr" | "to_set_expr" | "to_mset_expr" | "to_relation_expr"
108
4186
        | "perm_inverse_expr" => parse_function_unary_operator(ctx, node),
109
        "enum_operator" => {
110
12
            let Some(argument) = field!(recover, ctx, node, "argument") else {
111
                return Ok(None);
112
            };
113
12
            let saved = ctx.typechecking_context;
114
12
            ctx.typechecking_context = TypecheckingContext::Unknown;
115
12
            let parsed = parse_expression(ctx, argument);
116
12
            ctx.typechecking_context = saved;
117
12
            let Some(expression) = parsed? else {
118
                return Ok(None);
119
            };
120
12
            if !matches!(expression.return_type(), ReturnType::EnumeratedType(_)) {
121
                ctx.record_error(RecoverableParseError::new(
122
                    "Expected an enum member".to_owned(),
123
                    Some(argument.range()),
124
                ));
125
                return Ok(None);
126
12
            }
127
12
            let Some(operator) = field!(recover, ctx, node, "operator") else {
128
                return Ok(None);
129
            };
130
            let constructor =
131
12
                if &ctx.source_code[operator.start_byte()..operator.end_byte()] == "pred" {
132
                    Expression::Pred
133
                } else {
134
12
                    Expression::Succ
135
                };
136
12
            Ok(Some(constructor(Metadata::new(), Moo::new(expression))))
137
        }
138
51549
        "apply_expr" => parse_apply_expr(ctx, node),
139
        "image_expr" | "image_set_expr" | "pre_image_expr" | "inverse_expr" | "compose_expr" => {
140
10265
            parse_function_binary_operator(ctx, node)
141
        }
142
81
        "restrict_expr" => parse_restrict_expr(ctx, node),
143
        "attribute_as_constraint_expr" => parse_attribute_as_constraint(ctx, node),
144
135
        "parts_expr" | "participants_expr" => parse_partition_unary_operator(ctx, node),
145
189
        "together_expr" | "apart_expr" | "party_expr" => parse_partition_binary_operator(ctx, node),
146
        _ => {
147
            ctx.record_error(RecoverableParseError::new(
148
                format!("Expected atom, got: {}", node.kind()),
149
                Some(node.range()),
150
            ));
151
            Ok(None)
152
        }
153
    }
154
26897345
}
155

            
156
36234
fn parse_flatten(
157
36234
    ctx: &mut ParseContext,
158
36234
    node: &Node,
159
36234
) -> Result<Option<Expression>, FatalParseError> {
160
    // add error and return early if we're in a set context, since flatten doesn't produce sets
161
36234
    if ctx.typechecking_context == TypecheckingContext::Set {
162
        ctx.record_error(RecoverableParseError::new(
163
            format!(
164
                "Type error: {}\n\tExpected: set\n\tGot: flatten",
165
                ctx.source_code[node.start_byte()..node.end_byte()].trim()
166
            ),
167
            Some(node.range()),
168
        ));
169
        return Ok(None);
170
36234
    }
171

            
172
36234
    let Some(expr_node) = field!(recover, ctx, node, "expression") else {
173
        return Ok(None);
174
    };
175
    // TODO: verify the atom is a matrix
176
36234
    let Some(expr) = parse_atom(ctx, &expr_node)? else {
177
        return Ok(None);
178
    };
179

            
180
36234
    if let Some(depth_node) = node.child_by_field_name("depth") {
181
        let Some(depth) = parse_int(ctx, &depth_node) else {
182
            return Ok(None);
183
        };
184
        let depth_expression =
185
            Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(depth)));
186
        Ok(Some(Expression::Flatten(
187
            Metadata::new(),
188
            Some(Moo::new(depth_expression)),
189
            Moo::new(expr),
190
        )))
191
    } else {
192
36234
        Ok(Some(Expression::Flatten(
193
36234
            Metadata::new(),
194
36234
            None,
195
36234
            Moo::new(expr),
196
36234
        )))
197
    }
198
36234
}
199

            
200
161650
fn parse_table(ctx: &mut ParseContext, node: &Node) -> Result<Option<Expression>, FatalParseError> {
201
    // add error and return early if we're in a set context, since tables aren't allowed there
202
161650
    if ctx.typechecking_context == TypecheckingContext::Set {
203
        ctx.record_error(RecoverableParseError::new(
204
            format!(
205
                "Type error: {}\n\tExpected: set\n\tGot: table",
206
                ctx.source_code[node.start_byte()..node.end_byte()].trim()
207
            ),
208
            Some(node.range()),
209
        ));
210
        return Ok(None);
211
161650
    }
212

            
213
    // the variables and rows can contain arbitrary expressions, so we temporarily set the context to Unknown to avoid typechecking errors
214
161650
    let saved_context = ctx.typechecking_context;
215
161650
    ctx.typechecking_context = TypecheckingContext::Unknown;
216

            
217
161650
    let Some(variables_node) = field!(recover, ctx, node, "variables") else {
218
        return Ok(None);
219
    };
220
161650
    let Some(variables) = parse_table_operand(ctx, &variables_node)? else {
221
        return Ok(None);
222
    };
223

            
224
161650
    let Some(rows_node) = field!(recover, ctx, node, "rows") else {
225
        return Ok(None);
226
    };
227
161650
    let Some(rows) = parse_table_operand(ctx, &rows_node)? else {
228
        return Ok(None);
229
    };
230

            
231
161650
    ctx.typechecking_context = saved_context;
232

            
233
161650
    match node.kind() {
234
68581
        "table" => Ok(Some(Expression::Table(
235
68581
            Metadata::new(),
236
68581
            Moo::new(variables),
237
68581
            Moo::new(rows),
238
68581
        ))),
239
56997
        "short_table" => Ok(Some(Expression::ShortTable(
240
56997
            Metadata::new(),
241
56997
            Moo::new(variables),
242
56997
            Moo::new(rows),
243
56997
        ))),
244
36072
        "negative_table" => Ok(Some(Expression::NegativeTable(
245
36072
            Metadata::new(),
246
36072
            Moo::new(variables),
247
36072
            Moo::new(rows),
248
36072
        ))),
249
        _ => {
250
            ctx.record_error(RecoverableParseError::new(
251
                format!(
252
                    "Expected 'table' or 'negative_table', got: '{}'",
253
                    node.kind()
254
                ),
255
                Some(node.range()),
256
            ));
257
            Ok(None)
258
        }
259
    }
260
161650
}
261

            
262
472637
pub fn parse_table_operand(
263
472637
    ctx: &mut ParseContext,
264
472637
    node: &Node,
265
472637
) -> Result<Option<Expression>, FatalParseError> {
266
472637
    match node.kind() {
267
        "identifier" | "constant" | "matrix" | "index_or_slice" | "flatten" => {
268
154334
            parse_atom(ctx, node)
269
        }
270
        "sub_arith_expr" | "negative_expr" | "abs_value" | "factorial_expr" | "arithmetic_expr"
271
        | "product_expr" | "sum_expr" | "exponent" | "bool_expr" | "comparison_expr" => {
272
            parse_expression(ctx, *node)
273
        }
274
318303
        _ => parse_expression(ctx, *node),
275
    }
276
472637
}
277

            
278
3915
fn parse_element_id(
279
3915
    ctx: &mut ParseContext,
280
3915
    node: &Node,
281
3915
) -> Result<Option<Expression>, FatalParseError> {
282
3915
    if ctx.typechecking_context == TypecheckingContext::Set {
283
        ctx.record_error(RecoverableParseError::new(
284
            format!(
285
                "Type error: {}\n\tExpected: set\n\tGot: elementId",
286
                ctx.source_code[node.start_byte()..node.end_byte()].trim()
287
            ),
288
            Some(node.range()),
289
        ));
290
        return Ok(None);
291
3915
    }
292

            
293
3915
    let saved_context = ctx.typechecking_context;
294
3915
    ctx.typechecking_context = TypecheckingContext::Unknown;
295

            
296
3915
    let Some(matrix_node) = field!(recover, ctx, node, "matrix") else {
297
        return Ok(None);
298
    };
299
3915
    let Some(matrix) = parse_table_operand(ctx, &matrix_node)? else {
300
        ctx.typechecking_context = saved_context;
301
        return Ok(None);
302
    };
303

            
304
3915
    let Some(value_node) = field!(recover, ctx, node, "value") else {
305
        ctx.typechecking_context = saved_context;
306
        return Ok(None);
307
    };
308
3915
    let Some(value) = parse_expression(ctx, value_node)? else {
309
        ctx.typechecking_context = saved_context;
310
        return Ok(None);
311
    };
312

            
313
3915
    ctx.typechecking_context = saved_context;
314

            
315
3915
    let operator_node = node.child(0).unwrap();
316
3915
    ctx.add_span_and_doc_hover(&operator_node, ELEMENT_ID, SymbolKind::Function, None, None);
317

            
318
3915
    Ok(Some(Expression::ElementId(
319
3915
        Metadata::new(),
320
3915
        Moo::new(matrix),
321
3915
        Moo::new(value),
322
3915
    )))
323
3915
}
324

            
325
/// Parses the single argument of a unary function-call-style operator (`defined`, `range`,
326
/// `toSet`, `toMSet`, `toRelation`): keyword immediately followed by a parenthesised argument.
327
/// The argument's type varies by operator (function, set, mset, relation), so typechecking
328
/// context is relaxed to `Unknown` while parsing it, mirroring `parse_flatten`/`parse_element_id`.
329
4186
fn parse_function_unary_operator(
330
4186
    ctx: &mut ParseContext,
331
4186
    node: &Node,
332
4186
) -> Result<Option<Expression>, FatalParseError> {
333
4186
    let field_name = if node.kind() == "perm_inverse_expr" {
334
1
        "permutation"
335
    } else {
336
4185
        "function"
337
    };
338

            
339
4186
    let saved_context = ctx.typechecking_context;
340
4186
    ctx.typechecking_context = TypecheckingContext::Unknown;
341

            
342
4186
    let Some(function_node) = field!(recover, ctx, node, field_name) else {
343
        ctx.typechecking_context = saved_context;
344
        return Ok(None);
345
    };
346
4186
    let Some(function) = parse_expression(ctx, function_node)? else {
347
        ctx.typechecking_context = saved_context;
348
        return Ok(None);
349
    };
350

            
351
4186
    ctx.typechecking_context = saved_context;
352

            
353
4186
    match node.kind() {
354
1242
        "defined_expr" => Ok(Some(Expression::Defined(
355
1242
            Metadata::new(),
356
1242
            Moo::new(function),
357
1242
        ))),
358
2781
        "range_expr" => Ok(Some(Expression::Range(Metadata::new(), Moo::new(function)))),
359
81
        "to_set_expr" => Ok(Some(Expression::ToSet(Metadata::new(), Moo::new(function)))),
360
27
        "to_mset_expr" => Ok(Some(Expression::ToMSet(
361
27
            Metadata::new(),
362
27
            Moo::new(function),
363
27
        ))),
364
54
        "to_relation_expr" => Ok(Some(Expression::ToRelation(
365
54
            Metadata::new(),
366
54
            Moo::new(function),
367
54
        ))),
368
1
        "perm_inverse_expr" => Ok(Some(Expression::PermInverse(
369
1
            Metadata::new(),
370
1
            Moo::new(function),
371
1
        ))),
372
        _ => {
373
            ctx.record_error(RecoverableParseError::new(
374
                format!("Expected a function operator, got: {}", node.kind()),
375
                Some(node.range()),
376
            ));
377
            Ok(None)
378
        }
379
    }
380
4186
}
381

            
382
/// Parses an attribute-as-constraint predicate, e.g. `reflexive(r)` or `size(s, 3)`: a keyword
383
/// naming the attribute, immediately followed by a parenthesised target and an optional value.
384
/// Arity is not checked here (the grammar allows any attribute name with or without a value); a
385
/// later pass validates it against the target's actual domain kind.
386
fn parse_attribute_as_constraint(
387
    ctx: &mut ParseContext,
388
    node: &Node,
389
) -> Result<Option<Expression>, FatalParseError> {
390
    let Some(attr_node) = field!(recover, ctx, node, "attribute") else {
391
        return Ok(None);
392
    };
393
    let attr = Ustr::from(&ctx.source_code[attr_node.start_byte()..attr_node.end_byte()]);
394

            
395
    let saved_context = ctx.typechecking_context;
396
    ctx.typechecking_context = TypecheckingContext::Unknown;
397

            
398
    let Some(target_node) = field!(recover, ctx, node, "target") else {
399
        ctx.typechecking_context = saved_context;
400
        return Ok(None);
401
    };
402
    let Some(target) = parse_expression(ctx, target_node)? else {
403
        ctx.typechecking_context = saved_context;
404
        return Ok(None);
405
    };
406

            
407
    let value = match node.child_by_field_name("value") {
408
        Some(value_node) => match parse_expression(ctx, value_node)? {
409
            Some(value_expr) => Some(Moo::new(value_expr)),
410
            None => {
411
                ctx.typechecking_context = saved_context;
412
                return Ok(None);
413
            }
414
        },
415
        None => None,
416
    };
417

            
418
    ctx.typechecking_context = saved_context;
419

            
420
    Ok(Some(Expression::AttributeAsConstraint(
421
        Metadata::new(),
422
        Moo::new(target),
423
        attr,
424
        value,
425
    )))
426
}
427

            
428
/// Parses a unary partition operator (`parts`, `participants`): keyword immediately followed by
429
/// a parenthesised partition expression.
430
135
fn parse_partition_unary_operator(
431
135
    ctx: &mut ParseContext,
432
135
    node: &Node,
433
135
) -> Result<Option<Expression>, FatalParseError> {
434
135
    let saved_context = ctx.typechecking_context;
435
135
    ctx.typechecking_context = TypecheckingContext::Unknown;
436

            
437
135
    let Some(partition_node) = field!(recover, ctx, node, "partition") else {
438
        ctx.typechecking_context = saved_context;
439
        return Ok(None);
440
    };
441
135
    let Some(partition) = parse_expression(ctx, partition_node)? else {
442
27
        ctx.typechecking_context = saved_context;
443
27
        return Ok(None);
444
    };
445

            
446
108
    ctx.typechecking_context = saved_context;
447

            
448
108
    match node.kind() {
449
54
        "parts_expr" => Ok(Some(Expression::Parts(
450
54
            Metadata::new(),
451
54
            Moo::new(partition),
452
54
        ))),
453
54
        "participants_expr" => Ok(Some(Expression::Participants(
454
54
            Metadata::new(),
455
54
            Moo::new(partition),
456
54
        ))),
457
        _ => {
458
            ctx.record_error(RecoverableParseError::new(
459
                format!("Expected a partition operator, got: {}", node.kind()),
460
                Some(node.range()),
461
            ));
462
            Ok(None)
463
        }
464
    }
465
135
}
466

            
467
/// Parses the two arguments of a binary partition operator (`together`, `apart`, `party`):
468
/// keyword immediately followed by a parenthesised, comma-separated argument pair. `party_expr`
469
/// uses an `element`/`partition` field pair; `together_expr`/`apart_expr` use `elements`/
470
/// `partition`.
471
189
fn parse_partition_binary_operator(
472
189
    ctx: &mut ParseContext,
473
189
    node: &Node,
474
189
) -> Result<Option<Expression>, FatalParseError> {
475
189
    let first_field = if node.kind() == "party_expr" {
476
54
        "element"
477
    } else {
478
135
        "elements"
479
    };
480

            
481
189
    let saved_context = ctx.typechecking_context;
482
189
    ctx.typechecking_context = TypecheckingContext::Unknown;
483

            
484
189
    let Some(first_node) = field!(recover, ctx, node, first_field) else {
485
        ctx.typechecking_context = saved_context;
486
        return Ok(None);
487
    };
488
189
    let Some(first) = parse_expression(ctx, first_node)? else {
489
        ctx.typechecking_context = saved_context;
490
        return Ok(None);
491
    };
492

            
493
189
    let Some(partition_node) = field!(recover, ctx, node, "partition") else {
494
        ctx.typechecking_context = saved_context;
495
        return Ok(None);
496
    };
497
189
    let Some(partition) = parse_expression(ctx, partition_node)? else {
498
27
        ctx.typechecking_context = saved_context;
499
27
        return Ok(None);
500
    };
501

            
502
162
    ctx.typechecking_context = saved_context;
503

            
504
162
    match node.kind() {
505
54
        "together_expr" => Ok(Some(Expression::Together(
506
54
            Metadata::new(),
507
54
            Moo::new(first),
508
54
            Moo::new(partition),
509
54
        ))),
510
54
        "apart_expr" => Ok(Some(Expression::Apart(
511
54
            Metadata::new(),
512
54
            Moo::new(first),
513
54
            Moo::new(partition),
514
54
        ))),
515
54
        "party_expr" => Ok(Some(Expression::Party(
516
54
            Metadata::new(),
517
54
            Moo::new(first),
518
54
            Moo::new(partition),
519
54
        ))),
520
        _ => {
521
            ctx.record_error(RecoverableParseError::new(
522
                format!("Expected a partition operator, got: {}", node.kind()),
523
                Some(node.range()),
524
            ));
525
            Ok(None)
526
        }
527
    }
528
189
}
529

            
530
/// Parses the two arguments of a binary function-call-style operator (`image`, `imageSet`,
531
/// `preImage`, `inverse`): keyword immediately followed by a parenthesised, comma-separated
532
/// argument pair. `inverse_expr` uses `left`/`right` fields; the rest use `function`/`argument`.
533
/// Parses function or sequence application, `f(x)`, into the `image(f, x)` it is sugar for.
534
///
535
/// Several arguments make a tuple, so `f(1, 2)` and `f((1, 2))` mean the same thing, as in Conjure.
536
51549
fn parse_apply_expr(
537
51549
    ctx: &mut ParseContext,
538
51549
    node: &Node,
539
51549
) -> Result<Option<Expression>, FatalParseError> {
540
51549
    let saved_context = ctx.typechecking_context;
541
51549
    ctx.typechecking_context = TypecheckingContext::Unknown;
542

            
543
51549
    let parsed = (|ctx: &mut ParseContext| {
544
51549
        let Some(function_node) = field!(recover, ctx, node, "function") else {
545
            return Ok(None);
546
        };
547
51549
        let Some(function) = parse_expression(ctx, function_node)? else {
548
27
            return Ok(None);
549
        };
550

            
551
51522
        let mut cursor = node.walk();
552
51522
        let mut arguments = Vec::new();
553
51522
        for argument_node in node.children_by_field_name("argument", &mut cursor) {
554
51522
            let Some(argument) = parse_expression(ctx, argument_node)? else {
555
                return Ok(None);
556
            };
557
51522
            arguments.push(argument);
558
        }
559

            
560
51522
        let argument = match <[Expression; 1]>::try_from(arguments) {
561
51522
            Ok([argument]) => argument,
562
            Err(arguments) => Expression::AbstractLiteral(
563
                Metadata::new(),
564
                conjure_cp_core::ast::AbstractLiteral::Tuple(arguments),
565
            ),
566
        };
567

            
568
51522
        Ok(Some(Expression::Image(
569
51522
            Metadata::new(),
570
51522
            Moo::new(function),
571
51522
            Moo::new(argument),
572
51522
        )))
573
51549
    })(ctx);
574

            
575
51549
    ctx.typechecking_context = saved_context;
576
51549
    parsed
577
51549
}
578

            
579
10265
fn parse_function_binary_operator(
580
10265
    ctx: &mut ParseContext,
581
10265
    node: &Node,
582
10265
) -> Result<Option<Expression>, FatalParseError> {
583
10265
    let (first_field, second_field) = if matches!(node.kind(), "inverse_expr" | "compose_expr") {
584
137
        ("left", "right")
585
    } else {
586
10128
        ("function", "argument")
587
    };
588

            
589
10265
    let saved_context = ctx.typechecking_context;
590
10265
    ctx.typechecking_context = TypecheckingContext::Unknown;
591

            
592
10265
    let Some(first_node) = field!(recover, ctx, node, first_field) else {
593
        ctx.typechecking_context = saved_context;
594
        return Ok(None);
595
    };
596
10265
    let Some(first) = parse_expression(ctx, first_node)? else {
597
        ctx.typechecking_context = saved_context;
598
        return Ok(None);
599
    };
600

            
601
10265
    let Some(second_node) = field!(recover, ctx, node, second_field) else {
602
        ctx.typechecking_context = saved_context;
603
        return Ok(None);
604
    };
605
10265
    let Some(second) = parse_expression(ctx, second_node)? else {
606
        ctx.typechecking_context = saved_context;
607
        return Ok(None);
608
    };
609

            
610
10265
    ctx.typechecking_context = saved_context;
611

            
612
10265
    match node.kind() {
613
9966
        "image_expr" => Ok(Some(Expression::Image(
614
9966
            Metadata::new(),
615
9966
            Moo::new(first),
616
9966
            Moo::new(second),
617
9966
        ))),
618
81
        "image_set_expr" => Ok(Some(Expression::ImageSet(
619
81
            Metadata::new(),
620
81
            Moo::new(first),
621
81
            Moo::new(second),
622
81
        ))),
623
81
        "pre_image_expr" => Ok(Some(Expression::PreImage(
624
81
            Metadata::new(),
625
81
            Moo::new(first),
626
81
            Moo::new(second),
627
81
        ))),
628
136
        "inverse_expr" => Ok(Some(Expression::Inverse(
629
136
            Metadata::new(),
630
136
            Moo::new(first),
631
136
            Moo::new(second),
632
136
        ))),
633
1
        "compose_expr" => Ok(Some(Expression::Compose(
634
1
            Metadata::new(),
635
1
            Moo::new(first),
636
1
            Moo::new(second),
637
1
        ))),
638
        _ => {
639
            ctx.record_error(RecoverableParseError::new(
640
                format!("Expected a function operator, got: {}", node.kind()),
641
                Some(node.range()),
642
            ));
643
            Ok(None)
644
        }
645
    }
646
10265
}
647

            
648
/// Parses `restrict(f, dom)`. Unlike the other function operators, the second argument is
649
/// syntactically a domain rather than an expression. `Expression::Restrict` still stores it as
650
/// an `Expression` though (its `domain_of()` is called directly on that operand): a bare domain
651
/// name (e.g. `letting D be domain int(0,2)` used as `restrict(f, D)`) becomes a plain reference
652
/// to that declaration, matching the shape the via-conjure/JSON import path produces. An inline
653
/// domain literal (not just a name) is wrapped in a `DomainAnnotation` so `domain_of()` still
654
/// resolves correctly, though it will not print back out identically (no exhaustive/roundtrip
655
/// case in this codebase currently needs that form).
656
81
fn parse_restrict_expr(
657
81
    ctx: &mut ParseContext,
658
81
    node: &Node,
659
81
) -> Result<Option<Expression>, FatalParseError> {
660
81
    let saved_context = ctx.typechecking_context;
661
81
    ctx.typechecking_context = TypecheckingContext::Unknown;
662

            
663
81
    let Some(function_node) = field!(recover, ctx, node, "function") else {
664
        ctx.typechecking_context = saved_context;
665
        return Ok(None);
666
    };
667
81
    let Some(function) = parse_expression(ctx, function_node)? else {
668
        ctx.typechecking_context = saved_context;
669
        return Ok(None);
670
    };
671

            
672
81
    let Some(domain_node) = field!(recover, ctx, node, "domain") else {
673
        ctx.typechecking_context = saved_context;
674
        return Ok(None);
675
    };
676
81
    let Some(domain_expr) = parse_restrict_domain_argument(ctx, domain_node)? else {
677
        ctx.typechecking_context = saved_context;
678
        return Ok(None);
679
    };
680

            
681
81
    ctx.typechecking_context = saved_context;
682

            
683
81
    Ok(Some(Expression::Restrict(
684
81
        Metadata::new(),
685
81
        Moo::new(function),
686
81
        Moo::new(domain_expr),
687
81
    )))
688
81
}
689

            
690
81
fn parse_restrict_domain_argument(
691
81
    ctx: &mut ParseContext,
692
81
    domain_node: Node,
693
81
) -> Result<Option<Expression>, FatalParseError> {
694
    // Unwrap the generic "domain"/"annotation_domain" wrapper node(s) to see what's underneath.
695
81
    let mut inner = domain_node;
696
162
    while matches!(inner.kind(), "domain" | "annotation_domain") {
697
81
        let Some(child) = inner.child(0) else {
698
            break;
699
        };
700
81
        inner = child;
701
    }
702

            
703
81
    if inner.kind() == "identifier" {
704
        // A name referring to a domain: keep it as a plain reference expression, so it prints
705
        // back out as just the name (e.g. `restrict(f,D)`).
706
81
        return parse_atom(ctx, &inner);
707
    }
708

            
709
    let Some(domain) = parse_domain(ctx, domain_node)? else {
710
        return Ok(None);
711
    };
712
    Ok(Some(Expression::DomainAnnotation(
713
        Metadata::new(),
714
        Moo::new(Expression::Atomic(
715
            Metadata::new(),
716
            Atom::Literal(Literal::Bool(true)),
717
        )),
718
        domain,
719
    )))
720
81
}
721

            
722
775497
fn parse_index_or_slice(
723
775497
    ctx: &mut ParseContext,
724
775497
    node: &Node,
725
775497
) -> Result<Option<Expression>, FatalParseError> {
726
    // add error and return early if we're in a set context, since indexing/slicing doesn't produce sets
727
775497
    if ctx.typechecking_context == TypecheckingContext::Set {
728
        ctx.record_error(RecoverableParseError::new(
729
            format!(
730
                "Type error: {}\n\tExpected: set\n\tGot: index or slice",
731
                ctx.source_code[node.start_byte()..node.end_byte()].trim()
732
            ),
733
            Some(node.range()),
734
        ));
735
        return Ok(None);
736
775497
    }
737

            
738
    // Save current context and temporarily set to Unknown for the collection
739
775497
    let saved_context = ctx.typechecking_context;
740
775497
    let saved_inner_context = ctx.inner_typechecking_context;
741
775497
    ctx.typechecking_context = TypecheckingContext::Unknown;
742
    let mut collection: Expression;
743
775497
    match parse_atom(ctx, &field!(node, "collection"))? {
744
775470
        Some(expr) => collection = expr,
745
27
        None => return Ok(None),
746
    }
747
775470
    ctx.typechecking_context = saved_context;
748

            
749
775470
    let indices_field = field!(node, "indices");
750
775470
    let mut idx_nodes = named_children(&indices_field).collect::<VecDeque<_>>();
751

            
752
    // If LHS is a record, parse first index as a record field
753
775470
    if let ReturnType::Record(ents) | ReturnType::Variant(ents) = collection.return_type() {
754
43497
        let idx = idx_nodes
755
43497
            .pop_front()
756
43497
            .ok_or(FatalParseError::internal_error(
757
43497
                "Expected at least one indexing expression".into(),
758
43497
                Some(indices_field.range()),
759
43497
            ))?;
760
43497
        let name = Name::user(ctx.source_code[idx.start_byte()..idx.end_byte()].trim());
761
65232
        let has_name = ents.iter().any(|e| e.name == name);
762
43497
        if !has_name {
763
            return Err(FatalParseError::internal_error(
764
                format!("`{name}` is not a valid field name for `{collection}`"),
765
                Some(idx.range()),
766
            ));
767
43497
        }
768
43497
        collection = Expression::RecordField(Metadata::new(), Moo::new(collection), name);
769

            
770
        // If there are no more indices, return the record field directly
771
43497
        if idx_nodes.is_empty() {
772
43497
            return Ok(typecheck_index_or_slice(
773
43497
                ctx,
774
43497
                node,
775
43497
                collection,
776
43497
                saved_context,
777
43497
                saved_inner_context,
778
43497
            ));
779
        }
780
731973
    }
781

            
782
    // Parse the rest of the indices as normal
783
731973
    let first_index_range = idx_nodes.front().map(|idx| idx.range());
784
731973
    let mut indices = Vec::new();
785
731973
    for idx_node in idx_nodes {
786
927817
        indices.push(parse_index(ctx, &idx_node)?);
787
    }
788

            
789
920191
    let has_null_idx = indices.iter().any(|idx| idx.is_none());
790
731973
    if let Some((_, index_domains)) = collection.domain_of().and_then(|domain| domain.as_matrix())
791
648021
        && index_domains.len() != indices.len()
792
    {
793
24
        let operation = if has_null_idx { "slice" } else { "index" };
794
24
        ctx.record_error(RecoverableParseError::new(
795
24
            format!(
796
24
                "Invalid matrix {operation}: expected {} indices (one per dimension), but got {}",
797
24
                index_domains.len(),
798
24
                indices.len()
799
24
            ),
800
24
            Some(indices_field.range()),
801
24
        ));
802
24
        return Ok(None);
803
731949
    }
804

            
805
731949
    if !has_null_idx
806
701549
        && let ReturnType::Tuple(fields) = collection.return_type()
807
83385
        && let Some(Some(Expression::Atomic(_, Atom::Literal(Literal::Int(index))))) =
808
83385
            indices.first()
809
    {
810
83385
        let valid_index = index
811
83385
            .checked_sub(1)
812
83385
            .and_then(|index| usize::try_from(index).ok())
813
83385
            .is_some_and(|index| index < fields.len());
814

            
815
83385
        if !valid_index {
816
6
            ctx.record_error(RecoverableParseError::new(
817
6
                format!(
818
6
                    "Tuple index {index} is out of bounds; valid indices are 1..{}",
819
6
                    fields.len()
820
6
                ),
821
6
                Some(first_index_range.unwrap_or(indices_field.range())),
822
6
            ));
823
6
            return Ok(None);
824
83379
        }
825
648564
    }
826

            
827
731943
    let expression = if has_null_idx {
828
        // It's a slice
829
30400
        Expression::UnsafeSlice(Metadata::new(), Moo::new(collection), indices)
830
    } else {
831
        // It's an index
832
872753
        let idx_exprs: Vec<Expression> = indices.into_iter().map(|idx| idx.unwrap()).collect();
833
701543
        Expression::UnsafeIndex(Metadata::new(), Moo::new(collection), idx_exprs)
834
    };
835

            
836
731943
    Ok(typecheck_index_or_slice(
837
731943
        ctx,
838
731943
        node,
839
731943
        expression,
840
731943
        saved_context,
841
731943
        saved_inner_context,
842
731943
    ))
843
775497
}
844

            
845
775440
fn typecheck_index_or_slice(
846
775440
    ctx: &mut ParseContext,
847
775440
    node: &Node,
848
775440
    expression: Expression,
849
775440
    context: TypecheckingContext,
850
775440
    inner_context: TypecheckingContext,
851
775440
) -> Option<Expression> {
852
775440
    let return_type = expression.return_type();
853
775440
    let mismatch = if let Some(expected) = expected_scalar_type(context)
854
152701
        && return_type != expected
855
15780
        && return_type != ReturnType::Unknown
856
    {
857
12
        Some((expected, return_type))
858
775428
    } else if let Some(expected) = expected_scalar_type(inner_context)
859
13107
        && let Some(element_type) = return_type.elem_type()
860
12
        && element_type != expected
861
12
        && element_type != ReturnType::Unknown
862
    {
863
12
        Some((expected, element_type))
864
    } else {
865
775416
        None
866
    };
867

            
868
775440
    if let Some((expected, actual)) = mismatch {
869
24
        ctx.record_error(RecoverableParseError::new(
870
24
            format!(
871
24
                "Type error: {}\n\tExpected: {expected}\n\tGot: {actual}",
872
24
                ctx.source_code[node.start_byte()..node.end_byte()].trim()
873
24
            ),
874
24
            Some(node.range()),
875
24
        ));
876
24
        None
877
    } else {
878
775416
        Some(expression)
879
    }
880
775440
}
881

            
882
1550868
fn expected_scalar_type(context: TypecheckingContext) -> Option<ReturnType> {
883
1550868
    match context {
884
29628
        TypecheckingContext::Boolean => Some(ReturnType::Bool),
885
136180
        TypecheckingContext::Arithmetic => Some(ReturnType::Int),
886
1385060
        _ => None,
887
    }
888
1550868
}
889

            
890
927817
fn parse_index(ctx: &mut ParseContext, node: &Node) -> Result<Option<Expression>, FatalParseError> {
891
927817
    match node.kind() {
892
        "arithmetic_expr" | "atom" => {
893
896421
            let saved_context = ctx.typechecking_context;
894
896421
            ctx.typechecking_context = TypecheckingContext::Unknown;
895

            
896
            // TODO: add collection-aware index typechecking.
897
            // For tuple/matrix/set-like indexing, indices should be arithmetic.
898
            // For record field access, index atoms should resolve to valid field names.
899
            // This requires checking index expression together with the indexed collection type.
900

            
901
896421
            let Some(expr) = parse_expression(ctx, *node)? else {
902
                return Ok(None);
903
            };
904

            
905
896421
            ctx.typechecking_context = saved_context;
906
896421
            Ok(Some(expr))
907
        }
908
31396
        "null_index" => Ok(None),
909
        _ => {
910
            ctx.record_error(RecoverableParseError::new(
911
                format!("Expected an index, got: '{}'", node.kind()),
912
                Some(node.range()),
913
            ));
914
            Ok(None)
915
        }
916
    }
917
927817
}
918

            
919
5939629
fn parse_variable(ctx: &mut ParseContext, node: &Node) -> Result<Option<Atom>, FatalParseError> {
920
5939629
    let raw_name = &ctx.source_code[node.start_byte()..node.end_byte()];
921

            
922
5939629
    let name = Name::user(raw_name.trim());
923
5939629
    if let Some(symbols) = &ctx.symbols {
924
        let lookup_result = {
925
5939629
            let symbols_read = symbols.read();
926
5939629
            symbols_read.lookup(&name)
927
        };
928

            
929
5939629
        if let Some(decl) = lookup_result {
930
5939346
            let symbol_kind = match &decl.kind().clone() as &DeclarationKind {
931
4751670
                DeclarationKind::Find(_) | DeclarationKind::FindAuxiliary(_) => SymbolKind::FindVar,
932
350632
                DeclarationKind::Given(_) => SymbolKind::GivenVar,
933
255689
                DeclarationKind::ValueLetting(_, _) => SymbolKind::LettingVar,
934
                DeclarationKind::TemporaryValueLetting(_) => SymbolKind::LettingVar,
935
135
                DeclarationKind::DomainLetting(_) => SymbolKind::LettingVar,
936
507249
                DeclarationKind::Quantified(..) => SymbolKind::FindVar,
937
73971
                DeclarationKind::QuantifiedExpr(..) => SymbolKind::FindVar,
938
                DeclarationKind::EnumeratedType(_) | DeclarationKind::UnnamedType(_) => {
939
                    ctx.record_error(RecoverableParseError::new(
940
                        format!("The identifier '{name}' is a type, not a value"),
941
                        Some(node.range()),
942
                    ));
943
                    return Ok(None);
944
                }
945
                _ => SymbolKind::LettingVar,
946
            };
947

            
948
            let hover = HoverInfo {
949
5939346
                description: format!("Variable: {name}"),
950
5939346
                doc_key: None,
951
5939346
                kind: Some(symbol_kind),
952
5939346
                ty: decl.domain().map(|d| d.to_string()),
953
5939346
                decl_span: ctx.lookup_decl_span(&name),
954
            };
955
5939346
            span_with_hover(node, ctx.source_code, ctx.source_map, hover);
956

            
957
            // Type check the variable against the expected context
958
5939346
            if let Some(error_msg) = typecheck_variable(&decl, ctx.typechecking_context, raw_name) {
959
513
                ctx.record_error(RecoverableParseError::new(error_msg, Some(node.range())));
960
513
                return Ok(None);
961
5938833
            }
962

            
963
5938833
            Ok(Some(Atom::Reference(conjure_cp_core::ast::Reference::new(
964
5938833
                decl,
965
5938833
            ))))
966
        } else {
967
283
            ctx.record_error(RecoverableParseError::new(
968
283
                format!("The identifier '{}' is not defined", raw_name),
969
283
                Some(node.range()),
970
283
            ));
971
283
            Ok(None)
972
        }
973
    } else {
974
        ctx.record_error(RecoverableParseError::new(
975
            format!("Symbol table missing when parsing variable '{raw_name}'"),
976
            Some(node.range()),
977
        ));
978
        Ok(None)
979
    }
980
5939629
}
981

            
982
/// Type check a variable declaration against the expected expression context.
983
/// Returns an error message if the variable type doesn't match the context.
984
5939346
fn typecheck_variable(
985
5939346
    decl: &DeclarationPtr,
986
5939346
    context: TypecheckingContext,
987
5939346
    raw_name: &str,
988
5939346
) -> Option<String> {
989
    // Only type check when context is known
990
5939346
    if context == TypecheckingContext::Unknown {
991
4044538
        return None;
992
1894808
    }
993

            
994
    // Get the variable's domain and resolve it
995
1894808
    let domain = decl.domain()?;
996
1890812
    let ground_domain = domain.resolve().ok()?;
997

            
998
    // Determine what type is expected
999
1862214
    let expected = match context {
496288
        TypecheckingContext::Boolean => "bool",
1164605
        TypecheckingContext::Arithmetic => "int",
56601
        TypecheckingContext::Set => "set",
38043
        TypecheckingContext::SetOrMatrix => "set or matrix",
28674
        TypecheckingContext::MSet => "mset",
72738
        TypecheckingContext::Matrix => "matrix",
        TypecheckingContext::Tuple => "tuple",
3942
        TypecheckingContext::Record => "record",
        TypecheckingContext::Partition => "partition",
540
        TypecheckingContext::Permutation => "permutation",
783
        TypecheckingContext::Sequence => "sequence",
        TypecheckingContext::Function => "function",
        TypecheckingContext::Relation => "relation",
        TypecheckingContext::Unknown => return None, // shouldn't reach here
    };
    // Determine what type we actually have
1862214
    let actual = match ground_domain.as_ref() {
        GroundDomain::Empty(_) => "empty",
496261
        GroundDomain::Bool => "bool",
1164632
        GroundDomain::Int(_, _) => "int",
        GroundDomain::Tuple(_, _) => "tuple",
3969
        GroundDomain::Record(_, _) => "record",
        GroundDomain::Variant(_, _) => "variant",
78570
        GroundDomain::Matrix(_, _, _) => "matrix",
783
        GroundDomain::Sequence(_, _) => "sequence",
88785
        GroundDomain::Set(_, _) => "set",
28674
        GroundDomain::MSet(_, _) => "mset",
        GroundDomain::Function(_, _, _) => "function",
        GroundDomain::Relation(_, _) => "relation",
        GroundDomain::Partition(_, _) => "partition",
        GroundDomain::EnumeratedType(_, _) => "enum",
        GroundDomain::UnnamedType(_) => "unnamed",
540
        GroundDomain::Permutation(_, _) => "permutation",
    };
    // If types match, no error
1862214
    if expected == actual
38529
        || (context == TypecheckingContext::SetOrMatrix && matches!(actual, "set" | "matrix"))
    {
1861701
        return None;
513
    }
    // Otherwise, report the type mismatch
513
    Some(format!(
513
        "Type error: {}\n\tExpected: {}\n\tGot: {}",
513
        raw_name, expected, actual
513
    ))
5939346
}
4983285
fn parse_constant(ctx: &mut ParseContext, node: &Node) -> Result<Option<Literal>, FatalParseError> {
4983285
    let Some(inner) = named_child!(recover, ctx, node) else {
        return Ok(None);
    };
4983285
    let raw_value = &ctx.source_code[inner.start_byte()..inner.end_byte()];
4983285
    let lit = match inner.kind() {
        "integer" => {
4829510
            let Some(value) = parse_int(ctx, &inner) else {
54
                return Ok(None);
            };
4829456
            Literal::Int(value)
        }
        "TRUE" => {
75777
            let hover = HoverInfo {
75777
                description: format!("Boolean constant: {raw_value}"),
75777
                doc_key: None,
75777
                kind: None,
75777
                ty: None,
75777
                decl_span: None,
75777
            };
75777
            span_with_hover(&inner, ctx.source_code, ctx.source_map, hover);
75777
            Literal::Bool(true)
        }
        "FALSE" => {
77998
            let hover = HoverInfo {
77998
                description: format!("Boolean constant: {raw_value}"),
77998
                doc_key: None,
77998
                kind: None,
77998
                ty: None,
77998
                decl_span: None,
77998
            };
77998
            span_with_hover(&inner, ctx.source_code, ctx.source_map, hover);
77998
            Literal::Bool(false)
        }
        _ => {
            ctx.record_error(RecoverableParseError::new(
                format!(
                    "'{}' (kind: '{}') is not a valid constant",
                    raw_value,
                    inner.kind()
                ),
                Some(inner.range()),
            ));
            return Ok(None);
        }
    };
    // Type check the constant against the expected context
4983231
    if ctx.typechecking_context != TypecheckingContext::Unknown {
1775939
        let expected = match ctx.typechecking_context {
28838
            TypecheckingContext::Boolean => "bool",
1747047
            TypecheckingContext::Arithmetic => "int",
27
            TypecheckingContext::Set => "set",
            TypecheckingContext::SetOrMatrix => "set or matrix",
            TypecheckingContext::MSet => "mset",
27
            TypecheckingContext::Matrix => "matrix",
            TypecheckingContext::Tuple => "tuple",
            TypecheckingContext::Record => "record",
            TypecheckingContext::Partition => "partition",
            TypecheckingContext::Permutation => "permutation",
            TypecheckingContext::Sequence => "sequence",
            TypecheckingContext::Function => "function",
            TypecheckingContext::Relation => "relation",
            TypecheckingContext::Unknown => "",
        };
1775939
        let actual = match &lit {
28757
            Literal::Bool(_) => "bool",
1747182
            Literal::Int(_) => "int",
            Literal::EnumVariant(_) => "enum",
            Literal::Unnamed(_) => "unnamed",
            Literal::AbstractLiteral(_) => return Ok(None), // Abstract literals aren't type-checked here
        };
1775939
        if expected != actual {
216
            ctx.record_error(RecoverableParseError::new(
216
                format!(
216
                    "Type error: {}\n\tExpected: {}\n\tGot: {}",
216
                    raw_value, expected, actual
216
                ),
216
                Some(node.range()),
216
            ));
216
            return Ok(None);
1775723
        }
3207292
    }
4983015
    Ok(Some(lit))
4983285
}
4829510
pub(crate) fn parse_int(ctx: &mut ParseContext, node: &Node) -> Option<i32> {
4829510
    let raw_value = &ctx.source_code[node.start_byte()..node.end_byte()];
4829510
    if let Ok(v) = raw_value.parse::<i32>() {
4829456
        Some(v)
    } else {
54
        ctx.record_error(RecoverableParseError::new(
54
            "Expected an integer here".to_string(),
54
            Some(node.range()),
54
        ));
54
        None
    }
4829510
}