Skip to content

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

fix `convert` of `decl partial` emitting failing rust code (#14023)

Firestar9906cc94249b2a
diff --git a/cranelift/isle/isle/isle_examples/link/convert_partial_borrows.isle b/cranelift/isle/isle/isle_examples/link/convert_partial_borrows.isle
new file mode 100644
index 0000000000..fd86ab4e09
--- /dev/null
+++ b/cranelift/isle/isle/isle_examples/link/convert_partial_borrows.isle
@@ -0,0 +1,17 @@
+;; ISLE only passes primitives by value, enums are passed by reference.
+(type A (enum (B) (C)))
+(type W (enum (X) (Y)))
+
+(decl pure partial a_to_w (A) W)
+(extern constructor a_to_w a_to_w)
+(convert A W a_to_w)
+
+(decl build (W) u32)
+(extern constructor build build)
+
+;; The rule below passes an `A` where a `W` is expected, so ISLE inserts the
+;; partial converter `a_to_w`. Because `build` takes its `W` by reference, ISLE
+;; emits `let v = &a_to_w(...); let w = v?;` -- applying `?` to `&Option<W>`,
+;; which does not compile.
+(decl partial entry (A) u32)
+(rule (entry a) (build a))
diff --git a/cranelift/isle/isle/isle_examples/link/convert_partial_borrows_main.rs b/cranelift/isle/isle/isle_examples/link/convert_partial_borrows_main.rs
new file mode 100644
index 0000000000..0ab1271a78
--- /dev/null
+++ b/cranelift/isle/isle/isle_examples/link/convert_partial_borrows_main.rs
@@ -0,0 +1,26 @@
+extern crate alloc;
+extern crate core;
+
+mod convert_partial_borrows;
+use convert_partial_borrows::{A, W};
+
+struct Context;
+impl convert_partial_borrows::Context for Context {
+ fn a_to_w(&mut self, arg0: &A) -> Option<W> {
+ match arg0 {
+ A::B => Some(W::X),
+ A::C => Some(W::Y),
+ }
+ }
+
+ fn build(&mut self, arg0: &W) -> u32 {
+ match arg0 {
+ W::X => 0,
+ W::Y => 1,
+ }
+ }
+}
+
+fn main() {
+ convert_partial_borrows::constructor_entry(&mut Context, &A::B);
+}
diff --git a/cranelift/isle/isle/src/codegen.rs b/cranelift/isle/isle/src/codegen.rs
index 182f517c8c..ccfc44ba24 100644
--- a/cranelift/isle/isle/src/codegen.rs
+++ b/cranelift/isle/isle/src/codegen.rs
@@ -1027,7 +1027,19 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{
}
&Binding::MatchSome { source } => {
self.emit_expr(ctx, source)?;
- write!(ctx.out, "?")
+ // When isle uses an implicit `convert` from A to B and the conversion declaration is `partial`,
+ // it emits:
+ // ```
+ // let v1: &Option<B> = &C::a_to_b(ctx, arg0);
+ // let v2: &B = v1?;
+ // ```
+ // This fails to compile since you can't `?` a `&Option<T>`, only on an `Option` itself.
+ // So add a `.as_ref()` to convert it to `Option<&T>` before `?`.
+ if ctx.is_ref.contains(&source) {
+ write!(ctx.out, ".as_ref()?")
+ } else {
+ write!(ctx.out, "?")
+ }
}
&Binding::MatchTuple { source, field } => {
self.emit_expr(ctx, source)?;