Skip to main content

type_bridge_schema_compat/
lib.rs

1//! One-way compatibility front-ends for the V2 schema fact graph.
2//!
3//! This public supporting crate is deliberately narrow. Source-language parsers
4//! converge on `type_bridge_schema::FactAssembler`; contract and schema crates
5//! never depend on compatibility parsers or their transitive grammar
6//! dependencies.
7
8#![deny(missing_docs)]
9
10mod adopted_genesis;
11mod descriptor;
12mod function_references;
13mod literal;
14mod live_authority;
15mod released_syntax;
16
17pub use adopted_genesis::{
18    ADOPTED_GENESIS_FILE_NAME, AdoptedGenesisAuthority, LEGACY_LEDGER_SCHEMA_TYPEQL,
19    is_legacy_ledger_label, parse_adopted_genesis, parse_adopted_genesis_authority,
20    parse_adopted_genesis_authority_with_internal,
21};
22pub use function_references::{FunctionBodyReferences, SchemaReference, TypeqlDeclaredSchema};
23pub use live_authority::{
24    LiveLegacyLedgerPresence, LiveQueryAuthorityState, LiveQueryControlPresence,
25    MANAGED_FENCE_SCHEMA_TYPEQL, legacy_ledger_schema_presence, managed_fence_schema_presence,
26    rebuild_live_query_authority, rebuild_live_query_authority_state,
27};
28
29pub use descriptor::{
30    GENERATED_DECLARED_DESCRIPTOR_PATH, GENERATED_DECLARED_DESCRIPTOR_V1,
31    GENERATED_DECLARED_DESCRIPTOR_V2, GeneratedDeclaredDescriptorSetV1,
32    attach_declared_descriptors, empty_generated_declared_descriptors_json,
33    generate_package_with_declared_descriptors, generated_declared_descriptors_json,
34    generated_descriptors_to_declared, released_typeql_to_declared_lossless_projection,
35    released_typeql_to_declared_lossless_projection_with_references,
36    released_typeql_to_declared_projection, released_typeql_to_declared_projection_with_references,
37    typeql_to_generated_descriptors,
38};
39
40/// Comparison-only reporting between the frozen V1 parser and the V2 fact graph.
41pub mod shadow;
42
43pub use shadow::{
44    ShadowCompared, ShadowComparison, ShadowCoverage, ShadowCoverageState, ShadowDimension,
45    ShadowFinding, ShadowLaneNotRun, ShadowLaneOutcome, ShadowLaneRejection, ShadowLaneSummary,
46    ShadowUnavailableLane, ShadowVerdict, V1ShadowInternalError, V1ShadowReport, v1_shadow_report,
47};
48
49use std::collections::{BTreeMap, BTreeSet};
50
51use type_bridge_contract::codec::FormatVersion;
52use type_bridge_contract::diagnostic::{Diagnostic, DiagnosticCategory, DiagnosticCode};
53use type_bridge_contract::id::{
54    AttributeId, FunctionId, Label, RoleId, StructId, TypeId, TypeKind,
55};
56use type_bridge_contract::limits::MAX_CANONICAL_COLLECTION_LEN;
57use type_bridge_contract::schema::{
58    AnnotationFact, AnnotationFactId, AnnotationKindId, AnnotationSubjectId, CanonicalValueRange,
59    CanonicalValueSet, CollectionMode, DeclaredSchema, DocText, DocumentId, FunctionBody,
60    FunctionFact, FunctionParameter, FunctionReturnElement, FunctionReturnMode, FunctionSignature,
61    OwnsFact, OwnsFactId, PlaysFactId, RegexPattern, RelatesFactId, SchemaAnnotationValue,
62    SchemaDiagnostic, SchemaDiagnostics, SchemaFact, SourceSpan, StructFact, StructField, SubFact,
63    SubFactId, TypeFact, TypeReference, ValueFact, ValueFactId,
64};
65use type_bridge_contract::value::{CanonicalString, CanonicalValue, Cardinality, ValueTypeTag};
66use type_bridge_schema::FactAssembler;
67use typeql::Annotation;
68use typeql::annotation::CardinalityRange;
69use typeql::common::{Span, Spanned};
70use typeql::query::{QueryStructure, schema::SchemaQuery};
71use typeql::schema::definable::{
72    Definable,
73    function::{Function, Output},
74    struct_::Struct,
75    type_::{Capability, CapabilityBase, Type as TypeDeclaration},
76};
77use typeql::type_::{NamedType, NamedTypeAny, TypeRef, TypeRefAny};
78
79use crate::literal::{canonical_literal, validate_quoted_string};
80use crate::released_syntax::{ReleasedAnnotationTarget, ReleasedSyntax};
81
82/// Defensive source bound applied before entering the third-party parser.
83pub const MAX_TYPEQL_SCHEMA_BYTES: usize = 16 * 1024 * 1024;
84
85#[derive(Clone, Copy, Debug, Eq, PartialEq)]
86pub(crate) enum TypeqlSourceSizePolicy {
87    Defensive,
88    TrustedGenerator,
89}
90
91impl TypeqlSourceSizePolicy {
92    const fn allows(self, source_len: usize) -> bool {
93        matches!(self, Self::TrustedGenerator) || source_len <= MAX_TYPEQL_SCHEMA_BYTES
94    }
95}
96
97fn ensure_typeql_source_size(
98    source: &str,
99    size_policy: TypeqlSourceSizePolicy,
100) -> Result<(), SchemaDiagnostics> {
101    if size_policy.allows(source.len()) {
102        return Ok(());
103    }
104    Err(error(
105        DiagnosticCategory::InvalidContract,
106        "typeql_schema_size_limit",
107        "TypeQL schema source exceeds the compatibility parser limit",
108        None,
109    ))
110}
111
112/// Parse one TypeQL `define` query into the canonical declared schema graph
113/// and derive neutral references from every function body.
114pub fn typeql_to_declared_with_references(
115    document: DocumentId,
116    source: &str,
117) -> Result<TypeqlDeclaredSchema, SchemaDiagnostics> {
118    typeql_to_declared_with_references_with_size_policy(
119        document,
120        source,
121        TypeqlSourceSizePolicy::Defensive,
122    )
123}
124
125pub(crate) fn typeql_to_declared_with_references_with_size_policy(
126    document: DocumentId,
127    source: &str,
128    size_policy: TypeqlSourceSizePolicy,
129) -> Result<TypeqlDeclaredSchema, SchemaDiagnostics> {
130    ensure_typeql_source_size(source, size_policy)?;
131    typeql_to_declared_with_references_impl(document, source, source, None, None, None, None)
132}
133
134pub(crate) fn released_typeql_to_declared_with_references(
135    document: DocumentId,
136    released: &ReleasedSyntax,
137    size_policy: TypeqlSourceSizePolicy,
138) -> Result<TypeqlDeclaredSchema, SchemaDiagnostics> {
139    ensure_typeql_source_size(released.original_source(), size_policy)?;
140    let reference_projection = released_unresolved_capability_ranges(&document, released)?;
141    typeql_to_declared_with_references_impl(
142        document,
143        released.original_source(),
144        released.source(),
145        Some(released),
146        None,
147        None,
148        Some(&reference_projection.played_role_declarations),
149    )
150}
151
152pub(crate) fn released_typeql_to_declared_with_references_omitting_capabilities(
153    document: DocumentId,
154    released: &ReleasedSyntax,
155    omitted_declarations: &BTreeSet<usize>,
156    omitted_capabilities: &BTreeSet<usize>,
157    played_role_declarations: &BTreeMap<usize, String>,
158    size_policy: TypeqlSourceSizePolicy,
159) -> Result<TypeqlDeclaredSchema, SchemaDiagnostics> {
160    ensure_typeql_source_size(released.original_source(), size_policy)?;
161    typeql_to_declared_with_references_impl(
162        document,
163        released.original_source(),
164        released.source(),
165        Some(released),
166        Some(omitted_declarations),
167        Some(omitted_capabilities),
168        Some(played_role_declarations),
169    )
170}
171
172/// Index every non-portable declaration and causally unresolved capability in
173/// one released-schema pass.
174///
175/// Descriptor generation is intentionally open-world, but retrying the whole
176/// parser once per missing reference makes a small partial export quadratic.
177/// This index mirrors the released merge algebra, validates the surviving
178/// direct role graph in memory, and returns original byte ranges for every
179/// declaration/fact the generator-only projection must omit plus the declaring
180/// role scope for valid inherited plays edges. Descriptor omissions are kept
181/// separate from the older render-only role repair so newly unsupported
182/// canonical identities cannot change released model bytes.
183#[derive(Default)]
184pub(crate) struct ReleasedReferenceProjection {
185    pub(crate) omitted_declarations: BTreeMap<usize, usize>,
186    pub(crate) omitted: BTreeMap<usize, usize>,
187    pub(crate) omitted_from_render: BTreeMap<usize, usize>,
188    pub(crate) played_role_declarations: BTreeMap<usize, String>,
189}
190
191pub(crate) fn released_unresolved_capability_ranges(
192    document: &DocumentId,
193    released: &ReleasedSyntax,
194) -> Result<ReleasedReferenceProjection, SchemaDiagnostics> {
195    let queries = typeql::parse_queries(released.source()).map_err(|parse_error| {
196        error(
197            DiagnosticCategory::InvalidContract,
198            "invalid_typeql_schema",
199            format!("TypeQL schema parsing failed: {parse_error}"),
200            None,
201        )
202    })?;
203    let mut definables = Vec::new();
204    for query in queries {
205        match query.structure {
206            QueryStructure::Schema(SchemaQuery::Define(define)) => {
207                definables.extend(define.definables);
208            }
209            _ => {
210                return Err(error(
211                    DiagnosticCategory::InvalidContract,
212                    "expected_typeql_define",
213                    "schema compatibility input must contain only define queries",
214                    query_span(document, released.original_source(), query.span)?,
215                ));
216            }
217        }
218    }
219    restore_released_labels(released, &mut definables);
220    let declarations = definables
221        .iter()
222        .filter_map(|definable| match definable {
223            Definable::TypeDeclaration(declaration) => Some(declaration),
224            _ => None,
225        })
226        .collect::<Vec<_>>();
227    let kinds = infer_type_kinds(document, released.original_source(), &declarations, true)?;
228    let mut omitted_declarations = BTreeMap::new();
229    let mut invalid_type_labels = BTreeSet::new();
230    for (declaration, kind) in declarations.iter().zip(&kinds) {
231        let label = typeql_label(&declaration.label);
232        let portable = TypeId::new(*kind, label.clone())
233            .and_then(TypeFact::new)
234            .is_ok();
235        if !portable {
236            invalid_type_labels.insert(label);
237            if let Some(span) = declaration.span {
238                omitted_declarations.insert(span.begin_offset, span.end_offset);
239            }
240        }
241    }
242    // Every reopening of a non-portable identity belongs to the same omitted
243    // declaration closure, including a kindless standalone `plays` line.
244    for declaration in &declarations {
245        if invalid_type_labels.contains(&typeql_label(&declaration.label))
246            && let Some(span) = declaration.span
247        {
248            omitted_declarations.insert(span.begin_offset, span.end_offset);
249        }
250    }
251    let ids = declarations
252        .iter()
253        .zip(&kinds)
254        .filter(|(declaration, _)| {
255            !declaration
256                .span
257                .is_some_and(|span| omitted_declarations.contains_key(&span.begin_offset))
258        })
259        .map(|(declaration, kind)| (typeql_label(&declaration.label), *kind))
260        .collect::<BTreeMap<_, _>>();
261
262    let mut last_attribute_declaration = BTreeMap::new();
263    let mut last_sub_capability = BTreeMap::new();
264    let mut last_value_capability = BTreeMap::new();
265    for (declaration_index, (declaration, kind)) in declarations.iter().zip(&kinds).enumerate() {
266        let label = typeql_label(&declaration.label);
267        if *kind == TypeKind::Attribute {
268            last_attribute_declaration.insert(label.clone(), declaration_index);
269        }
270        for (capability_index, capability) in declaration.capabilities.iter().enumerate() {
271            if matches!(capability.base, CapabilityBase::Sub(_)) {
272                last_sub_capability.insert(label.clone(), (declaration_index, capability_index));
273            }
274            if matches!(capability.base, CapabilityBase::ValueType(_)) {
275                last_value_capability.insert(label.clone(), (declaration_index, capability_index));
276            }
277        }
278    }
279
280    struct IndexedCapability<'a> {
281        owner: String,
282        owner_kind: TypeKind,
283        capability: &'a Capability,
284        start: usize,
285        end: usize,
286    }
287
288    let mut effective = Vec::new();
289    let mut first_object_capability = BTreeSet::new();
290    for (declaration_index, (declaration, kind)) in declarations.iter().zip(&kinds).enumerate() {
291        if declaration
292            .span
293            .is_some_and(|span| omitted_declarations.contains_key(&span.begin_offset))
294        {
295            continue;
296        }
297        let owner = typeql_label(&declaration.label);
298        if *kind == TypeKind::Attribute
299            && last_attribute_declaration.get(&owner) != Some(&declaration_index)
300        {
301            continue;
302        }
303        for (capability_index, capability) in declaration.capabilities.iter().enumerate() {
304            if matches!(capability.base, CapabilityBase::Sub(_))
305                && last_sub_capability.get(&owner) != Some(&(declaration_index, capability_index))
306            {
307                continue;
308            }
309            if matches!(capability.base, CapabilityBase::ValueType(_))
310                && last_value_capability.get(&owner) != Some(&(declaration_index, capability_index))
311            {
312                continue;
313            }
314            if *kind != TypeKind::Attribute
315                && let Some(identity) = released_object_capability_identity(capability)
316                && !first_object_capability.insert((owner.clone(), identity))
317            {
318                continue;
319            }
320            let Some(span) = capability.span else {
321                continue;
322            };
323            effective.push(IndexedCapability {
324                owner: owner.clone(),
325                owner_kind: *kind,
326                capability,
327                start: span.begin_offset,
328                end: span.end_offset,
329            });
330        }
331    }
332
333    let mut omitted = BTreeMap::new();
334    let mut parents = BTreeMap::<String, String>::new();
335    for indexed in &effective {
336        match &indexed.capability.base {
337            CapabilityBase::Sub(sub) => {
338                let parent = typeql_label(&sub.supertype_label);
339                if root_kind(&parent).is_some() {
340                    continue;
341                }
342                match ids.get(&parent) {
343                    None => {
344                        omitted.insert(indexed.start, indexed.end);
345                    }
346                    Some(parent_kind) if *parent_kind == indexed.owner_kind => {
347                        parents.insert(indexed.owner.clone(), parent);
348                    }
349                    Some(_) => {}
350                }
351            }
352            CapabilityBase::Owns(owns) => {
353                if let Ok((attribute, _)) = capability_type_ref(&owns.owned)
354                    && !ids.contains_key(&attribute)
355                {
356                    omitted.insert(indexed.start, indexed.end);
357                }
358            }
359            _ => {}
360        }
361    }
362
363    let mut roles = BTreeMap::<(String, String), ReleasedIndexedRole>::new();
364    let mut role_names_by_relation = BTreeMap::<String, Vec<String>>::new();
365    for (capability_index, indexed) in effective.iter().enumerate() {
366        let CapabilityBase::Relates(relates) = &indexed.capability.base else {
367            continue;
368        };
369        let Ok((role, _)) = capability_type_ref(&relates.related) else {
370            continue;
371        };
372        let specializes = relates.specialised.as_ref().and_then(|specialized| {
373            capability_type_ref(specialized)
374                .ok()
375                .map(|(label, _)| label)
376        });
377        let role_is_portable = Label::new(&role).is_ok()
378            && specializes
379                .as_ref()
380                .is_none_or(|label| Label::new(label).is_ok());
381        if !role_is_portable {
382            omitted.insert(indexed.start, indexed.end);
383            continue;
384        }
385        role_names_by_relation
386            .entry(indexed.owner.clone())
387            .or_default()
388            .push(role.clone());
389        roles.insert(
390            (indexed.owner.clone(), role),
391            ReleasedIndexedRole {
392                capability_index,
393                specializes,
394            },
395        );
396    }
397
398    let relation_names = ids
399        .iter()
400        .filter_map(|(name, kind)| (*kind == TypeKind::Relation).then_some(name.clone()))
401        .collect::<BTreeSet<_>>();
402    let mut played_role_names_by_relation = BTreeMap::<String, BTreeSet<String>>::new();
403    for indexed in &effective {
404        if let CapabilityBase::Plays(plays) = &indexed.capability.base {
405            let relation = typeql_label(&plays.role.scope);
406            let role = typeql_label(&plays.role.name);
407            if Label::new(&relation).is_err() || Label::new(&role).is_err() {
408                omitted.insert(indexed.start, indexed.end);
409                continue;
410            }
411            played_role_names_by_relation
412                .entry(relation)
413                .or_default()
414                .insert(role);
415        }
416    }
417    let role_resolution = released_role_validities(
418        &relation_names,
419        &role_names_by_relation,
420        &played_role_names_by_relation,
421        &roles,
422        &parents,
423    );
424    for (key, validity) in &role_resolution.direct {
425        if *validity == ReleasedRoleValidity::Invalid {
426            let indexed = &effective[roles[key].capability_index];
427            omitted.insert(indexed.start, indexed.end);
428        }
429    }
430
431    let mut omitted_from_render = BTreeMap::new();
432    for (key, validity) in &role_resolution.direct {
433        if *validity == ReleasedRoleValidity::Invalid {
434            let indexed = &effective[roles[key].capability_index];
435            omitted_from_render.insert(indexed.start, indexed.end);
436        }
437    }
438
439    let mut played_role_declarations = BTreeMap::new();
440    let mut first_portable_plays = BTreeSet::new();
441    for indexed in &effective {
442        let CapabilityBase::Plays(plays) = &indexed.capability.base else {
443            continue;
444        };
445        if omitted.contains_key(&indexed.start) {
446            continue;
447        }
448        let relation = typeql_label(&plays.role.scope);
449        let role = typeql_label(&plays.role.name);
450        match ids.get(&relation) {
451            None => {
452                omitted.insert(indexed.start, indexed.end);
453            }
454            Some(TypeKind::Relation) => {
455                match role_resolution.plays.get(&(relation.clone(), role.clone())) {
456                    Some(ReleasedRoleValidity::Valid) => {
457                        if let Some(declaration) =
458                            role_resolution.play_declarations.get(&(relation, role))
459                        {
460                            let identity = (
461                                indexed.owner.clone(),
462                                declaration.clone(),
463                                typeql_label(&plays.role.name),
464                            );
465                            if first_portable_plays.insert(identity) {
466                                played_role_declarations.insert(indexed.start, declaration.clone());
467                            } else {
468                                // Distinct released role refs may collapse to
469                                // the same inherited direct role identity.
470                                // Preserve the first frozen capability and
471                                // record the later alias as open-world evidence
472                                // instead of feeding a duplicate fact to the
473                                // canonical assembler.
474                                omitted.insert(indexed.start, indexed.end);
475                            }
476                        }
477                    }
478                    Some(ReleasedRoleValidity::Invalid) | None => {
479                        omitted.insert(indexed.start, indexed.end);
480                    }
481                    Some(ReleasedRoleValidity::Indeterminate) => {}
482                }
483            }
484            Some(_) => {}
485        }
486    }
487
488    Ok(ReleasedReferenceProjection {
489        omitted_declarations,
490        omitted,
491        omitted_from_render,
492        played_role_declarations,
493    })
494}
495
496#[derive(Clone, Copy, Debug, Eq, PartialEq)]
497enum ReleasedRoleValidity {
498    Valid,
499    Invalid,
500    Indeterminate,
501}
502
503#[derive(Clone, Debug)]
504struct ReleasedIndexedRole {
505    capability_index: usize,
506    specializes: Option<String>,
507}
508
509struct ReleasedRoleResolution {
510    direct: BTreeMap<(String, String), ReleasedRoleValidity>,
511    plays: BTreeMap<(String, String), ReleasedRoleValidity>,
512    play_declarations: BTreeMap<(String, String), String>,
513}
514
515/// Resolve direct role specializations in relation-tree order without
516/// recursion or repeated ancestry walks.
517///
518/// `direct_labels` indexes valid direct declarations on the current ancestor
519/// path. Specialization does not remove its target from this index: the
520/// canonical assembler binds `as <label>` to a direct ancestor declaration,
521/// including one already replaced in the effective role view.
522///
523/// `effective_labels` separately mirrors the frozen generator's inherited
524/// local role names. A valid specialization removes its immediate inherited
525/// target name and adds its local name; plays checks query that set after the
526/// relation's own declarations have been applied. Explicit exit frames
527/// restore both views before visiting a sibling.
528///
529/// This is O((relations + roles) log roles), uses a heap work stack for deep
530/// inheritance, and exactly models the released parser after invalid direct
531/// specializations have been omitted: an omitted role contributes no label
532/// for a descendant specialization to bind.
533fn released_role_validities(
534    relation_names: &BTreeSet<String>,
535    role_names_by_relation: &BTreeMap<String, Vec<String>>,
536    played_role_names_by_relation: &BTreeMap<String, BTreeSet<String>>,
537    roles: &BTreeMap<(String, String), ReleasedIndexedRole>,
538    parents: &BTreeMap<String, String>,
539) -> ReleasedRoleResolution {
540    let mut children = BTreeMap::<String, Vec<String>>::new();
541    let mut roots = Vec::new();
542    for relation in relation_names {
543        match parents
544            .get(relation)
545            .filter(|parent| relation_names.contains(*parent))
546        {
547            Some(parent) => children
548                .entry(parent.clone())
549                .or_default()
550                .push(relation.clone()),
551            None => roots.push(relation.clone()),
552        }
553    }
554
555    // Any relation not reachable from a root participates in, or descends
556    // from, an inheritance cycle. Preserve its capabilities as indeterminate
557    // so the canonical assembler reports the cycle instead of this
558    // compatibility index inventing a different omission.
559    let mut direct = roles
560        .keys()
561        .cloned()
562        .map(|key| (key, ReleasedRoleValidity::Indeterminate))
563        .collect::<BTreeMap<_, _>>();
564    let mut plays = played_role_names_by_relation
565        .iter()
566        .flat_map(|(relation, role_names)| {
567            role_names.iter().map(|role_name| {
568                (
569                    (relation.clone(), role_name.clone()),
570                    ReleasedRoleValidity::Indeterminate,
571                )
572            })
573        })
574        .collect::<BTreeMap<_, _>>();
575    let mut direct_labels = BTreeSet::<String>::new();
576    let mut effective_roles = BTreeMap::<String, String>::new();
577    enum Traversal {
578        Enter(String),
579        Exit {
580            direct: Vec<(String, bool)>,
581            effective: Vec<(String, Option<String>)>,
582        },
583    }
584    let mut work = roots
585        .into_iter()
586        .rev()
587        .map(Traversal::Enter)
588        .collect::<Vec<_>>();
589    let mut play_declarations = BTreeMap::new();
590
591    while let Some(frame) = work.pop() {
592        match frame {
593            Traversal::Enter(relation) => {
594                let mut additions = BTreeSet::new();
595                let mut removals = BTreeSet::new();
596                if let Some(role_names) = role_names_by_relation.get(&relation) {
597                    for role_name in role_names {
598                        let key = (relation.clone(), role_name.clone());
599                        let role = &roles[&key];
600                        let resolved = match role.specializes.as_ref() {
601                            Some(specialized) if direct_labels.contains(specialized) => {
602                                removals.insert(specialized.clone());
603                                ReleasedRoleValidity::Valid
604                            }
605                            Some(_) => ReleasedRoleValidity::Invalid,
606                            None => ReleasedRoleValidity::Valid,
607                        };
608                        direct.insert(key, resolved);
609                        if resolved == ReleasedRoleValidity::Valid {
610                            additions.insert(role_name.clone());
611                        }
612                    }
613                }
614
615                let affected = removals.union(&additions).cloned().collect::<Vec<_>>();
616                let mut previous_effective = Vec::with_capacity(affected.len());
617                for role_name in affected {
618                    let previous = effective_roles.get(&role_name).cloned();
619                    previous_effective.push((role_name.clone(), previous));
620                    if additions.contains(&role_name) {
621                        effective_roles.insert(role_name, relation.clone());
622                    } else {
623                        effective_roles.remove(&role_name);
624                    }
625                }
626                let mut previous_direct = Vec::with_capacity(additions.len());
627                for role_name in &additions {
628                    let was_visible = direct_labels.contains(role_name);
629                    previous_direct.push((role_name.clone(), was_visible));
630                    direct_labels.insert(role_name.clone());
631                }
632
633                if let Some(played_role_names) = played_role_names_by_relation.get(&relation) {
634                    for role_name in played_role_names {
635                        let declaration = effective_roles.get(role_name);
636                        plays.insert(
637                            (relation.clone(), role_name.clone()),
638                            if declaration.is_some() {
639                                ReleasedRoleValidity::Valid
640                            } else {
641                                ReleasedRoleValidity::Invalid
642                            },
643                        );
644                        if let Some(declaration) = declaration {
645                            play_declarations
646                                .insert((relation.clone(), role_name.clone()), declaration.clone());
647                        }
648                    }
649                }
650
651                work.push(Traversal::Exit {
652                    direct: previous_direct,
653                    effective: previous_effective,
654                });
655                if let Some(relation_children) = children.get(&relation) {
656                    work.extend(
657                        relation_children
658                            .iter()
659                            .rev()
660                            .cloned()
661                            .map(Traversal::Enter),
662                    );
663                }
664            }
665            Traversal::Exit { direct, effective } => {
666                for (role_name, was_visible) in direct {
667                    if was_visible {
668                        direct_labels.insert(role_name);
669                    } else {
670                        direct_labels.remove(&role_name);
671                    }
672                }
673                for (role_name, previous) in effective {
674                    if let Some(declaration) = previous {
675                        effective_roles.insert(role_name, declaration);
676                    } else {
677                        effective_roles.remove(&role_name);
678                    }
679                }
680            }
681        }
682    }
683
684    ReleasedRoleResolution {
685        direct,
686        plays,
687        play_declarations,
688    }
689}
690
691fn typeql_to_declared_with_references_impl(
692    document: DocumentId,
693    source: &str,
694    parser_source: &str,
695    released: Option<&ReleasedSyntax>,
696    omitted_released_declarations: Option<&BTreeSet<usize>>,
697    omitted_released_capabilities: Option<&BTreeSet<usize>>,
698    played_role_declarations: Option<&BTreeMap<usize, String>>,
699) -> Result<TypeqlDeclaredSchema, SchemaDiagnostics> {
700    // Released schema sources may carry several define blocks; every query
701    // must still be a define, and their definables merge in source order.
702    let queries = typeql::parse_queries(parser_source).map_err(|parse_error| {
703        error(
704            DiagnosticCategory::InvalidContract,
705            "invalid_typeql_schema",
706            format!("TypeQL schema parsing failed: {parse_error}"),
707            None,
708        )
709    })?;
710    if queries.is_empty() {
711        return Err(error(
712            DiagnosticCategory::InvalidContract,
713            "expected_typeql_define",
714            "schema compatibility input must contain at least one define query",
715            None,
716        ));
717    }
718    let mut definables = Vec::new();
719    for query in queries {
720        match query.structure {
721            QueryStructure::Schema(SchemaQuery::Define(define)) => {
722                definables.extend(define.definables);
723            }
724            _ => {
725                return Err(error(
726                    DiagnosticCategory::InvalidContract,
727                    "expected_typeql_define",
728                    "schema compatibility input must contain only define queries",
729                    query_span(&document, source, query.span)?,
730                ));
731            }
732        }
733    }
734    if let Some(released) = released {
735        restore_released_labels(released, &mut definables);
736    }
737
738    let declarations: Vec<&TypeDeclaration> = definables
739        .iter()
740        .filter_map(|definable| match definable {
741            Definable::TypeDeclaration(declaration) => Some(declaration),
742            _ => None,
743        })
744        .collect();
745    let kinds = infer_type_kinds(&document, source, &declarations, released.is_some())?;
746    let mut ids = BTreeMap::new();
747    let mut assembler = FactAssembler::new(FormatVersion::V1);
748    let mut function_body_references = BTreeMap::new();
749
750    for (declaration, kind) in declarations.iter().zip(&kinds) {
751        if released_declaration_is_omitted(declaration, omitted_released_declarations) {
752            continue;
753        }
754        let label = typeql_label(&declaration.label);
755        let declaration_span = source_span(&document, source, declaration.span)?;
756        let id = TypeId::new(*kind, label.clone())
757            .map_err(|diagnostic| contract(diagnostic, declaration_span.clone()))?;
758        // Released renders re-open declared labels freely — kindless
759        // standalone `plays` lines and explicit split declarations alike —
760        // in any order. Every compatible re-opening merges into the one
761        // identity; genuinely conflicting kinds were already rejected by
762        // `infer_type_kinds` with both spans.
763        if ids.contains_key(&label) {
764            continue;
765        }
766        assembler.insert_fact(
767            SchemaFact::Type(
768                TypeFact::new(id.clone())
769                    .map_err(|diagnostic| contract(diagnostic, declaration_span.clone()))?,
770            ),
771            declaration_span,
772        )?;
773        ids.entry(label).or_insert(id);
774    }
775
776    if released.is_none() {
777        // Keep the strict adapter's original fact-insertion order and
778        // duplicate diagnostics. Released merge behavior belongs only to the
779        // compatibility projection below.
780        for declaration in &declarations {
781            let label = typeql_label(&declaration.label);
782            let id = ids.get(&label).cloned().ok_or_else(|| {
783                error(
784                    DiagnosticCategory::InvalidContract,
785                    "unknown_typeql_type",
786                    format!("TypeQL declaration `{label}` has no inferred type identity"),
787                    query_span(&document, source, declaration.span)
788                        .ok()
789                        .flatten(),
790                )
791            })?;
792            insert_annotations(
793                &mut assembler,
794                AnnotationSubjectId::Type(id.clone()),
795                &declaration.annotations,
796                &document,
797                source,
798            )?;
799            for capability in &declaration.capabilities {
800                insert_capability(
801                    &mut assembler,
802                    &ids,
803                    &id,
804                    capability,
805                    CapabilityAnnotations::Strict(&capability.annotations),
806                    &document,
807                    source,
808                )?;
809            }
810        }
811    } else {
812        // Reproduce the released parser's merge algebra before entering the
813        // strict fact assembler. Attribute declarations are map replacements
814        // (the final declaration wins); entity and relation declarations merge,
815        // with type annotations accumulated under their own last-write/OR
816        // identities and `sub` taking the final spelling.
817        let mut last_attribute_declaration = BTreeMap::new();
818        let mut last_sub_capability = BTreeMap::new();
819        let mut last_value_capability = BTreeMap::new();
820        for (declaration_index, (declaration, kind)) in declarations.iter().zip(&kinds).enumerate()
821        {
822            if released_declaration_is_omitted(declaration, omitted_released_declarations) {
823                continue;
824            }
825            let label = typeql_label(&declaration.label);
826            if *kind == TypeKind::Attribute {
827                last_attribute_declaration.insert(label.clone(), declaration_index);
828            }
829            for (capability_index, capability) in declaration.capabilities.iter().enumerate() {
830                if matches!(&capability.base, CapabilityBase::Sub(_)) {
831                    last_sub_capability
832                        .insert(label.clone(), (declaration_index, capability_index));
833                }
834                if matches!(&capability.base, CapabilityBase::ValueType(_)) {
835                    last_value_capability
836                        .insert(label.clone(), (declaration_index, capability_index));
837                }
838            }
839        }
840
841        let mut merged_type_annotations: BTreeMap<String, Vec<Annotation>> = BTreeMap::new();
842        let mut merged_value_annotations: BTreeMap<String, Vec<Annotation>> = BTreeMap::new();
843        for (declaration_index, (declaration, kind)) in declarations.iter().zip(&kinds).enumerate()
844        {
845            if released_declaration_is_omitted(declaration, omitted_released_declarations) {
846                continue;
847            }
848            let label = typeql_label(&declaration.label);
849            if *kind == TypeKind::Attribute
850                && last_attribute_declaration.get(&label) != Some(&declaration_index)
851            {
852                continue;
853            }
854            if let Some(released) = released {
855                for annotation in declaration.annotations.iter().chain(
856                    declaration
857                        .capabilities
858                        .iter()
859                        .flat_map(|capability| &capability.annotations),
860                ) {
861                    match released_annotation_target(released, annotation) {
862                        Some(ReleasedAnnotationTarget::Value) => merged_value_annotations
863                            .entry(label.clone())
864                            .or_default()
865                            .push(annotation.clone()),
866                        Some(ReleasedAnnotationTarget::Type) => merged_type_annotations
867                            .entry(label.clone())
868                            .or_default()
869                            .push(annotation.clone()),
870                        Some(ReleasedAnnotationTarget::Capability) => {}
871                        None if *kind == TypeKind::Attribute => {
872                            let target = released_attribute_annotation_target(annotation);
873                            let annotations = match target {
874                                ReleasedAnnotationTarget::Value => &mut merged_value_annotations,
875                                ReleasedAnnotationTarget::Type => &mut merged_type_annotations,
876                                ReleasedAnnotationTarget::Capability => continue,
877                            };
878                            annotations
879                                .entry(label.clone())
880                                .or_default()
881                                .push(annotation.clone());
882                        }
883                        None => {}
884                    }
885                }
886            } else {
887                merged_type_annotations
888                    .entry(label)
889                    .or_default()
890                    .extend(declaration.annotations.iter().cloned());
891            }
892        }
893        for (label, annotations) in merged_type_annotations {
894            let id = ids.get(&label).cloned().ok_or_else(|| {
895                error(
896                    DiagnosticCategory::InvalidContract,
897                    "unknown_typeql_type",
898                    format!("TypeQL declaration `{label}` has no inferred type identity"),
899                    None,
900                )
901            })?;
902            insert_released_annotations(
903                &mut assembler,
904                AnnotationSubjectId::Type(id.clone()),
905                &annotations,
906                &document,
907                source,
908            )?;
909        }
910
911        // The released generator observes the first owns/plays/relates capability
912        // by identity, including that capability's annotations. Its parser keeps
913        // duplicates in the initial declaration internally, but every released
914        // emitter resolves the ordered name back to the first matching capability;
915        // compatible projection therefore deduplicates both within one declaration
916        // and across later reopenings. Attribute declarations are replacements,
917        // and within the final declaration their last `sub` and `value` clauses win.
918        let mut first_object_capability = BTreeMap::new();
919        for (declaration_index, (declaration, kind)) in declarations.iter().zip(&kinds).enumerate()
920        {
921            if released_declaration_is_omitted(declaration, omitted_released_declarations) {
922                continue;
923            }
924            let label = typeql_label(&declaration.label);
925            if *kind == TypeKind::Attribute
926                && last_attribute_declaration.get(&label) != Some(&declaration_index)
927            {
928                continue;
929            }
930            let id = ids.get(&label).cloned().ok_or_else(|| {
931                error(
932                    DiagnosticCategory::InvalidContract,
933                    "unknown_typeql_type",
934                    format!("TypeQL declaration `{label}` has no inferred type identity"),
935                    query_span(&document, source, declaration.span)
936                        .ok()
937                        .flatten(),
938                )
939            })?;
940            for (capability_index, capability) in declaration.capabilities.iter().enumerate() {
941                if matches!(&capability.base, CapabilityBase::Sub(_))
942                    && last_sub_capability.get(&label)
943                        != Some(&(declaration_index, capability_index))
944                {
945                    continue;
946                }
947                if matches!(&capability.base, CapabilityBase::ValueType(_))
948                    && last_value_capability.get(&label)
949                        != Some(&(declaration_index, capability_index))
950                {
951                    continue;
952                }
953                if *kind != TypeKind::Attribute
954                    && let Some(capability_id) = released_object_capability_identity(capability)
955                {
956                    let key = (label.clone(), capability_id);
957                    if first_object_capability.contains_key(&key) {
958                        continue;
959                    }
960                    first_object_capability.insert(key, (declaration_index, capability_index));
961                }
962                if omitted_released_capabilities.is_some_and(|omitted| {
963                    capability
964                        .span
965                        .is_some_and(|span| omitted.contains(&span.begin_offset))
966                }) {
967                    continue;
968                }
969                let released_annotations;
970                let annotations = if let Some(released) = released {
971                    released_annotations = capability
972                        .annotations
973                        .iter()
974                        .filter(|annotation| {
975                            released_annotation_target(released, annotation)
976                                == Some(ReleasedAnnotationTarget::Capability)
977                        })
978                        .cloned()
979                        .collect::<Vec<_>>();
980                    released_annotations.as_slice()
981                } else {
982                    capability.annotations.as_slice()
983                };
984                insert_capability(
985                    &mut assembler,
986                    &ids,
987                    &id,
988                    capability,
989                    CapabilityAnnotations::Released {
990                        annotations,
991                        played_role_declaration: capability.span.and_then(|span| {
992                            played_role_declarations
993                                .and_then(|declarations| declarations.get(&span.begin_offset))
994                                .map(String::as_str)
995                        }),
996                    },
997                    &document,
998                    source,
999                )?;
1000            }
1001        }
1002
1003        for (label, annotations) in merged_value_annotations {
1004            let Some(first) = annotations.first() else {
1005                continue;
1006            };
1007            let annotation_span = source_span(&document, source, first.span())?;
1008            let attribute = AttributeId::new(&label)
1009                .map_err(|diagnostic| contract(diagnostic, annotation_span))?;
1010            insert_released_annotations(
1011                &mut assembler,
1012                AnnotationSubjectId::Value(ValueFactId::new(attribute)),
1013                &annotations,
1014                &document,
1015                source,
1016            )?;
1017        }
1018    }
1019
1020    for definable in &definables {
1021        match definable {
1022            Definable::TypeRename(_) | Definable::RoleTypeRename(_) => {
1023                return Err(error(
1024                    DiagnosticCategory::InvalidContract,
1025                    "expected_typeql_define",
1026                    "schema compatibility input must contain only define declarations",
1027                    None,
1028                ));
1029            }
1030            Definable::TypeDeclaration(_) => {}
1031            Definable::Struct(structure) => {
1032                insert_struct(&mut assembler, structure, &document, source)?;
1033            }
1034            Definable::Function(function) => {
1035                insert_function(&mut assembler, function, &document, source)?;
1036                let function_id = FunctionId::new(function.signature.ident.as_str_unchecked())
1037                    .expect("TypeQL emitted a function identifier rejected by the contract");
1038                let body_span = source_span(&document, source, function.block.span)?;
1039                let references =
1040                    function_references::collect_function_body_references(&function.block)
1041                        .map_err(|diagnostic| contract(diagnostic, body_span))?;
1042                function_body_references.insert(function_id, references);
1043            }
1044        }
1045    }
1046
1047    assembler
1048        .finish()
1049        .map(|declared| TypeqlDeclaredSchema::new(declared, function_body_references))
1050}
1051
1052fn restore_released_labels(released: &ReleasedSyntax, definables: &mut [Definable]) {
1053    for definable in definables {
1054        if let Definable::TypeDeclaration(declaration) = definable {
1055            released.restore_label(&mut declaration.label);
1056        }
1057    }
1058}
1059
1060/// Parse one TypeQL `define` query into the canonical declared schema graph.
1061///
1062/// This compatibility wrapper discards only the derived function-body index;
1063/// declared facts and their fingerprints are unchanged.
1064pub fn typeql_to_declared(
1065    document: DocumentId,
1066    source: &str,
1067) -> Result<DeclaredSchema, SchemaDiagnostics> {
1068    typeql_to_declared_with_references(document, source).map(TypeqlDeclaredSchema::into_declared)
1069}
1070
1071/// Parse TypeQL and return canonical direct facts in identity order.
1072pub fn typeql_to_facts(
1073    document: DocumentId,
1074    source: &str,
1075) -> Result<Vec<SchemaFact>, SchemaDiagnostics> {
1076    let declared = typeql_to_declared(document, source)?;
1077    Ok(declared.facts().cloned().collect())
1078}
1079
1080/// Transpile one legacy TOML schema and adapt its rendered TypeQL into the
1081/// canonical declared schema graph.
1082///
1083/// `rendered_typeql_document` identifies the generated TypeQL, not the input
1084/// TOML. Diagnostics from TypeQL parsing and adaptation therefore contain
1085/// offsets into the rendered source and never claim to locate original TOML
1086/// text. TOML decoding and validation diagnostics have no source span because
1087/// the legacy transpiler does not expose structured TOML locations.
1088pub fn toml_to_declared(
1089    rendered_typeql_document: DocumentId,
1090    toml_source: &str,
1091) -> Result<DeclaredSchema, SchemaDiagnostics> {
1092    let rendered_typeql =
1093        type_bridge_toml_transpiler::toml_to_typeql(toml_source).map_err(|transpile_error| {
1094            error(
1095                DiagnosticCategory::InvalidContract,
1096                "invalid_toml_schema",
1097                format!("TOML schema transpilation failed: {transpile_error}"),
1098                None,
1099            )
1100        })?;
1101    typeql_to_declared(rendered_typeql_document, &rendered_typeql)
1102}
1103
1104/// Transpile legacy TOML and return canonical direct facts in identity order.
1105///
1106/// See [`toml_to_declared`] for the provenance contract of
1107/// `rendered_typeql_document`.
1108pub fn toml_to_facts(
1109    rendered_typeql_document: DocumentId,
1110    toml_source: &str,
1111) -> Result<Vec<SchemaFact>, SchemaDiagnostics> {
1112    let declared = toml_to_declared(rendered_typeql_document, toml_source)?;
1113    Ok(declared.facts().cloned().collect())
1114}
1115
1116#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1117enum ReleasedObjectCapabilityIdentity {
1118    Owns(String),
1119    Relates(String),
1120    Plays(String, String),
1121}
1122
1123fn released_declaration_is_omitted(
1124    declaration: &TypeDeclaration,
1125    omitted: Option<&BTreeSet<usize>>,
1126) -> bool {
1127    omitted.is_some_and(|omitted| {
1128        declaration
1129            .span
1130            .is_some_and(|span| omitted.contains(&span.begin_offset))
1131    })
1132}
1133
1134fn released_object_capability_identity(
1135    capability: &Capability,
1136) -> Option<ReleasedObjectCapabilityIdentity> {
1137    match &capability.base {
1138        CapabilityBase::Owns(owns) => capability_type_ref(&owns.owned)
1139            .ok()
1140            .map(|(label, _)| label)
1141            .map(ReleasedObjectCapabilityIdentity::Owns),
1142        CapabilityBase::Relates(relates) => capability_type_ref(&relates.related)
1143            .ok()
1144            .map(|(label, _)| label)
1145            .map(ReleasedObjectCapabilityIdentity::Relates),
1146        CapabilityBase::Plays(plays) => Some(ReleasedObjectCapabilityIdentity::Plays(
1147            typeql_label(&plays.role.scope),
1148            typeql_label(&plays.role.name),
1149        )),
1150        _ => None,
1151    }
1152}
1153
1154fn released_annotation_target(
1155    released: &ReleasedSyntax,
1156    annotation: &Annotation,
1157) -> Option<ReleasedAnnotationTarget> {
1158    annotation
1159        .span()
1160        .map(|span| span.begin_offset)
1161        .and_then(|start| released.annotation_target(start))
1162}
1163
1164fn released_attribute_annotation_target(annotation: &Annotation) -> ReleasedAnnotationTarget {
1165    match annotation {
1166        Annotation::Regex(_) | Annotation::Range(_) | Annotation::Values(_) => {
1167            ReleasedAnnotationTarget::Value
1168        }
1169        _ => ReleasedAnnotationTarget::Type,
1170    }
1171}
1172
1173fn infer_type_kinds(
1174    document: &DocumentId,
1175    source: &str,
1176    declarations: &[&TypeDeclaration],
1177    released: bool,
1178) -> Result<Vec<TypeKind>, SchemaDiagnostics> {
1179    let mut inferred = Vec::with_capacity(declarations.len());
1180    for declaration in declarations {
1181        let mut kind = declaration
1182            .kind
1183            .as_ref()
1184            .map(|kind| kind_from_token(&kind.to_string()))
1185            .transpose()
1186            .map_err(|message| {
1187                at(
1188                    document,
1189                    source,
1190                    declaration.span,
1191                    "unsupported_typeql_kind",
1192                    message,
1193                )
1194            })?;
1195        for capability in &declaration.capabilities {
1196            let hint = match &capability.base {
1197                CapabilityBase::ValueType(_) => Some(TypeKind::Attribute),
1198                CapabilityBase::Relates(_) => Some(TypeKind::Relation),
1199                CapabilityBase::Sub(sub) => root_kind(&typeql_label(&sub.supertype_label)),
1200                _ => None,
1201            };
1202            if let Some(hint) = hint {
1203                merge_kind(&mut kind, hint).map_err(|message| {
1204                    at(
1205                        document,
1206                        source,
1207                        capability.span,
1208                        "conflicting_typeql_kind",
1209                        message,
1210                    )
1211                })?;
1212            }
1213        }
1214        inferred.push(kind);
1215    }
1216
1217    loop {
1218        let mut known = BTreeMap::new();
1219        for (declaration, kind) in declarations.iter().zip(&inferred) {
1220            if let Some(kind) = kind {
1221                let label = typeql_label(&declaration.label);
1222                if let Some(previous) = known.insert(label.clone(), *kind)
1223                    && previous != *kind
1224                {
1225                    return Err(at(
1226                        document,
1227                        source,
1228                        declaration.span,
1229                        "conflicting_typeql_kind",
1230                        format!("TypeQL label `{label}` is declared with incompatible kinds"),
1231                    ));
1232                }
1233            }
1234        }
1235        let mut changed = false;
1236        for (index, declaration) in declarations.iter().enumerate() {
1237            if inferred[index].is_some() {
1238                continue;
1239            }
1240            // A kindless statement re-opening an already-classified label
1241            // (released renders emit standalone `plays` lines this way)
1242            // inherits that label's kind.
1243            if let Some(own_kind) = known.get(&typeql_label(&declaration.label)) {
1244                inferred[index] = Some(*own_kind);
1245                changed = true;
1246                continue;
1247            }
1248            for capability in &declaration.capabilities {
1249                let CapabilityBase::Sub(sub) = &capability.base else {
1250                    continue;
1251                };
1252                if let Some(parent_kind) = known.get(&typeql_label(&sub.supertype_label)) {
1253                    inferred[index] = Some(*parent_kind);
1254                    changed = true;
1255                    break;
1256                }
1257            }
1258        }
1259        if !changed {
1260            break;
1261        }
1262    }
1263
1264    if released {
1265        for (declaration, kind) in declarations.iter().zip(&mut inferred) {
1266            let plays_only = declaration.kind.is_none()
1267                && !declaration.capabilities.is_empty()
1268                && declaration
1269                    .capabilities
1270                    .iter()
1271                    .all(|capability| matches!(capability.base, CapabilityBase::Plays(_)));
1272            if !plays_only {
1273                continue;
1274            }
1275            match kind {
1276                Some(TypeKind::Attribute) => {
1277                    return Err(at(
1278                        document,
1279                        source,
1280                        declaration.span,
1281                        "conflicting_typeql_kind",
1282                        format!(
1283                            "released standalone plays label `{}` conflicts with an attribute declaration",
1284                            typeql_label(&declaration.label)
1285                        ),
1286                    ));
1287                }
1288                Some(TypeKind::Entity | TypeKind::Relation) => {}
1289                Some(TypeKind::Struct) => {
1290                    return Err(at(
1291                        document,
1292                        source,
1293                        declaration.span,
1294                        "conflicting_typeql_kind",
1295                        format!(
1296                            "released standalone plays label `{}` cannot resolve to a struct",
1297                            typeql_label(&declaration.label)
1298                        ),
1299                    ));
1300                }
1301                None => *kind = Some(TypeKind::Entity),
1302            }
1303        }
1304    }
1305
1306    declarations
1307        .iter()
1308        .zip(inferred)
1309        .map(|(declaration, kind)| {
1310            kind.ok_or_else(|| {
1311                at(
1312                    document,
1313                    source,
1314                    declaration.span,
1315                    "ambiguous_typeql_kind",
1316                    format!(
1317                        "TypeQL declaration `{}` does not identify an entity, relation, or attribute kind",
1318                        typeql_label(&declaration.label)
1319                    ),
1320                )
1321            })
1322        })
1323        .collect()
1324}
1325
1326#[derive(Clone, Copy)]
1327enum CapabilityAnnotations<'a> {
1328    Strict(&'a [Annotation]),
1329    Released {
1330        annotations: &'a [Annotation],
1331        played_role_declaration: Option<&'a str>,
1332    },
1333}
1334
1335impl CapabilityAnnotations<'_> {
1336    const fn annotations(&self) -> &[Annotation] {
1337        match self {
1338            Self::Strict(annotations) | Self::Released { annotations, .. } => annotations,
1339        }
1340    }
1341
1342    const fn played_role_declaration(&self) -> Option<&str> {
1343        match self {
1344            Self::Strict(_) => None,
1345            Self::Released {
1346                played_role_declaration,
1347                ..
1348            } => *played_role_declaration,
1349        }
1350    }
1351}
1352
1353fn insert_capability(
1354    assembler: &mut FactAssembler,
1355    ids: &BTreeMap<String, TypeId>,
1356    owner: &TypeId,
1357    capability: &Capability,
1358    annotations: CapabilityAnnotations<'_>,
1359    document: &DocumentId,
1360    source: &str,
1361) -> Result<(), SchemaDiagnostics> {
1362    let annotation_slice = annotations.annotations();
1363    let capability_span = source_span(document, source, capability.span)?;
1364    let subject = match &capability.base {
1365        CapabilityBase::Sub(sub) => {
1366            let parent_label = typeql_label(&sub.supertype_label);
1367            if root_kind(&parent_label).is_some() {
1368                reject_annotations_if_present(annotation_slice, document, source)?;
1369                return Ok(());
1370            }
1371            let parent = ids.get(&parent_label).cloned().ok_or_else(|| {
1372                at(
1373                    document,
1374                    source,
1375                    sub.span,
1376                    "unknown_typeql_parent",
1377                    format!("unknown TypeQL parent `{parent_label}`"),
1378                )
1379            })?;
1380            let id = SubFactId::new(owner.clone(), parent)
1381                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1382            assembler.insert_fact(SchemaFact::Sub(SubFact::new(id.clone())), capability_span)?;
1383            AnnotationSubjectId::Sub(id)
1384        }
1385        CapabilityBase::ValueType(value) => {
1386            let value_type = named_value_type(&value.value_type).map_err(|message| {
1387                at(
1388                    document,
1389                    source,
1390                    value.span,
1391                    "unsupported_typeql_value_type",
1392                    message,
1393                )
1394            })?;
1395            let attribute = AttributeId::new(owner.label().as_str())
1396                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1397            let id = ValueFactId::new(attribute);
1398            assembler.insert_fact(
1399                SchemaFact::Value(ValueFact::new(id.clone(), value_type)),
1400                capability_span,
1401            )?;
1402            AnnotationSubjectId::Value(id)
1403        }
1404        CapabilityBase::Owns(owns) => {
1405            let (attribute_label, collection_mode) =
1406                capability_type_ref(&owns.owned).map_err(|message| {
1407                    at(
1408                        document,
1409                        source,
1410                        owns.span,
1411                        "unsupported_typeql_owns",
1412                        message,
1413                    )
1414                })?;
1415            let attribute_type = ids.get(&attribute_label).ok_or_else(|| {
1416                at(
1417                    document,
1418                    source,
1419                    owns.span,
1420                    "unknown_typeql_attribute",
1421                    format!("unknown owned attribute `{attribute_label}`"),
1422                )
1423            })?;
1424            if attribute_type.kind() != TypeKind::Attribute {
1425                return Err(at(
1426                    document,
1427                    source,
1428                    owns.span,
1429                    "invalid_typeql_owned_kind",
1430                    "TypeQL owns targets must be attribute types",
1431                ));
1432            }
1433            let attribute = AttributeId::new(attribute_label)
1434                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1435            let id = OwnsFactId::new(owner.clone(), attribute)
1436                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1437            assembler.insert_fact(
1438                SchemaFact::Owns(OwnsFact::new_with_collection_mode(
1439                    id.clone(),
1440                    collection_mode,
1441                )),
1442                capability_span,
1443            )?;
1444            AnnotationSubjectId::Owns(id)
1445        }
1446        CapabilityBase::Relates(relates) => {
1447            let (role_label, collection_mode) =
1448                capability_type_ref(&relates.related).map_err(|message| {
1449                    at(
1450                        document,
1451                        source,
1452                        relates.span,
1453                        "unsupported_typeql_relates",
1454                        message,
1455                    )
1456                })?;
1457            let role = RoleId::new(owner.label().as_str(), &role_label)
1458                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1459            let id = RelatesFactId::new(owner.clone(), role)
1460                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1461            let specializes = relates
1462                .specialised
1463                .as_ref()
1464                .map(|specialized| {
1465                    capability_type_ref(specialized)
1466                        .map(|(label, _)| label)
1467                        .map_err(|message| {
1468                            at(
1469                                document,
1470                                source,
1471                                specialized.span(),
1472                                "unsupported_typeql_role_specialization",
1473                                message,
1474                            )
1475                        })
1476                        .and_then(|label| {
1477                            let span = source_span(document, source, specialized.span())?;
1478                            let label = Label::new(label)
1479                                .map_err(|diagnostic| contract(diagnostic, span.clone()))?;
1480                            Ok((label, span))
1481                        })
1482                })
1483                .transpose()?;
1484            assembler.insert_relates_with_collection_mode(
1485                id.clone(),
1486                specializes,
1487                collection_mode,
1488                capability_span,
1489            )?;
1490            AnnotationSubjectId::Relates(id)
1491        }
1492        CapabilityBase::Plays(plays) => {
1493            let relation_label = annotations
1494                .played_role_declaration()
1495                .map(str::to_owned)
1496                .unwrap_or_else(|| typeql_label(&plays.role.scope));
1497            let role_label = typeql_label(&plays.role.name);
1498            let relation = Label::new(&relation_label)
1499                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1500            let role = Label::new(&role_label)
1501                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1502            assembler.insert_plays(
1503                owner.label().clone(),
1504                relation,
1505                role,
1506                capability_span.clone(),
1507            );
1508            let role_id = RoleId::new(relation_label, role_label)
1509                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1510            let id = PlaysFactId::new(owner.clone(), role_id)
1511                .map_err(|diagnostic| contract(diagnostic, capability_span.clone()))?;
1512            AnnotationSubjectId::Plays(id)
1513        }
1514        CapabilityBase::Alias(alias) => {
1515            return Err(at(
1516                document,
1517                source,
1518                alias.span,
1519                "unsupported_typeql_alias",
1520                "TypeQL aliases require an explicit capability contract",
1521            ));
1522        }
1523    };
1524
1525    match annotations {
1526        CapabilityAnnotations::Strict(_) => {
1527            insert_annotations(assembler, subject, annotation_slice, document, source)
1528        }
1529        CapabilityAnnotations::Released { .. } => {
1530            insert_released_annotations(assembler, subject, annotation_slice, document, source)
1531        }
1532    }
1533}
1534
1535fn insert_struct(
1536    assembler: &mut FactAssembler,
1537    structure: &Struct,
1538    document: &DocumentId,
1539    source: &str,
1540) -> Result<(), SchemaDiagnostics> {
1541    if let Some(annotation) = structure.annotations.first() {
1542        return Err(at(
1543            document,
1544            source,
1545            annotation.span(),
1546            "unsupported_typeql_struct_annotation",
1547            "struct annotations are not part of the portable V2 fact contract",
1548        ));
1549    }
1550    let structure_span = source_span(document, source, structure.span)?;
1551    let id = StructId::new(structure.ident.as_str_unchecked())
1552        .map_err(|diagnostic| contract(diagnostic, structure_span.clone()))?;
1553    let mut fields = Vec::with_capacity(structure.fields.len());
1554    for field in &structure.fields {
1555        if let Some(annotation) = field.annotations.first() {
1556            return Err(at(
1557                document,
1558                source,
1559                annotation.span(),
1560                "unsupported_typeql_struct_field_annotation",
1561                "struct field annotations are not live-pinned for the portable contract",
1562            ));
1563        }
1564        let (named, optional) = simple_or_optional_named(&field.type_).map_err(|message| {
1565            at(
1566                document,
1567                source,
1568                field.span,
1569                "unsupported_typeql_struct_field",
1570                message,
1571            )
1572        })?;
1573        let value_type = named_value_type(named).map_err(|message| {
1574            at(
1575                document,
1576                source,
1577                field.span,
1578                "unsupported_typeql_struct_field",
1579                message,
1580            )
1581        })?;
1582        let field_span = source_span(document, source, field.span)?;
1583        let name = Label::new(field.key.as_str_unchecked())
1584            .map_err(|diagnostic| contract(diagnostic, field_span))?;
1585        fields.push(StructField::new(name, value_type, optional));
1586    }
1587    let fact = StructFact::new(id, fields)
1588        .map_err(|diagnostic| contract(diagnostic, structure_span.clone()))?;
1589    assembler.insert_fact(SchemaFact::Struct(fact), structure_span)
1590}
1591
1592fn insert_function(
1593    assembler: &mut FactAssembler,
1594    function: &Function,
1595    document: &DocumentId,
1596    source: &str,
1597) -> Result<(), SchemaDiagnostics> {
1598    let function_span = source_span(document, source, function.span)?;
1599    let id = FunctionId::new(function.signature.ident.as_str_unchecked())
1600        .map_err(|diagnostic| contract(diagnostic, function_span.clone()))?;
1601    let mut parameters = Vec::with_capacity(function.signature.args.len());
1602    for argument in &function.signature.args {
1603        let (named, optional) = simple_or_optional_named(&argument.type_).map_err(|message| {
1604            at(
1605                document,
1606                source,
1607                argument.span,
1608                "unsupported_typeql_function_parameter",
1609                message,
1610            )
1611        })?;
1612        if optional {
1613            return Err(at(
1614                document,
1615                source,
1616                argument.span,
1617                "unsupported_typeql_function_parameter",
1618                "optional function parameters are not part of the V2 signature contract",
1619            ));
1620        }
1621        let name = argument.var.name().ok_or_else(|| {
1622            at(
1623                document,
1624                source,
1625                argument.span,
1626                "anonymous_typeql_function_parameter",
1627                "function parameters must use named variables",
1628            )
1629        })?;
1630        let argument_span = source_span(document, source, argument.span)?;
1631        let name = Label::new(name).map_err(|diagnostic| contract(diagnostic, argument_span))?;
1632        parameters.push(FunctionParameter::new(name, type_reference(named)?));
1633    }
1634    let returns = match &function.signature.output {
1635        Output::Single(single) => {
1636            let elements = return_elements(&single.types, document, source, single.span)?;
1637            if elements.len() == 1 {
1638                FunctionReturnMode::scalar(elements.into_iter().next().expect("one return element"))
1639            } else {
1640                FunctionReturnMode::tuple(elements)
1641                    .map_err(|diagnostic| contract(diagnostic, function_span.clone()))?
1642            }
1643        }
1644        Output::Stream(stream) => FunctionReturnMode::stream(return_elements(
1645            &stream.types,
1646            document,
1647            source,
1648            stream.span,
1649        )?)
1650        .map_err(|diagnostic| contract(diagnostic, function_span.clone()))?,
1651    };
1652    let signature = FunctionSignature::new(parameters, returns)
1653        .map_err(|diagnostic| contract(diagnostic, function_span.clone()))?;
1654    let block_span = function.block.span.ok_or_else(|| {
1655        error(
1656            DiagnosticCategory::InvalidContract,
1657            "missing_typeql_function_body_span",
1658            "TypeQL parser did not retain the function body span",
1659            Some(function_span.clone()),
1660        )
1661    })?;
1662    let body_text = source
1663        .get(block_span.begin_offset..block_span.end_offset)
1664        .ok_or_else(|| {
1665            error(
1666                DiagnosticCategory::InvalidContract,
1667                "invalid_typeql_function_body_span",
1668                "TypeQL function body span is outside the original source",
1669                Some(function_span.clone()),
1670            )
1671        })?;
1672    let body_span = source_span(document, source, Some(block_span))?;
1673    let body =
1674        FunctionBody::new(body_text).map_err(|diagnostic| contract(diagnostic, body_span))?;
1675    assembler.insert_fact(
1676        SchemaFact::Function(FunctionFact::new(id.clone(), signature, body)),
1677        function_span,
1678    )?;
1679    insert_annotations(
1680        assembler,
1681        AnnotationSubjectId::Function(id),
1682        &function.annotations,
1683        document,
1684        source,
1685    )
1686}
1687
1688fn return_elements(
1689    types: &[NamedTypeAny],
1690    document: &DocumentId,
1691    source: &str,
1692    span: Option<Span>,
1693) -> Result<Vec<FunctionReturnElement>, SchemaDiagnostics> {
1694    types
1695        .iter()
1696        .map(|type_| {
1697            let (named, optional) = simple_or_optional_named(type_).map_err(|message| {
1698                at(
1699                    document,
1700                    source,
1701                    span,
1702                    "unsupported_typeql_function_return",
1703                    message,
1704                )
1705            })?;
1706            Ok(FunctionReturnElement::new(type_reference(named)?, optional))
1707        })
1708        .collect()
1709}
1710
1711fn insert_annotations(
1712    assembler: &mut FactAssembler,
1713    subject: AnnotationSubjectId,
1714    annotations: &[Annotation],
1715    document: &DocumentId,
1716    source: &str,
1717) -> Result<(), SchemaDiagnostics> {
1718    for annotation in annotations {
1719        insert_released_annotations(
1720            assembler,
1721            subject.clone(),
1722            core::slice::from_ref(annotation),
1723            document,
1724            source,
1725        )?;
1726    }
1727    Ok(())
1728}
1729
1730fn insert_released_annotations(
1731    assembler: &mut FactAssembler,
1732    subject: AnnotationSubjectId,
1733    annotations: &[Annotation],
1734    document: &DocumentId,
1735    source: &str,
1736) -> Result<(), SchemaDiagnostics> {
1737    // The frozen parser stores one value per annotation identity: presence
1738    // flags accumulate, while doc/regex/values/card and each meta key use the
1739    // final spelling. Repeated attribute ranges update only the bounds present
1740    // in each spelling (`@range(1..) @range(..5)` becomes `1..5`). Stage the
1741    // merged facts before handing them to the strict assembler so compatible
1742    // repetitions do not look like direct fact duplication.
1743    let mut merged = BTreeMap::new();
1744    let mut released_range: Option<(
1745        Option<&typeql::value::Literal>,
1746        Option<&typeql::value::Literal>,
1747        SourceSpan,
1748    )> = None;
1749    for annotation in annotations {
1750        let annotation_span = source_span(document, source, annotation.span())?;
1751        if let Annotation::Range(range) = annotation {
1752            let (lower, upper, latest_span) =
1753                released_range.get_or_insert((None, None, annotation_span.clone()));
1754            if let Some(minimum) = range.min.as_ref() {
1755                *lower = Some(minimum);
1756            }
1757            if let Some(maximum) = range.max.as_ref() {
1758                *upper = Some(maximum);
1759            }
1760            *latest_span = annotation_span;
1761            continue;
1762        }
1763        let kind = annotation_identity_kind(annotation, annotation_span.clone())?;
1764        merged.insert(
1765            AnnotationFactId::new(subject.clone(), kind),
1766            (annotation, annotation_span),
1767        );
1768    }
1769    for (id, (annotation, annotation_span)) in merged {
1770        let (kind, value) = match annotation {
1771            Annotation::Abstract(_) => {
1772                (AnnotationKindId::Abstract, SchemaAnnotationValue::Presence)
1773            }
1774            Annotation::Independent(_) => (
1775                AnnotationKindId::Independent,
1776                SchemaAnnotationValue::Presence,
1777            ),
1778            Annotation::Key(_) => (AnnotationKindId::Key, SchemaAnnotationValue::Presence),
1779            Annotation::Unique(_) => (AnnotationKindId::Unique, SchemaAnnotationValue::Presence),
1780            Annotation::Distinct(_) => {
1781                (AnnotationKindId::Distinct, SchemaAnnotationValue::Presence)
1782            }
1783            Annotation::Cardinality(cardinality) => {
1784                let cardinality = match &cardinality.range {
1785                    CardinalityRange::Exact(exact) => {
1786                        let exact = parse_u64(&exact.value, &annotation_span)?;
1787                        Cardinality::new(exact, Some(exact))
1788                    }
1789                    CardinalityRange::Range(minimum, maximum) => Cardinality::new(
1790                        parse_u64(&minimum.value, &annotation_span)?,
1791                        maximum
1792                            .as_ref()
1793                            .map(|maximum| parse_u64(&maximum.value, &annotation_span))
1794                            .transpose()?,
1795                    ),
1796                }
1797                .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1798                (
1799                    AnnotationKindId::Card,
1800                    SchemaAnnotationValue::Cardinality(cardinality),
1801                )
1802            }
1803            Annotation::Regex(regex) => {
1804                validate_annotation_string(&regex.regex, "regex", annotation_span.clone())?;
1805                let text = regex.regex.unescape_regex().map_err(|unescape_error| {
1806                    error(
1807                        DiagnosticCategory::InvalidContract,
1808                        "invalid_typeql_regex",
1809                        format!("TypeQL regex decoding failed: {unescape_error}"),
1810                        Some(annotation_span.clone()),
1811                    )
1812                })?;
1813                let pattern = RegexPattern::new(text)
1814                    .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1815                (
1816                    AnnotationKindId::Regex,
1817                    SchemaAnnotationValue::Regex(pattern),
1818                )
1819            }
1820            Annotation::Doc(doc) => {
1821                validate_annotation_string(&doc.doc, "doc", annotation_span.clone())?;
1822                let text = doc.doc.unescape().map_err(|unescape_error| {
1823                    error(
1824                        DiagnosticCategory::InvalidContract,
1825                        "invalid_typeql_doc",
1826                        format!("TypeQL documentation decoding failed: {unescape_error}"),
1827                        Some(annotation_span.clone()),
1828                    )
1829                })?;
1830                let text = DocText::new(text)
1831                    .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1832                (AnnotationKindId::Doc, SchemaAnnotationValue::Doc(text))
1833            }
1834            Annotation::Meta(meta) => {
1835                validate_annotation_string(&meta.key, "meta_key", annotation_span.clone())?;
1836                let key = meta.key.unescape().map_err(|unescape_error| {
1837                    error(
1838                        DiagnosticCategory::InvalidContract,
1839                        "invalid_typeql_meta_key",
1840                        format!("TypeQL metadata key decoding failed: {unescape_error}"),
1841                        Some(annotation_span.clone()),
1842                    )
1843                })?;
1844                validate_annotation_string(&meta.value, "meta_value", annotation_span.clone())?;
1845                let value = meta.value.unescape().map_err(|unescape_error| {
1846                    error(
1847                        DiagnosticCategory::InvalidContract,
1848                        "invalid_typeql_meta_value",
1849                        format!("TypeQL metadata value decoding failed: {unescape_error}"),
1850                        Some(annotation_span.clone()),
1851                    )
1852                })?;
1853                let kind = AnnotationKindId::meta(key)
1854                    .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1855                let value = CanonicalString::new(value)
1856                    .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1857                (
1858                    kind,
1859                    SchemaAnnotationValue::Meta(CanonicalValue::String(value)),
1860                )
1861            }
1862            Annotation::Cascade(_) | Annotation::Subkey(_) => {
1863                return Err(error(
1864                    DiagnosticCategory::UnsupportedCapability,
1865                    "unsupported_typeql_annotation",
1866                    "TypeQL annotation has no portable V2 annotation identity",
1867                    Some(annotation_span),
1868                ));
1869            }
1870            Annotation::Range(range) => {
1871                let lower = range
1872                    .min
1873                    .as_ref()
1874                    .map(|literal| annotation_literal(literal, document, source))
1875                    .transpose()?;
1876                let upper = range
1877                    .max
1878                    .as_ref()
1879                    .map(|literal| annotation_literal(literal, document, source))
1880                    .transpose()?;
1881                let range = CanonicalValueRange::new(lower, upper)
1882                    .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1883                (AnnotationKindId::Range, SchemaAnnotationValue::Range(range))
1884            }
1885            Annotation::Values(values) => {
1886                if values.values.len() > MAX_CANONICAL_COLLECTION_LEN {
1887                    return Err(error(
1888                        DiagnosticCategory::InvalidContract,
1889                        "values_annotation_member_limit_exceeded",
1890                        format!(
1891                            "@values contains {} members; the maximum is {MAX_CANONICAL_COLLECTION_LEN}",
1892                            values.values.len()
1893                        ),
1894                        Some(annotation_span),
1895                    ));
1896                }
1897                let values = values
1898                    .values
1899                    .iter()
1900                    .map(|literal| annotation_literal(literal, document, source))
1901                    .collect::<Result<Vec<_>, _>>()?;
1902                let values = CanonicalValueSet::new(values)
1903                    .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1904                (
1905                    AnnotationKindId::Values,
1906                    SchemaAnnotationValue::Values(values),
1907                )
1908            }
1909        };
1910        debug_assert_eq!(id.kind(), &kind);
1911        let fact = AnnotationFact::new(id, value)
1912            .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1913        assembler.insert_fact(SchemaFact::Annotation(fact), annotation_span)?;
1914    }
1915    if let Some((lower, upper, annotation_span)) = released_range
1916        && (lower.is_some() || upper.is_some())
1917    {
1918        let lower = lower
1919            .map(|literal| annotation_literal(literal, document, source))
1920            .transpose()?;
1921        let upper = upper
1922            .map(|literal| annotation_literal(literal, document, source))
1923            .transpose()?;
1924        let range = CanonicalValueRange::new(lower, upper)
1925            .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1926        let id = AnnotationFactId::new(subject, AnnotationKindId::Range);
1927        let fact = AnnotationFact::new(id, SchemaAnnotationValue::Range(range))
1928            .map_err(|diagnostic| contract(diagnostic, annotation_span.clone()))?;
1929        assembler.insert_fact(SchemaFact::Annotation(fact), annotation_span)?;
1930    }
1931    Ok(())
1932}
1933
1934fn annotation_identity_kind(
1935    annotation: &Annotation,
1936    annotation_span: SourceSpan,
1937) -> Result<AnnotationKindId, SchemaDiagnostics> {
1938    Ok(match annotation {
1939        Annotation::Abstract(_) => AnnotationKindId::Abstract,
1940        Annotation::Independent(_) => AnnotationKindId::Independent,
1941        Annotation::Key(_) => AnnotationKindId::Key,
1942        Annotation::Unique(_) => AnnotationKindId::Unique,
1943        Annotation::Distinct(_) => AnnotationKindId::Distinct,
1944        Annotation::Cardinality(_) => AnnotationKindId::Card,
1945        Annotation::Regex(_) => AnnotationKindId::Regex,
1946        Annotation::Doc(_) => AnnotationKindId::Doc,
1947        Annotation::Range(_) => AnnotationKindId::Range,
1948        Annotation::Values(_) => AnnotationKindId::Values,
1949        Annotation::Meta(meta) => {
1950            validate_annotation_string(&meta.key, "meta_key", annotation_span.clone())?;
1951            let key = meta.key.unescape().map_err(|unescape_error| {
1952                error(
1953                    DiagnosticCategory::InvalidContract,
1954                    "invalid_typeql_meta_key",
1955                    format!("TypeQL metadata key decoding failed: {unescape_error}"),
1956                    Some(annotation_span.clone()),
1957                )
1958            })?;
1959            AnnotationKindId::meta(key)
1960                .map_err(|diagnostic| contract(diagnostic, annotation_span))?
1961        }
1962        Annotation::Cascade(_) | Annotation::Subkey(_) => {
1963            return Err(error(
1964                DiagnosticCategory::UnsupportedCapability,
1965                "unsupported_typeql_annotation",
1966                "TypeQL annotation has no portable V2 annotation identity",
1967                Some(annotation_span),
1968            ));
1969        }
1970    })
1971}
1972
1973fn validate_annotation_string(
1974    value: &typeql::value::StringLiteral,
1975    domain: &'static str,
1976    span: SourceSpan,
1977) -> Result<(), SchemaDiagnostics> {
1978    validate_quoted_string(value, domain).map_err(|conversion| {
1979        error(
1980            DiagnosticCategory::InvalidContract,
1981            conversion.code(),
1982            conversion.message(),
1983            Some(span),
1984        )
1985    })
1986}
1987
1988fn annotation_literal(
1989    literal: &typeql::value::Literal,
1990    document: &DocumentId,
1991    source: &str,
1992) -> Result<CanonicalValue, SchemaDiagnostics> {
1993    canonical_literal(literal).map_err(|conversion| {
1994        at(
1995            document,
1996            source,
1997            literal.span,
1998            conversion.code(),
1999            conversion.message(),
2000        )
2001    })
2002}
2003
2004fn reject_annotations_if_present(
2005    annotations: &[Annotation],
2006    document: &DocumentId,
2007    source: &str,
2008) -> Result<(), SchemaDiagnostics> {
2009    if let Some(annotation) = annotations.first() {
2010        return Err(at(
2011            document,
2012            source,
2013            annotation.span(),
2014            "unsupported_root_sub_annotation",
2015            "annotations on built-in root sub declarations have no portable subject identity",
2016        ));
2017    }
2018    Ok(())
2019}
2020
2021fn capability_type_ref(reference: &TypeRefAny) -> Result<(String, CollectionMode), String> {
2022    match reference {
2023        TypeRefAny::Type(inner) => {
2024            plain_inner_type_ref(inner).map(|label| (label, CollectionMode::Unordered))
2025        }
2026        TypeRefAny::List(list) => {
2027            plain_inner_type_ref(&list.inner).map(|label| (label, CollectionMode::OrderedList))
2028        }
2029    }
2030}
2031
2032fn plain_inner_type_ref(reference: &TypeRef) -> Result<String, String> {
2033    match reference {
2034        TypeRef::Label(label) => Ok(typeql_label(label)),
2035        TypeRef::Scoped(_) => {
2036            Err("scoped type references are not valid in this capability".to_owned())
2037        }
2038        TypeRef::Variable(_) => {
2039            Err("type variables are not valid in schema declarations".to_owned())
2040        }
2041    }
2042}
2043
2044fn simple_or_optional_named(reference: &NamedTypeAny) -> Result<(&NamedType, bool), String> {
2045    match reference {
2046        NamedTypeAny::Simple(named) => Ok((named, false)),
2047        NamedTypeAny::Optional(optional) => Ok((&optional.inner, true)),
2048        NamedTypeAny::List(_) => Err("list type references are not live-pinned".to_owned()),
2049    }
2050}
2051
2052fn type_reference(named: &NamedType) -> Result<TypeReference, SchemaDiagnostics> {
2053    TypeReference::from_token(named.to_string()).map_err(contract_without_span)
2054}
2055
2056fn named_value_type(named: &NamedType) -> Result<ValueTypeTag, String> {
2057    match named {
2058        NamedType::BuiltinValueType(value_type) => {
2059            value_type_from_token(&value_type.token.to_string())
2060        }
2061        // Released schema text spells some builtins through the frozen
2062        // alias table (`int`, `long`, `bool`); the strict grammar lexes
2063        // those as labels, and this compatibility front-end honors them.
2064        NamedType::Label(label) => value_type_from_token(&typeql_label(label)),
2065    }
2066}
2067
2068fn value_type_from_token(token: &str) -> Result<ValueTypeTag, String> {
2069    match token {
2070        "string" => Ok(ValueTypeTag::String),
2071        "integer" | "int" | "long" => Ok(ValueTypeTag::Long),
2072        "double" => Ok(ValueTypeTag::Double),
2073        "boolean" | "bool" => Ok(ValueTypeTag::Boolean),
2074        "date" => Ok(ValueTypeTag::Date),
2075        "datetime" => Ok(ValueTypeTag::DateTime),
2076        "datetime-tz" => Ok(ValueTypeTag::DateTimeTz),
2077        "decimal" => Ok(ValueTypeTag::Decimal),
2078        "duration" => Ok(ValueTypeTag::Duration),
2079        _ => Err(format!("unsupported TypeQL value type `{token}`")),
2080    }
2081}
2082
2083fn kind_from_token(token: &str) -> Result<TypeKind, String> {
2084    match token {
2085        "entity" => Ok(TypeKind::Entity),
2086        "relation" => Ok(TypeKind::Relation),
2087        "attribute" => Ok(TypeKind::Attribute),
2088        "role" => Err("roles must be declared through relation relates facts".to_owned()),
2089        _ => Err(format!("unsupported TypeQL type kind `{token}`")),
2090    }
2091}
2092
2093fn root_kind(label: &str) -> Option<TypeKind> {
2094    match label {
2095        "entity" => Some(TypeKind::Entity),
2096        "relation" => Some(TypeKind::Relation),
2097        "attribute" => Some(TypeKind::Attribute),
2098        _ => None,
2099    }
2100}
2101
2102fn merge_kind(kind: &mut Option<TypeKind>, hint: TypeKind) -> Result<(), String> {
2103    match kind {
2104        Some(current) if *current != hint => {
2105            Err("TypeQL declaration contains incompatible kind evidence".to_owned())
2106        }
2107        Some(_) => Ok(()),
2108        None => {
2109            *kind = Some(hint);
2110            Ok(())
2111        }
2112    }
2113}
2114
2115fn typeql_label(label: &typeql::type_::Label) -> String {
2116    label.ident.as_str_unchecked().to_owned()
2117}
2118
2119fn parse_u64(value: &str, span: &SourceSpan) -> Result<u64, SchemaDiagnostics> {
2120    value.parse().map_err(|_| {
2121        error(
2122            DiagnosticCategory::InvalidContract,
2123            "invalid_typeql_cardinality",
2124            "TypeQL cardinality is outside the portable unsigned 64-bit domain",
2125            Some(span.clone()),
2126        )
2127    })
2128}
2129
2130fn source_span(
2131    document: &DocumentId,
2132    source: &str,
2133    span: Option<Span>,
2134) -> Result<SourceSpan, SchemaDiagnostics> {
2135    let span = span.unwrap_or(Span {
2136        begin_offset: 0,
2137        end_offset: source.len(),
2138    });
2139    if span.begin_offset > span.end_offset
2140        || span.end_offset > source.len()
2141        || !source.is_char_boundary(span.begin_offset)
2142        || !source.is_char_boundary(span.end_offset)
2143    {
2144        return Err(error(
2145            DiagnosticCategory::InvalidContract,
2146            "invalid_typeql_source_span",
2147            "TypeQL parser returned a source span outside the original input",
2148            None,
2149        ));
2150    }
2151    let (line, column) = line_column(source, span.begin_offset)?;
2152    let (end_line, end_column) = line_column(source, span.end_offset)?;
2153    SourceSpan::new(
2154        document.clone(),
2155        span.begin_offset as u64,
2156        span.end_offset as u64,
2157        line,
2158        column,
2159        end_line,
2160        end_column,
2161    )
2162    .map_err(contract_without_span)
2163}
2164
2165fn query_span(
2166    document: &DocumentId,
2167    source: &str,
2168    span: Option<Span>,
2169) -> Result<Option<SourceSpan>, SchemaDiagnostics> {
2170    source_span(document, source, span).map(Some)
2171}
2172
2173fn line_column(source: &str, offset: usize) -> Result<(u32, u32), SchemaDiagnostics> {
2174    let prefix = &source[..offset];
2175    let line_count = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
2176    let column_count = prefix
2177        .rsplit_once('\n')
2178        .map_or(prefix, |(_, tail)| tail)
2179        .chars()
2180        .count()
2181        + 1;
2182    let line = u32::try_from(line_count).map_err(|_| {
2183        error(
2184            DiagnosticCategory::InvalidContract,
2185            "typeql_source_position_overflow",
2186            "TypeQL source line exceeds the portable position domain",
2187            None,
2188        )
2189    })?;
2190    let column = u32::try_from(column_count).map_err(|_| {
2191        error(
2192            DiagnosticCategory::InvalidContract,
2193            "typeql_source_position_overflow",
2194            "TypeQL source column exceeds the portable position domain",
2195            None,
2196        )
2197    })?;
2198    Ok((line, column))
2199}
2200
2201fn at(
2202    document: &DocumentId,
2203    source: &str,
2204    span: Option<Span>,
2205    code: &'static str,
2206    message: impl Into<String>,
2207) -> SchemaDiagnostics {
2208    match source_span(document, source, span) {
2209        Ok(span) => error(
2210            DiagnosticCategory::InvalidContract,
2211            code,
2212            message,
2213            Some(span),
2214        ),
2215        Err(error) => error,
2216    }
2217}
2218
2219fn error(
2220    category: DiagnosticCategory,
2221    code: &'static str,
2222    message: impl Into<String>,
2223    primary: Option<SourceSpan>,
2224) -> SchemaDiagnostics {
2225    let diagnostic = Diagnostic::new(
2226        category,
2227        DiagnosticCode::new(code).expect("static schema compatibility diagnostic code is valid"),
2228        message,
2229    );
2230    SchemaDiagnostics::one(SchemaDiagnostic::new(diagnostic, primary))
2231}
2232
2233fn contract(diagnostic: Diagnostic, span: SourceSpan) -> SchemaDiagnostics {
2234    SchemaDiagnostics::one(SchemaDiagnostic::new(diagnostic, Some(span)))
2235}
2236
2237fn contract_without_span(diagnostic: Diagnostic) -> SchemaDiagnostics {
2238    SchemaDiagnostics::one(SchemaDiagnostic::new(diagnostic, None))
2239}
2240
2241#[cfg(test)]
2242mod tests {
2243    use super::*;
2244
2245    #[test]
2246    fn trusted_generator_size_policy_does_not_widen_defensive_inputs() {
2247        assert!(TypeqlSourceSizePolicy::Defensive.allows(MAX_TYPEQL_SCHEMA_BYTES));
2248        assert!(!TypeqlSourceSizePolicy::Defensive.allows(MAX_TYPEQL_SCHEMA_BYTES + 1));
2249        assert!(TypeqlSourceSizePolicy::TrustedGenerator.allows(MAX_TYPEQL_SCHEMA_BYTES + 1));
2250    }
2251
2252    #[test]
2253    fn deep_role_specialization_index_uses_heap_stack_and_one_tree_walk() {
2254        const DEPTH: usize = 25_000;
2255        let mut relation_names = BTreeSet::new();
2256        let mut role_names_by_relation = BTreeMap::<String, Vec<String>>::new();
2257        let mut roles = BTreeMap::new();
2258        let mut parents = BTreeMap::new();
2259
2260        for index in 0..DEPTH {
2261            let relation = format!("relation-{index}");
2262            let role = if index == 0 {
2263                "root-role".to_owned()
2264            } else {
2265                format!("role-{index}")
2266            };
2267            relation_names.insert(relation.clone());
2268            role_names_by_relation.insert(relation.clone(), vec![role.clone()]);
2269            roles.insert(
2270                (relation.clone(), role),
2271                ReleasedIndexedRole {
2272                    capability_index: index,
2273                    specializes: (index != 0).then(|| "root-role".to_owned()),
2274                },
2275            );
2276            if index != 0 {
2277                parents.insert(relation, format!("relation-{}", index - 1));
2278            }
2279        }
2280
2281        let leaf = format!("relation-{}", DEPTH - 1);
2282        let leaf_role = format!("role-{}", DEPTH - 1);
2283        let played = BTreeMap::from([(
2284            leaf.clone(),
2285            BTreeSet::from(["root-role".to_owned(), leaf_role.clone()]),
2286        )]);
2287        let resolution = released_role_validities(
2288            &relation_names,
2289            &role_names_by_relation,
2290            &played,
2291            &roles,
2292            &parents,
2293        );
2294
2295        assert_eq!(resolution.direct.len(), DEPTH);
2296        assert!(
2297            resolution
2298                .direct
2299                .values()
2300                .all(|validity| *validity == ReleasedRoleValidity::Valid)
2301        );
2302        assert_eq!(
2303            resolution.plays.get(&(leaf.clone(), leaf_role)),
2304            Some(&ReleasedRoleValidity::Valid)
2305        );
2306        assert_eq!(
2307            resolution.plays.get(&(leaf, "root-role".to_owned())),
2308            Some(&ReleasedRoleValidity::Invalid)
2309        );
2310    }
2311}