Debian Codegraph @

crates/wast/src/component/resolve.rs

raw
1 use crate::Error;
2 use crate::component::*;
3 use crate::core::{self, ValType, resolve::ResolveCoreType};
4 use crate::kw;
5 use crate::names::Namespace;
6 use crate::token::Span;
7 use crate::token::{Id, Index};
8
9 /// Resolve the fields of a component and everything nested within it, changing
10 /// `Index::Id` to `Index::Num` and expanding alias syntax sugar.
11 pub fn resolve(component: &mut Component<'_>) -> Result<(), Error> {
12 let fields = match &mut component.kind {
13 ComponentKind::Text(fields) => fields,
14 ComponentKind::Binary(_) => return Ok(()),
15 };
16 let mut resolver = Resolver::default();
17 resolver.fields(component.id, fields)
18 }
19
20 impl<'a> From<Alias<'a>> for ComponentField<'a> {
21 fn from(a: Alias<'a>) -> Self {
22 Self::Alias(a)
23 }
24 }
25
26 impl<'a> From<Alias<'a>> for ModuleTypeDecl<'a> {
27 fn from(a: Alias<'a>) -> Self {
28 Self::Alias(a)
29 }
30 }
31
32 impl<'a> From<Alias<'a>> for ComponentTypeDecl<'a> {
33 fn from(a: Alias<'a>) -> Self {
34 Self::Alias(a)
35 }
36 }
37
38 impl<'a> From<Alias<'a>> for InstanceTypeDecl<'a> {
39 fn from(a: Alias<'a>) -> Self {
40 Self::Alias(a)
41 }
42 }
43
44 #[derive(Default)]
45 struct Resolver<'a> {
46 stack: Vec<ComponentState<'a>>,
47
48 // When a name refers to a definition in an outer scope, we'll need to
49 // insert an outer alias before it. This collects the aliases to be
50 // inserted during resolution.
51 aliases_to_insert: Vec<Alias<'a>>,
52 }
53
54 /// Context structure used to perform name resolution.
55 #[derive(Default)]
56 struct ComponentState<'a> {
57 id: Option<Id<'a>>,
58
59 // Namespaces within each component. Note that each namespace carries
60 // with it information about the signature of the item in that namespace.
61 // The signature is later used to synthesize the type of a component and
62 // inject type annotations if necessary.
63 core_funcs: Namespace<'a>,
64 core_globals: Namespace<'a>,
65 core_tables: Namespace<'a>,
66 core_memories: Namespace<'a>,
67 core_types: Namespace<'a>,
68 core_tags: Namespace<'a>,
69 core_instances: Namespace<'a>,
70 core_modules: Namespace<'a>,
71
72 funcs: Namespace<'a>,
73 types: Namespace<'a>,
74 instances: Namespace<'a>,
75 components: Namespace<'a>,
76 values: Namespace<'a>,
77 }
78
79 impl<'a> ComponentState<'a> {
80 fn new(id: Option<Id<'a>>) -> ComponentState<'a> {
81 ComponentState {
82 id,
83 ..ComponentState::default()
84 }
85 }
86
87 fn register_item_sig(&mut self, sig: &ItemSig<'a>) -> Result<u32, Error> {
88 match &sig.kind {
89 ItemSigKind::CoreModule(_) => self.core_modules.register(sig.id, "core module"),
90 ItemSigKind::Func(_) => self.funcs.register(sig.id, "func"),
91 ItemSigKind::Component(_) => self.components.register(sig.id, "component"),
92 ItemSigKind::Instance(_) => self.instances.register(sig.id, "instance"),
93 ItemSigKind::Value(_) => self.values.register(sig.id, "value"),
94 ItemSigKind::Type(_) => self.types.register(sig.id, "type"),
95 }
96 }
97 }
98
99 impl<'a> Resolver<'a> {
100 fn current(&mut self) -> &mut ComponentState<'a> {
101 self.stack
102 .last_mut()
103 .expect("should have at least one component state")
104 }
105
106 fn fields(
107 &mut self,
108 id: Option<Id<'a>>,
109 fields: &mut Vec<ComponentField<'a>>,
110 ) -> Result<(), Error> {
111 self.stack.push(ComponentState::new(id));
112 self.resolve_prepending_aliases(fields, Resolver::field, ComponentState::register)?;
113 self.stack.pop();
114 Ok(())
115 }
116
117 fn resolve_prepending_aliases<T>(
118 &mut self,
119 fields: &mut Vec<T>,
120 resolve: fn(&mut Self, &mut T) -> Result<(), Error>,
121 register: fn(&mut ComponentState<'a>, &T) -> Result<(), Error>,
122 ) -> Result<(), Error>
123 where
124 T: From<Alias<'a>>,
125 {
126 assert!(self.aliases_to_insert.is_empty());
127
128 // Iterate through the fields of the component. We use an index
129 // instead of an iterator because we'll be inserting aliases
130 // as we go.
131 let mut i = 0;
132 while i < fields.len() {
133 // Resolve names within the field.
134 resolve(self, &mut fields[i])?;
135
136 // Name resolution may have emitted some aliases. Insert them before
137 // the current definition.
138 let amt = self.aliases_to_insert.len();
139 fields.splice(i..i, self.aliases_to_insert.drain(..).map(T::from));
140 i += amt;
141
142 // Definitions can't refer to themselves or to definitions that appear
143 // later in the format. Now that we're done resolving this field,
144 // assign it an index for later definitions to refer to.
145 register(self.current(), &fields[i])?;
146
147 i += 1;
148 }
149
150 Ok(())
151 }
152
153 fn field(&mut self, field: &mut ComponentField<'a>) -> Result<(), Error> {
154 match field {
155 ComponentField::CoreModule(m) => self.core_module(m),
156 ComponentField::CoreInstance(i) => self.core_instance(i),
157 ComponentField::CoreType(t) => self.core_ty(t),
158 ComponentField::CoreRec(t) => self.core_rec(t),
159 ComponentField::Component(c) => self.component(c),
160 ComponentField::Instance(i) => self.instance(i),
161 ComponentField::Alias(a) => self.alias(a),
162 ComponentField::Type(t) => self.ty(t),
163 ComponentField::CanonicalFunc(f) => self.canonical_func(f),
164 ComponentField::CoreFunc(_) => unreachable!("should be expanded already"),
165 ComponentField::Func(_) => unreachable!("should be expanded already"),
166 ComponentField::Start(s) => self.start(s),
167 ComponentField::Import(i) => self.item_sig(&mut i.item),
168 ComponentField::Export(e) => {
169 if let Some(ty) = &mut e.ty {
170 self.item_sig(&mut ty.0)?;
171 }
172 self.export(&mut e.kind)
173 }
174 ComponentField::Custom(_) | ComponentField::Producers(_) => Ok(()),
175 }
176 }
177
178 fn core_module(&mut self, module: &mut CoreModule) -> Result<(), Error> {
179 match &mut module.kind {
180 CoreModuleKind::Inline { fields } => {
181 crate::core::resolve::resolve(fields)?;
182 }
183
184 CoreModuleKind::Import { .. } => {
185 unreachable!("should be expanded already")
186 }
187 }
188
189 Ok(())
190 }
191
192 fn component(&mut self, component: &mut NestedComponent<'a>) -> Result<(), Error> {
193 match &mut component.kind {
194 NestedComponentKind::Import { .. } => unreachable!("should be expanded already"),
195 NestedComponentKind::Inline(fields) => self.fields(component.id, fields),
196 }
197 }
198
199 fn core_instance(&mut self, instance: &mut CoreInstance<'a>) -> Result<(), Error> {
200 match &mut instance.kind {
201 CoreInstanceKind::Instantiate { module, args } => {
202 self.component_item_ref(module)?;
203 for arg in args {
204 match &mut arg.kind {
205 CoreInstantiationArgKind::Instance(i) => {
206 self.core_item_ref(i)?;
207 }
208 CoreInstantiationArgKind::BundleOfExports(..) => {
209 unreachable!("should be expanded already");
210 }
211 }
212 }
213 }
214 CoreInstanceKind::BundleOfExports(exports) => {
215 for export in exports {
216 self.core_item_ref(&mut export.item)?;
217 }
218 }
219 }
220 Ok(())
221 }
222
223 fn instance(&mut self, instance: &mut Instance<'a>) -> Result<(), Error> {
224 match &mut instance.kind {
225 InstanceKind::Instantiate { component, args } => {
226 self.component_item_ref(component)?;
227 for arg in args {
228 match &mut arg.kind {
229 InstantiationArgKind::Item(e) => {
230 self.export(e)?;
231 }
232 InstantiationArgKind::BundleOfExports(..) => {
233 unreachable!("should be expanded already")
234 }
235 }
236 }
237 }
238 InstanceKind::BundleOfExports(exports) => {
239 for export in exports {
240 self.export(&mut export.kind)?;
241 }
242 }
243 InstanceKind::Import { .. } => {
244 unreachable!("should be expanded already")
245 }
246 }
247 Ok(())
248 }
249
250 fn item_sig(&mut self, item: &mut ItemSig<'a>) -> Result<(), Error> {
251 match &mut item.kind {
252 // Here we must be explicit otherwise the module type reference will
253 // be assumed to be in the component type namespace
254 ItemSigKind::CoreModule(t) => self.core_type_use(t),
255 ItemSigKind::Func(t) => self.component_type_use(t),
256 ItemSigKind::Component(t) => self.component_type_use(t),
257 ItemSigKind::Instance(t) => self.component_type_use(t),
258 ItemSigKind::Value(t) => self.component_val_type(&mut t.0),
259 ItemSigKind::Type(b) => match b {
260 TypeBounds::Eq(i) => {
261 self.resolve_ns(i, Ns::Type)?;
262 Ok(())
263 }
264 TypeBounds::SubResource => Ok(()),
265 },
266 }
267 }
268
269 fn export(&mut self, kind: &mut ComponentExportKind<'a>) -> Result<(), Error> {
270 match kind {
271 // Here we do *not* have to be explicit as the item ref is to a core module
272 ComponentExportKind::CoreModule(r) => self.component_item_ref(r),
273 ComponentExportKind::Func(r) => self.component_item_ref(r),
274 ComponentExportKind::Value(r) => self.component_item_ref(r),
275 ComponentExportKind::Type(r) => self.component_item_ref(r),
276 ComponentExportKind::Component(r) => self.component_item_ref(r),
277 ComponentExportKind::Instance(r) => self.component_item_ref(r),
278 }
279 }
280
281 fn start(&mut self, start: &mut Start<'a>) -> Result<(), Error> {
282 self.resolve_ns(&mut start.func, Ns::Func)?;
283 for arg in start.args.iter_mut() {
284 self.component_item_ref(arg)?;
285 }
286 Ok(())
287 }
288
289 fn outer_alias<T: Into<Ns>>(
290 &mut self,
291 outer: &mut Index<'a>,
292 index: &mut Index<'a>,
293 kind: T,
294 span: Span,
295 ) -> Result<(), Error> {
296 // Short-circuit when both indices are already resolved as this
297 // helps to write tests for invalid modules where wasmparser should
298 // be the one returning the error.
299 if let Index::Num(..) = outer {
300 if let Index::Num(..) = index {
301 return Ok(());
302 }
303 }
304
305 // Resolve `outer`, and compute the depth at which to look up
306 // `index`.
307 let depth = match outer {
308 Index::Id(id) => {
309 let mut depth = 0;
310 for resolver in self.stack.iter().rev() {
311 if resolver.id == Some(*id) {
312 break;
313 }
314 depth += 1;
315 }
316 if depth as usize == self.stack.len() {
317 return Err(Error::new(
318 span,
319 format!("outer component `{}` not found", id.name()),
320 ));
321 }
322 depth
323 }
324 Index::Num(n, _span) => *n,
325 };
326
327 if depth as usize >= self.stack.len() {
328 return Err(Error::new(
329 span,
330 format!("outer count of `{depth}` is too large"),
331 ));
332 }
333
334 *outer = Index::Num(depth, span);
335
336 // Resolve `index` within the computed scope depth.
337 let computed = self.stack.len() - 1 - depth as usize;
338 self.stack[computed].resolve(kind.into(), index)?;
339
340 Ok(())
341 }
342
343 fn alias(&mut self, alias: &mut Alias<'a>) -> Result<(), Error> {
344 match &mut alias.target {
345 AliasTarget::Export {
346 instance,
347 name: _,
348 kind: _,
349 } => {
350 self.resolve_ns(instance, Ns::Instance)?;
351 }
352 AliasTarget::CoreExport {
353 instance,
354 name: _,
355 kind: _,
356 } => {
357 self.resolve_ns(instance, Ns::CoreInstance)?;
358 }
359 AliasTarget::Outer { outer, index, kind } => {
360 self.outer_alias(outer, index, *kind, alias.span)?;
361 }
362 }
363 Ok(())
364 }
365
366 fn canonical_func(&mut self, func: &mut CanonicalFunc<'a>) -> Result<(), Error> {
367 match &mut func.kind {
368 CanonicalFuncKind::Lift { ty, info } => {
369 self.component_type_use(ty)?;
370 self.core_item_ref(&mut info.func)?;
371 self.canon_opts(&mut info.opts)?;
372 }
373 CanonicalFuncKind::Core(core) => match core {
374 CoreFuncKind::Alias(_) => {
375 panic!("should have been removed during expansion")
376 }
377 CoreFuncKind::Lower(info) => {
378 self.component_item_ref(&mut info.func)?;
379 self.canon_opts(&mut info.opts)?;
380 }
381 CoreFuncKind::ResourceNew(info) => {
382 self.resolve_ns(&mut info.ty, Ns::Type)?;
383 }
384 CoreFuncKind::ResourceRep(info) => {
385 self.resolve_ns(&mut info.ty, Ns::Type)?;
386 }
387 CoreFuncKind::ResourceDrop(info) => {
388 self.resolve_ns(&mut info.ty, Ns::Type)?;
389 }
390 CoreFuncKind::ThreadSpawnRef(info) => {
391 self.resolve_ns(&mut info.ty, Ns::CoreType)?;
392 }
393 CoreFuncKind::ThreadSpawnIndirect(info) => {
394 self.resolve_ns(&mut info.ty, Ns::CoreType)?;
395 self.core_item_ref(&mut info.table)?;
396 }
397 CoreFuncKind::ThreadAvailableParallelism(_)
398 | CoreFuncKind::BackpressureSet
399 | CoreFuncKind::BackpressureInc
400 | CoreFuncKind::BackpressureDec
401 | CoreFuncKind::TaskCancel
402 | CoreFuncKind::ThreadYield(_)
403 | CoreFuncKind::SubtaskDrop
404 | CoreFuncKind::SubtaskCancel(_)
405 | CoreFuncKind::ErrorContextDrop => {}
406 CoreFuncKind::TaskReturn(info) => {
407 if let Some(ty) = &mut info.result {
408 self.component_val_type(ty)?;
409 }
410 self.canon_opts(&mut info.opts)?;
411 }
412 CoreFuncKind::ContextGet(_) | CoreFuncKind::ContextSet(_) => {}
413 CoreFuncKind::StreamNew(info) => {
414 self.resolve_ns(&mut info.ty, Ns::Type)?;
415 }
416 CoreFuncKind::StreamRead(info) => {
417 self.resolve_ns(&mut info.ty, Ns::Type)?;
418 self.canon_opts(&mut info.opts)?;
419 }
420 CoreFuncKind::StreamWrite(info) => {
421 self.resolve_ns(&mut info.ty, Ns::Type)?;
422 self.canon_opts(&mut info.opts)?;
423 }
424 CoreFuncKind::StreamCancelRead(info) => {
425 self.resolve_ns(&mut info.ty, Ns::Type)?;
426 }
427 CoreFuncKind::StreamCancelWrite(info) => {
428 self.resolve_ns(&mut info.ty, Ns::Type)?;
429 }
430 CoreFuncKind::StreamDropReadable(info) => {
431 self.resolve_ns(&mut info.ty, Ns::Type)?;
432 }
433 CoreFuncKind::StreamDropWritable(info) => {
434 self.resolve_ns(&mut info.ty, Ns::Type)?;
435 }
436 CoreFuncKind::FutureNew(info) => {
437 self.resolve_ns(&mut info.ty, Ns::Type)?;
438 }
439 CoreFuncKind::FutureRead(info) => {
440 self.resolve_ns(&mut info.ty, Ns::Type)?;
441 self.canon_opts(&mut info.opts)?;
442 }
443 CoreFuncKind::FutureWrite(info) => {
444 self.resolve_ns(&mut info.ty, Ns::Type)?;
445 self.canon_opts(&mut info.opts)?;
446 }
447 CoreFuncKind::FutureCancelRead(info) => {
448 self.resolve_ns(&mut info.ty, Ns::Type)?;
449 }
450 CoreFuncKind::FutureCancelWrite(info) => {
451 self.resolve_ns(&mut info.ty, Ns::Type)?;
452 }
453 CoreFuncKind::FutureDropReadable(info) => {
454 self.resolve_ns(&mut info.ty, Ns::Type)?;
455 }
456 CoreFuncKind::FutureDropWritable(info) => {
457 self.resolve_ns(&mut info.ty, Ns::Type)?;
458 }
459 CoreFuncKind::ErrorContextNew(info) => {
460 self.canon_opts(&mut info.opts)?;
461 }
462 CoreFuncKind::ErrorContextDebugMessage(info) => {
463 self.canon_opts(&mut info.opts)?;
464 }
465 CoreFuncKind::WaitableSetNew => {}
466 CoreFuncKind::WaitableSetWait(info) => {
467 self.core_item_ref(&mut info.memory)?;
468 }
469 CoreFuncKind::WaitableSetPoll(info) => {
470 self.core_item_ref(&mut info.memory)?;
471 }
472 CoreFuncKind::WaitableSetDrop => {}
473 CoreFuncKind::WaitableJoin => {}
474 CoreFuncKind::ThreadIndex => {}
475 CoreFuncKind::ThreadNewIndirect(info) => {
476 self.resolve_ns(&mut info.ty, Ns::CoreType)?;
477 self.core_item_ref(&mut info.table)?;
478 }
479 CoreFuncKind::ThreadSwitchTo(_) => {}
480 CoreFuncKind::ThreadSuspend(_) => {}
481 CoreFuncKind::ThreadResumeLater => {}
482 CoreFuncKind::ThreadYieldTo(_) => {}
483 },
484 }
485
486 Ok(())
487 }
488
489 fn canon_opts(&mut self, opts: &mut [CanonOpt<'a>]) -> Result<(), Error> {
490 for opt in opts {
491 match opt {
492 CanonOpt::StringUtf8
493 | CanonOpt::StringUtf16
494 | CanonOpt::StringLatin1Utf16
495 | CanonOpt::Async
496 | CanonOpt::Gc => {}
497 CanonOpt::Memory(r) => self.core_item_ref(r)?,
498 CanonOpt::Realloc(r) | CanonOpt::PostReturn(r) | CanonOpt::Callback(r) => {
499 self.core_item_ref(r)?
500 }
501 CanonOpt::CoreType(t) => self.core_item_ref(t)?,
502 }
503 }
504
505 Ok(())
506 }
507
508 fn core_type_use<T>(&mut self, ty: &mut CoreTypeUse<'a, T>) -> Result<(), Error> {
509 let item = match ty {
510 CoreTypeUse::Ref(r) => r,
511 CoreTypeUse::Inline(_) => {
512 unreachable!("inline type-use should be expanded by now")
513 }
514 };
515 self.core_item_ref(item)
516 }
517
518 fn component_type_use<T>(&mut self, ty: &mut ComponentTypeUse<'a, T>) -> Result<(), Error> {
519 let item = match ty {
520 ComponentTypeUse::Ref(r) => r,
521 ComponentTypeUse::Inline(_) => {
522 unreachable!("inline type-use should be expanded by now")
523 }
524 };
525 self.component_item_ref(item)
526 }
527
528 fn defined_type(&mut self, ty: &mut ComponentDefinedType<'a>) -> Result<(), Error> {
529 match ty {
530 ComponentDefinedType::Primitive(_) => {}
531 ComponentDefinedType::Flags(_) => {}
532 ComponentDefinedType::Enum(_) => {}
533 ComponentDefinedType::Record(r) => {
534 for field in r.fields.iter_mut() {
535 self.component_val_type(&mut field.ty)?;
536 }
537 }
538 ComponentDefinedType::Variant(v) => {
539 // Namespace for case identifier resolution
540 let mut ns = Namespace::default();
541 for case in v.cases.iter_mut() {
542 let index = ns.register(case.id, "variant case")?;
543
544 if let Some(ty) = &mut case.ty {
545 self.component_val_type(ty)?;
546 }
547
548 if let Some(refines) = &mut case.refines {
549 if let Refinement::Index(span, idx) = refines {
550 let resolved = ns.resolve(idx, "variant case")?;
551 if resolved == index {
552 return Err(Error::new(
553 *span,
554 "variant case cannot refine itself".to_string(),
555 ));
556 }
557
558 *refines = Refinement::Resolved(resolved);
559 }
560 }
561 }
562 }
563 ComponentDefinedType::List(List { element: t })
564 | ComponentDefinedType::FixedSizeList(FixedSizeList {
565 element: t,
566 elements: _,
567 }) => {
568 self.component_val_type(t)?;
569 }
570 ComponentDefinedType::Tuple(t) => {
571 for field in t.fields.iter_mut() {
572 self.component_val_type(field)?;
573 }
574 }
575 ComponentDefinedType::Option(o) => {
576 self.component_val_type(&mut o.element)?;
577 }
578 ComponentDefinedType::Result(r) => {
579 if let Some(ty) = &mut r.ok {
580 self.component_val_type(ty)?;
581 }
582
583 if let Some(ty) = &mut r.err {
584 self.component_val_type(ty)?;
585 }
586 }
587 ComponentDefinedType::Own(t) | ComponentDefinedType::Borrow(t) => {
588 self.resolve_ns(t, Ns::Type)?;
589 }
590 ComponentDefinedType::Stream(s) => {
591 if let Some(ty) = &mut s.element {
592 self.component_val_type(ty)?;
593 }
594 }
595 ComponentDefinedType::Future(f) => {
596 if let Some(ty) = &mut f.element {
597 self.component_val_type(ty)?;
598 }
599 }
600 }
601 Ok(())
602 }
603
604 fn component_val_type(&mut self, ty: &mut ComponentValType<'a>) -> Result<(), Error> {
605 match ty {
606 ComponentValType::Ref(idx) => {
607 self.resolve_ns(idx, Ns::Type)?;
608 Ok(())
609 }
610 ComponentValType::Inline(ComponentDefinedType::Primitive(_)) => Ok(()),
611 ComponentValType::Inline(_) => unreachable!("should be expanded by now"),
612 }
613 }
614
615 fn core_ty(&mut self, field: &mut CoreType<'a>) -> Result<(), Error> {
616 match &mut field.def {
617 CoreTypeDef::Def(ty) => {
618 // See comments in `module_type` for why registration of ids happens
619 // here for core types early.
620 self.current().core_types.register(field.id, "core type")?;
621 self.current().resolve_type_def(ty)?;
622 assert!(self.aliases_to_insert.is_empty());
623 }
624 CoreTypeDef::Module(t) => {
625 self.stack.push(ComponentState::new(field.id));
626 self.module_type(t)?;
627 self.stack.pop();
628 }
629 }
630 Ok(())
631 }
632
633 fn core_rec(&mut self, rec: &mut core::Rec<'a>) -> Result<(), Error> {
634 // See comments in `module_type` for why registration of ids happens
635 // here for core types early.
636 for ty in rec.types.iter() {
637 self.current().core_types.register(ty.id, "core type")?;
638 }
639 for ty in rec.types.iter_mut() {
640 self.current().resolve_type(ty)?;
641 }
642 assert!(self.aliases_to_insert.is_empty());
643 Ok(())
644 }
645
646 fn ty(&mut self, field: &mut Type<'a>) -> Result<(), Error> {
647 match &mut field.def {
648 TypeDef::Defined(t) => {
649 self.defined_type(t)?;
650 }
651 TypeDef::Func(f) => {
652 for param in f.params.iter_mut() {
653 self.component_val_type(&mut param.ty)?;
654 }
655
656 if let Some(result) = &mut f.result {
657 self.component_val_type(result)?;
658 }
659 }
660 TypeDef::Component(c) => {
661 self.stack.push(ComponentState::new(field.id));
662 self.component_type(c)?;
663 self.stack.pop();
664 }
665 TypeDef::Instance(i) => {
666 self.stack.push(ComponentState::new(field.id));
667 self.instance_type(i)?;
668 self.stack.pop();
669 }
670 TypeDef::Resource(r) => {
671 match &mut r.rep {
672 ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 | ValType::V128 => {}
673 ValType::Ref(r) => match &mut r.heap {
674 core::HeapType::Abstract { .. } => {}
675 core::HeapType::Concrete(id) => {
676 self.resolve_ns(id, Ns::Type)?;
677 }
678 },
679 }
680 if let Some(dtor) = &mut r.dtor {
681 self.core_item_ref(dtor)?;
682 }
683 }
684 }
685 Ok(())
686 }
687
688 fn component_type(&mut self, c: &mut ComponentType<'a>) -> Result<(), Error> {
689 self.resolve_prepending_aliases(
690 &mut c.decls,
691 |resolver, decl| match decl {
692 ComponentTypeDecl::Alias(alias) => resolver.alias(alias),
693 ComponentTypeDecl::CoreType(ty) => resolver.core_ty(ty),
694 ComponentTypeDecl::Type(ty) => resolver.ty(ty),
695 ComponentTypeDecl::Import(import) => resolver.item_sig(&mut import.item),
696 ComponentTypeDecl::Export(export) => resolver.item_sig(&mut export.item),
697 },
698 |state, decl| {
699 match decl {
700 ComponentTypeDecl::Alias(alias) => {
701 state.register_alias(alias)?;
702 }
703 ComponentTypeDecl::CoreType(ty) => {
704 state.core_types.register(ty.id, "core type")?;
705 }
706 ComponentTypeDecl::Type(ty) => {
707 state.types.register(ty.id, "type")?;
708 }
709 ComponentTypeDecl::Export(e) => {
710 state.register_item_sig(&e.item)?;
711 }
712 ComponentTypeDecl::Import(i) => {
713 state.register_item_sig(&i.item)?;
714 }
715 }
716 Ok(())
717 },
718 )
719 }
720
721 fn instance_type(&mut self, c: &mut InstanceType<'a>) -> Result<(), Error> {
722 self.resolve_prepending_aliases(
723 &mut c.decls,
724 |resolver, decl| match decl {
725 InstanceTypeDecl::Alias(alias) => resolver.alias(alias),
726 InstanceTypeDecl::CoreType(ty) => resolver.core_ty(ty),
727 InstanceTypeDecl::Type(ty) => resolver.ty(ty),
728 InstanceTypeDecl::Export(export) => resolver.item_sig(&mut export.item),
729 },
730 |state, decl| {
731 match decl {
732 InstanceTypeDecl::Alias(alias) => {
733 state.register_alias(alias)?;
734 }
735 InstanceTypeDecl::CoreType(ty) => {
736 state.core_types.register(ty.id, "core type")?;
737 }
738 InstanceTypeDecl::Type(ty) => {
739 state.types.register(ty.id, "type")?;
740 }
741 InstanceTypeDecl::Export(export) => {
742 state.register_item_sig(&export.item)?;
743 }
744 }
745 Ok(())
746 },
747 )
748 }
749
750 fn core_item_ref<K>(&mut self, item: &mut CoreItemRef<'a, K>) -> Result<(), Error>
751 where
752 K: CoreItem + Copy,
753 {
754 // Check for not being an instance export reference
755 if item.export_name.is_none() {
756 self.resolve_ns(&mut item.idx, item.kind.ns())?;
757 return Ok(());
758 }
759
760 // This is a reference to a core instance export
761 let mut index = item.idx;
762 self.resolve_ns(&mut index, Ns::CoreInstance)?;
763
764 // Record an alias to reference the export
765 let span = item.idx.span();
766 let alias = Alias {
767 span,
768 id: None,
769 name: None,
770 target: AliasTarget::CoreExport {
771 instance: index,
772 name: item.export_name.unwrap(),
773 kind: item.kind.ns().into(),
774 },
775 };
776
777 index = Index::Num(self.current().register_alias(&alias)?, span);
778 self.aliases_to_insert.push(alias);
779
780 item.idx = index;
781 item.export_name = None;
782
783 Ok(())
784 }
785
786 fn component_item_ref<K>(&mut self, item: &mut ItemRef<'a, K>) -> Result<(), Error>
787 where
788 K: ComponentItem + Copy,
789 {
790 // Check for not being an instance export reference
791 if item.export_names.is_empty() {
792 self.resolve_ns(&mut item.idx, item.kind.ns())?;
793 return Ok(());
794 }
795
796 // This is a reference to an instance export
797 let mut index = item.idx;
798 self.resolve_ns(&mut index, Ns::Instance)?;
799
800 let span = item.idx.span();
801 for (pos, export_name) in item.export_names.iter().enumerate() {
802 // Record an alias to reference the export
803 let alias = Alias {
804 span,
805 id: None,
806 name: None,
807 target: AliasTarget::Export {
808 instance: index,
809 name: export_name,
810 kind: if pos == item.export_names.len() - 1 {
811 item.kind.ns().into()
812 } else {
813 ComponentExportAliasKind::Instance
814 },
815 },
816 };
817
818 index = Index::Num(self.current().register_alias(&alias)?, span);
819 self.aliases_to_insert.push(alias);
820 }
821
822 item.idx = index;
823 item.export_names = Vec::new();
824
825 Ok(())
826 }
827
828 fn resolve_ns(&mut self, idx: &mut Index<'a>, ns: Ns) -> Result<u32, Error> {
829 // Perform resolution on a local clone walking up the stack of components
830 // that we have. Note that a local clone is used since we don't want to use
831 // the parent's resolved index if a parent matches, instead we want to use
832 // the index of the alias that we will automatically insert.
833 let mut idx_clone = *idx;
834 for (depth, resolver) in self.stack.iter_mut().rev().enumerate() {
835 let depth = depth as u32;
836 let found = match resolver.resolve(ns, &mut idx_clone) {
837 Ok(idx) => idx,
838 // Try the next parent
839 Err(_) => continue,
840 };
841
842 // If this is the current component then no extra alias is necessary, so
843 // return success.
844 if depth == 0 {
845 *idx = idx_clone;
846 return Ok(found);
847 }
848 let id = match idx {
849 Index::Id(id) => *id,
850 Index::Num(..) => unreachable!(),
851 };
852
853 // When resolution succeeds in a parent then an outer alias is
854 // automatically inserted here in this component.
855 let span = idx.span();
856 let alias = Alias {
857 span,
858 id: Some(id),
859 name: None,
860 target: AliasTarget::Outer {
861 outer: Index::Num(depth, span),
862 index: Index::Num(found, span),
863 kind: match ns {
864 Ns::CoreModule => ComponentOuterAliasKind::CoreModule,
865 Ns::CoreType => ComponentOuterAliasKind::CoreType,
866 Ns::Type => ComponentOuterAliasKind::Type,
867 Ns::Component => ComponentOuterAliasKind::Component,
868 _ => {
869 return Err(Error::new(
870 span,
871 format!(
872 "outer item `{}` is not a module, type, or component",
873 id.name(),
874 ),
875 ));
876 }
877 },
878 },
879 };
880 let local_index = self.current().register_alias(&alias)?;
881 self.aliases_to_insert.push(alias);
882 *idx = Index::Num(local_index, span);
883 return Ok(local_index);
884 }
885
886 // If resolution in any parent failed then simply return the error from our
887 // local namespace
888 self.current().resolve(ns, idx)?;
889 unreachable!()
890 }
891
892 fn module_type(&mut self, ty: &mut ModuleType<'a>) -> Result<(), Error> {
893 return self.resolve_prepending_aliases(
894 &mut ty.decls,
895 |resolver, decl| match decl {
896 ModuleTypeDecl::Alias(alias) => resolver.alias(alias),
897
898 // For types since the GC proposal to core wasm they're allowed
899 // to both refer to themselves and additionally a recursion
900 // group can define a set of types that all refer to one
901 // another. That means that the type names must be registered
902 // first before the type is resolved so the type's own name is
903 // in scope for itself.
904 //
905 // Note though that this means that aliases cannot be injected
906 // automatically for references to outer types. We don't know
907 // how many aliases are going to be created so we otherwise
908 // don't know the type index to register.
909 //
910 // As a compromise for now core types don't support
911 // auto-injection of aliases from outer scopes. They must be
912 // explicitly aliased in. Also note that the error message isn't
913 // great either. This may be something we want to improve in the
914 // future with a better error message or a pass that goes over
915 // everything first to inject aliases and then afterwards all
916 // other names are registered.
917 ModuleTypeDecl::Type(t) => {
918 resolver.current().core_types.register(t.id, "type")?;
919 resolver.current().resolve_type(t)
920 }
921 ModuleTypeDecl::Rec(t) => {
922 for t in t.types.iter_mut() {
923 resolver.current().core_types.register(t.id, "type")?;
924 }
925 for t in t.types.iter_mut() {
926 resolver.current().resolve_type(t)?;
927 }
928 Ok(())
929 }
930
931 ModuleTypeDecl::Import(import) => resolve_item_sig(resolver, &mut import.item),
932 ModuleTypeDecl::Export(_, item) => resolve_item_sig(resolver, item),
933 },
934 |state, decl| {
935 match decl {
936 ModuleTypeDecl::Alias(alias) => {
937 state.register_alias(alias)?;
938 }
939 // These were registered above already
940 ModuleTypeDecl::Type(_) | ModuleTypeDecl::Rec(_) => {}
941 // Only the type namespace is populated within the module type
942 // namespace so these are ignored here.
943 ModuleTypeDecl::Import(_) | ModuleTypeDecl::Export(..) => {}
944 }
945 Ok(())
946 },
947 );
948
949 fn resolve_item_sig<'a>(
950 resolver: &Resolver<'a>,
951 sig: &mut core::ItemSig<'a>,
952 ) -> Result<(), Error> {
953 match &mut sig.kind {
954 core::ItemKind::Func(ty) | core::ItemKind::Tag(core::TagType::Exception(ty)) => {
955 let idx = ty.index.as_mut().expect("index should be filled in");
956 resolver
957 .stack
958 .last()
959 .unwrap()
960 .core_types
961 .resolve(idx, "type")?;
962 }
963 core::ItemKind::Memory(_)
964 | core::ItemKind::Global(_)
965 | core::ItemKind::Table(_) => {}
966 }
967 Ok(())
968 }
969 }
970 }
971
972 impl<'a> ComponentState<'a> {
973 fn resolve(&self, ns: Ns, idx: &mut Index<'a>) -> Result<u32, Error> {
974 match ns {
975 Ns::CoreFunc => self.core_funcs.resolve(idx, "core func"),
976 Ns::CoreGlobal => self.core_globals.resolve(idx, "core global"),
977 Ns::CoreTable => self.core_tables.resolve(idx, "core table"),
978 Ns::CoreMemory => self.core_memories.resolve(idx, "core memory"),
979 Ns::CoreType => self.core_types.resolve(idx, "core type"),
980 Ns::CoreTag => self.core_tags.resolve(idx, "core tag"),
981 Ns::CoreInstance => self.core_instances.resolve(idx, "core instance"),
982 Ns::CoreModule => self.core_modules.resolve(idx, "core module"),
983 Ns::Func => self.funcs.resolve(idx, "func"),
984 Ns::Type => self.types.resolve(idx, "type"),
985 Ns::Instance => self.instances.resolve(idx, "instance"),
986 Ns::Component => self.components.resolve(idx, "component"),
987 Ns::Value => self.values.resolve(idx, "value"),
988 }
989 }
990
991 /// Assign an index to the given field.
992 fn register(&mut self, item: &ComponentField<'a>) -> Result<(), Error> {
993 match item {
994 ComponentField::CoreModule(m) => self.core_modules.register(m.id, "core module")?,
995 ComponentField::CoreInstance(i) => {
996 self.core_instances.register(i.id, "core instance")?
997 }
998 ComponentField::CoreType(ty) => match &ty.def {
999 CoreTypeDef::Def(_) => 0, // done above in `core_rec`
1000 CoreTypeDef::Module(_) => self.core_types.register(ty.id, "core type")?,
1001 },
1002 ComponentField::CoreRec(_) => 0, // done above in `core_rec`
1003 ComponentField::Component(c) => self.components.register(c.id, "component")?,
1004 ComponentField::Instance(i) => self.instances.register(i.id, "instance")?,
1005 ComponentField::Alias(a) => self.register_alias(a)?,
1006 ComponentField::Type(t) => self.types.register(t.id, "type")?,
1007 ComponentField::CanonicalFunc(f) => match &f.kind {
1008 CanonicalFuncKind::Lift { .. } => self.funcs.register(f.id, "func")?,
1009 CanonicalFuncKind::Core(_) => self.core_funcs.register(f.id, "core func")?,
1010 },
1011 ComponentField::CoreFunc(_) | ComponentField::Func(_) => {
1012 unreachable!("should be expanded already")
1013 }
1014 ComponentField::Start(s) => {
1015 for r in &s.results {
1016 self.values.register(*r, "value")?;
1017 }
1018 return Ok(());
1019 }
1020 ComponentField::Import(i) => self.register_item_sig(&i.item)?,
1021 ComponentField::Export(e) => match &e.kind {
1022 ComponentExportKind::CoreModule(_) => {
1023 self.core_modules.register(e.id, "core module")?
1024 }
1025 ComponentExportKind::Func(_) => self.funcs.register(e.id, "func")?,
1026 ComponentExportKind::Instance(_) => self.instances.register(e.id, "instance")?,
1027 ComponentExportKind::Value(_) => self.values.register(e.id, "value")?,
1028 ComponentExportKind::Component(_) => self.components.register(e.id, "component")?,
1029 ComponentExportKind::Type(_) => self.types.register(e.id, "type")?,
1030 },
1031 ComponentField::Custom(_) | ComponentField::Producers(_) => return Ok(()),
1032 };
1033
1034 Ok(())
1035 }
1036
1037 fn register_alias(&mut self, alias: &Alias<'a>) -> Result<u32, Error> {
1038 match alias.target {
1039 AliasTarget::Export { kind, .. } => match kind {
1040 ComponentExportAliasKind::CoreModule => {
1041 self.core_modules.register(alias.id, "core module")
1042 }
1043 ComponentExportAliasKind::Func => self.funcs.register(alias.id, "func"),
1044 ComponentExportAliasKind::Value => self.values.register(alias.id, "value"),
1045 ComponentExportAliasKind::Type => self.types.register(alias.id, "type"),
1046 ComponentExportAliasKind::Component => {
1047 self.components.register(alias.id, "component")
1048 }
1049 ComponentExportAliasKind::Instance => self.instances.register(alias.id, "instance"),
1050 },
1051 AliasTarget::CoreExport { kind, .. } => match kind {
1052 core::ExportKind::Func => self.core_funcs.register(alias.id, "core func"),
1053 core::ExportKind::Table => self.core_tables.register(alias.id, "core table"),
1054 core::ExportKind::Memory => self.core_memories.register(alias.id, "core memory"),
1055 core::ExportKind::Global => self.core_globals.register(alias.id, "core global"),
1056 core::ExportKind::Tag => self.core_tags.register(alias.id, "core tag"),
1057 },
1058 AliasTarget::Outer { kind, .. } => match kind {
1059 ComponentOuterAliasKind::CoreModule => {
1060 self.core_modules.register(alias.id, "core module")
1061 }
1062 ComponentOuterAliasKind::CoreType => {
1063 self.core_types.register(alias.id, "core type")
1064 }
1065 ComponentOuterAliasKind::Type => self.types.register(alias.id, "type"),
1066 ComponentOuterAliasKind::Component => {
1067 self.components.register(alias.id, "component")
1068 }
1069 },
1070 }
1071 }
1072 }
1073
1074 impl<'a> ResolveCoreType<'a> for ComponentState<'a> {
1075 fn resolve_type_name(&mut self, name: &mut Index<'a>) -> Result<u32, Error> {
1076 self.resolve(Ns::CoreType, name)
1077 }
1078 }
1079
1080 #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
1081 enum Ns {
1082 CoreFunc,
1083 CoreGlobal,
1084 CoreTable,
1085 CoreMemory,
1086 CoreType,
1087 CoreTag,
1088 CoreInstance,
1089 CoreModule,
1090 Func,
1091 Type,
1092 Instance,
1093 Component,
1094 Value,
1095 }
1096
1097 trait ComponentItem {
1098 fn ns(&self) -> Ns;
1099 }
1100
1101 trait CoreItem {
1102 fn ns(&self) -> Ns;
1103 }
1104
1105 macro_rules! component_item {
1106 ($kw:path, $kind:ident) => {
1107 impl ComponentItem for $kw {
1108 fn ns(&self) -> Ns {
1109 Ns::$kind
1110 }
1111 }
1112 };
1113 }
1114
1115 macro_rules! core_item {
1116 ($kw:path, $kind:ident) => {
1117 impl CoreItem for $kw {
1118 fn ns(&self) -> Ns {
1119 Ns::$kind
1120 }
1121 }
1122 };
1123 }
1124
1125 component_item!(kw::func, Func);
1126 component_item!(kw::r#type, Type);
1127 component_item!(kw::r#instance, Instance);
1128 component_item!(kw::component, Component);
1129 component_item!(kw::value, Value);
1130 component_item!(kw::module, CoreModule);
1131
1132 core_item!(kw::func, CoreFunc);
1133 core_item!(kw::memory, CoreMemory);
1134 core_item!(kw::table, CoreTable);
1135 core_item!(kw::r#type, CoreType);
1136 core_item!(kw::r#instance, CoreInstance);
1137
1138 impl From<Ns> for ComponentExportAliasKind {
1139 fn from(ns: Ns) -> Self {
1140 match ns {
1141 Ns::CoreModule => Self::CoreModule,
1142 Ns::Func => Self::Func,
1143 Ns::Type => Self::Type,
1144 Ns::Instance => Self::Instance,
1145 Ns::Component => Self::Component,
1146 Ns::Value => Self::Value,
1147 _ => unreachable!("not a component exportable namespace"),
1148 }
1149 }
1150 }
1151
1152 impl From<Ns> for core::ExportKind {
1153 fn from(ns: Ns) -> Self {
1154 match ns {
1155 Ns::CoreFunc => Self::Func,
1156 Ns::CoreTable => Self::Table,
1157 Ns::CoreGlobal => Self::Global,
1158 Ns::CoreMemory => Self::Memory,
1159 Ns::CoreTag => Self::Tag,
1160 _ => unreachable!("not a core exportable namespace"),
1161 }
1162 }
1163 }
1164
1165 impl From<ComponentOuterAliasKind> for Ns {
1166 fn from(kind: ComponentOuterAliasKind) -> Self {
1167 match kind {
1168 ComponentOuterAliasKind::CoreModule => Self::CoreModule,
1169 ComponentOuterAliasKind::CoreType => Self::CoreType,
1170 ComponentOuterAliasKind::Type => Self::Type,
1171 ComponentOuterAliasKind::Component => Self::Component,
1172 }
1173 }
1174 }
1175
1176 impl CoreItem for core::ExportKind {
1177 fn ns(&self) -> Ns {
1178 match self {
1179 Self::Func => Ns::CoreFunc,
1180 Self::Table => Ns::CoreTable,
1181 Self::Global => Ns::CoreGlobal,
1182 Self::Memory => Ns::CoreMemory,
1183 Self::Tag => Ns::CoreTag,
1184 }
1185 }
1186 }