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
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;

use crate::{LinkId, LinkMetadata, LinkNetwork, LinkType, ParseConfiguration, TranslationRuleSet};

const PROFILE_TERM: &str = "language-profile";
const PROFILE_LINK_TYPE_TERM: &str = "language-profile:link-type";
const PROFILE_CONCEPT_TERM: &str = "language-profile:concept";
const PROFILE_TRANSLATION_RULE_TERM: &str = "language-profile:translation-rule";
const PROFILE_DIAGNOSTIC_TERM: &str = "language-profile:unsupported-feature";

/// Per-language capability profile for restricting transforms to supported features.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageProfile {
    name: String,
    language: String,
    link_types: BTreeSet<LinkType>,
    concepts: BTreeSet<String>,
    translation_rules: BTreeSet<String>,
}

impl LanguageProfile {
    /// Creates an empty profile for a target language.
    #[must_use]
    pub fn new(name: impl Into<String>, language: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            language: language.into(),
            link_types: BTreeSet::new(),
            concepts: BTreeSet::new(),
            translation_rules: BTreeSet::new(),
        }
    }

    /// Built-in JavaScript same-language profile.
    #[must_use]
    pub fn javascript() -> Self {
        let mut profile = Self::new("JavaScript", "JavaScript");
        for link_type in [
            LinkType::Link,
            LinkType::Reference,
            LinkType::Relation,
            LinkType::Language,
            LinkType::Grammar,
            LinkType::Type,
            LinkType::Concept,
            LinkType::Syntax,
            LinkType::Field,
            LinkType::Trivia,
            LinkType::Token,
            LinkType::Document,
            LinkType::Semantic,
            LinkType::Region,
            LinkType::Object,
        ] {
            profile = profile.with_link_type(link_type);
        }
        profile
    }

    /// Looks up a built-in profile by name.
    #[must_use]
    pub fn builtin(name: &str) -> Option<Self> {
        match name.to_ascii_lowercase().as_str() {
            "javascript" | "js" => Some(Self::javascript()),
            _ => None,
        }
    }

    /// Computes a profile domain from a translation rule set.
    ///
    /// Rule query link-type filters become supported link types, query term
    /// filters become supported concept/feature terms, and every rule name is
    /// recorded as a supported translation rule.
    #[must_use]
    pub fn from_rule_set(
        name: impl Into<String>,
        language: impl Into<String>,
        rule_set: &TranslationRuleSet,
    ) -> Self {
        let mut profile = Self::new(name, language);
        for rule in rule_set.rules() {
            profile = profile.with_translation_rule(rule.name());
            if let Some(link_type) = rule.query().link_type_filter() {
                profile = profile.with_link_type(link_type);
            }
            if let Some(term) = rule.query().term_filter() {
                profile = profile.with_concept(term);
            }
        }
        profile
    }

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

    /// Target language this profile constrains.
    #[must_use]
    pub fn language(&self) -> &str {
        &self.language
    }

    /// Supported link types.
    #[must_use]
    pub const fn link_types(&self) -> &BTreeSet<LinkType> {
        &self.link_types
    }

    /// Supported concept or feature terms.
    #[must_use]
    pub const fn concepts(&self) -> &BTreeSet<String> {
        &self.concepts
    }

    /// Supported translation rule names.
    #[must_use]
    pub const fn translation_rules(&self) -> &BTreeSet<String> {
        &self.translation_rules
    }

    /// Returns a copy with a supported link type.
    #[must_use]
    pub fn with_link_type(mut self, link_type: LinkType) -> Self {
        self.link_types.insert(link_type);
        self
    }

    /// Returns a copy with a supported concept or feature term.
    #[must_use]
    pub fn with_concept(mut self, concept: impl Into<String>) -> Self {
        self.concepts.insert(concept.into());
        self
    }

    /// Returns a copy with a supported translation rule name.
    #[must_use]
    pub fn with_translation_rule(mut self, rule: impl Into<String>) -> Self {
        self.translation_rules.insert(rule.into());
        self
    }

    /// Whether this profile supports a link type.
    #[must_use]
    pub fn supports_link_type(&self, link_type: LinkType) -> bool {
        self.link_types.contains(&link_type)
    }

    /// Whether this profile supports a concept or feature term.
    #[must_use]
    pub fn supports_concept(&self, concept: &str) -> bool {
        self.concepts.contains(concept)
    }

    /// Whether this profile supports a translation rule name.
    #[must_use]
    pub fn supports_translation_rule(&self, rule: &str) -> bool {
        self.translation_rules.contains(rule)
    }

    /// Declares this profile as queryable links inside a network.
    pub fn declare_in(&self, network: &mut LinkNetwork) -> LanguageProfileLinks {
        let profile = self.profile_link(network).unwrap_or_else(|| {
            network.insert_link(
                [],
                LinkMetadata::new()
                    .with_link_type(LinkType::Semantic)
                    .with_named(true)
                    .with_term(PROFILE_TERM)
                    .with_language(&self.language)
                    .with_definition(&self.name),
            )
        });
        let mut capabilities = Vec::new();

        for link_type in &self.link_types {
            capabilities.push(self.ensure_capability_link(
                network,
                profile,
                PROFILE_LINK_TYPE_TERM,
                &link_type.to_string(),
            ));
        }
        for concept in &self.concepts {
            capabilities.push(self.ensure_capability_link(
                network,
                profile,
                PROFILE_CONCEPT_TERM,
                concept,
            ));
        }
        for rule in &self.translation_rules {
            capabilities.push(self.ensure_capability_link(
                network,
                profile,
                PROFILE_TRANSLATION_RULE_TERM,
                rule,
            ));
        }

        LanguageProfileLinks {
            profile,
            capabilities,
        }
    }

    /// Validates that all typed links in a network stay inside this profile.
    ///
    /// # Errors
    ///
    /// Returns [`LanguageProfileViolation`] for the first unsupported link
    /// type found in identifier order.
    pub fn validate_network(&self, network: &LinkNetwork) -> Result<(), LanguageProfileViolation> {
        for link in network.links() {
            if let Some(link_type) = link.metadata().link_type() {
                if !self.supports_link_type(link_type) {
                    return Err(LanguageProfileViolation::new(
                        format!("link type `{link_type}`"),
                        format!(
                            "Profile `{}` for `{}` does not support link type `{link_type}`.",
                            self.name, self.language
                        ),
                    ));
                }
            }

            if self.concepts.is_empty()
                || !matches!(
                    link.metadata().link_type(),
                    Some(LinkType::Concept | LinkType::Semantic)
                )
            {
                continue;
            }
            let Some(term) = link.metadata().term() else {
                continue;
            };
            if is_profile_control_term(term) || self.supports_concept(term) {
                continue;
            }
            return Err(LanguageProfileViolation::new(
                format!("concept `{term}`"),
                format!(
                    "Profile `{}` for `{}` does not support concept `{term}`.",
                    self.name, self.language
                ),
            ));
        }
        Ok(())
    }

    pub(crate) fn validate_transform_result(
        &self,
        network: &LinkNetwork,
    ) -> Result<(), LanguageProfileViolation> {
        self.validate_network(network)?;

        let source = network.reconstruct_text();
        if source.is_empty() {
            return Ok(());
        }

        let parsed = LinkNetwork::parse(&source, &self.language, ParseConfiguration::default());
        let report = parsed.verify_full_match(None);
        if report.issues().is_empty() {
            Ok(())
        } else {
            Err(LanguageProfileViolation::new(
                format!("{} syntax", self.language),
                format!(
                    "Profile `{}` for `{}` rejects source text that is not valid {}.",
                    self.name, self.language, self.language
                ),
            ))
        }
    }

    pub(crate) fn insert_diagnostic(
        &self,
        network: &mut LinkNetwork,
        violation: &LanguageProfileViolation,
        subject: Option<LinkId>,
    ) -> LinkId {
        let profile = self.declare_in(network).profile();
        let metadata = LinkMetadata::new()
            .with_link_type(LinkType::Semantic)
            .with_named(true)
            .with_term(PROFILE_DIAGNOSTIC_TERM)
            .with_language(&self.language)
            .with_definition(violation.to_string());

        match subject {
            Some(subject) => network.insert_link([profile, subject], metadata),
            None => network.insert_link([profile], metadata),
        }
    }

    fn profile_link(&self, network: &LinkNetwork) -> Option<LinkId> {
        network
            .links()
            .find(|link| {
                link.metadata().link_type() == Some(LinkType::Semantic)
                    && link.metadata().term() == Some(PROFILE_TERM)
                    && link.metadata().language() == Some(self.language())
                    && link.metadata().definition() == Some(self.name())
            })
            .map(crate::Link::id)
    }

    fn ensure_capability_link(
        &self,
        network: &mut LinkNetwork,
        profile: LinkId,
        term: &str,
        definition: &str,
    ) -> LinkId {
        if let Some(existing) = network
            .links()
            .find(|link| {
                link.references() == [profile]
                    && link.metadata().link_type() == Some(LinkType::Semantic)
                    && link.metadata().term() == Some(term)
                    && link.metadata().language() == Some(self.language())
                    && link.metadata().definition() == Some(definition)
            })
            .map(crate::Link::id)
        {
            return existing;
        }

        network.insert_link(
            [profile],
            LinkMetadata::new()
                .with_link_type(LinkType::Semantic)
                .with_named(true)
                .with_term(term)
                .with_language(&self.language)
                .with_definition(definition),
        )
    }
}

/// Links inserted when a language profile is declared in a network.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageProfileLinks {
    profile: LinkId,
    capabilities: Vec<LinkId>,
}

impl LanguageProfileLinks {
    /// Root profile link.
    #[must_use]
    pub const fn profile(&self) -> LinkId {
        self.profile
    }

    /// Capability child links.
    #[must_use]
    pub fn capabilities(&self) -> &[LinkId] {
        &self.capabilities
    }
}

/// A profile validation failure that can be recorded as a diagnostic link.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageProfileViolation {
    feature: String,
    message: String,
}

impl LanguageProfileViolation {
    fn new(feature: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            feature: feature.into(),
            message: message.into(),
        }
    }

    /// Unsupported feature that caused the violation.
    #[must_use]
    pub fn feature(&self) -> &str {
        &self.feature
    }
}

impl fmt::Display for LanguageProfileViolation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} Unsupported feature: {}.",
            self.message, self.feature
        )
    }
}

impl Error for LanguageProfileViolation {}

fn is_profile_control_term(term: &str) -> bool {
    term.starts_with("language-profile")
        || term.starts_with("translation-rule:")
        || term == "translation-rule"
        || term == "translation-rule-set"
}