1
use super::util::named_children;
2
use crate::diagnostics::diagnostics_api::SymbolKind;
3
use crate::diagnostics::source_map::{HoverInfo, span_with_hover};
4
use crate::errors::FatalParseError;
5
use crate::expression::parse_expression;
6
use crate::parser::ParseContext;
7
use crate::util::TypecheckingContext;
8
use crate::{RecoverableParseError, child};
9
use conjure_cp_core::ast::Typeable;
10
use conjure_cp_core::ast::{
11
    Atom, BinaryAttr, DeclarationPtr, Domain, DomainPtr, EnumVariantVal, Expression, Field,
12
    FuncAttr, IntVal, JectivityAttr, Literal, MSetAttr, Moo, Name, PartialityAttr, PartitionAttr,
13
    PermutationAttr, Range, Reference, RelAttr, SequenceAttr, SetAttr,
14
};
15
use tree_sitter::Node;
16

            
17
use crate::field;
18

            
19
/// Parse an Essence variable domain into its Conjure AST representation.
20
7587756
pub fn parse_domain(
21
7587756
    ctx: &mut ParseContext,
22
7587756
    domain: Node,
23
7587756
) -> Result<Option<DomainPtr>, FatalParseError> {
24
7587756
    match domain.kind() {
25
        "domain" | "annotation_domain" => {
26
3733709
            let inner = match domain.child(0) {
27
3733709
                Some(node) => node,
28
                None => {
29
                    ctx.record_error(RecoverableParseError::new(
30
                        format!("{} in expression of kind '{}'", "domain", domain.kind()),
31
                        Some(domain.range()),
32
                    ));
33
                    return Ok(None);
34
                }
35
            };
36
3733709
            parse_domain(ctx, inner)
37
        }
38
6
        "enum_domain" => parse_enum_domain(ctx, domain),
39
        "bool_domain" => {
40
291621
            ctx.add_span_and_doc_hover(&domain, "L_bool", SymbolKind::Domain, None, None);
41
291621
            Ok(Some(Domain::bool()))
42
        }
43
2498885
        "int_domain" | "annotation_int_domain" => parse_int_domain(ctx, domain),
44
        "identifier" => {
45
179454
            let Some(decl) = get_declaration_ptr_from_identifier(ctx, domain)? else {
46
108
                return Ok(None);
47
            };
48
179346
            let is_unnamed = decl.as_unnamed_type().is_some();
49
179346
            let type_domain = if is_unnamed {
50
42
                decl.domain()
51
            } else {
52
179304
                decl.as_enumerated_type().map(|ty| ty.to_domain())
53
            };
54
179346
            let Some(dom) = type_domain.or_else(|| Domain::reference(decl)) else {
55
27
                ctx.record_error(crate::errors::RecoverableParseError::new(
56
27
                    format!(
57
27
                        "The identifier '{}' is not a valid domain",
58
27
                        &ctx.source_code[domain.start_byte()..domain.end_byte()]
59
27
                    ),
60
27
                    Some(domain.range()),
61
27
                ));
62
27
                return Ok(None);
63
            };
64
179319
            let name = &ctx.source_code[domain.start_byte()..domain.end_byte()];
65

            
66
            // Not form docs, because we need context specific hover info
67
179319
            span_with_hover(
68
179319
                &domain,
69
179319
                ctx.source_code,
70
179319
                ctx.source_map,
71
179319
                HoverInfo {
72
179319
                    description: format!("Domain reference: {name}"),
73
179319
                    doc_key: None,
74
179319
                    kind: Some(SymbolKind::Variable),
75
179319
                    ty: None,
76
179319
                    decl_span: None, // could link to the declaration span if we wanted
77
179319
                },
78
179319
            );
79
179319
            Ok(Some(dom))
80
        }
81
80381
        "tuple_domain" | "annotation_tuple_domain" => parse_tuple_domain(ctx, domain),
82
290243
        "matrix_domain" | "annotation_matrix_domain" => parse_matrix_domain(ctx, domain),
83
10315
        "record_domain" | "annotation_record_domain" => parse_record_domain(ctx, domain),
84
21681
        "variant_domain" | "annotation_variant_domain" => parse_variant_domain(ctx, domain),
85
258378
        "set_domain" | "annotation_set_domain" => parse_set_domain(ctx, domain),
86
115021
        "mset_domain" | "annotation_mset_domain" => parse_mset_domain(ctx, domain),
87
48174
        "sequence_domain" | "annotation_sequence_domain" => parse_sequence_domain(ctx, domain),
88
44496
        "function_domain" | "annotation_function_domain" => parse_function_domain(ctx, domain),
89
3024
        "relation_domain" => parse_relation_domain(ctx, domain),
90
1080
        "partition_domain" => parse_partition_domain(ctx, domain),
91
11261
        "permutation_domain" => parse_permutation_domain(ctx, domain),
92
        _ => {
93
27
            ctx.record_error(RecoverableParseError::new(
94
27
                format!("{} is not a supported domain type", domain.kind()),
95
27
                Some(domain.range()),
96
27
            ));
97
27
            Ok(None)
98
        }
99
    }
100
7587756
}
101

            
102
115021
fn parse_mset_domain(
103
115021
    ctx: &mut ParseContext,
104
115021
    mset_domain: Node,
105
115021
) -> Result<Option<DomainPtr>, FatalParseError> {
106
115021
    let mut representation = None;
107
115021
    let mut size = Range::Unbounded;
108
115021
    let mut occurrence = Range::Unbounded;
109
115021
    let mut min_size = None;
110
115021
    let mut max_size = None;
111
115021
    let mut min_occurrence = None;
112
115021
    let mut max_occurrence = None;
113
115021
    let mut value_domain = None;
114

            
115
115021
    for child in named_children(&mset_domain) {
116
229988
        match child.kind() {
117
            "identifier" => {}
118
            "mset_attributes" => {
119
114967
                for attribute in named_children(&child) {
120
210845
                    let Some(value_node) = attribute.child_by_field_name("value") else {
121
                        return Ok(None);
122
                    };
123
210845
                    let name = attribute
124
210845
                        .child_by_field_name("attribute")
125
210845
                        .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
126
                        .unwrap_or_default();
127
210845
                    if name == "representation" {
128
55
                        representation = Some(
129
55
                            ctx.source_code[value_node.start_byte()..value_node.end_byte()]
130
55
                                .to_string(),
131
55
                        );
132
55
                        continue;
133
210790
                    }
134
                    // Attribute values may be expressions over givens, e.g. `maxSize |nums|`,
135
                    // which only become ground once the parameters are instantiated.
136
210790
                    let Some(value) = parse_int_val(ctx, value_node)? else {
137
                        return Ok(None);
138
                    };
139
210790
                    match name {
140
19116
                        "size" => size = Range::Single(value),
141
9612
                        "minSize" => min_size = Some(value),
142
86131
                        "maxSize" => max_size = Some(value),
143
162
                        "minOccur" => min_occurrence = Some(value),
144
95769
                        "maxOccur" => max_occurrence = Some(value),
145
                        _ => return Ok(None),
146
                    }
147
                }
148
            }
149
115021
            "domain" | "annotation_domain" => value_domain = parse_domain(ctx, child)?,
150
            _ => {}
151
        }
152
    }
153

            
154
115021
    if !matches!(size, Range::Single(_)) {
155
95905
        size = match (min_size, max_size) {
156
9612
            (Some(min), Some(max)) => Range::Bounded(min, max),
157
            (Some(min), None) => Range::UnboundedR(min),
158
76519
            (None, Some(max)) => Range::UnboundedL(max),
159
9774
            (None, None) => Range::Unbounded,
160
        };
161
19116
    }
162
115021
    occurrence = match (min_occurrence, max_occurrence) {
163
135
        (Some(min), Some(max)) => Range::Bounded(min, max),
164
27
        (Some(min), None) => Range::UnboundedR(min),
165
95634
        (None, Some(max)) => Range::UnboundedL(max),
166
19225
        (None, None) => occurrence,
167
    };
168

            
169
115021
    let Some(value_domain) = value_domain else {
170
        ctx.record_error(RecoverableParseError::new(
171
            "Multiset domain must have a value domain".to_string(),
172
            Some(mset_domain.range()),
173
        ));
174
        return Ok(None);
175
    };
176
115021
    let mut attrs = MSetAttr::new(size, occurrence);
177
115021
    if let Some(representation) = representation {
178
55
        attrs = attrs.with_representation(representation);
179
114966
    }
180
115021
    Ok(Some(Domain::mset(attrs, value_domain)))
181
115021
}
182

            
183
179460
fn get_declaration_ptr_from_identifier(
184
179460
    ctx: &mut ParseContext,
185
179460
    identifier: Node,
186
179460
) -> Result<Option<DeclarationPtr>, FatalParseError> {
187
179460
    let name = Name::user(&ctx.source_code[identifier.start_byte()..identifier.end_byte()]);
188
179460
    let decl = ctx.symbols.as_ref().unwrap().read().lookup(&name);
189

            
190
179460
    if decl.is_none() {
191
108
        ctx.record_error(crate::errors::RecoverableParseError::new(
192
108
            format!("The identifier '{}' is not defined", name),
193
108
            Some(identifier.range()),
194
108
        ));
195
108
        return Ok(None);
196
179352
    }
197
179352
    match decl {
198
179352
        Some(decl) => Ok(Some(decl)),
199
        None => {
200
            ctx.record_error(crate::errors::RecoverableParseError::new(
201
                format!("The identifier '{}' is not defined", name),
202
                Some(identifier.range()),
203
            ));
204
            Ok(None)
205
        }
206
    }
207
179460
}
208

            
209
/// The representation named by a domain's `representation` attribute node, as in
210
/// `int(representation order, 1..4)` or `matrix (representation packed) indexed by ...`.
211
2901505
fn representation_field(ctx: &ParseContext, domain: Node) -> Option<String> {
212
2901505
    let value = domain
213
2901505
        .child_by_field_name("representation")?
214
639
        .child_by_field_name("value")?;
215
639
    Some(ctx.source_code[value.start_byte()..value.end_byte()].to_string())
216
2901505
}
217

            
218
/// The value of an attribute node in an attribute list, e.g. `packed` in `representation packed`.
219
270
fn attribute_value_text(ctx: &ParseContext, attribute: Node) -> Option<String> {
220
270
    let value = attribute.child_by_field_name("value")?;
221
270
    Some(ctx.source_code[value.start_byte()..value.end_byte()].to_string())
222
270
}
223

            
224
/// Apply the preference written on a domain, if any, to the domain just built from it.
225
402593
fn with_representation(domain: DomainPtr, representation: Option<String>) -> DomainPtr {
226
402593
    match representation {
227
378
        Some(representation) => domain.with_representation_preference(&representation),
228
402215
        None => domain,
229
    }
230
402593
}
231

            
232
/// Parse an integer domain. Can be a single integer or a range, optionally preceded by a
233
/// representation preference: `int(representation order, 1..4)`.
234
2498885
fn parse_int_domain(
235
2498885
    ctx: &mut ParseContext,
236
2498885
    int_domain: Node,
237
2498885
) -> Result<Option<DomainPtr>, FatalParseError> {
238
2498885
    let representation = representation_field(ctx, int_domain);
239
2498885
    let Some(domain) = parse_int_domain_ranges(ctx, int_domain, representation.is_some())? else {
240
54
        return Ok(None);
241
    };
242
2498831
    Ok(Some(match representation {
243
261
        Some(representation) => domain.with_representation_preference(&representation),
244
2498570
        None => domain,
245
    }))
246
2498885
}
247

            
248
2498885
fn parse_int_domain_ranges(
249
2498885
    ctx: &mut ParseContext,
250
2498885
    int_domain: Node,
251
2498885
    has_representation: bool,
252
2498885
) -> Result<Option<DomainPtr>, FatalParseError> {
253
2498885
    let int_keyword_node = child!(int_domain, 0, "int");
254

            
255
2498885
    let Some(range_list) = int_domain.child_by_field_name("ranges") else {
256
110619
        ctx.add_span_and_doc_hover(&int_keyword_node, "L_int", SymbolKind::Domain, None, None);
257
110619
        let int_text = ctx.source_code[int_domain.start_byte()..int_domain.end_byte()].trim();
258
110619
        return if int_text == "int" || has_representation {
259
110558
            Ok(Some(Domain::int_ground(vec![Range::Unbounded])))
260
        } else {
261
61
            Ok(Some(Domain::int_ground(vec![])))
262
        };
263
    };
264
    // `int(<collection>)` takes its values from the collection rather than listing ranges, as in
265
    // `int([i | i <- nums])`. One component that is collection-valued means this form.
266
2388266
    let components: Vec<_> = named_children(&range_list).collect();
267
2388266
    if let [only] = components.as_slice()
268
2139440
        && matches!(only.kind(), "atom" | "arithmetic_expr")
269
87051
        && let Some(expr) = parse_collection_valued_expression(ctx, *only)?
270
    {
271
        ctx.add_span_and_doc_hover(&int_keyword_node, "int", SymbolKind::Domain, None, None);
272
        return Ok(Some(Domain::int_from_values(expr)));
273
2388266
    }
274

            
275
2388266
    let mut ranges_unresolved: Vec<Range<IntVal>> = Vec::new();
276
2388266
    let mut all_resolved = true;
277

            
278
2388266
    for domain_component in named_children(&range_list) {
279
2776442
        match domain_component.kind() {
280
            "atom" | "arithmetic_expr" | "integer" | "identifier" => {
281
662655
                let Some(int_val) = parse_int_val(ctx, domain_component)? else {
282
                    return Ok(None);
283
                };
284

            
285
662655
                if !matches!(int_val, IntVal::Const(_)) {
286
3909
                    all_resolved = false;
287
658746
                }
288
662655
                ranges_unresolved.push(Range::Single(int_val));
289
            }
290
            "int_range" | "annotation_int_range" => {
291
2113787
                let lower_bound = match domain_component.child_by_field_name("lower") {
292
                    Some(node) => {
293
2113754
                        match parse_int_val(ctx, node)? {
294
2113754
                            Some(val) => Some(val),
295
                            None => return Ok(None), // semantic error occurred
296
                        }
297
                    }
298
33
                    None => None,
299
                };
300
2113787
                let upper_bound = match domain_component.child_by_field_name("upper") {
301
                    Some(node) => {
302
2094683
                        match parse_int_val(ctx, node)? {
303
2094629
                            Some(val) => Some(val),
304
54
                            None => return Ok(None), // semantic error occurred
305
                        }
306
                    }
307
19104
                    None => None,
308
                };
309

            
310
2113733
                match (lower_bound, upper_bound) {
311
                    (Some(lower), Some(upper)) => {
312
2094596
                        if !matches!((&lower, &upper), (IntVal::Const(_), IntVal::Const(_))) {
313
212210
                            all_resolved = false;
314
1882386
                        }
315
2094596
                        ranges_unresolved.push(Range::Bounded(lower, upper));
316
                    }
317
                    (Some(lower), None) => {
318
19104
                        if !matches!(lower, IntVal::Const(_)) {
319
                            all_resolved = false;
320
19104
                        }
321
19104
                        ranges_unresolved.push(Range::UnboundedR(lower));
322
                    }
323
                    (None, Some(upper)) => {
324
33
                        if !matches!(upper, IntVal::Const(_)) {
325
                            all_resolved = false;
326
33
                        }
327
33
                        ranges_unresolved.push(Range::UnboundedL(upper));
328
                    }
329
                    _ => {
330
                        ctx.record_error(RecoverableParseError::new(
331
                            "Invalid int range: must have at least a lower or upper bound"
332
                                .to_string(),
333
                            Some(domain_component.range()),
334
                        ));
335
                        return Ok(None);
336
                    }
337
                }
338
            }
339
            _ => {
340
                ctx.record_error(RecoverableParseError::new(
341
                    format!(
342
                        "Unexpected int domain component: {}",
343
                        domain_component.kind()
344
                    ),
345
                    Some(domain_component.range()),
346
                ));
347
                return Ok(None);
348
            }
349
        }
350
    }
351

            
352
    // If all values are resolved constants, convert IntVals to raw integers
353
2388212
    if all_resolved {
354
2176143
        let ranges: Vec<Range<i32>> = ranges_unresolved
355
2176143
            .into_iter()
356
2560215
            .map(|r| r.resolve())
357
            .collect::<Result<Vec<_>, _>>()
358
            .map_err(|e| {
359
                FatalParseError::internal_error(
360
                    format!("could not resolve range: {e}"),
361
                    Some(int_domain.range()),
362
                )
363
            })?
364
            .into_iter()
365
2560215
            .filter(|range| !matches!(range, Range::Bounded(lower, upper) if lower > upper))
366
            .collect();
367

            
368
2176143
        ctx.add_span_and_doc_hover(&int_keyword_node, "L_int", SymbolKind::Domain, None, None);
369
2176143
        Ok(Some(Domain::int(ranges)))
370
    } else {
371
        // Otherwise, keep as an expression-based domain
372

            
373
        // Adding int keyword to the source map with hover info from documentation
374
212069
        ctx.add_span_and_doc_hover(&int_keyword_node, "L_int", SymbolKind::Domain, None, None);
375
212069
        Ok(Some(Domain::int(ranges_unresolved)))
376
    }
377
2498885
}
378

            
379
// Helper function to parse a node into an IntVal
380
// Handles constants, references, and arbitrary expressions
381
5291289
fn parse_int_val(ctx: &mut ParseContext, node: Node) -> Result<Option<IntVal>, FatalParseError> {
382
5291289
    if matches!(node.kind(), "atom" | "integer") {
383
4913902
        let text = &ctx.source_code[node.start_byte()..node.end_byte()];
384
4913902
        if let Ok(integer) = text.parse::<i32>() {
385
4729932
            return Ok(Some(IntVal::new_const(integer)));
386
183970
        }
387
377387
    }
388

            
389
561357
    if node.kind() == "identifier" {
390
        let Some(decl) = get_declaration_ptr_from_identifier(ctx, node)? else {
391
            // If identifier isn't defined, it's a semantic error.
392
            return Ok(None);
393
        };
394
        return Ok(Some(IntVal::Reference(Reference::new(decl))));
395
561357
    }
396

            
397
561357
    let saved_context = ctx.typechecking_context;
398
561357
    let saved_inner_context = ctx.inner_typechecking_context;
399
561357
    ctx.typechecking_context = TypecheckingContext::Arithmetic;
400
561357
    ctx.inner_typechecking_context = TypecheckingContext::Arithmetic;
401
561357
    let expr = parse_expression(ctx, node)?;
402
561357
    ctx.typechecking_context = saved_context;
403
561357
    ctx.inner_typechecking_context = saved_inner_context;
404

            
405
561357
    let Some(expr) = expr else {
406
81
        return Ok(None);
407
    };
408

            
409
561276
    if let Expression::Atomic(_, Atom::Reference(reference)) = &expr
410
183592
        && let Ok(reference_val) = IntVal::new_ref(reference)
411
    {
412
183592
        return Ok(Some(reference_val));
413
377684
    }
414

            
415
377684
    if let Expression::Atomic(_, Atom::Literal(Literal::Int(value))) = expr {
416
315337
        return Ok(Some(IntVal::new_const(value)));
417
62347
    }
418

            
419
62347
    Ok(IntVal::new_expr(Moo::new(expr)).ok())
420
5291289
}
421

            
422
80381
fn parse_tuple_domain(
423
80381
    ctx: &mut ParseContext,
424
80381
    tuple_domain: Node,
425
80381
) -> Result<Option<DomainPtr>, FatalParseError> {
426
80381
    let mut domains: Vec<DomainPtr> = Vec::new();
427
80381
    let representation = representation_field(ctx, tuple_domain);
428
80381
    for domain in named_children(&tuple_domain) {
429
160870
        if domain.kind() == "representation_attribute" {
430
108
            continue;
431
160762
        }
432
160762
        let Some(parsed_domain) = parse_domain(ctx, domain)? else {
433
27
            return Ok(None);
434
        };
435
160735
        domains.push(parsed_domain);
436
    }
437

            
438
    // extract the first child node which should be the 'tuple' keyword for hover info
439
80354
    if let Some(first) = tuple_domain.child(0)
440
80354
        && first.kind() == "tuple"
441
    {
442
        // Adding tuple to the source map with hover info from documentation
443
19575
        ctx.add_span_and_doc_hover(&first, "L_tuple", SymbolKind::Domain, None, None);
444
60779
    }
445

            
446
80354
    Ok(Some(with_representation(
447
80354
        Domain::tuple(domains),
448
80354
        representation,
449
80354
    )))
450
80381
}
451

            
452
290243
fn parse_matrix_domain(
453
290243
    ctx: &mut ParseContext,
454
290243
    matrix_domain: Node,
455
290243
) -> Result<Option<DomainPtr>, FatalParseError> {
456
290243
    let mut domains: Vec<DomainPtr> = Vec::new();
457
290243
    let representation = representation_field(ctx, matrix_domain);
458
290243
    let Some(index_domain_list) = field!(recover, ctx, matrix_domain, "index_domain_list") else {
459
        return Ok(None);
460
    };
461
290243
    for domain in named_children(&index_domain_list) {
462
344343
        let Some(parsed_domain) = parse_domain(ctx, domain)? else {
463
            return Ok(None);
464
        };
465
344343
        domains.push(parsed_domain);
466
    }
467
290243
    let Some(value_domain_node) = field!(recover, ctx, matrix_domain, "value_domain") else {
468
        return Ok(None);
469
    };
470
290243
    let Some(value_domain) = parse_domain(ctx, value_domain_node)? else {
471
        return Ok(None);
472
    };
473

            
474
    // Adding matrix to the source map with hover info from documentation
475
290243
    let matrix_keyword_node = child!(matrix_domain, 0, "matrix");
476
290243
    ctx.add_span_and_doc_hover(
477
290243
        &matrix_keyword_node,
478
290243
        "matrix",
479
290243
        SymbolKind::Domain,
480
290243
        None,
481
290243
        None,
482
290243
    );
483
290243
    Ok(Some(with_representation(
484
290243
        Domain::matrix(value_domain, domains),
485
290243
        representation,
486
290243
    )))
487
290243
}
488

            
489
10315
fn parse_record_domain(
490
10315
    ctx: &mut ParseContext,
491
10315
    record_domain: Node,
492
10315
) -> Result<Option<DomainPtr>, FatalParseError> {
493
10315
    let mut record_entries: Vec<Field<DomainPtr>> = Vec::new();
494
10315
    let representation = representation_field(ctx, record_domain);
495
10315
    for record_entry in named_children(&record_domain) {
496
20737
        if record_entry.kind() == "representation_attribute" {
497
108
            continue;
498
20629
        }
499
20629
        let Some(name_node) = field!(recover, ctx, record_entry, "name") else {
500
            return Ok(None);
501
        };
502
20629
        let name = Name::user(&ctx.source_code[name_node.start_byte()..name_node.end_byte()]);
503
20629
        let Some(domain_node) = field!(recover, ctx, record_entry, "domain") else {
504
            return Ok(None);
505
        };
506
20629
        let Some(value) = parse_domain(ctx, domain_node)? else {
507
            return Ok(None);
508
        };
509
20629
        record_entries.push(Field { name, value });
510
    }
511

            
512
    // Adding record keyword to the source map with hover info from documentation
513
10315
    let record_keyword_node = child!(record_domain, 0, "record");
514
10315
    ctx.add_span_and_doc_hover(
515
10315
        &record_keyword_node,
516
10315
        "L_record",
517
10315
        SymbolKind::Domain,
518
10315
        None,
519
10315
        None,
520
10315
    );
521
10315
    Ok(Some(with_representation(
522
10315
        Domain::record(record_entries),
523
10315
        representation,
524
10315
    )))
525
10315
}
526

            
527
21681
fn parse_variant_domain(
528
21681
    ctx: &mut ParseContext,
529
21681
    variant_domain: Node,
530
21681
) -> Result<Option<DomainPtr>, FatalParseError> {
531
21681
    let mut entries = Vec::new();
532
21681
    let representation = representation_field(ctx, variant_domain);
533
21681
    for entry in named_children(&variant_domain) {
534
43416
        if entry.kind() == "representation_attribute" {
535
54
            continue;
536
43362
        }
537
43362
        let Some(name_node) = field!(recover, ctx, entry, "name") else {
538
            return Ok(None);
539
        };
540
43362
        let name = Name::user(&ctx.source_code[name_node.start_byte()..name_node.end_byte()]);
541
43362
        let Some(domain_node) = field!(recover, ctx, entry, "domain") else {
542
            return Ok(None);
543
        };
544
43362
        let Some(value) = parse_domain(ctx, domain_node)? else {
545
            return Ok(None);
546
        };
547
43362
        entries.push(Field { name, value });
548
    }
549

            
550
21681
    let keyword = child!(variant_domain, 0, "variant");
551
21681
    ctx.add_span_and_doc_hover(&keyword, "variant", SymbolKind::Domain, None, None);
552
21681
    Ok(Some(with_representation(
553
21681
        Domain::variant(entries),
554
21681
        representation,
555
21681
    )))
556
21681
}
557

            
558
48174
fn parse_sequence_domain(
559
48174
    ctx: &mut ParseContext,
560
48174
    sequence_domain: Node,
561
48174
) -> Result<Option<DomainPtr>, FatalParseError> {
562
48174
    let mut size = Range::Unbounded;
563
48174
    let mut min_size = None;
564
48174
    let mut max_size = None;
565
48174
    let mut jectivity = JectivityAttr::None;
566
48174
    let mut representation = None;
567
48174
    let mut value_domain: Option<DomainPtr> = None;
568

            
569
48174
    for child in named_children(&sequence_domain) {
570
96348
        match child.kind() {
571
            "sequence_attributes" => {
572
48174
                for attribute in named_children(&child) {
573
56571
                    let name = attribute
574
56571
                        .child_by_field_name("attribute")
575
56571
                        .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
576
                        .unwrap_or_default();
577
56571
                    match name {
578
                        "size" | "minSize" | "maxSize" => {
579
51117
                            let Some(value_node) = attribute.child_by_field_name("value") else {
580
                                return Ok(None);
581
                            };
582
                            // Attribute values may be expressions over givens, e.g.
583
                            // `maxSize n`, which only become ground once the parameters are
584
                            // instantiated.
585
51117
                            let Some(value) = parse_int_val(ctx, value_node)? else {
586
                                return Ok(None);
587
                            };
588
51117
                            match name {
589
30105
                                "size" => size = Range::Single(value),
590
2943
                                "minSize" => min_size = Some(value),
591
18069
                                "maxSize" => max_size = Some(value),
592
                                _ => unreachable!(),
593
                            }
594
                        }
595
5346
                        "injective" => jectivity = JectivityAttr::Injective,
596
27
                        "surjective" => jectivity = JectivityAttr::Surjective,
597
27
                        "bijective" => jectivity = JectivityAttr::Bijective,
598
54
                        "representation" => representation = attribute_value_text(ctx, attribute),
599
                        _ => return Ok(None),
600
                    }
601
                }
602
            }
603
48174
            "domain" | "annotation_domain" => value_domain = parse_domain(ctx, child)?,
604
            _ => {}
605
        }
606
    }
607

            
608
48174
    if !matches!(size, Range::Single(_)) {
609
18069
        size = match (min_size, max_size) {
610
2943
            (Some(min), Some(max)) => Range::Bounded(min, max),
611
            (Some(min), None) => Range::UnboundedR(min),
612
15126
            (None, Some(max)) => Range::UnboundedL(max),
613
            (None, None) => Range::Unbounded,
614
        };
615
30105
    }
616

            
617
48174
    let Some(value_domain) = value_domain else {
618
        ctx.record_error(RecoverableParseError::new(
619
            "Sequence domain must have a value domain".to_string(),
620
            Some(sequence_domain.range()),
621
        ));
622
        return Ok(None);
623
    };
624

            
625
    // Adding sequence keyword to the source map with hover info from documentation
626
48174
    let sequence_keyword_node = child!(sequence_domain, 0, "sequence");
627
48174
    ctx.add_span_and_doc_hover(
628
48174
        &sequence_keyword_node,
629
48174
        "sequence",
630
48174
        SymbolKind::Domain,
631
48174
        None,
632
48174
        None,
633
48174
    );
634

            
635
48174
    let attrs = SequenceAttr {
636
48174
        size,
637
48174
        jectivity,
638
48174
        representation,
639
48174
    };
640
48174
    Ok(Some(Domain::sequence(attrs, value_domain)))
641
48174
}
642

            
643
// e.g. function int(1..3) --> int(1..3), function (total) bool --> int(13,17),
644
// function (minSize 1) int(1..2) --> set (size 1) of int(1..2). Mirrors
645
// parse_sequence_domain, plus the extra `partiality` field FuncAttr has.
646
44496
fn parse_function_domain(
647
44496
    ctx: &mut ParseContext,
648
44496
    function_domain: Node,
649
44496
) -> Result<Option<DomainPtr>, FatalParseError> {
650
44496
    let mut size = Range::Unbounded;
651
44496
    let mut min_size = None;
652
44496
    let mut max_size = None;
653
44496
    let mut partiality = PartialityAttr::Partial;
654
44496
    let mut jectivity = JectivityAttr::None;
655
44496
    let mut representation = None;
656

            
657
44496
    for child in named_children(&function_domain) {
658
132327
        if child.kind() == "function_attributes" {
659
43335
            for attribute in named_children(&child) {
660
48384
                let name = attribute
661
48384
                    .child_by_field_name("attribute")
662
48384
                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
663
                    .unwrap_or_default();
664
48384
                match name {
665
                    "size" | "minSize" | "maxSize" => {
666
1674
                        let Some(value_node) = attribute.child_by_field_name("value") else {
667
                            return Ok(None);
668
                        };
669
1674
                        let Some(value) = parse_int_val(ctx, value_node)? else {
670
                            return Ok(None);
671
                        };
672
1674
                        match name {
673
108
                            "size" => size = Range::Single(value),
674
594
                            "minSize" => min_size = Some(value),
675
972
                            "maxSize" => max_size = Some(value),
676
                            _ => unreachable!(),
677
                        }
678
                    }
679
42282
                    "total" => partiality = PartialityAttr::Total,
680
2133
                    "injective" => jectivity = JectivityAttr::Injective,
681
756
                    "surjective" => jectivity = JectivityAttr::Surjective,
682
1485
                    "bijective" => jectivity = JectivityAttr::Bijective,
683
54
                    "representation" => representation = attribute_value_text(ctx, attribute),
684
                    _ => return Ok(None),
685
                }
686
            }
687
88992
        }
688
    }
689

            
690
44496
    if !matches!(size, Range::Single(_)) {
691
44388
        size = match (min_size, max_size) {
692
486
            (Some(min), Some(max)) => Range::Bounded(min, max),
693
108
            (Some(min), None) => Range::UnboundedR(min),
694
486
            (None, Some(max)) => Range::UnboundedL(max),
695
43308
            (None, None) => Range::Unbounded,
696
        };
697
108
    }
698

            
699
44496
    let Some(domain_from_node) = function_domain.child_by_field_name("domain_from") else {
700
        ctx.record_error(RecoverableParseError::new(
701
            "Function domain must have a domain".to_string(),
702
            Some(function_domain.range()),
703
        ));
704
        return Ok(None);
705
    };
706
44496
    let Some(domain_from) = parse_domain(ctx, domain_from_node)? else {
707
        return Ok(None);
708
    };
709

            
710
44496
    let Some(domain_to_node) = function_domain.child_by_field_name("domain_to") else {
711
        ctx.record_error(RecoverableParseError::new(
712
            "Function domain must have a codomain".to_string(),
713
            Some(function_domain.range()),
714
        ));
715
        return Ok(None);
716
    };
717
44496
    let Some(domain_to) = parse_domain(ctx, domain_to_node)? else {
718
        return Ok(None);
719
    };
720

            
721
    // Adding function keyword to the source map with hover info from documentation
722
44496
    let function_keyword_node = child!(function_domain, 0, "function");
723
44496
    ctx.add_span_and_doc_hover(
724
44496
        &function_keyword_node,
725
44496
        "function",
726
44496
        SymbolKind::Domain,
727
44496
        None,
728
44496
        None,
729
44496
    );
730

            
731
44496
    let attrs = FuncAttr {
732
44496
        size,
733
44496
        partiality,
734
44496
        jectivity,
735
44496
        representation,
736
44496
    };
737
44496
    Ok(Some(Domain::function(attrs, domain_from, domain_to)))
738
44496
}
739

            
740
// e.g. relation of (int(1..3) * bool), relation (size 2, irreflexive) of (int(0..5) * int(0..5)).
741
// Binary relation attributes only make sense for a binary relation whose two columns share a
742
// domain; that constraint is enforced by the representations (`init`), not the parser.
743
3024
fn parse_relation_domain(
744
3024
    ctx: &mut ParseContext,
745
3024
    relation_domain: Node,
746
3024
) -> Result<Option<DomainPtr>, FatalParseError> {
747
3024
    let mut size = Range::Unbounded;
748
3024
    let mut min_size = None;
749
3024
    let mut max_size = None;
750
3024
    let mut binary = Vec::new();
751
3024
    let mut representation = None;
752

            
753
3024
    for child in named_children(&relation_domain) {
754
3942
        if child.kind() == "relation_attributes" {
755
918
            for attribute in named_children(&child) {
756
1485
                let name = attribute
757
1485
                    .child_by_field_name("attribute")
758
1485
                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
759
                    .unwrap_or_default();
760
1485
                match name {
761
                    "size" | "minSize" | "maxSize" => {
762
297
                        let Some(value_node) = attribute.child_by_field_name("value") else {
763
                            return Ok(None);
764
                        };
765
297
                        let Some(value) = parse_int_val(ctx, value_node)? else {
766
                            return Ok(None);
767
                        };
768
297
                        match name {
769
108
                            "size" => size = Range::Single(value),
770
                            "minSize" => min_size = Some(value),
771
189
                            "maxSize" => max_size = Some(value),
772
                            _ => unreachable!(),
773
                        }
774
                    }
775
54
                    "representation" => representation = attribute_value_text(ctx, attribute),
776
                    _ => {
777
1134
                        let Some(bin_attr) = BinaryAttr::from_keyword(name) else {
778
                            return Ok(None);
779
                        };
780
1134
                        binary.push(bin_attr);
781
                    }
782
                }
783
            }
784
3024
        }
785
    }
786

            
787
3024
    if !matches!(size, Range::Single(_)) {
788
2916
        size = match (min_size, max_size) {
789
            (Some(min), Some(max)) => Range::Bounded(min, max),
790
            (Some(min), None) => Range::UnboundedR(min),
791
189
            (None, Some(max)) => Range::UnboundedL(max),
792
2727
            (None, None) => Range::Unbounded,
793
        };
794
108
    }
795

            
796
3024
    let Some(column_list) = field!(recover, ctx, relation_domain, "relation_domain_list") else {
797
        return Ok(None);
798
    };
799
3024
    let mut columns: Vec<DomainPtr> = Vec::new();
800
3024
    for column in named_children(&column_list) {
801
6183
        let Some(parsed) = parse_domain(ctx, column)? else {
802
            return Ok(None);
803
        };
804
6183
        columns.push(parsed);
805
    }
806

            
807
    // Adding relation keyword to the source map with hover info from documentation
808
3024
    let relation_keyword_node = child!(relation_domain, 0, "relation");
809
3024
    ctx.add_span_and_doc_hover(
810
3024
        &relation_keyword_node,
811
3024
        "relation",
812
3024
        SymbolKind::Domain,
813
3024
        None,
814
3024
        None,
815
3024
    );
816

            
817
3024
    let attrs = RelAttr {
818
3024
        size,
819
3024
        binary,
820
3024
        representation,
821
3024
    };
822
3024
    Ok(Some(Domain::relation(attrs, columns)))
823
3024
}
824

            
825
1080
fn parse_partition_domain(
826
1080
    ctx: &mut ParseContext,
827
1080
    partition_domain: Node,
828
1080
) -> Result<Option<DomainPtr>, FatalParseError> {
829
1080
    let mut num_parts = Range::Unbounded;
830
1080
    let mut min_num_parts = None;
831
1080
    let mut max_num_parts = None;
832
1080
    let mut part_len = Range::Unbounded;
833
1080
    let mut min_part_len = None;
834
1080
    let mut max_part_len = None;
835
1080
    let mut is_regular = false;
836
1080
    let mut representation = None;
837

            
838
1080
    for child in named_children(&partition_domain) {
839
1836
        if child.kind() == "partition_attributes" {
840
756
            for attribute in named_children(&child) {
841
2376
                let name = attribute
842
2376
                    .child_by_field_name("attribute")
843
2376
                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
844
                    .unwrap_or_default();
845
2376
                match name {
846
                    "numParts" | "minNumParts" | "maxNumParts" | "partSize" | "minPartSize"
847
                    | "maxPartSize" => {
848
1944
                        let Some(value_node) = attribute.child_by_field_name("value") else {
849
                            return Ok(None);
850
                        };
851
1944
                        let Some(value) = parse_int_val(ctx, value_node)? else {
852
                            return Ok(None);
853
                        };
854
1944
                        match name {
855
162
                            "numParts" => num_parts = Range::Single(value),
856
378
                            "minNumParts" => min_num_parts = Some(value),
857
432
                            "maxNumParts" => max_num_parts = Some(value),
858
162
                            "partSize" => part_len = Range::Single(value),
859
432
                            "minPartSize" => min_part_len = Some(value),
860
378
                            "maxPartSize" => max_part_len = Some(value),
861
                            _ => unreachable!(),
862
                        }
863
                    }
864
378
                    "regular" => is_regular = true,
865
54
                    "representation" => representation = attribute_value_text(ctx, attribute),
866
                    _ => return Ok(None),
867
                }
868
            }
869
1080
        }
870
    }
871

            
872
1080
    if !matches!(num_parts, Range::Single(_)) {
873
918
        num_parts = match (min_num_parts, max_num_parts) {
874
378
            (Some(min), Some(max)) => Range::Bounded(min, max),
875
            (Some(min), None) => Range::UnboundedR(min),
876
54
            (None, Some(max)) => Range::UnboundedL(max),
877
486
            (None, None) => Range::Unbounded,
878
        };
879
162
    }
880
1080
    if !matches!(part_len, Range::Single(_)) {
881
918
        part_len = match (min_part_len, max_part_len) {
882
378
            (Some(min), Some(max)) => Range::Bounded(min, max),
883
54
            (Some(min), None) => Range::UnboundedR(min),
884
            (None, Some(max)) => Range::UnboundedL(max),
885
486
            (None, None) => Range::Unbounded,
886
        };
887
162
    }
888

            
889
1080
    let Some(value_domain) = field!(recover, ctx, partition_domain, "value_domain") else {
890
        return Ok(None);
891
    };
892
1080
    let Some(inner) = parse_domain(ctx, value_domain)? else {
893
        return Ok(None);
894
    };
895

            
896
1080
    let partition_keyword_node = child!(partition_domain, 0, "partition");
897
1080
    ctx.add_span_and_doc_hover(
898
1080
        &partition_keyword_node,
899
1080
        "partition",
900
1080
        SymbolKind::Domain,
901
1080
        None,
902
1080
        None,
903
1080
    );
904

            
905
1080
    let attrs = PartitionAttr {
906
1080
        num_parts,
907
1080
        part_len,
908
1080
        is_regular,
909
1080
        representation,
910
1080
    };
911
1080
    Ok(Some(Domain::partition(attrs, inner)))
912
1080
}
913

            
914
11261
fn parse_permutation_domain(
915
11261
    ctx: &mut ParseContext,
916
11261
    permutation_domain: Node,
917
11261
) -> Result<Option<DomainPtr>, FatalParseError> {
918
11261
    let mut num_moved = Range::Unbounded;
919
11261
    let mut min_num_moved = None;
920
11261
    let mut max_num_moved = None;
921
11261
    let mut representation = None;
922

            
923
11261
    for child in named_children(&permutation_domain) {
924
11586
        if child.kind() == "permutation_attributes" {
925
325
            for attribute in named_children(&child) {
926
487
                let name = attribute
927
487
                    .child_by_field_name("attribute")
928
487
                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
929
                    .unwrap_or_default();
930
487
                if name == "representation" {
931
54
                    representation = attribute_value_text(ctx, attribute);
932
54
                    continue;
933
433
                }
934
433
                let Some(value_node) = attribute.child_by_field_name("value") else {
935
                    return Ok(None);
936
                };
937
433
                let Some(value) = parse_int_val(ctx, value_node)? else {
938
                    return Ok(None);
939
                };
940
433
                match name {
941
109
                    "numMoved" => num_moved = Range::Single(value),
942
162
                    "minNumMoved" => min_num_moved = Some(value),
943
162
                    "maxNumMoved" => max_num_moved = Some(value),
944
                    _ => return Ok(None),
945
                }
946
            }
947
11261
        }
948
    }
949

            
950
11261
    if !matches!(num_moved, Range::Single(_)) {
951
11152
        num_moved = match (min_num_moved, max_num_moved) {
952
162
            (Some(min), Some(max)) => Range::Bounded(min, max),
953
            (Some(min), None) => Range::UnboundedR(min),
954
            (None, Some(max)) => Range::UnboundedL(max),
955
10990
            (None, None) => Range::Unbounded,
956
        };
957
109
    }
958

            
959
11261
    let Some(value_domain) = field!(recover, ctx, permutation_domain, "value_domain") else {
960
        return Ok(None);
961
    };
962
11261
    let Some(inner) = parse_domain(ctx, value_domain)? else {
963
        return Ok(None);
964
    };
965

            
966
11261
    let permutation_keyword_node = child!(permutation_domain, 0, "permutation");
967
11261
    ctx.add_span_and_doc_hover(
968
11261
        &permutation_keyword_node,
969
11261
        "permutation",
970
11261
        SymbolKind::Domain,
971
11261
        None,
972
11261
        None,
973
11261
    );
974

            
975
11261
    let attrs = PermutationAttr {
976
11261
        num_moved,
977
11261
        representation,
978
11261
    };
979
11261
    Ok(Some(Domain::permutation(attrs, inner)))
980
11261
}
981

            
982
258378
pub fn parse_set_domain(
983
258378
    ctx: &mut ParseContext,
984
258378
    set_domain: Node,
985
258378
) -> Result<Option<DomainPtr>, FatalParseError> {
986
258378
    let mut size = Range::Unbounded;
987
258378
    let mut min_size = None;
988
258378
    let mut max_size = None;
989
258378
    let mut representation = None;
990
258378
    let mut value_domain: Option<DomainPtr> = None;
991

            
992
258378
    for child in named_children(&set_domain) {
993
412206
        match child.kind() {
994
            "set_attributes" => {
995
153855
                for attribute in named_children(&child) {
996
154371
                    let Some(value_node) = attribute.child_by_field_name("value") else {
997
                        return Ok(None);
998
                    };
999
154371
                    let name = attribute
154371
                        .child_by_field_name("attribute")
154371
                        .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
                        .unwrap_or_default();
154371
                    if name == "representation" {
429
                        representation = Some(
429
                            ctx.source_code[value_node.start_byte()..value_node.end_byte()]
429
                                .to_string(),
429
                        );
429
                        continue;
153942
                    }
                    // Attribute values may be expressions over givens, e.g. `maxSize |nums|`,
                    // which only become ground once the parameters are instantiated.
153942
                    let Some(value) = parse_int_val(ctx, value_node)? else {
27
                        return Ok(None);
                    };
153915
                    match name {
79368
                        "size" => size = Range::Single(value),
46647
                        "minSize" => min_size = Some(value),
27900
                        "maxSize" => max_size = Some(value),
                        _ => return Ok(None),
                    }
                }
            }
            "domain" | "annotation_domain" => {
258351
                let Some(parsed_domain) = parse_domain(ctx, child)? else {
                    return Ok(None);
                };
258351
                value_domain = Some(parsed_domain);
            }
            _ => {
                ctx.record_error(RecoverableParseError::new(
                    format!("Unrecognized set domain child kind: {}", child.kind()),
                    Some(child.range()),
                ));
                return Ok(None);
            }
        }
    }
258351
    if let Some(domain) = value_domain {
        // Adding set to the source map with hover info from documentation
258351
        let set_keyword_node = child!(set_domain, 0, "set");
        // No documentation available for set domain, using fallback description
258351
        ctx.add_span_and_doc_hover(&set_keyword_node, "set", SymbolKind::Domain, None, None);
258351
        if !matches!(size, Range::Single(_)) {
178983
            size = match (min_size, max_size) {
342
                (Some(min), Some(max)) => Range::Bounded(min, max),
46305
                (Some(min), None) => Range::UnboundedR(min),
27558
                (None, Some(max)) => Range::UnboundedL(max),
104778
                (None, None) => Range::Unbounded,
            };
79368
        }
258351
        let mut attr = SetAttr::new(size);
258351
        if let Some(repr) = representation {
429
            attr = attr.with_representation(repr);
257922
        }
258351
        Ok(Some(Domain::set(attr, domain)))
    } else {
        ctx.record_error(RecoverableParseError::new(
            "Set domain must have a value domain".to_string(),
            Some(set_domain.range()),
        ));
        Ok(None)
    }
258378
}
/// Parses `node` when it denotes a collection of integers, for `int(<collection>)`.
///
/// Returns `None` without recording an error when it is something else, so the caller can carry on
/// reading the node as an ordinary range bound.
87051
fn parse_collection_valued_expression(
87051
    ctx: &mut ParseContext,
87051
    node: Node,
87051
) -> Result<Option<Expression>, FatalParseError> {
87051
    let saved_context = ctx.typechecking_context;
87051
    let saved_inner_context = ctx.inner_typechecking_context;
87051
    ctx.typechecking_context = TypecheckingContext::Unknown;
87051
    ctx.inner_typechecking_context = TypecheckingContext::Unknown;
87051
    let parsed = parse_expression(ctx, node);
87051
    ctx.typechecking_context = saved_context;
87051
    ctx.inner_typechecking_context = saved_inner_context;
87051
    let Some(expr) = parsed? else {
        return Ok(None);
    };
    use conjure_cp_core::ast::Typeable;
    // A comprehension's return type is its *element* type, so the variant has to be recognised
    // directly rather than asked for its type.
87051
    if matches!(expr, Expression::Comprehension(_, _)) {
        return Ok(Some(expr));
87051
    }
87051
    Ok(matches!(
87051
        expr.return_type(),
        conjure_cp_core::ast::ReturnType::Set(_)
            | conjure_cp_core::ast::ReturnType::MSet(_)
            | conjure_cp_core::ast::ReturnType::Matrix(_)
            | conjure_cp_core::ast::ReturnType::Sequence(_)
    )
87051
    .then_some(expr))
87051
}
6
fn parse_enum_domain(
6
    ctx: &mut ParseContext,
6
    node: Node,
6
) -> Result<Option<DomainPtr>, FatalParseError> {
6
    let Some(name) = field!(recover, ctx, node, "name") else {
        return Ok(None);
    };
6
    let Some(declaration) = get_declaration_ptr_from_identifier(ctx, name)? else {
        return Ok(None);
    };
6
    let Some(ty) = declaration.as_enumerated_type().map(|ty| ty.clone()) else {
        ctx.record_error(RecoverableParseError::new(
            "Expected an enumerated type".to_owned(),
            Some(name.range()),
        ));
        return Ok(None);
    };
6
    let Some(ranges_node) = field!(recover, ctx, node, "ranges") else {
        return Ok(None);
    };
6
    let mut ranges = Vec::new();
6
    for range in named_children(&ranges_node) {
12
        let mut parse_bound = |bound| -> Result<Option<EnumVariantVal>, FatalParseError> {
12
            let saved = ctx.typechecking_context;
12
            ctx.typechecking_context = TypecheckingContext::Unknown;
12
            let result = parse_expression(ctx, bound);
12
            ctx.typechecking_context = saved;
12
            let Some(expression) = result? else {
                return Ok(None);
            };
12
            if let Expression::Atomic(_, Atom::Reference(reference)) = expression
12
                && reference.return_type()
12
                    == conjure_cp_core::ast::ReturnType::EnumeratedType(ty.clone())
            {
12
                return Ok(Some(EnumVariantVal(reference)));
            }
            ctx.record_error(RecoverableParseError::new(
                "Expected a member of this enumerated type".to_owned(),
                Some(bound.range()),
            ));
            Ok(None)
12
        };
6
        if range.kind() == "int_range" {
6
            let lower = match range.child_by_field_name("lower") {
                Some(bound) => {
6
                    let Some(value) = parse_bound(bound)? else {
                        return Ok(None);
                    };
6
                    Some(value)
                }
                None => None,
            };
6
            let upper = match range.child_by_field_name("upper") {
                Some(bound) => {
6
                    let Some(value) = parse_bound(bound)? else {
                        return Ok(None);
                    };
6
                    Some(value)
                }
                None => None,
            };
6
            ranges.push(match (lower, upper) {
6
                (Some(a), Some(b)) => Range::Bounded(a, b),
                (Some(a), None) => Range::UnboundedR(a),
                (None, Some(b)) => Range::UnboundedL(b),
                (None, None) => Range::Unbounded,
            });
        } else {
            let Some(value) = parse_bound(range)? else {
                return Ok(None);
            };
            ranges.push(Range::Single(value));
        }
    }
6
    Ok(Some(Domain::enumerated(ty, ranges)))
6
}