meta-language 1.0.0

A self-describing links-network core for lossless language representation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
//! Editable program representations for JavaScript, Rust, Lean, and Rocq.

mod analysis;
mod edit;
mod module_resolution;
mod project;
mod snapshot;

pub use project::{
    ProgramExpansion, ProgramProjectContext, ProgramProjectModule, ProgramProjectReference,
    ProgramProjectSource,
};
pub use snapshot::{PROGRAM_SNAPSHOT_SCHEMA_VERSION, construct_program_from_fragments};

use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;

use crate::decorators::{DecoratorLevel, DecoratorSet, decorator_record, record_field};
use crate::{LinkNetwork, LinkType, ParseConfiguration, language_support};
use analysis::{
    SemanticToken, effect_markers, extension_markers, module_markers, proof_markers,
    resolve_bindings, scope_by_id, semantic_tokens, syntax_facts, unique_facts,
    validate_identifier,
};
use module_resolution::{module_requests, project_has_module};

/// Schema revision for four-language program representations.
pub const PROGRAM_REPRESENTATION_SCHEMA_VERSION: u32 = 1;

/// Semantic construct categories audited for every four-language frontend.
pub const SEMANTIC_CONSTRUCTS: [&str; 10] = [
    "modules-and-imports",
    "scopes-and-bindings",
    "recursive-definitions",
    "types-and-universes",
    "effects",
    "attributes",
    "macros-and-notation",
    "proof-terms-and-tactics",
    "surface-expansion-elaboration-traces",
    "project-context-and-dependencies",
];

/// Source range in UTF-8 byte offsets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct ProgramRange {
    start: usize,
    end: usize,
}

impl ProgramRange {
    /// Creates an exact UTF-8 byte range.
    #[must_use]
    pub const fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    /// Inclusive start byte.
    #[must_use]
    pub const fn start(self) -> usize {
        self.start
    }

    /// Exclusive end byte.
    #[must_use]
    pub const fn end(self) -> usize {
        self.end
    }
}

/// One lexical scope.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramScope {
    id: String,
    parent: Option<String>,
    range: ProgramRange,
    depth: usize,
}

impl ProgramScope {
    /// Stable scope identifier.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Parent scope identifier.
    #[must_use]
    pub fn parent(&self) -> Option<&str> {
        self.parent.as_deref()
    }

    /// Source range governed by the scope.
    #[must_use]
    pub const fn range(&self) -> ProgramRange {
        self.range
    }

    /// Lexical nesting depth.
    #[must_use]
    pub const fn depth(&self) -> usize {
        self.depth
    }
}

/// A resolved declaration and its exact references.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramBinding {
    id: String,
    name: String,
    kind: String,
    scope: String,
    declaration: ProgramRange,
    references: Vec<ProgramRange>,
}

impl ProgramBinding {
    /// Stable binding identifier derived from language and declaration byte.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Declared spelling.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Declaration kind.
    #[must_use]
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Governing lexical scope.
    #[must_use]
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// Declaration source range.
    #[must_use]
    pub const fn declaration(&self) -> ProgramRange {
        self.declaration
    }

    /// References resolving to this declaration.
    #[must_use]
    pub fn references(&self) -> &[ProgramRange] {
        &self.references
    }
}

/// Generic semantic fact with source evidence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramFact {
    kind: String,
    name: String,
    range: ProgramRange,
    phase: Option<String>,
    file: Option<String>,
}

impl ProgramFact {
    fn new(kind: impl Into<String>, name: impl Into<String>, range: ProgramRange) -> Self {
        Self {
            kind: kind.into(),
            name: name.into(),
            range,
            phase: None,
            file: None,
        }
    }

    fn with_phase(mut self, phase: &str) -> Self {
        self.phase = Some(phase.to_string());
        self
    }

    /// Fact kind.
    #[must_use]
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Fact name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Source range.
    #[must_use]
    pub const fn range(&self) -> ProgramRange {
        self.range
    }

    /// Representation phase, when applicable.
    #[must_use]
    pub fn phase(&self) -> Option<&str> {
        self.phase.as_deref()
    }

    /// The project file the range belongs to, when it is not the analyzed
    /// program itself.
    #[must_use]
    pub fn file(&self) -> Option<&str> {
        self.file.as_deref()
    }
}

/// CST node to semantic fact source mapping.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramSourceMapping {
    link_id: u64,
    term: String,
    range: ProgramRange,
}

impl ProgramSourceMapping {
    /// Source CST link id.
    #[must_use]
    pub const fn link_id(&self) -> u64 {
        self.link_id
    }

    /// Grammar term.
    #[must_use]
    pub fn term(&self) -> &str {
        &self.term
    }

    /// Mapped source range.
    #[must_use]
    pub const fn range(&self) -> ProgramRange {
        self.range
    }
}

/// Parse diagnostic retained in the representation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramDiagnostic {
    kind: &'static str,
    term: String,
    range: ProgramRange,
}

impl ProgramDiagnostic {
    /// Diagnostic kind.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        self.kind
    }

    /// Grammar term carrying the diagnostic.
    #[must_use]
    pub fn term(&self) -> &str {
        &self.term
    }

    /// Diagnostic source range.
    #[must_use]
    pub const fn range(&self) -> ProgramRange {
        self.range
    }
}

/// Representation state for one required semantic construct.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProgramConstructStatus {
    /// The source contains the construct and it has structured evidence.
    Represented,
    /// The source contains no instance of the construct.
    NotPresent,
    /// The language does not define this construct class.
    NotApplicable,
    /// The runtime has not produced the required semantic structure.
    Unavailable,
}

/// One semantic construct coverage record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramConstruct {
    kind: &'static str,
    status: ProgramConstructStatus,
    evidence: Vec<ProgramFact>,
    rationale: Option<String>,
}

impl ProgramConstruct {
    /// Construct category.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        self.kind
    }

    /// Representation state.
    #[must_use]
    pub const fn status(&self) -> ProgramConstructStatus {
        self.status
    }

    /// Source-backed evidence.
    #[must_use]
    pub fn evidence(&self) -> &[ProgramFact] {
        &self.evidence
    }

    /// Rationale for a non-represented state.
    #[must_use]
    pub fn rationale(&self) -> Option<&str> {
        self.rationale.as_deref()
    }
}

/// Semantic analysis or binding-safe edit failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProgramRepresentationError {
    /// No four-language frontend is registered.
    UnsupportedLanguage(String),
    /// Binding id is absent.
    UnknownBinding(String),
    /// Replacement is not a valid identifier.
    InvalidIdentifier {
        language: String,
        identifier: String,
    },
    /// Rename would capture another binding.
    CaptureConflict { identifier: String, offset: usize },
    /// A range is reversed, out of bounds, or splits a UTF-8 code point.
    InvalidRange { start: usize, end: usize },
    /// A move destination falls strictly inside the moved range.
    DestinationInsideRange,
    /// The edited result does not parse cleanly.
    InvalidEdit,
    /// A serialized program snapshot is malformed or inconsistent.
    InvalidSnapshot(String),
}

impl fmt::Display for ProgramRepresentationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedLanguage(language) => {
                write!(
                    formatter,
                    "program semantics are not registered for {language}"
                )
            }
            Self::UnknownBinding(binding) => write!(formatter, "unknown binding {binding}"),
            Self::InvalidIdentifier {
                language,
                identifier,
            } => write!(
                formatter,
                "{identifier:?} is not a valid {language} identifier"
            ),
            Self::CaptureConflict { identifier, offset } => write!(
                formatter,
                "rename would capture {identifier} at {offset} (binding conflict)"
            ),
            Self::InvalidRange { start, end } => {
                write!(formatter, "invalid UTF-8 source range {start}..{end}")
            }
            Self::DestinationInsideRange => {
                formatter.write_str("move destination is inside the moved range")
            }
            Self::InvalidEdit => formatter.write_str("structured edit does not reparse cleanly"),
            Self::InvalidSnapshot(reason) => {
                write!(formatter, "invalid program snapshot: {reason}")
            }
        }
    }
}

impl Error for ProgramRepresentationError {}

/// CST-backed resolved program model.
#[derive(Clone, Debug)]
pub struct ProgramRepresentation {
    schema_version: u32,
    language: &'static str,
    source: String,
    project: ProgramProjectContext,
    network: LinkNetwork,
    scopes: Vec<ProgramScope>,
    bindings: Vec<ProgramBinding>,
    unresolved_references: Vec<ProgramFact>,
    source_mappings: Vec<ProgramSourceMapping>,
    modules: Vec<ProgramFact>,
    types: Vec<ProgramFact>,
    extensions: Vec<ProgramFact>,
    proofs: Vec<ProgramFact>,
    diagnostics: Vec<ProgramDiagnostic>,
    project_modules: Vec<ProgramProjectModule>,
    project_facts: Vec<ProgramFact>,
    project_references: Vec<ProgramProjectReference>,
    expansions: Vec<ProgramExpansion>,
    constructs: Vec<ProgramConstruct>,
}

impl ProgramRepresentation {
    fn analyze(
        source: &str,
        language: &str,
        project: ProgramProjectContext,
    ) -> Result<Self, ProgramRepresentationError> {
        Self::analyze_decorated(source, language, project, &DecoratorSet::empty())
    }

    fn analyze_decorated(
        source: &str,
        language: &str,
        project: ProgramProjectContext,
        decorators: &DecoratorSet,
    ) -> Result<Self, ProgramRepresentationError> {
        let support = language_support(language)
            .ok_or_else(|| ProgramRepresentationError::UnsupportedLanguage(language.to_string()))?;
        let network = LinkNetwork::parse(source, support.name, ParseConfiguration::default());
        let source_mappings = decorate_syntax_facts(syntax_facts(&network), source, decorators);
        let tokens = semantic_tokens(source, support.name, &source_mappings);
        let (scopes, bindings, unresolved_references) =
            resolve_bindings(&tokens, &source_mappings, source.len(), support.name);
        let context = project::project_semantics(
            support.name,
            source,
            &source_mappings,
            &bindings,
            &unresolved_references,
            &project,
        );
        let modules = module_facts(
            &tokens,
            &source_mappings,
            source,
            support.name,
            &project,
            &context.requests,
        );
        let types = type_facts(&tokens, &source_mappings, support.name);
        let extensions = extension_facts(&tokens, &source_mappings, source, support.name);
        let proofs = proof_facts(&tokens, &source_mappings, support.name);
        let mut diagnostics = diagnostic_facts(&network);
        diagnostics.extend(project_diagnostics(&modules, &context.resolved_requests));
        diagnostics.extend(context.diagnostics.iter().cloned());
        let mut program = Self {
            schema_version: PROGRAM_REPRESENTATION_SCHEMA_VERSION,
            language: support.name,
            source: source.to_string(),
            project,
            network,
            scopes,
            bindings,
            unresolved_references,
            source_mappings,
            modules,
            types,
            extensions,
            proofs,
            diagnostics,
            project_modules: context.modules.clone(),
            project_facts: context.facts.clone(),
            project_references: context.references.clone(),
            expansions: context.expansions.clone(),
            constructs: Vec::new(),
        };
        program.constructs = construct_facts(&program, &context);
        Ok(program)
    }

    /// Schema revision.
    #[must_use]
    pub const fn schema_version(&self) -> u32 {
        self.schema_version
    }

    /// Canonical language name.
    #[must_use]
    pub const fn language(&self) -> &'static str {
        self.language
    }

    /// Exact source text.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Project context used during analysis.
    #[must_use]
    pub const fn project(&self) -> &ProgramProjectContext {
        &self.project
    }

    /// Concrete syntax network enriched by this representation.
    #[must_use]
    pub const fn network(&self) -> &LinkNetwork {
        &self.network
    }

    /// Lexical scopes inferred from parsed source.
    #[must_use]
    pub fn scopes(&self) -> &[ProgramScope] {
        &self.scopes
    }

    /// Local bindings inferred from parsed source.
    #[must_use]
    pub fn bindings(&self) -> &[ProgramBinding] {
        &self.bindings
    }

    /// Identifier occurrences without a local declaration.
    #[must_use]
    pub fn unresolved_references(&self) -> &[ProgramFact] {
        &self.unresolved_references
    }

    /// CST source mappings.
    #[must_use]
    pub fn source_mappings(&self) -> &[ProgramSourceMapping] {
        &self.source_mappings
    }

    /// Module and import facts.
    #[must_use]
    pub fn modules(&self) -> &[ProgramFact] {
        &self.modules
    }

    /// Type and universe facts.
    #[must_use]
    pub fn types(&self) -> &[ProgramFact] {
        &self.types
    }

    /// Attribute, macro, notation, and syntax-extension facts.
    #[must_use]
    pub fn extensions(&self) -> &[ProgramFact] {
        &self.extensions
    }

    /// Proof and tactic facts.
    #[must_use]
    pub fn proofs(&self) -> &[ProgramFact] {
        &self.proofs
    }

    /// Parse diagnostics.
    #[must_use]
    pub fn diagnostics(&self) -> &[ProgramDiagnostic] {
        &self.diagnostics
    }

    /// Project modules the entry program's requests resolve to.
    #[must_use]
    pub fn project_modules(&self) -> &[ProgramProjectModule] {
        &self.project_modules
    }

    /// Project files and manifests read during analysis.
    #[must_use]
    pub fn project_facts(&self) -> &[ProgramFact] {
        &self.project_facts
    }

    /// Links from the entry program to declarations in other project files.
    #[must_use]
    pub fn project_references(&self) -> &[ProgramProjectReference] {
        &self.project_references
    }

    /// Macro, template and notation expansions enabled by the project.
    #[must_use]
    pub fn expansions(&self) -> &[ProgramExpansion] {
        &self.expansions
    }

    /// Semantic construct coverage.
    #[must_use]
    pub fn constructs(&self) -> &[ProgramConstruct] {
        &self.constructs
    }

    /// Emits exact source from the retained token network.
    #[must_use]
    pub fn emit(&self) -> String {
        self.network.reconstruct_text()
    }
}

/// Analyzes a four-language program with project context.
pub fn analyze_program(
    source: &str,
    language: &str,
    project: ProgramProjectContext,
) -> Result<ProgramRepresentation, ProgramRepresentationError> {
    ProgramRepresentation::analyze(source, language, project)
}

/// [`analyze_program`] after the `cst-to-ast` decorators of `decorators`.
///
/// They see each syntax node the model is built from as `{ term, text }`:
/// setting `term` changes the construct the semantics read it as, and `drop`
/// leaves it out of the model. The network keeps the parsed tree either way.
pub fn analyze_program_decorated(
    source: &str,
    language: &str,
    project: ProgramProjectContext,
    decorators: &DecoratorSet,
) -> Result<ProgramRepresentation, ProgramRepresentationError> {
    ProgramRepresentation::analyze_decorated(source, language, project, decorators)
}

// The syntax facts the `cst-to-ast` decorators leave, with the terms they set.
fn decorate_syntax_facts(
    facts: Vec<ProgramSourceMapping>,
    source: &str,
    decorators: &DecoratorSet,
) -> Vec<ProgramSourceMapping> {
    if !decorators.has(DecoratorLevel::CstToAst) {
        return facts;
    }
    facts
        .into_iter()
        .filter_map(|mut fact| {
            let text = source
                .get(fact.range.start..fact.range.end)
                .unwrap_or_default();
            let record = decorator_record([("term", fact.term.as_str()), ("text", text)]);
            let decorated = decorators.decorate(DecoratorLevel::CstToAst, &record)?;
            record_field(&decorated, "term").clone_into(&mut fact.term);
            Some(fact)
        })
        .collect()
}

/// Constructs a program and rejects syntax that cannot be represented cleanly.
pub fn construct_program(
    source: &str,
    language: &str,
    project: ProgramProjectContext,
) -> Result<ProgramRepresentation, ProgramRepresentationError> {
    let program = ProgramRepresentation::analyze(source, language, project)?;
    if !program.network.verify_full_match(None).is_clean() {
        return Err(ProgramRepresentationError::InvalidEdit);
    }
    Ok(program)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TokenKind {
    Identifier,
    Keyword,
    Punctuation,
}

fn module_facts(
    tokens: &[SemanticToken],
    syntax: &[ProgramSourceMapping],
    source: &str,
    language: &str,
    project: &ProgramProjectContext,
    project_requests: &[ProgramFact],
) -> Vec<ProgramFact> {
    let markers = module_markers(language);
    let mut facts = Vec::new();
    for (index, token) in tokens.iter().enumerate() {
        if !markers.contains(&token.text.as_str()) {
            continue;
        }
        let names = tokens[index + 1..]
            .iter()
            .take_while(|candidate| {
                candidate.text != ";" && !markers.contains(&candidate.text.as_str())
            })
            .filter(|candidate| candidate.kind == TokenKind::Identifier)
            .take(3)
            .map(|candidate| candidate.text.as_str())
            .collect::<Vec<_>>()
            .join(".");
        facts.push(ProgramFact::new(&token.text, names, token.range));
    }
    facts.extend(project.dependencies().iter().map(|dependency| {
        ProgramFact::new(
            "declared-project-dependency",
            dependency,
            ProgramRange::default(),
        )
    }));
    let requests = module_requests(syntax, source, language);
    for request in requests.into_iter().chain(project_requests.iter().cloned()) {
        if project_has_module(project, &request.name, language) {
            facts.push(ProgramFact::new(
                "recognized-toolchain-module",
                &request.name,
                request.range,
            ));
        }
        facts.push(request);
    }
    unique_facts(facts)
}

fn type_facts(
    tokens: &[SemanticToken],
    syntax: &[ProgramSourceMapping],
    language: &str,
) -> Vec<ProgramFact> {
    let mut facts = syntax
        .iter()
        .filter(|mapping| {
            let term = mapping.term.to_ascii_lowercase();
            term.contains("type") || term.contains("universe")
        })
        .map(|mapping| {
            ProgramFact::new("syntax-type", &mapping.term, mapping.range).with_phase("surface")
        })
        .collect::<Vec<_>>();
    for (index, token) in tokens.iter().enumerate() {
        if token.text == ":"
            && let Some(value) = tokens.get(index + 1)
        {
            facts.push(
                ProgramFact::new("annotation", &value.text, value.range).with_phase("surface"),
            );
        }
        if matches!(token.text.as_str(), "universe" | "Universe" | "Type") {
            facts.push(
                ProgramFact::new(
                    "universe",
                    tokens
                        .get(index + 1)
                        .map_or(&token.text, |value| &value.text),
                    token.range,
                )
                .with_phase("surface"),
            );
        }
    }
    if language == "JavaScript" {
        facts.push(
            ProgramFact::new("dynamic-type", "ECMAScript value", ProgramRange::default())
                .with_phase("runtime"),
        );
    }
    unique_facts(facts)
}

fn extension_facts(
    tokens: &[SemanticToken],
    syntax: &[ProgramSourceMapping],
    source: &str,
    language: &str,
) -> Vec<ProgramFact> {
    let markers = extension_markers(language);
    let mut facts = tokens
        .iter()
        .filter(|token| markers.contains(&token.text.as_str()))
        .map(|token| ProgramFact::new(&token.text, &token.text, token.range))
        .collect::<Vec<_>>();
    facts.extend(syntax.iter().filter_map(|mapping| {
        let term = mapping.term.to_ascii_lowercase();
        [
            "macro",
            "attribute",
            "decorator",
            "quotation",
            "template",
            "notation",
        ]
        .iter()
        .any(|needle| term.contains(needle))
        .then(|| ProgramFact::new(&mapping.term, &mapping.term, mapping.range))
    }));
    if language == "JavaScript"
        && let Some(start) = source.find("\"use strict\"")
    {
        facts.push(ProgramFact::new(
            "directive",
            "use strict",
            ProgramRange::new(start, start + 12),
        ));
    }
    unique_facts(facts)
}

fn proof_facts(
    tokens: &[SemanticToken],
    syntax: &[ProgramSourceMapping],
    language: &str,
) -> Vec<ProgramFact> {
    if matches!(language, "JavaScript" | "Rust") {
        return Vec::new();
    }
    let markers = proof_markers(language);
    let facts = tokens
        .iter()
        .filter(|token| markers.contains(&token.text.as_str()))
        .map(|token| ProgramFact::new(&token.text, &token.text, token.range))
        .chain(syntax.iter().filter_map(|mapping| {
            let term = mapping.term.to_ascii_lowercase();
            ["theorem", "proof", "tactic"]
                .iter()
                .any(|needle| term.contains(needle))
                .then(|| ProgramFact::new(&mapping.term, &mapping.term, mapping.range))
        }))
        .collect();
    unique_facts(facts)
}

fn diagnostic_facts(network: &LinkNetwork) -> Vec<ProgramDiagnostic> {
    network
        .verify_full_match(None)
        .issues()
        .iter()
        .filter_map(|issue| {
            let link = network.link(issue.link_id())?;
            let span = link.metadata().span();
            Some(ProgramDiagnostic {
                kind: if link.metadata().flags().is_missing() {
                    "missing"
                } else {
                    "parse-error"
                },
                term: link.metadata().term().unwrap_or_default().to_string(),
                range: span.map_or_else(ProgramRange::default, |span| {
                    ProgramRange::new(span.byte_range().start(), span.byte_range().end())
                }),
            })
        })
        .collect()
}

fn project_diagnostics(
    modules: &[ProgramFact],
    resolved: &[(String, usize)],
) -> Vec<ProgramDiagnostic> {
    let recognized = modules
        .iter()
        .filter(|fact| fact.kind == "recognized-toolchain-module")
        .map(|fact| fact.name.as_str())
        .collect::<std::collections::HashSet<_>>();
    modules
        .iter()
        .filter(|fact| {
            fact.kind == "module-import"
                && !recognized.contains(fact.name.as_str())
                && !resolved
                    .iter()
                    .any(|(name, start)| *name == fact.name && *start == fact.range.start)
        })
        .map(|fact| ProgramDiagnostic {
            kind: "missing-project-context",
            term: fact.name.clone(),
            range: fact.range,
        })
        .collect()
}

fn construct_facts(
    program: &ProgramRepresentation,
    context: &project::ProjectResult,
) -> Vec<ProgramConstruct> {
    SEMANTIC_CONSTRUCTS
        .iter()
        .map(|kind| {
            let mut evidence = construct_evidence(program, kind);
            evidence.extend(project::project_evidence(&program.project, context, kind));
            if evidence.is_empty() && *kind == "surface-expansion-elaboration-traces" {
                return ProgramConstruct {
                    kind,
                    status: ProgramConstructStatus::Unavailable,
                    evidence,
                    rationale: Some(
                        "no macro expansion or elaboration trace has been produced".to_string(),
                    ),
                };
            }
            if evidence.is_empty()
                && *kind == "proof-terms-and-tactics"
                && matches!(program.language, "JavaScript" | "Rust")
            {
                return ProgramConstruct {
                    kind,
                    status: ProgramConstructStatus::NotApplicable,
                    evidence,
                    rationale: Some(format!(
                        "{} defines no proof/tactic sublanguage",
                        program.language
                    )),
                };
            }
            let represented = !evidence.is_empty();
            ProgramConstruct {
                kind,
                status: if represented {
                    ProgramConstructStatus::Represented
                } else {
                    ProgramConstructStatus::NotPresent
                },
                evidence,
                rationale: (!represented).then(|| {
                    "the analyzed source contains no instance of this construct".to_string()
                }),
            }
        })
        .collect()
}

fn construct_evidence(program: &ProgramRepresentation, kind: &str) -> Vec<ProgramFact> {
    match kind {
        "modules-and-imports" => program.modules.clone(),
        "scopes-and-bindings" => program
            .bindings
            .iter()
            .map(|binding| ProgramFact::new(&binding.kind, &binding.name, binding.declaration))
            .collect(),
        "recursive-definitions" => program
            .bindings
            .iter()
            .filter(|binding| {
                matches!(
                    binding.kind.as_str(),
                    "function" | "Fixpoint" | "CoFixpoint" | "def"
                ) && !binding.references.is_empty()
            })
            .map(|binding| ProgramFact::new("recursive", &binding.name, binding.declaration))
            .collect(),
        "types-and-universes" => program.types.clone(),
        "effects" => effect_facts(program),
        "attributes" => program
            .extensions
            .iter()
            .filter(|fact| {
                let kind = fact.kind.to_ascii_lowercase();
                ["attribute", "directive", "allow", "local", "simp", "#"]
                    .iter()
                    .any(|needle| kind.contains(needle))
            })
            .cloned()
            .collect(),
        "macros-and-notation" => program
            .extensions
            .iter()
            .filter(|fact| {
                let kind = fact.kind.to_ascii_lowercase();
                [
                    "macro", "notation", "template", "tagged", "prefix", "postfix", "infix",
                    "syntax",
                ]
                .iter()
                .any(|needle| kind.contains(needle))
            })
            .cloned()
            .collect(),
        "proof-terms-and-tactics" => program.proofs.clone(),
        "project-context-and-dependencies" => program
            .project
            .files()
            .iter()
            .chain(program.project.dependencies())
            .map(|name| ProgramFact::new("project", name, ProgramRange::default()))
            .collect(),
        _ => Vec::new(),
    }
}

fn effect_facts(program: &ProgramRepresentation) -> Vec<ProgramFact> {
    let mut facts = Vec::new();
    for marker in effect_markers(program.language) {
        facts.extend(program.source.match_indices(marker).map(|(start, value)| {
            ProgramFact::new(
                "effect",
                value,
                ProgramRange::new(start, start + value.len()),
            )
        }));
    }
    unique_facts(facts)
}