Skip to main content

charon_lib/transform/add_missing_info/
reorder_decls.rs

1//! Compute an ordering on declarations that:
2//! - Detects mutually-recursive groups;
3//! - Always orders an item before any of its uses (except for recursive cases);
4//! - Otherwise keeps a stable order.
5//!
6//! Aeneas needs this because proof assistant languages are sensitive to declaration order and need
7//! to be explicit about mutual recursion. This should come useful for translation to any other
8//! language with these properties.
9use crate::common::*;
10use crate::options::TranslateOptions;
11use crate::transform::TransformCtx;
12use crate::ullbc_ast::*;
13use derive_generic_visitor::*;
14use itertools::Itertools;
15use petgraph::graphmap::DiGraphMap;
16use std::collections::{HashMap, HashSet};
17use std::fmt::{Debug, Display, Error};
18use std::vec::Vec;
19
20use crate::transform::ctx::TransformPass;
21
22impl<Id: Copy> GDeclarationGroup<Id> {
23    pub fn get_ids(&self) -> &[Id] {
24        use GDeclarationGroup::*;
25        match self {
26            NonRec(id) => std::slice::from_ref(id),
27            Rec(ids) => ids.as_slice(),
28        }
29    }
30
31    pub fn get_any_trans_ids(&self) -> Vec<ItemId>
32    where
33        Id: Into<ItemId>,
34    {
35        self.get_ids().iter().copied().map(|id| id.into()).collect()
36    }
37
38    fn make_group(is_rec: bool, ids: Vec<ItemId>) -> Self
39    where
40        Id: TryFrom<ItemId>,
41        Id::Error: Debug,
42    {
43        let ids: Vec<_> = ids.into_iter().map(|x| x.try_into().unwrap()).collect();
44        if is_rec {
45            GDeclarationGroup::Rec(ids)
46        } else {
47            assert!(ids.len() == 1);
48            GDeclarationGroup::NonRec(ids[0])
49        }
50    }
51
52    fn to_mixed(&self) -> GDeclarationGroup<ItemId>
53    where
54        Id: Into<ItemId>,
55    {
56        match self {
57            GDeclarationGroup::NonRec(x) => GDeclarationGroup::NonRec((*x).into()),
58            GDeclarationGroup::Rec(_) => GDeclarationGroup::Rec(self.get_any_trans_ids()),
59        }
60    }
61}
62
63impl DeclarationGroup {
64    fn make_group(is_rec: bool, ids: Vec<ItemId>) -> Self {
65        let id0 = ids[0];
66        let all_same_kind = ids
67            .iter()
68            .all(|id| id0.variant_index_arity() == id.variant_index_arity());
69        match id0 {
70            _ if !all_same_kind => {
71                DeclarationGroup::Mixed(GDeclarationGroup::make_group(is_rec, ids))
72            }
73            ItemId::Type(_) => DeclarationGroup::Type(GDeclarationGroup::make_group(is_rec, ids)),
74            ItemId::Fun(_) => DeclarationGroup::Fun(GDeclarationGroup::make_group(is_rec, ids)),
75            ItemId::Global(_) => {
76                DeclarationGroup::Global(GDeclarationGroup::make_group(is_rec, ids))
77            }
78            ItemId::TraitDecl(_) => {
79                DeclarationGroup::TraitDecl(GDeclarationGroup::make_group(is_rec, ids))
80            }
81            ItemId::TraitImpl(_) => {
82                DeclarationGroup::TraitImpl(GDeclarationGroup::make_group(is_rec, ids))
83            }
84        }
85    }
86
87    pub fn to_mixed_group(&self) -> GDeclarationGroup<ItemId> {
88        use DeclarationGroup::*;
89        match self {
90            Type(gr) => gr.to_mixed(),
91            Fun(gr) => gr.to_mixed(),
92            Global(gr) => gr.to_mixed(),
93            TraitDecl(gr) => gr.to_mixed(),
94            TraitImpl(gr) => gr.to_mixed(),
95            Mixed(gr) => gr.clone(),
96        }
97    }
98
99    pub fn get_ids(&self) -> Vec<ItemId> {
100        use DeclarationGroup::*;
101        match self {
102            Type(gr) => gr.get_any_trans_ids(),
103            Fun(gr) => gr.get_any_trans_ids(),
104            Global(gr) => gr.get_any_trans_ids(),
105            TraitDecl(gr) => gr.get_any_trans_ids(),
106            TraitImpl(gr) => gr.get_any_trans_ids(),
107            Mixed(gr) => gr.get_any_trans_ids(),
108        }
109    }
110}
111
112impl<Id: Display> Display for GDeclarationGroup<Id> {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), Error> {
114        match self {
115            GDeclarationGroup::NonRec(id) => write!(f, "non-rec: {id}"),
116            GDeclarationGroup::Rec(ids) => {
117                write!(
118                    f,
119                    "rec: {}",
120                    pretty_display_list(|id| format!("    {id}"), ids)
121                )
122            }
123        }
124    }
125}
126
127impl Display for DeclarationGroup {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), Error> {
129        match self {
130            DeclarationGroup::Type(decl) => write!(f, "{{ Type(s): {decl} }}"),
131            DeclarationGroup::Fun(decl) => write!(f, "{{ Fun(s): {decl} }}"),
132            DeclarationGroup::Global(decl) => write!(f, "{{ Global(s): {decl} }}"),
133            DeclarationGroup::TraitDecl(decl) => write!(f, "{{ Trait decls(s): {decl} }}"),
134            DeclarationGroup::TraitImpl(decl) => write!(f, "{{ Trait impl(s): {decl} }}"),
135            DeclarationGroup::Mixed(decl) => write!(f, "{{ Mixed items: {decl} }}"),
136        }
137    }
138}
139
140#[derive(Default)]
141pub struct Deps {
142    /// The dependency graph between translated items. We're careful to only add items that got
143    /// translated.
144    graph: DiGraphMap<ItemId, ()>,
145    unprocessed: Vec<ItemId>,
146    visited: HashSet<ItemId>,
147}
148
149/// We use this when computing the graph
150#[derive(Visitor)]
151pub struct DepsForItem<'a> {
152    ctx: &'a TransformCtx,
153    deps: &'a mut Deps,
154    current_id: ItemId,
155    // Each item countains its own id; we dont' want to count that as a self-reference. Hence the
156    // first time we see its own id, we skip.
157    seen_current_id: bool,
158    // We use this to track the trait impl block the current item belongs to
159    // (if relevant).
160    //
161    // We use this to ignore the references to the parent impl block.
162    //
163    // If we don't do so, when computing our dependency graph we end up with
164    // mutually recursive trait impl blocks/trait method impls in the presence
165    // of associated types (the deepest reason is that we don't normalize the
166    // types we query from rustc when translating the types from function
167    // signatures - we avoid doing so because as of now it makes resolving
168    // the trait params harder: if we get normalized types, we have to
169    // implement a normalizer on our side to make sure we correctly match
170    // types...).
171    //
172    //
173    // For instance, the problem happens if in Rust we have:
174    // ```text
175    // pub trait WithConstTy {
176    //     type W;
177    //     fn f(x: &mut Self::W);
178    // }
179    //
180    // impl WithConstTy for bool {
181    //     type W = u64;
182    //     fn f(_: &mut Self::W) {}
183    // }
184    // ```
185    //
186    // In LLBC we get:
187    //
188    // ```text
189    // impl traits::Bool::0 : traits::WithConstTy<bool>
190    // {
191    //     type W = u64 with []
192    //     fn f = traits::Bool::0::f
193    // }
194    //
195    // fn traits::Bool::0::f<@R0>(@1: &@R0 mut (traits::Bool::0::W)) { .. }
196    // //                                       ^^^^^^^^^^^^^^^
197    // //                                    refers to the trait impl
198    // ```
199    parent_trait_impl: Option<TraitImplId>,
200    parent_trait_decl: Option<TraitDeclId>,
201}
202
203impl Deps {
204    fn visitor_for_item<'a>(
205        &'a mut self,
206        ctx: &'a TransformCtx,
207        item: ItemRef<'_>,
208    ) -> DepsForItem<'a> {
209        let current_id = item.id();
210        self.graph.add_node(current_id);
211
212        let mut for_item = DepsForItem {
213            ctx,
214            deps: self,
215            seen_current_id: false,
216            current_id,
217            parent_trait_impl: None,
218            parent_trait_decl: None,
219        };
220
221        // Add the id of the impl/trait this item belongs to, if necessary
222        match item.parent_info() {
223            ItemSource::TraitDecl { trait_ref, .. } => {
224                for_item.parent_trait_decl = Some(trait_ref.id)
225            }
226            ItemSource::TraitImpl { impl_ref, .. } => {
227                for_item.parent_trait_impl = Some(impl_ref.id)
228            }
229            _ => {}
230        }
231
232        for_item
233    }
234}
235
236impl DepsForItem<'_> {
237    fn insert_node(&mut self, tgt: impl Into<ItemId>) {
238        let tgt = tgt.into();
239        // Only add translated items.
240        if self.ctx.translated.get_item(tgt).is_some() && !self.deps.visited.contains(&tgt) {
241            self.deps.unprocessed.push(tgt);
242        }
243    }
244    fn insert_edge(&mut self, tgt: impl Into<ItemId>) {
245        let tgt = tgt.into();
246        if tgt == self.current_id && !self.seen_current_id {
247            // Each item contains its own id; this is a hack to avoid considering that as a self
248            // loop.
249            self.seen_current_id = true;
250            return;
251        }
252        self.insert_node(tgt);
253        // Only add translated items.
254        if self.ctx.translated.get_item(tgt).is_some() {
255            self.deps.graph.add_edge(self.current_id, tgt, ());
256        }
257    }
258}
259
260impl VisitAst for DepsForItem<'_> {
261    fn enter_type_decl_id(&mut self, id: &TypeDeclId) {
262        self.insert_edge(*id);
263    }
264
265    fn enter_global_decl_id(&mut self, id: &GlobalDeclId) {
266        self.insert_edge(*id);
267    }
268
269    fn enter_trait_impl_id(&mut self, id: &TraitImplId) {
270        // If the impl is the impl this item belongs to, we ignore it
271        // TODO: this is not very satisfying but this is the only way we have of preventing
272        // mutually recursive groups between method impls and trait impls in the presence of
273        // associated types...
274        if self.parent_trait_impl != Some(*id) {
275            self.insert_edge(*id);
276        }
277    }
278
279    fn enter_trait_decl_id(&mut self, id: &TraitDeclId) {
280        // If the trait is the trait this item belongs to, we ignore it. This is to avoid mutually
281        // recursive groups between e.g. traits decls and their globals. We treat methods
282        // specifically.
283        if self.parent_trait_decl != Some(*id) {
284            self.insert_edge(*id);
285        }
286    }
287
288    fn enter_fun_decl_id(&mut self, id: &FunDeclId) {
289        self.insert_edge(*id);
290    }
291
292    fn visit_item_meta(&mut self, meta: &ItemMeta) -> ControlFlow<Self::Break> {
293        // Don't visit the name because trait impls contain their own id in it. Attributes however
294        // can contain genuine dependencies, notably between an item and its specifications.
295        meta.attr_info.drive(self)
296    }
297    fn visit_item_source(&mut self, _: &ItemSource) -> ControlFlow<Self::Break> {
298        // Don't look inside to avoid recording a dependency from a method impl to the impl block
299        // it belongs to.
300        Continue(())
301    }
302}
303
304fn compute_declarations_graph(ctx: &TransformCtx) -> DiGraphMap<ItemId, ()> {
305    let mut deps = Deps::default();
306    // Start from the items included in `start_from`. We've mostly only translated items accessible
307    // from that, but some passes render items inaccessible again, which we filter out here.
308    deps.unprocessed = ctx
309        .translated
310        .all_items()
311        .filter(|item| {
312            ctx.options
313                .start_from
314                .iter()
315                .any(|pat| pat.matches(&ctx.translated, item.item_meta()))
316        })
317        .map(|item| item.id())
318        .collect();
319
320    // Explore reachable items.
321    while let Some(id) = deps.unprocessed.pop() {
322        if !deps.visited.insert(id) {
323            continue;
324        }
325        let Some(item) = ctx.translated.get_item(id) else {
326            continue;
327        };
328        let mut visitor = deps.visitor_for_item(ctx, item);
329        match item {
330            ItemRef::Type(..) | ItemRef::TraitImpl(..) | ItemRef::Global(..) => {
331                let _ = item.drive(&mut visitor);
332            }
333            ItemRef::Fun(d) => {
334                let FunDecl {
335                    def_id,
336                    item_meta,
337                    generics,
338                    signature,
339                    src,
340                    is_global_initializer: _,
341                    body,
342                } = d;
343                let _ = def_id.drive(&mut visitor); // For `seen_current_id`
344                let _ = item_meta.attr_info.drive(&mut visitor);
345                // Skip `d.is_global_initializer` to avoid incorrect mutual dependencies.
346                // TODO: add `is_global_initializer` to `ItemSource`.
347                let _ = generics.drive(&mut visitor);
348                let _ = signature.drive(&mut visitor);
349                let _ = body.drive(&mut visitor);
350                if let ItemSource::TraitDecl { trait_ref, .. } = src {
351                    visitor.insert_edge(trait_ref.id);
352                }
353            }
354            ItemRef::TraitDecl(d) => {
355                let TraitDecl {
356                    def_id,
357                    item_meta: _,
358                    generics,
359                    implied_clauses: parent_clauses,
360                    consts,
361                    types,
362                    methods,
363                    vtable,
364                } = d;
365                let _ = def_id.drive(&mut visitor); // For `seen_current_id`
366                // Visit the traits referenced in the generics
367                let _ = generics.drive(&mut visitor);
368
369                // Visit the parent clauses
370                let _ = parent_clauses.drive(&mut visitor);
371
372                // Visit the items
373                let _ = types.drive(&mut visitor);
374                let _ = vtable.drive(&mut visitor);
375
376                // We consider that a trait decl only contains the function/constant signatures.
377                // Therefore we don't explore the default const/method ids.
378                for assoc_const in consts {
379                    let TraitAssocConst {
380                        name: _,
381                        attr_info: _,
382                        ty,
383                        default,
384                    } = assoc_const;
385                    let _ = ty.drive(&mut visitor);
386                    if let Some(gref) = default {
387                        visitor.insert_node(gref.id); // Still count the item as reachable.
388                        let _ = gref.generics.drive(&mut visitor);
389                    }
390                }
391                for bound_method in methods {
392                    let _ = bound_method.params.drive(&mut visitor);
393                    let _ = bound_method.skip_binder.signature.drive(&mut visitor);
394                    if let Some(funref) = &bound_method.skip_binder.default {
395                        visitor.insert_node(funref.id); // Still count the item as reachable.
396                        let _ = funref.generics.drive(&mut visitor);
397                    }
398                }
399            }
400        }
401    }
402    deps.graph
403}
404
405fn compute_reordered_decls(ctx: &mut TransformCtx) -> DeclarationsGroups {
406    // Build the graph of dependencies between items.
407    let graph = compute_declarations_graph(ctx);
408
409    // Pre-sort files to limit the number of costly string comparisons. Maps file ids to an index
410    // that reflects ordering on the crates (with `core` and `std` sorted first) and file names.
411    let sorted_file_ids: IndexMap<FileId, usize> = ctx
412        .translated
413        .files
414        .indices()
415        .sorted_by_cached_key(|&file_id| {
416            let file = &ctx.translated.files[file_id];
417            let is_std = file.crate_name == "std" || file.crate_name == "core";
418            (!is_std, &file.crate_name, &file.name)
419        })
420        .enumerate()
421        .sorted_by_key(|(_i, file_id)| *file_id)
422        .map(|(i, _file_id)| i)
423        .collect();
424    assert_eq!(ctx.translated.files.len(), sorted_file_ids.slot_count());
425
426    // We sort items as follows: std items, then items from foreign crates (sorted by crate name),
427    // then local items. Within a crate, we sort by file then by source order.
428    let sort_by = |item: &ItemRef| {
429        let item_meta = item.item_meta();
430        let span = item_meta.span.data;
431        let file_name_order = sorted_file_ids.get(span.file_id);
432        (
433            item_meta.is_local,
434            file_name_order,
435            span.beg,
436            item_meta.name.mono_args().cloned(),
437            item.id(),
438        )
439    };
440    // We record for each item the order in which we're sorting it, to make `sort_by` cheap.
441    let item_sorted_index: HashMap<ItemId, usize> = ctx
442        .translated
443        .all_items()
444        .sorted_by_cached_key(sort_by)
445        .enumerate()
446        .map(|(i, item)| (item.id(), i))
447        .collect();
448    let sort_by = |id: &ItemId| item_sorted_index.get(id).unwrap();
449
450    // Compute SCCs (Strongly Connected Components) for the graph in a way that matches the chosen
451    // order as much as possible.
452    let reordered_sccs = super::sccs::ordered_scc(&graph, sort_by);
453
454    // Convert to a list of declarations.
455    let reordered_decls = reordered_sccs
456        .into_iter()
457        // This can happen if we failed to translate the item in this group.
458        .filter(|scc| !scc.is_empty())
459        .map(|scc| {
460            // If an SCC has length one, the declaration may be simply recursive: we determine whether
461            // it is the case by checking if the def id is in its own set of dependencies.
462            // Trait declarations often refer to `Self`, which means they are often considered as
463            // recursive by our analysis. So we cheat an declare them non-recursive.
464            // TODO: do something more precise. What is important is that we never use the "whole" self
465            // clause as argument, but rather projections over the self clause (like `<Self as
466            // Foo>::u`, in the declaration for `Foo`).
467            let id0 = scc[0];
468            let is_non_rec =
469                scc.len() == 1 && (id0.is_trait_decl() || !graph.neighbors(id0).contains(&id0));
470
471            DeclarationGroup::make_group(!is_non_rec, scc)
472        })
473        .collect();
474
475    trace!("{:?}", reordered_decls);
476    reordered_decls
477}
478
479pub struct Transform;
480impl TransformPass for Transform {
481    fn should_run(&self, options: &TranslateOptions) -> bool {
482        !options.no_reorder_decls
483    }
484
485    fn transform_ctx(&self, ctx: &mut TransformCtx) {
486        let reordered_decls = compute_reordered_decls(ctx);
487        ctx.translated.ordered_decls = Some(reordered_decls);
488    }
489}