charon_lib/transform/add_missing_info/
reorder_decls.rs1use crate::options::TranslateOptions;
10use crate::transform::TransformCtx;
11use crate::ullbc_ast::*;
12use crate::utils::*;
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 graph: DiGraphMap<ItemId, ()>,
145 unprocessed: Vec<ItemId>,
146 visited: HashSet<ItemId>,
147}
148
149#[derive(Visitor)]
151pub struct DepsForItem<'a> {
152 ctx: &'a TransformCtx,
153 deps: &'a mut Deps,
154 current_id: ItemId,
155 seen_current_id: bool,
158 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 match item {
223 ItemRef::Fun(FunDecl {
224 src: FunSource::TraitDefault { trait_ref, .. },
225 ..
226 })
227 | ItemRef::Global(GlobalDecl {
228 src: GlobalSource::TraitDefault { trait_ref, .. },
229 ..
230 }) => for_item.parent_trait_decl = Some(trait_ref.id),
231 ItemRef::Fun(FunDecl {
232 src: FunSource::TraitImpl { impl_ref, .. },
233 ..
234 })
235 | ItemRef::Global(GlobalDecl {
236 src: GlobalSource::TraitImpl { impl_ref, .. },
237 ..
238 }) => for_item.parent_trait_impl = Some(impl_ref.id),
239 _ => {}
240 }
241
242 for_item
243 }
244}
245
246impl DepsForItem<'_> {
247 fn insert_node(&mut self, tgt: impl Into<ItemId>) {
248 let tgt = tgt.into();
249 if self.ctx.translated.get_item(tgt).is_some() && !self.deps.visited.contains(&tgt) {
251 self.deps.unprocessed.push(tgt);
252 }
253 }
254 fn insert_edge(&mut self, tgt: impl Into<ItemId>) {
255 let tgt = tgt.into();
256 if tgt == self.current_id && !self.seen_current_id {
257 self.seen_current_id = true;
260 return;
261 }
262 self.insert_node(tgt);
263 if self.ctx.translated.get_item(tgt).is_some() {
265 self.deps.graph.add_edge(self.current_id, tgt, ());
266 }
267 }
268}
269
270impl VisitAst for DepsForItem<'_> {
271 fn enter_type_decl_id(&mut self, id: &TypeDeclId) {
272 self.insert_edge(*id);
273 }
274
275 fn enter_global_decl_id(&mut self, id: &GlobalDeclId) {
276 self.insert_edge(*id);
277 }
278
279 fn enter_trait_impl_id(&mut self, id: &TraitImplId) {
280 if self.parent_trait_impl != Some(*id) {
285 self.insert_edge(*id);
286 }
287 }
288
289 fn enter_trait_decl_id(&mut self, id: &TraitDeclId) {
290 if self.parent_trait_decl != Some(*id) {
294 self.insert_edge(*id);
295 }
296 }
297
298 fn enter_fun_decl_id(&mut self, id: &FunDeclId) {
299 self.insert_edge(*id);
300 }
301
302 fn visit_trait_assoc_const(
303 &mut self,
304 assoc_const: &TraitAssocConst,
305 ) -> ControlFlow<Self::Break> {
306 let TraitAssocConst {
307 name: _,
308 attr_info: _,
309 ty,
310 default,
311 } = assoc_const;
312 ty.drive(self)?;
313 if let Some(gref) = default {
316 self.insert_node(gref.id); gref.generics.drive(self)?;
318 }
319 Continue(())
320 }
321
322 fn visit_trait_method(&mut self, method: &TraitMethod) -> ControlFlow<Self::Break> {
323 let TraitMethod {
324 name: _,
325 item_meta: _,
326 signature,
327 default,
328 } = method;
329 signature.drive(self)?;
332 if let Some(funref) = default {
333 self.insert_node(funref.id); funref.generics.drive(self)?;
335 }
336 Continue(())
337 }
338
339 fn visit_item_meta(&mut self, meta: &ItemMeta) -> ControlFlow<Self::Break> {
340 meta.attr_info.drive(self)
343 }
344
345 fn visit_attribute(&mut self, attr: &Attribute) -> ControlFlow<Self::Break> {
346 match attr {
348 Attribute::IsContract { .. } => Continue(()),
349 _ => self.visit_inner(attr),
350 }
351 }
352
353 fn visit_type_source(&mut self, _: &TypeSource) -> ControlFlow<Self::Break> {
355 Continue(())
356 }
357 fn visit_fun_source(&mut self, src: &FunSource) -> ControlFlow<Self::Break> {
358 if let FunSource::TraitDefault { trait_ref, .. } = src {
359 self.insert_edge(trait_ref.id);
360 }
361 Continue(())
362 }
363 fn visit_global_source(&mut self, _: &GlobalSource) -> ControlFlow<Self::Break> {
364 Continue(())
365 }
366 fn visit_trait_decl_source(&mut self, _: &TraitDeclSource) -> ControlFlow<Self::Break> {
367 Continue(())
368 }
369 fn visit_trait_impl_source(&mut self, _: &TraitImplSource) -> ControlFlow<Self::Break> {
370 Continue(())
371 }
372}
373
374fn compute_declarations_graph(ctx: &TransformCtx) -> DiGraphMap<ItemId, ()> {
375 let mut deps = Deps::default();
376 deps.unprocessed = ctx
379 .translated
380 .all_items()
381 .filter(|item| {
382 ctx.options
383 .start_from
384 .iter()
385 .any(|pat| pat.matches(&ctx.translated, item.item_meta()))
386 })
387 .map(|item| item.id())
388 .collect();
389
390 while let Some(id) = deps.unprocessed.pop() {
392 if deps.visited.insert(id)
393 && let Some(item) = ctx.translated.get_item(id)
394 {
395 let mut visitor = deps.visitor_for_item(ctx, item);
396 item.drive(&mut visitor);
397 }
398 }
399 deps.graph
400}
401
402fn compute_reordered_decls(ctx: &mut TransformCtx) -> Vec<DeclarationGroup> {
403 let graph = compute_declarations_graph(ctx);
405
406 let sorted_file_ids: IndexMap<FileId, usize> = ctx
409 .translated
410 .files
411 .indices()
412 .sorted_by_cached_key(|&file_id| {
413 let file = &ctx.translated.files[file_id];
414 let is_std = file.crate_name == "std" || file.crate_name == "core";
415 (!is_std, &file.crate_name, &file.name)
416 })
417 .enumerate()
418 .sorted_by_key(|(_i, file_id)| *file_id)
419 .map(|(i, _file_id)| i)
420 .collect();
421 assert_eq!(ctx.translated.files.len(), sorted_file_ids.slot_count());
422
423 let sort_by = |item: &ItemRef| {
426 let item_meta = item.item_meta();
427 let span = item_meta.span.data;
428 let file_name_order = sorted_file_ids.get(span.file_id);
429 (
430 item_meta.is_local,
431 file_name_order,
432 span.beg,
433 item_meta.name.mono_args().cloned(),
434 item.id(),
435 )
436 };
437 let item_sorted_index: HashMap<ItemId, usize> = ctx
439 .translated
440 .all_items()
441 .sorted_by_cached_key(sort_by)
442 .enumerate()
443 .map(|(i, item)| (item.id(), i))
444 .collect();
445 let sort_by = |id: &ItemId| item_sorted_index.get(id).unwrap();
446
447 let reordered_sccs = super::sccs::ordered_scc(&graph, sort_by);
450
451 let reordered_decls = reordered_sccs
453 .into_iter()
454 .filter(|scc| !scc.is_empty())
456 .map(|scc| {
457 let id0 = scc[0];
465 let is_non_rec =
466 scc.len() == 1 && (id0.is_trait_decl() || !graph.neighbors(id0).contains(&id0));
467
468 DeclarationGroup::make_group(!is_non_rec, scc)
469 })
470 .collect();
471
472 trace!("{:?}", reordered_decls);
473 reordered_decls
474}
475
476pub struct Transform;
477impl TransformPass for Transform {
478 fn should_run(&self, options: &TranslateOptions) -> bool {
479 !options.no_reorder_decls
480 }
481
482 fn transform_ctx(&self, ctx: &mut TransformCtx) {
483 let reordered_decls = compute_reordered_decls(ctx);
484 ctx.translated.ordered_decls = Some(reordered_decls);
485 }
486}