Skip to main content

conjure_cp_essence_parser/parser/
domain.rs

1use super::util::named_children;
2use crate::diagnostics::diagnostics_api::SymbolKind;
3use crate::diagnostics::source_map::{HoverInfo, span_with_hover};
4use crate::errors::FatalParseError;
5use crate::expression::parse_expression;
6use crate::parser::ParseContext;
7use crate::util::TypecheckingContext;
8use crate::{RecoverableParseError, child};
9use conjure_cp_core::ast::Typeable;
10use 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};
15use tree_sitter::Node;
16
17use crate::field;
18
19/// Parse an Essence variable domain into its Conjure AST representation.
20pub fn parse_domain(
21    ctx: &mut ParseContext,
22    domain: Node,
23) -> Result<Option<DomainPtr>, FatalParseError> {
24    match domain.kind() {
25        "domain" | "annotation_domain" => {
26            let inner = match domain.child(0) {
27                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            parse_domain(ctx, inner)
37        }
38        "enum_domain" => parse_enum_domain(ctx, domain),
39        "bool_domain" => {
40            ctx.add_span_and_doc_hover(&domain, "L_bool", SymbolKind::Domain, None, None);
41            Ok(Some(Domain::bool()))
42        }
43        "int_domain" | "annotation_int_domain" => parse_int_domain(ctx, domain),
44        "identifier" => {
45            let Some(decl) = get_declaration_ptr_from_identifier(ctx, domain)? else {
46                return Ok(None);
47            };
48            let is_unnamed = decl.as_unnamed_type().is_some();
49            let type_domain = if is_unnamed {
50                decl.domain()
51            } else {
52                decl.as_enumerated_type().map(|ty| ty.to_domain())
53            };
54            let Some(dom) = type_domain.or_else(|| Domain::reference(decl)) else {
55                ctx.record_error(crate::errors::RecoverableParseError::new(
56                    format!(
57                        "The identifier '{}' is not a valid domain",
58                        &ctx.source_code[domain.start_byte()..domain.end_byte()]
59                    ),
60                    Some(domain.range()),
61                ));
62                return Ok(None);
63            };
64            let name = &ctx.source_code[domain.start_byte()..domain.end_byte()];
65
66            // Not form docs, because we need context specific hover info
67            span_with_hover(
68                &domain,
69                ctx.source_code,
70                ctx.source_map,
71                HoverInfo {
72                    description: format!("Domain reference: {name}"),
73                    doc_key: None,
74                    kind: Some(SymbolKind::Variable),
75                    ty: None,
76                    decl_span: None, // could link to the declaration span if we wanted
77                },
78            );
79            Ok(Some(dom))
80        }
81        "tuple_domain" | "annotation_tuple_domain" => parse_tuple_domain(ctx, domain),
82        "matrix_domain" | "annotation_matrix_domain" => parse_matrix_domain(ctx, domain),
83        "record_domain" | "annotation_record_domain" => parse_record_domain(ctx, domain),
84        "variant_domain" | "annotation_variant_domain" => parse_variant_domain(ctx, domain),
85        "set_domain" | "annotation_set_domain" => parse_set_domain(ctx, domain),
86        "mset_domain" | "annotation_mset_domain" => parse_mset_domain(ctx, domain),
87        "sequence_domain" | "annotation_sequence_domain" => parse_sequence_domain(ctx, domain),
88        "function_domain" | "annotation_function_domain" => parse_function_domain(ctx, domain),
89        "relation_domain" => parse_relation_domain(ctx, domain),
90        "partition_domain" => parse_partition_domain(ctx, domain),
91        "permutation_domain" => parse_permutation_domain(ctx, domain),
92        _ => {
93            ctx.record_error(RecoverableParseError::new(
94                format!("{} is not a supported domain type", domain.kind()),
95                Some(domain.range()),
96            ));
97            Ok(None)
98        }
99    }
100}
101
102fn parse_mset_domain(
103    ctx: &mut ParseContext,
104    mset_domain: Node,
105) -> Result<Option<DomainPtr>, FatalParseError> {
106    let mut representation = None;
107    let mut size = Range::Unbounded;
108    let mut occurrence = Range::Unbounded;
109    let mut min_size = None;
110    let mut max_size = None;
111    let mut min_occurrence = None;
112    let mut max_occurrence = None;
113    let mut value_domain = None;
114
115    for child in named_children(&mset_domain) {
116        match child.kind() {
117            "identifier" => {}
118            "mset_attributes" => {
119                for attribute in named_children(&child) {
120                    let Some(value_node) = attribute.child_by_field_name("value") else {
121                        return Ok(None);
122                    };
123                    let name = attribute
124                        .child_by_field_name("attribute")
125                        .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
126                        .unwrap_or_default();
127                    if name == "representation" {
128                        representation = Some(
129                            ctx.source_code[value_node.start_byte()..value_node.end_byte()]
130                                .to_string(),
131                        );
132                        continue;
133                    }
134                    // Attribute values may be expressions over givens, e.g. `maxSize |nums|`,
135                    // which only become ground once the parameters are instantiated.
136                    let Some(value) = parse_int_val(ctx, value_node)? else {
137                        return Ok(None);
138                    };
139                    match name {
140                        "size" => size = Range::Single(value),
141                        "minSize" => min_size = Some(value),
142                        "maxSize" => max_size = Some(value),
143                        "minOccur" => min_occurrence = Some(value),
144                        "maxOccur" => max_occurrence = Some(value),
145                        _ => return Ok(None),
146                    }
147                }
148            }
149            "domain" | "annotation_domain" => value_domain = parse_domain(ctx, child)?,
150            _ => {}
151        }
152    }
153
154    if !matches!(size, Range::Single(_)) {
155        size = match (min_size, max_size) {
156            (Some(min), Some(max)) => Range::Bounded(min, max),
157            (Some(min), None) => Range::UnboundedR(min),
158            (None, Some(max)) => Range::UnboundedL(max),
159            (None, None) => Range::Unbounded,
160        };
161    }
162    occurrence = match (min_occurrence, max_occurrence) {
163        (Some(min), Some(max)) => Range::Bounded(min, max),
164        (Some(min), None) => Range::UnboundedR(min),
165        (None, Some(max)) => Range::UnboundedL(max),
166        (None, None) => occurrence,
167    };
168
169    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    let mut attrs = MSetAttr::new(size, occurrence);
177    if let Some(representation) = representation {
178        attrs = attrs.with_representation(representation);
179    }
180    Ok(Some(Domain::mset(attrs, value_domain)))
181}
182
183fn get_declaration_ptr_from_identifier(
184    ctx: &mut ParseContext,
185    identifier: Node,
186) -> Result<Option<DeclarationPtr>, FatalParseError> {
187    let name = Name::user(&ctx.source_code[identifier.start_byte()..identifier.end_byte()]);
188    let decl = ctx.symbols.as_ref().unwrap().read().lookup(&name);
189
190    if decl.is_none() {
191        ctx.record_error(crate::errors::RecoverableParseError::new(
192            format!("The identifier '{}' is not defined", name),
193            Some(identifier.range()),
194        ));
195        return Ok(None);
196    }
197    match decl {
198        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}
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 ...`.
211fn representation_field(ctx: &ParseContext, domain: Node) -> Option<String> {
212    let value = domain
213        .child_by_field_name("representation")?
214        .child_by_field_name("value")?;
215    Some(ctx.source_code[value.start_byte()..value.end_byte()].to_string())
216}
217
218/// The value of an attribute node in an attribute list, e.g. `packed` in `representation packed`.
219fn attribute_value_text(ctx: &ParseContext, attribute: Node) -> Option<String> {
220    let value = attribute.child_by_field_name("value")?;
221    Some(ctx.source_code[value.start_byte()..value.end_byte()].to_string())
222}
223
224/// Apply the preference written on a domain, if any, to the domain just built from it.
225fn with_representation(domain: DomainPtr, representation: Option<String>) -> DomainPtr {
226    match representation {
227        Some(representation) => domain.with_representation_preference(&representation),
228        None => domain,
229    }
230}
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)`.
234fn parse_int_domain(
235    ctx: &mut ParseContext,
236    int_domain: Node,
237) -> Result<Option<DomainPtr>, FatalParseError> {
238    let representation = representation_field(ctx, int_domain);
239    let Some(domain) = parse_int_domain_ranges(ctx, int_domain, representation.is_some())? else {
240        return Ok(None);
241    };
242    Ok(Some(match representation {
243        Some(representation) => domain.with_representation_preference(&representation),
244        None => domain,
245    }))
246}
247
248fn parse_int_domain_ranges(
249    ctx: &mut ParseContext,
250    int_domain: Node,
251    has_representation: bool,
252) -> Result<Option<DomainPtr>, FatalParseError> {
253    let int_keyword_node = child!(int_domain, 0, "int");
254
255    let Some(range_list) = int_domain.child_by_field_name("ranges") else {
256        ctx.add_span_and_doc_hover(&int_keyword_node, "L_int", SymbolKind::Domain, None, None);
257        let int_text = ctx.source_code[int_domain.start_byte()..int_domain.end_byte()].trim();
258        return if int_text == "int" || has_representation {
259            Ok(Some(Domain::int_ground(vec![Range::Unbounded])))
260        } else {
261            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    let components: Vec<_> = named_children(&range_list).collect();
267    if let [only] = components.as_slice()
268        && matches!(only.kind(), "atom" | "arithmetic_expr")
269        && 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    }
274
275    let mut ranges_unresolved: Vec<Range<IntVal>> = Vec::new();
276    let mut all_resolved = true;
277
278    for domain_component in named_children(&range_list) {
279        match domain_component.kind() {
280            "atom" | "arithmetic_expr" | "integer" | "identifier" => {
281                let Some(int_val) = parse_int_val(ctx, domain_component)? else {
282                    return Ok(None);
283                };
284
285                if !matches!(int_val, IntVal::Const(_)) {
286                    all_resolved = false;
287                }
288                ranges_unresolved.push(Range::Single(int_val));
289            }
290            "int_range" | "annotation_int_range" => {
291                let lower_bound = match domain_component.child_by_field_name("lower") {
292                    Some(node) => {
293                        match parse_int_val(ctx, node)? {
294                            Some(val) => Some(val),
295                            None => return Ok(None), // semantic error occurred
296                        }
297                    }
298                    None => None,
299                };
300                let upper_bound = match domain_component.child_by_field_name("upper") {
301                    Some(node) => {
302                        match parse_int_val(ctx, node)? {
303                            Some(val) => Some(val),
304                            None => return Ok(None), // semantic error occurred
305                        }
306                    }
307                    None => None,
308                };
309
310                match (lower_bound, upper_bound) {
311                    (Some(lower), Some(upper)) => {
312                        if !matches!((&lower, &upper), (IntVal::Const(_), IntVal::Const(_))) {
313                            all_resolved = false;
314                        }
315                        ranges_unresolved.push(Range::Bounded(lower, upper));
316                    }
317                    (Some(lower), None) => {
318                        if !matches!(lower, IntVal::Const(_)) {
319                            all_resolved = false;
320                        }
321                        ranges_unresolved.push(Range::UnboundedR(lower));
322                    }
323                    (None, Some(upper)) => {
324                        if !matches!(upper, IntVal::Const(_)) {
325                            all_resolved = false;
326                        }
327                        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    if all_resolved {
354        let ranges: Vec<Range<i32>> = ranges_unresolved
355            .into_iter()
356            .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            .filter(|range| !matches!(range, Range::Bounded(lower, upper) if lower > upper))
366            .collect();
367
368        ctx.add_span_and_doc_hover(&int_keyword_node, "L_int", SymbolKind::Domain, None, None);
369        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        ctx.add_span_and_doc_hover(&int_keyword_node, "L_int", SymbolKind::Domain, None, None);
375        Ok(Some(Domain::int(ranges_unresolved)))
376    }
377}
378
379// Helper function to parse a node into an IntVal
380// Handles constants, references, and arbitrary expressions
381fn parse_int_val(ctx: &mut ParseContext, node: Node) -> Result<Option<IntVal>, FatalParseError> {
382    if matches!(node.kind(), "atom" | "integer") {
383        let text = &ctx.source_code[node.start_byte()..node.end_byte()];
384        if let Ok(integer) = text.parse::<i32>() {
385            return Ok(Some(IntVal::new_const(integer)));
386        }
387    }
388
389    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    }
396
397    let saved_context = ctx.typechecking_context;
398    let saved_inner_context = ctx.inner_typechecking_context;
399    ctx.typechecking_context = TypecheckingContext::Arithmetic;
400    ctx.inner_typechecking_context = TypecheckingContext::Arithmetic;
401    let expr = parse_expression(ctx, node)?;
402    ctx.typechecking_context = saved_context;
403    ctx.inner_typechecking_context = saved_inner_context;
404
405    let Some(expr) = expr else {
406        return Ok(None);
407    };
408
409    if let Expression::Atomic(_, Atom::Reference(reference)) = &expr
410        && let Ok(reference_val) = IntVal::new_ref(reference)
411    {
412        return Ok(Some(reference_val));
413    }
414
415    if let Expression::Atomic(_, Atom::Literal(Literal::Int(value))) = expr {
416        return Ok(Some(IntVal::new_const(value)));
417    }
418
419    Ok(IntVal::new_expr(Moo::new(expr)).ok())
420}
421
422fn parse_tuple_domain(
423    ctx: &mut ParseContext,
424    tuple_domain: Node,
425) -> Result<Option<DomainPtr>, FatalParseError> {
426    let mut domains: Vec<DomainPtr> = Vec::new();
427    let representation = representation_field(ctx, tuple_domain);
428    for domain in named_children(&tuple_domain) {
429        if domain.kind() == "representation_attribute" {
430            continue;
431        }
432        let Some(parsed_domain) = parse_domain(ctx, domain)? else {
433            return Ok(None);
434        };
435        domains.push(parsed_domain);
436    }
437
438    // extract the first child node which should be the 'tuple' keyword for hover info
439    if let Some(first) = tuple_domain.child(0)
440        && first.kind() == "tuple"
441    {
442        // Adding tuple to the source map with hover info from documentation
443        ctx.add_span_and_doc_hover(&first, "L_tuple", SymbolKind::Domain, None, None);
444    }
445
446    Ok(Some(with_representation(
447        Domain::tuple(domains),
448        representation,
449    )))
450}
451
452fn parse_matrix_domain(
453    ctx: &mut ParseContext,
454    matrix_domain: Node,
455) -> Result<Option<DomainPtr>, FatalParseError> {
456    let mut domains: Vec<DomainPtr> = Vec::new();
457    let representation = representation_field(ctx, matrix_domain);
458    let Some(index_domain_list) = field!(recover, ctx, matrix_domain, "index_domain_list") else {
459        return Ok(None);
460    };
461    for domain in named_children(&index_domain_list) {
462        let Some(parsed_domain) = parse_domain(ctx, domain)? else {
463            return Ok(None);
464        };
465        domains.push(parsed_domain);
466    }
467    let Some(value_domain_node) = field!(recover, ctx, matrix_domain, "value_domain") else {
468        return Ok(None);
469    };
470    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    let matrix_keyword_node = child!(matrix_domain, 0, "matrix");
476    ctx.add_span_and_doc_hover(
477        &matrix_keyword_node,
478        "matrix",
479        SymbolKind::Domain,
480        None,
481        None,
482    );
483    Ok(Some(with_representation(
484        Domain::matrix(value_domain, domains),
485        representation,
486    )))
487}
488
489fn parse_record_domain(
490    ctx: &mut ParseContext,
491    record_domain: Node,
492) -> Result<Option<DomainPtr>, FatalParseError> {
493    let mut record_entries: Vec<Field<DomainPtr>> = Vec::new();
494    let representation = representation_field(ctx, record_domain);
495    for record_entry in named_children(&record_domain) {
496        if record_entry.kind() == "representation_attribute" {
497            continue;
498        }
499        let Some(name_node) = field!(recover, ctx, record_entry, "name") else {
500            return Ok(None);
501        };
502        let name = Name::user(&ctx.source_code[name_node.start_byte()..name_node.end_byte()]);
503        let Some(domain_node) = field!(recover, ctx, record_entry, "domain") else {
504            return Ok(None);
505        };
506        let Some(value) = parse_domain(ctx, domain_node)? else {
507            return Ok(None);
508        };
509        record_entries.push(Field { name, value });
510    }
511
512    // Adding record keyword to the source map with hover info from documentation
513    let record_keyword_node = child!(record_domain, 0, "record");
514    ctx.add_span_and_doc_hover(
515        &record_keyword_node,
516        "L_record",
517        SymbolKind::Domain,
518        None,
519        None,
520    );
521    Ok(Some(with_representation(
522        Domain::record(record_entries),
523        representation,
524    )))
525}
526
527fn parse_variant_domain(
528    ctx: &mut ParseContext,
529    variant_domain: Node,
530) -> Result<Option<DomainPtr>, FatalParseError> {
531    let mut entries = Vec::new();
532    let representation = representation_field(ctx, variant_domain);
533    for entry in named_children(&variant_domain) {
534        if entry.kind() == "representation_attribute" {
535            continue;
536        }
537        let Some(name_node) = field!(recover, ctx, entry, "name") else {
538            return Ok(None);
539        };
540        let name = Name::user(&ctx.source_code[name_node.start_byte()..name_node.end_byte()]);
541        let Some(domain_node) = field!(recover, ctx, entry, "domain") else {
542            return Ok(None);
543        };
544        let Some(value) = parse_domain(ctx, domain_node)? else {
545            return Ok(None);
546        };
547        entries.push(Field { name, value });
548    }
549
550    let keyword = child!(variant_domain, 0, "variant");
551    ctx.add_span_and_doc_hover(&keyword, "variant", SymbolKind::Domain, None, None);
552    Ok(Some(with_representation(
553        Domain::variant(entries),
554        representation,
555    )))
556}
557
558fn parse_sequence_domain(
559    ctx: &mut ParseContext,
560    sequence_domain: Node,
561) -> Result<Option<DomainPtr>, FatalParseError> {
562    let mut size = Range::Unbounded;
563    let mut min_size = None;
564    let mut max_size = None;
565    let mut jectivity = JectivityAttr::None;
566    let mut representation = None;
567    let mut value_domain: Option<DomainPtr> = None;
568
569    for child in named_children(&sequence_domain) {
570        match child.kind() {
571            "sequence_attributes" => {
572                for attribute in named_children(&child) {
573                    let name = attribute
574                        .child_by_field_name("attribute")
575                        .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
576                        .unwrap_or_default();
577                    match name {
578                        "size" | "minSize" | "maxSize" => {
579                            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                            let Some(value) = parse_int_val(ctx, value_node)? else {
586                                return Ok(None);
587                            };
588                            match name {
589                                "size" => size = Range::Single(value),
590                                "minSize" => min_size = Some(value),
591                                "maxSize" => max_size = Some(value),
592                                _ => unreachable!(),
593                            }
594                        }
595                        "injective" => jectivity = JectivityAttr::Injective,
596                        "surjective" => jectivity = JectivityAttr::Surjective,
597                        "bijective" => jectivity = JectivityAttr::Bijective,
598                        "representation" => representation = attribute_value_text(ctx, attribute),
599                        _ => return Ok(None),
600                    }
601                }
602            }
603            "domain" | "annotation_domain" => value_domain = parse_domain(ctx, child)?,
604            _ => {}
605        }
606    }
607
608    if !matches!(size, Range::Single(_)) {
609        size = match (min_size, max_size) {
610            (Some(min), Some(max)) => Range::Bounded(min, max),
611            (Some(min), None) => Range::UnboundedR(min),
612            (None, Some(max)) => Range::UnboundedL(max),
613            (None, None) => Range::Unbounded,
614        };
615    }
616
617    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    let sequence_keyword_node = child!(sequence_domain, 0, "sequence");
627    ctx.add_span_and_doc_hover(
628        &sequence_keyword_node,
629        "sequence",
630        SymbolKind::Domain,
631        None,
632        None,
633    );
634
635    let attrs = SequenceAttr {
636        size,
637        jectivity,
638        representation,
639    };
640    Ok(Some(Domain::sequence(attrs, value_domain)))
641}
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.
646fn parse_function_domain(
647    ctx: &mut ParseContext,
648    function_domain: Node,
649) -> Result<Option<DomainPtr>, FatalParseError> {
650    let mut size = Range::Unbounded;
651    let mut min_size = None;
652    let mut max_size = None;
653    let mut partiality = PartialityAttr::Partial;
654    let mut jectivity = JectivityAttr::None;
655    let mut representation = None;
656
657    for child in named_children(&function_domain) {
658        if child.kind() == "function_attributes" {
659            for attribute in named_children(&child) {
660                let name = attribute
661                    .child_by_field_name("attribute")
662                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
663                    .unwrap_or_default();
664                match name {
665                    "size" | "minSize" | "maxSize" => {
666                        let Some(value_node) = attribute.child_by_field_name("value") else {
667                            return Ok(None);
668                        };
669                        let Some(value) = parse_int_val(ctx, value_node)? else {
670                            return Ok(None);
671                        };
672                        match name {
673                            "size" => size = Range::Single(value),
674                            "minSize" => min_size = Some(value),
675                            "maxSize" => max_size = Some(value),
676                            _ => unreachable!(),
677                        }
678                    }
679                    "total" => partiality = PartialityAttr::Total,
680                    "injective" => jectivity = JectivityAttr::Injective,
681                    "surjective" => jectivity = JectivityAttr::Surjective,
682                    "bijective" => jectivity = JectivityAttr::Bijective,
683                    "representation" => representation = attribute_value_text(ctx, attribute),
684                    _ => return Ok(None),
685                }
686            }
687        }
688    }
689
690    if !matches!(size, Range::Single(_)) {
691        size = match (min_size, max_size) {
692            (Some(min), Some(max)) => Range::Bounded(min, max),
693            (Some(min), None) => Range::UnboundedR(min),
694            (None, Some(max)) => Range::UnboundedL(max),
695            (None, None) => Range::Unbounded,
696        };
697    }
698
699    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    let Some(domain_from) = parse_domain(ctx, domain_from_node)? else {
707        return Ok(None);
708    };
709
710    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    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    let function_keyword_node = child!(function_domain, 0, "function");
723    ctx.add_span_and_doc_hover(
724        &function_keyword_node,
725        "function",
726        SymbolKind::Domain,
727        None,
728        None,
729    );
730
731    let attrs = FuncAttr {
732        size,
733        partiality,
734        jectivity,
735        representation,
736    };
737    Ok(Some(Domain::function(attrs, domain_from, domain_to)))
738}
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.
743fn parse_relation_domain(
744    ctx: &mut ParseContext,
745    relation_domain: Node,
746) -> Result<Option<DomainPtr>, FatalParseError> {
747    let mut size = Range::Unbounded;
748    let mut min_size = None;
749    let mut max_size = None;
750    let mut binary = Vec::new();
751    let mut representation = None;
752
753    for child in named_children(&relation_domain) {
754        if child.kind() == "relation_attributes" {
755            for attribute in named_children(&child) {
756                let name = attribute
757                    .child_by_field_name("attribute")
758                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
759                    .unwrap_or_default();
760                match name {
761                    "size" | "minSize" | "maxSize" => {
762                        let Some(value_node) = attribute.child_by_field_name("value") else {
763                            return Ok(None);
764                        };
765                        let Some(value) = parse_int_val(ctx, value_node)? else {
766                            return Ok(None);
767                        };
768                        match name {
769                            "size" => size = Range::Single(value),
770                            "minSize" => min_size = Some(value),
771                            "maxSize" => max_size = Some(value),
772                            _ => unreachable!(),
773                        }
774                    }
775                    "representation" => representation = attribute_value_text(ctx, attribute),
776                    _ => {
777                        let Some(bin_attr) = BinaryAttr::from_keyword(name) else {
778                            return Ok(None);
779                        };
780                        binary.push(bin_attr);
781                    }
782                }
783            }
784        }
785    }
786
787    if !matches!(size, Range::Single(_)) {
788        size = match (min_size, max_size) {
789            (Some(min), Some(max)) => Range::Bounded(min, max),
790            (Some(min), None) => Range::UnboundedR(min),
791            (None, Some(max)) => Range::UnboundedL(max),
792            (None, None) => Range::Unbounded,
793        };
794    }
795
796    let Some(column_list) = field!(recover, ctx, relation_domain, "relation_domain_list") else {
797        return Ok(None);
798    };
799    let mut columns: Vec<DomainPtr> = Vec::new();
800    for column in named_children(&column_list) {
801        let Some(parsed) = parse_domain(ctx, column)? else {
802            return Ok(None);
803        };
804        columns.push(parsed);
805    }
806
807    // Adding relation keyword to the source map with hover info from documentation
808    let relation_keyword_node = child!(relation_domain, 0, "relation");
809    ctx.add_span_and_doc_hover(
810        &relation_keyword_node,
811        "relation",
812        SymbolKind::Domain,
813        None,
814        None,
815    );
816
817    let attrs = RelAttr {
818        size,
819        binary,
820        representation,
821    };
822    Ok(Some(Domain::relation(attrs, columns)))
823}
824
825fn parse_partition_domain(
826    ctx: &mut ParseContext,
827    partition_domain: Node,
828) -> Result<Option<DomainPtr>, FatalParseError> {
829    let mut num_parts = Range::Unbounded;
830    let mut min_num_parts = None;
831    let mut max_num_parts = None;
832    let mut part_len = Range::Unbounded;
833    let mut min_part_len = None;
834    let mut max_part_len = None;
835    let mut is_regular = false;
836    let mut representation = None;
837
838    for child in named_children(&partition_domain) {
839        if child.kind() == "partition_attributes" {
840            for attribute in named_children(&child) {
841                let name = attribute
842                    .child_by_field_name("attribute")
843                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
844                    .unwrap_or_default();
845                match name {
846                    "numParts" | "minNumParts" | "maxNumParts" | "partSize" | "minPartSize"
847                    | "maxPartSize" => {
848                        let Some(value_node) = attribute.child_by_field_name("value") else {
849                            return Ok(None);
850                        };
851                        let Some(value) = parse_int_val(ctx, value_node)? else {
852                            return Ok(None);
853                        };
854                        match name {
855                            "numParts" => num_parts = Range::Single(value),
856                            "minNumParts" => min_num_parts = Some(value),
857                            "maxNumParts" => max_num_parts = Some(value),
858                            "partSize" => part_len = Range::Single(value),
859                            "minPartSize" => min_part_len = Some(value),
860                            "maxPartSize" => max_part_len = Some(value),
861                            _ => unreachable!(),
862                        }
863                    }
864                    "regular" => is_regular = true,
865                    "representation" => representation = attribute_value_text(ctx, attribute),
866                    _ => return Ok(None),
867                }
868            }
869        }
870    }
871
872    if !matches!(num_parts, Range::Single(_)) {
873        num_parts = match (min_num_parts, max_num_parts) {
874            (Some(min), Some(max)) => Range::Bounded(min, max),
875            (Some(min), None) => Range::UnboundedR(min),
876            (None, Some(max)) => Range::UnboundedL(max),
877            (None, None) => Range::Unbounded,
878        };
879    }
880    if !matches!(part_len, Range::Single(_)) {
881        part_len = match (min_part_len, max_part_len) {
882            (Some(min), Some(max)) => Range::Bounded(min, max),
883            (Some(min), None) => Range::UnboundedR(min),
884            (None, Some(max)) => Range::UnboundedL(max),
885            (None, None) => Range::Unbounded,
886        };
887    }
888
889    let Some(value_domain) = field!(recover, ctx, partition_domain, "value_domain") else {
890        return Ok(None);
891    };
892    let Some(inner) = parse_domain(ctx, value_domain)? else {
893        return Ok(None);
894    };
895
896    let partition_keyword_node = child!(partition_domain, 0, "partition");
897    ctx.add_span_and_doc_hover(
898        &partition_keyword_node,
899        "partition",
900        SymbolKind::Domain,
901        None,
902        None,
903    );
904
905    let attrs = PartitionAttr {
906        num_parts,
907        part_len,
908        is_regular,
909        representation,
910    };
911    Ok(Some(Domain::partition(attrs, inner)))
912}
913
914fn parse_permutation_domain(
915    ctx: &mut ParseContext,
916    permutation_domain: Node,
917) -> Result<Option<DomainPtr>, FatalParseError> {
918    let mut num_moved = Range::Unbounded;
919    let mut min_num_moved = None;
920    let mut max_num_moved = None;
921    let mut representation = None;
922
923    for child in named_children(&permutation_domain) {
924        if child.kind() == "permutation_attributes" {
925            for attribute in named_children(&child) {
926                let name = attribute
927                    .child_by_field_name("attribute")
928                    .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
929                    .unwrap_or_default();
930                if name == "representation" {
931                    representation = attribute_value_text(ctx, attribute);
932                    continue;
933                }
934                let Some(value_node) = attribute.child_by_field_name("value") else {
935                    return Ok(None);
936                };
937                let Some(value) = parse_int_val(ctx, value_node)? else {
938                    return Ok(None);
939                };
940                match name {
941                    "numMoved" => num_moved = Range::Single(value),
942                    "minNumMoved" => min_num_moved = Some(value),
943                    "maxNumMoved" => max_num_moved = Some(value),
944                    _ => return Ok(None),
945                }
946            }
947        }
948    }
949
950    if !matches!(num_moved, Range::Single(_)) {
951        num_moved = match (min_num_moved, max_num_moved) {
952            (Some(min), Some(max)) => Range::Bounded(min, max),
953            (Some(min), None) => Range::UnboundedR(min),
954            (None, Some(max)) => Range::UnboundedL(max),
955            (None, None) => Range::Unbounded,
956        };
957    }
958
959    let Some(value_domain) = field!(recover, ctx, permutation_domain, "value_domain") else {
960        return Ok(None);
961    };
962    let Some(inner) = parse_domain(ctx, value_domain)? else {
963        return Ok(None);
964    };
965
966    let permutation_keyword_node = child!(permutation_domain, 0, "permutation");
967    ctx.add_span_and_doc_hover(
968        &permutation_keyword_node,
969        "permutation",
970        SymbolKind::Domain,
971        None,
972        None,
973    );
974
975    let attrs = PermutationAttr {
976        num_moved,
977        representation,
978    };
979    Ok(Some(Domain::permutation(attrs, inner)))
980}
981
982pub fn parse_set_domain(
983    ctx: &mut ParseContext,
984    set_domain: Node,
985) -> Result<Option<DomainPtr>, FatalParseError> {
986    let mut size = Range::Unbounded;
987    let mut min_size = None;
988    let mut max_size = None;
989    let mut representation = None;
990    let mut value_domain: Option<DomainPtr> = None;
991
992    for child in named_children(&set_domain) {
993        match child.kind() {
994            "set_attributes" => {
995                for attribute in named_children(&child) {
996                    let Some(value_node) = attribute.child_by_field_name("value") else {
997                        return Ok(None);
998                    };
999                    let name = attribute
1000                        .child_by_field_name("attribute")
1001                        .map(|node| &ctx.source_code[node.start_byte()..node.end_byte()])
1002                        .unwrap_or_default();
1003                    if name == "representation" {
1004                        representation = Some(
1005                            ctx.source_code[value_node.start_byte()..value_node.end_byte()]
1006                                .to_string(),
1007                        );
1008                        continue;
1009                    }
1010                    // Attribute values may be expressions over givens, e.g. `maxSize |nums|`,
1011                    // which only become ground once the parameters are instantiated.
1012                    let Some(value) = parse_int_val(ctx, value_node)? else {
1013                        return Ok(None);
1014                    };
1015                    match name {
1016                        "size" => size = Range::Single(value),
1017                        "minSize" => min_size = Some(value),
1018                        "maxSize" => max_size = Some(value),
1019                        _ => return Ok(None),
1020                    }
1021                }
1022            }
1023            "domain" | "annotation_domain" => {
1024                let Some(parsed_domain) = parse_domain(ctx, child)? else {
1025                    return Ok(None);
1026                };
1027                value_domain = Some(parsed_domain);
1028            }
1029            _ => {
1030                ctx.record_error(RecoverableParseError::new(
1031                    format!("Unrecognized set domain child kind: {}", child.kind()),
1032                    Some(child.range()),
1033                ));
1034                return Ok(None);
1035            }
1036        }
1037    }
1038
1039    if let Some(domain) = value_domain {
1040        // Adding set to the source map with hover info from documentation
1041        let set_keyword_node = child!(set_domain, 0, "set");
1042        // No documentation available for set domain, using fallback description
1043        ctx.add_span_and_doc_hover(&set_keyword_node, "set", SymbolKind::Domain, None, None);
1044        if !matches!(size, Range::Single(_)) {
1045            size = match (min_size, max_size) {
1046                (Some(min), Some(max)) => Range::Bounded(min, max),
1047                (Some(min), None) => Range::UnboundedR(min),
1048                (None, Some(max)) => Range::UnboundedL(max),
1049                (None, None) => Range::Unbounded,
1050            };
1051        }
1052        let mut attr = SetAttr::new(size);
1053        if let Some(repr) = representation {
1054            attr = attr.with_representation(repr);
1055        }
1056        Ok(Some(Domain::set(attr, domain)))
1057    } else {
1058        ctx.record_error(RecoverableParseError::new(
1059            "Set domain must have a value domain".to_string(),
1060            Some(set_domain.range()),
1061        ));
1062        Ok(None)
1063    }
1064}
1065
1066/// Parses `node` when it denotes a collection of integers, for `int(<collection>)`.
1067///
1068/// Returns `None` without recording an error when it is something else, so the caller can carry on
1069/// reading the node as an ordinary range bound.
1070fn parse_collection_valued_expression(
1071    ctx: &mut ParseContext,
1072    node: Node,
1073) -> Result<Option<Expression>, FatalParseError> {
1074    let saved_context = ctx.typechecking_context;
1075    let saved_inner_context = ctx.inner_typechecking_context;
1076    ctx.typechecking_context = TypecheckingContext::Unknown;
1077    ctx.inner_typechecking_context = TypecheckingContext::Unknown;
1078    let parsed = parse_expression(ctx, node);
1079    ctx.typechecking_context = saved_context;
1080    ctx.inner_typechecking_context = saved_inner_context;
1081
1082    let Some(expr) = parsed? else {
1083        return Ok(None);
1084    };
1085    use conjure_cp_core::ast::Typeable;
1086
1087    // A comprehension's return type is its *element* type, so the variant has to be recognised
1088    // directly rather than asked for its type.
1089    if matches!(expr, Expression::Comprehension(_, _)) {
1090        return Ok(Some(expr));
1091    }
1092
1093    Ok(matches!(
1094        expr.return_type(),
1095        conjure_cp_core::ast::ReturnType::Set(_)
1096            | conjure_cp_core::ast::ReturnType::MSet(_)
1097            | conjure_cp_core::ast::ReturnType::Matrix(_)
1098            | conjure_cp_core::ast::ReturnType::Sequence(_)
1099    )
1100    .then_some(expr))
1101}
1102
1103fn parse_enum_domain(
1104    ctx: &mut ParseContext,
1105    node: Node,
1106) -> Result<Option<DomainPtr>, FatalParseError> {
1107    let Some(name) = field!(recover, ctx, node, "name") else {
1108        return Ok(None);
1109    };
1110    let Some(declaration) = get_declaration_ptr_from_identifier(ctx, name)? else {
1111        return Ok(None);
1112    };
1113    let Some(ty) = declaration.as_enumerated_type().map(|ty| ty.clone()) else {
1114        ctx.record_error(RecoverableParseError::new(
1115            "Expected an enumerated type".to_owned(),
1116            Some(name.range()),
1117        ));
1118        return Ok(None);
1119    };
1120    let Some(ranges_node) = field!(recover, ctx, node, "ranges") else {
1121        return Ok(None);
1122    };
1123    let mut ranges = Vec::new();
1124    for range in named_children(&ranges_node) {
1125        let mut parse_bound = |bound| -> Result<Option<EnumVariantVal>, FatalParseError> {
1126            let saved = ctx.typechecking_context;
1127            ctx.typechecking_context = TypecheckingContext::Unknown;
1128            let result = parse_expression(ctx, bound);
1129            ctx.typechecking_context = saved;
1130            let Some(expression) = result? else {
1131                return Ok(None);
1132            };
1133            if let Expression::Atomic(_, Atom::Reference(reference)) = expression
1134                && reference.return_type()
1135                    == conjure_cp_core::ast::ReturnType::EnumeratedType(ty.clone())
1136            {
1137                return Ok(Some(EnumVariantVal(reference)));
1138            }
1139            ctx.record_error(RecoverableParseError::new(
1140                "Expected a member of this enumerated type".to_owned(),
1141                Some(bound.range()),
1142            ));
1143            Ok(None)
1144        };
1145        if range.kind() == "int_range" {
1146            let lower = match range.child_by_field_name("lower") {
1147                Some(bound) => {
1148                    let Some(value) = parse_bound(bound)? else {
1149                        return Ok(None);
1150                    };
1151                    Some(value)
1152                }
1153                None => None,
1154            };
1155            let upper = match range.child_by_field_name("upper") {
1156                Some(bound) => {
1157                    let Some(value) = parse_bound(bound)? else {
1158                        return Ok(None);
1159                    };
1160                    Some(value)
1161                }
1162                None => None,
1163            };
1164            ranges.push(match (lower, upper) {
1165                (Some(a), Some(b)) => Range::Bounded(a, b),
1166                (Some(a), None) => Range::UnboundedR(a),
1167                (None, Some(b)) => Range::UnboundedL(b),
1168                (None, None) => Range::Unbounded,
1169            });
1170        } else {
1171            let Some(value) = parse_bound(range)? else {
1172                return Ok(None);
1173            };
1174            ranges.push(Range::Single(value));
1175        }
1176    }
1177    Ok(Some(Domain::enumerated(ty, ranges)))
1178}