diff --git a/crates/wasmprinter/src/component.rs b/crates/wasmprinter/src/component.rs index 40126a0d6e..517e4d039b 100644 --- a/crates/wasmprinter/src/component.rs +++ b/crates/wasmprinter/src/component.rs @@ -462,6 +462,24 @@ impl Printer<'_, '_> { Ok(&states[states.len() - count - 1]) } + /// Prints the `count` of an outer alias as the identifier of the scope it + /// refers to, unless a scope in between has the same identifier, which + /// the identifier would refer to instead. + fn print_outer_count(&mut self, states: &[State], count: u32) -> Result<()> { + if let Some(i) = states.len().checked_sub(count as usize + 1) { + if let Some(name) = &states[i].name { + let shadowed = states[i + 1..] + .iter() + .any(|s| s.name.as_ref() == Some(name)); + if !shadowed { + return name.write_identifier(self); + } + } + } + write!(self.result, "{count}")?; + Ok(()) + } + pub(crate) fn print_outer_alias( &mut self, states: &mut [State], @@ -479,11 +497,7 @@ impl Printer<'_, '_> { } }; self.start_group("alias outer ")?; - if let Some(name) = outer.name.as_ref() { - name.write(self)?; - } else { - write!(self.result, "{count}")?; - } + self.print_outer_count(states, count)?; self.result.write_str(" ")?; match kind { OuterAliasKind::Type => { @@ -1444,11 +1458,7 @@ impl Printer<'_, '_> { } }; self.start_group("alias outer ")?; - if let Some(name) = outer.name.as_ref() { - name.write(self)?; - } else { - write!(self.result, "{count}")?; - } + self.print_outer_count(states, count)?; self.result.write_str(" ")?; match kind { ComponentOuterAliasKind::CoreModule => { diff --git a/crates/wasmprinter/src/lib.rs b/crates/wasmprinter/src/lib.rs index de13090f7e..c8102b8103 100644 --- a/crates/wasmprinter/src/lib.rs +++ b/crates/wasmprinter/src/lib.rs @@ -183,11 +183,13 @@ impl State { } } +#[derive(Clone, PartialEq)] struct Naming { name: String, kind: NamingKind, } +#[derive(Clone, PartialEq)] enum NamingKind { DollarName, DollarQuotedName, @@ -533,6 +535,20 @@ impl Printer<'_, '_> { name.write(self)?; } } + + // Outer aliases refer to a nested component by the name + // printed above, which its parent gives it. + #[cfg(feature = "component-model")] + if let [.., parent, state] = &mut states[..] { + if state.encoding == Encoding::Component { + state.name = parent + .component + .component_names + .index_to_name + .get(&parent.component.components) + .cloned(); + } + } } Payload::CustomSection(c) => { // If the custom printing trait handles this section, keep