Skip to main content

meta_language/
semantic_translation.rs

1//! Semantic translations produced by the portable-core translator.
2//!
3//! A program in the portable core is parsed, type-checked and emitted as a native target program
4//! that prints the same lines and restates the same theorems. [`SemanticTranslation`] records what
5//! that translation relied on: its encodings, assumptions, proof obligations, source mappings,
6//! runtime dependencies and provenance.
7//!
8//! Mirrors the semantic half of `js/src/program-translation.js`.
9
10use sha2::{Digest, Sha256};
11
12use crate::translation::check::check_program;
13use crate::translation::diagnostics::TranslationError;
14use crate::translation::emit_common::{Assumption, Emitted, Encoding, IN_BOUNDS_READS, Mapping};
15use crate::translation::{
16    Span,
17    emit_javascript::emit_javascript,
18    emit_lean::emit_lean,
19    emit_rocq::emit_rocq,
20    emit_rust::{RustEmissionOptions, emit_rust_with_array_consumption},
21    javascript::parse_javascript,
22    lean::parse_lean,
23    rocq::parse_rocq,
24    rust::parse_rust,
25};
26
27const PROVENANCE_MARKER: &str = "meta-language:translation-provenance:v1";
28const TRANSLATOR: &str = "meta-language portable-core translator";
29
30/// What a semantic translation preserves: the printed lines and every stated proposition.
31pub const SEMANTIC_OBSERVATION: &str = "the lines main prints, in order, on executions that do not abort, and the proposition of every source theorem and assertion over the translated definitions";
32
33/// The contract encoding of a semantic translation.
34pub const SEMANTIC_ENCODING: &str =
35    "portable-core translation; the encodings it chose are listed in semantics.encodings";
36
37/// How a proof obligation of the source is met in the target.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct TranslationObligation {
40    /// Source theorem, or `main:assert@<offset>` for an assertion.
41    pub source: String,
42    /// Target declaration that states it.
43    pub target: String,
44    /// `theorem` or `assertion`.
45    pub kind: String,
46    /// Whether the statement has no free variables.
47    pub closed_goal: bool,
48    /// `target-kernel`, `source-kernel` or `runtime-assertion`.
49    pub discharge: String,
50    /// The target-side check of a source-kernel proof (`bounded`).
51    pub check: Option<String>,
52}
53
54/// Where a semantic translation came from.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct TranslationProvenance {
57    /// The translator that produced the artifact.
58    pub translator: &'static str,
59    /// Canonical source language.
60    pub source_language: &'static str,
61    /// Lowercase hexadecimal SHA-256 of the UTF-8 source.
62    pub source_sha256: String,
63    /// Source length in bytes.
64    pub source_bytes: usize,
65    /// The comment the artifact starts with.
66    pub header: String,
67}
68
69/// The record of one semantic translation.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct SemanticTranslation {
72    /// The target's entry point, when the source has a main program.
73    pub entry: Option<String>,
74    /// How the target's observations are made.
75    pub observation_procedure: &'static str,
76    /// Representation choices for constructs without a direct target equivalent.
77    pub encodings: Vec<Encoding>,
78    /// Assumptions, with the program-specific details.
79    pub assumptions: Vec<Assumption>,
80    /// Source theorems and assertions and how the target discharges them.
81    pub obligations: Vec<TranslationObligation>,
82    /// Where each source declaration went, with its source span in UTF-16 code units.
83    pub mappings: Vec<Mapping>,
84    /// Libraries and host features the emitted program needs.
85    pub runtime_dependencies: Vec<String>,
86    /// Where the translation came from.
87    pub provenance: TranslationProvenance,
88}
89
90/// Why a program stayed outside the portable core.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct TranslationDiagnostic {
93    /// `syntax`, `type` or `unsupported`.
94    pub kind: &'static str,
95    /// The message with its span suffix.
96    pub message: String,
97    /// The source range, in UTF-16 code units.
98    pub span: Option<Span>,
99}
100
101/// Provenance recovered from an artifact's first line.
102#[derive(Clone, Debug, PartialEq, Eq)]
103pub struct ReadTranslationProvenance {
104    /// Canonical source language.
105    pub source_language: &'static str,
106    /// Lowercase hexadecimal SHA-256 of the UTF-8 source.
107    pub source_sha256: String,
108    /// Source length in bytes.
109    pub source_bytes: usize,
110}
111
112/// Runs the portable-core pipeline for canonical language names.
113pub fn emit(
114    source: &str,
115    source_language: &str,
116    target_language: &str,
117) -> Result<Emitted, TranslationDiagnostic> {
118    let surface = match source_language {
119        "JavaScript" => parse_javascript(source),
120        "Rust" => parse_rust(source),
121        "Lean" => parse_lean(source),
122        _ => parse_rocq(source),
123    };
124    let emitted = surface
125        .and_then(|surface| check_program(&surface))
126        .and_then(|program| match target_language {
127            "JavaScript" => emit_javascript(&program),
128            "Rust" => emit_rust_with_array_consumption(&program, RustEmissionOptions::default()),
129            "Lean" => emit_lean(&program),
130            _ => emit_rocq(&program),
131        });
132    emitted.map_err(|error: TranslationError| TranslationDiagnostic {
133        kind: error.kind.as_str(),
134        message: error.message(),
135        span: error.span,
136    })
137}
138
139const fn comment(target_language: &str) -> (&'static str, &'static str) {
140    match target_language.as_bytes() {
141        b"Lean" => ("-- ", ""),
142        b"Rocq" => ("(* ", " *)"),
143        _ => ("// ", ""),
144    }
145}
146
147/// The artifact text and its semantic record.
148pub fn record(
149    source: &str,
150    source_language: &'static str,
151    target_language: &str,
152    emitted: Emitted,
153) -> (String, SemanticTranslation) {
154    let source_sha256 = Sha256::digest(source.as_bytes()).iter().fold(
155        String::with_capacity(64),
156        |mut hex, byte| {
157            use std::fmt::Write as _;
158            let _ = write!(hex, "{byte:02x}");
159            hex
160        },
161    );
162    let (open, close) = comment(target_language);
163    let header = format!(
164        "{open}{PROVENANCE_MARKER} source={source_language} sha256={source_sha256} bytes={}{close}",
165        source.len()
166    );
167    let kernel_target = matches!(target_language, "Lean" | "Rocq");
168    let obligations = emitted
169        .theorems
170        .into_iter()
171        .map(|theorem| TranslationObligation {
172            source: theorem.source,
173            target: theorem.target,
174            kind: theorem.kind,
175            closed_goal: theorem.closed_goal,
176            discharge: theorem.discharge.unwrap_or_else(|| {
177                if kernel_target {
178                    "target-kernel"
179                } else {
180                    "runtime-assertion"
181                }
182                .to_owned()
183            }),
184            check: theorem.check,
185        })
186        .collect();
187    let semantics = SemanticTranslation {
188        entry: emitted.entry,
189        observation_procedure: observation_procedure(target_language),
190        encodings: emitted.encodings,
191        assumptions: emitted.assumptions,
192        obligations,
193        mappings: emitted.mappings,
194        runtime_dependencies: runtime_dependencies(target_language, &emitted.text),
195        provenance: TranslationProvenance {
196            translator: TRANSLATOR,
197            source_language,
198            source_sha256,
199            source_bytes: source.len(),
200            header: header.clone(),
201        },
202    };
203    (format!("{header}\n{}", emitted.text), semantics)
204}
205
206/// The fixed assumption statements a contract lists for these assumptions, in their order.
207pub fn assumption_statements(assumptions: &[Assumption]) -> &'static [&'static str] {
208    const NONE: &[&str] = &[];
209    const READS: &[&str] = &[IN_BOUNDS_READS.statement];
210    let ids: Vec<&str> = assumptions
211        .iter()
212        .map(|assumption| assumption.id.as_str())
213        .collect();
214    match ids.as_slice() {
215        [] => NONE,
216        [first] if *first == IN_BOUNDS_READS.id => READS,
217        _ => unreachable!("unknown assumptions {ids:?}"),
218    }
219}
220
221const fn observation_procedure(target_language: &str) -> &'static str {
222    match target_language.as_bytes() {
223        b"JavaScript" => {
224            "run the module with node; --ml-check-theorems evaluates the theorem properties instead of main"
225        }
226        b"Rust" => {
227            "compile with rustc and run the binary; --ml-check-theorems evaluates the theorem properties instead of main"
228        }
229        b"Lean" => {
230            "lean --run executes main after the Lean kernel has checked every definition and theorem"
231        }
232        _ => {
233            "rocq compile checks every definition and proof; Eval vm_compute in main prints the list of output lines"
234        }
235    }
236}
237
238/// The libraries and host features the emitted program needs, read from its text.
239fn runtime_dependencies(target_language: &str, code: &str) -> Vec<String> {
240    let mut dependencies = Vec::new();
241    match target_language {
242        "JavaScript" => {
243            dependencies.push("ECMAScript 2026 host with BigInt".to_owned());
244            if code.contains("process.argv") {
245                dependencies.push("Node.js process.argv (selects --ml-check-theorems)".to_owned());
246            }
247        }
248        "Rust" => {
249            dependencies.push("Rust 1.99.0 standard library".to_owned());
250            if code.contains("\npub mod ml {") {
251                dependencies.push(
252                    "ml::Big arbitrary-precision integers, defined inside the artifact".to_owned(),
253                );
254            }
255            if code.contains("\npub mod ml_number {") {
256                dependencies.push(
257                    "ml_number JavaScript Number formatting and SameValue, defined inside the artifact"
258                        .to_owned(),
259                );
260            }
261        }
262        "Lean" => {
263            dependencies.push("Lean 4.34.1 core library".to_owned());
264            dependencies.extend(
265                code.lines()
266                    .filter_map(|line| line.strip_prefix("import "))
267                    .map(|module| module.trim().to_owned()),
268            );
269        }
270        _ => {
271            dependencies.push("Rocq 9.3".to_owned());
272            for line in code.lines() {
273                let Some(rest) = line.strip_prefix("From ") else {
274                    continue;
275                };
276                let Some((library, modules)) = rest.split_once(" Require Import ") else {
277                    continue;
278                };
279                let Some(modules) = modules.strip_suffix('.') else {
280                    continue;
281                };
282                if library.is_empty() || !library.chars().all(|c| c.is_ascii_alphabetic()) {
283                    continue;
284                }
285                dependencies.extend(
286                    modules
287                        .split_whitespace()
288                        .map(|module| format!("{library}.{module}")),
289                );
290            }
291        }
292    }
293    dependencies
294}
295
296/// Reads the provenance comment a semantic translation starts with.
297pub fn read_provenance(
298    code: &str,
299    target_language: &str,
300) -> Result<ReadTranslationProvenance, String> {
301    let (open, close) = comment(target_language);
302    let first_line = code.split('\n').next().unwrap_or_default();
303    let fields = first_line
304        .strip_prefix(open)
305        .and_then(|line| line.strip_prefix(PROVENANCE_MARKER))
306        .and_then(|line| line.strip_prefix(' '))
307        .and_then(|line| line.strip_suffix(close))
308        .ok_or_else(|| format!("missing {target_language} provenance comment"))?;
309    let field = |name: &str| {
310        fields.split(' ').find_map(|field| {
311            field
312                .strip_prefix(name)
313                .and_then(|rest| rest.strip_prefix('='))
314        })
315    };
316    let invalid = || "expected source, sha256 and bytes fields".to_owned();
317    let source_language = field("source")
318        .and_then(crate::language_support)
319        .ok_or_else(invalid)?
320        .name;
321    let source_sha256 = field("sha256")
322        .filter(|hash| {
323            hash.len() == 64
324                && hash
325                    .bytes()
326                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
327        })
328        .ok_or_else(invalid)?
329        .to_owned();
330    let source_bytes = field("bytes")
331        .and_then(|bytes| bytes.parse::<usize>().ok())
332        .ok_or_else(invalid)?;
333    Ok(ReadTranslationProvenance {
334        source_language,
335        source_sha256,
336        source_bytes,
337    })
338}