wit_parser/
resolve.rs

1use std::cmp::Ordering;
2use std::collections::hash_map;
3use std::collections::{BTreeMap, HashMap, HashSet};
4use std::fmt;
5use std::mem;
6use std::path::{Path, PathBuf};
7
8use anyhow::{anyhow, bail, Context, Result};
9use id_arena::{Arena, Id};
10use indexmap::{IndexMap, IndexSet};
11use semver::Version;
12#[cfg(feature = "serde")]
13use serde_derive::Serialize;
14
15use crate::ast::lex::Span;
16use crate::ast::{parse_use_path, ParsedUsePath};
17#[cfg(feature = "serde")]
18use crate::serde_::{serialize_arena, serialize_id_map};
19use crate::{
20    AstItem, Docs, Error, Function, FunctionKind, Handle, IncludeName, Interface, InterfaceId,
21    InterfaceSpan, LiftLowerAbi, ManglingAndAbi, PackageName, PackageNotFoundError, SourceMap,
22    Stability, Type, TypeDef, TypeDefKind, TypeId, TypeIdVisitor, TypeOwner, UnresolvedPackage,
23    UnresolvedPackageGroup, World, WorldId, WorldItem, WorldKey, WorldSpan,
24};
25
26mod clone;
27
28/// Representation of a fully resolved set of WIT packages.
29///
30/// This structure contains a graph of WIT packages and all of their contents
31/// merged together into the contained arenas. All items are sorted
32/// topologically and everything here is fully resolved, so with a `Resolve` no
33/// name lookups are necessary and instead everything is index-based.
34///
35/// Working with a WIT package requires inserting it into a `Resolve` to ensure
36/// that all of its dependencies are satisfied. This will give the full picture
37/// of that package's types and such.
38///
39/// Each item in a `Resolve` has a parent link to trace it back to the original
40/// package as necessary.
41#[derive(Default, Clone, Debug)]
42#[cfg_attr(feature = "serde", derive(Serialize))]
43pub struct Resolve {
44    /// All known worlds within this `Resolve`.
45    ///
46    /// Each world points at a `PackageId` which is stored below. No ordering is
47    /// guaranteed between this list of worlds.
48    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_arena"))]
49    pub worlds: Arena<World>,
50
51    /// All known interfaces within this `Resolve`.
52    ///
53    /// Each interface points at a `PackageId` which is stored below. No
54    /// ordering is guaranteed between this list of interfaces.
55    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_arena"))]
56    pub interfaces: Arena<Interface>,
57
58    /// All known types within this `Resolve`.
59    ///
60    /// Types are topologically sorted such that any type referenced from one
61    /// type is guaranteed to be defined previously. Otherwise though these are
62    /// not sorted by interface for example.
63    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_arena"))]
64    pub types: Arena<TypeDef>,
65
66    /// All known packages within this `Resolve`.
67    ///
68    /// This list of packages is not sorted. Sorted packages can be queried
69    /// through [`Resolve::topological_packages`].
70    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_arena"))]
71    pub packages: Arena<Package>,
72
73    /// A map of package names to the ID of the package with that name.
74    #[cfg_attr(feature = "serde", serde(skip))]
75    pub package_names: IndexMap<PackageName, PackageId>,
76
77    /// Activated features for this [`Resolve`].
78    ///
79    /// This set of features is empty by default. This is consulted for
80    /// `@unstable` annotations in loaded WIT documents. Any items with
81    /// `@unstable` are filtered out unless their feature is present within this
82    /// set.
83    #[cfg_attr(feature = "serde", serde(skip))]
84    pub features: IndexSet<String>,
85
86    /// Activate all features for this [`Resolve`].
87    #[cfg_attr(feature = "serde", serde(skip))]
88    pub all_features: bool,
89}
90
91/// A WIT package within a `Resolve`.
92///
93/// A package is a collection of interfaces and worlds. Packages additionally
94/// have a unique identifier that affects generated components and uniquely
95/// identifiers this particular package.
96#[derive(Clone, Debug)]
97#[cfg_attr(feature = "serde", derive(Serialize))]
98pub struct Package {
99    /// A unique name corresponding to this package.
100    pub name: PackageName,
101
102    /// Documentation associated with this package.
103    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
104    pub docs: Docs,
105
106    /// All interfaces contained in this packaged, keyed by the interface's
107    /// name.
108    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id_map"))]
109    pub interfaces: IndexMap<String, InterfaceId>,
110
111    /// All worlds contained in this package, keyed by the world's name.
112    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id_map"))]
113    pub worlds: IndexMap<String, WorldId>,
114}
115
116pub type PackageId = Id<Package>;
117
118/// All the sources used during resolving a directory or path.
119#[derive(Clone, Debug)]
120pub struct PackageSourceMap {
121    sources: Vec<Vec<PathBuf>>,
122    package_id_to_source_map_idx: BTreeMap<PackageId, usize>,
123}
124
125impl PackageSourceMap {
126    fn from_single_source(package_id: PackageId, source: &Path) -> Self {
127        Self {
128            sources: vec![vec![source.to_path_buf()]],
129            package_id_to_source_map_idx: BTreeMap::from([(package_id, 0)]),
130        }
131    }
132
133    fn from_source_maps(
134        source_maps: Vec<SourceMap>,
135        package_id_to_source_map_idx: BTreeMap<PackageId, usize>,
136    ) -> PackageSourceMap {
137        for (package_id, idx) in &package_id_to_source_map_idx {
138            if *idx >= source_maps.len() {
139                panic!(
140                    "Invalid source map index: {}, package id: {:?}, source maps size: {}",
141                    idx,
142                    package_id,
143                    source_maps.len()
144                )
145            }
146        }
147
148        Self {
149            sources: source_maps
150                .into_iter()
151                .map(|source_map| {
152                    source_map
153                        .source_files()
154                        .map(|path| path.to_path_buf())
155                        .collect()
156                })
157                .collect(),
158            package_id_to_source_map_idx,
159        }
160    }
161
162    /// All unique source paths.
163    pub fn paths(&self) -> impl Iterator<Item = &Path> {
164        // Usually any two source map should not have duplicated source paths,
165        // but it can happen, e.g. with using [`Resolve::push_str`] directly.
166        // To be sure we use a set for deduplication here.
167        self.sources
168            .iter()
169            .flatten()
170            .map(|path_buf| path_buf.as_ref())
171            .collect::<HashSet<&Path>>()
172            .into_iter()
173    }
174
175    /// Source paths for package
176    pub fn package_paths(&self, id: PackageId) -> Option<impl Iterator<Item = &Path>> {
177        self.package_id_to_source_map_idx
178            .get(&id)
179            .map(|&idx| self.sources[idx].iter().map(|path_buf| path_buf.as_ref()))
180    }
181}
182
183enum ParsedFile {
184    #[cfg(feature = "decoding")]
185    Package(PackageId),
186    Unresolved(UnresolvedPackageGroup),
187}
188
189/// Visitor helper for performing topological sort on a group of packages.
190fn visit<'a>(
191    pkg: &'a UnresolvedPackage,
192    pkg_details_map: &'a BTreeMap<PackageName, (UnresolvedPackage, usize)>,
193    order: &mut IndexSet<PackageName>,
194    visiting: &mut HashSet<&'a PackageName>,
195    source_maps: &[SourceMap],
196) -> Result<()> {
197    if order.contains(&pkg.name) {
198        return Ok(());
199    }
200
201    match pkg_details_map.get(&pkg.name) {
202        Some(pkg_details) => {
203            let (_, source_maps_index) = pkg_details;
204            source_maps[*source_maps_index].rewrite_error(|| {
205                for (i, (dep, _)) in pkg.foreign_deps.iter().enumerate() {
206                    let span = pkg.foreign_dep_spans[i];
207                    if !visiting.insert(dep) {
208                        bail!(Error::new(span, "package depends on itself"));
209                    }
210                    if let Some(dep) = pkg_details_map.get(dep) {
211                        let (dep_pkg, _) = dep;
212                        visit(dep_pkg, pkg_details_map, order, visiting, source_maps)?;
213                    }
214                    assert!(visiting.remove(dep));
215                }
216                assert!(order.insert(pkg.name.clone()));
217                Ok(())
218            })
219        }
220        None => panic!("No pkg_details found for package when doing topological sort"),
221    }
222}
223
224impl Resolve {
225    /// Creates a new [`Resolve`] with no packages/items inside of it.
226    pub fn new() -> Resolve {
227        Resolve::default()
228    }
229
230    /// Parse WIT packages from the input `path`.
231    ///
232    /// The input `path` can be one of:
233    ///
234    /// * A directory containing a WIT package with an optional `deps` directory
235    ///   for any dependent WIT packages it references.
236    /// * A single standalone WIT file.
237    /// * A wasm-encoded WIT package as a single file in the wasm binary format.
238    /// * A wasm-encoded WIT package as a single file in the wasm text format.
239    ///
240    /// In all of these cases packages are allowed to depend on previously
241    /// inserted packages into this `Resolve`. Resolution for packages is based
242    /// on the name of each package and reference.
243    ///
244    /// This method returns a `PackageId` and additionally a `PackageSourceMap`.
245    /// The `PackageId` represent the main package that was parsed. For example if a single WIT
246    /// file was specified  this will be the main package found in the file. For a directory this
247    /// will be all the main package in the directory itself. The `PackageId` value is useful
248    /// to pass to [`Resolve::select_world`] to take a user-specified world in a
249    /// conventional fashion and select which to use for bindings generation.
250    ///
251    /// The returned [`PackageSourceMap`] contains all the sources used during this operation.
252    /// This can be useful for systems that want to rebuild or regenerate bindings based on files modified,
253    /// or for ones which like to identify the used files for a package.
254    ///
255    /// More information can also be found at [`Resolve::push_dir`] and
256    /// [`Resolve::push_file`].
257    pub fn push_path(&mut self, path: impl AsRef<Path>) -> Result<(PackageId, PackageSourceMap)> {
258        self._push_path(path.as_ref())
259    }
260
261    fn _push_path(&mut self, path: &Path) -> Result<(PackageId, PackageSourceMap)> {
262        if path.is_dir() {
263            self.push_dir(path).with_context(|| {
264                format!(
265                    "failed to resolve directory while parsing WIT for path [{}]",
266                    path.display()
267                )
268            })
269        } else {
270            let id = self.push_file(path)?;
271            Ok((id, PackageSourceMap::from_single_source(id, path)))
272        }
273    }
274
275    fn sort_unresolved_packages(
276        &mut self,
277        main: UnresolvedPackageGroup,
278        deps: Vec<UnresolvedPackageGroup>,
279    ) -> Result<(PackageId, PackageSourceMap)> {
280        let mut pkg_details_map = BTreeMap::new();
281        let mut source_maps = Vec::new();
282
283        let mut insert = |group: UnresolvedPackageGroup| {
284            let UnresolvedPackageGroup {
285                main,
286                nested,
287                source_map,
288            } = group;
289            let i = source_maps.len();
290            source_maps.push(source_map);
291
292            for pkg in nested.into_iter().chain([main]) {
293                let name = pkg.name.clone();
294                let my_span = pkg.package_name_span;
295                let (prev_pkg, prev_i) = match pkg_details_map.insert(name.clone(), (pkg, i)) {
296                    Some(pair) => pair,
297                    None => continue,
298                };
299                let loc1 = source_maps[i].render_location(my_span);
300                let loc2 = source_maps[prev_i].render_location(prev_pkg.package_name_span);
301                bail!(
302                    "\
303package {name} is defined in two different locations:\n\
304  * {loc1}\n\
305  * {loc2}\n\
306                     "
307                )
308            }
309            Ok(())
310        };
311
312        let main_name = main.main.name.clone();
313        insert(main)?;
314        for dep in deps {
315            insert(dep)?;
316        }
317
318        // Perform a simple topological sort which will bail out on cycles
319        // and otherwise determine the order that packages must be added to
320        // this `Resolve`.
321        let mut order = IndexSet::new();
322        let mut visiting = HashSet::new();
323        for pkg_details in pkg_details_map.values() {
324            let (pkg, _) = pkg_details;
325            visit(
326                pkg,
327                &pkg_details_map,
328                &mut order,
329                &mut visiting,
330                &source_maps,
331            )?;
332        }
333
334        // Ensure that the final output is topologically sorted. Use a set to ensure that we render
335        // the buffers for each `SourceMap` only once, even though multiple packages may reference
336        // the same `SourceMap`.
337        let mut package_id_to_source_map_idx = BTreeMap::new();
338        let mut main_pkg_id = None;
339        for name in order {
340            let (pkg, source_map_index) = pkg_details_map.remove(&name).unwrap();
341            let source_map = &source_maps[source_map_index];
342            let is_main = pkg.name == main_name;
343            let id = self.push(pkg, source_map)?;
344            if is_main {
345                assert!(main_pkg_id.is_none());
346                main_pkg_id = Some(id);
347            }
348            package_id_to_source_map_idx.insert(id, source_map_index);
349        }
350
351        Ok((
352            main_pkg_id.unwrap(),
353            PackageSourceMap::from_source_maps(source_maps, package_id_to_source_map_idx),
354        ))
355    }
356
357    /// Parses the filesystem directory at `path` as a WIT package and returns
358    /// a fully resolved [`PackageId`] list as a result.
359    ///
360    /// The directory itself is parsed with [`UnresolvedPackageGroup::parse_dir`]
361    /// and then all packages found are inserted into this `Resolve`. The `path`
362    /// specified may have a `deps` subdirectory which is probed automatically
363    /// for any other WIT dependencies.
364    ///
365    /// The `deps` folder may contain:
366    ///
367    /// * `$path/deps/my-package/*.wit` - a directory that may contain multiple
368    ///   WIT files. This is parsed with [`UnresolvedPackageGroup::parse_dir`]
369    ///   and then inserted into this [`Resolve`]. Note that cannot recursively
370    ///   contain a `deps` directory.
371    /// * `$path/deps/my-package.wit` - a single-file WIT package. This is
372    ///   parsed with [`Resolve::push_file`] and then added to `self` for
373    ///   name reoslution.
374    /// * `$path/deps/my-package.{wasm,wat}` - a wasm-encoded WIT package either
375    ///   in the text for binary format.
376    ///
377    /// In all cases entries in the `deps` folder are added to `self` first
378    /// before adding files found in `path` itself. All WIT packages found are
379    /// candidates for name-based resolution that other packages may use.
380    ///
381    /// This function returns a tuple of two values. The first value is a
382    /// [`PackageId`], which represents the main WIT package found within
383    /// `path`. This argument is useful for passing to [`Resolve::select_world`]
384    /// for choosing something to bindgen with.
385    ///
386    /// The second value returned is a [`PackageSourceMap`], which contains all the sources
387    /// that were parsed during resolving. This can be useful for:
388    /// * build systems that want to rebuild bindings whenever one of the files changed
389    /// * or other tools, which want to identify the sources for the resolved packages
390    pub fn push_dir(&mut self, path: impl AsRef<Path>) -> Result<(PackageId, PackageSourceMap)> {
391        self._push_dir(path.as_ref())
392    }
393
394    fn _push_dir(&mut self, path: &Path) -> Result<(PackageId, PackageSourceMap)> {
395        let top_pkg = UnresolvedPackageGroup::parse_dir(path)
396            .with_context(|| format!("failed to parse package: {}", path.display()))?;
397        let deps = path.join("deps");
398        let deps = self
399            .parse_deps_dir(&deps)
400            .with_context(|| format!("failed to parse dependency directory: {}", deps.display()))?;
401
402        self.sort_unresolved_packages(top_pkg, deps)
403    }
404
405    fn parse_deps_dir(&mut self, path: &Path) -> Result<Vec<UnresolvedPackageGroup>> {
406        let mut ret = Vec::new();
407        if !path.exists() {
408            return Ok(ret);
409        }
410        let mut entries = path
411            .read_dir()
412            .and_then(|i| i.collect::<std::io::Result<Vec<_>>>())
413            .context("failed to read directory")?;
414        entries.sort_by_key(|e| e.file_name());
415        for dep in entries {
416            let path = dep.path();
417            let pkg = if dep.file_type()?.is_dir() || path.metadata()?.is_dir() {
418                // If this entry is a directory or a symlink point to a
419                // directory then always parse it as an `UnresolvedPackage`
420                // since it's intentional to not support recursive `deps`
421                // directories.
422                UnresolvedPackageGroup::parse_dir(&path)
423                    .with_context(|| format!("failed to parse package: {}", path.display()))?
424            } else {
425                // If this entry is a file then we may want to ignore it but
426                // this may also be a standalone WIT file or a `*.wasm` or
427                // `*.wat` encoded package.
428                let filename = dep.file_name();
429                match Path::new(&filename).extension().and_then(|s| s.to_str()) {
430                    Some("wit") | Some("wat") | Some("wasm") => match self._push_file(&path)? {
431                        #[cfg(feature = "decoding")]
432                        ParsedFile::Package(_) => continue,
433                        ParsedFile::Unresolved(pkg) => pkg,
434                    },
435
436                    // Other files in deps dir are ignored for now to avoid
437                    // accidentally including things like `.DS_Store` files in
438                    // the call below to `parse_dir`.
439                    _ => continue,
440                }
441            };
442            ret.push(pkg);
443        }
444        Ok(ret)
445    }
446
447    /// Parses the contents of `path` from the filesystem and pushes the result
448    /// into this `Resolve`.
449    ///
450    /// The `path` referenced here can be one of:
451    ///
452    /// * A WIT file. Note that in this case this single WIT file will be the
453    ///   entire package and any dependencies it has must already be in `self`.
454    /// * A WIT package encoded as WebAssembly, either in text or binary form.
455    ///   In this the package and all of its dependencies are automatically
456    ///   inserted into `self`.
457    ///
458    /// In both situations the `PackageId`s of the resulting resolved packages
459    /// are returned from this method. The return value is mostly useful in
460    /// conjunction with [`Resolve::select_world`].
461    pub fn push_file(&mut self, path: impl AsRef<Path>) -> Result<PackageId> {
462        match self._push_file(path.as_ref())? {
463            #[cfg(feature = "decoding")]
464            ParsedFile::Package(id) => Ok(id),
465            ParsedFile::Unresolved(pkg) => self.push_group(pkg),
466        }
467    }
468
469    fn _push_file(&mut self, path: &Path) -> Result<ParsedFile> {
470        let contents = std::fs::read(path)
471            .with_context(|| format!("failed to read path for WIT [{}]", path.display()))?;
472
473        // If decoding is enabled at compile time then try to see if this is a
474        // wasm file.
475        #[cfg(feature = "decoding")]
476        {
477            use crate::decoding::{decode, DecodedWasm};
478
479            #[cfg(feature = "wat")]
480            let is_wasm = wat::Detect::from_bytes(&contents).is_wasm();
481            #[cfg(not(feature = "wat"))]
482            let is_wasm = wasmparser::Parser::is_component(&contents);
483
484            if is_wasm {
485                #[cfg(feature = "wat")]
486                let contents = wat::parse_bytes(&contents).map_err(|mut e| {
487                    e.set_path(path);
488                    e
489                })?;
490
491                match decode(&contents)? {
492                    DecodedWasm::Component(..) => {
493                        bail!("found an actual component instead of an encoded WIT package in wasm")
494                    }
495                    DecodedWasm::WitPackage(resolve, pkg) => {
496                        let remap = self.merge(resolve)?;
497                        return Ok(ParsedFile::Package(remap.packages[pkg.index()]));
498                    }
499                }
500            }
501        }
502
503        // If this wasn't a wasm file then assume it's a WIT file.
504        let text = match std::str::from_utf8(&contents) {
505            Ok(s) => s,
506            Err(_) => bail!("input file is not valid utf-8 [{}]", path.display()),
507        };
508        let pkgs = UnresolvedPackageGroup::parse(path, text)?;
509        Ok(ParsedFile::Unresolved(pkgs))
510    }
511
512    /// Appends a new [`UnresolvedPackage`] to this [`Resolve`], creating a
513    /// fully resolved package with no dangling references.
514    ///
515    /// All the dependencies of `unresolved` must already have been loaded
516    /// within this `Resolve` via previous calls to `push` or other methods such
517    /// as [`Resolve::push_path`].
518    ///
519    /// Any dependency resolution error or otherwise world-elaboration error
520    /// will be returned here, if successful a package identifier is returned
521    /// which corresponds to the package that was just inserted.
522    pub fn push(
523        &mut self,
524        unresolved: UnresolvedPackage,
525        source_map: &SourceMap,
526    ) -> Result<PackageId> {
527        let ret = source_map.rewrite_error(|| Remap::default().append(self, unresolved));
528        if ret.is_ok() {
529            #[cfg(debug_assertions)]
530            self.assert_valid();
531        }
532        ret
533    }
534
535    /// Appends new [`UnresolvedPackageGroup`] to this [`Resolve`], creating a
536    /// fully resolved package with no dangling references.
537    ///
538    /// Any dependency resolution error or otherwise world-elaboration error
539    /// will be returned here, if successful a package identifier is returned
540    /// which corresponds to the package that was just inserted.
541    ///
542    /// The returned [`PackageId`]s are listed in topologically sorted order.
543    pub fn push_group(&mut self, unresolved_group: UnresolvedPackageGroup) -> Result<PackageId> {
544        let (pkg_id, _) = self.sort_unresolved_packages(unresolved_group, Vec::new())?;
545        Ok(pkg_id)
546    }
547
548    /// Convenience method for combining [`UnresolvedPackageGroup::parse`] and
549    /// [`Resolve::push_group`].
550    ///
551    /// The `path` provided is used for error messages but otherwise is not
552    /// read. This method does not touch the filesystem. The `contents` provided
553    /// are the contents of a WIT package.
554    pub fn push_str(&mut self, path: impl AsRef<Path>, contents: &str) -> Result<PackageId> {
555        self.push_group(UnresolvedPackageGroup::parse(path.as_ref(), contents)?)
556    }
557
558    pub fn all_bits_valid(&self, ty: &Type) -> bool {
559        match ty {
560            Type::U8
561            | Type::S8
562            | Type::U16
563            | Type::S16
564            | Type::U32
565            | Type::S32
566            | Type::U64
567            | Type::S64
568            | Type::F32
569            | Type::F64 => true,
570
571            Type::Bool | Type::Char | Type::String | Type::ErrorContext => false,
572
573            Type::Id(id) => match &self.types[*id].kind {
574                TypeDefKind::List(_)
575                | TypeDefKind::Variant(_)
576                | TypeDefKind::Enum(_)
577                | TypeDefKind::Option(_)
578                | TypeDefKind::Result(_)
579                | TypeDefKind::Future(_)
580                | TypeDefKind::Stream(_) => false,
581                TypeDefKind::Type(t) | TypeDefKind::FixedSizeList(t, ..) => self.all_bits_valid(t),
582
583                TypeDefKind::Handle(h) => match h {
584                    crate::Handle::Own(_) => true,
585                    crate::Handle::Borrow(_) => true,
586                },
587
588                TypeDefKind::Resource => false,
589                TypeDefKind::Record(r) => r.fields.iter().all(|f| self.all_bits_valid(&f.ty)),
590                TypeDefKind::Tuple(t) => t.types.iter().all(|t| self.all_bits_valid(t)),
591
592                // FIXME: this could perhaps be `true` for multiples-of-32 but
593                // seems better to probably leave this as unconditionally
594                // `false` for now, may want to reconsider later?
595                TypeDefKind::Flags(_) => false,
596
597                TypeDefKind::Unknown => unreachable!(),
598            },
599        }
600    }
601
602    /// Merges all the contents of a different `Resolve` into this one. The
603    /// `Remap` structure returned provides a mapping from all old indices to
604    /// new indices
605    ///
606    /// This operation can fail if `resolve` disagrees with `self` about the
607    /// packages being inserted. Otherwise though this will additionally attempt
608    /// to "union" packages found in `resolve` with those found in `self`.
609    /// Unioning packages is keyed on the name/url of packages for those with
610    /// URLs present. If found then it's assumed that both `Resolve` instances
611    /// were originally created from the same contents and are two views
612    /// of the same package.
613    pub fn merge(&mut self, resolve: Resolve) -> Result<Remap> {
614        log::trace!(
615            "merging {} packages into {} packages",
616            resolve.packages.len(),
617            self.packages.len()
618        );
619
620        let mut map = MergeMap::new(&resolve, &self);
621        map.build()?;
622        let MergeMap {
623            package_map,
624            interface_map,
625            type_map,
626            world_map,
627            interfaces_to_add,
628            worlds_to_add,
629            ..
630        } = map;
631
632        // With a set of maps from ids in `resolve` to ids in `self` the next
633        // operation is to start moving over items and building a `Remap` to
634        // update ids.
635        //
636        // Each component field of `resolve` is moved into `self` so long as
637        // its ID is not within one of the maps above. If it's present in a map
638        // above then that means the item is already present in `self` so a new
639        // one need not be added. If it's not present in a map that means it's
640        // not present in `self` so it must be added to an arena.
641        //
642        // When adding an item to an arena one of the `remap.update_*` methods
643        // is additionally called to update all identifiers from pointers within
644        // `resolve` to becoming pointers within `self`.
645        //
646        // Altogether this should weave all the missing items in `self` from
647        // `resolve` into one structure while updating all identifiers to
648        // be local within `self`.
649
650        let mut remap = Remap::default();
651        let Resolve {
652            types,
653            worlds,
654            interfaces,
655            packages,
656            package_names,
657            features: _,
658            ..
659        } = resolve;
660
661        let mut moved_types = Vec::new();
662        for (id, mut ty) in types {
663            let new_id = match type_map.get(&id).copied() {
664                Some(id) => {
665                    update_stability(&ty.stability, &mut self.types[id].stability)?;
666                    id
667                }
668                None => {
669                    log::debug!("moving type {:?}", ty.name);
670                    moved_types.push(id);
671                    remap.update_typedef(self, &mut ty, None)?;
672                    self.types.alloc(ty)
673                }
674            };
675            assert_eq!(remap.types.len(), id.index());
676            remap.types.push(Some(new_id));
677        }
678
679        let mut moved_interfaces = Vec::new();
680        for (id, mut iface) in interfaces {
681            let new_id = match interface_map.get(&id).copied() {
682                Some(id) => {
683                    update_stability(&iface.stability, &mut self.interfaces[id].stability)?;
684                    id
685                }
686                None => {
687                    log::debug!("moving interface {:?}", iface.name);
688                    moved_interfaces.push(id);
689                    remap.update_interface(self, &mut iface, None)?;
690                    self.interfaces.alloc(iface)
691                }
692            };
693            assert_eq!(remap.interfaces.len(), id.index());
694            remap.interfaces.push(Some(new_id));
695        }
696
697        let mut moved_worlds = Vec::new();
698        for (id, mut world) in worlds {
699            let new_id = match world_map.get(&id).copied() {
700                Some(world_id) => {
701                    update_stability(&world.stability, &mut self.worlds[world_id].stability)?;
702                    for from_import in world.imports.iter() {
703                        Resolve::update_world_imports_stability(
704                            from_import,
705                            &mut self.worlds[world_id].imports,
706                            &interface_map,
707                        )?;
708                    }
709                    for from_export in world.exports.iter() {
710                        Resolve::update_world_imports_stability(
711                            from_export,
712                            &mut self.worlds[world_id].exports,
713                            &interface_map,
714                        )?;
715                    }
716                    world_id
717                }
718                None => {
719                    log::debug!("moving world {}", world.name);
720                    moved_worlds.push(id);
721                    let mut update = |map: &mut IndexMap<WorldKey, WorldItem>| -> Result<_> {
722                        for (mut name, mut item) in mem::take(map) {
723                            remap.update_world_key(&mut name, None)?;
724                            match &mut item {
725                                WorldItem::Function(f) => remap.update_function(self, f, None)?,
726                                WorldItem::Interface { id, .. } => {
727                                    *id = remap.map_interface(*id, None)?
728                                }
729                                WorldItem::Type(i) => *i = remap.map_type(*i, None)?,
730                            }
731                            map.insert(name, item);
732                        }
733                        Ok(())
734                    };
735                    update(&mut world.imports)?;
736                    update(&mut world.exports)?;
737                    self.worlds.alloc(world)
738                }
739            };
740            assert_eq!(remap.worlds.len(), id.index());
741            remap.worlds.push(Some(new_id));
742        }
743
744        for (id, mut pkg) in packages {
745            let new_id = match package_map.get(&id).copied() {
746                Some(id) => id,
747                None => {
748                    for (_, id) in pkg.interfaces.iter_mut() {
749                        *id = remap.map_interface(*id, None)?;
750                    }
751                    for (_, id) in pkg.worlds.iter_mut() {
752                        *id = remap.map_world(*id, None)?;
753                    }
754                    self.packages.alloc(pkg)
755                }
756            };
757            assert_eq!(remap.packages.len(), id.index());
758            remap.packages.push(new_id);
759        }
760
761        for (name, id) in package_names {
762            let id = remap.packages[id.index()];
763            if let Some(prev) = self.package_names.insert(name, id) {
764                assert_eq!(prev, id);
765            }
766        }
767
768        // Fixup all "parent" links now.
769        //
770        // Note that this is only done for items that are actually moved from
771        // `resolve` into `self`, which is tracked by the various `moved_*`
772        // lists built incrementally above. The ids in the `moved_*` lists
773        // are ids within `resolve`, so they're translated through `remap` to
774        // ids within `self`.
775        for id in moved_worlds {
776            let id = remap.map_world(id, None)?;
777            if let Some(pkg) = self.worlds[id].package.as_mut() {
778                *pkg = remap.packages[pkg.index()];
779            }
780        }
781        for id in moved_interfaces {
782            let id = remap.map_interface(id, None)?;
783            if let Some(pkg) = self.interfaces[id].package.as_mut() {
784                *pkg = remap.packages[pkg.index()];
785            }
786        }
787        for id in moved_types {
788            let id = remap.map_type(id, None)?;
789            match &mut self.types[id].owner {
790                TypeOwner::Interface(id) => *id = remap.map_interface(*id, None)?,
791                TypeOwner::World(id) => *id = remap.map_world(*id, None)?,
792                TypeOwner::None => {}
793            }
794        }
795
796        // And finally process items that were present in `resolve` but were
797        // not present in `self`. This is only done for merged packages as
798        // documents may be added to `self.documents` but wouldn't otherwise be
799        // present in the `documents` field of the corresponding package.
800        for (name, pkg, iface) in interfaces_to_add {
801            let prev = self.packages[pkg]
802                .interfaces
803                .insert(name, remap.map_interface(iface, None)?);
804            assert!(prev.is_none());
805        }
806        for (name, pkg, world) in worlds_to_add {
807            let prev = self.packages[pkg]
808                .worlds
809                .insert(name, remap.map_world(world, None)?);
810            assert!(prev.is_none());
811        }
812
813        log::trace!("now have {} packages", self.packages.len());
814
815        #[cfg(debug_assertions)]
816        self.assert_valid();
817        Ok(remap)
818    }
819
820    fn update_world_imports_stability(
821        from_item: (&WorldKey, &WorldItem),
822        into_items: &mut IndexMap<WorldKey, WorldItem>,
823        interface_map: &HashMap<Id<Interface>, Id<Interface>>,
824    ) -> Result<()> {
825        match from_item.0 {
826            WorldKey::Name(_) => {
827                // No stability info to update here, only updating import/include stability
828                Ok(())
829            }
830            key @ WorldKey::Interface(_) => {
831                let new_key = MergeMap::map_name(key, interface_map);
832                if let Some(into) = into_items.get_mut(&new_key) {
833                    match (from_item.1, into) {
834                        (
835                            WorldItem::Interface {
836                                id: aid,
837                                stability: astability,
838                            },
839                            WorldItem::Interface {
840                                id: bid,
841                                stability: bstability,
842                            },
843                        ) => {
844                            let aid = interface_map.get(aid).copied().unwrap_or(*aid);
845                            assert_eq!(aid, *bid);
846                            update_stability(astability, bstability)?;
847                            Ok(())
848                        }
849                        _ => unreachable!(),
850                    }
851                } else {
852                    // we've already matched all the imports/exports by the time we are calling this
853                    // so this is unreachable since we should always find the item
854                    unreachable!()
855                }
856            }
857        }
858    }
859
860    /// Merges the world `from` into the world `into`.
861    ///
862    /// This will attempt to merge one world into another, unioning all of its
863    /// imports and exports together. This is an operation performed by
864    /// `wit-component`, for example where two different worlds from two
865    /// different libraries were linked into the same core wasm file and are
866    /// producing a singular world that will be the final component's
867    /// interface.
868    ///
869    /// This operation can fail if the imports/exports overlap.
870    pub fn merge_worlds(&mut self, from: WorldId, into: WorldId) -> Result<()> {
871        let mut new_imports = Vec::new();
872        let mut new_exports = Vec::new();
873
874        let from_world = &self.worlds[from];
875        let into_world = &self.worlds[into];
876
877        log::trace!("merging {} into {}", from_world.name, into_world.name);
878
879        // First walk over all the imports of `from` world and figure out what
880        // to do with them.
881        //
882        // If the same item exists in `from` and `into` then merge it together
883        // below with `merge_world_item` which basically asserts they're the
884        // same. Otherwise queue up a new import since if `from` has more
885        // imports than `into` then it's fine to add new imports.
886        for (name, from_import) in from_world.imports.iter() {
887            let name_str = self.name_world_key(name);
888            match into_world.imports.get(name) {
889                Some(into_import) => {
890                    log::trace!("info/from shared import on `{name_str}`");
891                    self.merge_world_item(from_import, into_import)
892                        .with_context(|| format!("failed to merge world import {name_str}"))?;
893                }
894                None => {
895                    log::trace!("new import: `{name_str}`");
896                    new_imports.push((name.clone(), from_import.clone()));
897                }
898            }
899        }
900
901        // Build a set of interfaces which are required to be imported because
902        // of `into`'s exports. This set is then used below during
903        // `ensure_can_add_world_export`.
904        //
905        // This is the set of interfaces which exports depend on that are
906        // themselves not exports.
907        let mut must_be_imported = HashMap::new();
908        for (key, export) in into_world.exports.iter() {
909            for dep in self.world_item_direct_deps(export) {
910                if into_world.exports.contains_key(&WorldKey::Interface(dep)) {
911                    continue;
912                }
913                self.foreach_interface_dep(dep, &mut |id| {
914                    must_be_imported.insert(id, key.clone());
915                });
916            }
917        }
918
919        // Next walk over exports of `from` and process these similarly to
920        // imports.
921        for (name, from_export) in from_world.exports.iter() {
922            let name_str = self.name_world_key(name);
923            match into_world.exports.get(name) {
924                Some(into_export) => {
925                    log::trace!("info/from shared export on `{name_str}`");
926                    self.merge_world_item(from_export, into_export)
927                        .with_context(|| format!("failed to merge world export {name_str}"))?;
928                }
929                None => {
930                    log::trace!("new export `{name_str}`");
931                    // See comments in `ensure_can_add_world_export` for why
932                    // this is slightly different than imports.
933                    self.ensure_can_add_world_export(
934                        into_world,
935                        name,
936                        from_export,
937                        &must_be_imported,
938                    )
939                    .with_context(|| {
940                        format!("failed to add export `{}`", self.name_world_key(name))
941                    })?;
942                    new_exports.push((name.clone(), from_export.clone()));
943                }
944            }
945        }
946
947        // For all the new imports and exports they may need to be "cloned" to
948        // be able to belong to the new world. For example:
949        //
950        // * Anonymous interfaces have a `package` field which points to the
951        //   package of the containing world, but `from` and `into` may not be
952        //   in the same package.
953        //
954        // * Type imports have an `owner` field that point to `from`, but they
955        //   now need to point to `into` instead.
956        //
957        // Cloning is no trivial task, however, so cloning is delegated to a
958        // submodule to perform a "deep" clone and copy items into new arena
959        // entries as necessary.
960        let mut cloner = clone::Cloner::new(self, TypeOwner::World(from), TypeOwner::World(into));
961        cloner.register_world_type_overlap(from, into);
962        for (name, item) in new_imports.iter_mut().chain(&mut new_exports) {
963            cloner.world_item(name, item);
964        }
965
966        // Insert any new imports and new exports found first.
967        let into_world = &mut self.worlds[into];
968        for (name, import) in new_imports {
969            let prev = into_world.imports.insert(name, import);
970            assert!(prev.is_none());
971        }
972        for (name, export) in new_exports {
973            let prev = into_world.exports.insert(name, export);
974            assert!(prev.is_none());
975        }
976
977        #[cfg(debug_assertions)]
978        self.assert_valid();
979        Ok(())
980    }
981
982    fn merge_world_item(&self, from: &WorldItem, into: &WorldItem) -> Result<()> {
983        let mut map = MergeMap::new(self, self);
984        match (from, into) {
985            (WorldItem::Interface { id: from, .. }, WorldItem::Interface { id: into, .. }) => {
986                // If these imports are the same that can happen, for
987                // example, when both worlds to `import foo:bar/baz;`. That
988                // foreign interface will point to the same interface within
989                // `Resolve`.
990                if from == into {
991                    return Ok(());
992                }
993
994                // .. otherwise this MUST be a case of
995                // `import foo: interface { ... }`. If `from != into` but
996                // both `from` and `into` have the same name then the
997                // `WorldKey::Interface` case is ruled out as otherwise
998                // they'd have different names.
999                //
1000                // In the case of an anonymous interface all we can do is
1001                // ensure that the interfaces both match, so use `MergeMap`
1002                // for that.
1003                map.build_interface(*from, *into)
1004                    .context("failed to merge interfaces")?;
1005            }
1006
1007            // Like `WorldKey::Name` interfaces for functions and types the
1008            // structure is asserted to be the same.
1009            (WorldItem::Function(from), WorldItem::Function(into)) => {
1010                map.build_function(from, into)
1011                    .context("failed to merge functions")?;
1012            }
1013            (WorldItem::Type(from), WorldItem::Type(into)) => {
1014                map.build_type_id(*from, *into)
1015                    .context("failed to merge types")?;
1016            }
1017
1018            // Kind-level mismatches are caught here.
1019            (WorldItem::Interface { .. }, _)
1020            | (WorldItem::Function { .. }, _)
1021            | (WorldItem::Type { .. }, _) => {
1022                bail!("different kinds of items");
1023            }
1024        }
1025        assert!(map.interfaces_to_add.is_empty());
1026        assert!(map.worlds_to_add.is_empty());
1027        Ok(())
1028    }
1029
1030    /// This method ensures that the world export of `name` and `item` can be
1031    /// added to the world `into` without changing the meaning of `into`.
1032    ///
1033    /// All dependencies of world exports must either be:
1034    ///
1035    /// * An export themselves
1036    /// * An import with all transitive dependencies of the import also imported
1037    ///
1038    /// It's not possible to depend on an import which then also depends on an
1039    /// export at some point, for example. This method ensures that if `name`
1040    /// and `item` are added that this property is upheld.
1041    fn ensure_can_add_world_export(
1042        &self,
1043        into: &World,
1044        name: &WorldKey,
1045        item: &WorldItem,
1046        must_be_imported: &HashMap<InterfaceId, WorldKey>,
1047    ) -> Result<()> {
1048        assert!(!into.exports.contains_key(name));
1049        let name = self.name_world_key(name);
1050
1051        // First make sure that all of this item's dependencies are either
1052        // exported or the entire chain of imports rooted at that dependency are
1053        // all imported.
1054        for dep in self.world_item_direct_deps(item) {
1055            if into.exports.contains_key(&WorldKey::Interface(dep)) {
1056                continue;
1057            }
1058            self.ensure_not_exported(into, dep)
1059                .with_context(|| format!("failed validating export of `{name}`"))?;
1060        }
1061
1062        // Second make sure that this item, if it's an interface, will not alter
1063        // the meaning of the preexisting world by ensuring that it's not in the
1064        // set of "must be imported" items.
1065        if let WorldItem::Interface { id, .. } = item {
1066            if let Some(export) = must_be_imported.get(&id) {
1067                let export_name = self.name_world_key(export);
1068                bail!(
1069                    "export `{export_name}` depends on `{name}` \
1070                     previously as an import which will change meaning \
1071                     if `{name}` is added as an export"
1072                );
1073            }
1074        }
1075
1076        Ok(())
1077    }
1078
1079    fn ensure_not_exported(&self, world: &World, id: InterfaceId) -> Result<()> {
1080        let key = WorldKey::Interface(id);
1081        let name = self.name_world_key(&key);
1082        if world.exports.contains_key(&key) {
1083            bail!(
1084                "world exports `{name}` but it's also transitively used by an \
1085                     import \
1086                   which means that this is not valid"
1087            )
1088        }
1089        for dep in self.interface_direct_deps(id) {
1090            self.ensure_not_exported(world, dep)
1091                .with_context(|| format!("failed validating transitive import dep `{name}`"))?;
1092        }
1093        Ok(())
1094    }
1095
1096    /// Returns an iterator of all the direct interface dependencies of this
1097    /// `item`.
1098    ///
1099    /// Note that this doesn't include transitive dependencies, that must be
1100    /// followed manually.
1101    fn world_item_direct_deps(&self, item: &WorldItem) -> impl Iterator<Item = InterfaceId> + '_ {
1102        let mut interface = None;
1103        let mut ty = None;
1104        match item {
1105            WorldItem::Function(_) => {}
1106            WorldItem::Type(id) => ty = Some(*id),
1107            WorldItem::Interface { id, .. } => interface = Some(*id),
1108        }
1109
1110        interface
1111            .into_iter()
1112            .flat_map(move |id| self.interface_direct_deps(id))
1113            .chain(ty.and_then(|t| self.type_interface_dep(t)))
1114    }
1115
1116    /// Invokes `f` with `id` and all transitive interface dependencies of `id`.
1117    ///
1118    /// Note that `f` may be called with the same id multiple times.
1119    fn foreach_interface_dep(&self, id: InterfaceId, f: &mut dyn FnMut(InterfaceId)) {
1120        self._foreach_interface_dep(id, f, &mut HashSet::new())
1121    }
1122
1123    // Internal detail of `foreach_interface_dep` which uses a hash map to prune
1124    // the visit tree to ensure that this doesn't visit an exponential number of
1125    // interfaces.
1126    fn _foreach_interface_dep(
1127        &self,
1128        id: InterfaceId,
1129        f: &mut dyn FnMut(InterfaceId),
1130        visited: &mut HashSet<InterfaceId>,
1131    ) {
1132        if !visited.insert(id) {
1133            return;
1134        }
1135        f(id);
1136        for dep in self.interface_direct_deps(id) {
1137            self._foreach_interface_dep(dep, f, visited);
1138        }
1139    }
1140
1141    /// Returns the ID of the specified `interface`.
1142    ///
1143    /// Returns `None` for unnamed interfaces.
1144    pub fn id_of(&self, interface: InterfaceId) -> Option<String> {
1145        let interface = &self.interfaces[interface];
1146        Some(self.id_of_name(interface.package.unwrap(), interface.name.as_ref()?))
1147    }
1148
1149    /// Returns the "canonicalized interface name" of `interface`.
1150    ///
1151    /// Returns `None` for unnamed interfaces. See `BuildTargets.md` in the
1152    /// upstream component model repository for more information about this.
1153    pub fn canonicalized_id_of(&self, interface: InterfaceId) -> Option<String> {
1154        let interface = &self.interfaces[interface];
1155        Some(self.canonicalized_id_of_name(interface.package.unwrap(), interface.name.as_ref()?))
1156    }
1157
1158    /// Convert a world to an "importized" version where the world is updated
1159    /// in-place to reflect what it would look like to be imported.
1160    ///
1161    /// This is a transformation which is used as part of the process of
1162    /// importing a component today. For example when a component depends on
1163    /// another component this is useful for generating WIT which can be use to
1164    /// represent the component being imported. The general idea is that this
1165    /// function will update the `world_id` specified such it imports the
1166    /// functionality that it previously exported. The world will be left with
1167    /// no exports.
1168    ///
1169    /// This world is then suitable for merging into other worlds or generating
1170    /// bindings in a context that is importing the original world. This
1171    /// is intended to be used as part of language tooling when depending on
1172    /// other components.
1173    pub fn importize(&mut self, world_id: WorldId, out_world_name: Option<String>) -> Result<()> {
1174        // Rename the world to avoid having it get confused with the original
1175        // name of the world. Add `-importized` to it for now. Precisely how
1176        // this new world is created may want to be updated over time if this
1177        // becomes problematic.
1178        let world = &mut self.worlds[world_id];
1179        let pkg = &mut self.packages[world.package.unwrap()];
1180        pkg.worlds.shift_remove(&world.name);
1181        if let Some(name) = out_world_name {
1182            world.name = name.clone();
1183            pkg.worlds.insert(name, world_id);
1184        } else {
1185            world.name.push_str("-importized");
1186            pkg.worlds.insert(world.name.clone(), world_id);
1187        }
1188
1189        // Trim all non-type definitions from imports. Types can be used by
1190        // exported functions, for example, so they're preserved.
1191        world.imports.retain(|_, item| match item {
1192            WorldItem::Type(_) => true,
1193            _ => false,
1194        });
1195
1196        for (name, export) in mem::take(&mut world.exports) {
1197            match (name.clone(), world.imports.insert(name, export)) {
1198                // no previous item? this insertion was ok
1199                (_, None) => {}
1200
1201                // cannot overwrite an import with an export
1202                (WorldKey::Name(name), Some(_)) => {
1203                    bail!("world export `{name}` conflicts with import of same name");
1204                }
1205
1206                // Exports already don't overlap each other and the only imports
1207                // preserved above were types so this shouldn't be reachable.
1208                (WorldKey::Interface(_), _) => unreachable!(),
1209            }
1210        }
1211
1212        // Fill out any missing transitive interface imports by elaborating this
1213        // world which does that for us.
1214        self.elaborate_world(world_id)?;
1215
1216        #[cfg(debug_assertions)]
1217        self.assert_valid();
1218        Ok(())
1219    }
1220
1221    /// Returns the ID of the specified `name` within the `pkg`.
1222    pub fn id_of_name(&self, pkg: PackageId, name: &str) -> String {
1223        let package = &self.packages[pkg];
1224        let mut base = String::new();
1225        base.push_str(&package.name.namespace);
1226        base.push_str(":");
1227        base.push_str(&package.name.name);
1228        base.push_str("/");
1229        base.push_str(name);
1230        if let Some(version) = &package.name.version {
1231            base.push_str(&format!("@{version}"));
1232        }
1233        base
1234    }
1235
1236    /// Returns the "canonicalized interface name" of the specified `name`
1237    /// within the `pkg`.
1238    ///
1239    /// See `BuildTargets.md` in the upstream component model repository for
1240    /// more information about this.
1241    pub fn canonicalized_id_of_name(&self, pkg: PackageId, name: &str) -> String {
1242        let package = &self.packages[pkg];
1243        let mut base = String::new();
1244        base.push_str(&package.name.namespace);
1245        base.push_str(":");
1246        base.push_str(&package.name.name);
1247        base.push_str("/");
1248        base.push_str(name);
1249        if let Some(version) = &package.name.version {
1250            base.push_str("@");
1251            let string = PackageName::version_compat_track_string(version);
1252            base.push_str(&string);
1253        }
1254        base
1255    }
1256
1257    /// Attempts to locate a world given the "default" set of `packages` and the
1258    /// optional string specifier `world`.
1259    ///
1260    /// This method is intended to be used by bindings generation tools to
1261    /// select a world from either `packages` or a package in this `Resolve`.
1262    /// The `packages` list is a return value from methods such as
1263    /// [`push_path`](Resolve::push_path), [`push_dir`](Resolve::push_dir),
1264    /// [`push_file`](Resolve::push_file), [`push_group`](Resolve::push_group),
1265    /// or [`push_str`](Resolve::push_str). The return values of those methods
1266    /// are the "main package list" which is specified by the user and is used
1267    /// as a heuristic for world selection.
1268    ///
1269    /// If `world` is `None` then `packages` must have one entry and that
1270    /// package must have exactly one world. If this is the case then that world
1271    /// will be returned, otherwise an error will be returned.
1272    ///
1273    /// If `world` is `Some` then it can either be:
1274    ///
1275    /// * A kebab-name of a world such as `"the-world"`. In this situation
1276    ///   the `packages` list must have only a single entry. If `packages` has
1277    ///   no entries or more than one, or if the kebab-name does not exist in
1278    ///   the one package specified, then an error will be returned.
1279    ///
1280    /// * An ID-based form of a world which is selected within this `Resolve`,
1281    ///   for example `"wasi:http/proxy"`. In this situation the `packages`
1282    ///   array is ignored and the ID specified is use to lookup a package. Note
1283    ///   that a version does not need to be specified in this string if there's
1284    ///   only one package of the same name and it has a version. In this
1285    ///   situation the version can be omitted.
1286    ///
1287    /// If successful the corresponding `WorldId` is returned, otherwise an
1288    /// error is returned.
1289    ///
1290    /// # Examples
1291    ///
1292    /// ```
1293    /// use anyhow::Result;
1294    /// use wit_parser::Resolve;
1295    ///
1296    /// fn main() -> Result<()> {
1297    ///     let mut resolve = Resolve::default();
1298    ///
1299    ///     // For inputs which have a single package and only one world `None`
1300    ///     // can be specified.
1301    ///     let id = resolve.push_str(
1302    ///         "./my-test.wit",
1303    ///         r#"
1304    ///             package example:wit1;
1305    ///
1306    ///             world foo {
1307    ///                 // ...
1308    ///             }
1309    ///         "#,
1310    ///     )?;
1311    ///     assert!(resolve.select_world(id, None).is_ok());
1312    ///
1313    ///     // For inputs which have a single package and multiple worlds then
1314    ///     // a world must be specified.
1315    ///     let id = resolve.push_str(
1316    ///         "./my-test.wit",
1317    ///         r#"
1318    ///             package example:wit2;
1319    ///
1320    ///             world foo { /* ... */ }
1321    ///
1322    ///             world bar { /* ... */ }
1323    ///         "#,
1324    ///     )?;
1325    ///     assert!(resolve.select_world(id, None).is_err());
1326    ///     assert!(resolve.select_world(id, Some("foo")).is_ok());
1327    ///     assert!(resolve.select_world(id, Some("bar")).is_ok());
1328    ///
1329    ///     // For inputs which have more than one package then a fully
1330    ///     // qualified name must be specified.
1331    ///
1332    ///     // Note that the `ids` or `packages` argument is ignored if a fully
1333    ///     // qualified world specified is provided meaning previous worlds
1334    ///     // can be selected.
1335    ///     assert!(resolve.select_world(id, Some("example:wit1/foo")).is_ok());
1336    ///     assert!(resolve.select_world(id, Some("example:wit2/foo")).is_ok());
1337    ///
1338    ///     // When selecting with a version it's ok to drop the version when
1339    ///     // there's only a single copy of that package in `Resolve`.
1340    ///     resolve.push_str(
1341    ///         "./my-test.wit",
1342    ///         r#"
1343    ///             package example:wit5@1.0.0;
1344    ///
1345    ///             world foo { /* ... */ }
1346    ///         "#,
1347    ///     )?;
1348    ///     assert!(resolve.select_world(id, Some("example:wit5/foo")).is_ok());
1349    ///
1350    ///     // However when a single package has multiple versions in a resolve
1351    ///     // it's required to specify the version to select which one.
1352    ///     resolve.push_str(
1353    ///         "./my-test.wit",
1354    ///         r#"
1355    ///             package example:wit5@2.0.0;
1356    ///
1357    ///             world foo { /* ... */ }
1358    ///         "#,
1359    ///     )?;
1360    ///     assert!(resolve.select_world(id, Some("example:wit5/foo")).is_err());
1361    ///     assert!(resolve.select_world(id, Some("example:wit5/foo@1.0.0")).is_ok());
1362    ///     assert!(resolve.select_world(id, Some("example:wit5/foo@2.0.0")).is_ok());
1363    ///
1364    ///     Ok(())
1365    /// }
1366    /// ```
1367    pub fn select_world(&self, package: PackageId, world: Option<&str>) -> Result<WorldId> {
1368        let world_path = match world {
1369            Some(world) => Some(
1370                parse_use_path(world)
1371                    .with_context(|| format!("failed to parse world specifier `{world}`"))?,
1372            ),
1373            None => None,
1374        };
1375
1376        let (pkg, world_name) = match world_path {
1377            Some(ParsedUsePath::Name(name)) => (package, name),
1378            Some(ParsedUsePath::Package(pkg, interface)) => {
1379                let pkg = match self.package_names.get(&pkg) {
1380                    Some(pkg) => *pkg,
1381                    None => {
1382                        let mut candidates = self.package_names.iter().filter(|(name, _)| {
1383                            pkg.version.is_none()
1384                                && pkg.name == name.name
1385                                && pkg.namespace == name.namespace
1386                                && name.version.is_some()
1387                        });
1388                        let candidate = candidates.next();
1389                        if let Some((c2, _)) = candidates.next() {
1390                            let (c1, _) = candidate.unwrap();
1391                            bail!(
1392                                "package name `{pkg}` is available at both \
1393                                 versions {} and {} but which is not specified",
1394                                c1.version.as_ref().unwrap(),
1395                                c2.version.as_ref().unwrap(),
1396                            );
1397                        }
1398                        match candidate {
1399                            Some((_, id)) => *id,
1400                            None => bail!("unknown package `{pkg}`"),
1401                        }
1402                    }
1403                };
1404                (pkg, interface.to_string())
1405            }
1406            None => {
1407                let pkg = &self.packages[package];
1408                let worlds = pkg
1409                    .worlds
1410                    .values()
1411                    .map(|world| (package, *world))
1412                    .collect::<Vec<_>>();
1413
1414                match &worlds[..] {
1415                    [] => bail!("The main package `{}` contains no worlds", pkg.name),
1416                    [(_, world)] => return Ok(*world),
1417                    _ => bail!(
1418                        "multiple worlds found; one must be explicitly chosen:{}",
1419                        worlds
1420                            .iter()
1421                            .map(|(pkg, world)| format!(
1422                                "\n  {}/{}",
1423                                self.packages[*pkg].name, self.worlds[*world].name
1424                            ))
1425                            .collect::<String>()
1426                    ),
1427                }
1428            }
1429        };
1430        let pkg = &self.packages[pkg];
1431        pkg.worlds
1432            .get(&world_name)
1433            .copied()
1434            .ok_or_else(|| anyhow!("no world named `{world_name}` in package"))
1435    }
1436
1437    /// Assigns a human readable name to the `WorldKey` specified.
1438    pub fn name_world_key(&self, key: &WorldKey) -> String {
1439        match key {
1440            WorldKey::Name(s) => s.to_string(),
1441            WorldKey::Interface(i) => self.id_of(*i).expect("unexpected anonymous interface"),
1442        }
1443    }
1444
1445    /// Same as [`Resolve::name_world_key`] except that `WorldKey::Interfaces`
1446    /// uses [`Resolve::canonicalized_id_of`].
1447    pub fn name_canonicalized_world_key(&self, key: &WorldKey) -> String {
1448        match key {
1449            WorldKey::Name(s) => s.to_string(),
1450            WorldKey::Interface(i) => self
1451                .canonicalized_id_of(*i)
1452                .expect("unexpected anonymous interface"),
1453        }
1454    }
1455
1456    /// Returns the interface that `id` uses a type from, if it uses a type from
1457    /// a different interface than `id` is defined within.
1458    ///
1459    /// If `id` is not a use-of-a-type or it's using a type in the same
1460    /// interface then `None` is returned.
1461    pub fn type_interface_dep(&self, id: TypeId) -> Option<InterfaceId> {
1462        let ty = &self.types[id];
1463        let dep = match ty.kind {
1464            TypeDefKind::Type(Type::Id(id)) => id,
1465            _ => return None,
1466        };
1467        let other = &self.types[dep];
1468        if ty.owner == other.owner {
1469            None
1470        } else {
1471            match other.owner {
1472                TypeOwner::Interface(id) => Some(id),
1473                _ => unreachable!(),
1474            }
1475        }
1476    }
1477
1478    /// Returns an iterator of all interfaces that the interface `id` depends
1479    /// on.
1480    ///
1481    /// Interfaces may depend on others for type information to resolve type
1482    /// imports.
1483    ///
1484    /// Note that the returned iterator may yield the same interface as a
1485    /// dependency multiple times. Additionally only direct dependencies of `id`
1486    /// are yielded, not transitive dependencies.
1487    pub fn interface_direct_deps(&self, id: InterfaceId) -> impl Iterator<Item = InterfaceId> + '_ {
1488        self.interfaces[id]
1489            .types
1490            .iter()
1491            .filter_map(move |(_name, ty)| self.type_interface_dep(*ty))
1492    }
1493
1494    /// Returns an iterator of all packages that the package `id` depends
1495    /// on.
1496    ///
1497    /// Packages may depend on others for type information to resolve type
1498    /// imports or interfaces to resolve worlds.
1499    ///
1500    /// Note that the returned iterator may yield the same package as a
1501    /// dependency multiple times. Additionally only direct dependencies of `id`
1502    /// are yielded, not transitive dependencies.
1503    pub fn package_direct_deps(&self, id: PackageId) -> impl Iterator<Item = PackageId> + '_ {
1504        let pkg = &self.packages[id];
1505
1506        pkg.interfaces
1507            .iter()
1508            .flat_map(move |(_name, id)| self.interface_direct_deps(*id))
1509            .chain(pkg.worlds.iter().flat_map(move |(_name, id)| {
1510                let world = &self.worlds[*id];
1511                world
1512                    .imports
1513                    .iter()
1514                    .chain(world.exports.iter())
1515                    .filter_map(move |(_name, item)| match item {
1516                        WorldItem::Interface { id, .. } => Some(*id),
1517                        WorldItem::Function(_) => None,
1518                        WorldItem::Type(t) => self.type_interface_dep(*t),
1519                    })
1520            }))
1521            .filter_map(move |iface_id| {
1522                let pkg = self.interfaces[iface_id].package?;
1523                if pkg == id {
1524                    None
1525                } else {
1526                    Some(pkg)
1527                }
1528            })
1529    }
1530
1531    /// Returns a topological ordering of packages contained in this `Resolve`.
1532    ///
1533    /// This returns a list of `PackageId` such that when visited in order it's
1534    /// guaranteed that all dependencies will have been defined by prior items
1535    /// in the list.
1536    pub fn topological_packages(&self) -> Vec<PackageId> {
1537        let mut pushed = vec![false; self.packages.len()];
1538        let mut order = Vec::new();
1539        for (id, _) in self.packages.iter() {
1540            self.build_topological_package_ordering(id, &mut pushed, &mut order);
1541        }
1542        order
1543    }
1544
1545    fn build_topological_package_ordering(
1546        &self,
1547        id: PackageId,
1548        pushed: &mut Vec<bool>,
1549        order: &mut Vec<PackageId>,
1550    ) {
1551        if pushed[id.index()] {
1552            return;
1553        }
1554        for dep in self.package_direct_deps(id) {
1555            self.build_topological_package_ordering(dep, pushed, order);
1556        }
1557        order.push(id);
1558        pushed[id.index()] = true;
1559    }
1560
1561    #[doc(hidden)]
1562    pub fn assert_valid(&self) {
1563        let mut package_interfaces = Vec::new();
1564        let mut package_worlds = Vec::new();
1565        for (id, pkg) in self.packages.iter() {
1566            let mut interfaces = HashSet::new();
1567            for (name, iface) in pkg.interfaces.iter() {
1568                assert!(interfaces.insert(*iface));
1569                let iface = &self.interfaces[*iface];
1570                assert_eq!(name, iface.name.as_ref().unwrap());
1571                assert_eq!(iface.package.unwrap(), id);
1572            }
1573            package_interfaces.push(pkg.interfaces.values().copied().collect::<HashSet<_>>());
1574            let mut worlds = HashSet::new();
1575            for (name, world) in pkg.worlds.iter() {
1576                assert!(worlds.insert(*world));
1577                assert_eq!(
1578                    pkg.worlds.get_key_value(name),
1579                    Some((name, world)),
1580                    "`MutableKeys` impl may have been used to change a key's hash or equality"
1581                );
1582                let world = &self.worlds[*world];
1583                assert_eq!(*name, world.name);
1584                assert_eq!(world.package.unwrap(), id);
1585            }
1586            package_worlds.push(pkg.worlds.values().copied().collect::<HashSet<_>>());
1587        }
1588
1589        let mut interface_types = Vec::new();
1590        for (id, iface) in self.interfaces.iter() {
1591            assert!(self.packages.get(iface.package.unwrap()).is_some());
1592            if iface.name.is_some() {
1593                assert!(package_interfaces[iface.package.unwrap().index()].contains(&id));
1594            }
1595
1596            for (name, ty) in iface.types.iter() {
1597                let ty = &self.types[*ty];
1598                assert_eq!(ty.name.as_ref(), Some(name));
1599                assert_eq!(ty.owner, TypeOwner::Interface(id));
1600            }
1601            interface_types.push(iface.types.values().copied().collect::<HashSet<_>>());
1602            for (name, f) in iface.functions.iter() {
1603                assert_eq!(*name, f.name);
1604            }
1605        }
1606
1607        let mut world_types = Vec::new();
1608        for (id, world) in self.worlds.iter() {
1609            log::debug!("validating world {}", &world.name);
1610            if let Some(package) = world.package {
1611                assert!(self.packages.get(package).is_some());
1612                assert!(package_worlds[package.index()].contains(&id));
1613            }
1614            assert!(world.includes.is_empty());
1615
1616            let mut types = HashSet::new();
1617            for (name, item) in world.imports.iter().chain(world.exports.iter()) {
1618                log::debug!("validating world item: {}", self.name_world_key(name));
1619                match item {
1620                    WorldItem::Interface { id, .. } => {
1621                        // anonymous interfaces must belong to the same package
1622                        // as the world's package.
1623                        if matches!(name, WorldKey::Name(_)) {
1624                            assert_eq!(self.interfaces[*id].package, world.package);
1625                        }
1626                    }
1627                    WorldItem::Function(f) => {
1628                        assert!(!matches!(name, WorldKey::Interface(_)));
1629                        assert_eq!(f.name, name.clone().unwrap_name());
1630                    }
1631                    WorldItem::Type(ty) => {
1632                        assert!(!matches!(name, WorldKey::Interface(_)));
1633                        assert!(types.insert(*ty));
1634                        let ty = &self.types[*ty];
1635                        assert_eq!(ty.name, Some(name.clone().unwrap_name()));
1636                        assert_eq!(ty.owner, TypeOwner::World(id));
1637                    }
1638                }
1639            }
1640            self.assert_world_elaborated(world);
1641            world_types.push(types);
1642        }
1643
1644        for (ty_id, ty) in self.types.iter() {
1645            match ty.owner {
1646                TypeOwner::Interface(id) => {
1647                    assert!(self.interfaces.get(id).is_some());
1648                    assert!(interface_types[id.index()].contains(&ty_id));
1649                }
1650                TypeOwner::World(id) => {
1651                    assert!(self.worlds.get(id).is_some());
1652                    assert!(world_types[id.index()].contains(&ty_id));
1653                }
1654                TypeOwner::None => {}
1655            }
1656        }
1657
1658        self.assert_topologically_sorted();
1659    }
1660
1661    fn assert_topologically_sorted(&self) {
1662        let mut positions = IndexMap::new();
1663        for id in self.topological_packages() {
1664            let pkg = &self.packages[id];
1665            log::debug!("pkg {}", pkg.name);
1666            let prev = positions.insert(Some(id), IndexSet::new());
1667            assert!(prev.is_none());
1668        }
1669        positions.insert(None, IndexSet::new());
1670
1671        for (id, iface) in self.interfaces.iter() {
1672            log::debug!("iface {:?}", iface.name);
1673            let ok = positions.get_mut(&iface.package).unwrap().insert(id);
1674            assert!(ok);
1675        }
1676
1677        for (_, world) in self.worlds.iter() {
1678            log::debug!("world {:?}", world.name);
1679
1680            let my_package = world.package;
1681            let my_package_pos = positions.get_index_of(&my_package).unwrap();
1682
1683            for (_, item) in world.imports.iter().chain(&world.exports) {
1684                let id = match item {
1685                    WorldItem::Interface { id, .. } => *id,
1686                    _ => continue,
1687                };
1688                let other_package = self.interfaces[id].package;
1689                let other_package_pos = positions.get_index_of(&other_package).unwrap();
1690
1691                assert!(other_package_pos <= my_package_pos);
1692            }
1693        }
1694
1695        for (_id, ty) in self.types.iter() {
1696            log::debug!("type {:?} {:?}", ty.name, ty.owner);
1697            let other_id = match ty.kind {
1698                TypeDefKind::Type(Type::Id(ty)) => ty,
1699                _ => continue,
1700            };
1701            let other = &self.types[other_id];
1702            if ty.kind == other.kind {
1703                continue;
1704            }
1705            let my_interface = match ty.owner {
1706                TypeOwner::Interface(id) => id,
1707                _ => continue,
1708            };
1709            let other_interface = match other.owner {
1710                TypeOwner::Interface(id) => id,
1711                _ => continue,
1712            };
1713
1714            let my_package = self.interfaces[my_interface].package;
1715            let other_package = self.interfaces[other_interface].package;
1716            let my_package_pos = positions.get_index_of(&my_package).unwrap();
1717            let other_package_pos = positions.get_index_of(&other_package).unwrap();
1718
1719            if my_package_pos == other_package_pos {
1720                let interfaces = &positions[&my_package];
1721                let my_interface_pos = interfaces.get_index_of(&my_interface).unwrap();
1722                let other_interface_pos = interfaces.get_index_of(&other_interface).unwrap();
1723                assert!(other_interface_pos <= my_interface_pos);
1724            } else {
1725                assert!(other_package_pos < my_package_pos);
1726            }
1727        }
1728    }
1729
1730    fn assert_world_elaborated(&self, world: &World) {
1731        for (key, item) in world.imports.iter() {
1732            log::debug!(
1733                "asserting elaborated world import {}",
1734                self.name_world_key(key)
1735            );
1736            match item {
1737                WorldItem::Type(t) => self.assert_world_imports_type_deps(world, key, *t),
1738
1739                // All types referred to must be imported.
1740                WorldItem::Function(f) => self.assert_world_function_imports_types(world, key, f),
1741
1742                // All direct dependencies of this interface must be imported.
1743                WorldItem::Interface { id, .. } => {
1744                    for dep in self.interface_direct_deps(*id) {
1745                        assert!(
1746                            world.imports.contains_key(&WorldKey::Interface(dep)),
1747                            "world import of {} is missing transitive dep of {}",
1748                            self.name_world_key(key),
1749                            self.id_of(dep).unwrap(),
1750                        );
1751                    }
1752                }
1753            }
1754        }
1755        for (key, item) in world.exports.iter() {
1756            log::debug!(
1757                "asserting elaborated world export {}",
1758                self.name_world_key(key)
1759            );
1760            match item {
1761                // Types referred to by this function must be imported.
1762                WorldItem::Function(f) => self.assert_world_function_imports_types(world, key, f),
1763
1764                // Dependencies of exported interfaces must also be exported, or
1765                // if imported then that entire chain of imports must be
1766                // imported and not exported.
1767                WorldItem::Interface { id, .. } => {
1768                    for dep in self.interface_direct_deps(*id) {
1769                        let dep_key = WorldKey::Interface(dep);
1770                        if world.exports.contains_key(&dep_key) {
1771                            continue;
1772                        }
1773                        self.foreach_interface_dep(dep, &mut |dep| {
1774                            let dep_key = WorldKey::Interface(dep);
1775                            assert!(
1776                                world.imports.contains_key(&dep_key),
1777                                "world should import {} (required by {})",
1778                                self.name_world_key(&dep_key),
1779                                self.name_world_key(key),
1780                            );
1781                            assert!(
1782                                !world.exports.contains_key(&dep_key),
1783                                "world should not export {} (required by {})",
1784                                self.name_world_key(&dep_key),
1785                                self.name_world_key(key),
1786                            );
1787                        });
1788                    }
1789                }
1790
1791                // exported types not allowed at this time
1792                WorldItem::Type(_) => unreachable!(),
1793            }
1794        }
1795    }
1796
1797    fn assert_world_imports_type_deps(&self, world: &World, key: &WorldKey, ty: TypeId) {
1798        // If this is a `use` statement then the referred-to interface must be
1799        // imported into this world.
1800        let ty = &self.types[ty];
1801        if let TypeDefKind::Type(Type::Id(other)) = ty.kind {
1802            if let TypeOwner::Interface(id) = self.types[other].owner {
1803                let key = WorldKey::Interface(id);
1804                assert!(world.imports.contains_key(&key));
1805                return;
1806            }
1807        }
1808
1809        // ... otherwise any named type that this type refers to, one level
1810        // deep, must be imported into this world under that name.
1811
1812        let mut visitor = MyVisit(self, Vec::new());
1813        visitor.visit_type_def(self, ty);
1814        for ty in visitor.1 {
1815            let ty = &self.types[ty];
1816            let Some(name) = ty.name.clone() else {
1817                continue;
1818            };
1819            let dep_key = WorldKey::Name(name);
1820            assert!(
1821                world.imports.contains_key(&dep_key),
1822                "world import `{}` should also force an import of `{}`",
1823                self.name_world_key(key),
1824                self.name_world_key(&dep_key),
1825            );
1826        }
1827
1828        struct MyVisit<'a>(&'a Resolve, Vec<TypeId>);
1829
1830        impl TypeIdVisitor for MyVisit<'_> {
1831            fn before_visit_type_id(&mut self, id: TypeId) -> bool {
1832                self.1.push(id);
1833                // recurse into unnamed types to look at all named types
1834                self.0.types[id].name.is_none()
1835            }
1836        }
1837    }
1838
1839    /// This asserts that all types referred to by `func` are imported into
1840    /// `world` under `WorldKey::Name`. Note that this is only applicable to
1841    /// named type
1842    fn assert_world_function_imports_types(&self, world: &World, key: &WorldKey, func: &Function) {
1843        for ty in func
1844            .parameter_and_result_types()
1845            .chain(func.kind.resource().map(Type::Id))
1846        {
1847            let Type::Id(id) = ty else {
1848                continue;
1849            };
1850            self.assert_world_imports_type_deps(world, key, id);
1851        }
1852    }
1853
1854    /// Returns whether the `stability` annotation contained within `pkg_id`
1855    /// should be included or not.
1856    ///
1857    /// The `span` provided here is an optional span pointing to the item that
1858    /// is annotated with `stability`.
1859    ///
1860    /// Returns `Ok(true)` if the item is included, or `Ok(false)` if the item
1861    /// is not.
1862    ///
1863    /// # Errors
1864    ///
1865    /// Returns an error if the `pkg_id` isn't annotated with sufficient version
1866    /// information to have a `stability` annotation. For example if `pkg_id`
1867    /// has no version listed then an error will be returned if `stability`
1868    /// mentions a version.
1869    fn include_stability(
1870        &self,
1871        stability: &Stability,
1872        pkg_id: &PackageId,
1873        span: Option<Span>,
1874    ) -> Result<bool> {
1875        let err = |msg: String| match span {
1876            Some(span) => Error::new(span, msg).into(),
1877            None => anyhow::Error::msg(msg),
1878        };
1879        Ok(match stability {
1880            Stability::Unknown => true,
1881            // NOTE: deprecations are intentionally omitted -- an existing
1882            // `@since` takes precedence over `@deprecated`
1883            Stability::Stable { since, .. } => {
1884                let Some(p) = self.packages.get(*pkg_id) else {
1885                    // We can't check much without a package (possibly dealing
1886                    // with an item in an `UnresolvedPackage`), @since version &
1887                    // deprecations can't be checked because there's no package
1888                    // version to compare to.
1889                    //
1890                    // Feature requirements on stabilized features are ignored
1891                    // in resolved packages, so we do the same here.
1892                    return Ok(true);
1893                };
1894
1895                // Use of feature gating with version specifiers inside a
1896                // package that is not versioned is not allowed
1897                let package_version = p.name.version.as_ref().ok_or_else(|| {
1898                    err(format!(
1899                        "package [{}] contains a feature gate with a version \
1900                         specifier, so it must have a version",
1901                        p.name
1902                    ))
1903                })?;
1904
1905                // If the version on the feature gate is:
1906                // - released, then we can include it
1907                // - unreleased, then we must check the feature (if present)
1908                if since > package_version {
1909                    return Err(err(format!(
1910                        "feature gate cannot reference unreleased version \
1911                        {since} of package [{}] (current version {package_version})",
1912                        p.name
1913                    )));
1914                }
1915
1916                true
1917            }
1918            Stability::Unstable { feature, .. } => {
1919                self.features.contains(feature) || self.all_features
1920            }
1921        })
1922    }
1923
1924    /// Convenience wrapper around `include_stability` specialized for types
1925    /// with a more targeted error message.
1926    fn include_type(&self, ty: &TypeDef, pkgid: PackageId, span: Span) -> Result<bool> {
1927        self.include_stability(&ty.stability, &pkgid, Some(span))
1928            .with_context(|| {
1929                format!(
1930                    "failed to process feature gate for type [{}] in package [{}]",
1931                    ty.name.as_ref().map(String::as_str).unwrap_or("<unknown>"),
1932                    self.packages[pkgid].name,
1933                )
1934            })
1935    }
1936
1937    /// Performs the "elaboration process" necessary for the `world_id`
1938    /// specified to ensure that all of its transitive imports are listed.
1939    ///
1940    /// This function will take the unordered lists of the specified world's
1941    /// imports and exports and "elaborate" them to ensure that they're
1942    /// topographically sorted where all transitively required interfaces by
1943    /// imports, or exports, are listed. This will additionally validate that
1944    /// the exports are all valid and present, specifically with the restriction
1945    /// noted on `elaborate_world_exports`.
1946    ///
1947    /// The world is mutated in-place in this `Resolve`.
1948    fn elaborate_world(&mut self, world_id: WorldId) -> Result<()> {
1949        // First process all imports. This is easier than exports since the only
1950        // requirement here is that all interfaces need to be added with a
1951        // topological order between them.
1952        let mut new_imports = IndexMap::new();
1953        let world = &self.worlds[world_id];
1954
1955        // Sort the imports by "class" to ensure that this matches the order
1956        // that items are printed and that items are in topological order.
1957        //
1958        // When printing worlds in WIT:
1959        //
1960        // * interfaces come first
1961        // * types are next
1962        //   * type imports are first
1963        //   * type definitions are next
1964        //   * resource definitions have methods printed inline
1965        // * freestanding functions are last
1966        //
1967        // This reflects the topological order between items where types
1968        // can refer to imports and functions can refer to these types. Ordering
1969        // within a single class (e.g. imports depending on each other, types
1970        // referring to each other) is already preserved by other passes in this
1971        // file and general AST resolution. That means that a stable sort here
1972        // can be used to ensure that each class is in the right location
1973        // relative to the others.
1974        //
1975        // Overall this ensures that round-trips of WIT through wasm should
1976        // always produce the same result.
1977        let sort_key = |resolve: &Resolve, item: &WorldItem| match item {
1978            WorldItem::Interface { .. } => 0,
1979            WorldItem::Type(ty) => {
1980                let ty = &resolve.types[*ty];
1981                match ty.kind {
1982                    TypeDefKind::Type(Type::Id(t)) if resolve.types[t].owner != ty.owner => 1,
1983                    _ => 2,
1984                }
1985            }
1986            WorldItem::Function(f) => {
1987                if f.kind.resource().is_none() {
1988                    3
1989                } else {
1990                    4
1991                }
1992            }
1993        };
1994
1995        // Sort world items when we start to elaborate the world to start with a
1996        // topological view of items.
1997        let mut world_imports = world.imports.iter().collect::<Vec<_>>();
1998        world_imports.sort_by_key(|(_name, import)| sort_key(self, import));
1999        for (name, item) in world_imports {
2000            match item {
2001                // Interfaces get their dependencies added first followed by the
2002                // interface itself.
2003                WorldItem::Interface { id, stability } => {
2004                    self.elaborate_world_import(&mut new_imports, name.clone(), *id, &stability);
2005                }
2006
2007                // Functions are added as-is since their dependence on types in
2008                // the world should already be satisfied.
2009                WorldItem::Function(_) => {
2010                    let prev = new_imports.insert(name.clone(), item.clone());
2011                    assert!(prev.is_none());
2012                }
2013
2014                // Types may depend on an interface, in which case a (possibly)
2015                // recursive addition of that interface happens here. Afterwards
2016                // the type itself can be added safely.
2017                WorldItem::Type(id) => {
2018                    if let Some(dep) = self.type_interface_dep(*id) {
2019                        self.elaborate_world_import(
2020                            &mut new_imports,
2021                            WorldKey::Interface(dep),
2022                            dep,
2023                            &self.types[*id].stability,
2024                        );
2025                    }
2026                    let prev = new_imports.insert(name.clone(), item.clone());
2027                    assert!(prev.is_none());
2028                }
2029            }
2030        }
2031
2032        // Exports are trickier than imports, notably to uphold the invariant
2033        // required by `elaborate_world_exports`. To do this the exports are
2034        // partitioned into interfaces/functions. All functions are added to
2035        // the new exports list during this loop but interfaces are all deferred
2036        // to be handled in the `elaborate_world_exports` function.
2037        let mut new_exports = IndexMap::new();
2038        let mut export_interfaces = IndexMap::new();
2039        for (name, item) in world.exports.iter() {
2040            match item {
2041                WorldItem::Interface { id, stability } => {
2042                    let prev = export_interfaces.insert(*id, (name.clone(), stability));
2043                    assert!(prev.is_none());
2044                }
2045                WorldItem::Function(_) => {
2046                    let prev = new_exports.insert(name.clone(), item.clone());
2047                    assert!(prev.is_none());
2048                }
2049                WorldItem::Type(_) => unreachable!(),
2050            }
2051        }
2052
2053        self.elaborate_world_exports(&export_interfaces, &mut new_imports, &mut new_exports)?;
2054
2055        // In addition to sorting at the start of elaboration also sort here at
2056        // the end of elaboration to handle types being interspersed with
2057        // interfaces as they're found.
2058        new_imports.sort_by_cached_key(|_name, import| sort_key(self, import));
2059
2060        // And with all that done the world is updated in-place with
2061        // imports/exports.
2062        log::trace!("imports = {:?}", new_imports);
2063        log::trace!("exports = {:?}", new_exports);
2064        let world = &mut self.worlds[world_id];
2065        world.imports = new_imports;
2066        world.exports = new_exports;
2067
2068        Ok(())
2069    }
2070
2071    fn elaborate_world_import(
2072        &self,
2073        imports: &mut IndexMap<WorldKey, WorldItem>,
2074        key: WorldKey,
2075        id: InterfaceId,
2076        stability: &Stability,
2077    ) {
2078        if imports.contains_key(&key) {
2079            return;
2080        }
2081        for dep in self.interface_direct_deps(id) {
2082            self.elaborate_world_import(imports, WorldKey::Interface(dep), dep, stability);
2083        }
2084        let prev = imports.insert(
2085            key,
2086            WorldItem::Interface {
2087                id,
2088                stability: stability.clone(),
2089            },
2090        );
2091        assert!(prev.is_none());
2092    }
2093
2094    /// This function adds all of the interfaces in `export_interfaces` to the
2095    /// list of exports of the `world` specified.
2096    ///
2097    /// This method is more involved than adding imports because it is fallible.
2098    /// Chiefly what can happen is that the dependencies of all exports must be
2099    /// satisfied by other exports or imports, but not both. For example given a
2100    /// situation such as:
2101    ///
2102    /// ```wit
2103    /// interface a {
2104    ///     type t = u32
2105    /// }
2106    /// interface b {
2107    ///     use a.{t}
2108    /// }
2109    /// interface c {
2110    ///     use a.{t}
2111    ///     use b.{t as t2}
2112    /// }
2113    /// ```
2114    ///
2115    /// where `c` depends on `b` and `a` where `b` depends on `a`, then the
2116    /// purpose of this method is to reject this world:
2117    ///
2118    /// ```wit
2119    /// world foo {
2120    ///     export a
2121    ///     export c
2122    /// }
2123    /// ```
2124    ///
2125    /// The reasoning here is unfortunately subtle and is additionally the
2126    /// subject of WebAssembly/component-model#208. Effectively the `c`
2127    /// interface depends on `b`, but it's not listed explicitly as an import,
2128    /// so it's then implicitly added as an import. This then transitively
2129    /// depends on `a` so it's also added as an import. At this point though `c`
2130    /// also depends on `a`, and it's also exported, so naively it should depend
2131    /// on the export and not implicitly add an import. This means though that
2132    /// `c` has access to two copies of `a`, one imported and one exported. This
2133    /// is not valid, especially in the face of resource types.
2134    ///
2135    /// Overall this method is tasked with rejecting the above world by walking
2136    /// over all the exports and adding their dependencies. Each dependency is
2137    /// recorded with whether it's required to be imported, and then if an
2138    /// export is added for something that's required to be an error then the
2139    /// operation fails.
2140    fn elaborate_world_exports(
2141        &self,
2142        export_interfaces: &IndexMap<InterfaceId, (WorldKey, &Stability)>,
2143        imports: &mut IndexMap<WorldKey, WorldItem>,
2144        exports: &mut IndexMap<WorldKey, WorldItem>,
2145    ) -> Result<()> {
2146        let mut required_imports = HashSet::new();
2147        for (id, (key, stability)) in export_interfaces.iter() {
2148            let name = self.name_world_key(&key);
2149            let ok = add_world_export(
2150                self,
2151                imports,
2152                exports,
2153                export_interfaces,
2154                &mut required_imports,
2155                *id,
2156                key,
2157                true,
2158                stability,
2159            );
2160            if !ok {
2161                bail!(
2162                    // FIXME: this is not a great error message and basically no
2163                    // one will know what to do when it gets printed. Improving
2164                    // this error message, however, is a chunk of work that may
2165                    // not be best spent doing this at this time, so I'm writing
2166                    // this comment instead.
2167                    //
2168                    // More-or-less what should happen here is that a "path"
2169                    // from this interface to the conflicting interface should
2170                    // be printed. It should be explained why an import is being
2171                    // injected, why that's conflicting with an export, and
2172                    // ideally with a suggestion of "add this interface to the
2173                    // export list to fix this error".
2174                    //
2175                    // That's a lot of info that's not easy to get at without
2176                    // more refactoring, so it's left to a future date in the
2177                    // hopes that most folks won't actually run into this for
2178                    // the time being.
2179                    InvalidTransitiveDependency(name),
2180                );
2181            }
2182        }
2183        return Ok(());
2184
2185        fn add_world_export(
2186            resolve: &Resolve,
2187            imports: &mut IndexMap<WorldKey, WorldItem>,
2188            exports: &mut IndexMap<WorldKey, WorldItem>,
2189            export_interfaces: &IndexMap<InterfaceId, (WorldKey, &Stability)>,
2190            required_imports: &mut HashSet<InterfaceId>,
2191            id: InterfaceId,
2192            key: &WorldKey,
2193            add_export: bool,
2194            stability: &Stability,
2195        ) -> bool {
2196            if exports.contains_key(key) {
2197                if add_export {
2198                    return true;
2199                } else {
2200                    return false;
2201                }
2202            }
2203            // If this is an import and it's already in the `required_imports`
2204            // set then we can skip it as we've already visited this interface.
2205            if !add_export && required_imports.contains(&id) {
2206                return true;
2207            }
2208            let ok = resolve.interface_direct_deps(id).all(|dep| {
2209                let key = WorldKey::Interface(dep);
2210                let add_export = add_export && export_interfaces.contains_key(&dep);
2211                add_world_export(
2212                    resolve,
2213                    imports,
2214                    exports,
2215                    export_interfaces,
2216                    required_imports,
2217                    dep,
2218                    &key,
2219                    add_export,
2220                    stability,
2221                )
2222            });
2223            if !ok {
2224                return false;
2225            }
2226            let item = WorldItem::Interface {
2227                id,
2228                stability: stability.clone(),
2229            };
2230            if add_export {
2231                if required_imports.contains(&id) {
2232                    return false;
2233                }
2234                exports.insert(key.clone(), item);
2235            } else {
2236                required_imports.insert(id);
2237                imports.insert(key.clone(), item);
2238            }
2239            true
2240        }
2241    }
2242
2243    /// Remove duplicate imports from a world if they import from the same
2244    /// interface with semver-compatible versions.
2245    ///
2246    /// This will merge duplicate interfaces present at multiple versions in
2247    /// both a world by selecting the larger version of the two interfaces. This
2248    /// requires that the interfaces are indeed semver-compatible and it means
2249    /// that some imports might be removed and replaced. Note that this is only
2250    /// done within a single semver track, for example the world imports 0.2.0
2251    /// and 0.2.1 then the result afterwards will be that it imports
2252    /// 0.2.1. If, however, 0.3.0 where imported then the final result would
2253    /// import both 0.2.0 and 0.3.0.
2254    pub fn merge_world_imports_based_on_semver(&mut self, world_id: WorldId) -> Result<()> {
2255        let world = &self.worlds[world_id];
2256
2257        // The first pass here is to build a map of "semver tracks" where they
2258        // key is per-interface and the value is the maximal version found in
2259        // that semver-compatible-track plus the interface which is the maximal
2260        // version.
2261        //
2262        // At the same time a `to_remove` set is maintained to remember what
2263        // interfaces are being removed from `from` and `into`. All of
2264        // `to_remove` are placed with a known other version.
2265        let mut semver_tracks = HashMap::new();
2266        let mut to_remove = HashSet::new();
2267        for (key, _) in world.imports.iter() {
2268            let iface_id = match key {
2269                WorldKey::Interface(id) => *id,
2270                WorldKey::Name(_) => continue,
2271            };
2272            let (track, version) = match self.semver_track(iface_id) {
2273                Some(track) => track,
2274                None => continue,
2275            };
2276            log::debug!(
2277                "{} is on track {}/{}",
2278                self.id_of(iface_id).unwrap(),
2279                track.0,
2280                track.1,
2281            );
2282            match semver_tracks.entry(track.clone()) {
2283                hash_map::Entry::Vacant(e) => {
2284                    e.insert((version, iface_id));
2285                }
2286                hash_map::Entry::Occupied(mut e) => match version.cmp(&e.get().0) {
2287                    Ordering::Greater => {
2288                        to_remove.insert(e.get().1);
2289                        e.insert((version, iface_id));
2290                    }
2291                    Ordering::Equal => {}
2292                    Ordering::Less => {
2293                        to_remove.insert(iface_id);
2294                    }
2295                },
2296            }
2297        }
2298
2299        // Build a map of "this interface is replaced with this interface" using
2300        // the results of the loop above.
2301        let mut replacements = HashMap::new();
2302        for id in to_remove {
2303            let (track, _) = self.semver_track(id).unwrap();
2304            let (_, latest) = semver_tracks[&track];
2305            let prev = replacements.insert(id, latest);
2306            assert!(prev.is_none());
2307        }
2308
2309        // Validate that `merge_world_item` succeeds for merging all removed
2310        // interfaces with their replacement. This is a double-check that the
2311        // semver version is actually correct and all items present in the old
2312        // interface are in the new.
2313        for (to_replace, replace_with) in replacements.iter() {
2314            self.merge_world_item(
2315                &WorldItem::Interface {
2316                    id: *to_replace,
2317                    stability: Default::default(),
2318                },
2319                &WorldItem::Interface {
2320                    id: *replace_with,
2321                    stability: Default::default(),
2322                },
2323            )
2324            .with_context(|| {
2325                let old_name = self.id_of(*to_replace).unwrap();
2326                let new_name = self.id_of(*replace_with).unwrap();
2327                format!(
2328                    "failed to upgrade `{old_name}` to `{new_name}`, was \
2329                     this semver-compatible update not semver compatible?"
2330                )
2331            })?;
2332        }
2333
2334        for (to_replace, replace_with) in replacements.iter() {
2335            log::debug!(
2336                "REPLACE {} => {}",
2337                self.id_of(*to_replace).unwrap(),
2338                self.id_of(*replace_with).unwrap(),
2339            );
2340        }
2341
2342        // Finally perform the actual transformation of the imports/exports.
2343        // Here all imports are removed if they're replaced and otherwise all
2344        // imports have their dependencies updated, possibly transitively, to
2345        // point to the new interfaces in `replacements`.
2346        //
2347        // Afterwards exports are additionally updated, but only their
2348        // dependencies on imports which were remapped. Exports themselves are
2349        // not deduplicated and/or removed.
2350        for (key, item) in mem::take(&mut self.worlds[world_id].imports) {
2351            if let WorldItem::Interface { id, .. } = item {
2352                if replacements.contains_key(&id) {
2353                    continue;
2354                }
2355            }
2356
2357            self.update_interface_deps_of_world_item(&item, &replacements);
2358
2359            let prev = self.worlds[world_id].imports.insert(key, item);
2360            assert!(prev.is_none());
2361        }
2362        for (key, item) in mem::take(&mut self.worlds[world_id].exports) {
2363            self.update_interface_deps_of_world_item(&item, &replacements);
2364            let prev = self.worlds[world_id].exports.insert(key, item);
2365            assert!(prev.is_none());
2366        }
2367
2368        // Run through `elaborate_world` to reorder imports as appropriate and
2369        // fill anything back in if it's actually required by exports. For now
2370        // this doesn't tamper with exports at all. Also note that this is
2371        // applied to all worlds in this `Resolve` because interfaces were
2372        // modified directly.
2373        let ids = self.worlds.iter().map(|(id, _)| id).collect::<Vec<_>>();
2374        for world_id in ids {
2375            self.elaborate_world(world_id).with_context(|| {
2376                let name = &self.worlds[world_id].name;
2377                format!(
2378                    "failed to elaborate world `{name}` after deduplicating imports \
2379                     based on semver"
2380                )
2381            })?;
2382        }
2383
2384        #[cfg(debug_assertions)]
2385        self.assert_valid();
2386
2387        Ok(())
2388    }
2389
2390    fn update_interface_deps_of_world_item(
2391        &mut self,
2392        item: &WorldItem,
2393        replacements: &HashMap<InterfaceId, InterfaceId>,
2394    ) {
2395        match *item {
2396            WorldItem::Type(t) => self.update_interface_dep_of_type(t, &replacements),
2397            WorldItem::Interface { id, .. } => {
2398                let types = self.interfaces[id]
2399                    .types
2400                    .values()
2401                    .copied()
2402                    .collect::<Vec<_>>();
2403                for ty in types {
2404                    self.update_interface_dep_of_type(ty, &replacements);
2405                }
2406            }
2407            WorldItem::Function(_) => {}
2408        }
2409    }
2410
2411    /// Returns the "semver track" of an interface plus the interface's version.
2412    ///
2413    /// This function returns `None` if the interface `id` has a package without
2414    /// a version. If the version is present, however, the first element of the
2415    /// tuple returned is a "semver track" for the specific interface. The
2416    /// version listed in `PackageName` will be modified so all
2417    /// semver-compatible versions are listed the same way.
2418    ///
2419    /// The second element in the returned tuple is this interface's package's
2420    /// version.
2421    fn semver_track(&self, id: InterfaceId) -> Option<((PackageName, String), &Version)> {
2422        let iface = &self.interfaces[id];
2423        let pkg = &self.packages[iface.package?];
2424        let version = pkg.name.version.as_ref()?;
2425        let mut name = pkg.name.clone();
2426        name.version = Some(PackageName::version_compat_track(version));
2427        Some(((name, iface.name.clone()?), version))
2428    }
2429
2430    /// If `ty` is a definition where it's a `use` from another interface, then
2431    /// change what interface it's using from according to the pairs in the
2432    /// `replacements` map.
2433    fn update_interface_dep_of_type(
2434        &mut self,
2435        ty: TypeId,
2436        replacements: &HashMap<InterfaceId, InterfaceId>,
2437    ) {
2438        let to_replace = match self.type_interface_dep(ty) {
2439            Some(id) => id,
2440            None => return,
2441        };
2442        let replace_with = match replacements.get(&to_replace) {
2443            Some(id) => id,
2444            None => return,
2445        };
2446        let dep = match self.types[ty].kind {
2447            TypeDefKind::Type(Type::Id(id)) => id,
2448            _ => return,
2449        };
2450        let name = self.types[dep].name.as_ref().unwrap();
2451        // Note the infallible name indexing happening here. This should be
2452        // previously validated with `merge_world_item` to succeed.
2453        let replacement_id = self.interfaces[*replace_with].types[name];
2454        self.types[ty].kind = TypeDefKind::Type(Type::Id(replacement_id));
2455    }
2456
2457    /// Returns the core wasm module/field names for the specified `import`.
2458    ///
2459    /// This function will return the core wasm module/field that can be used to
2460    /// use `import` with the name `mangling` scheme specified as well. This can
2461    /// be useful for bindings generators, for example, and these names are
2462    /// recognized by `wit-component` and `wasm-tools component new`.
2463    pub fn wasm_import_name(
2464        &self,
2465        mangling: ManglingAndAbi,
2466        import: WasmImport<'_>,
2467    ) -> (String, String) {
2468        match mangling {
2469            ManglingAndAbi::Standard32 => match import {
2470                WasmImport::Func { interface, func } => {
2471                    let module = match interface {
2472                        Some(key) => format!("cm32p2|{}", self.name_canonicalized_world_key(key)),
2473                        None => format!("cm32p2"),
2474                    };
2475                    (module, func.name.clone())
2476                }
2477                WasmImport::ResourceIntrinsic {
2478                    interface,
2479                    resource,
2480                    intrinsic,
2481                } => {
2482                    let name = self.types[resource].name.as_ref().unwrap();
2483                    let (prefix, name) = match intrinsic {
2484                        ResourceIntrinsic::ImportedDrop => ("", format!("{name}_drop")),
2485                        ResourceIntrinsic::ExportedDrop => ("_ex_", format!("{name}_drop")),
2486                        ResourceIntrinsic::ExportedNew => ("_ex_", format!("{name}_new")),
2487                        ResourceIntrinsic::ExportedRep => ("_ex_", format!("{name}_rep")),
2488                    };
2489                    let module = match interface {
2490                        Some(key) => {
2491                            format!("cm32p2|{prefix}{}", self.name_canonicalized_world_key(key))
2492                        }
2493                        None => {
2494                            assert_eq!(prefix, "");
2495                            format!("cm32p2")
2496                        }
2497                    };
2498                    (module, name)
2499                }
2500            },
2501            ManglingAndAbi::Legacy(abi) => match import {
2502                WasmImport::Func { interface, func } => {
2503                    let module = match interface {
2504                        Some(key) => self.name_world_key(key),
2505                        None => format!("$root"),
2506                    };
2507                    (module, format!("{}{}", abi.import_prefix(), func.name))
2508                }
2509                WasmImport::ResourceIntrinsic {
2510                    interface,
2511                    resource,
2512                    intrinsic,
2513                } => {
2514                    let name = self.types[resource].name.as_ref().unwrap();
2515                    let (prefix, name) = match intrinsic {
2516                        ResourceIntrinsic::ImportedDrop => ("", format!("[resource-drop]{name}")),
2517                        ResourceIntrinsic::ExportedDrop => {
2518                            ("[export]", format!("[resource-drop]{name}"))
2519                        }
2520                        ResourceIntrinsic::ExportedNew => {
2521                            ("[export]", format!("[resource-new]{name}"))
2522                        }
2523                        ResourceIntrinsic::ExportedRep => {
2524                            ("[export]", format!("[resource-rep]{name}"))
2525                        }
2526                    };
2527                    let module = match interface {
2528                        Some(key) => format!("{prefix}{}", self.name_world_key(key)),
2529                        None => {
2530                            assert_eq!(prefix, "");
2531                            format!("$root")
2532                        }
2533                    };
2534                    (module, format!("{}{name}", abi.import_prefix()))
2535                }
2536            },
2537        }
2538    }
2539
2540    /// Returns the core wasm export name for the specified `export`.
2541    ///
2542    /// This is the same as [`Resolve::wasm_import_name`], except for exports.
2543    pub fn wasm_export_name(&self, mangling: ManglingAndAbi, export: WasmExport<'_>) -> String {
2544        match mangling {
2545            ManglingAndAbi::Standard32 => match export {
2546                WasmExport::Func {
2547                    interface,
2548                    func,
2549                    kind,
2550                } => {
2551                    let mut name = String::from("cm32p2|");
2552                    if let Some(interface) = interface {
2553                        let s = self.name_canonicalized_world_key(interface);
2554                        name.push_str(&s);
2555                    }
2556                    name.push_str("|");
2557                    name.push_str(&func.name);
2558                    match kind {
2559                        WasmExportKind::Normal => {}
2560                        WasmExportKind::PostReturn => name.push_str("_post"),
2561                        WasmExportKind::Callback => todo!(
2562                            "not yet supported: \
2563                             async callback functions using standard name mangling"
2564                        ),
2565                    }
2566                    name
2567                }
2568                WasmExport::ResourceDtor {
2569                    interface,
2570                    resource,
2571                } => {
2572                    let name = self.types[resource].name.as_ref().unwrap();
2573                    let interface = self.name_canonicalized_world_key(interface);
2574                    format!("cm32p2|{interface}|{name}_dtor")
2575                }
2576                WasmExport::Memory => "cm32p2_memory".to_string(),
2577                WasmExport::Initialize => "cm32p2_initialize".to_string(),
2578                WasmExport::Realloc => "cm32p2_realloc".to_string(),
2579            },
2580            ManglingAndAbi::Legacy(abi) => match export {
2581                WasmExport::Func {
2582                    interface,
2583                    func,
2584                    kind,
2585                } => {
2586                    let mut name = abi.export_prefix().to_string();
2587                    match kind {
2588                        WasmExportKind::Normal => {}
2589                        WasmExportKind::PostReturn => name.push_str("cabi_post_"),
2590                        WasmExportKind::Callback => {
2591                            assert!(matches!(abi, LiftLowerAbi::AsyncCallback));
2592                            name = format!("[callback]{name}")
2593                        }
2594                    }
2595                    if let Some(interface) = interface {
2596                        let s = self.name_world_key(interface);
2597                        name.push_str(&s);
2598                        name.push_str("#");
2599                    }
2600                    name.push_str(&func.name);
2601                    name
2602                }
2603                WasmExport::ResourceDtor {
2604                    interface,
2605                    resource,
2606                } => {
2607                    let name = self.types[resource].name.as_ref().unwrap();
2608                    let interface = self.name_world_key(interface);
2609                    format!("{}{interface}#[dtor]{name}", abi.export_prefix())
2610                }
2611                WasmExport::Memory => "memory".to_string(),
2612                WasmExport::Initialize => "_initialize".to_string(),
2613                WasmExport::Realloc => "cabi_realloc".to_string(),
2614            },
2615        }
2616    }
2617}
2618
2619/// Possible imports that can be passed to [`Resolve::wasm_import_name`].
2620#[derive(Debug)]
2621pub enum WasmImport<'a> {
2622    /// A WIT function is being imported. Optionally from an interface.
2623    Func {
2624        /// The name of the interface that the function is being imported from.
2625        ///
2626        /// If the function is imported directly from the world then this is
2627        /// `Noen`.
2628        interface: Option<&'a WorldKey>,
2629
2630        /// The function being imported.
2631        func: &'a Function,
2632    },
2633
2634    /// A resource-related intrinsic is being imported.
2635    ResourceIntrinsic {
2636        /// The optional interface to import from, same as `WasmImport::Func`.
2637        interface: Option<&'a WorldKey>,
2638
2639        /// The resource that's being operated on.
2640        resource: TypeId,
2641
2642        /// The intrinsic that's being imported.
2643        intrinsic: ResourceIntrinsic,
2644    },
2645}
2646
2647/// Intrinsic definitions to go with [`WasmImport::ResourceIntrinsic`] which
2648/// also goes with [`Resolve::wasm_import_name`].
2649#[derive(Debug)]
2650pub enum ResourceIntrinsic {
2651    ImportedDrop,
2652    ExportedDrop,
2653    ExportedNew,
2654    ExportedRep,
2655}
2656
2657/// Indicates whether a function export is a normal export, a post-return
2658/// function, or a callback function.
2659#[derive(Debug)]
2660pub enum WasmExportKind {
2661    /// Normal function export.
2662    Normal,
2663
2664    /// Post-return function.
2665    PostReturn,
2666
2667    /// Async callback function.
2668    Callback,
2669}
2670
2671/// Different kinds of exports that can be passed to
2672/// [`Resolve::wasm_export_name`] to export from core wasm modules.
2673#[derive(Debug)]
2674pub enum WasmExport<'a> {
2675    /// A WIT function is being exported, optionally from an interface.
2676    Func {
2677        /// An optional interface which owns `func`. Use `None` for top-level
2678        /// world function.
2679        interface: Option<&'a WorldKey>,
2680
2681        /// The function being exported.
2682        func: &'a Function,
2683
2684        /// Kind of function (normal, post-return, or callback) being exported.
2685        kind: WasmExportKind,
2686    },
2687
2688    /// A destructor for a resource exported from this module.
2689    ResourceDtor {
2690        /// The interface that owns the resource.
2691        interface: &'a WorldKey,
2692        /// The resource itself that the destructor is for.
2693        resource: TypeId,
2694    },
2695
2696    /// Linear memory, the one that the canonical ABI uses.
2697    Memory,
2698
2699    /// An initialization function (not the core wasm `start`).
2700    Initialize,
2701
2702    /// The general-purpose realloc hook.
2703    Realloc,
2704}
2705
2706/// Structure returned by [`Resolve::merge`] which contains mappings from
2707/// old-ids to new-ids after the merge.
2708#[derive(Default)]
2709pub struct Remap {
2710    pub types: Vec<Option<TypeId>>,
2711    pub interfaces: Vec<Option<InterfaceId>>,
2712    pub worlds: Vec<Option<WorldId>>,
2713    pub packages: Vec<PackageId>,
2714
2715    /// A cache of anonymous `own<T>` handles for resource types.
2716    ///
2717    /// The appending operation of `Remap` is the one responsible for
2718    /// translating references to `T` where `T` is a resource into `own<T>`
2719    /// instead. This map is used to deduplicate the `own<T>` types generated
2720    /// to generate as few as possible.
2721    ///
2722    /// The key of this map is the resource id `T` in the new resolve, and
2723    /// the value is the `own<T>` type pointing to `T`.
2724    own_handles: HashMap<TypeId, TypeId>,
2725
2726    type_has_borrow: Vec<Option<bool>>,
2727}
2728
2729fn apply_map<T>(map: &[Option<Id<T>>], id: Id<T>, desc: &str, span: Option<Span>) -> Result<Id<T>> {
2730    match map.get(id.index()) {
2731        Some(Some(id)) => Ok(*id),
2732        Some(None) => {
2733            let msg = format!(
2734                "found a reference to a {desc} which is excluded \
2735                 due to its feature not being activated"
2736            );
2737            match span {
2738                Some(span) => Err(Error::new(span, msg).into()),
2739                None => bail!("{msg}"),
2740            }
2741        }
2742        None => panic!("request to remap a {desc} that has not yet been registered"),
2743    }
2744}
2745
2746impl Remap {
2747    pub fn map_type(&self, id: TypeId, span: Option<Span>) -> Result<TypeId> {
2748        apply_map(&self.types, id, "type", span)
2749    }
2750
2751    pub fn map_interface(&self, id: InterfaceId, span: Option<Span>) -> Result<InterfaceId> {
2752        apply_map(&self.interfaces, id, "interface", span)
2753    }
2754
2755    pub fn map_world(&self, id: WorldId, span: Option<Span>) -> Result<WorldId> {
2756        apply_map(&self.worlds, id, "world", span)
2757    }
2758
2759    fn append(
2760        &mut self,
2761        resolve: &mut Resolve,
2762        unresolved: UnresolvedPackage,
2763    ) -> Result<PackageId> {
2764        let pkgid = resolve.packages.alloc(Package {
2765            name: unresolved.name.clone(),
2766            docs: unresolved.docs.clone(),
2767            interfaces: Default::default(),
2768            worlds: Default::default(),
2769        });
2770        let prev = resolve.package_names.insert(unresolved.name.clone(), pkgid);
2771        if let Some(prev) = prev {
2772            resolve.package_names.insert(unresolved.name.clone(), prev);
2773            bail!(
2774                "attempting to re-add package `{}` when it's already present in this `Resolve`",
2775                unresolved.name,
2776            );
2777        }
2778
2779        self.process_foreign_deps(resolve, pkgid, &unresolved)?;
2780
2781        let foreign_types = self.types.len();
2782        let foreign_interfaces = self.interfaces.len();
2783        let foreign_worlds = self.worlds.len();
2784
2785        // Copy over all types first, updating any intra-type references. Note
2786        // that types are sorted topologically which means this iteration
2787        // order should be sufficient. Also note though that the interface
2788        // owner of a type isn't updated here due to interfaces not being known
2789        // yet.
2790        assert_eq!(unresolved.types.len(), unresolved.type_spans.len());
2791        for ((id, mut ty), span) in unresolved
2792            .types
2793            .into_iter()
2794            .zip(&unresolved.type_spans)
2795            .skip(foreign_types)
2796        {
2797            if !resolve.include_type(&ty, pkgid, *span)? {
2798                self.types.push(None);
2799                continue;
2800            }
2801
2802            self.update_typedef(resolve, &mut ty, Some(*span))?;
2803            let new_id = resolve.types.alloc(ty);
2804            assert_eq!(self.types.len(), id.index());
2805
2806            let new_id = match resolve.types[new_id] {
2807                // If this is an `own<T>` handle then either replace it with a
2808                // preexisting `own<T>` handle which may have been generated in
2809                // `update_ty`. If that doesn't exist though then insert it into
2810                // the `own_handles` cache.
2811                TypeDef {
2812                    name: None,
2813                    owner: TypeOwner::None,
2814                    kind: TypeDefKind::Handle(Handle::Own(id)),
2815                    docs: _,
2816                    stability: _,
2817                } => *self.own_handles.entry(id).or_insert(new_id),
2818
2819                // Everything not-related to `own<T>` doesn't get its ID
2820                // modified.
2821                _ => new_id,
2822            };
2823            self.types.push(Some(new_id));
2824        }
2825
2826        // Next transfer all interfaces into `Resolve`, updating type ids
2827        // referenced along the way.
2828        assert_eq!(
2829            unresolved.interfaces.len(),
2830            unresolved.interface_spans.len()
2831        );
2832        for ((id, mut iface), span) in unresolved
2833            .interfaces
2834            .into_iter()
2835            .zip(&unresolved.interface_spans)
2836            .skip(foreign_interfaces)
2837        {
2838            if !resolve
2839                .include_stability(&iface.stability, &pkgid, Some(span.span))
2840                .with_context(|| {
2841                    format!(
2842                        "failed to process feature gate for interface [{}] in package [{}]",
2843                        iface
2844                            .name
2845                            .as_ref()
2846                            .map(String::as_str)
2847                            .unwrap_or("<unknown>"),
2848                        resolve.packages[pkgid].name,
2849                    )
2850                })?
2851            {
2852                self.interfaces.push(None);
2853                continue;
2854            }
2855            assert!(iface.package.is_none());
2856            iface.package = Some(pkgid);
2857            self.update_interface(resolve, &mut iface, Some(span))?;
2858            let new_id = resolve.interfaces.alloc(iface);
2859            assert_eq!(self.interfaces.len(), id.index());
2860            self.interfaces.push(Some(new_id));
2861        }
2862
2863        // Now that interfaces are identified go back through the types and
2864        // update their interface owners.
2865        for (i, id) in self.types.iter().enumerate().skip(foreign_types) {
2866            let id = match id {
2867                Some(id) => *id,
2868                None => continue,
2869            };
2870            match &mut resolve.types[id].owner {
2871                TypeOwner::Interface(id) => {
2872                    let span = unresolved.type_spans[i];
2873                    *id = self.map_interface(*id, Some(span))
2874                        .with_context(|| {
2875                            "this type is not gated by a feature but its interface is gated by a feature"
2876                        })?;
2877                }
2878                TypeOwner::World(_) | TypeOwner::None => {}
2879            }
2880        }
2881
2882        // Expand worlds. Note that this does NOT process `include` statements,
2883        // that's handled below. Instead this just handles world item updates
2884        // and resolves references to types/items within `Resolve`.
2885        //
2886        // This is done after types/interfaces are fully settled so the
2887        // transitive relation between interfaces, through types, is understood
2888        // here.
2889        assert_eq!(unresolved.worlds.len(), unresolved.world_spans.len());
2890        for ((id, mut world), span) in unresolved
2891            .worlds
2892            .into_iter()
2893            .zip(&unresolved.world_spans)
2894            .skip(foreign_worlds)
2895        {
2896            if !resolve
2897                .include_stability(&world.stability, &pkgid, Some(span.span))
2898                .with_context(|| {
2899                    format!(
2900                        "failed to process feature gate for world [{}] in package [{}]",
2901                        world.name, resolve.packages[pkgid].name,
2902                    )
2903                })?
2904            {
2905                self.worlds.push(None);
2906                continue;
2907            }
2908            self.update_world(&mut world, resolve, &pkgid, &span)?;
2909
2910            let new_id = resolve.worlds.alloc(world);
2911            assert_eq!(self.worlds.len(), id.index());
2912            self.worlds.push(Some(new_id));
2913        }
2914
2915        // As with interfaces, now update the ids of world-owned types.
2916        for (i, id) in self.types.iter().enumerate().skip(foreign_types) {
2917            let id = match id {
2918                Some(id) => *id,
2919                None => continue,
2920            };
2921            match &mut resolve.types[id].owner {
2922                TypeOwner::World(id) => {
2923                    let span = unresolved.type_spans[i];
2924                    *id = self.map_world(*id, Some(span))
2925                        .with_context(|| {
2926                            "this type is not gated by a feature but its interface is gated by a feature"
2927                        })?;
2928                }
2929                TypeOwner::Interface(_) | TypeOwner::None => {}
2930            }
2931        }
2932
2933        // After the above, process `include` statements for worlds and
2934        // additionally fully elaborate them. Processing of `include` is
2935        // deferred until after the steps above so the fully resolved state of
2936        // local types in this package are all available. This is required
2937        // because `include` may copy types between worlds when the type is
2938        // defined in the world itself.
2939        //
2940        // This step, after processing `include`, will also use
2941        // `elaborate_world` to fully expand the world in terms of
2942        // imports/exports and ensure that all necessary imports/exports are all
2943        // listed.
2944        //
2945        // Note that `self.worlds` is already sorted in topological order so if
2946        // one world refers to another via `include` then it's guaranteed that
2947        // the one we're referring to is already expanded and ready to be
2948        // included.
2949        assert_eq!(self.worlds.len(), unresolved.world_spans.len());
2950        for (id, span) in self
2951            .worlds
2952            .iter()
2953            .zip(unresolved.world_spans.iter())
2954            .skip(foreign_worlds)
2955        {
2956            let Some(id) = *id else {
2957                continue;
2958            };
2959            self.process_world_includes(id, resolve, &pkgid, &span)?;
2960
2961            resolve.elaborate_world(id).with_context(|| {
2962                Error::new(
2963                    span.span,
2964                    format!(
2965                        "failed to elaborate world imports/exports of `{}`",
2966                        resolve.worlds[id].name
2967                    ),
2968                )
2969            })?;
2970        }
2971
2972        // Fixup "parent" ids now that everything has been identified
2973        for id in self.interfaces.iter().skip(foreign_interfaces) {
2974            let id = match id {
2975                Some(id) => *id,
2976                None => continue,
2977            };
2978            let iface = &mut resolve.interfaces[id];
2979            iface.package = Some(pkgid);
2980            if let Some(name) = &iface.name {
2981                let prev = resolve.packages[pkgid].interfaces.insert(name.clone(), id);
2982                assert!(prev.is_none());
2983            }
2984        }
2985        for id in self.worlds.iter().skip(foreign_worlds) {
2986            let id = match id {
2987                Some(id) => *id,
2988                None => continue,
2989            };
2990            let world = &mut resolve.worlds[id];
2991            world.package = Some(pkgid);
2992            let prev = resolve.packages[pkgid]
2993                .worlds
2994                .insert(world.name.clone(), id);
2995            assert!(prev.is_none());
2996        }
2997        Ok(pkgid)
2998    }
2999
3000    fn process_foreign_deps(
3001        &mut self,
3002        resolve: &mut Resolve,
3003        pkgid: PackageId,
3004        unresolved: &UnresolvedPackage,
3005    ) -> Result<()> {
3006        // Invert the `foreign_deps` map to be keyed by world id to get
3007        // used in the loops below.
3008        let mut world_to_package = HashMap::new();
3009        let mut interface_to_package = HashMap::new();
3010        for (i, (pkg_name, worlds_or_ifaces)) in unresolved.foreign_deps.iter().enumerate() {
3011            for (name, item) in worlds_or_ifaces {
3012                match item {
3013                    AstItem::Interface(unresolved_interface_id) => {
3014                        let prev = interface_to_package.insert(
3015                            *unresolved_interface_id,
3016                            (pkg_name, name, unresolved.foreign_dep_spans[i]),
3017                        );
3018                        assert!(prev.is_none());
3019                    }
3020                    AstItem::World(unresolved_world_id) => {
3021                        let prev = world_to_package.insert(
3022                            *unresolved_world_id,
3023                            (pkg_name, name, unresolved.foreign_dep_spans[i]),
3024                        );
3025                        assert!(prev.is_none());
3026                    }
3027                }
3028            }
3029        }
3030
3031        // Connect all interfaces referred to in `interface_to_package`, which
3032        // are at the front of `unresolved.interfaces`, to interfaces already
3033        // contained within `resolve`.
3034        self.process_foreign_interfaces(unresolved, &interface_to_package, resolve)?;
3035
3036        // Connect all worlds referred to in `world_to_package`, which
3037        // are at the front of `unresolved.worlds`, to worlds already
3038        // contained within `resolve`.
3039        self.process_foreign_worlds(unresolved, &world_to_package, resolve)?;
3040
3041        // Finally, iterate over all foreign-defined types and determine
3042        // what they map to.
3043        self.process_foreign_types(unresolved, pkgid, resolve)?;
3044
3045        for (id, span) in unresolved.required_resource_types.iter() {
3046            // Note that errors are ignored here because an error represents a
3047            // type that has been configured away. If a type is configured away
3048            // then any future use of it will generate an error so there's no
3049            // need to validate that it's a resource here.
3050            let Ok(mut id) = self.map_type(*id, Some(*span)) else {
3051                continue;
3052            };
3053            loop {
3054                match resolve.types[id].kind {
3055                    TypeDefKind::Type(Type::Id(i)) => id = i,
3056                    TypeDefKind::Resource => break,
3057                    _ => bail!(Error::new(
3058                        *span,
3059                        format!("type used in a handle must be a resource"),
3060                    )),
3061                }
3062            }
3063        }
3064
3065        #[cfg(debug_assertions)]
3066        resolve.assert_valid();
3067
3068        Ok(())
3069    }
3070
3071    fn process_foreign_interfaces(
3072        &mut self,
3073        unresolved: &UnresolvedPackage,
3074        interface_to_package: &HashMap<InterfaceId, (&PackageName, &String, Span)>,
3075        resolve: &mut Resolve,
3076    ) -> Result<(), anyhow::Error> {
3077        for (unresolved_iface_id, unresolved_iface) in unresolved.interfaces.iter() {
3078            let (pkg_name, interface, span) = match interface_to_package.get(&unresolved_iface_id) {
3079                Some(items) => *items,
3080                // All foreign interfaces are defined first, so the first one
3081                // which is defined in a non-foreign document means that all
3082                // further interfaces will be non-foreign as well.
3083                None => break,
3084            };
3085            let pkgid = resolve
3086                .package_names
3087                .get(pkg_name)
3088                .copied()
3089                .ok_or_else(|| {
3090                    PackageNotFoundError::new(
3091                        span,
3092                        pkg_name.clone(),
3093                        resolve.package_names.keys().cloned().collect(),
3094                    )
3095                })?;
3096
3097            // Functions can't be imported so this should be empty.
3098            assert!(unresolved_iface.functions.is_empty());
3099
3100            let pkg = &resolve.packages[pkgid];
3101            let span = &unresolved.interface_spans[unresolved_iface_id.index()];
3102            let iface_id = pkg
3103                .interfaces
3104                .get(interface)
3105                .copied()
3106                .ok_or_else(|| Error::new(span.span, "interface not found in package"))?;
3107            assert_eq!(self.interfaces.len(), unresolved_iface_id.index());
3108            self.interfaces.push(Some(iface_id));
3109        }
3110        for (id, _) in unresolved.interfaces.iter().skip(self.interfaces.len()) {
3111            assert!(
3112                interface_to_package.get(&id).is_none(),
3113                "found foreign interface after local interface"
3114            );
3115        }
3116        Ok(())
3117    }
3118
3119    fn process_foreign_worlds(
3120        &mut self,
3121        unresolved: &UnresolvedPackage,
3122        world_to_package: &HashMap<WorldId, (&PackageName, &String, Span)>,
3123        resolve: &mut Resolve,
3124    ) -> Result<(), anyhow::Error> {
3125        for (unresolved_world_id, _) in unresolved.worlds.iter() {
3126            let (pkg_name, world, span) = match world_to_package.get(&unresolved_world_id) {
3127                Some(items) => *items,
3128                // Same as above, all worlds are foreign until we find a
3129                // non-foreign one.
3130                None => break,
3131            };
3132
3133            let pkgid = resolve
3134                .package_names
3135                .get(pkg_name)
3136                .copied()
3137                .ok_or_else(|| Error::new(span, "package not found"))?;
3138            let pkg = &resolve.packages[pkgid];
3139            let span = &unresolved.world_spans[unresolved_world_id.index()];
3140            let world_id = pkg
3141                .worlds
3142                .get(world)
3143                .copied()
3144                .ok_or_else(|| Error::new(span.span, "world not found in package"))?;
3145            assert_eq!(self.worlds.len(), unresolved_world_id.index());
3146            self.worlds.push(Some(world_id));
3147        }
3148        for (id, _) in unresolved.worlds.iter().skip(self.worlds.len()) {
3149            assert!(
3150                world_to_package.get(&id).is_none(),
3151                "found foreign world after local world"
3152            );
3153        }
3154        Ok(())
3155    }
3156
3157    fn process_foreign_types(
3158        &mut self,
3159        unresolved: &UnresolvedPackage,
3160        pkgid: PackageId,
3161        resolve: &mut Resolve,
3162    ) -> Result<(), anyhow::Error> {
3163        for ((unresolved_type_id, unresolved_ty), span) in
3164            unresolved.types.iter().zip(&unresolved.type_spans)
3165        {
3166            // All "Unknown" types should appear first so once we're no longer
3167            // in unknown territory it's package-defined types so break out of
3168            // this loop.
3169            match unresolved_ty.kind {
3170                TypeDefKind::Unknown => {}
3171                _ => break,
3172            }
3173
3174            if !resolve.include_type(unresolved_ty, pkgid, *span)? {
3175                self.types.push(None);
3176                continue;
3177            }
3178
3179            let unresolved_iface_id = match unresolved_ty.owner {
3180                TypeOwner::Interface(id) => id,
3181                _ => unreachable!(),
3182            };
3183            let iface_id = self.map_interface(unresolved_iface_id, None)?;
3184            let name = unresolved_ty.name.as_ref().unwrap();
3185            let span = unresolved.unknown_type_spans[unresolved_type_id.index()];
3186            let type_id = *resolve.interfaces[iface_id]
3187                .types
3188                .get(name)
3189                .ok_or_else(|| {
3190                    Error::new(span, format!("type `{name}` not defined in interface"))
3191                })?;
3192            assert_eq!(self.types.len(), unresolved_type_id.index());
3193            self.types.push(Some(type_id));
3194        }
3195        for (_, ty) in unresolved.types.iter().skip(self.types.len()) {
3196            if let TypeDefKind::Unknown = ty.kind {
3197                panic!("unknown type after defined type");
3198            }
3199        }
3200        Ok(())
3201    }
3202
3203    fn update_typedef(
3204        &mut self,
3205        resolve: &mut Resolve,
3206        ty: &mut TypeDef,
3207        span: Option<Span>,
3208    ) -> Result<()> {
3209        // NB: note that `ty.owner` is not updated here since interfaces
3210        // haven't been mapped yet and that's done in a separate step.
3211        use crate::TypeDefKind::*;
3212        match &mut ty.kind {
3213            Handle(handle) => match handle {
3214                crate::Handle::Own(ty) | crate::Handle::Borrow(ty) => {
3215                    self.update_type_id(ty, span)?
3216                }
3217            },
3218            Resource => {}
3219            Record(r) => {
3220                for field in r.fields.iter_mut() {
3221                    self.update_ty(resolve, &mut field.ty, span)
3222                        .with_context(|| format!("failed to update field `{}`", field.name))?;
3223                }
3224            }
3225            Tuple(t) => {
3226                for ty in t.types.iter_mut() {
3227                    self.update_ty(resolve, ty, span)?;
3228                }
3229            }
3230            Variant(v) => {
3231                for case in v.cases.iter_mut() {
3232                    if let Some(t) = &mut case.ty {
3233                        self.update_ty(resolve, t, span)?;
3234                    }
3235                }
3236            }
3237            Option(t) | List(t, ..) | FixedSizeList(t, ..) | Future(Some(t)) | Stream(Some(t)) => {
3238                self.update_ty(resolve, t, span)?
3239            }
3240            Result(r) => {
3241                if let Some(ty) = &mut r.ok {
3242                    self.update_ty(resolve, ty, span)?;
3243                }
3244                if let Some(ty) = &mut r.err {
3245                    self.update_ty(resolve, ty, span)?;
3246                }
3247            }
3248
3249            // Note that `update_ty` is specifically not used here as typedefs
3250            // because for the `type a = b` form that doesn't force `a` to be a
3251            // handle type if `b` is a resource type, instead `a` is
3252            // simultaneously usable as a resource and a handle type
3253            Type(crate::Type::Id(id)) => self.update_type_id(id, span)?,
3254            Type(_) => {}
3255
3256            // nothing to do for these as they're just names or empty
3257            Flags(_) | Enum(_) | Future(None) | Stream(None) => {}
3258
3259            Unknown => unreachable!(),
3260        }
3261
3262        Ok(())
3263    }
3264
3265    fn update_ty(
3266        &mut self,
3267        resolve: &mut Resolve,
3268        ty: &mut Type,
3269        span: Option<Span>,
3270    ) -> Result<()> {
3271        let id = match ty {
3272            Type::Id(id) => id,
3273            _ => return Ok(()),
3274        };
3275        self.update_type_id(id, span)?;
3276
3277        // If `id` points to a `Resource` type then this means that what was
3278        // just discovered was a reference to what will implicitly become an
3279        // `own<T>` handle. This `own` handle is implicitly allocated here
3280        // and handled during the merging process.
3281        let mut cur = *id;
3282        let points_to_resource = loop {
3283            match resolve.types[cur].kind {
3284                TypeDefKind::Type(Type::Id(id)) => cur = id,
3285                TypeDefKind::Resource => break true,
3286                _ => break false,
3287            }
3288        };
3289
3290        if points_to_resource {
3291            *id = *self.own_handles.entry(*id).or_insert_with(|| {
3292                resolve.types.alloc(TypeDef {
3293                    name: None,
3294                    owner: TypeOwner::None,
3295                    kind: TypeDefKind::Handle(Handle::Own(*id)),
3296                    docs: Default::default(),
3297                    stability: Default::default(),
3298                })
3299            });
3300        }
3301        Ok(())
3302    }
3303
3304    fn update_type_id(&self, id: &mut TypeId, span: Option<Span>) -> Result<()> {
3305        *id = self.map_type(*id, span)?;
3306        Ok(())
3307    }
3308
3309    fn update_interface(
3310        &mut self,
3311        resolve: &mut Resolve,
3312        iface: &mut Interface,
3313        spans: Option<&InterfaceSpan>,
3314    ) -> Result<()> {
3315        iface.types.retain(|_, ty| self.types[ty.index()].is_some());
3316        let iface_pkg_id = iface.package.as_ref().unwrap_or_else(|| {
3317            panic!(
3318                "unexpectedly missing package on interface [{}]",
3319                iface
3320                    .name
3321                    .as_ref()
3322                    .map(String::as_str)
3323                    .unwrap_or("<unknown>"),
3324            )
3325        });
3326
3327        // NB: note that `iface.doc` is not updated here since interfaces
3328        // haven't been mapped yet and that's done in a separate step.
3329        for (_name, ty) in iface.types.iter_mut() {
3330            self.update_type_id(ty, spans.map(|s| s.span))?;
3331        }
3332        if let Some(spans) = spans {
3333            assert_eq!(iface.functions.len(), spans.funcs.len());
3334        }
3335        for (i, (func_name, func)) in iface.functions.iter_mut().enumerate() {
3336            let span = spans.map(|s| s.funcs[i]);
3337            if !resolve
3338                .include_stability(&func.stability, iface_pkg_id, span)
3339                .with_context(|| {
3340                    format!(
3341                        "failed to process feature gate for function [{func_name}] in package [{}]",
3342                        resolve.packages[*iface_pkg_id].name,
3343                    )
3344                })?
3345            {
3346                continue;
3347            }
3348            self.update_function(resolve, func, span)
3349                .with_context(|| format!("failed to update function `{}`", func.name))?;
3350        }
3351
3352        // Filter out all of the existing functions in interface which fail the
3353        // `include_stability()` check, as they shouldn't be available.
3354        for (name, func) in mem::take(&mut iface.functions) {
3355            if resolve.include_stability(&func.stability, iface_pkg_id, None)? {
3356                iface.functions.insert(name, func);
3357            }
3358        }
3359
3360        Ok(())
3361    }
3362
3363    fn update_function(
3364        &mut self,
3365        resolve: &mut Resolve,
3366        func: &mut Function,
3367        span: Option<Span>,
3368    ) -> Result<()> {
3369        if let Some(id) = func.kind.resource_mut() {
3370            self.update_type_id(id, span)?;
3371        }
3372        for (_, ty) in func.params.iter_mut() {
3373            self.update_ty(resolve, ty, span)?;
3374        }
3375        if let Some(ty) = &mut func.result {
3376            self.update_ty(resolve, ty, span)?;
3377        }
3378
3379        if let Some(ty) = &func.result {
3380            if self.type_has_borrow(resolve, ty) {
3381                match span {
3382                    Some(span) => {
3383                        bail!(Error::new(
3384                            span,
3385                            format!(
3386                                "function returns a type which contains \
3387                                 a `borrow<T>` which is not supported"
3388                            )
3389                        ))
3390                    }
3391                    None => unreachable!(),
3392                }
3393            }
3394        }
3395
3396        Ok(())
3397    }
3398
3399    fn update_world(
3400        &mut self,
3401        world: &mut World,
3402        resolve: &mut Resolve,
3403        pkg_id: &PackageId,
3404        spans: &WorldSpan,
3405    ) -> Result<()> {
3406        assert_eq!(world.imports.len(), spans.imports.len());
3407        assert_eq!(world.exports.len(), spans.exports.len());
3408
3409        // Rewrite imports/exports with their updated versions. Note that this
3410        // may involve updating the key of the imports/exports maps so this
3411        // starts by emptying them out and then everything is re-inserted.
3412        let imports = mem::take(&mut world.imports).into_iter();
3413        let imports = imports.zip(&spans.imports).map(|p| (p, true));
3414        let exports = mem::take(&mut world.exports).into_iter();
3415        let exports = exports.zip(&spans.exports).map(|p| (p, false));
3416        for (((mut name, mut item), span), import) in imports.chain(exports) {
3417            // Update the `id` eagerly here so `item.stability(..)` below
3418            // works.
3419            if let WorldItem::Type(id) = &mut item {
3420                *id = self.map_type(*id, Some(*span))?;
3421            }
3422            let stability = item.stability(resolve);
3423            if !resolve
3424                .include_stability(stability, pkg_id, Some(*span))
3425                .with_context(|| format!("failed to process world item in `{}`", world.name))?
3426            {
3427                continue;
3428            }
3429            self.update_world_key(&mut name, Some(*span))?;
3430            match &mut item {
3431                WorldItem::Interface { id, .. } => {
3432                    *id = self.map_interface(*id, Some(*span))?;
3433                }
3434                WorldItem::Function(f) => {
3435                    self.update_function(resolve, f, Some(*span))?;
3436                }
3437                WorldItem::Type(_) => {
3438                    // already mapped above
3439                }
3440            }
3441
3442            let dst = if import {
3443                &mut world.imports
3444            } else {
3445                &mut world.exports
3446            };
3447            let prev = dst.insert(name, item);
3448            assert!(prev.is_none());
3449        }
3450
3451        Ok(())
3452    }
3453
3454    fn process_world_includes(
3455        &self,
3456        id: WorldId,
3457        resolve: &mut Resolve,
3458        pkg_id: &PackageId,
3459        spans: &WorldSpan,
3460    ) -> Result<()> {
3461        let world = &mut resolve.worlds[id];
3462        // Resolve all `include` statements of the world which will add more
3463        // entries to the imports/exports list for this world.
3464        assert_eq!(world.includes.len(), spans.includes.len());
3465        let includes = mem::take(&mut world.includes);
3466        let include_names = mem::take(&mut world.include_names);
3467        for (((stability, include_world), span), names) in includes
3468            .into_iter()
3469            .zip(&spans.includes)
3470            .zip(&include_names)
3471        {
3472            if !resolve
3473                .include_stability(&stability, pkg_id, Some(*span))
3474                .with_context(|| {
3475                    format!(
3476                        "failed to process feature gate for included world [{}] in package [{}]",
3477                        resolve.worlds[include_world].name.as_str(),
3478                        resolve.packages[*pkg_id].name
3479                    )
3480                })?
3481            {
3482                continue;
3483            }
3484            self.resolve_include(id, include_world, names, *span, pkg_id, resolve)?;
3485        }
3486
3487        Ok(())
3488    }
3489
3490    fn update_world_key(&self, key: &mut WorldKey, span: Option<Span>) -> Result<()> {
3491        match key {
3492            WorldKey::Name(_) => {}
3493            WorldKey::Interface(id) => {
3494                *id = self.map_interface(*id, span)?;
3495            }
3496        }
3497        Ok(())
3498    }
3499
3500    fn resolve_include(
3501        &self,
3502        id: WorldId,
3503        include_world_id_orig: WorldId,
3504        names: &[IncludeName],
3505        span: Span,
3506        pkg_id: &PackageId,
3507        resolve: &mut Resolve,
3508    ) -> Result<()> {
3509        let world = &resolve.worlds[id];
3510        let include_world_id = self.map_world(include_world_id_orig, Some(span))?;
3511        let include_world = resolve.worlds[include_world_id].clone();
3512        let mut names_ = names.to_owned();
3513        let is_external_include = world.package != include_world.package;
3514
3515        // remove all imports and exports that match the names we're including
3516        for import in include_world.imports.iter() {
3517            self.remove_matching_name(import, &mut names_);
3518        }
3519        for export in include_world.exports.iter() {
3520            self.remove_matching_name(export, &mut names_);
3521        }
3522        if !names_.is_empty() {
3523            bail!(Error::new(
3524                span,
3525                format!("no import or export kebab-name `{}`. Note that an ID does not support renaming", names_[0].name),
3526            ));
3527        }
3528
3529        let mut cloner = clone::Cloner::new(
3530            resolve,
3531            TypeOwner::World(if is_external_include {
3532                include_world_id
3533            } else {
3534                include_world_id
3535                // include_world_id_orig
3536            }),
3537            TypeOwner::World(id),
3538        );
3539        cloner.new_package = Some(*pkg_id);
3540
3541        // copy the imports and exports from the included world into the current world
3542        for import in include_world.imports.iter() {
3543            self.resolve_include_item(
3544                &mut cloner,
3545                names,
3546                |resolve| &mut resolve.worlds[id].imports,
3547                import,
3548                span,
3549                "import",
3550                is_external_include,
3551            )?;
3552        }
3553
3554        for export in include_world.exports.iter() {
3555            self.resolve_include_item(
3556                &mut cloner,
3557                names,
3558                |resolve| &mut resolve.worlds[id].exports,
3559                export,
3560                span,
3561                "export",
3562                is_external_include,
3563            )?;
3564        }
3565        Ok(())
3566    }
3567
3568    fn resolve_include_item(
3569        &self,
3570        cloner: &mut clone::Cloner<'_>,
3571        names: &[IncludeName],
3572        get_items: impl Fn(&mut Resolve) -> &mut IndexMap<WorldKey, WorldItem>,
3573        item: (&WorldKey, &WorldItem),
3574        span: Span,
3575        item_type: &str,
3576        is_external_include: bool,
3577    ) -> Result<()> {
3578        match item.0 {
3579            WorldKey::Name(n) => {
3580                let n = if let Some(found) = names
3581                    .into_iter()
3582                    .find(|include_name| include_name.name == n.clone())
3583                {
3584                    found.as_.clone()
3585                } else {
3586                    n.clone()
3587                };
3588
3589                // When the `with` option to the `include` directive is
3590                // specified and is used to rename a function that means that
3591                // the function's own original name needs to be updated, so
3592                // reflect the change not only in the world key but additionally
3593                // in the function itself.
3594                let mut new_item = item.1.clone();
3595                if let WorldItem::Function(f) = &mut new_item {
3596                    f.name = n.clone();
3597                }
3598                let key = WorldKey::Name(n.clone());
3599                cloner.world_item(&key, &mut new_item);
3600
3601                let prev = get_items(cloner.resolve).insert(key, new_item);
3602                if prev.is_some() {
3603                    bail!(Error::new(
3604                        span,
3605                        format!("{item_type} of `{n}` shadows previously {item_type}ed items"),
3606                    ))
3607                }
3608            }
3609            key @ WorldKey::Interface(_) => {
3610                let prev = get_items(cloner.resolve)
3611                    .entry(key.clone())
3612                    .or_insert(item.1.clone());
3613                match (&item.1, prev) {
3614                    (
3615                        WorldItem::Interface {
3616                            id: aid,
3617                            stability: astability,
3618                        },
3619                        WorldItem::Interface {
3620                            id: bid,
3621                            stability: bstability,
3622                        },
3623                    ) => {
3624                        assert_eq!(*aid, *bid);
3625                        merge_include_stability(astability, bstability, is_external_include)?;
3626                    }
3627                    (WorldItem::Interface { .. }, _) => unreachable!(),
3628                    (WorldItem::Function(_), _) => unreachable!(),
3629                    (WorldItem::Type(_), _) => unreachable!(),
3630                }
3631            }
3632        };
3633
3634        Ok(())
3635    }
3636
3637    fn remove_matching_name(&self, item: (&WorldKey, &WorldItem), names: &mut Vec<IncludeName>) {
3638        match item.0 {
3639            WorldKey::Name(n) => {
3640                names.retain(|name| name.name != n.clone());
3641            }
3642            _ => {}
3643        }
3644    }
3645
3646    fn type_has_borrow(&mut self, resolve: &Resolve, ty: &Type) -> bool {
3647        let id = match ty {
3648            Type::Id(id) => *id,
3649            _ => return false,
3650        };
3651
3652        if let Some(Some(has_borrow)) = self.type_has_borrow.get(id.index()) {
3653            return *has_borrow;
3654        }
3655
3656        let result = self.typedef_has_borrow(resolve, &resolve.types[id]);
3657        if self.type_has_borrow.len() <= id.index() {
3658            self.type_has_borrow.resize(id.index() + 1, None);
3659        }
3660        self.type_has_borrow[id.index()] = Some(result);
3661        result
3662    }
3663
3664    fn typedef_has_borrow(&mut self, resolve: &Resolve, ty: &TypeDef) -> bool {
3665        match &ty.kind {
3666            TypeDefKind::Type(t) => self.type_has_borrow(resolve, t),
3667            TypeDefKind::Variant(v) => v
3668                .cases
3669                .iter()
3670                .filter_map(|case| case.ty.as_ref())
3671                .any(|ty| self.type_has_borrow(resolve, ty)),
3672            TypeDefKind::Handle(Handle::Borrow(_)) => true,
3673            TypeDefKind::Handle(Handle::Own(_)) => false,
3674            TypeDefKind::Resource => false,
3675            TypeDefKind::Record(r) => r
3676                .fields
3677                .iter()
3678                .any(|case| self.type_has_borrow(resolve, &case.ty)),
3679            TypeDefKind::Flags(_) => false,
3680            TypeDefKind::Tuple(t) => t.types.iter().any(|t| self.type_has_borrow(resolve, t)),
3681            TypeDefKind::Enum(_) => false,
3682            TypeDefKind::List(ty)
3683            | TypeDefKind::FixedSizeList(ty, ..)
3684            | TypeDefKind::Future(Some(ty))
3685            | TypeDefKind::Stream(Some(ty))
3686            | TypeDefKind::Option(ty) => self.type_has_borrow(resolve, ty),
3687            TypeDefKind::Result(r) => [&r.ok, &r.err]
3688                .iter()
3689                .filter_map(|t| t.as_ref())
3690                .any(|t| self.type_has_borrow(resolve, t)),
3691            TypeDefKind::Future(None) | TypeDefKind::Stream(None) => false,
3692            TypeDefKind::Unknown => unreachable!(),
3693        }
3694    }
3695}
3696
3697struct MergeMap<'a> {
3698    /// A map of package ids in `from` to those in `into` for those that are
3699    /// found to be equivalent.
3700    package_map: HashMap<PackageId, PackageId>,
3701
3702    /// A map of interface ids in `from` to those in `into` for those that are
3703    /// found to be equivalent.
3704    interface_map: HashMap<InterfaceId, InterfaceId>,
3705
3706    /// A map of type ids in `from` to those in `into` for those that are
3707    /// found to be equivalent.
3708    type_map: HashMap<TypeId, TypeId>,
3709
3710    /// A map of world ids in `from` to those in `into` for those that are
3711    /// found to be equivalent.
3712    world_map: HashMap<WorldId, WorldId>,
3713
3714    /// A list of documents that need to be added to packages in `into`.
3715    ///
3716    /// The elements here are:
3717    ///
3718    /// * The name of the interface/world
3719    /// * The ID within `into` of the package being added to
3720    /// * The ID within `from` of the item being added.
3721    interfaces_to_add: Vec<(String, PackageId, InterfaceId)>,
3722    worlds_to_add: Vec<(String, PackageId, WorldId)>,
3723
3724    /// Which `Resolve` is being merged from.
3725    from: &'a Resolve,
3726
3727    /// Which `Resolve` is being merged into.
3728    into: &'a Resolve,
3729}
3730
3731impl<'a> MergeMap<'a> {
3732    fn new(from: &'a Resolve, into: &'a Resolve) -> MergeMap<'a> {
3733        MergeMap {
3734            package_map: Default::default(),
3735            interface_map: Default::default(),
3736            type_map: Default::default(),
3737            world_map: Default::default(),
3738            interfaces_to_add: Default::default(),
3739            worlds_to_add: Default::default(),
3740            from,
3741            into,
3742        }
3743    }
3744
3745    fn build(&mut self) -> Result<()> {
3746        for from_id in self.from.topological_packages() {
3747            let from = &self.from.packages[from_id];
3748            let into_id = match self.into.package_names.get(&from.name) {
3749                Some(id) => *id,
3750
3751                // This package, according to its name and url, is not present
3752                // in `self` so it needs to get added below.
3753                None => {
3754                    log::trace!("adding unique package {}", from.name);
3755                    continue;
3756                }
3757            };
3758            log::trace!("merging duplicate package {}", from.name);
3759
3760            self.build_package(from_id, into_id).with_context(|| {
3761                format!("failed to merge package `{}` into existing copy", from.name)
3762            })?;
3763        }
3764
3765        Ok(())
3766    }
3767
3768    fn build_package(&mut self, from_id: PackageId, into_id: PackageId) -> Result<()> {
3769        let prev = self.package_map.insert(from_id, into_id);
3770        assert!(prev.is_none());
3771
3772        let from = &self.from.packages[from_id];
3773        let into = &self.into.packages[into_id];
3774
3775        // If an interface is present in `from_id` but not present in `into_id`
3776        // then it can be copied over wholesale. That copy is scheduled to
3777        // happen within the `self.interfaces_to_add` list.
3778        for (name, from_interface_id) in from.interfaces.iter() {
3779            let into_interface_id = match into.interfaces.get(name) {
3780                Some(id) => *id,
3781                None => {
3782                    log::trace!("adding unique interface {}", name);
3783                    self.interfaces_to_add
3784                        .push((name.clone(), into_id, *from_interface_id));
3785                    continue;
3786                }
3787            };
3788
3789            log::trace!("merging duplicate interfaces {}", name);
3790            self.build_interface(*from_interface_id, into_interface_id)
3791                .with_context(|| format!("failed to merge interface `{name}`"))?;
3792        }
3793
3794        for (name, from_world_id) in from.worlds.iter() {
3795            let into_world_id = match into.worlds.get(name) {
3796                Some(id) => *id,
3797                None => {
3798                    log::trace!("adding unique world {}", name);
3799                    self.worlds_to_add
3800                        .push((name.clone(), into_id, *from_world_id));
3801                    continue;
3802                }
3803            };
3804
3805            log::trace!("merging duplicate worlds {}", name);
3806            self.build_world(*from_world_id, into_world_id)
3807                .with_context(|| format!("failed to merge world `{name}`"))?;
3808        }
3809
3810        Ok(())
3811    }
3812
3813    fn build_interface(&mut self, from_id: InterfaceId, into_id: InterfaceId) -> Result<()> {
3814        let prev = self.interface_map.insert(from_id, into_id);
3815        assert!(prev.is_none());
3816
3817        let from_interface = &self.from.interfaces[from_id];
3818        let into_interface = &self.into.interfaces[into_id];
3819
3820        // Unlike documents/interfaces above if an interface in `from`
3821        // differs from the interface in `into` then that's considered an
3822        // error. Changing interfaces can reflect changes in imports/exports
3823        // which may not be expected so it's currently required that all
3824        // interfaces, when merged, exactly match.
3825        //
3826        // One case to consider here, for example, is that if a world in
3827        // `into` exports the interface `into_id` then if `from_id` were to
3828        // add more items into `into` then it would unexpectedly require more
3829        // items to be exported which may not work. In an import context this
3830        // might work since it's "just more items available for import", but
3831        // for now a conservative route of "interfaces must match" is taken.
3832
3833        for (name, from_type_id) in from_interface.types.iter() {
3834            let into_type_id = *into_interface
3835                .types
3836                .get(name)
3837                .ok_or_else(|| anyhow!("expected type `{name}` to be present"))?;
3838            let prev = self.type_map.insert(*from_type_id, into_type_id);
3839            assert!(prev.is_none());
3840
3841            self.build_type_id(*from_type_id, into_type_id)
3842                .with_context(|| format!("mismatch in type `{name}`"))?;
3843        }
3844
3845        for (name, from_func) in from_interface.functions.iter() {
3846            let into_func = match into_interface.functions.get(name) {
3847                Some(func) => func,
3848                None => bail!("expected function `{name}` to be present"),
3849            };
3850            self.build_function(from_func, into_func)
3851                .with_context(|| format!("mismatch in function `{name}`"))?;
3852        }
3853
3854        Ok(())
3855    }
3856
3857    fn build_type_id(&mut self, from_id: TypeId, into_id: TypeId) -> Result<()> {
3858        // FIXME: ideally the types should be "structurally
3859        // equal" but that's not trivial to do in the face of
3860        // resources.
3861        let _ = from_id;
3862        let _ = into_id;
3863        Ok(())
3864    }
3865
3866    fn build_type(&mut self, from_ty: &Type, into_ty: &Type) -> Result<()> {
3867        match (from_ty, into_ty) {
3868            (Type::Id(from), Type::Id(into)) => {
3869                self.build_type_id(*from, *into)?;
3870            }
3871            (from, into) if from != into => bail!("different kinds of types"),
3872            _ => {}
3873        }
3874        Ok(())
3875    }
3876
3877    fn build_function(&mut self, from_func: &Function, into_func: &Function) -> Result<()> {
3878        if from_func.name != into_func.name {
3879            bail!(
3880                "different function names `{}` and `{}`",
3881                from_func.name,
3882                into_func.name
3883            );
3884        }
3885        match (&from_func.kind, &into_func.kind) {
3886            (FunctionKind::Freestanding, FunctionKind::Freestanding) => {}
3887            (FunctionKind::AsyncFreestanding, FunctionKind::AsyncFreestanding) => {}
3888
3889            (FunctionKind::Method(from), FunctionKind::Method(into))
3890            | (FunctionKind::Static(from), FunctionKind::Static(into))
3891            | (FunctionKind::AsyncMethod(from), FunctionKind::AsyncMethod(into))
3892            | (FunctionKind::AsyncStatic(from), FunctionKind::AsyncStatic(into))
3893            | (FunctionKind::Constructor(from), FunctionKind::Constructor(into)) => {
3894                self.build_type_id(*from, *into)
3895                    .context("different function kind types")?;
3896            }
3897
3898            (FunctionKind::Method(_), _)
3899            | (FunctionKind::Constructor(_), _)
3900            | (FunctionKind::Static(_), _)
3901            | (FunctionKind::Freestanding, _)
3902            | (FunctionKind::AsyncFreestanding, _)
3903            | (FunctionKind::AsyncMethod(_), _)
3904            | (FunctionKind::AsyncStatic(_), _) => {
3905                bail!("different function kind types")
3906            }
3907        }
3908
3909        if from_func.params.len() != into_func.params.len() {
3910            bail!("different number of function parameters");
3911        }
3912        for ((from_name, from_ty), (into_name, into_ty)) in
3913            from_func.params.iter().zip(&into_func.params)
3914        {
3915            if from_name != into_name {
3916                bail!("different function parameter names: {from_name} != {into_name}");
3917            }
3918            self.build_type(from_ty, into_ty)
3919                .with_context(|| format!("different function parameter types for `{from_name}`"))?;
3920        }
3921        match (&from_func.result, &into_func.result) {
3922            (Some(from_ty), Some(into_ty)) => {
3923                self.build_type(from_ty, into_ty)
3924                    .context("different function result types")?;
3925            }
3926            (None, None) => {}
3927            (Some(_), None) | (None, Some(_)) => bail!("different number of function results"),
3928        }
3929        Ok(())
3930    }
3931
3932    fn build_world(&mut self, from_id: WorldId, into_id: WorldId) -> Result<()> {
3933        let prev = self.world_map.insert(from_id, into_id);
3934        assert!(prev.is_none());
3935
3936        let from_world = &self.from.worlds[from_id];
3937        let into_world = &self.into.worlds[into_id];
3938
3939        // Same as interfaces worlds are expected to exactly match to avoid
3940        // unexpectedly changing a particular component's view of imports and
3941        // exports.
3942        //
3943        // FIXME: this should probably share functionality with
3944        // `Resolve::merge_worlds` to support adding imports but not changing
3945        // exports.
3946
3947        if from_world.imports.len() != into_world.imports.len() {
3948            bail!("world contains different number of imports than expected");
3949        }
3950        if from_world.exports.len() != into_world.exports.len() {
3951            bail!("world contains different number of exports than expected");
3952        }
3953
3954        for (from_name, from) in from_world.imports.iter() {
3955            let into_name = MergeMap::map_name(from_name, &self.interface_map);
3956            let name_str = self.from.name_world_key(from_name);
3957            let into = into_world
3958                .imports
3959                .get(&into_name)
3960                .ok_or_else(|| anyhow!("import `{name_str}` not found in target world"))?;
3961            self.match_world_item(from, into)
3962                .with_context(|| format!("import `{name_str}` didn't match target world"))?;
3963        }
3964
3965        for (from_name, from) in from_world.exports.iter() {
3966            let into_name = MergeMap::map_name(from_name, &self.interface_map);
3967            let name_str = self.from.name_world_key(from_name);
3968            let into = into_world
3969                .exports
3970                .get(&into_name)
3971                .ok_or_else(|| anyhow!("export `{name_str}` not found in target world"))?;
3972            self.match_world_item(from, into)
3973                .with_context(|| format!("export `{name_str}` didn't match target world"))?;
3974        }
3975
3976        Ok(())
3977    }
3978
3979    fn map_name(
3980        from_name: &WorldKey,
3981        interface_map: &HashMap<InterfaceId, InterfaceId>,
3982    ) -> WorldKey {
3983        match from_name {
3984            WorldKey::Name(s) => WorldKey::Name(s.clone()),
3985            WorldKey::Interface(id) => {
3986                WorldKey::Interface(interface_map.get(id).copied().unwrap_or(*id))
3987            }
3988        }
3989    }
3990
3991    fn match_world_item(&mut self, from: &WorldItem, into: &WorldItem) -> Result<()> {
3992        match (from, into) {
3993            (WorldItem::Interface { id: from, .. }, WorldItem::Interface { id: into, .. }) => {
3994                match (
3995                    &self.from.interfaces[*from].name,
3996                    &self.into.interfaces[*into].name,
3997                ) {
3998                    // If one interface is unnamed then they must both be
3999                    // unnamed and they must both have the same structure for
4000                    // now.
4001                    (None, None) => self.build_interface(*from, *into)?,
4002
4003                    // Otherwise both interfaces must be named and they must
4004                    // have been previously found to be equivalent. Note that
4005                    // if either is unnamed it won't be present in
4006                    // `interface_map` so this'll return an error.
4007                    _ => {
4008                        if self.interface_map.get(&from) != Some(&into) {
4009                            bail!("interfaces are not the same");
4010                        }
4011                    }
4012                }
4013            }
4014            (WorldItem::Function(from), WorldItem::Function(into)) => {
4015                let _ = (from, into);
4016                // FIXME: should assert an check that `from` structurally
4017                // matches `into`
4018            }
4019            (WorldItem::Type(from), WorldItem::Type(into)) => {
4020                // FIXME: should assert an check that `from` structurally
4021                // matches `into`
4022                let prev = self.type_map.insert(*from, *into);
4023                assert!(prev.is_none());
4024            }
4025
4026            (WorldItem::Interface { .. }, _)
4027            | (WorldItem::Function(_), _)
4028            | (WorldItem::Type(_), _) => {
4029                bail!("world items do not have the same type")
4030            }
4031        }
4032        Ok(())
4033    }
4034}
4035
4036/// Updates stability annotations when merging `from` into `into`.
4037///
4038/// This is done to keep up-to-date stability information if possible.
4039/// Components for example don't carry stability information but WIT does so
4040/// this tries to move from "unknown" to stable/unstable if possible.
4041fn update_stability(from: &Stability, into: &mut Stability) -> Result<()> {
4042    // If `from` is unknown or the two stability annotations are equal then
4043    // there's nothing to do here.
4044    if from == into || from.is_unknown() {
4045        return Ok(());
4046    }
4047    // Otherwise if `into` is unknown then inherit the stability listed in
4048    // `from`.
4049    if into.is_unknown() {
4050        *into = from.clone();
4051        return Ok(());
4052    }
4053
4054    // Failing all that this means that the two attributes are different so
4055    // generate an error.
4056    bail!("mismatch in stability from '{:?}' to '{:?}'", from, into)
4057}
4058
4059fn merge_include_stability(
4060    from: &Stability,
4061    into: &mut Stability,
4062    is_external_include: bool,
4063) -> Result<()> {
4064    if is_external_include && from.is_stable() {
4065        log::trace!("dropped stability from external package");
4066        *into = Stability::Unknown;
4067        return Ok(());
4068    }
4069
4070    return update_stability(from, into);
4071}
4072
4073/// An error that can be returned during "world elaboration" during various
4074/// [`Resolve`] operations.
4075///
4076/// Methods on [`Resolve`] which mutate its internals, such as
4077/// [`Resolve::push_dir`] or [`Resolve::importize`] can fail if `world` imports
4078/// in WIT packages are invalid. This error indicates one of these situations
4079/// where an invalid dependency graph between imports and exports are detected.
4080///
4081/// Note that at this time this error is subtle and not easy to understand, and
4082/// work needs to be done to explain this better and additionally provide a
4083/// better error message. For now though this type enables callers to test for
4084/// the exact kind of error emitted.
4085#[derive(Debug, Clone)]
4086pub struct InvalidTransitiveDependency(String);
4087
4088impl fmt::Display for InvalidTransitiveDependency {
4089    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4090        write!(
4091            f,
4092            "interface `{}` transitively depends on an interface in \
4093             incompatible ways",
4094            self.0
4095        )
4096    }
4097}
4098
4099impl std::error::Error for InvalidTransitiveDependency {}
4100
4101#[cfg(test)]
4102mod tests {
4103    use crate::Resolve;
4104    use anyhow::Result;
4105
4106    #[test]
4107    fn select_world() -> Result<()> {
4108        let mut resolve = Resolve::default();
4109        resolve.push_str(
4110            "test.wit",
4111            r#"
4112                package foo:bar@0.1.0;
4113
4114                world foo {}
4115            "#,
4116        )?;
4117        resolve.push_str(
4118            "test.wit",
4119            r#"
4120                package foo:baz@0.1.0;
4121
4122                world foo {}
4123            "#,
4124        )?;
4125        resolve.push_str(
4126            "test.wit",
4127            r#"
4128                package foo:baz@0.2.0;
4129
4130                world foo {}
4131            "#,
4132        )?;
4133
4134        let dummy = resolve.push_str(
4135            "test.wit",
4136            r#"
4137                package foo:dummy;
4138
4139                world foo {}
4140            "#,
4141        )?;
4142
4143        assert!(resolve.select_world(dummy, None).is_ok());
4144        assert!(resolve.select_world(dummy, Some("xx")).is_err());
4145        assert!(resolve.select_world(dummy, Some("")).is_err());
4146        assert!(resolve.select_world(dummy, Some("foo:bar/foo")).is_ok());
4147        assert!(resolve
4148            .select_world(dummy, Some("foo:bar/foo@0.1.0"))
4149            .is_ok());
4150        assert!(resolve.select_world(dummy, Some("foo:baz/foo")).is_err());
4151        assert!(resolve
4152            .select_world(dummy, Some("foo:baz/foo@0.1.0"))
4153            .is_ok());
4154        assert!(resolve
4155            .select_world(dummy, Some("foo:baz/foo@0.2.0"))
4156            .is_ok());
4157        Ok(())
4158    }
4159}