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
//! The public four-language translator: semantic translations of portable-core programs, and
//! reversible target-native source envelopes for every other program.

use std::error::Error;
use std::fmt;

use crate::semantic_translation::{
    self, ReadTranslationProvenance, SEMANTIC_ENCODING, SEMANTIC_OBSERVATION, SemanticTranslation,
    TranslationDiagnostic,
};
use crate::{TranslationContract, TranslationSupport, language_support, translation_contract};

const ENVELOPE_MARKER: &str = "meta-language:portable-source-envelope:v1";

/// A target-language artifact: a semantic translation or a reversible source envelope.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramTranslation {
    source_language: &'static str,
    target_language: &'static str,
    code: String,
    contract: TranslationContract,
    semantics: Option<SemanticTranslation>,
    diagnostic: Option<TranslationDiagnostic>,
}

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

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

    /// Valid target-language source: the translated program or the portable envelope.
    #[must_use]
    pub fn code(&self) -> &str {
        &self.code
    }

    /// Preservation contract applied by this translation.
    #[must_use]
    pub const fn contract(&self) -> &TranslationContract {
        &self.contract
    }

    /// Encodings, assumptions, obligations, mappings and provenance of a semantic translation.
    #[must_use]
    pub const fn semantics(&self) -> Option<&SemanticTranslation> {
        self.semantics.as_ref()
    }

    /// Why the program stayed outside the portable core, for an envelope.
    #[must_use]
    pub const fn diagnostic(&self) -> Option<&TranslationDiagnostic> {
        self.diagnostic.as_ref()
    }
}

/// Exact source program recovered from a portable target artifact.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DecodedProgramTranslation {
    source_language: &'static str,
    source: String,
}

impl DecodedProgramTranslation {
    /// Canonical language of the recovered source.
    #[must_use]
    pub const fn source_language(&self) -> &'static str {
        self.source_language
    }

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

/// Portable translation failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProgramTranslationError {
    /// Source or target is outside the registered four-language surface.
    UnsupportedLanguage(String),
    /// Translation must be directed between distinct languages.
    SameLanguage(String),
    /// The artifact does not contain a valid envelope for the declared target.
    InvalidEnvelope(String),
    /// The artifact does not start with a valid provenance comment for the declared target.
    InvalidProvenance(String),
}

impl fmt::Display for ProgramTranslationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedLanguage(language) => {
                write!(
                    formatter,
                    "no four-language translation frontend for {language}"
                )
            }
            Self::SameLanguage(language) => {
                write!(
                    formatter,
                    "{language} uses ordinary source emission, not translation"
                )
            }
            Self::InvalidEnvelope(reason) => {
                write!(formatter, "invalid portable envelope: {reason}")
            }
            Self::InvalidProvenance(reason) => {
                write!(formatter, "invalid translation provenance: {reason}")
            }
        }
    }
}

impl Error for ProgramTranslationError {}

/// Translates a program between JavaScript, Rust, Lean and Rocq.
///
/// Programs in the portable core are parsed, type-checked and emitted as native target programs
/// that print the same lines and restate the same theorems; [`ProgramTranslation::semantics`]
/// records the encodings, assumptions, proof obligations, source mappings and provenance of that
/// translation. Other programs are carried in a reversible source envelope, whose
/// [`ProgramTranslation::diagnostic`] names the construct that kept them out of the portable core;
/// the envelope never relabels the original text as target-language syntax.
pub fn translate_program(
    source: &str,
    source_language: &str,
    target_language: &str,
) -> Result<ProgramTranslation, ProgramTranslationError> {
    let source_support = language_support(source_language)
        .ok_or_else(|| ProgramTranslationError::UnsupportedLanguage(source_language.to_string()))?;
    let target_support = language_support(target_language)
        .ok_or_else(|| ProgramTranslationError::UnsupportedLanguage(target_language.to_string()))?;
    let mut contract = translation_contract(source_support.name, target_support.name)
        .ok_or_else(|| ProgramTranslationError::SameLanguage(source_support.name.to_string()))?;
    let diagnostic =
        match semantic_translation::emit(source, source_support.name, target_support.name) {
            Ok(emitted) => {
                let (code, semantics) = semantic_translation::record(
                    source,
                    source_support.name,
                    target_support.name,
                    emitted,
                );
                contract.support = TranslationSupport::SemanticTranslation;
                contract.observation = SEMANTIC_OBSERVATION;
                contract.encoding = SEMANTIC_ENCODING;
                contract.assumptions =
                    semantic_translation::assumption_statements(&semantics.assumptions);
                contract.obligation = None;
                return Ok(ProgramTranslation {
                    source_language: source_support.name,
                    target_language: target_support.name,
                    code,
                    contract,
                    semantics: Some(semantics),
                    diagnostic: None,
                });
            }
            Err(diagnostic) => diagnostic,
        };
    let payload = hex_encode(source.as_bytes());
    let metadata = format!(
        "{ENVELOPE_MARKER}:{}:{}:{payload}",
        source_support.name,
        source.len()
    );
    let (code, observation) =
        target_source(target_support.name, &metadata, source_support.name, source);
    if let Some(observation) = observation {
        contract.support = TranslationSupport::SemanticSubset;
        contract.observation = observation;
        contract.encoding =
            "direct executable target source with a reversible source provenance envelope";
        contract.assumptions = &[];
        contract.obligation = None;
    }
    Ok(ProgramTranslation {
        source_language: source_support.name,
        target_language: target_support.name,
        code,
        contract,
        semantics: None,
        diagnostic: Some(diagnostic),
    })
}

/// Reads the provenance comment a semantic translation starts with.
pub fn read_translation_provenance(
    code: &str,
    target_language: &str,
) -> Result<ReadTranslationProvenance, ProgramTranslationError> {
    let target = language_support(target_language)
        .ok_or_else(|| ProgramTranslationError::UnsupportedLanguage(target_language.to_string()))?;
    semantic_translation::read_provenance(code, target.name)
        .map_err(ProgramTranslationError::InvalidProvenance)
}

/// Decodes and integrity-checks a portable source envelope from target source.
pub fn decode_program_translation(
    code: &str,
    target_language: &str,
) -> Result<DecodedProgramTranslation, ProgramTranslationError> {
    let target = language_support(target_language)
        .ok_or_else(|| ProgramTranslationError::UnsupportedLanguage(target_language.to_string()))?;
    let metadata = envelope_metadata(code, target.name)?;
    let fields = metadata.splitn(3, ':').collect::<Vec<_>>();
    if fields.len() != 3 {
        return Err(ProgramTranslationError::InvalidEnvelope(
            "expected source language, byte length, and hexadecimal payload".to_string(),
        ));
    }
    let source_support = language_support(fields[0]).ok_or_else(|| {
        ProgramTranslationError::InvalidEnvelope(format!("unknown source language {}", fields[0]))
    })?;
    let expected_len = fields[1].parse::<usize>().map_err(|_| {
        ProgramTranslationError::InvalidEnvelope("byte length is not an integer".to_string())
    })?;
    let bytes = hex_decode(fields[2])?;
    if bytes.len() != expected_len {
        return Err(ProgramTranslationError::InvalidEnvelope(format!(
            "declared {expected_len} bytes but decoded {}",
            bytes.len()
        )));
    }
    let source = String::from_utf8(bytes).map_err(|_| {
        ProgramTranslationError::InvalidEnvelope("payload is not UTF-8 source".to_string())
    })?;
    Ok(DecodedProgramTranslation {
        source_language: source_support.name,
        source,
    })
}

fn target_source(
    language: &str,
    metadata: &str,
    source_language: &str,
    source: &str,
) -> (String, Option<&'static str>) {
    match language {
        "JavaScript" => {
            if source_language == "Rust"
                && let Some((name, value)) = rust_constant_function(source)
            {
                return (
                    format!("/*{metadata}*/\nexport function {name}() {{ return {value}; }}\n"),
                    Some("calling the exported zero-argument function returns the same integer"),
                );
            }
            (
                format!(
                    "/*{metadata}*/\nexport const __meta_language_portable_v1 = Object.freeze({{ schemaVersion: 1 }});\n"
                ),
                None,
            )
        }
        "Rust" => {
            if source_language == "JavaScript"
                && let Some(value) = javascript_print_number(source)
            {
                return (
                    format!("/*{metadata}*/\npub fn main() {{ println!(\"{value}\"); }}\n"),
                    Some(
                        "running the target main function prints the same decimal value and newline",
                    ),
                );
            }
            (
                format!("/*{metadata}*/\npub const __META_LANGUAGE_PORTABLE_V1: u32 = 1;\n"),
                None,
            )
        }
        "Lean" => (
            format!("/-{metadata}-/\ndef __meta_language_portable_v1 : Nat := 1\n"),
            None,
        ),
        "Rocq" => (
            format!("(*{metadata}*)\nDefinition __meta_language_portable_v1 : nat := 1.\n"),
            None,
        ),
        _ => unreachable!("target was resolved by language_support"),
    }
}

fn rust_constant_function(source: &str) -> Option<(&str, &str)> {
    let body = source.strip_prefix("pub fn ")?;
    let (name, rest) = body.split_once("() -> u32 { ")?;
    let value = rest.strip_suffix(" }")?;
    let mut characters = name.bytes();
    if !matches!(characters.next()?, b'A'..=b'Z' | b'a'..=b'z' | b'_')
        || !characters.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
        || matches!(
            name,
            "break"
                | "case"
                | "catch"
                | "class"
                | "const"
                | "continue"
                | "debugger"
                | "default"
                | "delete"
                | "do"
                | "else"
                | "enum"
                | "export"
                | "extends"
                | "false"
                | "finally"
                | "for"
                | "function"
                | "if"
                | "import"
                | "in"
                | "instanceof"
                | "new"
                | "null"
                | "return"
                | "super"
                | "switch"
                | "this"
                | "throw"
                | "true"
                | "try"
                | "typeof"
                | "var"
                | "void"
                | "while"
                | "with"
                | "yield"
                | "await"
                | "let"
                | "static"
                | "implements"
                | "interface"
                | "package"
                | "private"
                | "protected"
                | "public"
                | "arguments"
                | "eval"
        )
        || value.is_empty()
        || (value.len() > 1 && value.starts_with('0'))
        || !value.bytes().all(|byte| byte.is_ascii_digit())
        || value.parse::<u64>().ok()? > u64::from(u32::MAX)
    {
        return None;
    }
    Some((name, value))
}

fn javascript_print_number(source: &str) -> Option<&str> {
    let value = source.strip_prefix("console.log(")?.strip_suffix(");")?;
    (!(value.is_empty() || value.len() > 1 && value.starts_with('0'))
        && value.bytes().all(|byte| byte.is_ascii_digit())
        && value.parse::<u64>().ok()? <= 9_007_199_254_740_991)
        .then_some(value)
}

fn envelope_metadata<'a>(
    code: &'a str,
    target_language: &str,
) -> Result<&'a str, ProgramTranslationError> {
    let (open, close) = match target_language {
        "Lean" => ("/-", "-/"),
        "Rocq" => ("(*", "*)"),
        _ => ("/*", "*/"),
    };
    let body = code
        .strip_prefix(open)
        .and_then(|value| value.split_once(close).map(|(metadata, _)| metadata))
        .ok_or_else(|| {
            ProgramTranslationError::InvalidEnvelope(format!(
                "missing {target_language} envelope comment"
            ))
        })?;
    body.strip_prefix(ENVELOPE_MARKER)
        .and_then(|value| value.strip_prefix(':'))
        .ok_or_else(|| {
            ProgramTranslationError::InvalidEnvelope("missing schema marker".to_string())
        })
}

fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    encoded
}

fn hex_decode(encoded: &str) -> Result<Vec<u8>, ProgramTranslationError> {
    if !encoded.len().is_multiple_of(2) {
        return Err(ProgramTranslationError::InvalidEnvelope(
            "hexadecimal payload has odd length".to_string(),
        ));
    }
    encoded
        .as_bytes()
        .as_chunks::<2>()
        .0
        .iter()
        .map(|pair| {
            let high = hex_digit(pair[0])?;
            let low = hex_digit(pair[1])?;
            Ok((high << 4) | low)
        })
        .collect()
}

fn hex_digit(byte: u8) -> Result<u8, ProgramTranslationError> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        _ => Err(ProgramTranslationError::InvalidEnvelope(
            "payload contains a non-hexadecimal byte".to_string(),
        )),
    }
}