A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
isle `struct` support (#13319)
Firestar996b96285fc022
diff --git a/Cargo.lock b/Cargo.lockindex e9584eae85..a3fe4552a8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -908,7 +908,6 @@ version = "0.133.0"dependencies = ["codespan-reporting","log",- "tempfile",][[package]]diff --git a/cranelift/isle/docs/language-reference.md b/cranelift/isle/docs/language-reference.mdindex 4316c27d02..b8213e2cd2 100644--- a/cranelift/isle/docs/language-reference.md+++ b/cranelift/isle/docs/language-reference.md@@ -1491,6 +1491,7 @@ The grammar accepted by the parser is as follows:<type-body> ::= "(" "primitive" <ident> ")"| "(" "enum" <enum-variant>* ")"+ | "(" "struct" <variant-field>* ")"<enum-variant> ::= <ident>| "(" <ident> <variant-field>* ")"diff --git a/cranelift/isle/isle/Cargo.toml b/cranelift/isle/isle/Cargo.tomlindex ce969741cf..fbeef489b4 100644--- a/cranelift/isle/isle/Cargo.toml+++ b/cranelift/isle/isle/Cargo.toml@@ -16,9 +16,6 @@ workspace = truecodespan-reporting = { version = "0.11.1", optional = true }log = { workspace = true, optional = true }-[dev-dependencies]-tempfile = "3"-[features]default = []diff --git a/cranelift/isle/isle/isle_examples/pass/struct.isle b/cranelift/isle/isle/isle_examples/pass/struct.islenew file mode 100644index 0000000000..bf45408bdf--- /dev/null+++ b/cranelift/isle/isle/isle_examples/pass/struct.isle@@ -0,0 +1,16 @@+(type A (struct (x u32) (y u32)))+(type B (struct (x u32)))+(type C (enum+ (Ca (x A))+ (Cb (x B))))+(type D (struct (x C)))++(decl D2B (D) B)++(rule 1+ (D2B (D (C.Ca (A x _))))+ (B x))++(rule 0+ (D2B (D (C.Cb (B x))))+ (B x))diff --git a/cranelift/isle/isle/isle_examples/run/struct_test.isle b/cranelift/isle/isle/isle_examples/run/struct_test.islenew file mode 100644index 0000000000..1fca02e697--- /dev/null+++ b/cranelift/isle/isle/isle_examples/run/struct_test.isle@@ -0,0 +1,8 @@+(type A (struct (x u32) (y u32)))+(type B extern (struct (x u32)))+(type C (enum+ (Ca (x A))+ (Cb (x B))))+(type D extern (struct (x C)))++(type UnitStruct (struct))diff --git a/cranelift/isle/isle/isle_examples/run/struct_test_main.rs b/cranelift/isle/isle/isle_examples/run/struct_test_main.rsnew file mode 100644index 0000000000..ddf87407a8--- /dev/null+++ b/cranelift/isle/isle/isle_examples/run/struct_test_main.rs@@ -0,0 +1,40 @@+extern crate alloc;+extern crate core;++mod struct_test;+use struct_test::{A, C, UnitStruct};++#[derive(Clone, Debug)]+pub struct B {+ pub x: u32,+}++#[derive(Clone, Debug)]+pub struct D {+ pub x: C,+}++struct Context();+impl struct_test::Context for Context {}++fn main() {+ let a = D {+ x: C::Ca {+ x: A { x: 42, y: 123 },+ },+ };+ let b = D {+ x: C::Cb { x: B { x: 42 } },+ };+ for d in [a, b] {+ match d {+ D {+ x: C::Ca { x: A { x, .. } } | C::Cb { x: B { x } },+ } => {+ assert_eq!(x, 42);+ }+ }+ }++ let unit = UnitStruct;+}diff --git a/cranelift/isle/isle/src/ast.rs b/cranelift/isle/isle/src/ast.rsindex 9b9ab7d4ed..91fee80bbf 100644--- a/cranelift/isle/isle/src/ast.rs+++ b/cranelift/isle/isle/src/ast.rs@@ -42,12 +42,11 @@ pub struct Type {}/// The actual type-value: a primitive or an enum with variants.-///-/// TODO: add structs as well?#[derive(Clone, PartialEq, Eq, Debug)]pub enum TypeValue {Primitive(Ident, Pos),Enum(Vec<Variant>, Pos),+ Struct(Vec<Field>, Pos),}/// One variant of an enum type.diff --git a/cranelift/isle/isle/src/codegen.rs b/cranelift/isle/isle/src/codegen.rsindex 4427972dc4..a4b7194a72 100644--- a/cranelift/isle/isle/src/codegen.rs+++ b/cranelift/isle/isle/src/codegen.rs@@ -2,7 +2,8 @@use crate::files::Files;use crate::sema::{- BuiltinType, ExternalSig, IntType, ReturnKind, Term, TermEnv, TermId, Type, TypeEnv, TypeId,+ BuiltinType, ExternalSig, Field, IntType, ReturnKind, Term, TermEnv, TermId, Type, TypeEnv,+ TypeId,};use crate::serialize::{Block, ControlFlow, EvalStep, MatchArm};use crate::stablemapset::StableSet;@@ -436,6 +437,40 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{}writeln!(code, "}}").unwrap();}+ &Type::Struct {+ name,+ is_extern,+ is_nodebug,+ ref fields,+ pos,+ ..+ } if !is_extern => {+ let name = &self.typeenv.syms[name.index()];+ writeln!(+ code,+ "\n/// Internal type {}: defined at {}.",+ name,+ pos.pretty_print_line(&self.files)+ )+ .unwrap();++ // Generate the `derive`s.+ let debug_derive = if is_nodebug { "" } else { ", Debug" };+ if fields.is_empty() {+ writeln!(code, "#[derive(Copy, Clone, PartialEq, Eq{debug_derive})]")+ .unwrap();+ writeln!(code, "pub struct {name};").unwrap();+ } else {+ writeln!(code, "#[derive(Clone{debug_derive})]").unwrap();+ writeln!(code, "pub struct {name} {{").unwrap();+ for field in fields {+ let name = &self.typeenv.syms[field.name.index()];+ let ty_name = self.typeenv.types[field.ty.index()].name(self.typeenv);+ writeln!(code, " pub {name}: {ty_name},").unwrap();+ }+ writeln!(code, "}}").unwrap();+ }+ }_ => {}}}@@ -445,7 +480,7 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{match self.typeenv.types[typeid.index()] {Type::Builtin(bt) => String::from(bt.name()),Type::Primitive(_, sym, _) => self.typeenv.syms[sym.index()].clone(),- Type::Enum { name, .. } => {+ Type::Enum { name, .. } | Type::Struct { name, .. } => {let r = if by_ref { "&" } else { "" };format!("{}{}", r, self.typeenv.syms[name.index()])}@@ -550,7 +585,7 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{let name = ty.name(self.typeenv);let is_ref = match ty {Type::Builtin(_) | Type::Primitive(..) => false,- Type::Enum { .. } => true,+ Type::Enum { .. } | Type::Struct { .. } => true,};(is_ref, String::from(name))}@@ -688,7 +723,9 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{write!(ctx.out, " == ")?;self.emit_constraint(ctx, *source, arm)?;}- Constraint::Variant { .. } | Constraint::Some => {+ Constraint::Variant { .. }+ | Constraint::Struct { .. }+ | Constraint::Some => {write!(ctx.out, "{}if let ", &ctx.indent)?;self.emit_constraint(ctx, *source, arm)?;write!(ctx.out, " = ")?;@@ -854,51 +891,77 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{let binding = &ctx.ruleset.bindings[result.index()];- let mut call =- |term: TermId,- parameters: &[BindingId],+ let call = |ctx: &mut BodyContext<W>,+ term: TermId,+ parameters: &[BindingId],+ get_sig: fn(&Term, &TypeEnv) -> Option<ExternalSig>| {+ let termdata = &self.termenv.terms[term.index()];+ let sig = get_sig(termdata, self.typeenv).unwrap();+ if let &[ret_ty] = &sig.ret_tys[..] {+ let (is_ref, _) = self.ty(ret_ty);+ if is_ref {+ ctx.set_ref(result, true);+ write!(ctx.out, "&")?;+ }+ }+ write!(ctx.out, "{}(ctx", sig.full_name)?;+ debug_assert_eq!(parameters.len(), sig.param_tys.len());+ for (¶meter, &arg_ty) in parameters.iter().zip(sig.param_tys.iter()) {+ let (is_ref, _) = self.ty(arg_ty);+ write!(ctx.out, ", ")?;+ let (before, after) = match (is_ref, ctx.is_ref.contains(¶meter)) {+ (false, true) => ("", ".clone()"),+ (true, false) => ("&", ""),+ _ => ("", ""),+ };+ write!(ctx.out, "{before}")?;+ self.emit_expr(ctx, parameter)?;+ write!(ctx.out, "{after}")?;+ }+ if let ReturnKind::Iterator = sig.ret_kind {+ write!(ctx.out, ", &mut v{}", result.index())?;+ }+ write!(ctx.out, ")")+ };- get_sig: fn(&Term, &TypeEnv) -> Option<ExternalSig>| {- let termdata = &self.termenv.terms[term.index()];- let sig = get_sig(termdata, self.typeenv).unwrap();- if let &[ret_ty] = &sig.ret_tys[..] {- let (is_ref, _) = self.ty(ret_ty);- if is_ref {- ctx.set_ref(result, true);- write!(ctx.out, "&")?;+ let extract_fields = |ctx: &mut BodyContext<W>,+ field_bindings: &[BindingId],+ type_fields: &[Field]|+ -> std::fmt::Result {+ if !field_bindings.is_empty() {+ ctx.begin_block()?;+ for (field, value) in type_fields.iter().zip(field_bindings.iter()) {+ write!(+ ctx.out,+ "{}{}: ",+ &ctx.indent,+ &self.typeenv.syms[field.name.index()],+ )?;+ self.emit_expr(ctx, *value)?;+ if ctx.is_ref.contains(value) {+ write!(ctx.out, ".clone()")?;}+ writeln!(ctx.out, ",")?;}- write!(ctx.out, "{}(ctx", sig.full_name)?;- debug_assert_eq!(parameters.len(), sig.param_tys.len());- for (¶meter, &arg_ty) in parameters.iter().zip(sig.param_tys.iter()) {- let (is_ref, _) = self.ty(arg_ty);- write!(ctx.out, ", ")?;- let (before, after) = match (is_ref, ctx.is_ref.contains(¶meter)) {- (false, true) => ("", ".clone()"),- (true, false) => ("&", ""),- _ => ("", ""),- };- write!(ctx.out, "{before}")?;- self.emit_expr(ctx, parameter)?;- write!(ctx.out, "{after}")?;- }- if let ReturnKind::Iterator = sig.ret_kind {- write!(ctx.out, ", &mut v{}", result.index())?;- }- write!(ctx.out, ")")- };+ ctx.end_block_without_newline()?;+ }+ Ok(())+ };match binding {&Binding::ConstBool { val, .. } => self.emit_bool(ctx, val),&Binding::ConstInt { val, ty } => self.emit_int(ctx, val, ty),Binding::ConstPrim { val } => write!(ctx.out, "{}", &self.typeenv.syms[val.index()]),Binding::Argument { index } => write!(ctx.out, "arg{}", index.index()),- Binding::Extractor { term, parameter } => {- call(*term, std::slice::from_ref(parameter), Term::extractor_sig)- }+ Binding::Extractor { term, parameter } => call(+ ctx,+ *term,+ std::slice::from_ref(parameter),+ Term::extractor_sig,+ ),Binding::Constructor {term, parameters, ..- } => call(*term, ¶meters[..], Term::constructor_sig),+ } => call(ctx, *term, ¶meters[..], Term::constructor_sig),Binding::MakeVariant {ty,@@ -907,7 +970,7 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{} => {let (name, variants) = match &self.typeenv.types[ty.index()] {Type::Enum { name, variants, .. } => (name, variants),- _ => unreachable!("MakeVariant with primitive type"),+ _ => unreachable!("MakeVariant with non-enum type"),};let variant = &variants[variant.index()];write!(@@ -916,24 +979,15 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{&self.typeenv.syms[name.index()],&self.typeenv.syms[variant.name.index()])?;- if !fields.is_empty() {- ctx.begin_block()?;- for (field, value) in variant.fields.iter().zip(fields.iter()) {- write!(- ctx.out,- "{}{}: ",- &ctx.indent,- &self.typeenv.syms[field.name.index()],- )?;- self.emit_expr(ctx, *value)?;- if ctx.is_ref.contains(value) {- write!(ctx.out, ".clone()")?;- }- writeln!(ctx.out, ",")?;- }- ctx.end_block_without_newline()?;- }- Ok(())+ extract_fields(ctx, fields, &variant.fields)+ }+ Binding::MakeStruct { ty, fields } => {+ let (name, type_fields) = match &self.typeenv.types[ty.index()] {+ Type::Struct { name, fields, .. } => (name, fields),+ _ => unreachable!("MakeStruct with non-struct type"),+ };+ write!(ctx.out, "{}", &self.typeenv.syms[name.index()],)?;+ extract_fields(ctx, fields, type_fields)}&Binding::MakeSome { inner } => {@@ -952,7 +1006,8 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{// These are not supposed to happen. If they do, make the generated code fail to compile// so this is easier to debug than if we panic during codegen.- &Binding::MatchVariant { source, field, .. } => {+ &Binding::MatchVariant { source, field, .. }+ | &Binding::ExtractStruct { source, field, .. } => {self.emit_expr(ctx, source)?;write!(ctx.out, ".{} /*FIXME*/", field.index())}@@ -969,7 +1024,7 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{source: BindingId,constraint: Constraint,) -> std::fmt::Result {- if let Constraint::Variant { .. } = constraint {+ if let Constraint::Variant { .. } | Constraint::Struct { .. } = constraint {if !ctx.is_ref.contains(&source) {write!(ctx.out, "&")?;}@@ -1002,7 +1057,7 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{Constraint::Variant { ty, variant, .. } => {let (name, variants) = match &self.typeenv.types[ty.index()] {Type::Enum { name, variants, .. } => (name, variants),- _ => unreachable!("Variant constraint on primitive type"),+ _ => unreachable!("Variant constraint on non-enum type"),};let variant = &variants[variant.index()];write!(@@ -1011,32 +1066,16 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{&self.typeenv.syms[name.index()],&self.typeenv.syms[variant.name.index()])?;- if !bindings.is_empty() {- ctx.begin_block()?;- let mut skipped_some = false;- for (&binding, field) in bindings.iter().zip(variant.fields.iter()) {- if let Some(binding) = binding {- write!(- ctx.out,- "{}{}: ",- &ctx.indent,- &self.typeenv.syms[field.name.index()]- )?;- let (is_ref, _) = self.ty(field.ty);- if is_ref {- ctx.set_ref(binding, true);- write!(ctx.out, "ref ")?;- }- writeln!(ctx.out, "v{},", binding.index())?;- } else {- skipped_some = true;- }- }- if skipped_some {- writeln!(ctx.out, "{}..", &ctx.indent)?;- }- ctx.end_block_without_newline()?;- }+ self.emit_fields(ctx, bindings, &variant.fields)?;+ Ok(())+ }+ Constraint::Struct { ty, .. } => {+ let (name, fields) = match &self.typeenv.types[ty.index()] {+ Type::Struct { name, fields, .. } => (name, fields),+ _ => unreachable!("Struct constraint on non-struct type"),+ };+ write!(ctx.out, "&{}", &self.typeenv.syms[name.index()],)?;+ self.emit_fields(ctx, bindings, &fields)?;Ok(())}Constraint::Some => {@@ -1052,6 +1091,41 @@ impl<L: Length, C> Length for ContextIterWrapper<L, C> {{}}+ fn emit_fields<W: Write>(+ &self,+ ctx: &mut BodyContext<W>,+ bindings: &[Option<BindingId>],+ fields: &[Field],+ ) -> std::fmt::Result {+ if !bindings.is_empty() {+ ctx.begin_block()?;+ let mut skipped_some = false;+ for (&binding, field) in bindings.iter().zip(fields.iter()) {+ if let Some(binding) = binding {+ write!(+ ctx.out,+ "{}{}: ",+ &ctx.indent,+ &self.typeenv.syms[field.name.index()]+ )?;+ let (is_ref, _) = self.ty(field.ty);+ if is_ref {+ ctx.set_ref(binding, true);+ write!(ctx.out, "ref ")?;+ }+ writeln!(ctx.out, "v{},", binding.index())?;+ } else {+ skipped_some = true;+ }+ }+ if skipped_some {+ writeln!(ctx.out, "{}..", &ctx.indent)?;+ }+ ctx.end_block_without_newline()?;+ }+ Ok(())+ }+fn emit_bool<W: Write>(&self,ctx: &mut BodyContext<W>,diff --git a/cranelift/isle/isle/src/parser.rs b/cranelift/isle/isle/src/parser.rsindex 6583c69aa6..8d2d65e507 100644--- a/cranelift/isle/isle/src/parser.rs+++ b/cranelift/isle/isle/src/parser.rs@@ -294,6 +294,13 @@ impl<'a> Parser<'a> {}self.expect_rparen()?;Ok(TypeValue::Enum(variants, pos))+ } else if self.eat_sym_str("struct")? {+ let mut fields = vec![];+ while !self.is_rparen() {+ fields.push(self.parse_type_field()?);+ }+ self.expect_rparen()?;+ Ok(TypeValue::Struct(fields, pos))} else {Err(self.error(pos, "Unknown type definition".to_string()))}diff --git a/cranelift/isle/isle/src/printer.rs b/cranelift/isle/isle/src/printer.rsindex 7159c44c33..7195823016 100644--- a/cranelift/isle/isle/src/printer.rs+++ b/cranelift/isle/isle/src/printer.rs@@ -400,6 +400,11 @@ impl ToSExpr for TypeValue {parts.extend(variants.iter().map(ToSExpr::to_sexpr));SExpr::List(parts)}+ TypeValue::Struct(fields, _) => {+ let mut parts = vec![SExpr::atom("struct")];+ parts.extend(fields.iter().map(ToSExpr::to_sexpr));+ SExpr::List(parts)+ }}}}diff --git a/cranelift/isle/isle/src/sema.rs b/cranelift/isle/isle/src/sema.rsindex 14c322a4e9..a5ed3f27d7 100644--- a/cranelift/isle/isle/src/sema.rs+++ b/cranelift/isle/isle/src/sema.rs@@ -268,6 +268,30 @@ pub enum Type {/// The ISLE source position where this `enum` is defined.pos: Pos,},++ /// A Rust struct.+ ///+ /// Pretty much the same as an enum with a single variant, but will emit a Rust `struct` at codegen time instead of+ /// an enum.+ Struct {+ /// The name of this enum.+ name: Sym,+ /// This `enum`'s type id.+ id: TypeId,+ /// Is this `struct` defined in external Rust code?+ ///+ /// If so, ISLE will not emit a definition for it. If not, then it will+ /// emit a Rust definition for it.+ is_extern: bool,+ /// Whether this type should *not* derive `Debug`.+ ///+ /// Incompatible with `is_extern`.+ is_nodebug: bool,+ /// The different variants for this enum.+ fields: Vec<Field>,+ /// The ISLE source position where this `enum` is defined.+ pos: Pos,+ },}impl Type {@@ -275,7 +299,9 @@ impl Type {pub fn name<'a>(&self, tyenv: &'a TypeEnv) -> &'a str {match self {Self::Builtin(ty) => ty.name(),- Self::Primitive(_, name, _) | Self::Enum { name, .. } => &tyenv.syms[name.index()],+ Self::Primitive(_, name, _) | Self::Enum { name, .. } | Type::Struct { name, .. } => {+ &tyenv.syms[name.index()]+ }}}@@ -283,7 +309,9 @@ impl Type {pub fn pos(&self) -> Option<Pos> {match self {Self::Builtin(..) => None,- Self::Primitive(_, _, pos) | Self::Enum { pos, .. } => Some(*pos),+ Self::Primitive(_, _, pos) | Self::Enum { pos, .. } | Type::Struct { pos, .. } => {+ Some(*pos)+ }}}@@ -411,6 +439,8 @@ pub enum TermKind {/// `(A.A1 ...)` then the variant ID corresponds to `A1`.variant: VariantId,},+ /// A struct constructor or extractor.+ Struct,/// A term declared via a `(decl ...)` form.Decl {/// Flags from the term's declaration.@@ -507,6 +537,11 @@ impl Term {matches!(self.kind, TermKind::EnumVariant { .. })}+ /// Is this term a struct?+ pub fn is_struct(&self) -> bool {+ matches!(self.kind, TermKind::Struct { .. })+ }+/// Is this term partial?pub fn is_partial(&self) -> bool {matches!(@@ -534,6 +569,7 @@ impl Term {matches!(self.kind,TermKind::EnumVariant { .. }+ | TermKind::Struct| TermKind::Decl {constructor_kind: Some(_),..@@ -546,6 +582,7 @@ impl Term {matches!(self.kind,TermKind::EnumVariant { .. }+ | TermKind::Struct| TermKind::Decl {extractor_kind: Some(_),..@@ -777,6 +814,15 @@ pub trait PatternVisitor {variant: VariantId,) -> Vec<Self::PatternId>;+ /// Extract the `input` struct into its fields. Returns an identifier for each field within the+ /// struct. The length of the return list must equal the length of `arg_tys`.+ fn add_extract_struct(+ &mut self,+ input: Self::PatternId,+ input_ty: TypeId,+ arg_tys: &[TypeId],+ ) -> Vec<Self::PatternId>;+/// Match if the given external extractor succeeds on `input`. Returns an identifier for each/// return value from the external extractor. The length of the return list must equal the/// length of `output_tys`.@@ -839,6 +885,7 @@ impl Pattern {TermKind::EnumVariant { variant } => {visitor.add_match_variant(input, ty, &termdata.arg_tys, *variant)}+ TermKind::Struct => visitor.add_extract_struct(input, ty, &termdata.arg_tys),TermKind::Decl {extractor_kind: None,..@@ -907,6 +954,13 @@ pub trait ExprVisitor {variant: VariantId,) -> Self::ExprId;+ /// Construct a struct with the given `inputs` assigned to the struct's fields in order.+ fn add_create_struct(+ &mut self,+ inputs: Vec<(Self::ExprId, TypeId)>,+ ty: TypeId,+ ) -> Self::ExprId;+/// Call an external constructor with the given `inputs` as arguments.fn add_construct(&mut self,@@ -969,6 +1023,7 @@ impl Expr {TermKind::EnumVariant { variant } => {visitor.add_create_variant(arg_values_tys, ty, *variant)}+ TermKind::Struct => visitor.add_create_struct(arg_values_tys, ty),TermKind::Decl {constructor_kind: Some(_),flags,@@ -1253,38 +1308,7 @@ impl TypeEnv {);return None;}- let mut fields = vec![];- for field in &variant.fields {- let field_name = self.intern_mut(&field.name);- if fields.iter().any(|f: &Field| f.name == field_name) {- self.report_error(- field.pos,- format!(- "Duplicate field name '{}' in variant '{}' of type",- field.name.0, variant.name.0- ),- );- return None;- }- let field_tid = match self.get_type_by_name(&field.ty) {- Some(tid) => tid,- None => {- self.report_error(- field.ty.1,- format!(- "Unknown type '{}' for field '{}' in variant '{}'",- field.ty.0, field.name.0, variant.name.0- ),- );- return None;- }- };- fields.push(Field {- name: field_name,- id: FieldId(fields.len()),- ty: field_tid,- });- }+ let fields = self.fields_from_ast(&variant.fields, Some(&variant.name))?;variants.push(Variant {name,fullname,@@ -1301,9 +1325,67 @@ impl TypeEnv {pos: ty.pos,})}+ &ast::TypeValue::Struct(ref fields, _) => {+ if ty.is_extern && ty.is_nodebug {+ self.report_error(ty.pos, "external types cannot be marked `nodebug`");+ return None;+ }+ Some(Type::Struct {+ name,+ id: tid,+ is_extern: ty.is_extern,+ is_nodebug: ty.is_nodebug,+ fields: self.fields_from_ast(&fields, None)?,+ pos: ty.pos,+ })+ }}}+ fn fields_from_ast(+ &mut self,+ fields: &[ast::Field],+ variant_name: Option<&ast::Ident>,+ ) -> Option<Vec<Field>> {+ let mut out = Vec::with_capacity(fields.len());+ for field in fields {+ let field_name = self.intern_mut(&field.name);+ if out.iter().any(|f: &Field| f.name == field_name) {+ let msg = if let Some(variant_name) = variant_name {+ format!(+ "Duplicate field name '{}' in variant '{}' of type",+ field.name.0, variant_name.0+ )+ } else {+ format!("Duplicate field name '{}'", field.name.0)+ };+ self.report_error(field.pos, msg);+ return None;+ }+ let field_tid = match self.get_type_by_name(&field.ty) {+ Some(tid) => tid,+ None => {+ let msg = if let Some(variant_name) = variant_name {+ format!(+ "Unknown type '{}' for field '{}' in variant '{}'",+ field.ty.0, field.name.0, variant_name.0+ )+ } else {+ format!("Unknown type '{}' for field '{}'", field.ty.0, field.name.0)+ };+ self.report_error(field.ty.1, msg);+ return None;+ }+ };+ out.push(Field {+ name: field_name,+ id: FieldId(out.len()),+ ty: field_tid,+ });+ }+ Some(out)+ }+fn error(&self, pos: Pos, msg: impl Into<String>) -> Error {Error::TypeError {msg: msg.into(),@@ -1533,6 +1615,31 @@ impl TermEnv {self.term_map.insert(variant.fullname, tid);}}+ &Type::Struct {+ pos,+ id,+ name,+ ref fields,+ ..+ } => {+ if self.term_map.contains_key(&name) {+ let name = tyenv.syms[name.index()].clone();+ tyenv.report_error(pos, format!("Duplicate struct constructor: '{name}'",));+ continue 'types;+ }+ let tid = TermId(self.terms.len());+ let arg_tys = fields.iter().map(|fld| fld.ty).collect::<Vec<_>>();+ let ret_ty = id;+ self.terms.push(Term {+ id: tid,+ decl_pos: pos,+ name,+ arg_tys,+ ret_ty,+ kind: TermKind::Struct,+ });+ self.term_map.insert(name, tid);+ }_ => {}}}@@ -1594,6 +1701,14 @@ impl TermEnv {);continue;}+ TermKind::Struct => {+ tyenv.report_error(+ pos,+ "Rule LHS root term is incorrect kind; cannot be struct"+ .to_string(),+ );+ continue;+ }}}_ => {}@@ -1646,6 +1761,14 @@ impl TermEnv {);continue;}+ TermKind::Struct { .. } => {+ tyenv.report_error(+ ext.pos,+ "Extractor macro body defined on term of incorrect kind; cannot be a \+ struct",+ );+ continue;+ }TermKind::Decl {flags,extractor_kind,@@ -1841,6 +1964,15 @@ impl TermEnv {),);}+ TermKind::Struct { .. } => {+ tyenv.report_error(+ pos,+ format!(+ "External constructor cannot be defined on a struct: {}",+ term.0,+ ),+ );+ }}}&ast::Def::Extern(ast::Extern::Extractor {@@ -1904,6 +2036,13 @@ impl TermEnv {);continue;}+ TermKind::Struct { .. } => {+ tyenv.report_error(+ pos,+ format!("Cannot define extractor for struct '{}'", term.0),+ );+ continue;+ }}}_ => {}@@ -2255,7 +2394,7 @@ impl TermEnv {// TODO: check that multi-extractors are only used in terms declared `multi`match &termdata.kind {- TermKind::EnumVariant { .. } => {}+ TermKind::EnumVariant { .. } | TermKind::Struct => {}TermKind::Decl {extractor_kind: Some(ExtractorKind::ExternalExtractor { .. }),..diff --git a/cranelift/isle/isle/src/serialize.rs b/cranelift/isle/isle/src/serialize.rsindex 97ff776930..408a526172 100644--- a/cranelift/isle/isle/src/serialize.rs+++ b/cranelift/isle/isle/src/serialize.rs@@ -422,7 +422,10 @@ impl<'a> Decomposition<'a> {// type of control flow, in `make_control_flow`.if matches!(binding,- Binding::Iterator { .. } | Binding::MatchVariant { .. } | Binding::MatchSome { .. }+ Binding::Iterator { .. }+ | Binding::MatchVariant { .. }+ | Binding::ExtractStruct { .. }+ | Binding::MatchSome { .. }) {continue;}@@ -521,7 +524,9 @@ impl<'a> Decomposition<'a> {// Only let-bind variant constructors if they have some fields.// Building a variant with no fields is cheap, but don't// duplicate more complex expressions.- Binding::MakeVariant { fields, .. } => !fields.is_empty(),+ Binding::MakeVariant { fields, .. } | Binding::MakeStruct { fields, .. } => {+ !fields.is_empty()+ }// By default, do let-bind: that's always safe._ => true,diff --git a/cranelift/isle/isle/src/trie_again.rs b/cranelift/isle/isle/src/trie_again.rsindex 1ffb578106..1f1cd98cbb 100644--- a/cranelift/isle/isle/src/trie_again.rs+++ b/cranelift/isle/isle/src/trie_again.rs@@ -118,6 +118,24 @@ pub enum Binding {/// get the field names.field: TupleIndex,},+ /// The result of constructing a struct.+ MakeStruct {+ /// Which struct type should be constructed?+ ty: sema::TypeId,+ /// What expressions should be provided for this struct's fields?+ fields: Box<[BindingId]>,+ },+ /// Extract the fields of the struct from one of the previous bindings to produce a new binding+ /// from one of its fields. There must be a corresponding [Constraint::Struct] for each+ /// `source`/`variant` pair that appears in some `ExtractStruct` binding.+ ExtractStruct {+ /// Which binding is being matched?+ source: BindingId,+ /// Which field of this struct are we projecting out? Although ISLE uses named fields,+ /// we track them by index for constant-time comparisons. The [sema::TypeEnv] can be used to+ /// get the field names.+ field: TupleIndex,+ },/// The result of constructing an Option::Some variant.MakeSome {/// Contained expression.@@ -156,6 +174,15 @@ pub enum Constraint {/// convenience, to avoid needing to look up the variant in a [sema::TypeEnv].fields: TupleIndex,},+ /// The value must match this struct variant.+ Struct {+ /// Which struct type is being matched? This is implied by the binding where the constraint is+ /// applied, but recorded here for convenience.+ ty: sema::TypeId,+ /// Number of fields in this variant of this enum. This is recorded in the constraint for+ /// convenience, to avoid needing to look up the variant in a [sema::TypeEnv].+ fields: TupleIndex,+ },/// The value must equal this boolean literal.ConstBool {/// The constant value.@@ -270,6 +297,8 @@ impl Binding {Binding::Iterator { source } => std::slice::from_ref(source),Binding::MakeVariant { fields, .. } => &fields[..],Binding::MatchVariant { source, .. } => std::slice::from_ref(source),+ Binding::MakeStruct { fields, .. } => &fields[..],+ Binding::ExtractStruct { source, .. } => std::slice::from_ref(source),Binding::MakeSome { inner } => std::slice::from_ref(inner),Binding::MatchSome { source } => std::slice::from_ref(source),Binding::MatchTuple { source, .. } => std::slice::from_ref(source),@@ -296,6 +325,10 @@ impl Constraint {field,}).collect(),+ Constraint::Struct { fields, .. } => (0..fields.0)+ .map(TupleIndex)+ .map(|field| Binding::ExtractStruct { source, field })+ .collect(),}}}@@ -575,6 +608,22 @@ impl sema::PatternVisitor for RuleSetBuilder {)}+ fn add_extract_struct(+ &mut self,+ input: Self::PatternId,+ input_ty: sema::TypeId,+ arg_tys: &[sema::TypeId],+ ) -> Vec<Self::PatternId> {+ let fields = TupleIndex(arg_tys.len().try_into().unwrap());+ self.set_constraint(+ input,+ Constraint::Struct {+ fields,+ ty: input_ty,+ },+ )+ }+fn add_extract(&mut self,input: BindingId,@@ -641,6 +690,17 @@ impl sema::ExprVisitor for RuleSetBuilder {})}+ fn add_create_struct(+ &mut self,+ inputs: Vec<(Self::ExprId, sema::TypeId)>,+ ty: sema::TypeId,+ ) -> Self::ExprId {+ self.dedup_binding(Binding::MakeStruct {+ ty,+ fields: inputs.into_iter().map(|(expr, _)| expr).collect(),+ })+ }+fn add_construct(&mut self,inputs: Vec<(BindingId, sema::TypeId)>,diff --git a/cranelift/isle/isle/tests/run_tests.rs b/cranelift/isle/isle/tests/run_tests.rsindex 3cdc817be8..b8452a1d14 100644--- a/cranelift/isle/isle/tests/run_tests.rs+++ b/cranelift/isle/isle/tests/run_tests.rs@@ -1,13 +1,13 @@//! Helper for autogenerated unit tests.-use std::io::BufWriter;-use std::iter::zip;-use cranelift_isle::compile;use cranelift_isle::error::Errors;use cranelift_isle::lexer;use cranelift_isle::parser;use cranelift_isle::printer;+use std::io::BufWriter;+use std::iter::zip;+use std::path::PathBuf;fn build(filename: &str) -> Result<String, Errors> {compile::from_files(&[filename], &Default::default())@@ -29,29 +29,27 @@ pub fn run_fail(filename: &str) {}}-fn build_and_link_isle(isle_filename: &str) -> (tempfile::TempDir, std::path::PathBuf) {- let tempdir = tempfile::tempdir().unwrap();- let code = build(isle_filename).unwrap();-+fn build_and_link_isle(isle_filename: &str) -> (PathBuf, PathBuf) {let isle_filename_base = std::path::Path::new(isle_filename).file_stem().unwrap().to_str().unwrap().to_string();- let isle_generated_code = tempdir- .path()- .to_path_buf()- .join(isle_filename_base.clone() + ".rs");+ let tempdir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(&isle_filename_base);+ eprintln!("Test directory at: {}", tempdir.display());+ std::fs::create_dir_all(&tempdir).unwrap();++ let code = build(isle_filename).unwrap();+ let isle_generated_code = tempdir.join(isle_filename_base.clone() + ".rs");std::fs::write(isle_generated_code, code).unwrap();let rust_filename = isle_filename.replace(".isle", "").to_string() + "_main.rs";let rust_filename_base = std::path::Path::new(&rust_filename).file_name().unwrap();- let rust_driver = tempdir.path().to_path_buf().join(&rust_filename_base);- println!("copying {rust_filename} to {rust_driver:?}");+ let rust_driver = tempdir.join(&rust_filename_base);std::fs::copy(&rust_filename, &rust_driver).unwrap();- let output = tempdir.path().to_path_buf().join("out");+ let output = tempdir.join("out");let mut rustc = std::process::Command::new("rustc").arg(&rust_driver)