1
use crate::errors::{FatalParseError, RecoverableParseError};
2
use crate::expression::parse_expression;
3
use crate::field;
4
use crate::parser::ParseContext;
5
use crate::parser::domain::parse_domain;
6
use crate::util::{TypecheckingContext, named_children};
7
use conjure_cp_core::ast::{AbstractLiteral, DomainPtr, Expression};
8
use conjure_cp_core::{domain_int, range};
9
use tree_sitter::Node;
10

            
11
1993551
pub fn parse_abstract(
12
1993551
    ctx: &mut ParseContext,
13
1993551
    node: &Node,
14
1993551
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
15
1993551
    if typecheck_abstract_literal(ctx, node) {
16
27
        return Ok(None);
17
1993524
    }
18

            
19
1993524
    match node.kind() {
20
17415
        "record" => parse_record(ctx, node),
21
15795
        "variant" => parse_variant(ctx, node),
22
231045
        "tuple" => parse_tuple(ctx, node),
23
1144765
        "matrix" => parse_matrix(ctx, node),
24
353166
        "set_literal" => parse_set_literal(ctx, node),
25
28782
        "mset_literal" => parse_mset_literal(ctx, node),
26
182466
        "sequence_literal" => parse_sequence_literal(ctx, node),
27
2214
        "function_literal" => parse_function_literal(ctx, node),
28
1971
        "relation_literal" => parse_relation_literal(ctx, node),
29
729
        "partition_literal" => parse_partition_literal(ctx, node),
30
15176
        "permutation_literal" => parse_permutation_literal(ctx, node),
31
        _ => {
32
            ctx.record_error(RecoverableParseError::new(
33
                format!("Expected abstract literal, got: {}", node.kind()),
34
                Some(node.range()),
35
            ));
36
            Ok(None)
37
        }
38
    }
39
1993551
}
40

            
41
1993551
fn typecheck_abstract_literal(ctx: &mut ParseContext, node: &Node) -> bool {
42
1993551
    let expected = match ctx.typechecking_context {
43
        TypecheckingContext::Boolean => "bool",
44
        TypecheckingContext::Arithmetic => "int",
45
2262
        TypecheckingContext::Set => "set",
46
390339
        TypecheckingContext::SetOrMatrix => "set or matrix",
47
        TypecheckingContext::MSet => "mset",
48
53136
        TypecheckingContext::Matrix => "matrix",
49
7884
        TypecheckingContext::Tuple => "tuple",
50
3942
        TypecheckingContext::Record => "record",
51
243
        TypecheckingContext::Partition => "partition",
52
        TypecheckingContext::Permutation => "permutation",
53
8775
        TypecheckingContext::Sequence => "sequence",
54
        TypecheckingContext::Function => "function",
55
        TypecheckingContext::Relation => "relation",
56
1526970
        TypecheckingContext::Unknown => "unknown",
57
    };
58

            
59
1993551
    let got = match node.kind() {
60
353166
        "set_literal" => "set",
61
28782
        "mset_literal" => "mset",
62
182466
        "sequence_literal" => "sequence",
63
2214
        "function_literal" => "function",
64
1971
        "relation_literal" => "relation",
65
729
        "partition_literal" => "partition",
66
15176
        "permutation_literal" => "permutation",
67
1144765
        "matrix" => "matrix",
68
231072
        "tuple" => "tuple",
69
17415
        "record" => "record",
70
15795
        "variant" => "variant",
71
        _ => {
72
            ctx.record_error(RecoverableParseError::new(
73
                format!("Expected abstract literal, got: {}", node.kind()),
74
                Some(node.range()),
75
            ));
76
            return true;
77
        }
78
    };
79

            
80
1993551
    if expected != "unknown"
81
466581
        && !(ctx.typechecking_context == TypecheckingContext::SetOrMatrix
82
390339
            && matches!(got, "set" | "matrix"))
83
76269
        && expected != got
84
    {
85
27
        ctx.record_error(RecoverableParseError::new(
86
27
            format!(
87
27
                "Type error: {}\n\tExpected: {}\n\tGot: {}",
88
27
                ctx.source_code[node.start_byte()..node.end_byte()].trim(),
89
27
                expected,
90
27
                got
91
27
            ),
92
27
            Some(node.range()),
93
27
        ));
94
27
        return true;
95
1993524
    }
96

            
97
1993524
    false
98
1993551
}
99

            
100
15795
fn parse_variant(
101
15795
    ctx: &mut ParseContext,
102
15795
    node: &Node,
103
15795
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
104
15795
    let Some(pair) = node.child_by_field_name("name_value_pair") else {
105
        return Ok(None);
106
    };
107
15795
    let Some(name_node) = field!(recover, ctx, pair, "name") else {
108
        return Ok(None);
109
    };
110
15795
    let name = conjure_cp_core::ast::Name::user(
111
15795
        &ctx.source_code[name_node.start_byte()..name_node.end_byte()],
112
15795
    );
113
15795
    let Some(value_node) = field!(recover, ctx, pair, "value") else {
114
        return Ok(None);
115
    };
116
15795
    let saved_context = ctx.typechecking_context;
117
15795
    let saved_inner_context = ctx.inner_typechecking_context;
118
15795
    ctx.typechecking_context = ctx.inner_typechecking_context;
119
15795
    ctx.inner_typechecking_context = TypecheckingContext::Unknown;
120
15795
    let value = parse_expression(ctx, value_node)?;
121
15795
    ctx.typechecking_context = saved_context;
122
15795
    ctx.inner_typechecking_context = saved_inner_context;
123
15795
    let Some(value) = value else {
124
        return Ok(None);
125
    };
126
15795
    Ok(Some(AbstractLiteral::Variant(
127
15795
        conjure_cp_core::ast::Moo::new(conjure_cp_core::ast::records::Field { name, value }),
128
15795
    )))
129
15795
}
130

            
131
17415
fn parse_record(
132
17415
    ctx: &mut ParseContext,
133
17415
    node: &Node,
134
17415
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
135
17415
    let saved_ctx = ctx.typechecking_context;
136
17415
    let saved_inner_ctx = ctx.inner_typechecking_context;
137
17415
    let mut values = Vec::new();
138
17415
    let mut had_error = false;
139
17415
    for child in node.children_by_field_name("name_value_pair", &mut node.walk()) {
140
34830
        let Some(name_node) = field!(recover, ctx, child, "name") else {
141
            return Ok(None);
142
        };
143
34830
        let name_str = &ctx.source_code[name_node.start_byte()..name_node.end_byte()];
144
34830
        let name = conjure_cp_core::ast::Name::user(name_str);
145

            
146
34830
        let Some(value_node) = field!(recover, ctx, child, "value") else {
147
            return Ok(None);
148
        };
149

            
150
        // Record fields are heterogeneous, just like tuple positions.
151
34830
        ctx.typechecking_context = TypecheckingContext::Unknown;
152
34830
        ctx.inner_typechecking_context = TypecheckingContext::Unknown;
153
34830
        let Some(value) = parse_expression(ctx, value_node)? else {
154
            had_error = true;
155
            continue;
156
        };
157

            
158
34830
        values.push(conjure_cp_core::ast::records::Field { name, value });
159
    }
160

            
161
17415
    ctx.typechecking_context = saved_ctx;
162
17415
    ctx.inner_typechecking_context = saved_inner_ctx;
163
17415
    if had_error {
164
        Ok(None)
165
    } else {
166
17415
        Ok(Some(AbstractLiteral::Record(values)))
167
    }
168
17415
}
169

            
170
231045
fn parse_tuple(
171
231045
    ctx: &mut ParseContext,
172
231045
    node: &Node,
173
231045
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
174
    // Save the typechecking context
175
231045
    let saved_ctx = ctx.typechecking_context;
176
231045
    let saved_inner_ctx = ctx.inner_typechecking_context;
177

            
178
231045
    let mut elements = Vec::new();
179
231045
    let mut had_error = false;
180
231045
    for child in named_children(node) {
181
        // A tuple is heterogeneous: each position has its own type, so the surrounding scalar
182
        // context says nothing about any given element. `(y, z)` of type `(int, bool)` must not
183
        // have `z` checked against the tuple's own context.
184
462258
        ctx.typechecking_context = TypecheckingContext::Unknown;
185
462258
        ctx.inner_typechecking_context = TypecheckingContext::Unknown;
186

            
187
462258
        let Some(expr) = parse_expression(ctx, child)? else {
188
            had_error = true;
189
            continue;
190
        };
191
462258
        elements.push(expr);
192
    }
193

            
194
231045
    ctx.typechecking_context = saved_ctx;
195
231045
    ctx.inner_typechecking_context = saved_inner_ctx;
196
231045
    if had_error {
197
        Ok(None)
198
    } else {
199
231045
        Ok(Some(AbstractLiteral::Tuple(elements)))
200
    }
201
231045
}
202

            
203
1144765
fn parse_matrix(
204
1144765
    ctx: &mut ParseContext,
205
1144765
    node: &Node,
206
1144765
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
207
    // Save the typechecking contexts
208
1144765
    let saved_ctx = ctx.typechecking_context;
209
1144765
    let saved_inner_ctx = ctx.inner_typechecking_context;
210

            
211
1144765
    let mut elements = vec![];
212
1144765
    let mut domain: Option<DomainPtr> = None;
213
1144765
    let mut had_error = false;
214
1144765
    for child in named_children(node) {
215
3099716
        if matches!(child.kind(), "single_line_comment" | "language_declaration") {
216
            continue;
217
3099716
        }
218
3099716
        if child.kind() == "arithmetic_expr"
219
2171618
            || child.kind() == "bool_expr"
220
2167061
            || child.kind() == "comparison_expr"
221
2152724
            || child.kind() == "atom"
222
        {
223
            // Parse elements with inner typechecking context
224
2987344
            ctx.typechecking_context = saved_inner_ctx;
225
2987344
            ctx.inner_typechecking_context = TypecheckingContext::Unknown;
226

            
227
2987344
            let Some(expr) = parse_expression(ctx, child)? else {
228
243
                had_error = true;
229
243
                continue;
230
            };
231
2987101
            elements.push(expr);
232
        } else {
233
            // Parse domains with unknown typechecking context
234
112372
            ctx.typechecking_context = TypecheckingContext::Unknown;
235

            
236
112372
            let Some(parsed_domain) = parse_domain(ctx, child)? else {
237
27
                had_error = true;
238
27
                continue;
239
            };
240
112345
            domain = Some(parsed_domain);
241
        }
242
    }
243
1144765
    if domain.is_none() {
244
1032420
        let count = elements.len() as i32;
245
1032420
        domain = Some(domain_int!(1..count));
246
112345
    }
247

            
248
1144765
    ctx.typechecking_context = saved_ctx;
249
1144765
    ctx.inner_typechecking_context = saved_inner_ctx;
250
1144765
    if had_error {
251
189
        Ok(None)
252
    } else {
253
1144576
        Ok(Some(AbstractLiteral::Matrix(elements, domain.unwrap())))
254
    }
255
1144765
}
256

            
257
353976
fn parse_set_literal(
258
353976
    ctx: &mut ParseContext,
259
353976
    node: &Node,
260
353976
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
261
    // Save the typechecking contexts
262
353976
    let saved_ctx = ctx.typechecking_context;
263
353976
    let saved_inner_ctx = ctx.inner_typechecking_context;
264

            
265
353976
    let mut elements = Vec::new();
266
353976
    let mut had_error = false;
267
353976
    for child in named_children(node) {
268
        // Parse elements with inner typechecking context
269
732810
        ctx.typechecking_context = saved_inner_ctx;
270
732810
        ctx.inner_typechecking_context = TypecheckingContext::Unknown;
271

            
272
732810
        let Some(expr) = parse_expression(ctx, child)? else {
273
81
            had_error = true;
274
81
            continue;
275
        };
276
732729
        elements.push(expr);
277
    }
278

            
279
353976
    ctx.typechecking_context = saved_ctx;
280
353976
    ctx.inner_typechecking_context = saved_inner_ctx;
281
353976
    if had_error {
282
81
        Ok(None)
283
    } else {
284
353895
        Ok(Some(AbstractLiteral::Set(elements)))
285
    }
286
353976
}
287

            
288
28782
fn parse_mset_literal(
289
28782
    ctx: &mut ParseContext,
290
28782
    node: &Node,
291
28782
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
292
28782
    let saved_ctx = ctx.typechecking_context;
293
28782
    let saved_inner_ctx = ctx.inner_typechecking_context;
294
28782
    let mut elements = Vec::new();
295
28782
    let mut had_error = false;
296
28782
    for child in named_children(node) {
297
38313
        ctx.typechecking_context = saved_inner_ctx;
298
38313
        ctx.inner_typechecking_context = TypecheckingContext::Unknown;
299
38313
        let Some(expression) = parse_expression(ctx, child)? else {
300
            had_error = true;
301
            continue;
302
        };
303
38313
        elements.push(expression);
304
    }
305
28782
    ctx.typechecking_context = saved_ctx;
306
28782
    ctx.inner_typechecking_context = saved_inner_ctx;
307
28782
    if had_error {
308
        Ok(None)
309
    } else {
310
28782
        Ok(Some(AbstractLiteral::MSet(elements)))
311
    }
312
28782
}
313

            
314
182466
fn parse_sequence_literal(
315
182466
    ctx: &mut ParseContext,
316
182466
    node: &Node,
317
182466
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
318
182466
    let saved_ctx = ctx.typechecking_context;
319
182466
    let saved_inner_ctx = ctx.inner_typechecking_context;
320
182466
    let mut elements = Vec::new();
321
182466
    let mut had_error = false;
322
182466
    for child in named_children(node) {
323
351972
        ctx.typechecking_context = saved_inner_ctx;
324
351972
        ctx.inner_typechecking_context = TypecheckingContext::Unknown;
325
351972
        let Some(expression) = parse_expression(ctx, child)? else {
326
            had_error = true;
327
            continue;
328
        };
329
351972
        elements.push(expression);
330
    }
331
182466
    ctx.typechecking_context = saved_ctx;
332
182466
    ctx.inner_typechecking_context = saved_inner_ctx;
333
182466
    if had_error {
334
        Ok(None)
335
    } else {
336
182466
        Ok(Some(AbstractLiteral::Sequence(elements)))
337
    }
338
182466
}
339

            
340
2214
fn parse_function_literal(
341
2214
    ctx: &mut ParseContext,
342
2214
    node: &Node,
343
2214
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
344
2214
    let saved_ctx = ctx.typechecking_context;
345
2214
    let saved_inner_ctx = ctx.inner_typechecking_context;
346
2214
    let mut pairs = Vec::new();
347
2214
    let mut had_error = false;
348
2214
    for pair in named_children(node) {
349
        // key/value can be of any type (matching the domain/codomain of the function), so
350
        // typecheck context is relaxed here, mirroring the other abstract literal parsers.
351
6318
        ctx.typechecking_context = TypecheckingContext::Unknown;
352
6318
        ctx.inner_typechecking_context = TypecheckingContext::Unknown;
353

            
354
6318
        let Some(key_node) = field!(recover, ctx, pair, "key") else {
355
            had_error = true;
356
            continue;
357
        };
358
6318
        let Some(key) = parse_expression(ctx, key_node)? else {
359
            had_error = true;
360
            continue;
361
        };
362

            
363
6318
        let Some(value_node) = field!(recover, ctx, pair, "value") else {
364
            had_error = true;
365
            continue;
366
        };
367
6318
        let Some(value) = parse_expression(ctx, value_node)? else {
368
            had_error = true;
369
            continue;
370
        };
371

            
372
6318
        pairs.push((key, value));
373
    }
374
2214
    ctx.typechecking_context = saved_ctx;
375
2214
    ctx.inner_typechecking_context = saved_inner_ctx;
376
2214
    if had_error {
377
        Ok(None)
378
    } else {
379
2214
        Ok(Some(AbstractLiteral::Function(pairs)))
380
    }
381
2214
}
382

            
383
1971
fn parse_relation_literal(
384
1971
    ctx: &mut ParseContext,
385
1971
    node: &Node,
386
1971
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
387
1971
    let saved_ctx = ctx.typechecking_context;
388
1971
    let saved_inner_ctx = ctx.inner_typechecking_context;
389
1971
    let mut tuples = Vec::new();
390
1971
    let mut had_error = false;
391
1971
    for tuple_node in named_children(node) {
392
5913
        let mut fields = Vec::new();
393
5913
        for field_node in named_children(&tuple_node) {
394
            // Each column can be of any type (matching the relation's own column domains), so
395
            // typecheck context is relaxed here, mirroring the other abstract literal parsers.
396
11826
            ctx.typechecking_context = TypecheckingContext::Unknown;
397
11826
            ctx.inner_typechecking_context = TypecheckingContext::Unknown;
398

            
399
11826
            let Some(expr) = parse_expression(ctx, field_node)? else {
400
                had_error = true;
401
                continue;
402
            };
403
11826
            fields.push(expr);
404
        }
405
5913
        tuples.push(fields);
406
    }
407
1971
    ctx.typechecking_context = saved_ctx;
408
1971
    ctx.inner_typechecking_context = saved_inner_ctx;
409
1971
    if had_error {
410
        Ok(None)
411
    } else {
412
1971
        Ok(Some(AbstractLiteral::Relation(tuples)))
413
    }
414
1971
}
415

            
416
729
fn parse_partition_literal(
417
729
    ctx: &mut ParseContext,
418
729
    node: &Node,
419
729
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
420
729
    let saved_ctx = ctx.typechecking_context;
421
729
    let saved_inner_ctx = ctx.inner_typechecking_context;
422
729
    let mut parts = Vec::new();
423
729
    let mut had_error = false;
424
729
    for part_node in named_children(node) {
425
        // Each part is itself a set literal; its elements can be of any type (matching the
426
        // partition's own inner domain), so typecheck context is relaxed here, mirroring the
427
        // other abstract literal parsers.
428
810
        ctx.typechecking_context = TypecheckingContext::Unknown;
429
810
        ctx.inner_typechecking_context = TypecheckingContext::Unknown;
430

            
431
810
        let Some(AbstractLiteral::Set(elements)) = parse_set_literal(ctx, &part_node)? else {
432
            had_error = true;
433
            continue;
434
        };
435
810
        parts.push(elements);
436
    }
437
729
    ctx.typechecking_context = saved_ctx;
438
729
    ctx.inner_typechecking_context = saved_inner_ctx;
439
729
    if had_error {
440
        Ok(None)
441
    } else {
442
729
        Ok(Some(AbstractLiteral::Partition(parts)))
443
    }
444
729
}
445

            
446
15176
fn parse_permutation_literal(
447
15176
    ctx: &mut ParseContext,
448
15176
    node: &Node,
449
15176
) -> Result<Option<AbstractLiteral<Expression>>, FatalParseError> {
450
15176
    let saved_ctx = ctx.typechecking_context;
451
15176
    let saved_inner_ctx = ctx.inner_typechecking_context;
452
15176
    let mut cycles = Vec::new();
453
15176
    let mut had_error = false;
454
15176
    for cycle_node in named_children(node) {
455
15581
        let mut elements = Vec::new();
456
15581
        for element_node in named_children(&cycle_node) {
457
            // Each element can be of any type (matching the permutation's own inner domain), so
458
            // typecheck context is relaxed here, mirroring the other abstract literal parsers.
459
45770
            ctx.typechecking_context = TypecheckingContext::Unknown;
460
45770
            ctx.inner_typechecking_context = TypecheckingContext::Unknown;
461

            
462
45770
            let Some(expr) = parse_expression(ctx, element_node)? else {
463
                had_error = true;
464
                continue;
465
            };
466
45770
            elements.push(expr);
467
        }
468
15581
        cycles.push(elements);
469
    }
470
15176
    ctx.typechecking_context = saved_ctx;
471
15176
    ctx.inner_typechecking_context = saved_inner_ctx;
472
15176
    if had_error {
473
        Ok(None)
474
    } else {
475
15176
        Ok(Some(AbstractLiteral::Permutation(cycles)))
476
    }
477
15176
}