meta-language 0.40.0

A self-describing links-network core for lossless language representation
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
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use crate::language_profile::LanguageProfile;
use crate::link_network::{Link, LinkId, LinkNetwork, LinkType};
use crate::query::{LinkQuery, QueryCaptures, QueryMatch, QueryPredicate, QueryPredicateHost};
use crate::source::{ByteRange, SourceSpan};
use crate::substitution::{SubstitutionReport, SubstitutionRule, VariableSubstitutionRule};

/// Replacement rule used by the query-and-transform surface.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReplacementRule {
    kind: ReplacementKind,
}

impl ReplacementRule {
    /// Replaces the source text covered by links captured under `capture_name`.
    ///
    /// Captured syntax links are rewritten by changing the token links inside
    /// the captured range, so all tokens outside the captured links keep their
    /// original text and order.
    #[must_use]
    pub fn captured_text(capture_name: impl Into<String>, replacement: impl Into<String>) -> Self {
        Self {
            kind: ReplacementKind::CapturedText {
                capture_name: normalize_capture_name(capture_name),
                replacement: replacement.into(),
            },
        }
    }

    /// Applies an exact-reference substitution via [`LinkNetwork::apply_substitution`].
    #[must_use]
    pub const fn substitution(rule: SubstitutionRule) -> Self {
        Self {
            kind: ReplacementKind::Substitution(rule),
        }
    }

    /// Applies a variable substitution via [`LinkNetwork::apply_variable_substitution`].
    #[must_use]
    pub const fn variable_substitution(rule: VariableSubstitutionRule) -> Self {
        Self {
            kind: ReplacementKind::VariableSubstitution(rule),
        }
    }

    /// Replaces captured source text with a quasiquote template.
    ///
    /// Placeholders use `{{capture_name}}` and are resolved from the same query
    /// match before each replacement is applied.
    #[must_use]
    pub fn quasiquote(capture_name: impl Into<String>, template: QuasiquoteTemplate) -> Self {
        Self {
            kind: ReplacementKind::Quasiquote {
                capture_name: normalize_capture_name(capture_name),
                template,
            },
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum ReplacementKind {
    CapturedText {
        capture_name: String,
        replacement: String,
    },
    Quasiquote {
        capture_name: String,
        template: QuasiquoteTemplate,
    },
    Substitution(SubstitutionRule),
    VariableSubstitution(VariableSubstitutionRule),
}

/// Result of replacing query-selected links.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ReplacementReport {
    text_replacements: Vec<TextReplacement>,
    template_errors: Vec<QuasiquoteError>,
    substitution: SubstitutionReport,
    profile_diagnostics: Vec<LinkId>,
}

impl ReplacementReport {
    pub(crate) const fn from_substitution(substitution: SubstitutionReport) -> Self {
        Self {
            text_replacements: Vec::new(),
            template_errors: Vec::new(),
            substitution,
            profile_diagnostics: Vec::new(),
        }
    }

    /// Source-text replacements made for captured links.
    #[must_use]
    pub fn text_replacements(&self) -> &[TextReplacement] {
        &self.text_replacements
    }

    /// Template rendering errors that prevented replacements.
    #[must_use]
    pub fn template_errors(&self) -> &[QuasiquoteError] {
        &self.template_errors
    }

    /// Structural substitution result, when the rule delegates to substitution.
    #[must_use]
    pub const fn substitution(&self) -> &SubstitutionReport {
        &self.substitution
    }

    /// Diagnostic links created when a language profile rejected a replacement.
    #[must_use]
    pub fn profile_diagnostics(&self) -> &[LinkId] {
        &self.profile_diagnostics
    }

    /// Returns whether the replacement made no text or structural changes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.text_replacements.is_empty()
            && self.template_errors.is_empty()
            && self.substitution.created().is_empty()
            && self.substitution.updated().is_empty()
            && self.substitution.deleted().is_empty()
            && self.profile_diagnostics.is_empty()
    }
}

/// One source-text replacement applied to captured token links.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextReplacement {
    capture_name: String,
    link_id: LinkId,
    token_ids: Vec<LinkId>,
    span: Option<SourceSpan>,
    old_text: String,
    new_text: String,
}

impl TextReplacement {
    fn new(
        capture_name: &str,
        link_id: LinkId,
        token_ids: Vec<LinkId>,
        span: Option<SourceSpan>,
        old_text: String,
        new_text: &str,
    ) -> Self {
        Self {
            capture_name: capture_name.to_string(),
            link_id,
            token_ids,
            span,
            old_text,
            new_text: new_text.to_string(),
        }
    }

    /// Capture name that produced this replacement.
    #[must_use]
    pub fn capture_name(&self) -> &str {
        &self.capture_name
    }

    /// Captured link whose source text was replaced.
    #[must_use]
    pub const fn link_id(&self) -> LinkId {
        self.link_id
    }

    /// Token links edited to perform the replacement.
    #[must_use]
    pub fn token_ids(&self) -> &[LinkId] {
        &self.token_ids
    }

    /// Source span covered by the edited tokens.
    #[must_use]
    pub const fn span(&self) -> Option<SourceSpan> {
        self.span
    }

    /// Source text reconstructed from the captured tokens before replacement.
    #[must_use]
    pub fn old_text(&self) -> &str {
        &self.old_text
    }

    /// Replacement text written into the captured range.
    #[must_use]
    pub fn new_text(&self) -> &str {
        &self.new_text
    }
}

/// Built-in predicate host for text predicates over query captures.
#[derive(Clone, Copy, Debug, Default)]
pub struct SourceTextPredicateHost;

impl QueryPredicateHost for SourceTextPredicateHost {
    fn evaluate(
        &self,
        predicate: &QueryPredicate,
        captures: &QueryCaptures,
        network: &LinkNetwork,
    ) -> bool {
        let Some((capture_name, literal)) = capture_literal_arguments(predicate) else {
            return false;
        };
        let Some(captured_text) = captured_text(network, captures.first(capture_name)) else {
            return false;
        };

        match predicate.name() {
            "eq?" => captured_text == literal,
            "not-eq?" => captured_text != literal,
            _ => false,
        }
    }
}

/// Quasiquote replacement template with `{{capture}}` placeholders.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QuasiquoteTemplate {
    parts: Vec<TemplatePart>,
}

impl QuasiquoteTemplate {
    /// Parses a template source string.
    pub fn parse(source: impl Into<String>) -> Result<Self, QuasiquoteError> {
        let source = source.into();
        let mut parts = Vec::new();
        let mut rest = source.as_str();
        while let Some(start) = rest.find("{{") {
            if start > 0 {
                parts.push(TemplatePart::Literal(rest[..start].to_string()));
            }
            let after_open = &rest[start + 2..];
            let Some(end) = after_open.find("}}") else {
                return Err(QuasiquoteError::Parse(
                    "unterminated quasiquote placeholder".to_string(),
                ));
            };
            let name = normalize_capture_name(after_open[..end].trim());
            if name.is_empty() {
                return Err(QuasiquoteError::Parse(
                    "quasiquote placeholder is empty".to_string(),
                ));
            }
            parts.push(TemplatePart::Placeholder(name));
            rest = &after_open[end + 2..];
        }
        if !rest.is_empty() {
            parts.push(TemplatePart::Literal(rest.to_string()));
        }
        if parts.is_empty() {
            parts.push(TemplatePart::Literal(source));
        }
        Ok(Self { parts })
    }

    fn render(
        &self,
        network: &LinkNetwork,
        query_match: &QueryMatch,
        old_text: &str,
    ) -> Result<String, QuasiquoteError> {
        let mut values = BTreeMap::<String, String>::new();
        for part in &self.parts {
            if let TemplatePart::Placeholder(name) = part {
                if values.contains_key(name) {
                    continue;
                }
                let Some(text) = captured_text(network, query_match.captures().first(name)) else {
                    return Err(QuasiquoteError::MissingPlaceholder(name.clone()));
                };
                values.insert(name.clone(), text);
            }
        }

        let mut rendered = String::new();
        for part in &self.parts {
            match part {
                TemplatePart::Literal(literal) => rendered.push_str(literal),
                TemplatePart::Placeholder(name) => {
                    let Some(value) = values.get(name) else {
                        return Err(QuasiquoteError::MissingPlaceholder(name.clone()));
                    };
                    rendered.push_str(value);
                }
            }
        }
        Ok(preserve_parentheses(old_text, rendered))
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum TemplatePart {
    Literal(String),
    Placeholder(String),
}

/// Error returned while parsing or rendering a quasiquote template.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum QuasiquoteError {
    /// Template source is malformed.
    Parse(String),
    /// Template references a capture that is not bound by the query match.
    MissingPlaceholder(String),
}

impl fmt::Display for QuasiquoteError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse(message) => formatter.write_str(message),
            Self::MissingPlaceholder(name) => {
                write!(formatter, "quasiquote placeholder `{name}` is not captured")
            }
        }
    }
}

impl std::error::Error for QuasiquoteError {}

impl LinkNetwork {
    /// Finds query matches using the transform surface's source-text predicates.
    ///
    /// This delegates structural matching to [`LinkQuery`]'s S-expression
    /// matcher. Built-in predicates such as `#eq? @capture "text"` compare the
    /// text reconstructed from captured token links.
    #[must_use]
    pub fn find(&self, query: &LinkQuery) -> Vec<QueryMatch> {
        self.query_matches_with(query, &SourceTextPredicateHost)
    }

    /// Applies a replacement rule to links selected by [`LinkNetwork::find`].
    pub fn replace(&mut self, matches: &[QueryMatch], rule: &ReplacementRule) -> ReplacementReport {
        match &rule.kind {
            ReplacementKind::CapturedText {
                capture_name,
                replacement,
            } => ReplacementReport {
                text_replacements: self.replace_captured_text(matches, capture_name, replacement),
                template_errors: Vec::new(),
                substitution: SubstitutionReport::default(),
                profile_diagnostics: Vec::new(),
            },
            ReplacementKind::Quasiquote {
                capture_name,
                template,
            } => {
                let (text_replacements, template_errors) =
                    self.replace_captured_quasiquote(matches, capture_name, template);
                ReplacementReport {
                    text_replacements,
                    template_errors,
                    substitution: SubstitutionReport::default(),
                    profile_diagnostics: Vec::new(),
                }
            }
            ReplacementKind::Substitution(rule) => {
                if matches.is_empty() {
                    ReplacementReport::default()
                } else {
                    ReplacementReport {
                        text_replacements: Vec::new(),
                        template_errors: Vec::new(),
                        substitution: self.apply_substitution(rule),
                        profile_diagnostics: Vec::new(),
                    }
                }
            }
            ReplacementKind::VariableSubstitution(rule) => {
                if matches.is_empty() {
                    ReplacementReport::default()
                } else {
                    ReplacementReport {
                        text_replacements: Vec::new(),
                        template_errors: Vec::new(),
                        substitution: self.apply_variable_substitution(rule),
                        profile_diagnostics: Vec::new(),
                    }
                }
            }
        }
    }

    /// Applies a replacement only when the result stays inside a language profile.
    ///
    /// The replacement is first evaluated on a cloned network. If the candidate
    /// network validates against the profile, it is committed to `self`. If the
    /// profile rejects it, `self` keeps its original source text and receives a
    /// queryable `language-profile:unsupported-feature` diagnostic link.
    pub fn replace_with_profile(
        &mut self,
        matches: &[QueryMatch],
        rule: &ReplacementRule,
        profile: &LanguageProfile,
    ) -> ReplacementReport {
        let mut candidate = self.clone();
        let report = candidate.replace(matches, rule);
        if report.is_empty() {
            return report;
        }

        match profile.validate_transform_result(&candidate) {
            Ok(()) => {
                *self = candidate;
                report
            }
            Err(violation) => {
                let diagnostic = profile.insert_diagnostic(
                    self,
                    &violation,
                    matches.first().map(QueryMatch::link_id),
                );
                ReplacementReport {
                    profile_diagnostics: vec![diagnostic],
                    ..ReplacementReport::default()
                }
            }
        }
    }

    fn replace_captured_text(
        &mut self,
        matches: &[QueryMatch],
        capture_name: &str,
        replacement: &str,
    ) -> Vec<TextReplacement> {
        let mut touched_tokens = BTreeSet::new();
        let mut replacements = Vec::new();

        for query_match in matches {
            for capture in query_match
                .captures()
                .iter()
                .filter(|capture| capture.name() == capture_name)
            {
                let token_ids = source_token_ids(self, capture.link_id());
                if token_ids.is_empty()
                    || token_ids
                        .iter()
                        .any(|token_id| touched_tokens.contains(token_id))
                {
                    continue;
                }

                let old_text = text_for_tokens(self, &token_ids);
                if old_text == replacement {
                    continue;
                }

                let span = span_for_tokens(self, &token_ids);
                let first_token = token_ids[0];
                if !self.set_term(first_token, replacement.to_string()) {
                    continue;
                }
                for token_id in token_ids.iter().skip(1) {
                    let _ = self.set_term(*token_id, String::new());
                }

                touched_tokens.extend(token_ids.iter().copied());
                replacements.push(TextReplacement::new(
                    capture_name,
                    capture.link_id(),
                    token_ids,
                    span,
                    old_text,
                    replacement,
                ));
            }
        }

        replacements
    }

    fn replace_captured_quasiquote(
        &mut self,
        matches: &[QueryMatch],
        capture_name: &str,
        template: &QuasiquoteTemplate,
    ) -> (Vec<TextReplacement>, Vec<QuasiquoteError>) {
        let mut touched_tokens = BTreeSet::new();
        let mut replacements = Vec::new();
        let mut errors = Vec::new();

        for query_match in matches {
            for capture in query_match
                .captures()
                .iter()
                .filter(|capture| capture.name() == capture_name)
            {
                let token_ids = source_token_ids(self, capture.link_id());
                if token_ids.is_empty()
                    || token_ids
                        .iter()
                        .any(|token_id| touched_tokens.contains(token_id))
                {
                    continue;
                }

                let old_text = text_for_tokens(self, &token_ids);
                let replacement = match template.render(self, query_match, &old_text) {
                    Ok(replacement) => replacement,
                    Err(error) => {
                        errors.push(error);
                        continue;
                    }
                };
                if old_text == replacement {
                    continue;
                }

                let span = span_for_tokens(self, &token_ids);
                let first_token = token_ids[0];
                if !self.set_term(first_token, replacement.clone()) {
                    continue;
                }
                for token_id in token_ids.iter().skip(1) {
                    let _ = self.set_term(*token_id, String::new());
                }

                touched_tokens.extend(token_ids.iter().copied());
                replacements.push(TextReplacement::new(
                    capture_name,
                    capture.link_id(),
                    token_ids,
                    span,
                    old_text,
                    &replacement,
                ));
            }
        }

        (replacements, errors)
    }
}

fn normalize_capture_name(name: impl Into<String>) -> String {
    name.into().trim_start_matches('@').to_string()
}

fn preserve_parentheses(old_text: &str, rendered: String) -> String {
    let trimmed_old = old_text.trim();
    let trimmed_rendered = rendered.trim();
    if trimmed_old.starts_with('(')
        && trimmed_old.ends_with(')')
        && !(trimmed_rendered.starts_with('(') && trimmed_rendered.ends_with(')'))
    {
        format!("({rendered})")
    } else {
        rendered
    }
}

fn capture_literal_arguments(predicate: &QueryPredicate) -> Option<(&str, &str)> {
    let [capture_argument, literal_argument] = predicate.arguments() else {
        return None;
    };
    Some((
        capture_argument.capture_name()?,
        literal_argument.literal()?,
    ))
}

fn captured_text(network: &LinkNetwork, link_id: Option<LinkId>) -> Option<String> {
    let link_id = link_id?;
    let token_ids = source_token_ids(network, link_id);
    if token_ids.is_empty() {
        network
            .link(link_id)
            .and_then(|link| link.metadata().term())
            .map(str::to_string)
    } else {
        Some(text_for_tokens(network, &token_ids))
    }
}

fn source_token_ids(network: &LinkNetwork, link_id: LinkId) -> Vec<LinkId> {
    let mut visited = BTreeSet::new();
    let mut token_ids = Vec::new();
    collect_source_tokens(network, link_id, &mut visited, &mut token_ids);
    token_ids.sort_by_key(|token_id| token_sort_key(network, *token_id));
    token_ids.dedup();
    token_ids
}

fn collect_source_tokens(
    network: &LinkNetwork,
    link_id: LinkId,
    visited: &mut BTreeSet<LinkId>,
    token_ids: &mut Vec<LinkId>,
) {
    if !visited.insert(link_id) {
        return;
    }
    let Some(link) = network.link(link_id) else {
        return;
    };

    match link.metadata().link_type() {
        Some(LinkType::Token) => {
            if !link.metadata().flags().is_missing() {
                token_ids.push(link_id);
            }
            return;
        }
        Some(LinkType::Field | LinkType::Trivia) => return,
        _ => {}
    }

    let children = network
        .links()
        .filter(|candidate| candidate.references().first().copied() == Some(link_id))
        .map(Link::id)
        .collect::<Vec<_>>();
    for child in children {
        collect_source_tokens(network, child, visited, token_ids);
    }
}

fn token_sort_key(network: &LinkNetwork, token_id: LinkId) -> (usize, u64) {
    let start = network
        .link(token_id)
        .and_then(|link| link.metadata().span())
        .map_or(usize::MAX, |span| span.byte_range().start());
    (start, token_id.as_u64())
}

fn text_for_tokens(network: &LinkNetwork, token_ids: &[LinkId]) -> String {
    token_ids
        .iter()
        .filter_map(|token_id| network.link(*token_id))
        .filter_map(|link| link.metadata().term())
        .collect()
}

fn span_for_tokens(network: &LinkNetwork, token_ids: &[LinkId]) -> Option<SourceSpan> {
    let spans = token_ids
        .iter()
        .filter_map(|token_id| network.link(*token_id))
        .filter_map(|link| link.metadata().span())
        .collect::<Vec<_>>();
    let first = spans.first()?;
    let last = spans.last()?;
    Some(SourceSpan::new(
        ByteRange::new(first.byte_range().start(), last.byte_range().end()),
        first.start_point(),
        last.end_point(),
    ))
}