Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

gc_ops: Add support for struct subtypes (#12931)

Khagan (Khan) Karimovdad2293e2446
diff --git a/crates/fuzzing/Cargo.toml b/crates/fuzzing/Cargo.toml
index 1c9c55138b..0b7955e28e 100644
--- a/crates/fuzzing/Cargo.toml
+++ b/crates/fuzzing/Cargo.toml
@@ -15,6 +15,7 @@ workspace = true
wasmtime-test-util = { workspace = true, features = ['wast'] }
[dependencies]
+wasmtime-environ = { workspace = true }
backtrace = { workspace = true }
arbitrary = { workspace = true, features = ["derive"] }
env_logger = { workspace = true }
diff --git a/crates/fuzzing/src/generators/gc_ops/mutator.rs b/crates/fuzzing/src/generators/gc_ops/mutator.rs
index 7e2f821366..8150440fbe 100644
--- a/crates/fuzzing/src/generators/gc_ops/mutator.rs
+++ b/crates/fuzzing/src/generators/gc_ops/mutator.rs
@@ -6,6 +6,7 @@ use mutatis::{
Candidates, Context, DefaultMutate, Generate, Mutate, Result as MutResult, mutators as m,
};
use smallvec::SmallVec;
+use std::collections::BTreeMap;
/// Mutator for [`Types`]: handles adding/removing types and all rec-group
/// structural mutations (duplicate, remove, merge, split, move).
@@ -32,7 +33,13 @@ impl TypesMutator {
return Ok(());
};
let tid = types.fresh_type_id(ctx.rng());
- types.insert_empty_struct(tid, gid);
+ let is_final = (ctx.rng().gen_u32() % 4) == 0;
+ let supertype = if (ctx.rng().gen_u32() % 4) == 0 {
+ ctx.rng().choose(types.type_defs.keys()).copied()
+ } else {
+ None
+ };
+ types.insert_empty_struct(tid, gid, is_final, supertype);
log::debug!("Added empty struct {tid:?} to rec group {gid:?}");
Ok(())
})?;
@@ -189,22 +196,49 @@ impl TypesMutator {
let Some(src_gid) = ctx.rng().choose(types.rec_groups.keys()).copied() else {
return Ok(());
};
- let Some(count) = types.rec_groups.get(&src_gid).map(|s| s.len()) else {
+ let Some(src_members) = types.rec_groups.get(&src_gid) else {
return Ok(());
};
- if count == 0 {
+ if src_members.is_empty() {
+ return Ok(());
+ }
+
+ // Collect (TypeId, is_final, supertype) for members of the source group.
+ let members: SmallVec<[(TypeId, bool, Option<TypeId>); 32]> = src_members
+ .iter()
+ .filter_map(|tid| {
+ types
+ .type_defs
+ .get(tid)
+ .map(|def| (*tid, def.is_final, def.supertype))
+ })
+ .collect();
+
+ if members.is_empty() {
return Ok(());
}
+ // Create a new rec group.
let new_gid = types.fresh_rec_group_id(ctx.rng());
types.insert_rec_group(new_gid);
- for _ in 0..count {
- let tid = types.fresh_type_id(ctx.rng());
- types.insert_empty_struct(tid, new_gid);
+ // Allocate fresh type ids for each member and build old-to-new map.
+ let mut old_to_new: BTreeMap<TypeId, TypeId> = BTreeMap::new();
+ for (old_tid, _, _) in &members {
+ old_to_new.insert(*old_tid, types.fresh_type_id(ctx.rng()));
}
- log::debug!("Duplicated rec group {src_gid:?} as {new_gid:?} ({count} types)");
+ // Insert duplicated defs, rewriting intra-group supertype edges to cloned ids.
+ for (old_tid, is_final, supertype) in &members {
+ let new_tid = old_to_new[old_tid];
+ let mapped_super = supertype.map(|st| *old_to_new.get(&st).unwrap_or(&st));
+ types.insert_empty_struct(new_tid, new_gid, *is_final, mapped_super);
+ }
+
+ log::debug!(
+ "Duplicated rec group {src_gid:?} as {new_gid:?} ({count} types)",
+ count = members.len()
+ );
Ok(())
})?;
Ok(())
diff --git a/crates/fuzzing/src/generators/gc_ops/ops.rs b/crates/fuzzing/src/generators/gc_ops/ops.rs
index 9c81e82d10..0c8049e7a6 100644
--- a/crates/fuzzing/src/generators/gc_ops/ops.rs
+++ b/crates/fuzzing/src/generators/gc_ops/ops.rs
@@ -3,9 +3,10 @@
use crate::generators::gc_ops::types::StackType;
use crate::generators::gc_ops::{
limits::GcOpsLimits,
- types::{CompositeType, StructType, TypeId, Types},
+ types::{CompositeType, RecGroupId, StructType, TypeId, Types},
};
use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
use wasm_encoder::{
CodeSection, ConstExpr, EntityType, ExportKind, ExportSection, Function, FunctionSection,
GlobalSection, ImportSection, Instruction, Module, RefType, TableSection, TableType,
@@ -105,12 +106,52 @@ impl GcOps {
let struct_type_base: u32 = types.len();
+ // Sort all types globally so supertypes come before subtypes.
+ // This is used to order types *within* each rec group.
+ let mut type_order = Vec::new();
+ self.types.sort_types_topo(&mut type_order);
+
+ // Build a position map so we can sort each group's members
+ // according to the global type order.
+ let type_position: BTreeMap<TypeId, usize> = type_order
+ .iter()
+ .enumerate()
+ .map(|(i, &id)| (id, i))
+ .collect();
+
+ // Topological sort of rec groups: if a type in group G has a
+ // supertype in group H, then H appears before G.
+ let mut group_order = Vec::new();
+ self.types.sort_rec_groups_topo(&mut group_order);
+
+ // For each group, collect its members sorted by the global type order.
+ let mut group_members: BTreeMap<RecGroupId, Vec<TypeId>> = BTreeMap::new();
+ for &gid in &group_order {
+ if let Some(member_set) = self.types.rec_groups.get(&gid) {
+ let mut members: Vec<TypeId> = member_set.iter().copied().collect();
+ members.sort_by_key(|tid| type_position.get(tid).copied().unwrap_or(usize::MAX));
+ group_members.insert(gid, members);
+ }
+ }
+
+ // Build the type-id-to-wasm-index map directly.
+ let mut type_ids_to_index: BTreeMap<TypeId, u32> = BTreeMap::new();
+ let mut next_idx = struct_type_base;
+ for g in &group_order {
+ if let Some(members) = group_members.get(g) {
+ for &tid in members {
+ type_ids_to_index.insert(tid, next_idx);
+ next_idx += 1;
+ }
+ }
+ }
+
let encode_ty_id = |ty_id: &TypeId| -> wasm_encoder::SubType {
let def = &self.types.type_defs[ty_id];
match &def.composite_type {
CompositeType::Struct(StructType {}) => wasm_encoder::SubType {
- is_final: true,
- supertype_idx: None,
+ is_final: def.is_final,
+ supertype_idx: def.supertype.map(|st| type_ids_to_index[&st]),
composite_type: wasm_encoder::CompositeType {
inner: wasm_encoder::CompositeInnerType::Struct(wasm_encoder::StructType {
fields: Box::new([]),
@@ -125,13 +166,12 @@ impl GcOps {
let mut struct_count = 0;
- for member_set in self.types.rec_groups.values() {
- let member_types: Vec<wasm_encoder::SubType> =
- member_set.iter().map(|tid| encode_ty_id(tid)).collect();
- let member_count = u32::try_from(member_types.len())
- .expect("member_types len should be within u32 range");
- types.ty().rec(member_types);
- struct_count += member_count;
+ // Emit rec groups in the derived order.
+ for g in &group_order {
+ let type_ids = group_members.get(g).map(|v| v.as_slice()).unwrap_or(&[]);
+ let members: Vec<wasm_encoder::SubType> = type_ids.iter().map(encode_ty_id).collect();
+ types.ty().rec(members);
+ struct_count += u32::try_from(type_ids.len()).unwrap();
}
let typed_fn_type_base: u32 = struct_type_base + struct_count;
diff --git a/crates/fuzzing/src/generators/gc_ops/tests.rs b/crates/fuzzing/src/generators/gc_ops/tests.rs
index 57f3073d8c..e3e856cbe2 100644
--- a/crates/fuzzing/src/generators/gc_ops/tests.rs
+++ b/crates/fuzzing/src/generators/gc_ops/tests.rs
@@ -59,7 +59,10 @@ fn test_ops(num_params: u32, num_globals: u32, table_size: u32) -> GcOps {
if t.limits.max_rec_groups > 0 {
for i in 0..t.limits.max_types {
let gid = RecGroupId(rng.gen_range(0..t.limits.max_rec_groups));
- t.types.insert_empty_struct(TypeId(i), gid);
+ let is_final = false;
+ let supertype = None;
+ t.types
+ .insert_empty_struct(TypeId(i), gid, is_final, supertype);
}
}
@@ -83,6 +86,7 @@ fn mutate_gc_ops_with_default_mutator() -> mutatis::Result<()> {
session.mutate(&mut ops)?;
let wasm = ops.to_wasm_binary();
+ println!("wasm: {}", wasmprinter::print_bytes(&wasm).unwrap());
crate::oracles::log_wasm(&wasm);
let mut validator = wasmparser::Validator::new_with_features(features);
@@ -192,7 +196,7 @@ fn every_op_generated() -> mutatis::Result<()> {
}
#[test]
-fn emits_empty_rec_groups_and_validates() -> mutatis::Result<()> {
+fn emits_rec_groups_and_validates() -> mutatis::Result<()> {
let _ = env_logger::try_init();
let mut ops = test_ops(5, 5, 5);
@@ -212,8 +216,16 @@ fn emits_empty_rec_groups_and_validates() -> mutatis::Result<()> {
let recs = wat.matches("(rec").count();
let structs = wat.matches("(struct)").count();
- assert_eq!(recs, 7, "expected 2 (rec) blocks, got {recs}");
- assert_eq!(structs, 10, "expected no struct types, got {structs}");
+ assert_eq!(
+ recs,
+ ops.types.rec_groups.len(),
+ "one (rec) block per rec group"
+ );
+ assert_eq!(
+ structs,
+ ops.types.type_defs.len(),
+ "one (struct) per struct type in type_defs"
+ );
Ok(())
}
@@ -287,3 +299,259 @@ fn fixup_check_types_and_indexes() -> mutatis::Result<()> {
Ok(())
}
+
+#[test]
+fn sort_types_by_supertype_orders_supertype_before_subtype_across_rec_groups() {
+ let mut types = Types::new();
+ let ga = RecGroupId(0);
+ let gb = RecGroupId(1);
+ let gc = RecGroupId(2);
+ let gd = RecGroupId(3);
+ types.insert_rec_group(ga);
+ types.insert_rec_group(gb);
+ types.insert_rec_group(gc);
+ types.insert_rec_group(gd);
+
+ let a = TypeId(0);
+ let b = TypeId(1);
+ let c = TypeId(2);
+ let d = TypeId(3);
+
+ // Cross-rec-group chain: C <: A <: B <: D.
+ types.insert_empty_struct(a, ga, false, Some(b)); // A <: B
+ types.insert_empty_struct(b, gb, false, Some(d)); // B <: D
+ types.insert_empty_struct(c, gc, false, Some(a)); // C <: A
+ types.insert_empty_struct(d, gd, false, None); // D
+
+ let mut sorted = Vec::new();
+ types.sort_types_topo(&mut sorted);
+
+ // Rec-group boundaries do not change topological ordering by supertype.
+ assert_eq!(
+ sorted,
+ [TypeId(3), TypeId(1), TypeId(0), TypeId(2)],
+ "topo order: supertype before subtype across rec groups"
+ );
+}
+
+#[test]
+fn fixup_preserves_subtyping_within_same_rec_group() {
+ let _ = env_logger::try_init();
+
+ let mut types = Types::new();
+ let g = RecGroupId(0);
+ types.insert_rec_group(g);
+
+ let super_ty = TypeId(0);
+ let sub_ty = TypeId(1);
+
+ // Both types are in the same rec group.
+ // The second subtypes the first.
+ types.insert_empty_struct(super_ty, g, false, None);
+ types.insert_empty_struct(sub_ty, g, false, Some(super_ty));
+
+ let limits = GcOpsLimits {
+ num_params: 0,
+ num_globals: 0,
+ table_size: 0,
+ max_rec_groups: 10,
+ max_types: 10,
+ };
+
+ types.fixup(&limits);
+
+ assert_eq!(types.rec_group_of(super_ty), Some(g));
+ assert_eq!(types.rec_group_of(sub_ty), Some(g));
+ assert_eq!(
+ types.type_defs.get(&sub_ty).unwrap().supertype,
+ Some(super_ty)
+ );
+}
+
+#[test]
+fn fixup_breaks_one_edge_in_multi_rec_group_type_cycle() {
+ let _ = env_logger::try_init();
+
+ let mut types = Types::new();
+
+ let g_a = RecGroupId(0);
+ let g_bc = RecGroupId(1);
+ let g_d = RecGroupId(2);
+
+ types.insert_rec_group(g_a);
+ types.insert_rec_group(g_bc);
+ types.insert_rec_group(g_d);
+
+ let a = TypeId(0);
+ let b = TypeId(1);
+ let c = TypeId(2);
+ let d = TypeId(3);
+
+ // Rec(a)
+ types.insert_empty_struct(a, g_a, false, Some(d));
+
+ // Rec(b, c)
+ types.insert_empty_struct(b, g_bc, false, None);
+ types.insert_empty_struct(c, g_bc, false, Some(a));
+
+ // Rec(d)
+ types.insert_empty_struct(d, g_d, false, Some(c));
+
+ let limits = GcOpsLimits {
+ num_params: 0,
+ num_globals: 0,
+ table_size: 0,
+ max_rec_groups: 10,
+ max_types: 10,
+ };
+
+ types.fixup(&limits);
+
+ let a_super = types.type_defs.get(&a).unwrap().supertype;
+ let c_super = types.type_defs.get(&c).unwrap().supertype;
+ let d_super = types.type_defs.get(&d).unwrap().supertype;
+
+ let cleared = [a_super, c_super, d_super]
+ .into_iter()
+ .filter(|st| st.is_none())
+ .count();
+
+ assert!(
+ cleared == 1,
+ "fixup should clear exactly one edge to break the cycle"
+ );
+}
+
+#[test]
+fn sort_rec_groups_topo_orders_dependencies_first() {
+ let mut types = Types::new();
+
+ let g0 = RecGroupId(0);
+ let g1 = RecGroupId(1);
+ let g2 = RecGroupId(2);
+ let g3 = RecGroupId(3);
+
+ types.insert_rec_group(g0);
+ types.insert_rec_group(g1);
+ types.insert_rec_group(g2);
+ types.insert_rec_group(g3);
+
+ let a = TypeId(0);
+ let b = TypeId(1);
+ let c = TypeId(2);
+ let d = TypeId(3);
+ let e = TypeId(4);
+ let f = TypeId(5);
+
+ types.insert_empty_struct(a, g0, false, Some(b)); // g0 -> g1
+ types.insert_empty_struct(b, g1, false, Some(c)); // g1 -> g2
+ types.insert_empty_struct(c, g2, false, Some(d)); // g2 ->g3
+ types.insert_empty_struct(d, g3, false, None);
+ types.insert_empty_struct(e, g0, false, None);
+ types.insert_empty_struct(f, g2, false, None);
+
+ let mut sorted = Vec::new();
+ types.sort_rec_groups_topo(&mut sorted);
+
+ // g3 has no deps, g2 depends on g3, g1 on g2, g0 on g1.
+ assert_eq!(
+ sorted,
+ [RecGroupId(3), RecGroupId(2), RecGroupId(1), RecGroupId(0)],
+ "topo order: depended-on groups before dependent groups"
+ );
+}
+
+#[test]
+fn break_rec_group_cycles() {
+ let mut types = Types::new();
+
+ let g0 = RecGroupId(0);
+ let g1 = RecGroupId(1);
+ let g2 = RecGroupId(2);
+ let g3 = RecGroupId(3);
+
+ types.insert_rec_group(g0);
+ types.insert_rec_group(g1);
+ types.insert_rec_group(g2);
+ types.insert_rec_group(g3);
+
+ let a0 = TypeId(0);
+ let a1 = TypeId(1);
+ let b0 = TypeId(2);
+ let b1 = TypeId(3);
+ let c0 = TypeId(4);
+ let c1 = TypeId(5);
+ let c2 = TypeId(6);
+ let d0 = TypeId(7);
+ let d1 = TypeId(8);
+
+ // Before: t
+ //
+ // ----------------------------------
+ // | outer cycle │
+ // v │
+ // +----+ +----+ +----+ │
+ // | g0 |------>| g1 |------>| g2 |---
+ // +----+ +----+ +----+
+ // ^ │
+ // │ inner │
+ // │ cycle v
+ // │ +----+
+ // -----------| g3 |
+ // +----+
+ //
+ // After: back edges dropped, clean chain
+ //
+ // +----+ +----+ +----+ +----+
+ // | g0 |------>| g1 |------>| g2 |------>| g3 |
+ // +----+ +----+ +----+ +----+
+
+ types.insert_empty_struct(a0, g0, false, Some(b0)); // g0 -> g1
+ types.insert_empty_struct(a1, g0, false, None);
+
+ types.insert_empty_struct(b0, g1, false, None);
+ types.insert_empty_struct(b1, g1, false, Some(c0)); // g1 -> g2
+
+ types.insert_empty_struct(c0, g2, false, None);
+ types.insert_empty_struct(c1, g2, false, Some(a1)); // g2 -> g0 (outer back edge)
+ types.insert_empty_struct(c2, g2, false, Some(d0)); // g2 -> g3
+
+ types.insert_empty_struct(d0, g3, false, None);
+ types.insert_empty_struct(d1, g3, false, Some(b0)); // g3 -> g1 (inner back edge)
+
+ // Type graph is acyclic — breaking supertype cycles changes nothing.
+ types.break_supertype_cycles();
+ assert_eq!(types.type_defs.get(&a0).unwrap().supertype, Some(b0));
+ assert_eq!(types.type_defs.get(&b1).unwrap().supertype, Some(c0));
+ assert_eq!(types.type_defs.get(&c1).unwrap().supertype, Some(a1));
+ assert_eq!(types.type_defs.get(&c2).unwrap().supertype, Some(d0));
+ assert_eq!(types.type_defs.get(&d1).unwrap().supertype, Some(b0));
+
+ assert_eq!(types.rec_groups.len(), 4);
+
+ types.break_rec_group_cycles();
+
+ // All four groups preserved.
+ assert_eq!(types.rec_groups.len(), 4);
+ assert!(types.rec_groups.contains_key(&g0));
+ assert!(types.rec_groups.contains_key(&g1));
+ assert!(types.rec_groups.contains_key(&g2));
+ assert!(types.rec_groups.contains_key(&g3));
+
+ // Back edge (g2->g0): c1's supertype cleared.
+ assert_eq!(types.type_defs.get(&c1).unwrap().supertype, None);
+
+ // Back edge (g3->g1): d1's supertype cleared.
+ assert_eq!(types.type_defs.get(&d1).unwrap().supertype, None);
+
+ // All other cross-group supertypes preserved.
+ assert_eq!(types.type_defs.get(&a0).unwrap().supertype, Some(b0));
+ assert_eq!(types.type_defs.get(&b1).unwrap().supertype, Some(c0));
+ assert_eq!(types.type_defs.get(&c2).unwrap().supertype, Some(d0));
+
+ // Result is a clean chain: g0 -> g1 -> g2 -> g3
+ let mut topo = Vec::new();
+ types.sort_rec_groups_topo(&mut topo);
+ assert_eq!(topo.len(), 4);
+ assert_eq!(topo, vec![g3, g2, g1, g0]);
+}
diff --git a/crates/fuzzing/src/generators/gc_ops/types.rs b/crates/fuzzing/src/generators/gc_ops/types.rs
index ce7ca24328..d7a822fa95 100644
--- a/crates/fuzzing/src/generators/gc_ops/types.rs
+++ b/crates/fuzzing/src/generators/gc_ops/types.rs
@@ -5,6 +5,7 @@ use crate::generators::gc_ops::ops::GcOp;
use serde::{Deserialize, Serialize};
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};
+use wasmtime_environ::graphs::{Dfs, DfsEvent, Graph};
/// Identifies a `(rec ...)` group.
#[derive(
@@ -32,9 +33,81 @@ pub enum CompositeType {
/// A sub-type definition (the per-type payload).
#[derive(Debug, Serialize, Deserialize)]
pub struct SubType {
+ pub(crate) is_final: bool,
+ pub(crate) supertype: Option<TypeId>,
pub(crate) composite_type: CompositeType,
}
+/// Supertype graph: edges go from a type to its supertype.
+struct SupertypeGraph<'a> {
+ type_defs: &'a BTreeMap<TypeId, SubType>,
+}
+
+impl Graph<TypeId> for SupertypeGraph<'_> {
+ type NodesIter<'a>
+ = std::iter::Copied<std::collections::btree_map::Keys<'a, TypeId, SubType>>
+ where
+ Self: 'a;
+
+ fn nodes(&self) -> Self::NodesIter<'_> {
+ self.type_defs.keys().copied()
+ }
+
+ type SuccessorsIter<'a>
+ = std::option::IntoIter<TypeId>
+ where
+ Self: 'a;
+
+ fn successors(&self, node: TypeId) -> Self::SuccessorsIter<'_> {
+ self.type_defs
+ .get(&node)
+ .and_then(|def| def.supertype)
+ .into_iter()
+ }
+}
+
+/// Rec-group dependency graph: group A depends on group B when a type
+/// in A has a supertype in B.
+struct RecGroupGraph<'a> {
+ type_defs: &'a BTreeMap<TypeId, SubType>,
+ rec_groups: &'a BTreeMap<RecGroupId, BTreeSet<TypeId>>,
+ type_to_group: &'a BTreeMap<TypeId, RecGroupId>,
+}
+
+impl Graph<RecGroupId> for RecGroupGraph<'_> {
+ type NodesIter<'a>
+ = std::iter::Copied<std::collections::btree_map::Keys<'a, RecGroupId, BTreeSet<TypeId>>>
+ where
+ Self: 'a;
+
+ fn nodes(&self) -> Self::NodesIter<'_> {
+ self.rec_groups.keys().copied()
+ }
+
+ type SuccessorsIter<'a>
+ = std::vec::IntoIter<RecGroupId>
+ where
+ Self: 'a;
+
+ fn successors(&self, group: RecGroupId) -> Self::SuccessorsIter<'_> {
+ let mut deps = BTreeSet::new();
+
+ if let Some(type_ids) = self.rec_groups.get(&group) {
+ for &ty in type_ids {
+ if let Some(super_ty) = self.type_defs.get(&ty).and_then(|d| d.supertype) {
+ if let Some(&super_group) = self.type_to_group.get(&super_ty) {
+ if super_group != group {
+ deps.insert(super_group);
+ }
+ }
+ }
+ }
+ }
+
+ deps.into_iter().collect::<Vec<_>>().into_iter()
+ }
+}
+
/// All type and rec-group state.
///
/// Rec groups own sets of [`TypeId`]s; moving a type between groups is
@@ -89,7 +162,13 @@ impl Types {
/// Insert an empty struct type into the given rec group.
///
/// The rec group must already exist.
- pub fn insert_empty_struct(&mut self, id: TypeId, group: RecGroupId) {
+ pub fn insert_empty_struct(
+ &mut self,
+ id: TypeId,
+ group: RecGroupId,
+ is_final: bool,
+ supertype: Option<TypeId>,
+ ) {
self.rec_groups
.get_mut(&group)
.expect("rec group must exist")
@@ -97,6 +176,8 @@ impl Types {
self.type_defs.insert(
id,
SubType {
+ is_final,
+ supertype,
composite_type: CompositeType::Struct(StructType::default()),
},
);
@@ -118,6 +199,158 @@ impl Types {
.map(|(gid, _)| *gid)
}
+ /// Topological sort of types by their supertype (supertype before subtype).
+ pub fn sort_types_topo(&self, out: &mut Vec<TypeId>) {
+ let graph = SupertypeGraph {
+ type_defs: &self.type_defs,
+ };
+
+ let mut dfs = Dfs::new(graph.nodes());
+ let mut seen = BTreeSet::new();
+
+ out.clear();
+ out.reserve(self.type_defs.len());
+
+ while let Some(event) = dfs.next(&graph, |id| seen.contains(&id)) {
+ match event {
+ DfsEvent::Pre(id) => {
+ seen.insert(id);
+ }
+ DfsEvent::Post(id) => {
+ out.push(id);
+ }
+ DfsEvent::AfterEdge(_, _) => {}
+ }
+ }
+ }
+
+ /// Topological sort of rec groups: if a type in group G has a
+ /// supertype in group H, then H appears before G in the output.
+ pub fn sort_rec_groups_topo(&self, out: &mut Vec<RecGroupId>) {
+ let type_to_group = self.type_to_group_map();
+ let graph = RecGroupGraph {
+ type_defs: &self.type_defs,
+ rec_groups: &self.rec_groups,
+ type_to_group: &type_to_group,
+ };
+
+ let mut dfs = Dfs::new(graph.nodes());
+ let mut seen = BTreeSet::new();
+
+ out.clear();
+ out.reserve(self.rec_groups.len());
+
+ while let Some(event) = dfs.next(&graph, |id| seen.contains(&id)) {
+ match event {
+ DfsEvent::Pre(id) => {
+ seen.insert(id);
+ }
+ DfsEvent::Post(id) => {
+ out.push(id);
+ }
+ DfsEvent::AfterEdge(_, _) => {}
+ }
+ }
+ }
+
+ /// Break cycles in the [type -> supertype] graph by dropping some supertype edges.
+ pub fn break_supertype_cycles(&mut self) {
+ let graph = SupertypeGraph {
+ type_defs: &self.type_defs,
+ };
+
+ let mut dfs = Dfs::new(graph.nodes());
+ let mut seen = BTreeSet::new();
+ let mut active = BTreeSet::new();
+ let mut to_clear = BTreeSet::new();
+
+ while let Some(event) = dfs.next(&graph, |id| seen.contains(&id)) {
+ match event {
+ DfsEvent::Pre(id) => {
+ seen.insert(id);
+ active.insert(id);
+ }
+ DfsEvent::Post(id) => {
+ active.remove(&id);
+ }
+ DfsEvent::AfterEdge(from, to) => {
+ if active.contains(&to) {
+ to_clear.insert(from);
+ }
+ }
+ }
+ }
+
+ for id in to_clear {
+ if let Some(def) = self.type_defs.get_mut(&id) {
+ def.supertype = None;
+ }
+ }
+ }
+
+ /// Build a reverse map from type id to its owning rec group.
+ fn type_to_group_map(&self) -> BTreeMap<TypeId, RecGroupId> {
+ self.rec_groups
+ .iter()
+ .flat_map(|(&gid, members)| members.iter().map(move |&tid| (tid, gid)))
+ .collect()
+ }
+
+ /// Break cycles in the rec-group dependency graph by dropping cross-group
+ /// supertype edges that are DFS back edges.
+ pub fn break_rec_group_cycles(&mut self) {
+ let type_to_group = self.type_to_group_map();
+ let graph = RecGroupGraph {
+ type_defs: &self.type_defs,
+ rec_groups: &self.rec_groups,
+ type_to_group: &type_to_group,
+ };
+
+ let mut seen = BTreeSet::new();
+ let mut back_edges: BTreeSet<(RecGroupId, RecGroupId)> = BTreeSet::new();
+ let mut dfs = Dfs::default();
+
+ for &root in self.rec_groups.keys() {
+ if seen.contains(&root) {
+ continue;
+ }
+ dfs.add_root(root);
+ let mut active = BTreeSet::new();
+
+ while let Some(event) = dfs.next(&graph, |id| seen.contains(&id)) {
+ match event {
+ DfsEvent::Pre(id) => {
+ seen.insert(id);
+ active.insert(id);
+ }
+ DfsEvent::Post(id) => {
+ active.remove(&id);
+ }
+ DfsEvent::AfterEdge(from, to) => {
+ if active.contains(&to) {
+ back_edges.insert((from, to));
+ }
+ }
+ }
+ }
+ }
+
+ // Drop supertype edges that correspond to back edges.
+ if !back_edges.is_empty() {
+ for (&tid, def) in self.type_defs.iter_mut() {
+ if let Some(st) = def.supertype {
+ if let (Some(&sg), Some(&spg)) =
+ (type_to_group.get(&tid), type_to_group.get(&st))
+ {
+ if back_edges.contains(&(sg, spg)) {
+ def.supertype = None;
+ }
+ }
+ }
+ }
+ }
+ }
+
/// Fix up the types to ensure they are within the limits.
pub fn fixup(&mut self, limits: &GcOpsLimits) {
let max_rec_groups =
@@ -166,6 +399,35 @@ impl Types {
}
}
+ // 6. Clear supertypes that reference removed types.
+ let valid_type_ids: BTreeSet<TypeId> = self.type_defs.keys().copied().collect();
+ for def in self.type_defs.values_mut() {
+ if let Some(st) = def.supertype {
+ if !valid_type_ids.contains(&st) {
+ def.supertype = None;
+ }
+ }
+ }
+
+ // 7. A subtype cannot have a final supertype.
+ let final_type_ids: BTreeSet<TypeId> = self
+ .type_defs
+ .iter()
+ .filter(|(_, d)| d.is_final)
+ .map(|(id, _)| *id)
+ .collect();
+ for def in self.type_defs.values_mut() {
+ if let Some(st) = def.supertype {
+ if final_type_ids.contains(&st) {
+ def.supertype = None;
+ }
+ }
+ }
+
+ // 8. Break supertype cycles and rec-group dependency cycles.
+ self.break_supertype_cycles();
+ self.break_rec_group_cycles();
+
debug_assert!(self.is_well_formed(limits));
}
@@ -202,6 +464,22 @@ impl Types {
log::debug!("[-] Failed: type_defs.keys().all(|tid| all.contains(tid)) is false");
return false;
}
+ // Every supertype must exist and must not be final.
+ for (&tid, def) in &self.type_defs {
+ if let Some(st) = def.supertype {
+ match self.type_defs.get(&st) {
+ None => {
+ log::debug!("[-] Failed: supertype {st:?} missing for subtype {tid:?}");
+ return false;
+ }
+ Some(super_def) if super_def.is_final => {
+ log::debug!("[-] Failed: subtype {tid:?} has final supertype {st:?}");
+ return false;
+ }
+ _ => {}
+ }
+ }
+ }
true
}
}