Skip to main content

meta_language/translation/
emit_common.rs

1//! State shared by the emitters.
2//!
3//! The state holds target names for every declaration, the source-to-target
4//! mapping, and the encodings and assumptions a translation relies on. Every
5//! emitter records what it did here, so the translation contract lists exactly
6//! the choices that were made for this program.
7//!
8//! Mirrors `js/src/translation/emit-common.js`.
9
10use std::collections::{BTreeSet, HashMap, HashSet};
11
12use serde::{Deserialize, Serialize};
13
14use super::diagnostics::{Result, unsupported};
15use super::ir::{Decl, Effect, Expr, Node, Pattern, Plan, Program, Prop};
16use super::types::Type;
17use super::{Language, Span};
18
19/// A fixed assumption text, so that contracts compare across runtimes.
20#[derive(Clone, Copy, Debug)]
21pub struct AssumptionText {
22    pub id: &'static str,
23    pub statement: &'static str,
24}
25
26pub const IN_BOUNDS_READS: AssumptionText = AssumptionText {
27    id: "in-bounds-array-reads",
28    statement: "the translation agrees with the source on executions whose array reads are in bounds; JavaScript reads undefined at an index outside an array, where the target aborts",
29};
30
31/// Where a source declaration went in the target.
32#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "camelCase")]
34pub struct Mapping {
35    pub kind: String,
36    pub source: String,
37    pub target: String,
38    pub source_span: Option<Span>,
39}
40
41/// An assumption the translation relies on, with the program-specific details.
42#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
43pub struct Assumption {
44    pub id: String,
45    pub statement: String,
46    pub details: Vec<String>,
47}
48
49/// A representation choice the translation made.
50#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub struct Encoding {
52    pub id: String,
53    pub statement: String,
54}
55
56/// A theorem or assertion the target states, and how it is discharged.
57#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct TheoremRecord {
60    pub source: String,
61    pub target: String,
62    pub kind: String,
63    pub closed_goal: bool,
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub discharge: Option<String>,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub check: Option<String>,
68}
69
70/// An emitted target program together with its translation contract.
71#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
72pub struct Emitted {
73    pub language: Language,
74    pub text: String,
75    /// The helper definitions `text` starts with, in order. Not part of the
76    /// serialised contract.
77    #[serde(skip)]
78    pub preludes: Vec<String>,
79    /// The translated top-level definitions of `text`, in order, without the
80    /// header, the preludes and the entry point. Not part of the serialised
81    /// contract.
82    #[serde(skip)]
83    pub definitions: Vec<String>,
84    pub mappings: Vec<Mapping>,
85    pub assumptions: Vec<Assumption>,
86    pub encodings: Vec<Encoding>,
87    pub theorems: Vec<TheoremRecord>,
88    pub entry: Option<String>,
89}
90
91/// How constructors are named: inside a module next to their type (Rocq), or under the type.
92#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
93pub enum CtorStyle {
94    Module,
95    #[default]
96    Data,
97}
98
99/// Target naming rules for [`EmitState`].
100#[derive(Clone, Copy, Default)]
101#[allow(clippy::struct_excessive_bools)] // the flags mirror independent target namespaces
102pub struct EmitOptions {
103    pub ctor_style: CtorStyle,
104    pub type_name: Option<fn(&str) -> String>,
105    pub value_name: Option<fn(&str) -> String>,
106    pub ctor_name: Option<fn(&str) -> String>,
107    pub module_segment: Option<fn(&str) -> String>,
108    /// Names the target itself derives from a declaration (Rocq's `f_equation`, `T_ind`).
109    pub generated: Option<fn(&str) -> Vec<String>>,
110    pub type_space: bool,
111    pub modules_share_term_space: bool,
112    pub modules_share_type_space: bool,
113    /// Names root declarations may not take because the target's prelude has them.
114    pub root_reserved: &'static [&'static str],
115}
116
117struct Target {
118    local: String,
119    path: Vec<String>,
120}
121
122pub struct EmitState<'p> {
123    pub program: &'p Program,
124    pub language: Language,
125    pub ident: fn(&str) -> String,
126    reserved: BTreeSet<String>,
127    options: EmitOptions,
128    names: HashMap<String, Target>,
129    ctor_names: HashMap<String, String>,
130    module_names: HashMap<String, String>,
131    taken: HashMap<String, HashSet<String>>,
132    claimed: BTreeSet<String>,
133    pub mappings: Vec<Mapping>,
134    assumptions: Vec<Assumption>,
135    encodings: Vec<Encoding>,
136    pub theorems: Vec<TheoremRecord>,
137}
138
139impl<'p> EmitState<'p> {
140    #[must_use]
141    pub fn new(
142        program: &'p Program,
143        language: Language,
144        ident: fn(&str) -> String,
145        reserved: &[&str],
146        options: EmitOptions,
147    ) -> Self {
148        let mut state = Self {
149            program,
150            language,
151            ident,
152            reserved: reserved.iter().map(|name| (*name).to_owned()).collect(),
153            options,
154            names: HashMap::new(),
155            ctor_names: HashMap::new(),
156            module_names: HashMap::new(),
157            taken: HashMap::new(),
158            claimed: BTreeSet::new(),
159            mappings: Vec::new(),
160            assumptions: Vec::new(),
161            encodings: Vec::new(),
162            theorems: Vec::new(),
163        };
164        state.assign();
165        state
166    }
167
168    /// Target names are fixed up front, so references never depend on emission order.
169    fn assign(&mut self) {
170        let module_name = self.options.module_segment.unwrap_or(self.ident);
171        // JavaScript modules are values; Rust modules share the type namespace.
172        let module_space = if self.options.modules_share_term_space {
173            "term"
174        } else if self.options.modules_share_type_space {
175            "type"
176        } else {
177            "module"
178        };
179        let program = self.program;
180        for entry in &program.declarations {
181            let module_path = entry.module_path();
182            let mut segments = Vec::new();
183            for (index, segment) in module_path.iter().enumerate() {
184                let key = module_path[..=index].join(".");
185                if !self.module_names.contains_key(&key) {
186                    let parent = module_path[..index].join(".");
187                    let name =
188                        self.claim(&format!("{module_space}:{parent}"), &module_name(segment));
189                    self.module_names.insert(key.clone(), name);
190                }
191                segments.push(self.module_names[&key].clone());
192            }
193            let space = format!("term:{}", module_path.join("."));
194            let base = match entry {
195                Decl::Data(_) => self.options.type_name.unwrap_or(self.ident)(entry.name()),
196                _ => self.options.value_name.unwrap_or(self.ident)(entry.name()),
197            };
198            let local_space = if matches!(entry, Decl::Data(_)) && self.options.type_space {
199                format!("type:{}", module_path.join("."))
200            } else {
201                space.clone()
202            };
203            let local = self.claim(&local_space, &base);
204            self.names.insert(
205                entry.full_name().to_owned(),
206                Target {
207                    local,
208                    path: segments,
209                },
210            );
211            if let Decl::Data(data) = entry {
212                for ctor in &data.ctors {
213                    let ctor_base = self.options.ctor_name.unwrap_or(self.ident)(&ctor.name);
214                    let ctor_space = if self.options.ctor_style == CtorStyle::Module {
215                        space.clone()
216                    } else {
217                        format!("ctor:{}", data.full_name)
218                    };
219                    let name = self.claim(&ctor_space, &ctor_base);
220                    self.ctor_names
221                        .insert(format!("{}#{}", data.full_name, ctor.name), name);
222                }
223            }
224        }
225    }
226
227    fn claim(&mut self, space: &str, name: &str) -> String {
228        if !self.taken.contains_key(space) {
229            // Root declarations may not redeclare the target's prelude (`root_reserved`).
230            let mut used: HashSet<String> = self.reserved.iter().cloned().collect();
231            if space.ends_with(':') {
232                used.extend(
233                    self.options
234                        .root_reserved
235                        .iter()
236                        .map(|name| (*name).to_owned()),
237                );
238            }
239            self.taken.insert(space.to_owned(), used);
240        }
241        let generated = self.options.generated;
242        let used = self
243            .taken
244            .get_mut(space)
245            .expect("namespace was just created");
246        let is_generated = |candidate: &str, used: &HashSet<String>| {
247            generated.is_some_and(|generated| {
248                generated(candidate).iter().any(|name| used.contains(name))
249            })
250        };
251        let mut candidate = name.to_owned();
252        let mut index = 2;
253        while used.contains(&candidate) || is_generated(&candidate, used) {
254            candidate = format!("{name}_{index}");
255            index += 1;
256        }
257        let mut names = vec![candidate.clone()];
258        if let Some(generated) = generated {
259            names.extend(generated(&candidate));
260        }
261        for name in names {
262            used.insert(name.clone());
263            self.claimed.insert(name);
264        }
265        candidate
266    }
267
268    /// Keeps locals off `name`, the target name of another item of the
269    /// module that the program calls or reads.
270    pub fn reserve(&mut self, name: String) {
271        self.claimed.insert(name);
272    }
273
274    /// Names a local binder may not take: a local named like a module, a
275    /// top-level function or a constructor would shadow it in the target.
276    #[must_use]
277    pub fn local_reserved(&self) -> BTreeSet<String> {
278        self.reserved.union(&self.claimed).cloned().collect()
279    }
280
281    /// The target name of a declaration within its module.
282    ///
283    /// # Panics
284    /// When `full_name` is not a declaration of the program.
285    #[must_use]
286    pub fn local_name(&self, full_name: &str) -> &str {
287        &self.names[full_name].local
288    }
289
290    /// The target module path of a declaration.
291    ///
292    /// # Panics
293    /// When `full_name` is not a declaration of the program.
294    #[must_use]
295    pub fn module_path(&self, full_name: &str) -> &[String] {
296        &self.names[full_name].path
297    }
298
299    /// The target name of a source module.
300    #[must_use]
301    pub fn module_name(&self, source_path: &[String]) -> Option<&str> {
302        self.module_names
303            .get(&source_path.join("."))
304            .map(String::as_str)
305    }
306
307    /// Fully qualified reference from the top level.
308    #[must_use]
309    pub fn reference(&self, full_name: &str, separator: &str) -> String {
310        let target = &self.names[full_name];
311        let mut parts = target.path.clone();
312        parts.push(target.local.clone());
313        parts.join(separator)
314    }
315
316    /// The target name of a constructor within its namespace.
317    ///
318    /// # Panics
319    /// When the constructor is not declared.
320    #[must_use]
321    pub fn ctor_local(&self, data_name: &str, ctor: &str) -> &str {
322        &self.ctor_names[&format!("{data_name}#{ctor}")]
323    }
324
325    /// Fully qualified constructor reference from the top level.
326    #[must_use]
327    pub fn ctor_ref(&self, data_name: &str, ctor: &str, separator: &str) -> String {
328        let local = self.ctor_local(data_name, ctor);
329        if self.options.ctor_style == CtorStyle::Module {
330            let mut parts = self.module_path(data_name).to_vec();
331            parts.push(local.to_owned());
332            return parts.join(separator);
333        }
334        format!("{}{separator}{local}", self.reference(data_name, separator))
335    }
336
337    /// Records where a declaration (and a data type's constructors) went.
338    pub fn map(&mut self, entry: &Decl, target: &str) {
339        // A generated ml_io pair (output.rs) has no source declaration to map.
340        if matches!(entry, Decl::Data(data) if data.output) {
341            return;
342        }
343        let source_span = entry.span();
344        let mut path = self.module_path(entry.full_name()).to_vec();
345        path.push(target.to_owned());
346        self.mappings.push(Mapping {
347            kind: match entry {
348                Decl::Fn(_) => "function",
349                other => other.kind(),
350            }
351            .to_owned(),
352            source: entry.full_name().to_owned(),
353            target: path.join("."),
354            source_span,
355        });
356        if let Decl::Data(data) = entry {
357            for ctor in &data.ctors {
358                self.mappings.push(Mapping {
359                    kind: "constructor".to_owned(),
360                    source: format!("{}.{}", data.full_name, ctor.name),
361                    target: self.ctor_ref(&data.full_name, &ctor.name, "."),
362                    source_span,
363                });
364            }
365        }
366    }
367
368    pub fn assume(&mut self, assumption: AssumptionText, detail: Option<&str>) {
369        let index = if let Some(index) = self
370            .assumptions
371            .iter()
372            .position(|record| record.id == assumption.id)
373        {
374            index
375        } else {
376            self.assumptions.push(Assumption {
377                id: assumption.id.to_owned(),
378                statement: assumption.statement.to_owned(),
379                details: Vec::new(),
380            });
381            self.assumptions.len() - 1
382        };
383        let record = &mut self.assumptions[index];
384        if let Some(detail) = detail
385            && !record.details.iter().any(|known| known == detail)
386        {
387            record.details.push(detail.to_owned());
388        }
389    }
390
391    /// A machine integer of a pure target: its unbounded representation, with Rust's aborts threaded as values (`output`).
392    pub fn machine_integer(&mut self, ty: &Type, representation: &str) {
393        let key = ty.key();
394        self.encode(
395            &format!("machine-integer:{key}"),
396            &format!("{key} values are {representation} values; every {key} operation tests where Rust panics, overflow or a zero divisor, and aborts there with Rust's panic message, and otherwise computes the in-range result exactly"),
397        );
398    }
399
400    /// An array read: in bounds it is the element, outside it JavaScript's undefined, which the targets do not model.
401    pub fn array_read(&mut self) {
402        self.assume(IN_BOUNDS_READS, None);
403    }
404
405    pub fn encode(&mut self, id: &str, statement: &str) {
406        if !self.encodings.iter().any(|encoding| encoding.id == id) {
407            self.encodings.push(Encoding {
408                id: id.to_owned(),
409                statement: statement.to_owned(),
410            });
411        }
412    }
413
414    /// Records a theorem; `bounded` theorems are checked by the source
415    /// kernel and tested on bounded inputs in the target.
416    pub fn theorem(&mut self, full_name: &str, name: &str, closed_goal: bool, bounded: bool) {
417        let mut path = self.module_path(full_name).to_vec();
418        path.push(name.to_owned());
419        self.theorems.push(TheoremRecord {
420            source: full_name.to_owned(),
421            target: path.join("."),
422            kind: "theorem".to_owned(),
423            closed_goal,
424            discharge: bounded.then(|| "source-kernel".to_owned()),
425            check: bounded.then(|| "bounded".to_owned()),
426        });
427    }
428
429    pub fn assertion_theorem(&mut self, name: &str, effect: &Effect) {
430        self.assertion_theorem_with(name, effect, None);
431    }
432
433    /// An assertion with how it is discharged, such as `runtime-assertion`.
434    pub fn assertion_theorem_with(&mut self, name: &str, effect: &Effect, discharge: Option<&str>) {
435        let span = match effect {
436            Effect::Print { span, .. }
437            | Effect::Let { span, .. }
438            | Effect::Assert { span, .. }
439            | Effect::Output { span, .. }
440            | Effect::Unwrap { span, .. } => *span,
441        };
442        self.theorems.push(TheoremRecord {
443            source: format!(
444                "main:assert@{}",
445                span.map_or_else(|| "?".to_owned(), |span| span.start.to_string())
446            ),
447            target: name.to_owned(),
448            kind: "assertion".to_owned(),
449            closed_goal: true,
450            discharge: discharge.map(str::to_owned),
451            check: None,
452        });
453    }
454
455    #[must_use]
456    pub fn assumption_list(&self) -> Vec<Assumption> {
457        self.assumptions.clone()
458    }
459
460    #[must_use]
461    pub fn encoding_list(&self) -> Vec<Encoding> {
462        self.encodings.clone()
463    }
464
465    /// The emitted result with this state's contract.
466    #[must_use]
467    pub fn finish(&self, text: String, entry: Option<String>) -> Emitted {
468        Emitted {
469            language: self.language,
470            text,
471            preludes: Vec::new(),
472            definitions: Vec::new(),
473            mappings: self.mappings.clone(),
474            assumptions: self.assumption_list(),
475            encodings: self.encoding_list(),
476            theorems: self.theorems.clone(),
477            entry,
478        }
479    }
480}
481
482fn type_dependencies(ty: &Type, found: &mut HashSet<String>) {
483    match ty {
484        Type::Data { name } => {
485            found.insert(name.clone());
486        }
487        _ => {
488            for child in ty.children() {
489                type_dependencies(child, found);
490            }
491        }
492    }
493}
494
495fn expr_dependencies(expr: &Expr, found: &mut HashSet<String>) {
496    type_dependencies(&expr.ty, found);
497    match &expr.node {
498        Node::Call { func, .. } | Node::FunctionRef { func } => {
499            found.insert(func.clone());
500        }
501        Node::Ctor { data, .. } => {
502            found.insert(data.clone());
503        }
504        Node::Binary {
505            domain: Some(domain),
506            ..
507        } => type_dependencies(domain, found),
508        Node::Cast { from, to, .. } => {
509            type_dependencies(from, found);
510            type_dependencies(to, found);
511        }
512        Node::Match { cases, .. } => {
513            for kase in cases {
514                if let Pattern::Ctor { data, .. } = &kase.pattern {
515                    found.insert(data.clone());
516                }
517            }
518        }
519        _ => {}
520    }
521    for child in expr.children() {
522        expr_dependencies(child, found);
523    }
524}
525
526fn prop_dependencies(prop: &Prop, found: &mut HashSet<String>) {
527    match prop {
528        Prop::Forall { binders, body } => {
529            for binder in binders {
530                type_dependencies(&binder.ty, found);
531            }
532            prop_dependencies(body, found);
533        }
534        Prop::And { left, right } | Prop::Or { left, right } | Prop::Implies { left, right } => {
535            prop_dependencies(left, found);
536            prop_dependencies(right, found);
537        }
538        Prop::Not { arg } => prop_dependencies(arg, found),
539        Prop::Bool { expr } => expr_dependencies(expr, found),
540        other => {
541            if let Some((_, comparison)) = other.comparison() {
542                expr_dependencies(&comparison.left, found);
543                expr_dependencies(&comparison.right, found);
544                type_dependencies(&comparison.domain, found);
545            }
546        }
547    }
548}
549
550/// An operation that may abort, which `output` threads as a value before a pure target sees it.
551///
552/// # Panics
553/// Always: the emitter met a node the threading should have rewritten.
554pub fn unthreaded(what: &str) -> ! {
555    panic!("{what} reaches a pure target's emitter without its abort threaded")
556}
557
558/// Declarations every declaration refers to (types, functions, constructors, lemmas).
559#[must_use]
560pub fn dependencies(entry: &Decl) -> HashSet<String> {
561    fn lemmas(plan: &Plan, found: &mut HashSet<String>) {
562        match plan {
563            Plan::Close { hints } => {
564                found.extend(hints.lemmas.iter().cloned());
565                found.extend(hints.unfold.iter().cloned());
566            }
567            Plan::Induction(split) | Plan::Cases(split) => {
568                for kase in &split.cases {
569                    lemmas(&kase.plan, found);
570                }
571            }
572        }
573    }
574    let mut found = HashSet::new();
575    match entry {
576        Decl::Data(data) => {
577            for ctor in &data.ctors {
578                for field in &ctor.fields {
579                    type_dependencies(&field.ty, &mut found);
580                }
581            }
582        }
583        Decl::Fn(function) => {
584            for param in &function.params {
585                type_dependencies(&param.ty, &mut found);
586            }
587            type_dependencies(&function.ret, &mut found);
588            expr_dependencies(&function.body, &mut found);
589        }
590        Decl::Theorem(theorem) => {
591            for binder in &theorem.binders {
592                type_dependencies(&binder.ty, &mut found);
593            }
594            prop_dependencies(&theorem.prop, &mut found);
595            lemmas(&theorem.proof.plan, &mut found);
596        }
597    }
598    found.remove(entry.full_name());
599    found
600}
601
602/// Whether a node depends on declarations of a kind, directly or not.
603pub struct Dependence {
604    marked: HashSet<String>,
605    /// Whether a node with a Number-typed part depends by itself.
606    floats: bool,
607}
608
609impl Dependence {
610    /// Whether a node computes with JavaScript Numbers: it has a
611    /// Number-typed part, or uses a declaration that does.
612    #[must_use]
613    pub fn numbers(program: &Program) -> Self {
614        let marked = program
615            .declarations
616            .iter()
617            .filter(|entry| !matches!(entry, Decl::Theorem(_)) && mentions_float(entry))
618            .map(|entry| entry.full_name().to_owned())
619            .collect();
620        Self::closed(program, marked, true)
621    }
622
623    /// Whether a node calls a recursive function with no decreasing
624    /// argument: Lean defines those as partial defs, whose equations the
625    /// kernel cannot unfold.
626    #[must_use]
627    pub fn partial(program: &Program) -> Self {
628        let marked = program
629            .declarations
630            .iter()
631            .filter(|entry| {
632                matches!(entry, Decl::Fn(function)
633                    if function.mutual || (function.recursive && function.decreasing.is_none()))
634            })
635            .map(|entry| entry.full_name().to_owned())
636            .collect();
637        Self::closed(program, marked, false)
638    }
639
640    fn closed(program: &Program, mut numeric: HashSet<String>, floats: bool) -> Self {
641        let uses: Vec<(String, HashSet<String>)> = program
642            .declarations
643            .iter()
644            .map(|entry| (entry.full_name().to_owned(), dependencies(entry)))
645            .collect();
646        let mut grew = true;
647        while grew {
648            grew = false;
649            for (name, used) in &uses {
650                if !numeric.contains(name) && used.iter().any(|name| numeric.contains(name)) {
651                    numeric.insert(name.clone());
652                    grew = true;
653                }
654            }
655        }
656        Self {
657            marked: numeric,
658            floats,
659        }
660    }
661
662    #[must_use]
663    pub fn prop(&self, prop: &Prop) -> bool {
664        let mut found = HashSet::new();
665        prop_dependencies(prop, &mut found);
666        (self.floats && mentions_float(prop)) || found.iter().any(|name| self.marked.contains(name))
667    }
668
669    #[must_use]
670    pub fn expr(&self, expr: &Expr) -> bool {
671        let mut found = HashSet::new();
672        expr_dependencies(expr, &mut found);
673        (self.floats && mentions_float(expr)) || found.iter().any(|name| self.marked.contains(name))
674    }
675}
676
677/// True when a node has a part of type `float`.
678fn mentions_float(node: &impl Serialize) -> bool {
679    fn visit(value: &serde_json::Value) -> bool {
680        match value {
681            serde_json::Value::Array(items) => items.iter().any(visit),
682            serde_json::Value::Object(fields) => {
683                fields.get("kind").and_then(serde_json::Value::as_str) == Some("float")
684                    || fields.values().any(visit)
685            }
686            _ => false,
687        }
688    }
689    serde_json::to_value(node).is_ok_and(|value| visit(&value))
690}
691
692/// Each function the checker marked mutual, mapped to its group.
693///
694/// A group is the functions it calls that call it back, directly or not,
695/// itself included, in source order. A function on a cycle of calls is itself
696/// mutual, so the cycles run through mutual functions only.
697#[must_use]
698pub fn mutual_groups(program: &Program) -> HashMap<String, Vec<&Decl>> {
699    let members: Vec<&Decl> = program
700        .declarations
701        .iter()
702        .filter(|entry| matches!(entry, Decl::Fn(function) if function.mutual))
703        .collect();
704    let calls: HashMap<&str, HashSet<String>> = members
705        .iter()
706        .map(|entry| (entry.full_name(), dependencies(entry)))
707        .collect();
708    let reached = |from: &str| {
709        let mut seen: HashSet<String> = HashSet::from([from.to_owned()]);
710        let mut stack = vec![from.to_owned()];
711        while let Some(name) = stack.pop() {
712            for next in calls.get(name.as_str()).into_iter().flatten() {
713                if calls.contains_key(next.as_str()) && seen.insert(next.clone()) {
714                    stack.push(next.clone());
715                }
716            }
717        }
718        seen
719    };
720    let reach: HashMap<&str, HashSet<String>> = members
721        .iter()
722        .map(|entry| (entry.full_name(), reached(entry.full_name())))
723        .collect();
724    members
725        .iter()
726        .map(|entry| {
727            let group = members
728                .iter()
729                .copied()
730                .filter(|other| {
731                    reach[entry.full_name()].contains(other.full_name())
732                        && reach[other.full_name()].contains(entry.full_name())
733                })
734                .collect();
735            (entry.full_name().to_owned(), group)
736        })
737        .collect()
738}
739
740/// Declarations in an order where each follows everything it uses.
741///
742/// Source order is kept where possible and, among ready declarations, the
743/// ones in the module being emitted come first so modules stay contiguous.
744///
745/// # Errors
746/// On cyclic declarations, and on modules that would have to be reopened
747/// when `require_contiguous_modules` is set.
748pub fn order_declarations(
749    program: &Program,
750    require_contiguous_modules: bool,
751) -> Result<Vec<&Decl>> {
752    let entries = &program.declarations;
753    let position: HashMap<&str, usize> = entries
754        .iter()
755        .enumerate()
756        .map(|(index, entry)| (entry.full_name(), index))
757        .collect();
758    let pending: Vec<HashSet<String>> = entries.iter().map(dependencies).collect();
759    // A group of mutually recursive functions is ready, and placed, as one.
760    let groups = mutual_groups(program);
761    let unit = |index: usize| -> Vec<&Decl> {
762        groups
763            .get(entries[index].full_name())
764            .cloned()
765            .unwrap_or_else(|| vec![&entries[index]])
766    };
767    let mut done: HashSet<&str> = HashSet::new();
768    let mut order: Vec<&Decl> = Vec::new();
769    let mut current: &[String] = &[];
770    while order.len() < entries.len() {
771        let mut ready: Vec<usize> = (0..entries.len())
772            .filter(|&index| {
773                let members = unit(index);
774                !done.contains(entries[index].full_name())
775                    && members.iter().all(|member| {
776                        pending[position[member.full_name()]].iter().all(|name| {
777                            done.contains(name.as_str())
778                                || !position.contains_key(name.as_str())
779                                || members.iter().any(|other| other.full_name() == name)
780                        })
781                    })
782            })
783            .collect();
784        if ready.is_empty() {
785            let stuck = entries
786                .iter()
787                .find(|entry| !done.contains(entry.full_name()))
788                .expect("some declaration is pending");
789            return Err(unsupported(
790                "cyclic declarations",
791                &format!(
792                    "{} depends on declarations that depend on it, which needs mutual definitions",
793                    stuck.full_name()
794                ),
795                stuck.span(),
796            ));
797        }
798        let shared = |index: usize| {
799            let path = entries[index].module_path();
800            current
801                .iter()
802                .zip(path)
803                .take_while(|(left, right)| left == right)
804                .count()
805        };
806        ready.sort_by(|&left, &right| shared(right).cmp(&shared(left)).then(left.cmp(&right)));
807        let next = &entries[ready[0]];
808        for member in unit(ready[0]) {
809            if member.module_path() != next.module_path() {
810                return Err(unsupported(
811                    "mutual recursion across modules",
812                    &format!(
813                        "{} and {} are mutually recursive in different modules; the target defines them together in one module",
814                        next.full_name(),
815                        member.full_name()
816                    ),
817                    member.span(),
818                ));
819            }
820            order.push(member);
821            done.insert(member.full_name());
822        }
823        current = next.module_path();
824    }
825    if require_contiguous_modules {
826        let mut closed: HashSet<String> = HashSet::new();
827        let mut open: &[String] = &[];
828        for entry in &order {
829            let path = entry.module_path();
830            for depth in 0..open.len() {
831                if path.get(depth) != Some(&open[depth]) {
832                    for index in depth..open.len() {
833                        closed.insert(open[..=index].join("."));
834                    }
835                    break;
836                }
837            }
838            for depth in 1..=path.len() {
839                let key = path[..depth].join(".");
840                if closed.contains(&key) {
841                    return Err(unsupported(
842                        "interleaved modules",
843                        &format!(
844                            "module {key} would have to be reopened after its declarations depend on later ones; the target cannot reopen a module"
845                        ),
846                        entry.span(),
847                    ));
848                }
849            }
850            open = path;
851        }
852    }
853    Ok(order)
854}