Skip to main content

meta_language/
self_translation.rs

1//! Translates meta-language's own modules between JavaScript, TypeScript and
2//! Rust through meta-language links.
3//!
4//! The source is parsed losslessly with its default grammar; a translation
5//! into the same language writes the links back byte for byte, and a
6//! translation into the other language translates each top-level item the
7//! portable core can express and carries every other item verbatim in a
8//! marked comment. Both kinds of item keep their source as provenance, so
9//! translating an unedited translation back restores the source byte for
10//! byte.
11//!
12//! Mirrors `js/src/self-translation.js`.
13
14use crate::translation::frontend_rules::{
15    accept_source_envelope_restoration, accept_source_prefix_restoration,
16};
17use crate::translation::surface::SExpr;
18use std::collections::BTreeMap;
19use std::collections::{HashMap, HashSet};
20use std::fmt;
21use std::fmt::Write as _;
22use std::sync::LazyLock;
23
24use regex::Regex;
25use sha2::{Digest, Sha256};
26
27use crate::decorators::DecoratorSet;
28use crate::grammar::decorate_emitted;
29use crate::translation::surface::External;
30use crate::{LinkNetwork, ParseConfiguration};
31
32mod binding;
33mod emission;
34pub mod representation;
35mod representation_rules;
36use emission::emit_item;
37use representation::Context;
38mod scope;
39mod typescript_erasure;
40mod typescript_erasure_rules;
41mod typescript_portable_typing;
42use scope::{BindingScopeContext, translate_binding_groups};
43
44use self::binding::{Binder, ModuleSignatureContext};
45use typescript_erasure::requires_type_script_erasure;
46pub use typescript_erasure::{ErasedTypeScript, Erasure, erase_type_script};
47pub use typescript_portable_typing::project_type_script_typing;
48
49/// The signature of an exported item of a JavaScript or TypeScript module.
50///
51/// It binds the name a module that imports it uses: a function's parameters
52/// and result, or a constant's type and whether a literal gives its value.
53pub type SelfTranslationSignature = External;
54
55/// What [`self_translate_with`] translates a module with.
56#[derive(Clone, Debug, Default, PartialEq, Eq)]
57pub struct SelfTranslationOptions {
58    /// The emitter decorators, as [`self_translate_decorated`] applies them.
59    pub decorators: DecoratorSet,
60    /// The module's directory inside its crate, as path segments: the crate
61    /// root when empty. A relative import becomes a `use crate::…` of the
62    /// module it names from there.
63    pub module_directory: Vec<String>,
64    /// The signatures [`self_translation_signatures`] gives for each module
65    /// the module imports, by import specifier, which bind the imported names.
66    pub imports: BTreeMap<String, Vec<SelfTranslationSignature>>,
67    /// Select the shared UTF16 prelude and paired Text lowering; unsupported emissions are carried.
68    pub utf16_strings: bool,
69}
70
71/// The languages self-translation reads and writes.
72pub const SELF_TRANSLATION_LANGUAGES: [&str; 3] = ["JavaScript", "TypeScript", "Rust"];
73
74const HEADER: &str = "// meta-language:self-translation:v1 ";
75const CARRIED: &str = "// meta-language:carried ";
76const TRANSLATED: &str = "// meta-language:translated ";
77const SOURCE_LINE: &str = "// |";
78const PRELUDE_BEGIN: &str = "// meta-language:prelude begin";
79const PRELUDE_END: &str = "// meta-language:prelude end";
80// Portable-core Rust keeps the source's parentheses and names.
81const RUST_ALLOW: &str = "#![allow(unused, unreachable_patterns, non_snake_case, non_camel_case_types, invalid_nan_comparisons)]";
82const COMMENTS: [&str; 3] = ["comment", "line_comment", "block_comment"];
83
84static RUST_EXPORT: LazyLock<Regex> =
85    LazyLock::new(|| Regex::new(r"(?m)^pub(\([^)]*\))?\s").expect("a valid pattern"));
86static JAVASCRIPT_EXPORT: LazyLock<Regex> =
87    LazyLock::new(|| Regex::new(r"(?m)^export\s").expect("a valid pattern"));
88static RUST_MAIN: LazyLock<Regex> =
89    LazyLock::new(|| Regex::new(r"\bfn\s+main\s*\(").expect("a valid pattern"));
90static LINE_BREAK: LazyLock<Regex> =
91    LazyLock::new(|| Regex::new(r"\r?\n").expect("a valid pattern"));
92
93/// An unknown language or a source the links do not reproduce.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct SelfTranslationError {
96    /// What went wrong.
97    pub message: String,
98}
99
100impl fmt::Display for SelfTranslationError {
101    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
102        formatter.write_str(&self.message)
103    }
104}
105
106impl std::error::Error for SelfTranslationError {}
107
108/// A top-level item of the source and what self-translation did with it.
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct SelfTranslationItem {
111    /// The item's syntax node kind.
112    pub term: String,
113    /// The item's first byte in the source.
114    pub start: usize,
115    /// The byte after the item in the source.
116    pub end: usize,
117    /// `kept` (same language), `translated`, `restored` (provenance gave back
118    /// its source), `comment`, `provenance` (a self-translation header or
119    /// prelude) or `carried`.
120    pub status: &'static str,
121    /// Why a carried item was carried.
122    pub reason: Option<String>,
123}
124
125/// A translated module with the status of each of its top-level items.
126#[derive(Clone, Debug, PartialEq, Eq)]
127pub struct SelfTranslation {
128    /// The canonical source language.
129    pub source_language: &'static str,
130    /// The canonical target language.
131    pub target_language: &'static str,
132    /// The translated module.
133    pub code: String,
134    /// The source's top-level items in order.
135    pub items: Vec<SelfTranslationItem>,
136}
137
138/// The self-translation language `language` names, or `None`.
139#[must_use]
140pub fn self_translation_language(language: &str) -> Option<&'static str> {
141    match language.to_lowercase().as_str() {
142        "javascript" | "js" | "mjs" => Some("JavaScript"),
143        "typescript" | "ts" => Some("TypeScript"),
144        "rust" | "rs" => Some("Rust"),
145        _ => None,
146    }
147}
148
149fn required(language: &str) -> Result<&'static str, SelfTranslationError> {
150    self_translation_language(language).ok_or_else(|| SelfTranslationError {
151        message: format!(
152            "self-translation reads and writes {}, not {language}",
153            SELF_TRANSLATION_LANGUAGES.join(", ")
154        ),
155    })
156}
157
158// The family a language's code is written in: TypeScript items are read and
159// written as JavaScript.
160fn family(language: &str) -> &'static str {
161    if language == "Rust" {
162        "Rust"
163    } else {
164        "JavaScript"
165    }
166}
167
168fn sha256(text: &str) -> String {
169    Sha256::digest(text.as_bytes())
170        .iter()
171        .fold(String::new(), |mut hex, byte| {
172            let _ = write!(hex, "{byte:02x}");
173            hex
174        })
175}
176
177#[derive(Clone, Debug)]
178struct Item<'a> {
179    term: String,
180    start: usize,
181    end: usize,
182    comment: bool,
183    text: &'a str,
184    after: &'a str,
185}
186
187/// Translates `source` from `source_language` to `target_language`, each one
188/// of [`SELF_TRANSLATION_LANGUAGES`] or an alias of one.
189///
190/// # Errors
191///
192/// A [`SelfTranslationError`] for an unknown language or a source its links
193/// do not reproduce.
194pub fn self_translate(
195    source: &str,
196    source_language: &str,
197    target_language: &str,
198) -> Result<SelfTranslation, SelfTranslationError> {
199    self_translate_decorated(
200        source,
201        source_language,
202        target_language,
203        &DecoratorSet::default(),
204    )
205}
206
207/// [`self_translate`] with the emitter `decorators` applied.
208///
209/// They decorate the code each translated item writes before its provenance
210/// marker is hashed, so the decorated translation still translates back to
211/// `source`.
212///
213/// # Errors
214///
215/// As [`self_translate`].
216pub fn self_translate_decorated(
217    source: &str,
218    source_language: &str,
219    target_language: &str,
220    decorators: &DecoratorSet,
221) -> Result<SelfTranslation, SelfTranslationError> {
222    let options = SelfTranslationOptions {
223        decorators: decorators.clone(),
224        ..SelfTranslationOptions::default()
225    };
226    self_translate_with(source, source_language, target_language, &options)
227}
228
229/// [`self_translate`] with `options`.
230///
231/// From JavaScript or TypeScript into Rust, an item may call and read the
232/// module's other top-level items: each item is translated after the items
233/// it names, with the signatures of those that translated bound, and the
234/// Rust names them as its own translation does. `import { a, b as c } from
235/// './m.mjs'` becomes `use crate::m::{a, b as c};`, and the signatures
236/// `options.imports` gives for `./m.mjs` bind the imported names the same way.
237///
238/// # Errors
239///
240/// As [`self_translate`].
241pub fn self_translate_with(
242    source: &str,
243    source_language: &str,
244    target_language: &str,
245    options: &SelfTranslationOptions,
246) -> Result<SelfTranslation, SelfTranslationError> {
247    translate_module(source, source_language, target_language, options)
248        .map(|(translation, _)| translation)
249}
250
251/// The signatures of the exported items of the JavaScript or TypeScript
252/// module `source` that translate into Rust, in source order, for the
253/// `imports` of a module that imports them.
254///
255/// # Errors
256///
257/// A [`SelfTranslationError`] for an unknown or a Rust language or a source
258/// its links do not reproduce.
259pub fn self_translation_signatures(
260    source: &str,
261    language: &str,
262    options: &SelfTranslationOptions,
263) -> Result<Vec<SelfTranslationSignature>, SelfTranslationError> {
264    if family(required(language)?) != "JavaScript" {
265        return Err(SelfTranslationError {
266            message: format!(
267                "signatures are read from JavaScript or TypeScript modules, not {language}"
268            ),
269        });
270    }
271    translate_module(source, language, "Rust", options).map(|(_, signatures)| signatures)
272}
273
274fn translate_module(
275    source: &str,
276    source_language: &str,
277    target_language: &str,
278    options: &SelfTranslationOptions,
279) -> Result<(SelfTranslation, Vec<SelfTranslationSignature>), SelfTranslationError> {
280    let decorators = &options.decorators;
281    let from = required(source_language)?;
282    let to = required(target_language)?;
283    let network = LinkNetwork::parse(source, from, ParseConfiguration::default());
284    let reconstructed = network.reconstruct_text();
285    let utf16_strings = representation::select(&network, source, from, options.utf16_strings);
286    if reconstructed != source {
287        return Err(SelfTranslationError {
288            message: format!("the {from} links of the source do not reproduce it"),
289        });
290    }
291    let items = top_level_items(source, from);
292    let kept_family =
293        from == "JavaScript" || (from == "TypeScript" && !requires_type_script_erasure(source));
294    if family(from) == family(to) && (from == to || (kept_family && !source.starts_with(HEADER))) {
295        let items = items
296            .iter()
297            .map(|item| SelfTranslationItem {
298                term: item.term.clone(),
299                start: item.start,
300                end: item.end,
301                status: "kept",
302                reason: None,
303            })
304            .collect();
305        let translation = SelfTranslation {
306            source_language: from,
307            target_language: to,
308            code: reconstructed,
309            items,
310        };
311        return Ok((translation, Vec::new()));
312    }
313    let mut blocks: Vec<String> = Vec::new();
314    let mut preludes: Vec<String> = Vec::new();
315    let mut recorded = Vec::new();
316    let mut gap = String::new();
317    let groups = group_items(&items, source);
318    let (outs, scans, signature_context) = if family(to) == "Rust" {
319        Binder {
320            groups: &groups,
321            source,
322            from,
323            to,
324            decorators,
325            module_directory: &options.module_directory,
326            imports: &options.imports,
327            utf16_strings,
328        }
329        .translate()
330    } else {
331        let outs = groups
332            .iter()
333            .map(|group| {
334                translate_group(
335                    group,
336                    from,
337                    to,
338                    decorators,
339                    &Context {
340                        utf16_strings,
341                        ..Context::default()
342                    },
343                )
344            })
345            .collect();
346        (
347            outs,
348            Vec::new(),
349            ModuleSignatureContext {
350                module_scope_known: true,
351                owner_counts: HashMap::new(),
352                module_binding_names: Vec::new(),
353            },
354        )
355    };
356    let module_scope_known = signature_context.module_scope_known;
357    let results = translate_binding_groups(
358        &groups,
359        source,
360        from,
361        to,
362        decorators,
363        &outs,
364        BindingScopeContext {
365            utf16_strings,
366            module_scope_known,
367            module_binding_names: signature_context.module_binding_names.clone(),
368        },
369    );
370    let layout_envelope =
371        crate::translation::self_translation_layout_rules::require_self_translation_layout_envelope(
372            (
373                source.contains('\r'),
374                results
375                    .first()
376                    .and_then(|(group, _)| group.items.first())
377                    .map_or(source.len(), |item| item.start)
378                    > 0,
379                !matches!(
380                    results.last().map_or(source, |(group, _)| group.after),
381                    "" | "\n"
382                ),
383                results
384                    .iter()
385                    .take(results.len().saturating_sub(1))
386                    .any(|(group, _)| group.after != breaks(group.after)),
387            ),
388        );
389    let exported_names: HashSet<&str> = scans
390        .iter()
391        .flatten()
392        .filter(|scan| scan.exported)
393        .filter_map(|scan| scan.declares.as_deref())
394        .collect();
395    let signatures: Vec<SelfTranslationSignature> = results
396        .iter()
397        .filter(|(_, out)| out.status == "translated")
398        .flat_map(|(_, out)| {
399            out.signatures
400                .iter()
401                .filter(|signature| {
402                    exported_names.contains(signature.name())
403                        && signature_context.accept_signature_binding(signature.name())
404                })
405                .cloned()
406        })
407        .collect();
408    for (group, out) in results {
409        for prelude in out.preludes {
410            if !preludes.contains(&prelude) {
411                preludes.push(prelude);
412            }
413        }
414        for item in &group.items {
415            recorded.push(SelfTranslationItem {
416                term: item.term.clone(),
417                start: item.start,
418                end: item.end,
419                status: out.status,
420                reason: out.reason.clone(),
421            });
422        }
423        if let Some(code) = out.code {
424            let separator = if blocks.is_empty() {
425                String::new()
426            } else {
427                breaks(&gap)
428            };
429            blocks.push(format!("{separator}{code}"));
430            group.after.clone_into(&mut gap);
431        } else if gap.is_empty() {
432            // A dropped group keeps the layout before it.
433            group.after.clone_into(&mut gap);
434        }
435    }
436    let body = format!("{}\n", blocks.concat());
437    // An unedited translation back gives the source its header describes.
438    let header = items
439        .iter()
440        .find(|item| item.comment && item.text.starts_with(HEADER));
441    if let Some(header) = header
442        && header.text.contains(&format!(" source={to} "))
443        && header.text.contains(&format!(" sha256={} ", sha256(&body)))
444    {
445        let translation = SelfTranslation {
446            source_language: from,
447            target_language: to,
448            code: body,
449            items: recorded,
450        };
451        return Ok((translation, signatures));
452    }
453    if let Some(header) = header {
454        static SOURCE_ENVELOPE: LazyLock<Regex> = LazyLock::new(|| {
455            Regex::new(r" envelope-sha256=([a-f0-9]{64}) original=(.*)$").unwrap()
456        });
457        if let Some(envelope) = SOURCE_ENVELOPE.captures(header.text)
458            && let Ok(original) = serde_json::from_str::<String>(&envelope[2])
459            && accept_source_envelope_restoration(
460                header.text.contains(&format!(" source={to} ")),
461                sha256(&source[header.end..]) == envelope[1],
462                header.text.split_ascii_whitespace().find_map(|field| {
463                    field
464                        .strip_prefix("bytes=")
465                        .and_then(|value| value.parse::<usize>().ok())
466                }) == Some(original.len())
467                    && header
468                        .text
469                        .contains(&format!(" sha256={} ", sha256(&original))),
470            )
471        {
472            return Ok((
473                SelfTranslation {
474                    source_language: from,
475                    target_language: to,
476                    code: original,
477                    items: recorded,
478                },
479                signatures,
480            ));
481        }
482        let original_length = header.text.split_ascii_whitespace().find_map(|field| {
483            field
484                .strip_prefix("bytes=")
485                .and_then(|value| value.parse::<usize>().ok())
486        });
487        if let Some(length) = original_length
488            && let Some(original) = body.get(..length)
489            && let Some(layout) = body.get(length..)
490            && accept_source_prefix_restoration(
491                header.text.contains(&format!(" source={to} ")),
492                header
493                    .text
494                    .contains(&format!(" sha256={} ", sha256(original))),
495                layout
496                    .encode_utf16()
497                    .all(crate::translation::lexer::is_js_space),
498            )
499        {
500            return Ok((
501                SelfTranslation {
502                    source_language: from,
503                    target_language: to,
504                    code: original.to_owned(),
505                    items: recorded,
506                },
507                signatures,
508            ));
509        }
510    }
511    if family(to) == "Rust" && recorded.iter().any(|item| item.status == "translated") {
512        preludes.insert(0, RUST_ALLOW.to_owned());
513    }
514    let mut lines = vec![
515        format!(
516            "{HEADER}source={from} target={to} sha256={} bytes={}",
517            sha256(source),
518            source.len()
519        ),
520        String::new(),
521    ];
522    if !preludes.is_empty() {
523        lines.push(PRELUDE_BEGIN.to_owned());
524        for (index, prelude) in preludes.into_iter().enumerate() {
525            if index > 0 {
526                lines.push(String::new());
527            }
528            lines.push(prelude);
529        }
530        lines.push(PRELUDE_END.to_owned());
531        lines.push(String::new());
532    }
533    if layout_envelope {
534        let tail = format!("\n{}\n{body}", lines[1..].join("\n"));
535        let original = serde_json::to_string(source)
536            .expect("source text serializes")
537            .replace('\u{2028}', "\\u2028")
538            .replace('\u{2029}', "\\u2029");
539        write!(
540            lines[0],
541            " envelope-sha256={} original={original}",
542            sha256(&tail)
543        )
544        .expect("writing a string succeeds");
545    }
546    let translation = SelfTranslation {
547        source_language: from,
548        target_language: to,
549        code: format!("{}\n{body}", lines.join("\n")),
550        items: recorded,
551    };
552    Ok((translation, signatures))
553}
554
555// The layout between two emitted blocks: its line breaks, at least one.
556fn breaks(gap: &str) -> String {
557    "\n".repeat(gap.matches('\n').count().max(1))
558}
559
560/// The top-level items of `text`, with their text and the layout after each.
561fn top_level_items<'a>(text: &'a str, language: &str) -> Vec<Item<'a>> {
562    let bytes = text.as_bytes();
563    let nodes: Vec<(String, usize, usize)> =
564        crate::tree_sitter_adapter::top_level_nodes(text, language)
565            .unwrap_or_default()
566            .into_iter()
567            .filter(|(term, _, _)| term != "whitespace")
568            .map(|(term, start, mut end)| {
569                // A Rust line comment ends with its line break, which is layout here.
570                if COMMENTS.contains(&term.as_str()) && end > 0 && bytes[end - 1] == b'\n' {
571                    end -= if end > 1 && bytes[end - 2] == b'\r' {
572                        2
573                    } else {
574                        1
575                    };
576                }
577                (term, start, end)
578            })
579            .collect();
580    nodes
581        .iter()
582        .enumerate()
583        .map(|(index, (term, start, end))| Item {
584            term: term.clone(),
585            start: *start,
586            end: *end,
587            comment: COMMENTS.contains(&term.as_str()),
588            text: &text[*start..*end],
589            after: &text[*end..nodes.get(index + 1).map_or(text.len(), |next| next.1)],
590        })
591        .collect()
592}
593
594fn line_break(layout: &str) -> bool {
595    layout == "\n" || layout == "\r\n"
596}
597
598fn source_lines(items: &[Item<'_>]) -> Vec<String> {
599    items
600        .iter()
601        .map(|item| {
602            let rest = &item.text[SOURCE_LINE.len()..];
603            rest.strip_prefix(' ').unwrap_or(rest).to_owned()
604        })
605        .collect()
606}
607
608fn is_marker(item: &Item<'_>) -> bool {
609    item.comment
610        && [HEADER, CARRIED, TRANSLATED, PRELUDE_BEGIN]
611            .iter()
612            .any(|marker| item.text.starts_with(marker))
613}
614
615#[derive(Clone, Debug)]
616enum GroupKind {
617    Provenance,
618    Carried {
619        language: String,
620        lines: Vec<String>,
621    },
622    Comment {
623        text: String,
624        term: String,
625    },
626    Item {
627        text: String,
628        term: String,
629    },
630}
631
632#[derive(Clone)]
633struct Group<'a> {
634    kind: GroupKind,
635    items: Vec<Item<'a>>,
636    after: &'a str,
637}
638
639/// Groups the items: a self-translation header, a prelude block, a carried or
640/// translated item with its provenance, and an item with the comments directly
641/// before it are one group each.
642fn group_items<'a>(items: &[Item<'a>], text: &'a str) -> Vec<Group<'a>> {
643    let mut groups = Vec::new();
644    let between = |first: &Item<'_>, last: &Item<'_>| text[first.start..last.end].to_owned();
645    // The `// |` source lines that follow the item at `at` line by line.
646    let lines_after = |at: usize| {
647        let mut end = at;
648        while end + 1 < items.len()
649            && items[end + 1].comment
650            && items[end + 1].text.starts_with(SOURCE_LINE)
651            && line_break(items[end].after)
652        {
653            end += 1;
654        }
655        end
656    };
657    let mut index = 0;
658    while index < items.len() {
659        let item = &items[index];
660        let (end, kind) = if item.comment && item.text.starts_with(HEADER) {
661            (index, GroupKind::Provenance)
662        } else if item.comment && item.text == PRELUDE_BEGIN {
663            let mut end = index;
664            while end + 1 < items.len() && items[end].text != PRELUDE_END {
665                end += 1;
666            }
667            (end, GroupKind::Provenance)
668        } else if item.comment && item.text.starts_with(CARRIED) {
669            let end = lines_after(index);
670            let language = first_word(&item.text[CARRIED.len()..]);
671            let lines = source_lines(&items[index + 1..=end]);
672            (end, GroupKind::Carried { language, lines })
673        } else if item.comment && item.text.starts_with(TRANSLATED) {
674            let rest = &item.text[TRANSLATED.len()..];
675            let field = |name: &str| {
676                rest.split(' ').skip(2).find_map(|field| {
677                    let (key, value) = field.split_once('=').unwrap_or((field, ""));
678                    (key == name).then_some(value)
679                })
680            };
681            let lines_end = lines_after(index);
682            let count = field("items").and_then(|count| count.parse::<usize>().ok());
683            if count == Some(0) && field("sha256") == Some(sha256("").as_str()) {
684                let lines = source_lines(&items[index + 1..=lines_end]);
685                groups.push(Group {
686                    kind: GroupKind::Carried {
687                        language: first_word(rest),
688                        lines,
689                    },
690                    items: items[index..=lines_end].to_vec(),
691                    after: items[lines_end].after,
692                });
693                index = lines_end + 1;
694                continue;
695            }
696            count
697                .and_then(|count| definitions_end(items, lines_end, count))
698                .map_or_else(
699                    || {
700                        (
701                            index,
702                            GroupKind::Comment {
703                                text: item.text.to_owned(),
704                                term: item.term.clone(),
705                            },
706                        )
707                    },
708                    |last| {
709                        let code = between(&items[lines_end + 1], &items[last]);
710                        if field("sha256") == Some(sha256(&code).as_str()) {
711                            let lines = source_lines(&items[index + 1..=lines_end]);
712                            (
713                                last,
714                                GroupKind::Carried {
715                                    language: first_word(rest),
716                                    lines,
717                                },
718                            )
719                        } else {
720                            // An edited translation is translated again; its provenance is dropped.
721                            (lines_end, GroupKind::Provenance)
722                        }
723                    },
724                )
725        } else {
726            // Comments directly before an item document it and travel with it.
727            let mut end = index;
728            while items[end].comment
729                && end + 1 < items.len()
730                && line_break(items[end].after)
731                && !is_marker(&items[end + 1])
732            {
733                end += 1;
734            }
735            let text = between(item, &items[end]);
736            let term = items[end].term.clone();
737            // A run of comments no item follows is one comment group.
738            if items[end].comment {
739                (end, GroupKind::Comment { text, term })
740            } else {
741                (end, GroupKind::Item { text, term })
742            }
743        };
744        groups.push(Group {
745            kind,
746            items: items[index..=end].to_vec(),
747            after: items[end].after,
748        });
749        index = end + 1;
750    }
751    groups
752}
753
754/// The last item of the `count` definitions after the item at `after`: a
755/// definition's attributes (`#[derive(…)]`) are items of their own in Rust.
756fn definitions_end(items: &[Item<'_>], after: usize, count: usize) -> Option<usize> {
757    if count == 0 {
758        return None;
759    }
760    let mut left = count;
761    for (at, item) in items.iter().enumerate().skip(after + 1) {
762        if item.term != "attribute_item" && !item.comment {
763            left -= 1;
764        }
765        if left == 0 {
766            return Some(at);
767        }
768    }
769    None
770}
771
772fn first_word(text: &str) -> String {
773    text.split(' ').next().unwrap_or_default().to_owned()
774}
775
776#[derive(Clone)]
777struct Translated {
778    code: Option<String>,
779    preludes: Vec<String>,
780    status: &'static str,
781    reason: Option<String>,
782    /// The signatures a translated item gives the other items of its module.
783    signatures: Vec<External>,
784}
785
786fn translate_group(
787    group: &Group<'_>,
788    from: &str,
789    to: &str,
790    decorators: &DecoratorSet,
791    context: &Context,
792) -> Translated {
793    translate_group_bound(group, from, to, decorators, context, &HashMap::new())
794}
795
796fn translate_group_bound(
797    group: &Group<'_>,
798    from: &str,
799    to: &str,
800    decorators: &DecoratorSet,
801    context: &Context,
802    literal_bindings: &HashMap<String, SExpr>,
803) -> Translated {
804    let done = |code: String, status: &'static str| Translated {
805        code: Some(code),
806        preludes: Vec::new(),
807        status,
808        reason: None,
809        signatures: Vec::new(),
810    };
811    let (text, term) = match &group.kind {
812        GroupKind::Provenance => {
813            return Translated {
814                code: None,
815                preludes: Vec::new(),
816                status: "provenance",
817                reason: None,
818                signatures: Vec::new(),
819            };
820        }
821        GroupKind::Carried { language, lines } => {
822            if family(language) == family(to) {
823                return done(lines.join("\n"), "restored");
824            }
825            let mut code = vec![group.items[0].text.to_owned()];
826            code.extend(lines.iter().map(|line| source_line(line)));
827            return Translated {
828                reason: Some("carried from another language".to_owned()),
829                ..done(code.join("\n"), "carried")
830            };
831        }
832        GroupKind::Comment { text, term } => {
833            // A copied comment has no provenance, so it must also fit the source.
834            if group
835                .items
836                .iter()
837                .all(|item| comment_fits(item.text, from) && comment_fits(item.text, to))
838            {
839                return done(text.clone(), "comment");
840            }
841            return carry(text, term, from, "comment the target cannot hold");
842        }
843        GroupKind::Item { text, term } => (text, term),
844    };
845    if term == "ERROR" {
846        return carry(text, term, from, "syntax");
847    }
848    if from == "TypeScript" && to == "JavaScript" {
849        let erased = match erase_type_script(text) {
850            Ok(erased) => erased,
851            Err(error) => return carry(text, term, from, &error.reason),
852        };
853        let erased_code = erased.code.trim();
854        let count = top_level_items(erased_code, "JavaScript")
855            .iter()
856            .filter(|item| !item.comment)
857            .count();
858        let code = if count == 0 { "" } else { erased_code };
859        let mut lines = vec![format!(
860            "{TRANSLATED}{from} {term} items={count} sha256={}",
861            sha256(code)
862        )];
863        lines.extend(LINE_BREAK.split(text).map(source_line));
864        if !code.is_empty() {
865            lines.push(code.to_owned());
866        }
867        return done(lines.join("\n"), "translated");
868    }
869    let (emitted, signatures) = match emit_item(text, from, to, context, literal_bindings) {
870        Ok(Some(emitted)) => emitted,
871        Ok(None) => return carry(text, term, from, "top-level statement"),
872        Err(error) => {
873            return carry(
874                text,
875                term,
876                from,
877                if from == "TypeScript"
878                    || error.construct.as_deref() == Some("UTF16 Text representation")
879                {
880                    &error.reason
881                } else {
882                    error.kind.as_str()
883                },
884            );
885        }
886    };
887    if emitted.definitions.is_empty() {
888        return carry(text, term, from, "no definition");
889    }
890    let exported = family(to) == "JavaScript"
891        && if family(from) == "Rust" {
892            RUST_EXPORT.is_match(text)
893        } else {
894            JAVASCRIPT_EXPORT.is_match(text)
895        };
896    let generic = emitted
897        .definitions
898        .iter()
899        .map(|definition| {
900            if exported {
901                format!("export {definition}")
902            } else {
903                definition.clone()
904            }
905        })
906        .collect::<Vec<_>>()
907        .join("\n\n");
908    let code = decorate_emitted(to, &generic, decorators);
909    if code.trim().is_empty() {
910        return carry(text, term, from, "dropped by a decorator");
911    }
912    let count = emitted.definitions.len();
913    let marker = format!(
914        "{TRANSLATED}{from} {term} items={} sha256={}",
915        count,
916        sha256(&code)
917    );
918    let mut lines = vec![marker];
919    lines.extend(LINE_BREAK.split(text).map(source_line));
920    lines.push(code);
921    Translated {
922        code: Some(lines.join("\n")),
923        preludes: emitted.preludes,
924        status: "translated",
925        reason: None,
926        signatures,
927    }
928}
929
930fn carry(text: &str, term: &str, from: &str, reason: &str) -> Translated {
931    let mut lines = vec![format!("{CARRIED}{from} {term} ({reason})")];
932    lines.extend(LINE_BREAK.split(text).map(source_line));
933    Translated {
934        code: Some(lines.join("\n")),
935        preludes: Vec::new(),
936        status: "carried",
937        reason: Some(reason.to_owned()),
938        signatures: Vec::new(),
939    }
940}
941
942fn source_line(line: &str) -> String {
943    if line.is_empty() {
944        SOURCE_LINE.to_owned()
945    } else {
946        format!("{SOURCE_LINE} {line}")
947    }
948}
949
950// A comment keeps its text when the target reads it as an ordinary comment:
951// a Rust doc comment needs an item after it, and Rust block comments nest.
952fn comment_fits(text: &str, to: &str) -> bool {
953    if text.starts_with("/*") {
954        let inner = text
955            .get(2..text.len().saturating_sub(2))
956            .unwrap_or_default();
957        if inner.contains("/*") || inner.contains("*/") {
958            return false;
959        }
960    }
961    family(to) != "Rust"
962        || !["///", "//!", "/**", "/*!"]
963            .iter()
964            .any(|prefix| text.starts_with(prefix))
965}